1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import { basename, join } from 'path'
5 import { Transaction } from 'sequelize/types'
6 import { TrackerModel } from '@server/models/server/tracker'
7 import { VideoLiveModel } from '@server/models/video/video-live'
8 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
10 ActivityHashTagObject,
11 ActivityMagnetUrlObject,
12 ActivityPlaylistSegmentHashesObject,
13 ActivityPlaylistUrlObject,
14 ActivitypubHttpFetcherPayload,
17 ActivityVideoUrlObject
18 } from '../../../shared/index'
19 import { ActivityIconObject, ActivityTrackerUrlObject, VideoObject } from '../../../shared/models/activitypub/objects'
20 import { VideoPrivacy } from '../../../shared/models/videos'
21 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
22 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
23 import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
25 isAPVideoFileUrlMetadataObject,
26 isAPVideoTrackerUrlObject,
27 sanitizeAndCheckVideoTorrentObject
28 } from '../../helpers/custom-validators/activitypub/videos'
29 import { isArray } from '../../helpers/custom-validators/misc'
30 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
31 import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
32 import { logger } from '../../helpers/logger'
33 import { doJSONRequest } from '../../helpers/requests'
34 import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
39 P2P_MEDIA_LOADER_PEER_VERSION,
43 } from '../../initializers/constants'
44 import { sequelizeTypescript } from '../../initializers/database'
45 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
46 import { VideoModel } from '../../models/video/video'
47 import { VideoCaptionModel } from '../../models/video/video-caption'
48 import { VideoCommentModel } from '../../models/video/video-comment'
49 import { VideoFileModel } from '../../models/video/video-file'
50 import { VideoShareModel } from '../../models/video/video-share'
51 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
58 MStreamingPlaylistFilesVideo,
59 MStreamingPlaylistVideo,
62 MVideoAccountLightBlacklistAllFiles,
64 MVideoAPWithoutCaption,
72 } from '../../types/models'
73 import { MThumbnail } from '../../types/models/video/thumbnail'
74 import { FilteredModelAttributes } from '../../types/sequelize'
75 import { ActorFollowScoreCache } from '../files-cache'
76 import { JobQueue } from '../job-queue'
77 import { Notifier } from '../notifier'
78 import { PeerTubeSocket } from '../peertube-socket'
79 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
80 import { setVideoTags } from '../video'
81 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
82 import { generateTorrentFileName } from '../video-paths'
83 import { getOrCreateActorAndServerAndModel } from './actor'
84 import { crawlCollectionPage } from './crawl'
85 import { sendCreateVideo, sendUpdateVideo } from './send'
86 import { addVideoShares, shareVideoByServerAndChannel } from './share'
87 import { addVideoComments } from './video-comments'
88 import { createRates } from './video-rates'
90 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: Transaction) {
91 const video = videoArg as MVideoAP
94 // Check this is not a blacklisted video, or unfederated blacklisted video
95 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
96 // Check the video is public/unlisted and published
97 video.hasPrivacyForFederation() && video.hasStateForFederation()
99 // Fetch more attributes that we will need to serialize in AP object
100 if (isArray(video.VideoCaptions) === false) {
101 video.VideoCaptions = await video.$get('VideoCaptions', {
102 attributes: [ 'filename', 'language' ],
108 // Now we'll add the video's meta data to our followers
109 await sendCreateVideo(video, transaction)
110 await shareVideoByServerAndChannel(video, transaction)
112 await sendUpdateVideo(video, transaction)
117 async function fetchRemoteVideo (videoUrl: string): Promise<{ statusCode: number, videoObject: VideoObject }> {
118 logger.info('Fetching remote video %s.', videoUrl)
120 const { statusCode, body } = await doJSONRequest<any>(videoUrl, { activityPub: true })
122 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
123 logger.debug('Remote video JSON is not valid.', { body })
124 return { statusCode, videoObject: undefined }
127 return { statusCode, videoObject: body }
130 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
131 const host = video.VideoChannel.Account.Actor.Server.host
132 const path = video.getDescriptionAPIPath()
133 const url = REMOTE_SCHEME.HTTP + '://' + host + path
135 const { body } = await doJSONRequest<any>(url)
136 return body.description || ''
139 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
140 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
141 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
143 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
144 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
147 return getOrCreateActorAndServerAndModel(channel.id, 'all')
156 refreshVideo?: boolean
158 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
159 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
161 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
163 if (syncParam.likes === true) {
164 const handler = items => createRates(items, video, 'like')
165 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
167 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
168 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
170 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
173 if (syncParam.dislikes === true) {
174 const handler = items => createRates(items, video, 'dislike')
175 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
177 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
178 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
180 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
183 if (syncParam.shares === true) {
184 const handler = items => addVideoShares(items, video)
185 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
187 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
188 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
190 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
193 if (syncParam.comments === true) {
194 const handler = items => addVideoComments(items)
195 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
197 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
198 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
200 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
203 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
206 type GetVideoResult <T> = Promise<{
209 autoBlacklisted?: boolean
212 type GetVideoParamAll = {
213 videoObject: { id: string } | string
214 syncParam?: SyncParam
216 allowRefresh?: boolean
219 type GetVideoParamImmutable = {
220 videoObject: { id: string } | string
221 syncParam?: SyncParam
222 fetchType: 'only-immutable-attributes'
226 type GetVideoParamOther = {
227 videoObject: { id: string } | string
228 syncParam?: SyncParam
229 fetchType?: 'all' | 'only-video'
230 allowRefresh?: boolean
233 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
234 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
235 function getOrCreateVideoAndAccountAndChannel (
236 options: GetVideoParamOther
237 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
238 async function getOrCreateVideoAndAccountAndChannel (
239 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
240 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
242 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
243 const fetchType = options.fetchType || 'all'
244 const allowRefresh = options.allowRefresh !== false
247 const videoUrl = getAPId(options.videoObject)
248 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
250 if (videoFromDatabase) {
251 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
252 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
253 const refreshOptions = {
254 video: videoFromDatabase as MVideoThumbnail,
255 fetchedType: fetchType,
259 if (syncParam.refreshVideo === true) {
260 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
262 await JobQueue.Instance.createJobWithPromise({
263 type: 'activitypub-refresher',
264 payload: { type: 'video', url: videoFromDatabase.url }
269 return { video: videoFromDatabase, created: false }
272 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
273 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
275 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
276 const videoChannel = actor.VideoChannel
279 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
281 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
283 return { video: videoCreated, created: true, autoBlacklisted }
285 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
286 if (err.name === 'SequelizeUniqueConstraintError') {
287 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
288 if (fallbackVideo) return { video: fallbackVideo, created: false }
295 async function updateVideoFromAP (options: {
296 video: MVideoAccountLightBlacklistAllFiles
297 videoObject: VideoObject
298 account: MAccountIdActor
299 channel: MChannelDefault
300 overrideTo?: string[]
302 const { video, videoObject, account, channel, overrideTo } = options
304 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
306 let videoFieldsSave: any
307 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
308 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
311 let thumbnailModel: MThumbnail
314 thumbnailModel = await createVideoMiniatureFromUrl({
315 downloadUrl: getThumbnailFromIcons(videoObject).url,
317 type: ThumbnailType.MINIATURE
320 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
323 const videoUpdated = await sequelizeTypescript.transaction(async t => {
324 const sequelizeOptions = { transaction: t }
326 videoFieldsSave = video.toJSON()
328 // Check we can update the channel: we trust the remote server
329 const oldVideoChannel = video.VideoChannel
331 if (!oldVideoChannel.Actor.serverId || !channel.Actor.serverId) {
332 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
335 if (oldVideoChannel.Actor.serverId !== channel.Actor.serverId) {
336 throw new Error('New channel ' + channel.Actor.url + ' is not on the same server than new channel ' + oldVideoChannel.Actor.url)
339 const to = overrideTo || videoObject.to
340 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
341 video.name = videoData.name
342 video.uuid = videoData.uuid
343 video.url = videoData.url
344 video.category = videoData.category
345 video.licence = videoData.licence
346 video.language = videoData.language
347 video.description = videoData.description
348 video.support = videoData.support
349 video.nsfw = videoData.nsfw
350 video.commentsEnabled = videoData.commentsEnabled
351 video.downloadEnabled = videoData.downloadEnabled
352 video.waitTranscoding = videoData.waitTranscoding
353 video.state = videoData.state
354 video.duration = videoData.duration
355 video.createdAt = videoData.createdAt
356 video.publishedAt = videoData.publishedAt
357 video.originallyPublishedAt = videoData.originallyPublishedAt
358 video.privacy = videoData.privacy
359 video.channelId = videoData.channelId
360 video.views = videoData.views
361 video.isLive = videoData.isLive
363 // Ensures we update the updated video attribute
364 video.changed('updatedAt', true)
366 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
368 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
370 if (videoUpdated.getPreview()) {
371 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
372 const previewModel = createPlaceholderThumbnail({
375 type: ThumbnailType.PREVIEW,
378 await videoUpdated.addAndSaveThumbnail(previewModel, t)
382 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
383 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
385 // Remove video files that do not exist anymore
386 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
387 await Promise.all(destroyTasks)
389 // Update or add other one
390 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
391 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
395 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
396 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
398 // Remove video playlists that do not exist anymore
399 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
400 await Promise.all(destroyTasks)
402 let oldStreamingPlaylistFiles: MVideoFile[] = []
403 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
404 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
407 videoUpdated.VideoStreamingPlaylists = []
409 for (const playlistAttributes of streamingPlaylistAttributes) {
410 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
411 .then(([ streamingPlaylist ]) => streamingPlaylist as MStreamingPlaylistFilesVideo)
412 streamingPlaylistModel.Video = videoUpdated
414 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
415 .map(a => new VideoFileModel(a))
416 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
417 await Promise.all(destroyTasks)
419 // Update or add other one
420 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
421 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
423 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
429 const tags = videoObject.tag
430 .filter(isAPHashTagObject)
431 .map(tag => tag.name)
432 await setVideoTags({ video: videoUpdated, tags, transaction: t })
437 const trackers = getTrackerUrls(videoObject, videoUpdated)
438 await setVideoTrackers({ video: videoUpdated, trackers, transaction: t })
443 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
445 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
446 const caption = new VideoCaptionModel({
447 videoId: videoUpdated.id,
448 filename: VideoCaptionModel.generateCaptionName(c.identifier),
449 language: c.identifier,
453 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
455 await Promise.all(videoCaptionsPromises)
459 // Create or update existing live
461 const [ videoLive ] = await VideoLiveModel.upsert({
462 saveReplay: videoObject.liveSaveReplay,
463 permanentLive: videoObject.permanentLive,
465 }, { transaction: t, returning: true })
467 videoUpdated.VideoLive = videoLive
468 } else { // Delete existing live if it exists
469 await VideoLiveModel.destroy({
476 videoUpdated.VideoLive = null
483 await autoBlacklistVideoIfNeeded({
488 transaction: undefined
492 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
494 if (videoUpdated.isLive) {
495 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
496 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
499 logger.info('Remote video with uuid %s updated', videoObject.uuid)
503 if (video !== undefined && videoFieldsSave !== undefined) {
504 resetSequelizeInstance(video, videoFieldsSave)
507 // This is just a debug because we will retry the insert
508 logger.debug('Cannot update the remote video.', { err })
513 async function refreshVideoIfNeeded (options: {
514 video: MVideoThumbnail
515 fetchedType: VideoFetchByUrlType
517 }): Promise<MVideoThumbnail> {
518 if (!options.video.isOutdated()) return options.video
520 // We need more attributes if the argument video was fetched with not enough joints
521 const video = options.fetchedType === 'all'
522 ? options.video as MVideoAccountLightBlacklistAllFiles
523 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
526 const { statusCode, videoObject } = await fetchRemoteVideo(video.url)
527 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
528 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
530 // Video does not exist anymore
531 await video.destroy()
535 if (videoObject === undefined) {
536 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
538 await video.setAsRefreshed()
542 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
544 const updateOptions = {
547 account: channelActor.VideoChannel.Account,
548 channel: channelActor.VideoChannel
550 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
551 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
553 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
557 logger.warn('Cannot refresh video %s.', options.video.url, { err })
559 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
561 // Don't refresh in loop
562 await video.setAsRefreshed()
569 refreshVideoIfNeeded,
570 federateVideoIfNeeded,
572 getOrCreateVideoAndAccountAndChannel,
573 fetchRemoteVideoDescription,
574 getOrCreateVideoChannelFromVideoObject
577 // ---------------------------------------------------------------------------
579 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
580 const urlMediaType = url.mediaType
582 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
585 function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
586 return url && url.mediaType === 'application/x-mpegURL'
589 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
590 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
593 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
594 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
597 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
598 return url && url.type === 'Hashtag'
601 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
602 logger.debug('Adding remote video %s.', videoObject.id)
604 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
605 const video = VideoModel.build(videoData) as MVideoThumbnail
607 const promiseThumbnail = createVideoMiniatureFromUrl({
608 downloadUrl: getThumbnailFromIcons(videoObject).url,
610 type: ThumbnailType.MINIATURE
612 logger.error('Cannot create miniature from url.', { err })
616 let thumbnailModel: MThumbnail
617 if (waitThumbnail === true) {
618 thumbnailModel = await promiseThumbnail
621 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
623 const sequelizeOptions = { transaction: t }
625 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
626 videoCreated.VideoChannel = channel
628 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
630 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
631 const previewModel = createPlaceholderThumbnail({
634 type: ThumbnailType.PREVIEW,
638 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
641 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
643 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
644 const videoFiles = await Promise.all(videoFilePromises)
646 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
647 videoCreated.VideoStreamingPlaylists = []
649 for (const playlistAttributes of streamingPlaylistsAttributes) {
650 const playlist = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t }) as MStreamingPlaylistFilesVideo
651 playlist.Video = videoCreated
653 const playlistFiles = videoFileActivityUrlToDBAttributes(playlist, playlistAttributes.tagAPObject)
654 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
655 playlist.VideoFiles = await Promise.all(videoFilePromises)
657 videoCreated.VideoStreamingPlaylists.push(playlist)
661 const tags = videoObject.tag
662 .filter(isAPHashTagObject)
664 await setVideoTags({ video: videoCreated, tags, transaction: t })
667 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
668 const caption = new VideoCaptionModel({
669 videoId: videoCreated.id,
670 filename: VideoCaptionModel.generateCaptionName(c.identifier),
671 language: c.identifier,
675 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
677 await Promise.all(videoCaptionsPromises)
681 const trackers = getTrackerUrls(videoObject, videoCreated)
682 await setVideoTrackers({ video: videoCreated, trackers, transaction: t })
685 videoCreated.VideoFiles = videoFiles
687 if (videoCreated.isLive) {
688 const videoLive = new VideoLiveModel({
690 saveReplay: videoObject.liveSaveReplay,
691 permanentLive: videoObject.permanentLive,
692 videoId: videoCreated.id
695 videoCreated.VideoLive = await videoLive.save({ transaction: t })
698 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
706 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
708 return { autoBlacklisted, videoCreated }
710 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
712 if (thumbnailModel) await thumbnailModel.removeThumbnail()
718 if (waitThumbnail === false) {
719 // Error is already caught above
720 // eslint-disable-next-line @typescript-eslint/no-floating-promises
721 promiseThumbnail.then(thumbnailModel => {
722 if (!thumbnailModel) return
724 thumbnailModel = videoCreated.id
726 return thumbnailModel.save()
730 return { autoBlacklisted, videoCreated }
733 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
734 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
735 ? VideoPrivacy.PUBLIC
736 : VideoPrivacy.UNLISTED
738 const duration = videoObject.duration.replace(/[^\d]+/, '')
739 const language = videoObject.language?.identifier
741 const category = videoObject.category
742 ? parseInt(videoObject.category.identifier, 10)
745 const licence = videoObject.licence
746 ? parseInt(videoObject.licence.identifier, 10)
749 const description = videoObject.content || null
750 const support = videoObject.support || null
753 name: videoObject.name,
754 uuid: videoObject.uuid,
761 nsfw: videoObject.sensitive,
762 commentsEnabled: videoObject.commentsEnabled,
763 downloadEnabled: videoObject.downloadEnabled,
764 waitTranscoding: videoObject.waitTranscoding,
765 isLive: videoObject.isLiveBroadcast,
766 state: videoObject.state,
767 channelId: videoChannel.id,
768 duration: parseInt(duration, 10),
769 createdAt: new Date(videoObject.published),
770 publishedAt: new Date(videoObject.published),
772 originallyPublishedAt: videoObject.originallyPublishedAt
773 ? new Date(videoObject.originallyPublishedAt)
776 updatedAt: new Date(videoObject.updated),
777 views: videoObject.views,
785 function videoFileActivityUrlToDBAttributes (
786 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
787 urls: (ActivityTagObject | ActivityUrlObject)[]
789 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
791 if (fileUrls.length === 0) return []
793 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
794 for (const fileUrl of fileUrls) {
795 // Fetch associated magnet uri
796 const magnet = urls.filter(isAPMagnetUrlObject)
797 .find(u => u.height === fileUrl.height)
799 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
801 const parsed = magnetUtil.decode(magnet.href)
802 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
803 throw new Error('Cannot parse magnet URI ' + magnet.href)
806 const torrentUrl = Array.isArray(parsed.xs)
810 // Fetch associated metadata url, if any
811 const metadata = urls.filter(isAPVideoFileUrlMetadataObject)
813 return u.height === fileUrl.height &&
814 u.fps === fileUrl.fps &&
815 u.rel.includes(fileUrl.mediaType)
818 const extname = getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, fileUrl.mediaType)
819 const resolution = fileUrl.height
820 const videoId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id
821 const videoStreamingPlaylistId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
825 infoHash: parsed.infoHash,
828 fps: fileUrl.fps || -1,
829 metadataUrl: metadata?.href,
831 // Use the name of the remote file because we don't proxify video file requests
832 filename: basename(fileUrl.href),
833 fileUrl: fileUrl.href,
836 // Use our own torrent name since we proxify torrent requests
837 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
839 // This is a video file owned by a video or by a streaming playlist
841 videoStreamingPlaylistId
844 attributes.push(attribute)
850 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
851 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
852 if (playlistUrls.length === 0) return []
854 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
855 for (const playlistUrlObject of playlistUrls) {
856 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
858 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
860 // FIXME: backward compatibility introduced in v2.1.0
861 if (files.length === 0) files = videoFiles
863 if (!segmentsSha256UrlObject) {
864 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
869 type: VideoStreamingPlaylistType.HLS,
870 playlistUrl: playlistUrlObject.href,
871 segmentsSha256Url: segmentsSha256UrlObject.href,
872 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
873 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
875 tagAPObject: playlistUrlObject.tag
878 attributes.push(attribute)
884 function getThumbnailFromIcons (videoObject: VideoObject) {
885 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
886 // Fallback if there are not valid icons
887 if (validIcons.length === 0) validIcons = videoObject.icon
889 return minBy(validIcons, 'width')
892 function getPreviewFromIcons (videoObject: VideoObject) {
893 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
895 return maxBy(validIcons, 'width')
898 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
901 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
904 function getTrackerUrls (object: VideoObject, video: MVideoWithHost) {
907 const trackers = object.url.filter(u => isAPVideoTrackerUrlObject(u))
908 .map((u: ActivityTrackerUrlObject) => {
909 if (isArray(u.rel) && u.rel.includes('websocket')) wsFound = true
914 if (wsFound) return trackers
917 buildRemoteVideoBaseUrl(video, '/tracker/socket', REMOTE_SCHEME.WS),
918 buildRemoteVideoBaseUrl(video, '/tracker/announce')
922 async function setVideoTrackers (options: {
925 transaction?: Transaction
927 const { video, trackers, transaction } = options
929 const trackerInstances = await TrackerModel.findOrCreateTrackers(trackers, transaction)
931 await video.$set('Trackers', trackerInstances, { transaction })