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'
11 ActivityHashTagObject,
12 ActivityMagnetUrlObject,
13 ActivityPlaylistSegmentHashesObject,
14 ActivityPlaylistUrlObject,
15 ActivitypubHttpFetcherPayload,
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'
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'
40 P2P_MEDIA_LOADER_PEER_VERSION,
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'
59 MStreamingPlaylistFilesVideo,
60 MStreamingPlaylistVideo,
63 MVideoAccountLightBlacklistAllFiles,
65 MVideoAPWithoutCaption,
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'
91 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: Transaction) {
92 const video = videoArg as MVideoAP
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()
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' ],
109 // Now we'll add the video's meta data to our followers
110 await sendCreateVideo(video, transaction)
111 await shareVideoByServerAndChannel(video, transaction)
113 await sendUpdateVideo(video, transaction)
118 async function fetchRemoteVideo (videoUrl: string): Promise<{ statusCode: number, videoObject: VideoObject }> {
119 logger.info('Fetching remote video %s.', videoUrl)
121 const { statusCode, body } = await doJSONRequest<any>(videoUrl, { activityPub: true })
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 }
128 return { statusCode, videoObject: body }
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
136 const { body } = await doJSONRequest<any>(url)
137 return body.description || ''
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)
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}`)
148 return getOrCreateActorAndServerAndModel(channel.id, 'all')
157 refreshVideo?: boolean
159 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
160 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
162 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
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)
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 }))
171 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
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)
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 }))
181 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
184 if (syncParam.shares === true) {
185 const handler = items => addVideoShares(items, video)
186 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
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 }))
191 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
194 if (syncParam.comments === true) {
195 const handler = items => addVideoComments(items)
196 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
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 }))
201 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
204 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
207 type GetVideoResult <T> = Promise<{
210 autoBlacklisted?: boolean
213 type GetVideoParamAll = {
214 videoObject: { id: string } | string
215 syncParam?: SyncParam
217 allowRefresh?: boolean
220 type GetVideoParamImmutable = {
221 videoObject: { id: string } | string
222 syncParam?: SyncParam
223 fetchType: 'only-immutable-attributes'
227 type GetVideoParamOther = {
228 videoObject: { id: string } | string
229 syncParam?: SyncParam
230 fetchType?: 'all' | 'only-video'
231 allowRefresh?: boolean
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> {
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
248 const videoUrl = getAPId(options.videoObject)
249 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
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,
260 if (syncParam.refreshVideo === true) {
261 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
263 await JobQueue.Instance.createJobWithPromise({
264 type: 'activitypub-refresher',
265 payload: { type: 'video', url: videoFromDatabase.url }
270 return { video: videoFromDatabase, created: false }
273 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
274 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
276 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
277 const videoChannel = actor.VideoChannel
280 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
282 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
284 return { video: videoCreated, created: true, autoBlacklisted }
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 }
296 async function updateVideoFromAP (options: {
297 video: MVideoAccountLightBlacklistAllFiles
298 videoObject: VideoObject
299 account: MAccountIdActor
300 channel: MChannelDefault
301 overrideTo?: string[]
303 const { video, videoObject, account, channel, overrideTo } = options
305 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
307 let videoFieldsSave: any
308 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
309 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
312 let thumbnailModel: MThumbnail
315 thumbnailModel = await createVideoMiniatureFromUrl({
316 downloadUrl: getThumbnailFromIcons(videoObject).url,
318 type: ThumbnailType.MINIATURE
321 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
324 const videoUpdated = await sequelizeTypescript.transaction(async t => {
325 const sequelizeOptions = { transaction: t }
327 videoFieldsSave = video.toJSON()
329 // Check we can update the channel: we trust the remote server
330 const oldVideoChannel = video.VideoChannel
332 if (!oldVideoChannel.Actor.serverId || !channel.Actor.serverId) {
333 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
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)
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
364 // Ensures we update the updated video attribute
365 video.changed('updatedAt', true)
367 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
369 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
371 if (videoUpdated.getPreview()) {
372 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
373 const previewModel = createPlaceholderThumbnail({
376 type: ThumbnailType.PREVIEW,
379 await videoUpdated.addAndSaveThumbnail(previewModel, t)
383 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
384 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
386 // Remove video files that do not exist anymore
387 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
388 await Promise.all(destroyTasks)
390 // Update or add other one
391 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
392 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
396 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
397 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
399 // Remove video playlists that do not exist anymore
400 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
401 await Promise.all(destroyTasks)
403 let oldStreamingPlaylistFiles: MVideoFile[] = []
404 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
405 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
408 videoUpdated.VideoStreamingPlaylists = []
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
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)
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)
424 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
430 const tags = videoObject.tag
431 .filter(isAPHashTagObject)
432 .map(tag => tag.name)
433 await setVideoTags({ video: videoUpdated, tags, transaction: t })
438 const trackers = getTrackerUrls(videoObject, videoUpdated)
439 await setVideoTrackers({ video: videoUpdated, trackers, transaction: t })
444 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
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,
454 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
456 await Promise.all(videoCaptionsPromises)
460 // Create or update existing live
462 const [ videoLive ] = await VideoLiveModel.upsert({
463 saveReplay: videoObject.liveSaveReplay,
464 permanentLive: videoObject.permanentLive,
466 }, { transaction: t, returning: true })
468 videoUpdated.VideoLive = videoLive
469 } else { // Delete existing live if it exists
470 await VideoLiveModel.destroy({
477 videoUpdated.VideoLive = null
484 await autoBlacklistVideoIfNeeded({
489 transaction: undefined
493 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
495 if (videoUpdated.isLive) {
496 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
497 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
500 logger.info('Remote video with uuid %s updated', videoObject.uuid)
504 if (video !== undefined && videoFieldsSave !== undefined) {
505 resetSequelizeInstance(video, videoFieldsSave)
508 // This is just a debug because we will retry the insert
509 logger.debug('Cannot update the remote video.', { err })
514 async function refreshVideoIfNeeded (options: {
515 video: MVideoThumbnail
516 fetchedType: VideoFetchByUrlType
518 }): Promise<MVideoThumbnail> {
519 if (!options.video.isOutdated()) return options.video
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)
527 const { videoObject } = await fetchRemoteVideo(video.url)
529 if (videoObject === undefined) {
530 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
532 await video.setAsRefreshed()
536 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
538 const updateOptions = {
541 account: channelActor.VideoChannel.Account,
542 channel: channelActor.VideoChannel
544 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
545 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
547 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
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)
554 // Video does not exist anymore
555 await video.destroy()
559 logger.warn('Cannot refresh video %s.', options.video.url, { err })
561 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
563 // Don't refresh in loop
564 await video.setAsRefreshed()
571 refreshVideoIfNeeded,
572 federateVideoIfNeeded,
574 getOrCreateVideoAndAccountAndChannel,
575 fetchRemoteVideoDescription,
576 getOrCreateVideoChannelFromVideoObject
579 // ---------------------------------------------------------------------------
581 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
582 const urlMediaType = url.mediaType
584 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
587 function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
588 return url && url.mediaType === 'application/x-mpegURL'
591 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
592 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
595 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
596 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
599 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
600 return url && url.type === 'Hashtag'
603 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
604 logger.debug('Adding remote video %s.', videoObject.id)
606 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
607 const video = VideoModel.build(videoData) as MVideoThumbnail
609 const promiseThumbnail = createVideoMiniatureFromUrl({
610 downloadUrl: getThumbnailFromIcons(videoObject).url,
612 type: ThumbnailType.MINIATURE
614 logger.error('Cannot create miniature from url.', { err })
618 let thumbnailModel: MThumbnail
619 if (waitThumbnail === true) {
620 thumbnailModel = await promiseThumbnail
623 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
625 const sequelizeOptions = { transaction: t }
627 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
628 videoCreated.VideoChannel = channel
630 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
632 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
633 const previewModel = createPlaceholderThumbnail({
636 type: ThumbnailType.PREVIEW,
640 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
643 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
645 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
646 const videoFiles = await Promise.all(videoFilePromises)
648 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
649 videoCreated.VideoStreamingPlaylists = []
651 for (const playlistAttributes of streamingPlaylistsAttributes) {
652 const playlist = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t }) as MStreamingPlaylistFilesVideo
653 playlist.Video = videoCreated
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)
659 videoCreated.VideoStreamingPlaylists.push(playlist)
663 const tags = videoObject.tag
664 .filter(isAPHashTagObject)
666 await setVideoTags({ video: videoCreated, tags, transaction: t })
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,
677 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
679 await Promise.all(videoCaptionsPromises)
683 const trackers = getTrackerUrls(videoObject, videoCreated)
684 await setVideoTrackers({ video: videoCreated, trackers, transaction: t })
687 videoCreated.VideoFiles = videoFiles
689 if (videoCreated.isLive) {
690 const videoLive = new VideoLiveModel({
692 saveReplay: videoObject.liveSaveReplay,
693 permanentLive: videoObject.permanentLive,
694 videoId: videoCreated.id
697 videoCreated.VideoLive = await videoLive.save({ transaction: t })
700 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
708 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
710 return { autoBlacklisted, videoCreated }
712 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
714 if (thumbnailModel) await thumbnailModel.removeThumbnail()
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
726 thumbnailModel = videoCreated.id
728 return thumbnailModel.save()
732 return { autoBlacklisted, videoCreated }
735 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
736 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
737 ? VideoPrivacy.PUBLIC
738 : VideoPrivacy.UNLISTED
740 const duration = videoObject.duration.replace(/[^\d]+/, '')
741 const language = videoObject.language?.identifier
743 const category = videoObject.category
744 ? parseInt(videoObject.category.identifier, 10)
747 const licence = videoObject.licence
748 ? parseInt(videoObject.licence.identifier, 10)
751 const description = videoObject.content || null
752 const support = videoObject.support || null
755 name: videoObject.name,
756 uuid: videoObject.uuid,
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),
774 originallyPublishedAt: videoObject.originallyPublishedAt
775 ? new Date(videoObject.originallyPublishedAt)
778 updatedAt: new Date(videoObject.updated),
779 views: videoObject.views,
787 function videoFileActivityUrlToDBAttributes (
788 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
789 urls: (ActivityTagObject | ActivityUrlObject)[]
791 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
793 if (fileUrls.length === 0) return []
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)
801 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
803 const parsed = magnetUtil.decode(magnet.href)
804 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
805 throw new Error('Cannot parse magnet URI ' + magnet.href)
808 const torrentUrl = Array.isArray(parsed.xs)
812 // Fetch associated metadata url, if any
813 const metadata = urls.filter(isAPVideoFileUrlMetadataObject)
815 return u.height === fileUrl.height &&
816 u.fps === fileUrl.fps &&
817 u.rel.includes(fileUrl.mediaType)
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
827 infoHash: parsed.infoHash,
830 fps: fileUrl.fps || -1,
831 metadataUrl: metadata?.href,
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,
838 // Use our own torrent name since we proxify torrent requests
839 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
841 // This is a video file owned by a video or by a streaming playlist
843 videoStreamingPlaylistId
846 attributes.push(attribute)
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 []
856 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
857 for (const playlistUrlObject of playlistUrls) {
858 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
860 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
862 // FIXME: backward compatibility introduced in v2.1.0
863 if (files.length === 0) files = videoFiles
865 if (!segmentsSha256UrlObject) {
866 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
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,
877 tagAPObject: playlistUrlObject.tag
880 attributes.push(attribute)
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
891 return minBy(validIcons, 'width')
894 function getPreviewFromIcons (videoObject: VideoObject) {
895 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
897 return maxBy(validIcons, 'width')
900 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
903 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, ActorImageModel.generateFilename()))
906 function getTrackerUrls (object: VideoObject, video: MVideoWithHost) {
909 const trackers = object.url.filter(u => isAPVideoTrackerUrlObject(u))
910 .map((u: ActivityTrackerUrlObject) => {
911 if (isArray(u.rel) && u.rel.includes('websocket')) wsFound = true
916 if (wsFound) return trackers
919 buildRemoteVideoBaseUrl(video, '/tracker/socket', REMOTE_SCHEME.WS),
920 buildRemoteVideoBaseUrl(video, '/tracker/announce')
924 async function setVideoTrackers (options: {
927 transaction?: Transaction
929 const { video, trackers, transaction } = options
931 const trackerInstances = await TrackerModel.findOrCreateTrackers(trackers, transaction)
933 await video.$set('Trackers', trackerInstances, { transaction })