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