videos.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. import * as Bluebird from 'bluebird'
  2. import { maxBy, minBy } from 'lodash'
  3. import * as magnetUtil from 'magnet-uri'
  4. import { join } from 'path'
  5. import * as request from 'request'
  6. import * as sequelize from 'sequelize'
  7. import { VideoLiveModel } from '@server/models/video/video-live'
  8. import {
  9. ActivityHashTagObject,
  10. ActivityMagnetUrlObject,
  11. ActivityPlaylistSegmentHashesObject,
  12. ActivityPlaylistUrlObject,
  13. ActivitypubHttpFetcherPayload,
  14. ActivityTagObject,
  15. ActivityUrlObject,
  16. ActivityVideoUrlObject
  17. } from '../../../shared/index'
  18. import { VideoObject } from '../../../shared/models/activitypub/objects'
  19. import { VideoPrivacy } from '../../../shared/models/videos'
  20. import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
  21. import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
  22. import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
  23. import { isAPVideoFileMetadataObject, sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
  24. import { isArray } from '../../helpers/custom-validators/misc'
  25. import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
  26. import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
  27. import { logger } from '../../helpers/logger'
  28. import { doRequest } from '../../helpers/requests'
  29. import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
  30. import {
  31. ACTIVITY_PUB,
  32. MIMETYPES,
  33. P2P_MEDIA_LOADER_PEER_VERSION,
  34. PREVIEWS_SIZE,
  35. REMOTE_SCHEME,
  36. STATIC_PATHS,
  37. THUMBNAILS_SIZE
  38. } from '../../initializers/constants'
  39. import { sequelizeTypescript } from '../../initializers/database'
  40. import { AccountVideoRateModel } from '../../models/account/account-video-rate'
  41. import { VideoModel } from '../../models/video/video'
  42. import { VideoCaptionModel } from '../../models/video/video-caption'
  43. import { VideoCommentModel } from '../../models/video/video-comment'
  44. import { VideoFileModel } from '../../models/video/video-file'
  45. import { VideoShareModel } from '../../models/video/video-share'
  46. import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
  47. import {
  48. MAccountIdActor,
  49. MChannelAccountLight,
  50. MChannelDefault,
  51. MChannelId,
  52. MStreamingPlaylist,
  53. MVideo,
  54. MVideoAccountLight,
  55. MVideoAccountLightBlacklistAllFiles,
  56. MVideoAP,
  57. MVideoAPWithoutCaption,
  58. MVideoFile,
  59. MVideoFullLight,
  60. MVideoId,
  61. MVideoImmutable,
  62. MVideoThumbnail
  63. } from '../../types/models'
  64. import { MThumbnail } from '../../types/models/video/thumbnail'
  65. import { FilteredModelAttributes } from '../../types/sequelize'
  66. import { ActorFollowScoreCache } from '../files-cache'
  67. import { JobQueue } from '../job-queue'
  68. import { Notifier } from '../notifier'
  69. import { PeerTubeSocket } from '../peertube-socket'
  70. import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
  71. import { setVideoTags } from '../video'
  72. import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
  73. import { getOrCreateActorAndServerAndModel } from './actor'
  74. import { crawlCollectionPage } from './crawl'
  75. import { sendCreateVideo, sendUpdateVideo } from './send'
  76. import { addVideoShares, shareVideoByServerAndChannel } from './share'
  77. import { addVideoComments } from './video-comments'
  78. import { createRates } from './video-rates'
  79. import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
  80. async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
  81. const video = videoArg as MVideoAP
  82. if (
  83. // Check this is not a blacklisted video, or unfederated blacklisted video
  84. (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
  85. // Check the video is public/unlisted and published
  86. video.hasPrivacyForFederation() && video.hasStateForFederation()
  87. ) {
  88. // Fetch more attributes that we will need to serialize in AP object
  89. if (isArray(video.VideoCaptions) === false) {
  90. video.VideoCaptions = await video.$get('VideoCaptions', {
  91. attributes: [ 'language' ],
  92. transaction
  93. })
  94. }
  95. if (isNewVideo) {
  96. // Now we'll add the video's meta data to our followers
  97. await sendCreateVideo(video, transaction)
  98. await shareVideoByServerAndChannel(video, transaction)
  99. } else {
  100. await sendUpdateVideo(video, transaction)
  101. }
  102. }
  103. }
  104. async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoObject }> {
  105. const options = {
  106. uri: videoUrl,
  107. method: 'GET',
  108. json: true,
  109. activityPub: true
  110. }
  111. logger.info('Fetching remote video %s.', videoUrl)
  112. const { response, body } = await doRequest<any>(options)
  113. if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
  114. logger.debug('Remote video JSON is not valid.', { body })
  115. return { response, videoObject: undefined }
  116. }
  117. return { response, videoObject: body }
  118. }
  119. async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
  120. const host = video.VideoChannel.Account.Actor.Server.host
  121. const path = video.getDescriptionAPIPath()
  122. const options = {
  123. uri: REMOTE_SCHEME.HTTP + '://' + host + path,
  124. json: true
  125. }
  126. const { body } = await doRequest<any>(options)
  127. return body.description ? body.description : ''
  128. }
  129. function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
  130. const channel = videoObject.attributedTo.find(a => a.type === 'Group')
  131. if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
  132. if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
  133. throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
  134. }
  135. return getOrCreateActorAndServerAndModel(channel.id, 'all')
  136. }
  137. type SyncParam = {
  138. likes: boolean
  139. dislikes: boolean
  140. shares: boolean
  141. comments: boolean
  142. thumbnail: boolean
  143. refreshVideo?: boolean
  144. }
  145. async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
  146. logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
  147. const jobPayloads: ActivitypubHttpFetcherPayload[] = []
  148. if (syncParam.likes === true) {
  149. const handler = items => createRates(items, video, 'like')
  150. const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
  151. await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
  152. .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
  153. } else {
  154. jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
  155. }
  156. if (syncParam.dislikes === true) {
  157. const handler = items => createRates(items, video, 'dislike')
  158. const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
  159. await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
  160. .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
  161. } else {
  162. jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
  163. }
  164. if (syncParam.shares === true) {
  165. const handler = items => addVideoShares(items, video)
  166. const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
  167. await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
  168. .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
  169. } else {
  170. jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
  171. }
  172. if (syncParam.comments === true) {
  173. const handler = items => addVideoComments(items)
  174. const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
  175. await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
  176. .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
  177. } else {
  178. jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
  179. }
  180. await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
  181. }
  182. type GetVideoResult <T> = Promise<{
  183. video: T
  184. created: boolean
  185. autoBlacklisted?: boolean
  186. }>
  187. type GetVideoParamAll = {
  188. videoObject: { id: string } | string
  189. syncParam?: SyncParam
  190. fetchType?: 'all'
  191. allowRefresh?: boolean
  192. }
  193. type GetVideoParamImmutable = {
  194. videoObject: { id: string } | string
  195. syncParam?: SyncParam
  196. fetchType: 'only-immutable-attributes'
  197. allowRefresh: false
  198. }
  199. type GetVideoParamOther = {
  200. videoObject: { id: string } | string
  201. syncParam?: SyncParam
  202. fetchType?: 'all' | 'only-video'
  203. allowRefresh?: boolean
  204. }
  205. function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
  206. function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
  207. function getOrCreateVideoAndAccountAndChannel (
  208. options: GetVideoParamOther
  209. ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
  210. async function getOrCreateVideoAndAccountAndChannel (
  211. options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
  212. ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
  213. // Default params
  214. const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
  215. const fetchType = options.fetchType || 'all'
  216. const allowRefresh = options.allowRefresh !== false
  217. // Get video url
  218. const videoUrl = getAPId(options.videoObject)
  219. let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
  220. if (videoFromDatabase) {
  221. // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
  222. if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
  223. const refreshOptions = {
  224. video: videoFromDatabase as MVideoThumbnail,
  225. fetchedType: fetchType,
  226. syncParam
  227. }
  228. if (syncParam.refreshVideo === true) {
  229. videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
  230. } else {
  231. await JobQueue.Instance.createJobWithPromise({
  232. type: 'activitypub-refresher',
  233. payload: { type: 'video', url: videoFromDatabase.url }
  234. })
  235. }
  236. }
  237. return { video: videoFromDatabase, created: false }
  238. }
  239. const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
  240. if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
  241. const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
  242. const videoChannel = actor.VideoChannel
  243. try {
  244. const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
  245. await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
  246. return { video: videoCreated, created: true, autoBlacklisted }
  247. } catch (err) {
  248. // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
  249. if (err.name === 'SequelizeUniqueConstraintError') {
  250. const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
  251. if (fallbackVideo) return { video: fallbackVideo, created: false }
  252. }
  253. throw err
  254. }
  255. }
  256. async function updateVideoFromAP (options: {
  257. video: MVideoAccountLightBlacklistAllFiles
  258. videoObject: VideoObject
  259. account: MAccountIdActor
  260. channel: MChannelDefault
  261. overrideTo?: string[]
  262. }) {
  263. const { video, videoObject, account, channel, overrideTo } = options
  264. logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
  265. let videoFieldsSave: any
  266. const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
  267. const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
  268. try {
  269. let thumbnailModel: MThumbnail
  270. try {
  271. thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
  272. } catch (err) {
  273. logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
  274. }
  275. const videoUpdated = await sequelizeTypescript.transaction(async t => {
  276. const sequelizeOptions = { transaction: t }
  277. videoFieldsSave = video.toJSON()
  278. // Check actor has the right to update the video
  279. const videoChannel = video.VideoChannel
  280. if (videoChannel.Account.id !== account.id) {
  281. throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
  282. }
  283. const to = overrideTo || videoObject.to
  284. const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
  285. video.name = videoData.name
  286. video.uuid = videoData.uuid
  287. video.url = videoData.url
  288. video.category = videoData.category
  289. video.licence = videoData.licence
  290. video.language = videoData.language
  291. video.description = videoData.description
  292. video.support = videoData.support
  293. video.nsfw = videoData.nsfw
  294. video.commentsEnabled = videoData.commentsEnabled
  295. video.downloadEnabled = videoData.downloadEnabled
  296. video.waitTranscoding = videoData.waitTranscoding
  297. video.state = videoData.state
  298. video.duration = videoData.duration
  299. video.createdAt = videoData.createdAt
  300. video.publishedAt = videoData.publishedAt
  301. video.originallyPublishedAt = videoData.originallyPublishedAt
  302. video.privacy = videoData.privacy
  303. video.channelId = videoData.channelId
  304. video.views = videoData.views
  305. video.isLive = videoData.isLive
  306. // Ensures we update the updated video attribute
  307. video.changed('updatedAt', true)
  308. const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
  309. if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
  310. if (videoUpdated.getPreview()) {
  311. const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
  312. const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
  313. await videoUpdated.addAndSaveThumbnail(previewModel, t)
  314. }
  315. {
  316. const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
  317. const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
  318. // Remove video files that do not exist anymore
  319. const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
  320. await Promise.all(destroyTasks)
  321. // Update or add other one
  322. const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
  323. videoUpdated.VideoFiles = await Promise.all(upsertTasks)
  324. }
  325. {
  326. const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
  327. const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
  328. // Remove video playlists that do not exist anymore
  329. const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
  330. await Promise.all(destroyTasks)
  331. let oldStreamingPlaylistFiles: MVideoFile[] = []
  332. for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
  333. oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
  334. }
  335. videoUpdated.VideoStreamingPlaylists = []
  336. for (const playlistAttributes of streamingPlaylistAttributes) {
  337. const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
  338. .then(([ streamingPlaylist ]) => streamingPlaylist)
  339. const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
  340. .map(a => new VideoFileModel(a))
  341. const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
  342. await Promise.all(destroyTasks)
  343. // Update or add other one
  344. const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
  345. streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
  346. videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
  347. }
  348. }
  349. {
  350. // Update Tags
  351. const tags = videoObject.tag
  352. .filter(isAPHashTagObject)
  353. .map(tag => tag.name)
  354. await setVideoTags({ video: videoUpdated, tags, transaction: t, defaultValue: videoUpdated.Tags })
  355. }
  356. {
  357. // Update captions
  358. await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
  359. const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
  360. return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
  361. })
  362. await Promise.all(videoCaptionsPromises)
  363. }
  364. {
  365. // Create or update existing live
  366. if (video.isLive) {
  367. const [ videoLive ] = await VideoLiveModel.upsert({
  368. saveReplay: videoObject.liveSaveReplay,
  369. permanentLive: videoObject.permanentLive,
  370. videoId: video.id
  371. }, { transaction: t, returning: true })
  372. videoUpdated.VideoLive = videoLive
  373. } else { // Delete existing live if it exists
  374. await VideoLiveModel.destroy({
  375. where: {
  376. videoId: video.id
  377. },
  378. transaction: t
  379. })
  380. videoUpdated.VideoLive = null
  381. }
  382. }
  383. return videoUpdated
  384. })
  385. await autoBlacklistVideoIfNeeded({
  386. video: videoUpdated,
  387. user: undefined,
  388. isRemote: true,
  389. isNew: false,
  390. transaction: undefined
  391. })
  392. // Notify our users?
  393. if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
  394. if (videoUpdated.isLive) {
  395. PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
  396. PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
  397. }
  398. logger.info('Remote video with uuid %s updated', videoObject.uuid)
  399. return videoUpdated
  400. } catch (err) {
  401. if (video !== undefined && videoFieldsSave !== undefined) {
  402. resetSequelizeInstance(video, videoFieldsSave)
  403. }
  404. // This is just a debug because we will retry the insert
  405. logger.debug('Cannot update the remote video.', { err })
  406. throw err
  407. }
  408. }
  409. async function refreshVideoIfNeeded (options: {
  410. video: MVideoThumbnail
  411. fetchedType: VideoFetchByUrlType
  412. syncParam: SyncParam
  413. }): Promise<MVideoThumbnail> {
  414. if (!options.video.isOutdated()) return options.video
  415. // We need more attributes if the argument video was fetched with not enough joints
  416. const video = options.fetchedType === 'all'
  417. ? options.video as MVideoAccountLightBlacklistAllFiles
  418. : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
  419. try {
  420. const { response, videoObject } = await fetchRemoteVideo(video.url)
  421. if (response.statusCode === HttpStatusCode.NOT_FOUND_404) {
  422. logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
  423. // Video does not exist anymore
  424. await video.destroy()
  425. return undefined
  426. }
  427. if (videoObject === undefined) {
  428. logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
  429. await video.setAsRefreshed()
  430. return video
  431. }
  432. const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
  433. const updateOptions = {
  434. video,
  435. videoObject,
  436. account: channelActor.VideoChannel.Account,
  437. channel: channelActor.VideoChannel
  438. }
  439. await retryTransactionWrapper(updateVideoFromAP, updateOptions)
  440. await syncVideoExternalAttributes(video, videoObject, options.syncParam)
  441. ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
  442. return video
  443. } catch (err) {
  444. logger.warn('Cannot refresh video %s.', options.video.url, { err })
  445. ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
  446. // Don't refresh in loop
  447. await video.setAsRefreshed()
  448. return video
  449. }
  450. }
  451. export {
  452. updateVideoFromAP,
  453. refreshVideoIfNeeded,
  454. federateVideoIfNeeded,
  455. fetchRemoteVideo,
  456. getOrCreateVideoAndAccountAndChannel,
  457. fetchRemoteVideoDescription,
  458. getOrCreateVideoChannelFromVideoObject
  459. }
  460. // ---------------------------------------------------------------------------
  461. function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
  462. const urlMediaType = url.mediaType
  463. return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
  464. }
  465. function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
  466. return url && url.mediaType === 'application/x-mpegURL'
  467. }
  468. function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
  469. return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
  470. }
  471. function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
  472. return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
  473. }
  474. function isAPHashTagObject (url: any): url is ActivityHashTagObject {
  475. return url && url.type === 'Hashtag'
  476. }
  477. async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
  478. logger.debug('Adding remote video %s.', videoObject.id)
  479. const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
  480. const video = VideoModel.build(videoData) as MVideoThumbnail
  481. const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
  482. .catch(err => {
  483. logger.error('Cannot create miniature from url.', { err })
  484. return undefined
  485. })
  486. let thumbnailModel: MThumbnail
  487. if (waitThumbnail === true) {
  488. thumbnailModel = await promiseThumbnail
  489. }
  490. const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
  491. const sequelizeOptions = { transaction: t }
  492. const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
  493. videoCreated.VideoChannel = channel
  494. if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
  495. const previewIcon = getPreviewFromIcons(videoObject)
  496. const previewUrl = previewIcon
  497. ? previewIcon.url
  498. : buildRemoteVideoBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
  499. const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
  500. if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
  501. // Process files
  502. const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
  503. const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
  504. const videoFiles = await Promise.all(videoFilePromises)
  505. const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
  506. videoCreated.VideoStreamingPlaylists = []
  507. for (const playlistAttributes of streamingPlaylistsAttributes) {
  508. const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
  509. const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
  510. const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
  511. playlistModel.VideoFiles = await Promise.all(videoFilePromises)
  512. videoCreated.VideoStreamingPlaylists.push(playlistModel)
  513. }
  514. // Process tags
  515. const tags = videoObject.tag
  516. .filter(isAPHashTagObject)
  517. .map(t => t.name)
  518. await setVideoTags({ video: videoCreated, tags, transaction: t })
  519. // Process captions
  520. const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
  521. return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
  522. })
  523. await Promise.all(videoCaptionsPromises)
  524. videoCreated.VideoFiles = videoFiles
  525. if (videoCreated.isLive) {
  526. const videoLive = new VideoLiveModel({
  527. streamKey: null,
  528. saveReplay: videoObject.liveSaveReplay,
  529. permanentLive: videoObject.permanentLive,
  530. videoId: videoCreated.id
  531. })
  532. videoCreated.VideoLive = await videoLive.save({ transaction: t })
  533. }
  534. const autoBlacklisted = await autoBlacklistVideoIfNeeded({
  535. video: videoCreated,
  536. user: undefined,
  537. isRemote: true,
  538. isNew: true,
  539. transaction: t
  540. })
  541. logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
  542. return { autoBlacklisted, videoCreated }
  543. })
  544. if (waitThumbnail === false) {
  545. // Error is already caught above
  546. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  547. promiseThumbnail.then(thumbnailModel => {
  548. if (!thumbnailModel) return
  549. thumbnailModel = videoCreated.id
  550. return thumbnailModel.save()
  551. })
  552. }
  553. return { autoBlacklisted, videoCreated }
  554. }
  555. function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
  556. const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
  557. ? VideoPrivacy.PUBLIC
  558. : VideoPrivacy.UNLISTED
  559. const duration = videoObject.duration.replace(/[^\d]+/, '')
  560. const language = videoObject.language?.identifier
  561. const category = videoObject.category
  562. ? parseInt(videoObject.category.identifier, 10)
  563. : undefined
  564. const licence = videoObject.licence
  565. ? parseInt(videoObject.licence.identifier, 10)
  566. : undefined
  567. const description = videoObject.content || null
  568. const support = videoObject.support || null
  569. return {
  570. name: videoObject.name,
  571. uuid: videoObject.uuid,
  572. url: videoObject.id,
  573. category,
  574. licence,
  575. language,
  576. description,
  577. support,
  578. nsfw: videoObject.sensitive,
  579. commentsEnabled: videoObject.commentsEnabled,
  580. downloadEnabled: videoObject.downloadEnabled,
  581. waitTranscoding: videoObject.waitTranscoding,
  582. isLive: videoObject.isLiveBroadcast,
  583. state: videoObject.state,
  584. channelId: videoChannel.id,
  585. duration: parseInt(duration, 10),
  586. createdAt: new Date(videoObject.published),
  587. publishedAt: new Date(videoObject.published),
  588. originallyPublishedAt: videoObject.originallyPublishedAt
  589. ? new Date(videoObject.originallyPublishedAt)
  590. : null,
  591. updatedAt: new Date(videoObject.updated),
  592. views: videoObject.views,
  593. likes: 0,
  594. dislikes: 0,
  595. remote: true,
  596. privacy
  597. }
  598. }
  599. function videoFileActivityUrlToDBAttributes (
  600. videoOrPlaylist: MVideo | MStreamingPlaylist,
  601. urls: (ActivityTagObject | ActivityUrlObject)[]
  602. ) {
  603. const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
  604. if (fileUrls.length === 0) return []
  605. const attributes: FilteredModelAttributes<VideoFileModel>[] = []
  606. for (const fileUrl of fileUrls) {
  607. // Fetch associated magnet uri
  608. const magnet = urls.filter(isAPMagnetUrlObject)
  609. .find(u => u.height === fileUrl.height)
  610. if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
  611. const parsed = magnetUtil.decode(magnet.href)
  612. if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
  613. throw new Error('Cannot parse magnet URI ' + magnet.href)
  614. }
  615. // Fetch associated metadata url, if any
  616. const metadata = urls.filter(isAPVideoFileMetadataObject)
  617. .find(u => {
  618. return u.height === fileUrl.height &&
  619. u.fps === fileUrl.fps &&
  620. u.rel.includes(fileUrl.mediaType)
  621. })
  622. const mediaType = fileUrl.mediaType
  623. const attribute = {
  624. extname: getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, mediaType),
  625. infoHash: parsed.infoHash,
  626. resolution: fileUrl.height,
  627. size: fileUrl.size,
  628. fps: fileUrl.fps || -1,
  629. metadataUrl: metadata?.href,
  630. // This is a video file owned by a video or by a streaming playlist
  631. videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
  632. videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
  633. }
  634. attributes.push(attribute)
  635. }
  636. return attributes
  637. }
  638. function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
  639. const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
  640. if (playlistUrls.length === 0) return []
  641. const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
  642. for (const playlistUrlObject of playlistUrls) {
  643. const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
  644. let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
  645. // FIXME: backward compatibility introduced in v2.1.0
  646. if (files.length === 0) files = videoFiles
  647. if (!segmentsSha256UrlObject) {
  648. logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
  649. continue
  650. }
  651. const attribute = {
  652. type: VideoStreamingPlaylistType.HLS,
  653. playlistUrl: playlistUrlObject.href,
  654. segmentsSha256Url: segmentsSha256UrlObject.href,
  655. p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
  656. p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
  657. videoId: video.id,
  658. tagAPObject: playlistUrlObject.tag
  659. }
  660. attributes.push(attribute)
  661. }
  662. return attributes
  663. }
  664. function getThumbnailFromIcons (videoObject: VideoObject) {
  665. let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
  666. // Fallback if there are not valid icons
  667. if (validIcons.length === 0) validIcons = videoObject.icon
  668. return minBy(validIcons, 'width')
  669. }
  670. function getPreviewFromIcons (videoObject: VideoObject) {
  671. const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
  672. // FIXME: don't put a fallback here for compatibility with PeerTube <2.2
  673. return maxBy(validIcons, 'width')
  674. }