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'
9 ActivityMagnetUrlObject,
10 ActivityPlaylistSegmentHashesObject,
11 ActivityPlaylistUrlObject,
12 ActivitypubHttpFetcherPayload,
15 ActivityVideoUrlObject,
17 } from '../../../shared/index'
18 import { VideoTorrentObject } 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 { TagModel } from '../../models/video/tag'
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 { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
71 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
72 import { getOrCreateActorAndServerAndModel } from './actor'
73 import { crawlCollectionPage } from './crawl'
74 import { sendCreateVideo, sendUpdateVideo } from './send'
75 import { addVideoShares, shareVideoByServerAndChannel } from './share'
76 import { addVideoComments } from './video-comments'
77 import { createRates } from './video-rates'
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
278 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
280 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
282 return { video: videoCreated, created: true, autoBlacklisted }
284 // Maybe a concurrent getOrCreateVideoAndAccountAndChannel call created this video
285 if (err.name === 'SequelizeUniqueConstraintError') {
286 const fallbackVideo = await fetchVideoByUrl(videoUrl, fetchType)
287 if (fallbackVideo) return { video: fallbackVideo, created: false }
294 async function updateVideoFromAP (options: {
295 video: MVideoAccountLightBlacklistAllFiles
296 videoObject: VideoTorrentObject
297 account: MAccountIdActor
298 channel: MChannelDefault
299 overrideTo?: string[]
301 const { video, videoObject, account, channel, overrideTo } = options
303 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
305 let videoFieldsSave: any
306 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
307 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
310 let thumbnailModel: MThumbnail
313 thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
315 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
318 const videoUpdated = await sequelizeTypescript.transaction(async t => {
319 const sequelizeOptions = { transaction: t }
321 videoFieldsSave = video.toJSON()
323 // Check actor has the right to update the video
324 const videoChannel = video.VideoChannel
325 if (videoChannel.Account.id !== account.id) {
326 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
329 const to = overrideTo || videoObject.to
330 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
331 video.name = videoData.name
332 video.uuid = videoData.uuid
333 video.url = videoData.url
334 video.category = videoData.category
335 video.licence = videoData.licence
336 video.language = videoData.language
337 video.description = videoData.description
338 video.support = videoData.support
339 video.nsfw = videoData.nsfw
340 video.commentsEnabled = videoData.commentsEnabled
341 video.downloadEnabled = videoData.downloadEnabled
342 video.waitTranscoding = videoData.waitTranscoding
343 video.state = videoData.state
344 video.duration = videoData.duration
345 video.createdAt = videoData.createdAt
346 video.publishedAt = videoData.publishedAt
347 video.originallyPublishedAt = videoData.originallyPublishedAt
348 video.privacy = videoData.privacy
349 video.channelId = videoData.channelId
350 video.views = videoData.views
352 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
354 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
356 if (videoUpdated.getPreview()) {
357 const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
358 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
359 await videoUpdated.addAndSaveThumbnail(previewModel, t)
363 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
364 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
366 // Remove video files that do not exist anymore
367 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
368 await Promise.all(destroyTasks)
370 // Update or add other one
371 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
372 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
376 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
377 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
379 // Remove video playlists that do not exist anymore
380 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
381 await Promise.all(destroyTasks)
383 let oldStreamingPlaylistFiles: MVideoFile[] = []
384 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
385 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
388 videoUpdated.VideoStreamingPlaylists = []
390 for (const playlistAttributes of streamingPlaylistAttributes) {
391 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
392 .then(([ streamingPlaylist ]) => streamingPlaylist)
394 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
395 .map(a => new VideoFileModel(a))
396 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
397 await Promise.all(destroyTasks)
399 // Update or add other one
400 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
401 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
403 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
409 const tags = videoObject.tag
410 .filter(isAPHashTagObject)
411 .map(tag => tag.name)
412 const tagInstances = await TagModel.findOrCreateTags(tags, t)
413 await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
418 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
420 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
421 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
423 await Promise.all(videoCaptionsPromises)
429 await autoBlacklistVideoIfNeeded({
434 transaction: undefined
437 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
439 logger.info('Remote video with uuid %s updated', videoObject.uuid)
443 if (video !== undefined && videoFieldsSave !== undefined) {
444 resetSequelizeInstance(video, videoFieldsSave)
447 // This is just a debug because we will retry the insert
448 logger.debug('Cannot update the remote video.', { err })
453 async function refreshVideoIfNeeded (options: {
454 video: MVideoThumbnail
455 fetchedType: VideoFetchByUrlType
457 }): Promise<MVideoThumbnail> {
458 if (!options.video.isOutdated()) return options.video
460 // We need more attributes if the argument video was fetched with not enough joints
461 const video = options.fetchedType === 'all'
462 ? options.video as MVideoAccountLightBlacklistAllFiles
463 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
466 const { response, videoObject } = await fetchRemoteVideo(video.url)
467 if (response.statusCode === 404) {
468 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
470 // Video does not exist anymore
471 await video.destroy()
475 if (videoObject === undefined) {
476 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
478 await video.setAsRefreshed()
482 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
484 const updateOptions = {
487 account: channelActor.VideoChannel.Account,
488 channel: channelActor.VideoChannel
490 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
491 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
493 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
497 logger.warn('Cannot refresh video %s.', options.video.url, { err })
499 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
501 // Don't refresh in loop
502 await video.setAsRefreshed()
509 refreshVideoIfNeeded,
510 federateVideoIfNeeded,
512 getOrCreateVideoAndAccountAndChannel,
513 fetchRemoteVideoDescription,
514 getOrCreateVideoChannelFromVideoObject
517 // ---------------------------------------------------------------------------
519 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
520 const urlMediaType = url.mediaType
522 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
525 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
526 return url && url.mediaType === 'application/x-mpegURL'
529 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
530 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
533 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
534 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
537 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
538 return url && url.type === 'Hashtag'
541 async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAccountLight, waitThumbnail = false) {
542 logger.debug('Adding remote video %s.', videoObject.id)
544 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
545 const video = VideoModel.build(videoData) as MVideoThumbnail
547 const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
549 logger.error('Cannot create miniature from url.', { err })
553 let thumbnailModel: MThumbnail
554 if (waitThumbnail === true) {
555 thumbnailModel = await promiseThumbnail
558 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
559 const sequelizeOptions = { transaction: t }
561 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
562 videoCreated.VideoChannel = channel
564 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
566 const previewIcon = getPreviewFromIcons(videoObject)
567 const previewUrl = previewIcon
569 : buildRemoteVideoBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
570 const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
572 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
575 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
577 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
578 const videoFiles = await Promise.all(videoFilePromises)
580 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
581 videoCreated.VideoStreamingPlaylists = []
583 for (const playlistAttributes of streamingPlaylistsAttributes) {
584 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
586 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
587 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
588 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
590 videoCreated.VideoStreamingPlaylists.push(playlistModel)
594 const tags = videoObject.tag
595 .filter(isAPHashTagObject)
597 const tagInstances = await TagModel.findOrCreateTags(tags, t)
598 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
601 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
602 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
604 await Promise.all(videoCaptionsPromises)
606 videoCreated.VideoFiles = videoFiles
607 videoCreated.Tags = tagInstances
609 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
617 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
619 return { autoBlacklisted, videoCreated }
622 if (waitThumbnail === false) {
623 // Error is already caught above
624 // eslint-disable-next-line @typescript-eslint/no-floating-promises
625 promiseThumbnail.then(thumbnailModel => {
626 if (!thumbnailModel) return
628 thumbnailModel = videoCreated.id
630 return thumbnailModel.save()
634 return { autoBlacklisted, videoCreated }
637 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) {
638 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
639 ? VideoPrivacy.PUBLIC
640 : VideoPrivacy.UNLISTED
642 const duration = videoObject.duration.replace(/[^\d]+/, '')
643 const language = videoObject.language?.identifier
645 const category = videoObject.category
646 ? parseInt(videoObject.category.identifier, 10)
649 const licence = videoObject.licence
650 ? parseInt(videoObject.licence.identifier, 10)
653 const description = videoObject.content || null
654 const support = videoObject.support || null
657 name: videoObject.name,
658 uuid: videoObject.uuid,
665 nsfw: videoObject.sensitive,
666 commentsEnabled: videoObject.commentsEnabled,
667 downloadEnabled: videoObject.downloadEnabled,
668 waitTranscoding: videoObject.waitTranscoding,
669 state: videoObject.state,
670 channelId: videoChannel.id,
671 duration: parseInt(duration, 10),
672 createdAt: new Date(videoObject.published),
673 publishedAt: new Date(videoObject.published),
675 originallyPublishedAt: videoObject.originallyPublishedAt
676 ? new Date(videoObject.originallyPublishedAt)
679 updatedAt: new Date(videoObject.updated),
680 views: videoObject.views,
688 function videoFileActivityUrlToDBAttributes (
689 videoOrPlaylist: MVideo | MStreamingPlaylist,
690 urls: (ActivityTagObject | ActivityUrlObject)[]
692 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
694 if (fileUrls.length === 0) return []
696 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
697 for (const fileUrl of fileUrls) {
698 // Fetch associated magnet uri
699 const magnet = urls.filter(isAPMagnetUrlObject)
700 .find(u => u.height === fileUrl.height)
702 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
704 const parsed = magnetUtil.decode(magnet.href)
705 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
706 throw new Error('Cannot parse magnet URI ' + magnet.href)
709 // Fetch associated metadata url, if any
710 const metadata = urls.filter(isAPVideoFileMetadataObject)
712 return u.height === fileUrl.height &&
713 u.fps === fileUrl.fps &&
714 u.rel.includes(fileUrl.mediaType)
717 const mediaType = fileUrl.mediaType
719 extname: getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, mediaType),
720 infoHash: parsed.infoHash,
721 resolution: fileUrl.height,
723 fps: fileUrl.fps || -1,
724 metadataUrl: metadata?.href,
726 // This is a video file owned by a video or by a streaming playlist
727 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
728 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
731 attributes.push(attribute)
737 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoTorrentObject, videoFiles: MVideoFile[]) {
738 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
739 if (playlistUrls.length === 0) return []
741 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
742 for (const playlistUrlObject of playlistUrls) {
743 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
745 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
747 // FIXME: backward compatibility introduced in v2.1.0
748 if (files.length === 0) files = videoFiles
750 if (!segmentsSha256UrlObject) {
751 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
756 type: VideoStreamingPlaylistType.HLS,
757 playlistUrl: playlistUrlObject.href,
758 segmentsSha256Url: segmentsSha256UrlObject.href,
759 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
760 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
762 tagAPObject: playlistUrlObject.tag
765 attributes.push(attribute)
771 function getThumbnailFromIcons (videoObject: VideoTorrentObject) {
772 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
773 // Fallback if there are not valid icons
774 if (validIcons.length === 0) validIcons = videoObject.icon
776 return minBy(validIcons, 'width')
779 function getPreviewFromIcons (videoObject: VideoTorrentObject) {
780 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
782 // FIXME: don't put a fallback here for compatibility with PeerTube <2.2
784 return maxBy(validIcons, 'width')