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