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