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