]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
a5f58dd013c95769422cd393bd8eca018c9a89e0
[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 { basename, join } from 'path'
5 import { Transaction } from 'sequelize/types'
6 import { TrackerModel } from '@server/models/server/tracker'
7 import { VideoLiveModel } from '@server/models/video/video-live'
8 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
9 import {
10 ActivityHashTagObject,
11 ActivityMagnetUrlObject,
12 ActivityPlaylistSegmentHashesObject,
13 ActivityPlaylistUrlObject,
14 ActivitypubHttpFetcherPayload,
15 ActivityTagObject,
16 ActivityUrlObject,
17 ActivityVideoUrlObject
18 } from '../../../shared/index'
19 import { ActivityIconObject, ActivityTrackerUrlObject, VideoObject } from '../../../shared/models/activitypub/objects'
20 import { VideoPrivacy } from '../../../shared/models/videos'
21 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
22 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
23 import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
24 import {
25 isAPVideoFileUrlMetadataObject,
26 isAPVideoTrackerUrlObject,
27 sanitizeAndCheckVideoTorrentObject
28 } from '../../helpers/custom-validators/activitypub/videos'
29 import { isArray } from '../../helpers/custom-validators/misc'
30 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
31 import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
32 import { logger } from '../../helpers/logger'
33 import { doJSONRequest } from '../../helpers/requests'
34 import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
35 import {
36 ACTIVITY_PUB,
37 LAZY_STATIC_PATHS,
38 MIMETYPES,
39 P2P_MEDIA_LOADER_PEER_VERSION,
40 PREVIEWS_SIZE,
41 REMOTE_SCHEME,
42 THUMBNAILS_SIZE
43 } from '../../initializers/constants'
44 import { sequelizeTypescript } from '../../initializers/database'
45 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
46 import { VideoModel } from '../../models/video/video'
47 import { VideoCaptionModel } from '../../models/video/video-caption'
48 import { VideoCommentModel } from '../../models/video/video-comment'
49 import { VideoFileModel } from '../../models/video/video-file'
50 import { VideoShareModel } from '../../models/video/video-share'
51 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
52 import {
53 MAccountIdActor,
54 MChannelAccountLight,
55 MChannelDefault,
56 MChannelId,
57 MStreamingPlaylist,
58 MStreamingPlaylistFilesVideo,
59 MStreamingPlaylistVideo,
60 MVideo,
61 MVideoAccountLight,
62 MVideoAccountLightBlacklistAllFiles,
63 MVideoAP,
64 MVideoAPWithoutCaption,
65 MVideoCaption,
66 MVideoFile,
67 MVideoFullLight,
68 MVideoId,
69 MVideoImmutable,
70 MVideoThumbnail,
71 MVideoWithHost
72 } from '../../types/models'
73 import { MThumbnail } from '../../types/models/video/thumbnail'
74 import { FilteredModelAttributes } from '../../types/sequelize'
75 import { ActorFollowScoreCache } from '../files-cache'
76 import { JobQueue } from '../job-queue'
77 import { Notifier } from '../notifier'
78 import { PeerTubeSocket } from '../peertube-socket'
79 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
80 import { setVideoTags } from '../video'
81 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
82 import { generateTorrentFileName } from '../video-paths'
83 import { getOrCreateActorAndServerAndModel } from './actor'
84 import { crawlCollectionPage } from './crawl'
85 import { sendCreateVideo, sendUpdateVideo } from './send'
86 import { addVideoShares, shareVideoByServerAndChannel } from './share'
87 import { addVideoComments } from './video-comments'
88 import { createRates } from './video-rates'
89
90 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: Transaction) {
91 const video = videoArg as MVideoAP
92
93 if (
94 // Check this is not a blacklisted video, or unfederated blacklisted video
95 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
96 // Check the video is public/unlisted and published
97 video.hasPrivacyForFederation() && video.hasStateForFederation()
98 ) {
99 // Fetch more attributes that we will need to serialize in AP object
100 if (isArray(video.VideoCaptions) === false) {
101 video.VideoCaptions = await video.$get('VideoCaptions', {
102 attributes: [ 'filename', 'language' ],
103 transaction
104 })
105 }
106
107 if (isNewVideo) {
108 // Now we'll add the video's meta data to our followers
109 await sendCreateVideo(video, transaction)
110 await shareVideoByServerAndChannel(video, transaction)
111 } else {
112 await sendUpdateVideo(video, transaction)
113 }
114 }
115 }
116
117 async function fetchRemoteVideo (videoUrl: string): Promise<{ statusCode: number, videoObject: VideoObject }> {
118 logger.info('Fetching remote video %s.', videoUrl)
119
120 const { statusCode, body } = await doJSONRequest<any>(videoUrl, { activityPub: true })
121
122 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
123 logger.debug('Remote video JSON is not valid.', { body })
124 return { statusCode, videoObject: undefined }
125 }
126
127 return { statusCode, videoObject: body }
128 }
129
130 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
131 const host = video.VideoChannel.Account.Actor.Server.host
132 const path = video.getDescriptionAPIPath()
133 const url = REMOTE_SCHEME.HTTP + '://' + host + path
134
135 const { body } = await doJSONRequest<any>(url)
136 return body.description || ''
137 }
138
139 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
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: VideoObject, 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: VideoObject
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, { videoObject: options.videoObject, 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({
315 downloadUrl: getThumbnailFromIcons(videoObject).url,
316 video,
317 type: ThumbnailType.MINIATURE
318 })
319 } catch (err) {
320 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
321 }
322
323 const videoUpdated = await sequelizeTypescript.transaction(async t => {
324 const sequelizeOptions = { transaction: t }
325
326 videoFieldsSave = video.toJSON()
327
328 // Check we can update the channel: we trust the remote server
329 const oldVideoChannel = video.VideoChannel
330
331 if (!oldVideoChannel.Actor.serverId || !channel.Actor.serverId) {
332 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
333 }
334
335 if (oldVideoChannel.Actor.serverId !== channel.Actor.serverId) {
336 throw new Error('New channel ' + channel.Actor.url + ' is not on the same server than new channel ' + oldVideoChannel.Actor.url)
337 }
338
339 const to = overrideTo || videoObject.to
340 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
341 video.name = videoData.name
342 video.uuid = videoData.uuid
343 video.url = videoData.url
344 video.category = videoData.category
345 video.licence = videoData.licence
346 video.language = videoData.language
347 video.description = videoData.description
348 video.support = videoData.support
349 video.nsfw = videoData.nsfw
350 video.commentsEnabled = videoData.commentsEnabled
351 video.downloadEnabled = videoData.downloadEnabled
352 video.waitTranscoding = videoData.waitTranscoding
353 video.state = videoData.state
354 video.duration = videoData.duration
355 video.createdAt = videoData.createdAt
356 video.publishedAt = videoData.publishedAt
357 video.originallyPublishedAt = videoData.originallyPublishedAt
358 video.privacy = videoData.privacy
359 video.channelId = videoData.channelId
360 video.views = videoData.views
361 video.isLive = videoData.isLive
362
363 // Ensures we update the updated video attribute
364 video.changed('updatedAt', true)
365
366 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
367
368 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
369
370 if (videoUpdated.getPreview()) {
371 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
372 const previewModel = createPlaceholderThumbnail({
373 fileUrl: previewUrl,
374 video,
375 type: ThumbnailType.PREVIEW,
376 size: PREVIEWS_SIZE
377 })
378 await videoUpdated.addAndSaveThumbnail(previewModel, t)
379 }
380
381 {
382 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
383 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
384
385 // Remove video files that do not exist anymore
386 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
387 await Promise.all(destroyTasks)
388
389 // Update or add other one
390 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
391 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
392 }
393
394 {
395 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
396 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
397
398 // Remove video playlists that do not exist anymore
399 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
400 await Promise.all(destroyTasks)
401
402 let oldStreamingPlaylistFiles: MVideoFile[] = []
403 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
404 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
405 }
406
407 videoUpdated.VideoStreamingPlaylists = []
408
409 for (const playlistAttributes of streamingPlaylistAttributes) {
410 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
411 .then(([ streamingPlaylist ]) => streamingPlaylist as MStreamingPlaylistFilesVideo)
412 streamingPlaylistModel.Video = videoUpdated
413
414 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
415 .map(a => new VideoFileModel(a))
416 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
417 await Promise.all(destroyTasks)
418
419 // Update or add other one
420 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
421 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
422
423 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
424 }
425 }
426
427 {
428 // Update Tags
429 const tags = videoObject.tag
430 .filter(isAPHashTagObject)
431 .map(tag => tag.name)
432 await setVideoTags({ video: videoUpdated, tags, transaction: t })
433 }
434
435 // Update trackers
436 {
437 const trackers = getTrackerUrls(videoObject, videoUpdated)
438 await setVideoTrackers({ video: videoUpdated, trackers, transaction: t })
439 }
440
441 {
442 // Update captions
443 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
444
445 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
446 const caption = new VideoCaptionModel({
447 videoId: videoUpdated.id,
448 filename: VideoCaptionModel.generateCaptionName(c.identifier),
449 language: c.identifier,
450 fileUrl: c.url
451 }) as MVideoCaption
452
453 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
454 })
455 await Promise.all(videoCaptionsPromises)
456 }
457
458 {
459 // Create or update existing live
460 if (video.isLive) {
461 const [ videoLive ] = await VideoLiveModel.upsert({
462 saveReplay: videoObject.liveSaveReplay,
463 permanentLive: videoObject.permanentLive,
464 videoId: video.id
465 }, { transaction: t, returning: true })
466
467 videoUpdated.VideoLive = videoLive
468 } else { // Delete existing live if it exists
469 await VideoLiveModel.destroy({
470 where: {
471 videoId: video.id
472 },
473 transaction: t
474 })
475
476 videoUpdated.VideoLive = null
477 }
478 }
479
480 return videoUpdated
481 })
482
483 await autoBlacklistVideoIfNeeded({
484 video: videoUpdated,
485 user: undefined,
486 isRemote: true,
487 isNew: false,
488 transaction: undefined
489 })
490
491 // Notify our users?
492 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
493
494 if (videoUpdated.isLive) {
495 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
496 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
497 }
498
499 logger.info('Remote video with uuid %s updated', videoObject.uuid)
500
501 return videoUpdated
502 } catch (err) {
503 if (video !== undefined && videoFieldsSave !== undefined) {
504 resetSequelizeInstance(video, videoFieldsSave)
505 }
506
507 // This is just a debug because we will retry the insert
508 logger.debug('Cannot update the remote video.', { err })
509 throw err
510 }
511 }
512
513 async function refreshVideoIfNeeded (options: {
514 video: MVideoThumbnail
515 fetchedType: VideoFetchByUrlType
516 syncParam: SyncParam
517 }): Promise<MVideoThumbnail> {
518 if (!options.video.isOutdated()) return options.video
519
520 // We need more attributes if the argument video was fetched with not enough joints
521 const video = options.fetchedType === 'all'
522 ? options.video as MVideoAccountLightBlacklistAllFiles
523 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
524
525 try {
526 const { statusCode, videoObject } = await fetchRemoteVideo(video.url)
527 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
528 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
529
530 // Video does not exist anymore
531 await video.destroy()
532 return undefined
533 }
534
535 if (videoObject === undefined) {
536 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
537
538 await video.setAsRefreshed()
539 return video
540 }
541
542 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
543
544 const updateOptions = {
545 video,
546 videoObject,
547 account: channelActor.VideoChannel.Account,
548 channel: channelActor.VideoChannel
549 }
550 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
551 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
552
553 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
554
555 return video
556 } catch (err) {
557 logger.warn('Cannot refresh video %s.', options.video.url, { err })
558
559 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
560
561 // Don't refresh in loop
562 await video.setAsRefreshed()
563 return video
564 }
565 }
566
567 export {
568 updateVideoFromAP,
569 refreshVideoIfNeeded,
570 federateVideoIfNeeded,
571 fetchRemoteVideo,
572 getOrCreateVideoAndAccountAndChannel,
573 fetchRemoteVideoDescription,
574 getOrCreateVideoChannelFromVideoObject
575 }
576
577 // ---------------------------------------------------------------------------
578
579 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
580 const urlMediaType = url.mediaType
581
582 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
583 }
584
585 function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
586 return url && url.mediaType === 'application/x-mpegURL'
587 }
588
589 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
590 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
591 }
592
593 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
594 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
595 }
596
597 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
598 return url && url.type === 'Hashtag'
599 }
600
601 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
602 logger.debug('Adding remote video %s.', videoObject.id)
603
604 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
605 const video = VideoModel.build(videoData) as MVideoThumbnail
606
607 const promiseThumbnail = createVideoMiniatureFromUrl({
608 downloadUrl: getThumbnailFromIcons(videoObject).url,
609 video,
610 type: ThumbnailType.MINIATURE
611 }).catch(err => {
612 logger.error('Cannot create miniature from url.', { err })
613 return undefined
614 })
615
616 let thumbnailModel: MThumbnail
617 if (waitThumbnail === true) {
618 thumbnailModel = await promiseThumbnail
619 }
620
621 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
622 try {
623 const sequelizeOptions = { transaction: t }
624
625 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
626 videoCreated.VideoChannel = channel
627
628 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
629
630 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
631 const previewModel = createPlaceholderThumbnail({
632 fileUrl: previewUrl,
633 video: videoCreated,
634 type: ThumbnailType.PREVIEW,
635 size: PREVIEWS_SIZE
636 })
637
638 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
639
640 // Process files
641 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
642
643 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
644 const videoFiles = await Promise.all(videoFilePromises)
645
646 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
647 videoCreated.VideoStreamingPlaylists = []
648
649 for (const playlistAttributes of streamingPlaylistsAttributes) {
650 const playlist = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t }) as MStreamingPlaylistFilesVideo
651 playlist.Video = videoCreated
652
653 const playlistFiles = videoFileActivityUrlToDBAttributes(playlist, playlistAttributes.tagAPObject)
654 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
655 playlist.VideoFiles = await Promise.all(videoFilePromises)
656
657 videoCreated.VideoStreamingPlaylists.push(playlist)
658 }
659
660 // Process tags
661 const tags = videoObject.tag
662 .filter(isAPHashTagObject)
663 .map(t => t.name)
664 await setVideoTags({ video: videoCreated, tags, transaction: t })
665
666 // Process captions
667 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
668 const caption = new VideoCaptionModel({
669 videoId: videoCreated.id,
670 filename: VideoCaptionModel.generateCaptionName(c.identifier),
671 language: c.identifier,
672 fileUrl: c.url
673 }) as MVideoCaption
674
675 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
676 })
677 await Promise.all(videoCaptionsPromises)
678
679 // Process trackers
680 {
681 const trackers = getTrackerUrls(videoObject, videoCreated)
682 await setVideoTrackers({ video: videoCreated, trackers, transaction: t })
683 }
684
685 videoCreated.VideoFiles = videoFiles
686
687 if (videoCreated.isLive) {
688 const videoLive = new VideoLiveModel({
689 streamKey: null,
690 saveReplay: videoObject.liveSaveReplay,
691 permanentLive: videoObject.permanentLive,
692 videoId: videoCreated.id
693 })
694
695 videoCreated.VideoLive = await videoLive.save({ transaction: t })
696 }
697
698 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
699 video: videoCreated,
700 user: undefined,
701 isRemote: true,
702 isNew: true,
703 transaction: t
704 })
705
706 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
707
708 return { autoBlacklisted, videoCreated }
709 } catch (err) {
710 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
711 // Remove thumbnail
712 if (thumbnailModel) await thumbnailModel.removeThumbnail()
713
714 throw err
715 }
716 })
717
718 if (waitThumbnail === false) {
719 // Error is already caught above
720 // eslint-disable-next-line @typescript-eslint/no-floating-promises
721 promiseThumbnail.then(thumbnailModel => {
722 if (!thumbnailModel) return
723
724 thumbnailModel = videoCreated.id
725
726 return thumbnailModel.save()
727 })
728 }
729
730 return { autoBlacklisted, videoCreated }
731 }
732
733 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
734 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
735 ? VideoPrivacy.PUBLIC
736 : VideoPrivacy.UNLISTED
737
738 const duration = videoObject.duration.replace(/[^\d]+/, '')
739 const language = videoObject.language?.identifier
740
741 const category = videoObject.category
742 ? parseInt(videoObject.category.identifier, 10)
743 : undefined
744
745 const licence = videoObject.licence
746 ? parseInt(videoObject.licence.identifier, 10)
747 : undefined
748
749 const description = videoObject.content || null
750 const support = videoObject.support || null
751
752 return {
753 name: videoObject.name,
754 uuid: videoObject.uuid,
755 url: videoObject.id,
756 category,
757 licence,
758 language,
759 description,
760 support,
761 nsfw: videoObject.sensitive,
762 commentsEnabled: videoObject.commentsEnabled,
763 downloadEnabled: videoObject.downloadEnabled,
764 waitTranscoding: videoObject.waitTranscoding,
765 isLive: videoObject.isLiveBroadcast,
766 state: videoObject.state,
767 channelId: videoChannel.id,
768 duration: parseInt(duration, 10),
769 createdAt: new Date(videoObject.published),
770 publishedAt: new Date(videoObject.published),
771
772 originallyPublishedAt: videoObject.originallyPublishedAt
773 ? new Date(videoObject.originallyPublishedAt)
774 : null,
775
776 updatedAt: new Date(videoObject.updated),
777 views: videoObject.views,
778 likes: 0,
779 dislikes: 0,
780 remote: true,
781 privacy
782 }
783 }
784
785 function videoFileActivityUrlToDBAttributes (
786 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
787 urls: (ActivityTagObject | ActivityUrlObject)[]
788 ) {
789 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
790
791 if (fileUrls.length === 0) return []
792
793 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
794 for (const fileUrl of fileUrls) {
795 // Fetch associated magnet uri
796 const magnet = urls.filter(isAPMagnetUrlObject)
797 .find(u => u.height === fileUrl.height)
798
799 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
800
801 const parsed = magnetUtil.decode(magnet.href)
802 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
803 throw new Error('Cannot parse magnet URI ' + magnet.href)
804 }
805
806 const torrentUrl = Array.isArray(parsed.xs)
807 ? parsed.xs[0]
808 : parsed.xs
809
810 // Fetch associated metadata url, if any
811 const metadata = urls.filter(isAPVideoFileUrlMetadataObject)
812 .find(u => {
813 return u.height === fileUrl.height &&
814 u.fps === fileUrl.fps &&
815 u.rel.includes(fileUrl.mediaType)
816 })
817
818 const extname = getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, fileUrl.mediaType)
819 const resolution = fileUrl.height
820 const videoId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id
821 const videoStreamingPlaylistId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
822
823 const attribute = {
824 extname,
825 infoHash: parsed.infoHash,
826 resolution,
827 size: fileUrl.size,
828 fps: fileUrl.fps || -1,
829 metadataUrl: metadata?.href,
830
831 // Use the name of the remote file because we don't proxify video file requests
832 filename: basename(fileUrl.href),
833 fileUrl: fileUrl.href,
834
835 torrentUrl,
836 // Use our own torrent name since we proxify torrent requests
837 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
838
839 // This is a video file owned by a video or by a streaming playlist
840 videoId,
841 videoStreamingPlaylistId
842 }
843
844 attributes.push(attribute)
845 }
846
847 return attributes
848 }
849
850 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
851 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
852 if (playlistUrls.length === 0) return []
853
854 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
855 for (const playlistUrlObject of playlistUrls) {
856 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
857
858 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
859
860 // FIXME: backward compatibility introduced in v2.1.0
861 if (files.length === 0) files = videoFiles
862
863 if (!segmentsSha256UrlObject) {
864 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
865 continue
866 }
867
868 const attribute = {
869 type: VideoStreamingPlaylistType.HLS,
870 playlistUrl: playlistUrlObject.href,
871 segmentsSha256Url: segmentsSha256UrlObject.href,
872 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
873 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
874 videoId: video.id,
875 tagAPObject: playlistUrlObject.tag
876 }
877
878 attributes.push(attribute)
879 }
880
881 return attributes
882 }
883
884 function getThumbnailFromIcons (videoObject: VideoObject) {
885 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
886 // Fallback if there are not valid icons
887 if (validIcons.length === 0) validIcons = videoObject.icon
888
889 return minBy(validIcons, 'width')
890 }
891
892 function getPreviewFromIcons (videoObject: VideoObject) {
893 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
894
895 return maxBy(validIcons, 'width')
896 }
897
898 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
899 return previewIcon
900 ? previewIcon.url
901 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
902 }
903
904 function getTrackerUrls (object: VideoObject, video: MVideoWithHost) {
905 let wsFound = false
906
907 const trackers = object.url.filter(u => isAPVideoTrackerUrlObject(u))
908 .map((u: ActivityTrackerUrlObject) => {
909 if (isArray(u.rel) && u.rel.includes('websocket')) wsFound = true
910
911 return u.href
912 })
913
914 if (wsFound) return trackers
915
916 return [
917 buildRemoteVideoBaseUrl(video, '/tracker/socket', REMOTE_SCHEME.WS),
918 buildRemoteVideoBaseUrl(video, '/tracker/announce')
919 ]
920 }
921
922 async function setVideoTrackers (options: {
923 video: MVideo
924 trackers: string[]
925 transaction?: Transaction
926 }) {
927 const { video, trackers, transaction } = options
928
929 const trackerInstances = await TrackerModel.findOrCreateTrackers(trackers, transaction)
930
931 await video.$set('Trackers', trackerInstances, { transaction })
932 }