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,
64 } from '../../types/models'
65 import { MThumbnail } from '../../types/models/video/thumbnail'
66 import { FilteredModelAttributes } from '../../types/sequelize'
67 import { ActorFollowScoreCache } from '../files-cache'
68 import { JobQueue } from '../job-queue'
69 import { Notifier } from '../notifier'
70 import { PeerTubeSocket } from '../peertube-socket'
71 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
72 import { setVideoTags } from '../video'
73 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
74 import { getOrCreateActorAndServerAndModel } from './actor'
75 import { crawlCollectionPage } from './crawl'
76 import { sendCreateVideo, sendUpdateVideo } from './send'
77 import { addVideoShares, shareVideoByServerAndChannel } from './share'
78 import { addVideoComments } from './video-comments'
79 import { createRates } from './video-rates'
81 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
82 const video = videoArg as MVideoAP
85 // Check this is not a blacklisted video, or unfederated blacklisted video
86 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
87 // Check the video is public/unlisted and published
88 video.hasPrivacyForFederation() && video.hasStateForFederation()
90 // Fetch more attributes that we will need to serialize in AP object
91 if (isArray(video.VideoCaptions) === false) {
92 video.VideoCaptions = await video.$get('VideoCaptions', {
93 attributes: [ 'language' ],
99 // Now we'll add the video's meta data to our followers
100 await sendCreateVideo(video, transaction)
101 await shareVideoByServerAndChannel(video, transaction)
103 await sendUpdateVideo(video, transaction)
108 async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoObject }> {
116 logger.info('Fetching remote video %s.', videoUrl)
118 const { response, body } = await doRequest<any>(options)
120 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
121 logger.debug('Remote video JSON is not valid.', { body })
122 return { response, videoObject: undefined }
125 return { response, videoObject: body }
128 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
129 const host = video.VideoChannel.Account.Actor.Server.host
130 const path = video.getDescriptionAPIPath()
132 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
136 const { body } = await doRequest<any>(options)
137 return body.description ? body.description : ''
140 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoObject) {
141 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
142 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
144 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
145 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
148 return getOrCreateActorAndServerAndModel(channel.id, 'all')
157 refreshVideo?: boolean
159 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoObject, syncParam: SyncParam) {
160 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
162 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
164 if (syncParam.likes === true) {
165 const handler = items => createRates(items, video, 'like')
166 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
168 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
169 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
171 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
174 if (syncParam.dislikes === true) {
175 const handler = items => createRates(items, video, 'dislike')
176 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
178 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
179 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
181 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
184 if (syncParam.shares === true) {
185 const handler = items => addVideoShares(items, video)
186 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
188 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
189 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
191 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
194 if (syncParam.comments === true) {
195 const handler = items => addVideoComments(items)
196 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
198 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
199 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
201 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
204 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
207 type GetVideoResult <T> = Promise<{
210 autoBlacklisted?: boolean
213 type GetVideoParamAll = {
214 videoObject: { id: string } | string
215 syncParam?: SyncParam
217 allowRefresh?: boolean
220 type GetVideoParamImmutable = {
221 videoObject: { id: string } | string
222 syncParam?: SyncParam
223 fetchType: 'only-immutable-attributes'
227 type GetVideoParamOther = {
228 videoObject: { id: string } | string
229 syncParam?: SyncParam
230 fetchType?: 'all' | 'only-video'
231 allowRefresh?: boolean
234 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
235 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
236 function getOrCreateVideoAndAccountAndChannel (
237 options: GetVideoParamOther
238 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
239 async function getOrCreateVideoAndAccountAndChannel (
240 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
241 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
243 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
244 const fetchType = options.fetchType || 'all'
245 const allowRefresh = options.allowRefresh !== false
248 const videoUrl = getAPId(options.videoObject)
249 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
251 if (videoFromDatabase) {
252 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
253 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
254 const refreshOptions = {
255 video: videoFromDatabase as MVideoThumbnail,
256 fetchedType: fetchType,
260 if (syncParam.refreshVideo === true) {
261 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
263 await JobQueue.Instance.createJobWithPromise({
264 type: 'activitypub-refresher',
265 payload: { type: 'video', url: videoFromDatabase.url }
270 return { video: videoFromDatabase, created: false }
273 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
274 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
276 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
277 const videoChannel = actor.VideoChannel
280 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
282 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
284 return { video: videoCreated, created: true, autoBlacklisted }
286 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
287 if (err.name === 'SequelizeUniqueConstraintError') {
288 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
289 if (fallbackVideo) return { video: fallbackVideo, created: false }
296 async function updateVideoFromAP (options: {
297 video: MVideoAccountLightBlacklistAllFiles
298 videoObject: VideoObject
299 account: MAccountIdActor
300 channel: MChannelDefault
301 overrideTo?: string[]
303 const { video, videoObject, account, channel, overrideTo } = options
305 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { videoObject: options.videoObject, account, channel })
307 let videoFieldsSave: any
308 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
309 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
312 let thumbnailModel: MThumbnail
315 thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
317 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
320 const videoUpdated = await sequelizeTypescript.transaction(async t => {
321 const sequelizeOptions = { transaction: t }
323 videoFieldsSave = video.toJSON()
325 // Check actor has the right to update the video
326 const videoChannel = video.VideoChannel
327 if (videoChannel.Account.id !== account.id) {
328 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
331 const to = overrideTo || videoObject.to
332 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
333 video.name = videoData.name
334 video.uuid = videoData.uuid
335 video.url = videoData.url
336 video.category = videoData.category
337 video.licence = videoData.licence
338 video.language = videoData.language
339 video.description = videoData.description
340 video.support = videoData.support
341 video.nsfw = videoData.nsfw
342 video.commentsEnabled = videoData.commentsEnabled
343 video.downloadEnabled = videoData.downloadEnabled
344 video.waitTranscoding = videoData.waitTranscoding
345 video.state = videoData.state
346 video.duration = videoData.duration
347 video.createdAt = videoData.createdAt
348 video.publishedAt = videoData.publishedAt
349 video.originallyPublishedAt = videoData.originallyPublishedAt
350 video.privacy = videoData.privacy
351 video.channelId = videoData.channelId
352 video.views = videoData.views
353 video.isLive = videoData.isLive
355 // Ensures we update the updated video attribute
356 video.changed('updatedAt', true)
358 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
360 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
362 if (videoUpdated.getPreview()) {
363 const previewUrl = getPreviewUrl(getPreviewFromIcons(videoObject), video)
364 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
365 await videoUpdated.addAndSaveThumbnail(previewModel, t)
369 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
370 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
372 // Remove video files that do not exist anymore
373 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
374 await Promise.all(destroyTasks)
376 // Update or add other one
377 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
378 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
382 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
383 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
385 // Remove video playlists that do not exist anymore
386 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
387 await Promise.all(destroyTasks)
389 let oldStreamingPlaylistFiles: MVideoFile[] = []
390 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
391 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
394 videoUpdated.VideoStreamingPlaylists = []
396 for (const playlistAttributes of streamingPlaylistAttributes) {
397 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
398 .then(([ streamingPlaylist ]) => streamingPlaylist)
400 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
401 .map(a => new VideoFileModel(a))
402 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
403 await Promise.all(destroyTasks)
405 // Update or add other one
406 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
407 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
409 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
415 const tags = videoObject.tag
416 .filter(isAPHashTagObject)
417 .map(tag => tag.name)
418 await setVideoTags({ video: videoUpdated, tags, transaction: t, defaultValue: videoUpdated.Tags })
423 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
425 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
426 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
428 await Promise.all(videoCaptionsPromises)
432 // Create or update existing live
434 const [ videoLive ] = await VideoLiveModel.upsert({
435 saveReplay: videoObject.liveSaveReplay,
436 permanentLive: videoObject.permanentLive,
438 }, { transaction: t, returning: true })
440 videoUpdated.VideoLive = videoLive
441 } else { // Delete existing live if it exists
442 await VideoLiveModel.destroy({
449 videoUpdated.VideoLive = null
456 await autoBlacklistVideoIfNeeded({
461 transaction: undefined
465 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated)
467 if (videoUpdated.isLive) {
468 PeerTubeSocket.Instance.sendVideoLiveNewState(videoUpdated)
469 PeerTubeSocket.Instance.sendVideoViewsUpdate(videoUpdated)
472 logger.info('Remote video with uuid %s updated', videoObject.uuid)
476 if (video !== undefined && videoFieldsSave !== undefined) {
477 resetSequelizeInstance(video, videoFieldsSave)
480 // This is just a debug because we will retry the insert
481 logger.debug('Cannot update the remote video.', { err })
486 async function refreshVideoIfNeeded (options: {
487 video: MVideoThumbnail
488 fetchedType: VideoFetchByUrlType
490 }): Promise<MVideoThumbnail> {
491 if (!options.video.isOutdated()) return options.video
493 // We need more attributes if the argument video was fetched with not enough joints
494 const video = options.fetchedType === 'all'
495 ? options.video as MVideoAccountLightBlacklistAllFiles
496 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
499 const { response, videoObject } = await fetchRemoteVideo(video.url)
500 if (response.statusCode === HttpStatusCode.NOT_FOUND_404) {
501 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
503 // Video does not exist anymore
504 await video.destroy()
508 if (videoObject === undefined) {
509 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
511 await video.setAsRefreshed()
515 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
517 const updateOptions = {
520 account: channelActor.VideoChannel.Account,
521 channel: channelActor.VideoChannel
523 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
524 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
526 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
530 logger.warn('Cannot refresh video %s.', options.video.url, { err })
532 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
534 // Don't refresh in loop
535 await video.setAsRefreshed()
542 refreshVideoIfNeeded,
543 federateVideoIfNeeded,
545 getOrCreateVideoAndAccountAndChannel,
546 fetchRemoteVideoDescription,
547 getOrCreateVideoChannelFromVideoObject
550 // ---------------------------------------------------------------------------
552 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
553 const urlMediaType = url.mediaType
555 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
558 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
559 return url && url.mediaType === 'application/x-mpegURL'
562 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
563 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
566 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
567 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
570 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
571 return url && url.type === 'Hashtag'
574 async function createVideo (videoObject: VideoObject, channel: MChannelAccountLight, waitThumbnail = false) {
575 logger.debug('Adding remote video %s.', videoObject.id)
577 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
578 const video = VideoModel.build(videoData) as MVideoThumbnail
580 const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
582 logger.error('Cannot create miniature from url.', { err })
586 let thumbnailModel: MThumbnail
587 if (waitThumbnail === true) {
588 thumbnailModel = await promiseThumbnail
591 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
592 const sequelizeOptions = { transaction: t }
594 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
595 videoCreated.VideoChannel = channel
597 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
599 const previewIcon = getPreviewFromIcons(videoObject)
600 const previewUrl = getPreviewUrl(previewIcon, videoCreated)
601 const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
603 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
606 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
608 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
609 const videoFiles = await Promise.all(videoFilePromises)
611 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
612 videoCreated.VideoStreamingPlaylists = []
614 for (const playlistAttributes of streamingPlaylistsAttributes) {
615 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
617 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
618 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
619 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
621 videoCreated.VideoStreamingPlaylists.push(playlistModel)
625 const tags = videoObject.tag
626 .filter(isAPHashTagObject)
628 await setVideoTags({ video: videoCreated, tags, transaction: t })
631 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
632 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
634 await Promise.all(videoCaptionsPromises)
636 videoCreated.VideoFiles = videoFiles
638 if (videoCreated.isLive) {
639 const videoLive = new VideoLiveModel({
641 saveReplay: videoObject.liveSaveReplay,
642 permanentLive: videoObject.permanentLive,
643 videoId: videoCreated.id
646 videoCreated.VideoLive = await videoLive.save({ transaction: t })
649 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
657 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
659 return { autoBlacklisted, videoCreated }
662 if (waitThumbnail === false) {
663 // Error is already caught above
664 // eslint-disable-next-line @typescript-eslint/no-floating-promises
665 promiseThumbnail.then(thumbnailModel => {
666 if (!thumbnailModel) return
668 thumbnailModel = videoCreated.id
670 return thumbnailModel.save()
674 return { autoBlacklisted, videoCreated }
677 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
678 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
679 ? VideoPrivacy.PUBLIC
680 : VideoPrivacy.UNLISTED
682 const duration = videoObject.duration.replace(/[^\d]+/, '')
683 const language = videoObject.language?.identifier
685 const category = videoObject.category
686 ? parseInt(videoObject.category.identifier, 10)
689 const licence = videoObject.licence
690 ? parseInt(videoObject.licence.identifier, 10)
693 const description = videoObject.content || null
694 const support = videoObject.support || null
697 name: videoObject.name,
698 uuid: videoObject.uuid,
705 nsfw: videoObject.sensitive,
706 commentsEnabled: videoObject.commentsEnabled,
707 downloadEnabled: videoObject.downloadEnabled,
708 waitTranscoding: videoObject.waitTranscoding,
709 isLive: videoObject.isLiveBroadcast,
710 state: videoObject.state,
711 channelId: videoChannel.id,
712 duration: parseInt(duration, 10),
713 createdAt: new Date(videoObject.published),
714 publishedAt: new Date(videoObject.published),
716 originallyPublishedAt: videoObject.originallyPublishedAt
717 ? new Date(videoObject.originallyPublishedAt)
720 updatedAt: new Date(videoObject.updated),
721 views: videoObject.views,
729 function videoFileActivityUrlToDBAttributes (
730 videoOrPlaylist: MVideo | MStreamingPlaylist,
731 urls: (ActivityTagObject | ActivityUrlObject)[]
733 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
735 if (fileUrls.length === 0) return []
737 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
738 for (const fileUrl of fileUrls) {
739 // Fetch associated magnet uri
740 const magnet = urls.filter(isAPMagnetUrlObject)
741 .find(u => u.height === fileUrl.height)
743 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
745 const parsed = magnetUtil.decode(magnet.href)
746 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
747 throw new Error('Cannot parse magnet URI ' + magnet.href)
750 // Fetch associated metadata url, if any
751 const metadata = urls.filter(isAPVideoFileMetadataObject)
753 return u.height === fileUrl.height &&
754 u.fps === fileUrl.fps &&
755 u.rel.includes(fileUrl.mediaType)
758 const mediaType = fileUrl.mediaType
760 extname: getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, mediaType),
761 infoHash: parsed.infoHash,
762 resolution: fileUrl.height,
764 fps: fileUrl.fps || -1,
765 metadataUrl: metadata?.href,
767 // This is a video file owned by a video or by a streaming playlist
768 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
769 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
772 attributes.push(attribute)
778 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
779 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
780 if (playlistUrls.length === 0) return []
782 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
783 for (const playlistUrlObject of playlistUrls) {
784 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
786 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
788 // FIXME: backward compatibility introduced in v2.1.0
789 if (files.length === 0) files = videoFiles
791 if (!segmentsSha256UrlObject) {
792 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
797 type: VideoStreamingPlaylistType.HLS,
798 playlistUrl: playlistUrlObject.href,
799 segmentsSha256Url: segmentsSha256UrlObject.href,
800 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
801 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
803 tagAPObject: playlistUrlObject.tag
806 attributes.push(attribute)
812 function getThumbnailFromIcons (videoObject: VideoObject) {
813 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
814 // Fallback if there are not valid icons
815 if (validIcons.length === 0) validIcons = videoObject.icon
817 return minBy(validIcons, 'width')
820 function getPreviewFromIcons (videoObject: VideoObject) {
821 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
823 return maxBy(validIcons, 'width')
826 function getPreviewUrl (previewIcon: ActivityIconObject, video: MVideoAccountLight) {
829 : buildRemoteVideoBaseUrl(video, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))