1 import * as Bluebird from 'bluebird'
2 import * as sequelize from 'sequelize'
3 import * as magnetUtil from 'magnet-uri'
4 import * as request from 'request'
7 ActivityMagnetUrlObject,
8 ActivityPlaylistSegmentHashesObject,
9 ActivityPlaylistUrlObject,
12 ActivityVideoUrlObject,
14 } from '../../../shared/index'
15 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
16 import { VideoPrivacy } from '../../../shared/models/videos'
17 import { isAPVideoFileMetadataObject, sanitizeAndCheckVideoTorrentObject } from '../../helpers/custom-validators/activitypub/videos'
18 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
19 import { deleteNonExistingModels, resetSequelizeInstance, retryTransactionWrapper } from '../../helpers/database-utils'
20 import { logger } from '../../helpers/logger'
21 import { doRequest } from '../../helpers/requests'
25 P2P_MEDIA_LOADER_PEER_VERSION,
30 } from '../../initializers/constants'
31 import { TagModel } from '../../models/video/tag'
32 import { VideoModel } from '../../models/video/video'
33 import { VideoFileModel } from '../../models/video/video-file'
34 import { getOrCreateActorAndServerAndModel } from './actor'
35 import { addVideoComments } from './video-comments'
36 import { crawlCollectionPage } from './crawl'
37 import { sendCreateVideo, sendUpdateVideo } from './send'
38 import { isArray } from '../../helpers/custom-validators/misc'
39 import { VideoCaptionModel } from '../../models/video/video-caption'
40 import { JobQueue } from '../job-queue'
41 import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher'
42 import { createRates } from './video-rates'
43 import { addVideoShares, shareVideoByServerAndChannel } from './share'
44 import { fetchVideoByUrl, VideoFetchByUrlType } from '../../helpers/video'
45 import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
46 import { Notifier } from '../notifier'
47 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
48 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
49 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
50 import { VideoShareModel } from '../../models/video/video-share'
51 import { VideoCommentModel } from '../../models/video/video-comment'
52 import { sequelizeTypescript } from '../../initializers/database'
53 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
54 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
55 import { join } from 'path'
56 import { FilteredModelAttributes } from '../../typings/sequelize'
57 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
58 import { ActorFollowScoreCache } from '../files-cache'
67 MVideoAccountLightBlacklistAllFiles,
69 MVideoAPWithoutCaption,
75 } from '../../typings/models'
76 import { MThumbnail } from '../../typings/models/video/thumbnail'
77 import { maxBy, minBy } from 'lodash'
79 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
80 const video = videoArg as MVideoAP
83 // Check this is not a blacklisted video, or unfederated blacklisted video
84 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
85 // Check the video is public/unlisted and published
86 video.hasPrivacyForFederation() && video.state === VideoState.PUBLISHED
88 // Fetch more attributes that we will need to serialize in AP object
89 if (isArray(video.VideoCaptions) === false) {
90 video.VideoCaptions = await video.$get('VideoCaptions', {
91 attributes: [ 'language' ],
97 // Now we'll add the video's meta data to our followers
98 await sendCreateVideo(video, transaction)
99 await shareVideoByServerAndChannel(video, transaction)
101 await sendUpdateVideo(video, transaction)
106 async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoTorrentObject }> {
114 logger.info('Fetching remote video %s.', videoUrl)
116 const { response, body } = await doRequest<any>(options)
118 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
119 logger.debug('Remote video JSON is not valid.', { body })
120 return { response, videoObject: undefined }
123 return { response, videoObject: body }
126 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
127 const host = video.VideoChannel.Account.Actor.Server.host
128 const path = video.getDescriptionAPIPath()
130 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
134 const { body } = await doRequest<any>(options)
135 return body.description ? body.description : ''
138 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoTorrentObject) {
139 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
140 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
142 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
143 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
146 return getOrCreateActorAndServerAndModel(channel.id, 'all')
155 refreshVideo?: boolean
157 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoTorrentObject, syncParam: SyncParam) {
158 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
160 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
162 if (syncParam.likes === true) {
163 const handler = items => createRates(items, video, 'like')
164 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
166 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
167 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
169 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
172 if (syncParam.dislikes === true) {
173 const handler = items => createRates(items, video, 'dislike')
174 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
176 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
177 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
179 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
182 if (syncParam.shares === true) {
183 const handler = items => addVideoShares(items, video)
184 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
186 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
187 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
189 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
192 if (syncParam.comments === true) {
193 const handler = items => addVideoComments(items)
194 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
196 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
197 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
199 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
202 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
205 type GetVideoResult <T> = Promise<{
208 autoBlacklisted?: boolean
211 type GetVideoParamAll = {
212 videoObject: { id: string } | string
213 syncParam?: SyncParam
215 allowRefresh?: boolean
218 type GetVideoParamImmutable = {
219 videoObject: { id: string } | string
220 syncParam?: SyncParam
221 fetchType: 'only-immutable-attributes'
225 type GetVideoParamOther = {
226 videoObject: { id: string } | string
227 syncParam?: SyncParam
228 fetchType?: 'all' | 'only-video'
229 allowRefresh?: boolean
232 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamAll): GetVideoResult<MVideoAccountLightBlacklistAllFiles>
233 function getOrCreateVideoAndAccountAndChannel (options: GetVideoParamImmutable): GetVideoResult<MVideoImmutable>
234 function getOrCreateVideoAndAccountAndChannel (
235 options: GetVideoParamOther
236 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail>
237 async function getOrCreateVideoAndAccountAndChannel (
238 options: GetVideoParamAll | GetVideoParamImmutable | GetVideoParamOther
239 ): GetVideoResult<MVideoAccountLightBlacklistAllFiles | MVideoThumbnail | MVideoImmutable> {
241 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
242 const fetchType = options.fetchType || 'all'
243 const allowRefresh = options.allowRefresh !== false
246 const videoUrl = getAPId(options.videoObject)
247 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
249 if (videoFromDatabase) {
250 // If allowRefresh is true, we could not call this function using 'only-immutable-attributes' fetch type
251 if (allowRefresh === true && (videoFromDatabase as MVideoThumbnail).isOutdated()) {
252 const refreshOptions = {
253 video: videoFromDatabase as MVideoThumbnail,
254 fetchedType: fetchType,
258 if (syncParam.refreshVideo === true) {
259 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
261 await JobQueue.Instance.createJobWithPromise({
262 type: 'activitypub-refresher',
263 payload: { type: 'video', url: videoFromDatabase.url }
268 return { video: videoFromDatabase, created: false }
271 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
272 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
274 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
275 const videoChannel = actor.VideoChannel
276 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
278 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
280 return { video: videoCreated, created: true, autoBlacklisted }
283 async function updateVideoFromAP (options: {
284 video: MVideoAccountLightBlacklistAllFiles
285 videoObject: VideoTorrentObject
286 account: MAccountIdActor
287 channel: MChannelDefault
288 overrideTo?: string[]
290 const { video, videoObject, account, channel, overrideTo } = options
292 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
294 let videoFieldsSave: any
295 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
296 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
299 let thumbnailModel: MThumbnail
302 thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
304 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
307 const videoUpdated = await sequelizeTypescript.transaction(async t => {
308 const sequelizeOptions = { transaction: t }
310 videoFieldsSave = video.toJSON()
312 // Check actor has the right to update the video
313 const videoChannel = video.VideoChannel
314 if (videoChannel.Account.id !== account.id) {
315 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
318 const to = overrideTo || videoObject.to
319 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
320 video.name = videoData.name
321 video.uuid = videoData.uuid
322 video.url = videoData.url
323 video.category = videoData.category
324 video.licence = videoData.licence
325 video.language = videoData.language
326 video.description = videoData.description
327 video.support = videoData.support
328 video.nsfw = videoData.nsfw
329 video.commentsEnabled = videoData.commentsEnabled
330 video.downloadEnabled = videoData.downloadEnabled
331 video.waitTranscoding = videoData.waitTranscoding
332 video.state = videoData.state
333 video.duration = videoData.duration
334 video.createdAt = videoData.createdAt
335 video.publishedAt = videoData.publishedAt
336 video.originallyPublishedAt = videoData.originallyPublishedAt
337 video.privacy = videoData.privacy
338 video.channelId = videoData.channelId
339 video.views = videoData.views
341 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
343 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
345 if (videoUpdated.getPreview()) {
346 const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
347 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
348 await videoUpdated.addAndSaveThumbnail(previewModel, t)
352 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
353 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
355 // Remove video files that do not exist anymore
356 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
357 await Promise.all(destroyTasks)
359 // Update or add other one
360 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
361 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
365 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
366 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
368 // Remove video playlists that do not exist anymore
369 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
370 await Promise.all(destroyTasks)
372 let oldStreamingPlaylistFiles: MVideoFile[] = []
373 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
374 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
377 videoUpdated.VideoStreamingPlaylists = []
379 for (const playlistAttributes of streamingPlaylistAttributes) {
380 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
381 .then(([ streamingPlaylist ]) => streamingPlaylist)
383 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
384 .map(a => new VideoFileModel(a))
385 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
386 await Promise.all(destroyTasks)
388 // Update or add other one
389 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
390 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
392 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
398 const tags = videoObject.tag
399 .filter(isAPHashTagObject)
400 .map(tag => tag.name)
401 const tagInstances = await TagModel.findOrCreateTags(tags, t)
402 await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
407 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
409 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
410 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
412 await Promise.all(videoCaptionsPromises)
418 await autoBlacklistVideoIfNeeded({
423 transaction: undefined
426 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
428 logger.info('Remote video with uuid %s updated', videoObject.uuid)
432 if (video !== undefined && videoFieldsSave !== undefined) {
433 resetSequelizeInstance(video, videoFieldsSave)
436 // This is just a debug because we will retry the insert
437 logger.debug('Cannot update the remote video.', { err })
442 async function refreshVideoIfNeeded (options: {
443 video: MVideoThumbnail
444 fetchedType: VideoFetchByUrlType
446 }): Promise<MVideoThumbnail> {
447 if (!options.video.isOutdated()) return options.video
449 // We need more attributes if the argument video was fetched with not enough joints
450 const video = options.fetchedType === 'all'
451 ? options.video as MVideoAccountLightBlacklistAllFiles
452 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
455 const { response, videoObject } = await fetchRemoteVideo(video.url)
456 if (response.statusCode === 404) {
457 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
459 // Video does not exist anymore
460 await video.destroy()
464 if (videoObject === undefined) {
465 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
467 await video.setAsRefreshed()
471 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
473 const updateOptions = {
476 account: channelActor.VideoChannel.Account,
477 channel: channelActor.VideoChannel
479 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
480 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
482 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
486 logger.warn('Cannot refresh video %s.', options.video.url, { err })
488 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
490 // Don't refresh in loop
491 await video.setAsRefreshed()
498 refreshVideoIfNeeded,
499 federateVideoIfNeeded,
501 getOrCreateVideoAndAccountAndChannel,
502 fetchRemoteVideoDescription,
503 getOrCreateVideoChannelFromVideoObject
506 // ---------------------------------------------------------------------------
508 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
509 const mimeTypes = Object.keys(MIMETYPES.VIDEO.MIMETYPE_EXT)
511 const urlMediaType = url.mediaType
512 return mimeTypes.includes(urlMediaType) && urlMediaType.startsWith('video/')
515 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
516 return url && url.mediaType === 'application/x-mpegURL'
519 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
520 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
523 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
524 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
527 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
528 return url && url.type === 'Hashtag'
531 async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAccountLight, waitThumbnail = false) {
532 logger.debug('Adding remote video %s.', videoObject.id)
534 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
535 const video = VideoModel.build(videoData) as MVideoThumbnail
537 const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
539 logger.error('Cannot create miniature from url.', { err })
543 let thumbnailModel: MThumbnail
544 if (waitThumbnail === true) {
545 thumbnailModel = await promiseThumbnail
548 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
549 const sequelizeOptions = { transaction: t }
551 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
552 videoCreated.VideoChannel = channel
554 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
556 const previewIcon = getPreviewFromIcons(videoObject)
557 const previewUrl = previewIcon
559 : buildRemoteVideoBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
560 const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
562 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
565 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
567 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
568 const videoFiles = await Promise.all(videoFilePromises)
570 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
571 videoCreated.VideoStreamingPlaylists = []
573 for (const playlistAttributes of streamingPlaylistsAttributes) {
574 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
576 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
577 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
578 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
580 videoCreated.VideoStreamingPlaylists.push(playlistModel)
584 const tags = videoObject.tag
585 .filter(isAPHashTagObject)
587 const tagInstances = await TagModel.findOrCreateTags(tags, t)
588 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
591 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
592 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
594 await Promise.all(videoCaptionsPromises)
596 videoCreated.VideoFiles = videoFiles
597 videoCreated.Tags = tagInstances
599 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
607 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
609 return { autoBlacklisted, videoCreated }
612 if (waitThumbnail === false) {
613 // Error is already caught above
614 // eslint-disable-next-line @typescript-eslint/no-floating-promises
615 promiseThumbnail.then(thumbnailModel => {
616 if (!thumbnailModel) return
618 thumbnailModel = videoCreated.id
620 return thumbnailModel.save()
624 return { autoBlacklisted, videoCreated }
627 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) {
628 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
629 ? VideoPrivacy.PUBLIC
630 : VideoPrivacy.UNLISTED
632 const duration = videoObject.duration.replace(/[^\d]+/, '')
633 const language = videoObject.language?.identifier
635 const category = videoObject.category
636 ? parseInt(videoObject.category.identifier, 10)
639 const licence = videoObject.licence
640 ? parseInt(videoObject.licence.identifier, 10)
643 const description = videoObject.content || null
644 const support = videoObject.support || null
647 name: videoObject.name,
648 uuid: videoObject.uuid,
655 nsfw: videoObject.sensitive,
656 commentsEnabled: videoObject.commentsEnabled,
657 downloadEnabled: videoObject.downloadEnabled,
658 waitTranscoding: videoObject.waitTranscoding,
659 state: videoObject.state,
660 channelId: videoChannel.id,
661 duration: parseInt(duration, 10),
662 createdAt: new Date(videoObject.published),
663 publishedAt: new Date(videoObject.published),
665 originallyPublishedAt: videoObject.originallyPublishedAt
666 ? new Date(videoObject.originallyPublishedAt)
669 updatedAt: new Date(videoObject.updated),
670 views: videoObject.views,
678 function videoFileActivityUrlToDBAttributes (
679 videoOrPlaylist: MVideo | MStreamingPlaylist,
680 urls: (ActivityTagObject | ActivityUrlObject)[]
682 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
684 if (fileUrls.length === 0) return []
686 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
687 for (const fileUrl of fileUrls) {
688 // Fetch associated magnet uri
689 const magnet = urls.filter(isAPMagnetUrlObject)
690 .find(u => u.height === fileUrl.height)
692 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
694 const parsed = magnetUtil.decode(magnet.href)
695 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
696 throw new Error('Cannot parse magnet URI ' + magnet.href)
699 // Fetch associated metadata url, if any
700 const metadata = urls.filter(isAPVideoFileMetadataObject)
702 return u.height === fileUrl.height &&
703 u.fps === fileUrl.fps &&
704 u.rel.includes(fileUrl.mediaType)
707 const mediaType = fileUrl.mediaType
709 extname: MIMETYPES.VIDEO.MIMETYPE_EXT[mediaType],
710 infoHash: parsed.infoHash,
711 resolution: fileUrl.height,
713 fps: fileUrl.fps || -1,
714 metadataUrl: metadata?.href,
716 // This is a video file owned by a video or by a streaming playlist
717 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
718 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
721 attributes.push(attribute)
727 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoTorrentObject, videoFiles: MVideoFile[]) {
728 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
729 if (playlistUrls.length === 0) return []
731 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
732 for (const playlistUrlObject of playlistUrls) {
733 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
735 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
737 // FIXME: backward compatibility introduced in v2.1.0
738 if (files.length === 0) files = videoFiles
740 if (!segmentsSha256UrlObject) {
741 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
746 type: VideoStreamingPlaylistType.HLS,
747 playlistUrl: playlistUrlObject.href,
748 segmentsSha256Url: segmentsSha256UrlObject.href,
749 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
750 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
752 tagAPObject: playlistUrlObject.tag
755 attributes.push(attribute)
761 function getThumbnailFromIcons (videoObject: VideoTorrentObject) {
762 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
763 // Fallback if there are not valid icons
764 if (validIcons.length === 0) validIcons = videoObject.icon
766 return minBy(validIcons, 'width')
769 function getPreviewFromIcons (videoObject: VideoTorrentObject) {
770 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
772 // FIXME: don't put a fallback here for compatibility with PeerTube <2.2
774 return maxBy(validIcons, 'width')