1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import { basename, join } from 'path'
5 import * as request from 'request'
6 import { Transaction } from 'sequelize/types'
7 import { TrackerModel } from '@server/models/server/tracker'
8 import { VideoLiveModel } from '@server/models/video/video-live'
9 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
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 { doRequest } 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<{ response: request.RequestResponse, videoObject: VideoObject }> {
126 logger.info('Fetching remote video %s.', videoUrl)
128 const { response, body } = await doRequest<any>(options)
130 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
131 logger.debug('Remote video JSON is not valid.', { body })
132 return { response, videoObject: undefined }
135 return { response, videoObject: body }
138 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
139 const host = video.VideoChannel.Account.Actor.Server.host
140 const path = video.getDescriptionAPIPath()
142 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
146 const { body } = await doRequest<any>(options)
147 return body.description ? body.description : ''
150 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
151 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
152 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
154 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
155 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
158 return getOrCreateActorAndServerAndModel(channel.id, 'all')
167 refreshVideo?: boolean
169 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
170 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
172 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
174 if (syncParam.likes === true) {
175 const handler = items => createRates(items, video, 'like')
176 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
178 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
179 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
181 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
184 if (syncParam.dislikes === true) {
185 const handler = items => createRates(items, video, 'dislike')
186 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
188 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
189 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
191 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
194 if (syncParam.shares === true) {
195 const handler = items => addVideoShares(items, video)
196 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
198 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
199 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
201 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
204 if (syncParam.comments === true) {
205 const handler = items => addVideoComments(items)
206 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
208 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
209 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
211 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
214 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
217 type GetVideoResult <T> = Promise<{
220 autoBlacklisted?: boolean
223 type GetVideoParamAll = {
224 videoObject: { id: string } | string
225 syncParam?: SyncParam
227 allowRefresh?: boolean
230 type GetVideoParamImmutable = {
231 videoObject: { id: string } | string
232 syncParam?: SyncParam
233 fetchType: 'only-immutable-attributes'
237 type GetVideoParamOther = {
238 videoObject: { id: string } | string
239 syncParam?: SyncParam
240 fetchType?: 'all' | 'only-video'
241 allowRefresh?: boolean
244 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
245 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
246 function getOrCreateVideoAndAccountAndChannel (
247 options: GetVideoParamOther
248 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
249 async function getOrCreateVideoAndAccountAndChannel (
250 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
251 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
253 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
254 const fetchType = options.fetchType || 'all'
255 const allowRefresh = options.allowRefresh !== false
258 const videoUrl = getAPId(options.videoObject)
259 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
261 if (videoFromDatabase) {
262 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
263 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
264 const refreshOptions = {
265 video: videoFromDatabase as MVideoThumbnail,
266 fetchedType: fetchType,
270 if (syncParam.refreshVideo === true) {
271 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
273 await JobQueue.Instance.createJobWithPromise({
274 type: 'activitypub-refresher',
275 payload: { type: 'video', url: videoFromDatabase.url }
280 return { video: videoFromDatabase, created: false }
283 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
284 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
286 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
287 const videoChannel = actor.VideoChannel
290 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
292 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
294 return { video: videoCreated, created: true, autoBlacklisted }
296 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
297 if (err.name === 'SequelizeUniqueConstraintError') {
298 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
299 if (fallbackVideo) return { video: fallbackVideo, created: false }
306 async function updateVideoFromAP (options: {
307 video: MVideoAccountLightBlacklistAllFiles
308 videoObject: VideoObject
309 account: MAccountIdActor
310 channel: MChannelDefault
311 overrideTo?: string[]
313 const { video, videoObject, account, channel, overrideTo } = options
315 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
317 let videoFieldsSave: any
318 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
319 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
322 let thumbnailModel: MThumbnail
325 thumbnailModel = await createVideoMiniatureFromUrl({
326 downloadUrl: getThumbnailFromIcons(videoObject).url,
328 type: ThumbnailType.MINIATURE
331 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
334 const videoUpdated = await sequelizeTypescript.transaction(async t => {
335 const sequelizeOptions = { transaction: t }
337 videoFieldsSave = video.toJSON()
339 // Check we can update the channel: we trust the remote server
340 const oldVideoChannel = video.VideoChannel
342 if (!oldVideoChannel.Actor.serverId || !channel.Actor.serverId) {
343 throw new Error('Cannot check old channel/new channel validity because `serverId` is null')
346 if (oldVideoChannel.Actor.serverId !== channel.Actor.serverId) {
347 throw new Error('New channel ' + channel.Actor.url + ' is not on the same server than new channel ' + oldVideoChannel.Actor.url)
350 const to = overrideTo || videoObject.to
351 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
352 video.name = videoData.name
353 video.uuid = videoData.uuid
354 video.url = videoData.url
355 video.category = videoData.category
356 video.licence = videoData.licence
357 video.language = videoData.language
358 video.description = videoData.description
359 video.support = videoData.support
360 video.nsfw = videoData.nsfw
361 video.commentsEnabled = videoData.commentsEnabled
362 video.downloadEnabled = videoData.downloadEnabled
363 video.waitTranscoding = videoData.waitTranscoding
364 video.state = videoData.state
365 video.duration = videoData.duration
366 video.createdAt = videoData.createdAt
367 video.publishedAt = videoData.publishedAt
368 video.originallyPublishedAt = videoData.originallyPublishedAt
369 video.privacy = videoData.privacy
370 video.channelId = videoData.channelId
371 video.views = videoData.views
372 video.isLive = videoData.isLive
374 // Ensures we update the updated video attribute
375 video.changed('updatedAt', true)
377 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
379 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
381 if (videoUpdated.getPreview()) {
382 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
383 const previewModel = createPlaceholderThumbnail({
386 type: ThumbnailType.PREVIEW,
389 await videoUpdated.addAndSaveThumbnail(previewModel, t)
393 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
394 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
396 // Remove video files that do not exist anymore
397 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
398 await Promise.all(destroyTasks)
400 // Update or add other one
401 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
402 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
406 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
407 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
409 // Remove video playlists that do not exist anymore
410 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
411 await Promise.all(destroyTasks)
413 let oldStreamingPlaylistFiles: MVideoFile[] = []
414 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
415 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
418 videoUpdated.VideoStreamingPlaylists = []
420 for (const playlistAttributes of streamingPlaylistAttributes) {
421 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
422 .then(([ streamingPlaylist ]) => streamingPlaylist as MStreamingPlaylistFilesVideo)
423 streamingPlaylistModel.Video = videoUpdated
425 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
426 .map(a => new VideoFileModel(a))
427 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
428 await Promise.all(destroyTasks)
430 // Update or add other one
431 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
432 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
434 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
440 const tags = videoObject.tag
441 .filter(isAPHashTagObject)
442 .map(tag => tag.name)
443 await setVideoTags({ video: videoUpdated, tags, transaction: t })
448 const trackers = getTrackerUrls(videoObject, videoUpdated)
449 await setVideoTrackers({ video: videoUpdated, trackers, transaction: t })
454 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
456 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
457 const caption = new VideoCaptionModel({
458 videoId: videoUpdated.id,
459 filename: VideoCaptionModel.generateCaptionName(c.identifier),
460 language: c.identifier,
464 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
466 await Promise.all(videoCaptionsPromises)
470 // Create or update existing live
472 const [ videoLive ] = await VideoLiveModel.upsert({
473 saveReplay: videoObject.liveSaveReplay,
474 permanentLive: videoObject.permanentLive,
476 }, { transaction: t, returning: true })
478 videoUpdated.VideoLive = videoLive
479 } else { // Delete existing live if it exists
480 await VideoLiveModel.destroy({
487 videoUpdated.VideoLive = null
494 await autoBlacklistVideoIfNeeded({
499 transaction: undefined
503 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
505 if (videoUpdated.isLive) {
506 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
507 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
510 logger.info('Remote video with uuid %s updated', videoObject.uuid)
514 if (video !== undefined && videoFieldsSave !== undefined) {
515 resetSequelizeInstance(video, videoFieldsSave)
518 // This is just a debug because we will retry the insert
519 logger.debug('Cannot update the remote video.', { err })
524 async function refreshVideoIfNeeded (options: {
525 video: MVideoThumbnail
526 fetchedType: VideoFetchByUrlType
528 }): Promise<MVideoThumbnail> {
529 if (!options.video.isOutdated()) return options.video
531 // We need more attributes if the argument video was fetched with not enough joints
532 const video = options.fetchedType === 'all'
533 ? options.video as MVideoAccountLightBlacklistAllFiles
534 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
537 const { response, videoObject } = await fetchRemoteVideo(video.url)
538 if (response.statusCode === HttpStatusCode.NOT_FOUND_404) {
539 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
541 // Video does not exist anymore
542 await video.destroy()
546 if (videoObject === undefined) {
547 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
549 await video.setAsRefreshed()
553 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
555 const updateOptions = {
558 account: channelActor.VideoChannel.Account,
559 channel: channelActor.VideoChannel
561 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
562 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
564 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
568 logger.warn('Cannot refresh video %s.', options.video.url, { err })
570 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
572 // Don't refresh in loop
573 await video.setAsRefreshed()
580 refreshVideoIfNeeded,
581 federateVideoIfNeeded,
583 getOrCreateVideoAndAccountAndChannel,
584 fetchRemoteVideoDescription,
585 getOrCreateVideoChannelFromVideoObject
588 // ---------------------------------------------------------------------------
590 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
591 const urlMediaType = url.mediaType
593 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
596 function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
597 return url && url.mediaType === 'application/x-mpegURL'
600 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
601 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
604 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
605 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
608 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
609 return url && url.type === 'Hashtag'
612 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
613 logger.debug('Adding remote video %s.', videoObject.id)
615 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
616 const video = VideoModel.build(videoData) as MVideoThumbnail
618 const promiseThumbnail = createVideoMiniatureFromUrl({
619 downloadUrl: getThumbnailFromIcons(videoObject).url,
621 type: ThumbnailType.MINIATURE
623 logger.error('Cannot create miniature from url.', { err })
627 let thumbnailModel: MThumbnail
628 if (waitThumbnail === true) {
629 thumbnailModel = await promiseThumbnail
632 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
634 const sequelizeOptions = { transaction: t }
636 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
637 videoCreated.VideoChannel = channel
639 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
641 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
642 const previewModel = createPlaceholderThumbnail({
645 type: ThumbnailType.PREVIEW,
649 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
652 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
654 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
655 const videoFiles = await Promise.all(videoFilePromises)
657 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
658 videoCreated.VideoStreamingPlaylists = []
660 for (const playlistAttributes of streamingPlaylistsAttributes) {
661 const playlist = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t }) as MStreamingPlaylistFilesVideo
662 playlist.Video = videoCreated
664 const playlistFiles = videoFileActivityUrlToDBAttributes(playlist, playlistAttributes.tagAPObject)
665 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
666 playlist.VideoFiles = await Promise.all(videoFilePromises)
668 videoCreated.VideoStreamingPlaylists.push(playlist)
672 const tags = videoObject.tag
673 .filter(isAPHashTagObject)
675 await setVideoTags({ video: videoCreated, tags, transaction: t })
678 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
679 const caption = new VideoCaptionModel({
680 videoId: videoCreated.id,
681 filename: VideoCaptionModel.generateCaptionName(c.identifier),
682 language: c.identifier,
686 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
688 await Promise.all(videoCaptionsPromises)
692 const trackers = getTrackerUrls(videoObject, videoCreated)
693 await setVideoTrackers({ video: videoCreated, trackers, transaction: t })
696 videoCreated.VideoFiles = videoFiles
698 if (videoCreated.isLive) {
699 const videoLive = new VideoLiveModel({
701 saveReplay: videoObject.liveSaveReplay,
702 permanentLive: videoObject.permanentLive,
703 videoId: videoCreated.id
706 videoCreated.VideoLive = await videoLive.save({ transaction: t })
709 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
717 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
719 return { autoBlacklisted, videoCreated }
721 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
723 if (thumbnailModel) await thumbnailModel.removeThumbnail()
729 if (waitThumbnail === false) {
730 // Error is already caught above
731 // eslint-disable-next-line @typescript-eslint/no-floating-promises
732 promiseThumbnail.then(thumbnailModel => {
733 if (!thumbnailModel) return
735 thumbnailModel = videoCreated.id
737 return thumbnailModel.save()
741 return { autoBlacklisted, videoCreated }
744 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
745 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
746 ? VideoPrivacy.PUBLIC
747 : VideoPrivacy.UNLISTED
749 const duration = videoObject.duration.replace(/[^\d]+/, '')
750 const language = videoObject.language?.identifier
752 const category = videoObject.category
753 ? parseInt(videoObject.category.identifier, 10)
756 const licence = videoObject.licence
757 ? parseInt(videoObject.licence.identifier, 10)
760 const description = videoObject.content || null
761 const support = videoObject.support || null
764 name: videoObject.name,
765 uuid: videoObject.uuid,
772 nsfw: videoObject.sensitive,
773 commentsEnabled: videoObject.commentsEnabled,
774 downloadEnabled: videoObject.downloadEnabled,
775 waitTranscoding: videoObject.waitTranscoding,
776 isLive: videoObject.isLiveBroadcast,
777 state: videoObject.state,
778 channelId: videoChannel.id,
779 duration: parseInt(duration, 10),
780 createdAt: new Date(videoObject.published),
781 publishedAt: new Date(videoObject.published),
783 originallyPublishedAt: videoObject.originallyPublishedAt
784 ? new Date(videoObject.originallyPublishedAt)
787 updatedAt: new Date(videoObject.updated),
788 views: videoObject.views,
796 function videoFileActivityUrlToDBAttributes (
797 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
798 urls: (ActivityTagObject | ActivityUrlObject)[]
800 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
802 if (fileUrls.length === 0) return []
804 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
805 for (const fileUrl of fileUrls) {
806 // Fetch associated magnet uri
807 const magnet = urls.filter(isAPMagnetUrlObject)
808 .find(u => u.height === fileUrl.height)
810 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
812 const parsed = magnetUtil.decode(magnet.href)
813 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
814 throw new Error('Cannot parse magnet URI ' + magnet.href)
817 const torrentUrl = Array.isArray(parsed.xs)
821 // Fetch associated metadata url, if any
822 const metadata = urls.filter(isAPVideoFileUrlMetadataObject)
824 return u.height === fileUrl.height &&
825 u.fps === fileUrl.fps &&
826 u.rel.includes(fileUrl.mediaType)
829 const extname = getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, fileUrl.mediaType)
830 const resolution = fileUrl.height
831 const videoId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id
832 const videoStreamingPlaylistId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
836 infoHash: parsed.infoHash,
839 fps: fileUrl.fps || -1,
840 metadataUrl: metadata?.href,
842 // Use the name of the remote file because we don't proxify video file requests
843 filename: basename(fileUrl.href),
844 fileUrl: fileUrl.href,
847 // Use our own torrent name since we proxify torrent requests
848 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
850 // This is a video file owned by a video or by a streaming playlist
852 videoStreamingPlaylistId
855 attributes.push(attribute)
861 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
862 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
863 if (playlistUrls.length === 0) return []
865 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
866 for (const playlistUrlObject of playlistUrls) {
867 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
869 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
871 // FIXME: backward compatibility introduced in v2.1.0
872 if (files.length === 0) files = videoFiles
874 if (!segmentsSha256UrlObject) {
875 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
880 type: VideoStreamingPlaylistType.HLS,
881 playlistUrl: playlistUrlObject.href,
882 segmentsSha256Url: segmentsSha256UrlObject.href,
883 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
884 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
886 tagAPObject: playlistUrlObject.tag
889 attributes.push(attribute)
895 function getThumbnailFromIcons (videoObject: VideoObject) {
896 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
897 // Fallback if there are not valid icons
898 if (validIcons.length === 0) validIcons = videoObject.icon
900 return minBy(validIcons, 'width')
903 function getPreviewFromIcons (videoObject: VideoObject) {
904 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
906 return maxBy(validIcons, 'width')
909 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
912 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
915 function getTrackerUrls (object: VideoObject, video: MVideoWithHost) {
918 const trackers = object.url.filter(u => isAPVideoTrackerUrlObject(u))
919 .map((u: ActivityTrackerUrlObject) => {
920 if (isArray(u.rel) && u.rel.includes('websocket')) wsFound = true
925 if (wsFound) return trackers
928 buildRemoteVideoBaseUrl(video, '/tracker/socket', REMOTE_SCHEME.WS),
929 buildRemoteVideoBaseUrl(video, '/tracker/announce')
933 async function setVideoTrackers (options: {
936 transaction?: Transaction
938 const { video, trackers, transaction } = options
940 const trackerInstances = await TrackerModel.findOrCreateTrackers(trackers, transaction)
942 await video.$set('Trackers', trackerInstances, { transaction })