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 * as sequelize from 'sequelize'
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, 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'
24 import { isAPVideoFileMetadataObject, sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
25 import { isArray } from '../../helpers/custom-validators/misc'
26 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
27 import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
28 import { logger } from '../../helpers/logger'
29 import { doRequest } from '../../helpers/requests'
30 import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
35 P2P_MEDIA_LOADER_PEER_VERSION,
39 } from '../../initializers/constants'
40 import { sequelizeTypescript } from '../../initializers/database'
41 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
42 import { VideoModel } from '../../models/video/video'
43 import { VideoCaptionModel } from '../../models/video/video-caption'
44 import { VideoCommentModel } from '../../models/video/video-comment'
45 import { VideoFileModel } from '../../models/video/video-file'
46 import { VideoShareModel } from '../../models/video/video-share'
47 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
54 MStreamingPlaylistFilesVideo,
55 MStreamingPlaylistVideo,
58 MVideoAccountLightBlacklistAllFiles,
60 MVideoAPWithoutCaption,
68 } from '../../types/models'
69 import { MThumbnail } from '../../types/models/video/thumbnail'
70 import { FilteredModelAttributes } from '../../types/sequelize'
71 import { ActorFollowScoreCache } from '../files-cache'
72 import { JobQueue } from '../job-queue'
73 import { Notifier } from '../notifier'
74 import { PeerTubeSocket } from '../peertube-socket'
75 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
76 import { setVideoTags } from '../video'
77 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
78 import { generateTorrentFileName } from '../video-paths'
79 import { getOrCreateActorAndServerAndModel } from './actor'
80 import { crawlCollectionPage } from './crawl'
81 import { sendCreateVideo, sendUpdateVideo } from './send'
82 import { addVideoShares, shareVideoByServerAndChannel } from './share'
83 import { addVideoComments } from './video-comments'
84 import { createRates } from './video-rates'
86 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
87 const video = videoArg as MVideoAP
90 // Check this is not a blacklisted video, or unfederated blacklisted video
91 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
92 // Check the video is public/unlisted and published
93 video.hasPrivacyForFederation() && video.hasStateForFederation()
95 // Fetch more attributes that we will need to serialize in AP object
96 if (isArray(video.VideoCaptions) === false) {
97 video.VideoCaptions = await video.$get('VideoCaptions', {
98 attributes: [ 'filename', 'language' ],
104 // Now we'll add the video's meta data to our followers
105 await sendCreateVideo(video, transaction)
106 await shareVideoByServerAndChannel(video, transaction)
108 await sendUpdateVideo(video, transaction)
113 async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoObject }> {
121 logger.info('Fetching remote video %s.', videoUrl)
123 const { response, body } = await doRequest<any>(options)
125 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
126 logger.debug('Remote video JSON is not valid.', { body })
127 return { response, videoObject: undefined }
130 return { response, videoObject: body }
133 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
134 const host = video.VideoChannel.Account.Actor.Server.host
135 const path = video.getDescriptionAPIPath()
137 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
141 const { body } = await doRequest<any>(options)
142 return body.description ? body.description : ''
145 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
146 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
147 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
149 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
150 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
153 return getOrCreateActorAndServerAndModel(channel.id, 'all')
162 refreshVideo?: boolean
164 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
165 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
167 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
169 if (syncParam.likes === true) {
170 const handler = items => createRates(items, video, 'like')
171 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
173 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
174 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
176 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
179 if (syncParam.dislikes === true) {
180 const handler = items => createRates(items, video, 'dislike')
181 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
183 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
184 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
186 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
189 if (syncParam.shares === true) {
190 const handler = items => addVideoShares(items, video)
191 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
193 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
194 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
196 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
199 if (syncParam.comments === true) {
200 const handler = items => addVideoComments(items)
201 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
203 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
204 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
206 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
209 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
212 type GetVideoResult <T> = Promise<{
215 autoBlacklisted?: boolean
218 type GetVideoParamAll = {
219 videoObject: { id: string } | string
220 syncParam?: SyncParam
222 allowRefresh?: boolean
225 type GetVideoParamImmutable = {
226 videoObject: { id: string } | string
227 syncParam?: SyncParam
228 fetchType: 'only-immutable-attributes'
232 type GetVideoParamOther = {
233 videoObject: { id: string } | string
234 syncParam?: SyncParam
235 fetchType?: 'all' | 'only-video'
236 allowRefresh?: boolean
239 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
240 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
241 function getOrCreateVideoAndAccountAndChannel (
242 options: GetVideoParamOther
243 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
244 async function getOrCreateVideoAndAccountAndChannel (
245 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
246 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
248 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
249 const fetchType = options.fetchType || 'all'
250 const allowRefresh = options.allowRefresh !== false
253 const videoUrl = getAPId(options.videoObject)
254 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
256 if (videoFromDatabase) {
257 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
258 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
259 const refreshOptions = {
260 video: videoFromDatabase as MVideoThumbnail,
261 fetchedType: fetchType,
265 if (syncParam.refreshVideo === true) {
266 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
268 await JobQueue.Instance.createJobWithPromise({
269 type: 'activitypub-refresher',
270 payload: { type: 'video', url: videoFromDatabase.url }
275 return { video: videoFromDatabase, created: false }
278 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
279 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
281 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
282 const videoChannel = actor.VideoChannel
285 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
287 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
289 return { video: videoCreated, created: true, autoBlacklisted }
291 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
292 if (err.name === 'SequelizeUniqueConstraintError') {
293 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
294 if (fallbackVideo) return { video: fallbackVideo, created: false }
301 async function updateVideoFromAP (options: {
302 video: MVideoAccountLightBlacklistAllFiles
303 videoObject: VideoObject
304 account: MAccountIdActor
305 channel: MChannelDefault
306 overrideTo?: string[]
308 const { video, videoObject, account, channel, overrideTo } = options
310 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
312 let videoFieldsSave: any
313 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
314 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
317 let thumbnailModel: MThumbnail
320 thumbnailModel = await createVideoMiniatureFromUrl({
321 downloadUrl: getThumbnailFromIcons(videoObject).url,
323 type: ThumbnailType.MINIATURE
326 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
329 const videoUpdated = await sequelizeTypescript.transaction(async t => {
330 const sequelizeOptions = { transaction: t }
332 videoFieldsSave = video.toJSON()
334 // Check actor has the right to update the video
335 const videoChannel = video.VideoChannel
336 if (videoChannel.Account.id !== account.id) {
337 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.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, defaultValue: videoUpdated.Tags })
438 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
440 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
441 const caption = new VideoCaptionModel({
442 videoId: videoUpdated.id,
443 filename: VideoCaptionModel.generateCaptionName(c.identifier),
444 language: c.identifier,
448 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
450 await Promise.all(videoCaptionsPromises)
454 // Create or update existing live
456 const [ videoLive ] = await VideoLiveModel.upsert({
457 saveReplay: videoObject.liveSaveReplay,
458 permanentLive: videoObject.permanentLive,
460 }, { transaction: t, returning: true })
462 videoUpdated.VideoLive = videoLive
463 } else { // Delete existing live if it exists
464 await VideoLiveModel.destroy({
471 videoUpdated.VideoLive = null
478 await autoBlacklistVideoIfNeeded({
483 transaction: undefined
487 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
489 if (videoUpdated.isLive) {
490 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
491 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
494 logger.info('Remote video with uuid %s updated', videoObject.uuid)
498 if (video !== undefined && videoFieldsSave !== undefined) {
499 resetSequelizeInstance(video, videoFieldsSave)
502 // This is just a debug because we will retry the insert
503 logger.debug('Cannot update the remote video.', { err })
508 async function refreshVideoIfNeeded (options: {
509 video: MVideoThumbnail
510 fetchedType: VideoFetchByUrlType
512 }): Promise<MVideoThumbnail> {
513 if (!options.video.isOutdated()) return options.video
515 // We need more attributes if the argument video was fetched with not enough joints
516 const video = options.fetchedType === 'all'
517 ? options.video as MVideoAccountLightBlacklistAllFiles
518 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
521 const { response, videoObject } = await fetchRemoteVideo(video.url)
522 if (response.statusCode === HttpStatusCode.NOT_FOUND_404) {
523 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
525 // Video does not exist anymore
526 await video.destroy()
530 if (videoObject === undefined) {
531 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
533 await video.setAsRefreshed()
537 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
539 const updateOptions = {
542 account: channelActor.VideoChannel.Account,
543 channel: channelActor.VideoChannel
545 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
546 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
548 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
552 logger.warn('Cannot refresh video %s.', options.video.url, { err })
554 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
556 // Don't refresh in loop
557 await video.setAsRefreshed()
564 refreshVideoIfNeeded,
565 federateVideoIfNeeded,
567 getOrCreateVideoAndAccountAndChannel,
568 fetchRemoteVideoDescription,
569 getOrCreateVideoChannelFromVideoObject
572 // ---------------------------------------------------------------------------
574 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
575 const urlMediaType = url.mediaType
577 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
580 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
581 return url && url.mediaType === 'application/x-mpegURL'
584 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
585 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
588 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
589 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
592 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
593 return url && url.type === 'Hashtag'
596 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
597 logger.debug('Adding remote video %s.', videoObject.id)
599 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
600 const video = VideoModel.build(videoData) as MVideoThumbnail
602 const promiseThumbnail = createVideoMiniatureFromUrl({
603 downloadUrl: getThumbnailFromIcons(videoObject).url,
605 type: ThumbnailType.MINIATURE
607 logger.error('Cannot create miniature from url.', { err })
611 let thumbnailModel: MThumbnail
612 if (waitThumbnail === true) {
613 thumbnailModel = await promiseThumbnail
616 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
618 const sequelizeOptions = { transaction: t }
620 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
621 videoCreated.VideoChannel = channel
623 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
625 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
626 const previewModel = createPlaceholderThumbnail({
629 type: ThumbnailType.PREVIEW,
633 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
636 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
638 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
639 const videoFiles = await Promise.all(videoFilePromises)
641 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
642 videoCreated.VideoStreamingPlaylists = []
644 for (const playlistAttributes of streamingPlaylistsAttributes) {
645 const playlist = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t }) as MStreamingPlaylistFilesVideo
646 playlist.Video = videoCreated
648 const playlistFiles = videoFileActivityUrlToDBAttributes(playlist, playlistAttributes.tagAPObject)
649 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
650 playlist.VideoFiles = await Promise.all(videoFilePromises)
652 videoCreated.VideoStreamingPlaylists.push(playlist)
656 const tags = videoObject.tag
657 .filter(isAPHashTagObject)
659 await setVideoTags({ video: videoCreated, tags, transaction: t })
662 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
663 const caption = new VideoCaptionModel({
664 videoId: videoCreated.id,
665 filename: VideoCaptionModel.generateCaptionName(c.identifier),
666 language: c.identifier,
670 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
672 await Promise.all(videoCaptionsPromises)
674 videoCreated.VideoFiles = videoFiles
676 if (videoCreated.isLive) {
677 const videoLive = new VideoLiveModel({
679 saveReplay: videoObject.liveSaveReplay,
680 permanentLive: videoObject.permanentLive,
681 videoId: videoCreated.id
684 videoCreated.VideoLive = await videoLive.save({ transaction: t })
687 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
695 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
697 return { autoBlacklisted, videoCreated }
699 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
701 if (thumbnailModel) await thumbnailModel.removeThumbnail()
707 if (waitThumbnail === false) {
708 // Error is already caught above
709 // eslint-disable-next-line @typescript-eslint/no-floating-promises
710 promiseThumbnail.then(thumbnailModel => {
711 if (!thumbnailModel) return
713 thumbnailModel = videoCreated.id
715 return thumbnailModel.save()
719 return { autoBlacklisted, videoCreated }
722 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
723 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
724 ? VideoPrivacy.PUBLIC
725 : VideoPrivacy.UNLISTED
727 const duration = videoObject.duration.replace(/[^\d]+/, '')
728 const language = videoObject.language?.identifier
730 const category = videoObject.category
731 ? parseInt(videoObject.category.identifier, 10)
734 const licence = videoObject.licence
735 ? parseInt(videoObject.licence.identifier, 10)
738 const description = videoObject.content || null
739 const support = videoObject.support || null
742 name: videoObject.name,
743 uuid: videoObject.uuid,
750 nsfw: videoObject.sensitive,
751 commentsEnabled: videoObject.commentsEnabled,
752 downloadEnabled: videoObject.downloadEnabled,
753 waitTranscoding: videoObject.waitTranscoding,
754 isLive: videoObject.isLiveBroadcast,
755 state: videoObject.state,
756 channelId: videoChannel.id,
757 duration: parseInt(duration, 10),
758 createdAt: new Date(videoObject.published),
759 publishedAt: new Date(videoObject.published),
761 originallyPublishedAt: videoObject.originallyPublishedAt
762 ? new Date(videoObject.originallyPublishedAt)
765 updatedAt: new Date(videoObject.updated),
766 views: videoObject.views,
774 function videoFileActivityUrlToDBAttributes (
775 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
776 urls: (ActivityTagObject | ActivityUrlObject)[]
778 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
780 if (fileUrls.length === 0) return []
782 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
783 for (const fileUrl of fileUrls) {
784 // Fetch associated magnet uri
785 const magnet = urls.filter(isAPMagnetUrlObject)
786 .find(u => u.height === fileUrl.height)
788 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
790 const parsed = magnetUtil.decode(magnet.href)
791 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
792 throw new Error('Cannot parse magnet URI ' + magnet.href)
795 const torrentUrl = Array.isArray(parsed.xs)
799 // Fetch associated metadata url, if any
800 const metadata = urls.filter(isAPVideoFileMetadataObject)
802 return u.height === fileUrl.height &&
803 u.fps === fileUrl.fps &&
804 u.rel.includes(fileUrl.mediaType)
807 const extname = getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, fileUrl.mediaType)
808 const resolution = fileUrl.height
809 const videoId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id
810 const videoStreamingPlaylistId = (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
814 infoHash: parsed.infoHash,
817 fps: fileUrl.fps || -1,
818 metadataUrl: metadata?.href,
820 // Use the name of the remote file because we don't proxify video file requests
821 filename: basename(fileUrl.href),
822 fileUrl: fileUrl.href,
825 // Use our own torrent name since we proxify torrent requests
826 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
828 // This is a video file owned by a video or by a streaming playlist
830 videoStreamingPlaylistId
833 attributes.push(attribute)
839 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
840 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
841 if (playlistUrls.length === 0) return []
843 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
844 for (const playlistUrlObject of playlistUrls) {
845 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
847 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
849 // FIXME: backward compatibility introduced in v2.1.0
850 if (files.length === 0) files = videoFiles
852 if (!segmentsSha256UrlObject) {
853 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
858 type: VideoStreamingPlaylistType.HLS,
859 playlistUrl: playlistUrlObject.href,
860 segmentsSha256Url: segmentsSha256UrlObject.href,
861 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
862 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
864 tagAPObject: playlistUrlObject.tag
867 attributes.push(attribute)
873 function getThumbnailFromIcons (videoObject: VideoObject) {
874 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
875 // Fallback if there are not valid icons
876 if (validIcons.length === 0) validIcons = videoObject.icon
878 return minBy(validIcons, 'width')
881 function getPreviewFromIcons (videoObject: VideoObject) {
882 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
884 return maxBy(validIcons, 'width')
887 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoWithHost) {
890 : buildRemoteVideoBaseUrl(video, join(LAZY_STATIC_PATHS.PREVIEWS, video.generatePreviewName()))