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