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'
10 ActivityMagnetUrlObject,
11 ActivityPlaylistSegmentHashesObject,
12 ActivityPlaylistUrlObject,
13 ActivitypubHttpFetcherPayload,
16 ActivityVideoUrlObject
17 } from '../../../shared/index'
18 import { VideoObject } from '../../../shared/models/activitypub/objects'
19 import { VideoPrivacy } from '../../../shared/models/videos'
20 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
21 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
22 import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
23 import { isAPVideoFileMetadataObject, sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
24 import { isArray } from '../../helpers/custom-validators/misc'
25 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
26 import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
27 import { logger } from '../../helpers/logger'
28 import { doRequest } from '../../helpers/requests'
29 import { fetchVideoByUrl, getExtFromMimetype, VideoFetchByUrlType } from '../../helpers/video'
33 P2P_MEDIA_LOADER_PEER_VERSION,
38 } from '../../initializers/constants'
39 import { sequelizeTypescript } from '../../initializers/database'
40 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
41 import { VideoModel } from '../../models/video/video'
42 import { VideoCaptionModel } from '../../models/video/video-caption'
43 import { VideoCommentModel } from '../../models/video/video-comment'
44 import { VideoFileModel } from '../../models/video/video-file'
45 import { VideoShareModel } from '../../models/video/video-share'
46 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
55 MVideoAccountLightBlacklistAllFiles,
57 MVideoAPWithoutCaption,
63 } from '../../types/models'
64 import { MThumbnail } from '../../types/models/video/thumbnail'
65 import { FilteredModelAttributes } from '../../types/sequelize'
66 import { ActorFollowScoreCache } from '../files-cache'
67 import { JobQueue } from '../job-queue'
68 import { Notifier } from '../notifier'
69 import { PeerTubeSocket } from '../peertube-socket'
70 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
71 import { setVideoTags } from '../video'
72 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
73 import { getOrCreateActorAndServerAndModel } from './actor'
74 import { crawlCollectionPage } from './crawl'
75 import { sendCreateVideo, sendUpdateVideo } from './send'
76 import { addVideoShares, shareVideoByServerAndChannel } from './share'
77 import { addVideoComments } from './video-comments'
78 import { createRates } from './video-rates'
80 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
81 const video = videoArg as MVideoAP
84 // Check this is not a blacklisted video, or unfederated blacklisted video
85 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
86 // Check the video is public/unlisted and published
87 video.hasPrivacyForFederation() && video.hasStateForFederation()
89 // Fetch more attributes that we will need to serialize in AP object
90 if (isArray(video.VideoCaptions) === false) {
91 video.VideoCaptions = await video.$get('VideoCaptions', {
92 attributes: [ 'language' ],
98 // Now we'll add the video's meta data to our followers
99 await sendCreateVideo(video, transaction)
100 await shareVideoByServerAndChannel(video, transaction)
102 await sendUpdateVideo(video, transaction)
107 async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoObject }> {
115 logger.info('Fetching remote video %s.', videoUrl)
117 const { response, body } = await doRequest<any>(options)
119 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
120 logger.debug('Remote video JSON is not valid.', { body })
121 return { response, videoObject: undefined }
124 return { response, videoObject: body }
127 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
128 const host = video.VideoChannel.Account.Actor.Server.host
129 const path = video.getDescriptionAPIPath()
131 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
135 const { body } = await doRequest<any>(options)
136 return body.description ? 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(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
316 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
319 const videoUpdated = await sequelizeTypescript.transaction(async t => {
320 const sequelizeOptions = { transaction: t }
322 videoFieldsSave = video.toJSON()
324 // Check actor has the right to update the video
325 const videoChannel = video.VideoChannel
326 if (videoChannel.Account.id !== account.id) {
327 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
330 const to = overrideTo || videoObject.to
331 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
332 video.name = videoData.name
333 video.uuid = videoData.uuid
334 video.url = videoData.url
335 video.category = videoData.category
336 video.licence = videoData.licence
337 video.language = videoData.language
338 video.description = videoData.description
339 video.support = videoData.support
340 video.nsfw = videoData.nsfw
341 video.commentsEnabled = videoData.commentsEnabled
342 video.downloadEnabled = videoData.downloadEnabled
343 video.waitTranscoding = videoData.waitTranscoding
344 video.state = videoData.state
345 video.duration = videoData.duration
346 video.createdAt = videoData.createdAt
347 video.publishedAt = videoData.publishedAt
348 video.originallyPublishedAt = videoData.originallyPublishedAt
349 video.privacy = videoData.privacy
350 video.channelId = videoData.channelId
351 video.views = videoData.views
352 video.isLive = videoData.isLive
354 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
356 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
358 if (videoUpdated.getPreview()) {
359 const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
360 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
361 await videoUpdated.addAndSaveThumbnail(previewModel, t)
365 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
366 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
368 // Remove video files that do not exist anymore
369 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
370 await Promise.all(destroyTasks)
372 // Update or add other one
373 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
374 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
378 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
379 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
381 // Remove video playlists that do not exist anymore
382 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
383 await Promise.all(destroyTasks)
385 let oldStreamingPlaylistFiles: MVideoFile[] = []
386 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
387 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
390 videoUpdated.VideoStreamingPlaylists = []
392 for (const playlistAttributes of streamingPlaylistAttributes) {
393 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
394 .then(([ streamingPlaylist ]) => streamingPlaylist)
396 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
397 .map(a => new VideoFileModel(a))
398 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
399 await Promise.all(destroyTasks)
401 // Update or add other one
402 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
403 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
405 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
411 const tags = videoObject.tag
412 .filter(isAPHashTagObject)
413 .map(tag => tag.name)
414 await setVideoTags({ video: videoUpdated, tags, transaction: t, defaultValue: videoUpdated.Tags })
419 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
421 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
422 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
424 await Promise.all(videoCaptionsPromises)
428 // Create or update existing live
430 const [ videoLive ] = await VideoLiveModel.upsert({
431 saveReplay: videoObject.liveSaveReplay,
432 permanentLive: videoObject.permanentLive,
434 }, { transaction: t, returning: true })
436 videoUpdated.VideoLive = videoLive
437 } else { // Delete existing live if it exists
438 await VideoLiveModel.destroy({
445 videoUpdated.VideoLive = null
452 await autoBlacklistVideoIfNeeded({
457 transaction: undefined
460 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
461 if (videoUpdated.isLive) PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
463 logger.info('Remote video with uuid %s updated', videoObject.uuid)
467 if (video !== undefined && videoFieldsSave !== undefined) {
468 resetSequelizeInstance(video, videoFieldsSave)
471 // This is just a debug because we will retry the insert
472 logger.debug('Cannot update the remote video.', { err })
477 async function refreshVideoIfNeeded (options: {
478 video: MVideoThumbnail
479 fetchedType: VideoFetchByUrlType
481 }): Promise<MVideoThumbnail> {
482 if (!options.video.isOutdated()) return options.video
484 // We need more attributes if the argument video was fetched with not enough joints
485 const video = options.fetchedType === 'all'
486 ? options.video as MVideoAccountLightBlacklistAllFiles
487 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
490 const { response, videoObject } = await fetchRemoteVideo(video.url)
491 if (response.statusCode === 404) {
492 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
494 // Video does not exist anymore
495 await video.destroy()
499 if (videoObject === undefined) {
500 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
502 await video.setAsRefreshed()
506 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
508 const updateOptions = {
511 account: channelActor.VideoChannel.Account,
512 channel: channelActor.VideoChannel
514 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
515 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
517 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
521 logger.warn('Cannot refresh video %s.', options.video.url, { err })
523 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
525 // Don't refresh in loop
526 await video.setAsRefreshed()
533 refreshVideoIfNeeded,
534 federateVideoIfNeeded,
536 getOrCreateVideoAndAccountAndChannel,
537 fetchRemoteVideoDescription,
538 getOrCreateVideoChannelFromVideoObject
541 // ---------------------------------------------------------------------------
543 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
544 const urlMediaType = url.mediaType
546 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
549 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
550 return url && url.mediaType === 'application/x-mpegURL'
553 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
554 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
557 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
558 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
561 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
562 return url && url.type === 'Hashtag'
565 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
566 logger.debug('Adding remote video %s.', videoObject.id)
568 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
569 const video = VideoModel.build(videoData) as MVideoThumbnail
571 const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
573 logger.error('Cannot create miniature from url.', { err })
577 let thumbnailModel: MThumbnail
578 if (waitThumbnail === true) {
579 thumbnailModel = await promiseThumbnail
582 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
583 const sequelizeOptions = { transaction: t }
585 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
586 videoCreated.VideoChannel = channel
588 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
590 const previewIcon = getPreviewFromIcons(videoObject)
591 const previewUrl = previewIcon
593 : buildRemoteVideoBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
594 const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
596 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
599 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
601 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
602 const videoFiles = await Promise.all(videoFilePromises)
604 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
605 videoCreated.VideoStreamingPlaylists = []
607 for (const playlistAttributes of streamingPlaylistsAttributes) {
608 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
610 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
611 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
612 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
614 videoCreated.VideoStreamingPlaylists.push(playlistModel)
618 const tags = videoObject.tag
619 .filter(isAPHashTagObject)
621 await setVideoTags({ video: videoCreated, tags, transaction: t })
624 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
625 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
627 await Promise.all(videoCaptionsPromises)
629 videoCreated.VideoFiles = videoFiles
631 if (videoCreated.isLive) {
632 const videoLive = new VideoLiveModel({
634 saveReplay: videoObject.liveSaveReplay,
635 permanentLive: videoObject.permanentLive,
636 videoId: videoCreated.id
639 videoCreated.VideoLive = await videoLive.save({ transaction: t })
642 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
650 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
652 return { autoBlacklisted, videoCreated }
655 if (waitThumbnail === false) {
656 // Error is already caught above
657 // eslint-disable-next-line @typescript-eslint/no-floating-promises
658 promiseThumbnail.then(thumbnailModel => {
659 if (!thumbnailModel) return
661 thumbnailModel = videoCreated.id
663 return thumbnailModel.save()
667 return { autoBlacklisted, videoCreated }
670 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
671 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
672 ? VideoPrivacy.PUBLIC
673 : VideoPrivacy.UNLISTED
675 const duration = videoObject.duration.replace(/[^\d]+/, '')
676 const language = videoObject.language?.identifier
678 const category = videoObject.category
679 ? parseInt(videoObject.category.identifier, 10)
682 const licence = videoObject.licence
683 ? parseInt(videoObject.licence.identifier, 10)
686 const description = videoObject.content || null
687 const support = videoObject.support || null
690 name: videoObject.name,
691 uuid: videoObject.uuid,
698 nsfw: videoObject.sensitive,
699 commentsEnabled: videoObject.commentsEnabled,
700 downloadEnabled: videoObject.downloadEnabled,
701 waitTranscoding: videoObject.waitTranscoding,
702 isLive: videoObject.isLiveBroadcast,
703 state: videoObject.state,
704 channelId: videoChannel.id,
705 duration: parseInt(duration, 10),
706 createdAt: new Date(videoObject.published),
707 publishedAt: new Date(videoObject.published),
709 originallyPublishedAt: videoObject.originallyPublishedAt
710 ? new Date(videoObject.originallyPublishedAt)
713 updatedAt: new Date(videoObject.updated),
714 views: videoObject.views,
722 function videoFileActivityUrlToDBAttributes (
723 videoOrPlaylist: MVideo | MStreamingPlaylist,
724 urls: (ActivityTagObject | ActivityUrlObject)[]
726 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
728 if (fileUrls.length === 0) return []
730 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
731 for (const fileUrl of fileUrls) {
732 // Fetch associated magnet uri
733 const magnet = urls.filter(isAPMagnetUrlObject)
734 .find(u => u.height === fileUrl.height)
736 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
738 const parsed = magnetUtil.decode(magnet.href)
739 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
740 throw new Error('Cannot parse magnet URI ' + magnet.href)
743 // Fetch associated metadata url, if any
744 const metadata = urls.filter(isAPVideoFileMetadataObject)
746 return u.height === fileUrl.height &&
747 u.fps === fileUrl.fps &&
748 u.rel.includes(fileUrl.mediaType)
751 const mediaType = fileUrl.mediaType
753 extname: getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, mediaType),
754 infoHash: parsed.infoHash,
755 resolution: fileUrl.height,
757 fps: fileUrl.fps || -1,
758 metadataUrl: metadata?.href,
760 // This is a video file owned by a video or by a streaming playlist
761 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
762 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
765 attributes.push(attribute)
771 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
772 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
773 if (playlistUrls.length === 0) return []
775 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
776 for (const playlistUrlObject of playlistUrls) {
777 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
779 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
781 // FIXME: backward compatibility introduced in v2.1.0
782 if (files.length === 0) files = videoFiles
784 if (!segmentsSha256UrlObject) {
785 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
790 type: VideoStreamingPlaylistType.HLS,
791 playlistUrl: playlistUrlObject.href,
792 segmentsSha256Url: segmentsSha256UrlObject.href,
793 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
794 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
796 tagAPObject: playlistUrlObject.tag
799 attributes.push(attribute)
805 function getThumbnailFromIcons (videoObject: VideoObject) {
806 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
807 // Fallback if there are not valid icons
808 if (validIcons.length === 0) validIcons = videoObject.icon
810 return minBy(validIcons, 'width')
813 function getPreviewFromIcons (videoObject: VideoObject) {
814 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
816 // FIXME: don't put a fallback here for compatibility with PeerTube <2.2
818 return maxBy(validIcons, 'width')