1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import { 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'
34 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'
56 MVideoAccountLightBlacklistAllFiles,
58 MVideoAPWithoutCaption,
65 } from '../../types/models'
66 import { MThumbnail } from '../../types/models/video/thumbnail'
67 import { FilteredModelAttributes } from '../../types/sequelize'
68 import { ActorFollowScoreCache } from '../files-cache'
69 import { JobQueue } from '../job-queue'
70 import { Notifier } from '../notifier'
71 import { PeerTubeSocket } from '../peertube-socket'
72 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
73 import { setVideoTags } from '../video'
74 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
75 import { getOrCreateActorAndServerAndModel } from './actor'
76 import { crawlCollectionPage } from './crawl'
77 import { sendCreateVideo, sendUpdateVideo } from './send'
78 import { addVideoShares, shareVideoByServerAndChannel } from './share'
79 import { addVideoComments } from './video-comments'
80 import { createRates } from './video-rates'
82 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
83 const video = videoArg as MVideoAP
86 // Check this is not a blacklisted video, or unfederated blacklisted video
87 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
88 // Check the video is public/unlisted and published
89 video.hasPrivacyForFederation() && video.hasStateForFederation()
91 // Fetch more attributes that we will need to serialize in AP object
92 if (isArray(video.VideoCaptions) === false) {
93 video.VideoCaptions = await video.$get('VideoCaptions', {
94 attributes: [ 'filename', 'language' ],
100 // Now we'll add the video's meta data to our followers
101 await sendCreateVideo(video, transaction)
102 await shareVideoByServerAndChannel(video, transaction)
104 await sendUpdateVideo(video, transaction)
109 async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoObject }> {
117 logger.info('Fetching remote video %s.', videoUrl)
119 const { response, body } = await doRequest<any>(options)
121 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
122 logger.debug('Remote video JSON is not valid.', { body })
123 return { response, videoObject: undefined }
126 return { response, videoObject: body }
129 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
130 const host = video.VideoChannel.Account.Actor.Server.host
131 const path = video.getDescriptionAPIPath()
133 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
137 const { body } = await doRequest<any>(options)
138 return body.description ? body.description : ''
141 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
142 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
143 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
145 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
146 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
149 return getOrCreateActorAndServerAndModel(channel.id, 'all')
158 refreshVideo?: boolean
160 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
161 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
163 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
165 if (syncParam.likes === true) {
166 const handler = items => createRates(items, video, 'like')
167 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
169 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
170 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
172 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
175 if (syncParam.dislikes === true) {
176 const handler = items => createRates(items, video, 'dislike')
177 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
179 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
180 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
182 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
185 if (syncParam.shares === true) {
186 const handler = items => addVideoShares(items, video)
187 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
189 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
190 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
192 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
195 if (syncParam.comments === true) {
196 const handler = items => addVideoComments(items)
197 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
199 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
200 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
202 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
205 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
208 type GetVideoResult <T> = Promise<{
211 autoBlacklisted?: boolean
214 type GetVideoParamAll = {
215 videoObject: { id: string } | string
216 syncParam?: SyncParam
218 allowRefresh?: boolean
221 type GetVideoParamImmutable = {
222 videoObject: { id: string } | string
223 syncParam?: SyncParam
224 fetchType: 'only-immutable-attributes'
228 type GetVideoParamOther = {
229 videoObject: { id: string } | string
230 syncParam?: SyncParam
231 fetchType?: 'all' | 'only-video'
232 allowRefresh?: boolean
235 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
236 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
237 function getOrCreateVideoAndAccountAndChannel (
238 options: GetVideoParamOther
239 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
240 async function getOrCreateVideoAndAccountAndChannel (
241 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
242 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
244 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
245 const fetchType = options.fetchType || 'all'
246 const allowRefresh = options.allowRefresh !== false
249 const videoUrl = getAPId(options.videoObject)
250 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
252 if (videoFromDatabase) {
253 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
254 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
255 const refreshOptions = {
256 video: videoFromDatabase as MVideoThumbnail,
257 fetchedType: fetchType,
261 if (syncParam.refreshVideo === true) {
262 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
264 await JobQueue.Instance.createJobWithPromise({
265 type: 'activitypub-refresher',
266 payload: { type: 'video', url: videoFromDatabase.url }
271 return { video: videoFromDatabase, created: false }
274 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
275 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
277 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
278 const videoChannel = actor.VideoChannel
281 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
283 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
285 return { video: videoCreated, created: true, autoBlacklisted }
287 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
288 if (err.name === 'SequelizeUniqueConstraintError') {
289 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
290 if (fallbackVideo) return { video: fallbackVideo, created: false }
297 async function updateVideoFromAP (options: {
298 video: MVideoAccountLightBlacklistAllFiles
299 videoObject: VideoObject
300 account: MAccountIdActor
301 channel: MChannelDefault
302 overrideTo?: string[]
304 const { video, videoObject, account, channel, overrideTo } = options
306 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
308 let videoFieldsSave: any
309 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
310 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
313 let thumbnailModel: MThumbnail
316 thumbnailModel = await createVideoMiniatureFromUrl({
317 downloadUrl: getThumbnailFromIcons(videoObject).url,
319 type: ThumbnailType.MINIATURE
322 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
325 const videoUpdated = await sequelizeTypescript.transaction(async t => {
326 const sequelizeOptions = { transaction: t }
328 videoFieldsSave = video.toJSON()
330 // Check actor has the right to update the video
331 const videoChannel = video.VideoChannel
332 if (videoChannel.Account.id !== account.id) {
333 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
336 const to = overrideTo || videoObject.to
337 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
338 video.name = videoData.name
339 video.uuid = videoData.uuid
340 video.url = videoData.url
341 video.category = videoData.category
342 video.licence = videoData.licence
343 video.language = videoData.language
344 video.description = videoData.description
345 video.support = videoData.support
346 video.nsfw = videoData.nsfw
347 video.commentsEnabled = videoData.commentsEnabled
348 video.downloadEnabled = videoData.downloadEnabled
349 video.waitTranscoding = videoData.waitTranscoding
350 video.state = videoData.state
351 video.duration = videoData.duration
352 video.createdAt = videoData.createdAt
353 video.publishedAt = videoData.publishedAt
354 video.originallyPublishedAt = videoData.originallyPublishedAt
355 video.privacy = videoData.privacy
356 video.channelId = videoData.channelId
357 video.views = videoData.views
358 video.isLive = videoData.isLive
360 // Ensures we update the updated video attribute
361 video.changed('updatedAt', true)
363 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
365 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
367 if (videoUpdated.getPreview()) {
368 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
369 const previewModel = createPlaceholderThumbnail({
372 type: ThumbnailType.PREVIEW,
375 await videoUpdated.addAndSaveThumbnail(previewModel, t)
379 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
380 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
382 // Remove video files that do not exist anymore
383 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
384 await Promise.all(destroyTasks)
386 // Update or add other one
387 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
388 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
392 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
393 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
395 // Remove video playlists that do not exist anymore
396 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
397 await Promise.all(destroyTasks)
399 let oldStreamingPlaylistFiles: MVideoFile[] = []
400 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
401 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
404 videoUpdated.VideoStreamingPlaylists = []
406 for (const playlistAttributes of streamingPlaylistAttributes) {
407 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
408 .then(([ streamingPlaylist ]) => streamingPlaylist)
410 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
411 .map(a => new VideoFileModel(a))
412 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
413 await Promise.all(destroyTasks)
415 // Update or add other one
416 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
417 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
419 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
425 const tags = videoObject.tag
426 .filter(isAPHashTagObject)
427 .map(tag => tag.name)
428 await setVideoTags({ video: videoUpdated, tags, transaction: t, defaultValue: videoUpdated.Tags })
433 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
435 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
436 const caption = new VideoCaptionModel({
437 videoId: videoUpdated.id,
438 filename: VideoCaptionModel.generateCaptionName(c.identifier),
439 language: c.identifier,
443 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
445 await Promise.all(videoCaptionsPromises)
449 // Create or update existing live
451 const [ videoLive ] = await VideoLiveModel.upsert({
452 saveReplay: videoObject.liveSaveReplay,
453 permanentLive: videoObject.permanentLive,
455 }, { transaction: t, returning: true })
457 videoUpdated.VideoLive = videoLive
458 } else { // Delete existing live if it exists
459 await VideoLiveModel.destroy({
466 videoUpdated.VideoLive = null
473 await autoBlacklistVideoIfNeeded({
478 transaction: undefined
482 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
484 if (videoUpdated.isLive) {
485 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
486 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
489 logger.info('Remote video with uuid %s updated', videoObject.uuid)
493 if (video !== undefined && videoFieldsSave !== undefined) {
494 resetSequelizeInstance(video, videoFieldsSave)
497 // This is just a debug because we will retry the insert
498 logger.debug('Cannot update the remote video.', { err })
503 async function refreshVideoIfNeeded (options: {
504 video: MVideoThumbnail
505 fetchedType: VideoFetchByUrlType
507 }): Promise<MVideoThumbnail> {
508 if (!options.video.isOutdated()) return options.video
510 // We need more attributes if the argument video was fetched with not enough joints
511 const video = options.fetchedType === 'all'
512 ? options.video as MVideoAccountLightBlacklistAllFiles
513 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
516 const { response, videoObject } = await fetchRemoteVideo(video.url)
517 if (response.statusCode === HttpStatusCode.NOT_FOUND_404) {
518 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
520 // Video does not exist anymore
521 await video.destroy()
525 if (videoObject === undefined) {
526 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
528 await video.setAsRefreshed()
532 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
534 const updateOptions = {
537 account: channelActor.VideoChannel.Account,
538 channel: channelActor.VideoChannel
540 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
541 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
543 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
547 logger.warn('Cannot refresh video %s.', options.video.url, { err })
549 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
551 // Don't refresh in loop
552 await video.setAsRefreshed()
559 refreshVideoIfNeeded,
560 federateVideoIfNeeded,
562 getOrCreateVideoAndAccountAndChannel,
563 fetchRemoteVideoDescription,
564 getOrCreateVideoChannelFromVideoObject
567 // ---------------------------------------------------------------------------
569 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
570 const urlMediaType = url.mediaType
572 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
575 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
576 return url && url.mediaType === 'application/x-mpegURL'
579 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
580 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
583 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
584 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
587 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
588 return url && url.type === 'Hashtag'
591 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
592 logger.debug('Adding remote video %s.', videoObject.id)
594 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
595 const video = VideoModel.build(videoData) as MVideoThumbnail
597 const promiseThumbnail = createVideoMiniatureFromUrl({
598 downloadUrl: getThumbnailFromIcons(videoObject).url,
600 type: ThumbnailType.MINIATURE
602 logger.error('Cannot create miniature from url.', { err })
606 let thumbnailModel: MThumbnail
607 if (waitThumbnail === true) {
608 thumbnailModel = await promiseThumbnail
611 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
613 const sequelizeOptions = { transaction: t }
615 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
616 videoCreated.VideoChannel = channel
618 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
620 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), videoCreated)
621 const previewModel = createPlaceholderThumbnail({
624 type: ThumbnailType.PREVIEW,
628 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
631 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
633 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
634 const videoFiles = await Promise.all(videoFilePromises)
636 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
637 videoCreated.VideoStreamingPlaylists = []
639 for (const playlistAttributes of streamingPlaylistsAttributes) {
640 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
642 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
643 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
644 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
646 videoCreated.VideoStreamingPlaylists.push(playlistModel)
650 const tags = videoObject.tag
651 .filter(isAPHashTagObject)
653 await setVideoTags({ video: videoCreated, tags, transaction: t })
656 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
657 const caption = new VideoCaptionModel({
658 videoId: videoCreated.id,
659 filename: VideoCaptionModel.generateCaptionName(c.identifier),
660 language: c.identifier,
664 return VideoCaptionModel.insertOrReplaceLanguage(caption, t)
666 await Promise.all(videoCaptionsPromises)
668 videoCreated.VideoFiles = videoFiles
670 if (videoCreated.isLive) {
671 const videoLive = new VideoLiveModel({
673 saveReplay: videoObject.liveSaveReplay,
674 permanentLive: videoObject.permanentLive,
675 videoId: videoCreated.id
678 videoCreated.VideoLive = await videoLive.save({ transaction: t })
681 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
689 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
691 return { autoBlacklisted, videoCreated }
693 // FIXME: Use rollback hook when https://github.com/sequelize/sequelize/pull/13038 is released
695 if (thumbnailModel) await thumbnailModel.removeThumbnail()
701 if (waitThumbnail === false) {
702 // Error is already caught above
703 // eslint-disable-next-line @typescript-eslint/no-floating-promises
704 promiseThumbnail.then(thumbnailModel => {
705 if (!thumbnailModel) return
707 thumbnailModel = videoCreated.id
709 return thumbnailModel.save()
713 return { autoBlacklisted, videoCreated }
716 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
717 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
718 ? VideoPrivacy.PUBLIC
719 : VideoPrivacy.UNLISTED
721 const duration = videoObject.duration.replace(/[^\d]+/, '')
722 const language = videoObject.language?.identifier
724 const category = videoObject.category
725 ? parseInt(videoObject.category.identifier, 10)
728 const licence = videoObject.licence
729 ? parseInt(videoObject.licence.identifier, 10)
732 const description = videoObject.content || null
733 const support = videoObject.support || null
736 name: videoObject.name,
737 uuid: videoObject.uuid,
744 nsfw: videoObject.sensitive,
745 commentsEnabled: videoObject.commentsEnabled,
746 downloadEnabled: videoObject.downloadEnabled,
747 waitTranscoding: videoObject.waitTranscoding,
748 isLive: videoObject.isLiveBroadcast,
749 state: videoObject.state,
750 channelId: videoChannel.id,
751 duration: parseInt(duration, 10),
752 createdAt: new Date(videoObject.published),
753 publishedAt: new Date(videoObject.published),
755 originallyPublishedAt: videoObject.originallyPublishedAt
756 ? new Date(videoObject.originallyPublishedAt)
759 updatedAt: new Date(videoObject.updated),
760 views: videoObject.views,
768 function videoFileActivityUrlToDBAttributes (
769 videoOrPlaylist: MVideo | MStreamingPlaylist,
770 urls: (ActivityTagObject | ActivityUrlObject)[]
772 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
774 if (fileUrls.length === 0) return []
776 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
777 for (const fileUrl of fileUrls) {
778 // Fetch associated magnet uri
779 const magnet = urls.filter(isAPMagnetUrlObject)
780 .find(u => u.height === fileUrl.height)
782 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
784 const parsed = magnetUtil.decode(magnet.href)
785 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
786 throw new Error('Cannot parse magnet URI ' + magnet.href)
789 // Fetch associated metadata url, if any
790 const metadata = urls.filter(isAPVideoFileMetadataObject)
792 return u.height === fileUrl.height &&
793 u.fps === fileUrl.fps &&
794 u.rel.includes(fileUrl.mediaType)
797 const mediaType = fileUrl.mediaType
799 extname: getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, mediaType),
800 infoHash: parsed.infoHash,
801 resolution: fileUrl.height,
803 fps: fileUrl.fps || -1,
804 metadataUrl: metadata?.href,
806 // This is a video file owned by a video or by a streaming playlist
807 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
808 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
811 attributes.push(attribute)
817 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
818 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
819 if (playlistUrls.length === 0) return []
821 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
822 for (const playlistUrlObject of playlistUrls) {
823 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
825 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
827 // FIXME: backward compatibility introduced in v2.1.0
828 if (files.length === 0) files = videoFiles
830 if (!segmentsSha256UrlObject) {
831 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
836 type: VideoStreamingPlaylistType.HLS,
837 playlistUrl: playlistUrlObject.href,
838 segmentsSha256Url: segmentsSha256UrlObject.href,
839 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
840 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
842 tagAPObject: playlistUrlObject.tag
845 attributes.push(attribute)
851 function getThumbnailFromIcons (videoObject: VideoObject) {
852 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
853 // Fallback if there are not valid icons
854 if (validIcons.length === 0) validIcons = videoObject.icon
856 return minBy(validIcons, 'width')
859 function getPreviewFromIcons (videoObject: VideoObject) {
860 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
862 return maxBy(validIcons, 'width')
865 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoAccountLight) {
868 : buildRemoteVideoBaseUrl(video, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))