]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
452e43c8cca9022ad22d333e141bd3c68cddda37
[github/Chocobozzz/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 ActivityVideoFileMetadataObject,
13 ActivityVideoUrlObject,
14 VideoState
15 } from '../../../shared/index'
16 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
17 import { VideoPrivacy } from '../../../shared/models/videos'
18 import { sanitizeAndCheckVideoTorrentObject, isAPVideoFileMetadataObject } from '../../helpers/custom-validators/activitypub/videos'
19 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
20 import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
21 import { logger } from '../../helpers/logger'
22 import { doRequest } from '../../helpers/requests'
23 import {
24 ACTIVITY_PUB,
25 MIMETYPES,
26 P2P_MEDIA_LOADER_PEER_VERSION,
27 PREVIEWS_SIZE,
28 REMOTE_SCHEME,
29 STATIC_PATHS,
30 THUMBNAILS_SIZE
31 } from '../../initializers/constants'
32 import { TagModel } from '../../models/video/tag'
33 import { VideoModel } from '../../models/video/video'
34 import { VideoFileModel } from '../../models/video/video-file'
35 import { getOrCreateActorAndServerAndModel } from './actor'
36 import { addVideoComments } from './video-comments'
37 import { crawlCollectionPage } from './crawl'
38 import { sendCreateVideo, sendUpdateVideo } from './send'
39 import { isArray } from '../../helpers/custom-validators/misc'
40 import { VideoCaptionModel } from '../../models/video/video-caption'
41 import { JobQueue } from '../job-queue'
42 import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher'
43 import { createRates } from './video-rates'
44 import { addVideoShares, shareVideoByServerAndChannel } from './share'
45 import { fetchVideoByUrl, VideoFetchByUrlType } from '../../helpers/video'
46 import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
47 import { Notifier } from '../notifier'
48 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
49 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
50 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
51 import { VideoShareModel } from '../../models/video/video-share'
52 import { VideoCommentModel } from '../../models/video/video-comment'
53 import { sequelizeTypescript } from '../../initializers/database'
54 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
55 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
56 import { join } from 'path'
57 import { FilteredModelAttributes } from '../../typings/sequelize'
58 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
59 import { ActorFollowScoreCache } from '../files-cache'
60 import {
61 MAccountIdActor,
62 MChannelAccountLight,
63 MChannelDefault,
64 MChannelId,
65 MStreamingPlaylist,
66 MVideo,
67 MVideoAccountLight,
68 MVideoAccountLightBlacklistAllFiles,
69 MVideoAP,
70 MVideoAPWithoutCaption,
71 MVideoFile,
72 MVideoFullLight,
73 MVideoId,
74 MVideoImmutable,
75 MVideoThumbnail
76 } from '../../typings/models'
77 import { MThumbnail } from '../../typings/models/video/thumbnail'
78 import { maxBy, minBy } from 'lodash'
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 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
278
279 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
280
281 return { video: videoCreated, created: true, autoBlacklisted }
282 }
283
284 async function updateVideoFromAP (options: {
285 video: MVideoAccountLightBlacklistAllFiles
286 videoObject: VideoTorrentObject
287 account: MAccountIdActor
288 channel: MChannelDefault
289 overrideTo?: string[]
290 }) {
291 const { video, videoObject, account, channel, overrideTo } = options
292
293 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
294
295 let videoFieldsSave: any
296 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
297 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
298
299 try {
300 let thumbnailModel: MThumbnail
301
302 try {
303 thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
304 } catch (err) {
305 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
306 }
307
308 const videoUpdated = await sequelizeTypescript.transaction(async t => {
309 const sequelizeOptions = { transaction: t }
310
311 videoFieldsSave = video.toJSON()
312
313 // Check actor has the right to update the video
314 const videoChannel = video.VideoChannel
315 if (videoChannel.Account.id !== account.id) {
316 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
317 }
318
319 const to = overrideTo || videoObject.to
320 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
321 video.name = videoData.name
322 video.uuid = videoData.uuid
323 video.url = videoData.url
324 video.category = videoData.category
325 video.licence = videoData.licence
326 video.language = videoData.language
327 video.description = videoData.description
328 video.support = videoData.support
329 video.nsfw = videoData.nsfw
330 video.commentsEnabled = videoData.commentsEnabled
331 video.downloadEnabled = videoData.downloadEnabled
332 video.waitTranscoding = videoData.waitTranscoding
333 video.state = videoData.state
334 video.duration = videoData.duration
335 video.createdAt = videoData.createdAt
336 video.publishedAt = videoData.publishedAt
337 video.originallyPublishedAt = videoData.originallyPublishedAt
338 video.privacy = videoData.privacy
339 video.channelId = videoData.channelId
340 video.views = videoData.views
341
342 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
343
344 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
345
346 if (videoUpdated.getPreview()) {
347 const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
348 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
349 await videoUpdated.addAndSaveThumbnail(previewModel, t)
350 }
351
352 {
353 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
354 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
355
356 // Remove video files that do not exist anymore
357 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
358 await Promise.all(destroyTasks)
359
360 // Update or add other one
361 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
362 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
363 }
364
365 {
366 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
367 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
368
369 // Remove video playlists that do not exist anymore
370 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
371 await Promise.all(destroyTasks)
372
373 let oldStreamingPlaylistFiles: MVideoFile[] = []
374 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
375 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
376 }
377
378 videoUpdated.VideoStreamingPlaylists = []
379
380 for (const playlistAttributes of streamingPlaylistAttributes) {
381 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
382 .then(([ streamingPlaylist ]) => streamingPlaylist)
383
384 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
385 .map(a => new VideoFileModel(a))
386 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
387 await Promise.all(destroyTasks)
388
389 // Update or add other one
390 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
391 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
392
393 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
394 }
395 }
396
397 {
398 // Update Tags
399 const tags = videoObject.tag
400 .filter(isAPHashTagObject)
401 .map(tag => tag.name)
402 const tagInstances = await TagModel.findOrCreateTags(tags, t)
403 await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
404 }
405
406 {
407 // Update captions
408 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
409
410 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
411 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
412 })
413 await Promise.all(videoCaptionsPromises)
414 }
415
416 return videoUpdated
417 })
418
419 await autoBlacklistVideoIfNeeded({
420 video: videoUpdated,
421 user: undefined,
422 isRemote: true,
423 isNew: false,
424 transaction: undefined
425 })
426
427 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
428
429 logger.info('Remote video with uuid %s updated', videoObject.uuid)
430
431 return videoUpdated
432 } catch (err) {
433 if (video !== undefined && videoFieldsSave !== undefined) {
434 resetSequelizeInstance(video, videoFieldsSave)
435 }
436
437 // This is just a debug because we will retry the insert
438 logger.debug('Cannot update the remote video.', { err })
439 throw err
440 }
441 }
442
443 async function refreshVideoIfNeeded (options: {
444 video: MVideoThumbnail
445 fetchedType: VideoFetchByUrlType
446 syncParam: SyncParam
447 }): Promise<MVideoThumbnail> {
448 if (!options.video.isOutdated()) return options.video
449
450 // We need more attributes if the argument video was fetched with not enough joints
451 const video = options.fetchedType === 'all'
452 ? options.video as MVideoAccountLightBlacklistAllFiles
453 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
454
455 try {
456 const { response, videoObject } = await fetchRemoteVideo(video.url)
457 if (response.statusCode === 404) {
458 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
459
460 // Video does not exist anymore
461 await video.destroy()
462 return undefined
463 }
464
465 if (videoObject === undefined) {
466 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
467
468 await video.setAsRefreshed()
469 return video
470 }
471
472 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
473
474 const updateOptions = {
475 video,
476 videoObject,
477 account: channelActor.VideoChannel.Account,
478 channel: channelActor.VideoChannel
479 }
480 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
481 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
482
483 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
484
485 return video
486 } catch (err) {
487 logger.warn('Cannot refresh video %s.', options.video.url, { err })
488
489 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
490
491 // Don't refresh in loop
492 await video.setAsRefreshed()
493 return video
494 }
495 }
496
497 export {
498 updateVideoFromAP,
499 refreshVideoIfNeeded,
500 federateVideoIfNeeded,
501 fetchRemoteVideo,
502 getOrCreateVideoAndAccountAndChannel,
503 fetchRemoteVideoDescription,
504 getOrCreateVideoChannelFromVideoObject
505 }
506
507 // ---------------------------------------------------------------------------
508
509 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
510 const mimeTypes = Object.keys(MIMETYPES.VIDEO.MIMETYPE_EXT)
511
512 const urlMediaType = url.mediaType
513 return mimeTypes.includes(urlMediaType) && urlMediaType.startsWith('video/')
514 }
515
516 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
517 return url && url.mediaType === 'application/x-mpegURL'
518 }
519
520 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
521 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
522 }
523
524 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
525 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
526 }
527
528 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
529 return url && url.type === 'Hashtag'
530 }
531
532 async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAccountLight, waitThumbnail = false) {
533 logger.debug('Adding remote video %s.', videoObject.id)
534
535 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
536 const video = VideoModel.build(videoData) as MVideoThumbnail
537
538 const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
539 .catch(err => {
540 logger.error('Cannot create miniature from url.', { err })
541 return undefined
542 })
543
544 let thumbnailModel: MThumbnail
545 if (waitThumbnail === true) {
546 thumbnailModel = await promiseThumbnail
547 }
548
549 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
550 const sequelizeOptions = { transaction: t }
551
552 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
553 videoCreated.VideoChannel = channel
554
555 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
556
557 const previewIcon = getPreviewFromIcons(videoObject)
558 const previewUrl = previewIcon
559 ? previewIcon.url
560 : buildRemoteVideoBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
561 const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
562
563 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
564
565 // Process files
566 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
567
568 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
569 const videoFiles = await Promise.all(videoFilePromises)
570
571 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
572 videoCreated.VideoStreamingPlaylists = []
573
574 for (const playlistAttributes of streamingPlaylistsAttributes) {
575 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
576
577 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
578 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
579 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
580
581 videoCreated.VideoStreamingPlaylists.push(playlistModel)
582 }
583
584 // Process tags
585 const tags = videoObject.tag
586 .filter(isAPHashTagObject)
587 .map(t => t.name)
588 const tagInstances = await TagModel.findOrCreateTags(tags, t)
589 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
590
591 // Process captions
592 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
593 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
594 })
595 await Promise.all(videoCaptionsPromises)
596
597 videoCreated.VideoFiles = videoFiles
598 videoCreated.Tags = tagInstances
599
600 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
601 video: videoCreated,
602 user: undefined,
603 isRemote: true,
604 isNew: true,
605 transaction: t
606 })
607
608 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
609
610 return { autoBlacklisted, videoCreated }
611 })
612
613 if (waitThumbnail === false) {
614 // Error is already caught above
615 // eslint-disable-next-line @typescript-eslint/no-floating-promises
616 promiseThumbnail.then(thumbnailModel => {
617 if (!thumbnailModel) return
618
619 thumbnailModel = videoCreated.id
620
621 return thumbnailModel.save()
622 })
623 }
624
625 return { autoBlacklisted, videoCreated }
626 }
627
628 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) {
629 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
630 ? VideoPrivacy.PUBLIC
631 : VideoPrivacy.UNLISTED
632
633 const duration = videoObject.duration.replace(/[^\d]+/, '')
634 const language = videoObject.language?.identifier
635
636 const category = videoObject.category
637 ? parseInt(videoObject.category.identifier, 10)
638 : undefined
639
640 const licence = videoObject.licence
641 ? parseInt(videoObject.licence.identifier, 10)
642 : undefined
643
644 const description = videoObject.content || null
645 const support = videoObject.support || null
646
647 return {
648 name: videoObject.name,
649 uuid: videoObject.uuid,
650 url: videoObject.id,
651 category,
652 licence,
653 language,
654 description,
655 support,
656 nsfw: videoObject.sensitive,
657 commentsEnabled: videoObject.commentsEnabled,
658 downloadEnabled: videoObject.downloadEnabled,
659 waitTranscoding: videoObject.waitTranscoding,
660 state: videoObject.state,
661 channelId: videoChannel.id,
662 duration: parseInt(duration, 10),
663 createdAt: new Date(videoObject.published),
664 publishedAt: new Date(videoObject.published),
665
666 originallyPublishedAt: videoObject.originallyPublishedAt
667 ? new Date(videoObject.originallyPublishedAt)
668 : null,
669
670 updatedAt: new Date(videoObject.updated),
671 views: videoObject.views,
672 likes: 0,
673 dislikes: 0,
674 remote: true,
675 privacy
676 }
677 }
678
679 function videoFileActivityUrlToDBAttributes (
680 videoOrPlaylist: MVideo | MStreamingPlaylist,
681 urls: (ActivityTagObject | ActivityUrlObject)[]
682 ) {
683 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
684
685 if (fileUrls.length === 0) return []
686
687 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
688 for (const fileUrl of fileUrls) {
689 // Fetch associated magnet uri
690 const magnet = urls.filter(isAPMagnetUrlObject)
691 .find(u => u.height === fileUrl.height)
692
693 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
694
695 const parsed = magnetUtil.decode(magnet.href)
696 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
697 throw new Error('Cannot parse magnet URI ' + magnet.href)
698 }
699
700 // Fetch associated metadata url, if any
701 const metadata = urls.filter(isAPVideoFileMetadataObject)
702 .find(u => {
703 return u.height === fileUrl.height &&
704 u.fps === fileUrl.fps &&
705 u.rel.includes(fileUrl.mediaType)
706 })
707
708 const mediaType = fileUrl.mediaType
709 const attribute = {
710 extname: MIMETYPES.VIDEO.MIMETYPE_EXT[mediaType],
711 infoHash: parsed.infoHash,
712 resolution: fileUrl.height,
713 size: fileUrl.size,
714 fps: fileUrl.fps || -1,
715 metadataUrl: metadata?.href,
716
717 // This is a video file owned by a video or by a streaming playlist
718 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
719 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
720 }
721
722 attributes.push(attribute)
723 }
724
725 return attributes
726 }
727
728 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoTorrentObject, videoFiles: MVideoFile[]) {
729 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
730 if (playlistUrls.length === 0) return []
731
732 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
733 for (const playlistUrlObject of playlistUrls) {
734 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
735
736 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
737
738 // FIXME: backward compatibility introduced in v2.1.0
739 if (files.length === 0) files = videoFiles
740
741 if (!segmentsSha256UrlObject) {
742 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
743 continue
744 }
745
746 const attribute = {
747 type: VideoStreamingPlaylistType.HLS,
748 playlistUrl: playlistUrlObject.href,
749 segmentsSha256Url: segmentsSha256UrlObject.href,
750 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
751 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
752 videoId: video.id,
753 tagAPObject: playlistUrlObject.tag
754 }
755
756 attributes.push(attribute)
757 }
758
759 return attributes
760 }
761
762 function getThumbnailFromIcons (videoObject: VideoTorrentObject) {
763 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
764 // Fallback if there are not valid icons
765 if (validIcons.length === 0) validIcons = videoObject.icon
766
767 return minBy(validIcons, 'width')
768 }
769
770 function getPreviewFromIcons (videoObject: VideoTorrentObject) {
771 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
772
773 // FIXME: don't put a fallback here for compatibility with PeerTube <2.2
774
775 return maxBy(validIcons, 'width')
776 }