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