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 { 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,
28 STATIC_PATHS, THUMBNAILS_SIZE
29 } from '../../initializers/constants'
30 import { TagModel } from '../../models/video/tag'
31 import { VideoModel } from '../../models/video/video'
32 import { VideoFileModel } from '../../models/video/video-file'
33 import { getOrCreateActorAndServerAndModel } from './actor'
34 import { addVideoComments } from './video-comments'
35 import { crawlCollectionPage } from './crawl'
36 import { sendCreateVideo, sendUpdateVideo } from './send'
37 import { isArray } from '../../helpers/custom-validators/misc'
38 import { VideoCaptionModel } from '../../models/video/video-caption'
39 import { JobQueue } from '../job-queue'
40 import { ActivitypubHttpFetcherPayload } from '../job-queue/handlers/activitypub-http-fetcher'
41 import { createRates } from './video-rates'
42 import { addVideoShares, shareVideoByServerAndChannel } from './share'
43 import { fetchVideoByUrl, VideoFetchByUrlType } from '../../helpers/video'
44 import { buildRemoteVideoBaseUrl, checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
45 import { Notifier } from '../notifier'
46 import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist'
47 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
48 import { AccountVideoRateModel } from '../../models/account/account-video-rate'
49 import { VideoShareModel } from '../../models/video/video-share'
50 import { VideoCommentModel } from '../../models/video/video-comment'
51 import { sequelizeTypescript } from '../../initializers/database'
52 import { createPlaceholderThumbnail, createVideoMiniatureFromUrl } from '../thumbnail'
53 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
54 import { join } from 'path'
55 import { FilteredModelAttributes } from '../../typings/sequelize'
56 import { autoBlacklistVideoIfNeeded } from '../video-blacklist'
57 import { ActorFollowScoreCache } from '../files-cache'
66 MVideoAccountLightBlacklistAllFiles,
68 MVideoAPWithoutCaption,
73 } from '../../typings/models'
74 import { MThumbnail } from '../../typings/models/video/thumbnail'
75 import { maxBy, minBy } from 'lodash'
77 async function federateVideoIfNeeded (videoArg: MVideoAPWithoutCaption, isNewVideo: boolean, transaction?: sequelize.Transaction) {
78 const video = videoArg as MVideoAP
81 // Check this is not a blacklisted video, or unfederated blacklisted video
82 (video.isBlacklisted() === false || (isNewVideo === false && video.VideoBlacklist.unfederated === false)) &&
83 // Check the video is public/unlisted and published
84 video.hasPrivacyForFederation() && video.state === VideoState.PUBLISHED
86 // Fetch more attributes that we will need to serialize in AP object
87 if (isArray(video.VideoCaptions) === false) {
88 video.VideoCaptions = await video.$get('VideoCaptions', {
89 attributes: [ 'language' ],
95 // Now we'll add the video's meta data to our followers
96 await sendCreateVideo(video, transaction)
97 await shareVideoByServerAndChannel(video, transaction)
99 await sendUpdateVideo(video, transaction)
104 async function fetchRemoteVideo (videoUrl: string): Promise<{ response: request.RequestResponse, videoObject: VideoTorrentObject }> {
112 logger.info('Fetching remote video %s.', videoUrl)
114 const { response, body } = await doRequest(options)
116 if (sanitizeAndCheckVideoTorrentObject(body) === false || checkUrlsSameHost(body.id, videoUrl) !== true) {
117 logger.debug('Remote video JSON is not valid.', { body })
118 return { response, videoObject: undefined }
121 return { response, videoObject: body }
124 async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
125 const host = video.VideoChannel.Account.Actor.Server.host
126 const path = video.getDescriptionAPIPath()
128 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
132 const { body } = await doRequest(options)
133 return body.description ? body.description : ''
136 function getOrCreateVideoChannelFromVideoObject (videoObject: VideoTorrentObject) {
137 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
138 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
140 if (checkUrlsSameHost(channel.id, videoObject.id) !== true) {
141 throw new Error(`Video channel url ${channel.id} does not have the same host than video object id ${videoObject.id}`)
144 return getOrCreateActorAndServerAndModel(channel.id, 'all')
153 refreshVideo?: boolean
155 async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoTorrentObject, syncParam: SyncParam) {
156 logger.info('Adding likes/dislikes/shares/comments of video %s.', video.uuid)
158 const jobPayloads: ActivitypubHttpFetcherPayload[] = []
160 if (syncParam.likes === true) {
161 const handler = items => createRates(items, video, 'like')
162 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate)
164 await crawlCollectionPage<string>(fetchedVideo.likes, handler, cleaner)
165 .catch(err => logger.error('Cannot add likes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.likes }))
167 jobPayloads.push({ uri: fetchedVideo.likes, videoId: video.id, type: 'video-likes' as 'video-likes' })
170 if (syncParam.dislikes === true) {
171 const handler = items => createRates(items, video, 'dislike')
172 const cleaner = crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate)
174 await crawlCollectionPage<string>(fetchedVideo.dislikes, handler, cleaner)
175 .catch(err => logger.error('Cannot add dislikes of video %s.', video.uuid, { err, rootUrl: fetchedVideo.dislikes }))
177 jobPayloads.push({ uri: fetchedVideo.dislikes, videoId: video.id, type: 'video-dislikes' as 'video-dislikes' })
180 if (syncParam.shares === true) {
181 const handler = items => addVideoShares(items, video)
182 const cleaner = crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate)
184 await crawlCollectionPage<string>(fetchedVideo.shares, handler, cleaner)
185 .catch(err => logger.error('Cannot add shares of video %s.', video.uuid, { err, rootUrl: fetchedVideo.shares }))
187 jobPayloads.push({ uri: fetchedVideo.shares, videoId: video.id, type: 'video-shares' as 'video-shares' })
190 if (syncParam.comments === true) {
191 const handler = items => addVideoComments(items)
192 const cleaner = crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
194 await crawlCollectionPage<string>(fetchedVideo.comments, handler, cleaner)
195 .catch(err => logger.error('Cannot add comments of video %s.', video.uuid, { err, rootUrl: fetchedVideo.comments }))
197 jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' })
200 await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }))
203 function getOrCreateVideoAndAccountAndChannel (options: {
204 videoObject: { id: string } | string
205 syncParam?: SyncParam
207 allowRefresh?: boolean
208 }): Promise<{ video: MVideoAccountLightBlacklistAllFiles, created: boolean, autoBlacklisted?: boolean }>
209 function getOrCreateVideoAndAccountAndChannel (options: {
210 videoObject: { id: string } | string
211 syncParam?: SyncParam
212 fetchType?: VideoFetchByUrlType
213 allowRefresh?: boolean
214 }): Promise<{ video: MVideoAccountLightBlacklistAllFiles | MVideoThumbnail, created: boolean, autoBlacklisted?: boolean }>
215 async function getOrCreateVideoAndAccountAndChannel (options: {
216 videoObject: { id: string } | string
217 syncParam?: SyncParam
218 fetchType?: VideoFetchByUrlType
219 allowRefresh?: boolean // true by default
220 }): Promise<{ video: MVideoAccountLightBlacklistAllFiles | MVideoThumbnail, created: boolean, autoBlacklisted?: boolean }> {
222 const syncParam = options.syncParam || { likes: true, dislikes: true, shares: true, comments: true, thumbnail: true, refreshVideo: false }
223 const fetchType = options.fetchType || 'all'
224 const allowRefresh = options.allowRefresh !== false
227 const videoUrl = getAPId(options.videoObject)
229 let videoFromDatabase = await fetchVideoByUrl(videoUrl, fetchType)
230 if (videoFromDatabase) {
231 if (videoFromDatabase.isOutdated() && allowRefresh === true) {
232 const refreshOptions = {
233 video: videoFromDatabase,
234 fetchedType: fetchType,
238 if (syncParam.refreshVideo === true) {
239 videoFromDatabase = await refreshVideoIfNeeded(refreshOptions)
241 await JobQueue.Instance.createJobWithPromise({
242 type: 'activitypub-refresher',
243 payload: { type: 'video', url: videoFromDatabase.url }
248 return { video: videoFromDatabase, created: false }
251 const { videoObject: fetchedVideo } = await fetchRemoteVideo(videoUrl)
252 if (!fetchedVideo) throw new Error('Cannot fetch remote video with url: ' + videoUrl)
254 const actor = await getOrCreateVideoChannelFromVideoObject(fetchedVideo)
255 const videoChannel = actor.VideoChannel
256 const { autoBlacklisted, videoCreated } = await retryTransactionWrapper(createVideo, fetchedVideo, videoChannel, syncParam.thumbnail)
258 await syncVideoExternalAttributes(videoCreated, fetchedVideo, syncParam)
260 return { video: videoCreated, created: true, autoBlacklisted }
263 async function updateVideoFromAP (options: {
264 video: MVideoAccountLightBlacklistAllFiles
265 videoObject: VideoTorrentObject
266 account: MAccountIdActor
267 channel: MChannelDefault
268 overrideTo?: string[]
270 const { video, videoObject, account, channel, overrideTo } = options
272 logger.debug('Updating remote video "%s".', options.videoObject.uuid, { account, channel })
274 let videoFieldsSave: any
275 const wasPrivateVideo = video.privacy === VideoPrivacy.PRIVATE
276 const wasUnlistedVideo = video.privacy === VideoPrivacy.UNLISTED
279 let thumbnailModel: MThumbnail
282 thumbnailModel = await createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
284 logger.warn('Cannot generate thumbnail of %s.', videoObject.id, { err })
287 const videoUpdated = await sequelizeTypescript.transaction(async t => {
288 const sequelizeOptions = { transaction: t }
290 videoFieldsSave = video.toJSON()
292 // Check actor has the right to update the video
293 const videoChannel = video.VideoChannel
294 if (videoChannel.Account.id !== account.id) {
295 throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url)
298 const to = overrideTo || videoObject.to
299 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to)
300 video.name = videoData.name
301 video.uuid = videoData.uuid
302 video.url = videoData.url
303 video.category = videoData.category
304 video.licence = videoData.licence
305 video.language = videoData.language
306 video.description = videoData.description
307 video.support = videoData.support
308 video.nsfw = videoData.nsfw
309 video.commentsEnabled = videoData.commentsEnabled
310 video.downloadEnabled = videoData.downloadEnabled
311 video.waitTranscoding = videoData.waitTranscoding
312 video.state = videoData.state
313 video.duration = videoData.duration
314 video.createdAt = videoData.createdAt
315 video.publishedAt = videoData.publishedAt
316 video.originallyPublishedAt = videoData.originallyPublishedAt
317 video.privacy = videoData.privacy
318 video.channelId = videoData.channelId
319 video.views = videoData.views
321 const videoUpdated = await video.save(sequelizeOptions) as MVideoFullLight
323 if (thumbnailModel) await videoUpdated.addAndSaveThumbnail(thumbnailModel, t)
325 const previewUrl = videoUpdated.getPreview().getFileUrl(videoUpdated)
326 const previewModel = createPlaceholderThumbnail(previewUrl, video, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
327 await videoUpdated.addAndSaveThumbnail(previewModel, t)
330 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoUpdated, videoObject.url)
331 const newVideoFiles = videoFileAttributes.map(a => new VideoFileModel(a))
333 // Remove video files that do not exist anymore
334 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoFiles, newVideoFiles, t)
335 await Promise.all(destroyTasks)
337 // Update or add other one
338 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'video', t))
339 videoUpdated.VideoFiles = await Promise.all(upsertTasks)
343 const streamingPlaylistAttributes = streamingPlaylistActivityUrlToDBAttributes(videoUpdated, videoObject, videoUpdated.VideoFiles)
344 const newStreamingPlaylists = streamingPlaylistAttributes.map(a => new VideoStreamingPlaylistModel(a))
346 // Remove video playlists that do not exist anymore
347 const destroyTasks = deleteNonExistingModels(videoUpdated.VideoStreamingPlaylists, newStreamingPlaylists, t)
348 await Promise.all(destroyTasks)
350 let oldStreamingPlaylistFiles: MVideoFile[] = []
351 for (const videoStreamingPlaylist of videoUpdated.VideoStreamingPlaylists) {
352 oldStreamingPlaylistFiles = oldStreamingPlaylistFiles.concat(videoStreamingPlaylist.VideoFiles)
355 videoUpdated.VideoStreamingPlaylists = []
357 for (const playlistAttributes of streamingPlaylistAttributes) {
358 const streamingPlaylistModel = await VideoStreamingPlaylistModel.upsert(playlistAttributes, { returning: true, transaction: t })
359 .then(([ streamingPlaylist ]) => streamingPlaylist)
361 const newVideoFiles: MVideoFile[] = videoFileActivityUrlToDBAttributes(streamingPlaylistModel, playlistAttributes.tagAPObject)
362 .map(a => new VideoFileModel(a))
363 const destroyTasks = deleteNonExistingModels(oldStreamingPlaylistFiles, newVideoFiles, t)
364 await Promise.all(destroyTasks)
366 // Update or add other one
367 const upsertTasks = newVideoFiles.map(f => VideoFileModel.customUpsert(f, 'streaming-playlist', t))
368 streamingPlaylistModel.VideoFiles = await Promise.all(upsertTasks)
370 videoUpdated.VideoStreamingPlaylists.push(streamingPlaylistModel)
376 const tags = videoObject.tag
377 .filter(isAPHashTagObject)
378 .map(tag => tag.name)
379 const tagInstances = await TagModel.findOrCreateTags(tags, t)
380 await videoUpdated.$set('Tags', tagInstances, sequelizeOptions)
385 await VideoCaptionModel.deleteAllCaptionsOfRemoteVideo(videoUpdated.id, t)
387 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
388 return VideoCaptionModel.insertOrReplaceLanguage(videoUpdated.id, c.identifier, c.url, t)
390 await Promise.all(videoCaptionsPromises)
396 await autoBlacklistVideoIfNeeded({
401 transaction: undefined
404 if (wasPrivateVideo || wasUnlistedVideo) Notifier.Instance.notifyOnNewVideoIfNeeded(videoUpdated) // Notify our users?
406 logger.info('Remote video with uuid %s updated', videoObject.uuid)
410 if (video !== undefined && videoFieldsSave !== undefined) {
411 resetSequelizeInstance(video, videoFieldsSave)
414 // This is just a debug because we will retry the insert
415 logger.debug('Cannot update the remote video.', { err })
420 async function refreshVideoIfNeeded (options: {
421 video: MVideoThumbnail
422 fetchedType: VideoFetchByUrlType
424 }): Promise<MVideoThumbnail> {
425 if (!options.video.isOutdated()) return options.video
427 // We need more attributes if the argument video was fetched with not enough joints
428 const video = options.fetchedType === 'all'
429 ? options.video as MVideoAccountLightBlacklistAllFiles
430 : await VideoModel.loadByUrlAndPopulateAccount(options.video.url)
433 const { response, videoObject } = await fetchRemoteVideo(video.url)
434 if (response.statusCode === 404) {
435 logger.info('Cannot refresh remote video %s: video does not exist anymore. Deleting it.', video.url)
437 // Video does not exist anymore
438 await video.destroy()
442 if (videoObject === undefined) {
443 logger.warn('Cannot refresh remote video %s: invalid body.', video.url)
445 await video.setAsRefreshed()
449 const channelActor = await getOrCreateVideoChannelFromVideoObject(videoObject)
451 const updateOptions = {
454 account: channelActor.VideoChannel.Account,
455 channel: channelActor.VideoChannel
457 await retryTransactionWrapper(updateVideoFromAP, updateOptions)
458 await syncVideoExternalAttributes(video, videoObject, options.syncParam)
460 ActorFollowScoreCache.Instance.addGoodServerId(video.VideoChannel.Actor.serverId)
464 logger.warn('Cannot refresh video %s.', options.video.url, { err })
466 ActorFollowScoreCache.Instance.addBadServerId(video.VideoChannel.Actor.serverId)
468 // Don't refresh in loop
469 await video.setAsRefreshed()
476 refreshVideoIfNeeded,
477 federateVideoIfNeeded,
479 getOrCreateVideoAndAccountAndChannel,
480 fetchRemoteVideoDescription,
481 getOrCreateVideoChannelFromVideoObject
484 // ---------------------------------------------------------------------------
486 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
487 const mimeTypes = Object.keys(MIMETYPES.VIDEO.MIMETYPE_EXT)
489 const urlMediaType = url.mediaType
490 return mimeTypes.indexOf(urlMediaType) !== -1 && urlMediaType.startsWith('video/')
493 function isAPStreamingPlaylistUrlObject (url: ActivityUrlObject): url is ActivityPlaylistUrlObject {
494 return url && url.mediaType === 'application/x-mpegURL'
497 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
498 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
501 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
502 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
505 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
506 return url && url.type === 'Hashtag'
509 async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAccountLight, waitThumbnail = false) {
510 logger.debug('Adding remote video %s.', videoObject.id)
512 const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, videoObject.to)
513 const video = VideoModel.build(videoData) as MVideoThumbnail
515 const promiseThumbnail = createVideoMiniatureFromUrl(getThumbnailFromIcons(videoObject).url, video, ThumbnailType.MINIATURE)
517 let thumbnailModel: MThumbnail
518 if (waitThumbnail === true) {
519 thumbnailModel = await promiseThumbnail
522 const { autoBlacklisted, videoCreated } = await sequelizeTypescript.transaction(async t => {
523 const sequelizeOptions = { transaction: t }
525 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
526 videoCreated.VideoChannel = channel
528 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
530 const previewIcon = getPreviewFromIcons(videoObject)
531 const previewUrl = previewIcon
533 : buildRemoteVideoBaseUrl(videoCreated, join(STATIC_PATHS.PREVIEWS, video.generatePreviewName()))
534 const previewModel = createPlaceholderThumbnail(previewUrl, videoCreated, ThumbnailType.PREVIEW, PREVIEWS_SIZE)
536 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
539 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject.url)
541 const videoFilePromises = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
542 const videoFiles = await Promise.all(videoFilePromises)
544 const streamingPlaylistsAttributes = streamingPlaylistActivityUrlToDBAttributes(videoCreated, videoObject, videoFiles)
545 videoCreated.VideoStreamingPlaylists = []
547 for (const playlistAttributes of streamingPlaylistsAttributes) {
548 const playlistModel = await VideoStreamingPlaylistModel.create(playlistAttributes, { transaction: t })
550 const playlistFiles = videoFileActivityUrlToDBAttributes(playlistModel, playlistAttributes.tagAPObject)
551 const videoFilePromises = playlistFiles.map(f => VideoFileModel.create(f, { transaction: t }))
552 playlistModel.VideoFiles = await Promise.all(videoFilePromises)
554 videoCreated.VideoStreamingPlaylists.push(playlistModel)
558 const tags = videoObject.tag
559 .filter(isAPHashTagObject)
561 const tagInstances = await TagModel.findOrCreateTags(tags, t)
562 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
565 const videoCaptionsPromises = videoObject.subtitleLanguage.map(c => {
566 return VideoCaptionModel.insertOrReplaceLanguage(videoCreated.id, c.identifier, c.url, t)
568 await Promise.all(videoCaptionsPromises)
570 videoCreated.VideoFiles = videoFiles
571 videoCreated.Tags = tagInstances
573 const autoBlacklisted = await autoBlacklistVideoIfNeeded({
581 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
583 return { autoBlacklisted, videoCreated }
586 if (waitThumbnail === false) {
587 promiseThumbnail.then(thumbnailModel => {
588 thumbnailModel = videoCreated.id
590 return thumbnailModel.save()
591 }).catch(err => logger.error('Cannot create miniature from url.', { err }))
594 return { autoBlacklisted, videoCreated }
597 function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) {
598 const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED
599 const duration = videoObject.duration.replace(/[^\d]+/, '')
601 let language: string | undefined
602 if (videoObject.language) {
603 language = videoObject.language.identifier
606 let category: number | undefined
607 if (videoObject.category) {
608 category = parseInt(videoObject.category.identifier, 10)
611 let licence: number | undefined
612 if (videoObject.licence) {
613 licence = parseInt(videoObject.licence.identifier, 10)
616 const description = videoObject.content || null
617 const support = videoObject.support || null
620 name: videoObject.name,
621 uuid: videoObject.uuid,
628 nsfw: videoObject.sensitive,
629 commentsEnabled: videoObject.commentsEnabled,
630 downloadEnabled: videoObject.downloadEnabled,
631 waitTranscoding: videoObject.waitTranscoding,
632 state: videoObject.state,
633 channelId: videoChannel.id,
634 duration: parseInt(duration, 10),
635 createdAt: new Date(videoObject.published),
636 publishedAt: new Date(videoObject.published),
637 originallyPublishedAt: videoObject.originallyPublishedAt ? new Date(videoObject.originallyPublishedAt) : null,
638 updatedAt: new Date(videoObject.updated),
639 views: videoObject.views,
647 function videoFileActivityUrlToDBAttributes (
648 videoOrPlaylist: MVideo | MStreamingPlaylist,
649 urls: (ActivityTagObject | ActivityUrlObject)[]
651 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
653 if (fileUrls.length === 0) return []
655 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
656 for (const fileUrl of fileUrls) {
657 // Fetch associated magnet uri
658 const magnet = urls.filter(isAPMagnetUrlObject)
659 .find(u => u.height === fileUrl.height)
661 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
663 const parsed = magnetUtil.decode(magnet.href)
664 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
665 throw new Error('Cannot parse magnet URI ' + magnet.href)
668 const mediaType = fileUrl.mediaType
670 extname: MIMETYPES.VIDEO.MIMETYPE_EXT[mediaType],
671 infoHash: parsed.infoHash,
672 resolution: fileUrl.height,
674 fps: fileUrl.fps || -1,
676 // This is a video file owned by a video or by a streaming playlist
677 videoId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? null : videoOrPlaylist.id,
678 videoStreamingPlaylistId: (videoOrPlaylist as MStreamingPlaylist).playlistUrl ? videoOrPlaylist.id : null
681 attributes.push(attribute)
687 function streamingPlaylistActivityUrlToDBAttributes (video: MVideoId, videoObject: VideoTorrentObject, videoFiles: MVideoFile[]) {
688 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
689 if (playlistUrls.length === 0) return []
691 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
692 for (const playlistUrlObject of playlistUrls) {
693 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
695 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
697 // FIXME: backward compatibility introduced in v2.1.0
698 if (files.length === 0) files = videoFiles
700 if (!segmentsSha256UrlObject) {
701 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
706 type: VideoStreamingPlaylistType.HLS,
707 playlistUrl: playlistUrlObject.href,
708 segmentsSha256Url: segmentsSha256UrlObject.href,
709 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
710 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
712 tagAPObject: playlistUrlObject.tag
715 attributes.push(attribute)
721 function getThumbnailFromIcons (videoObject: VideoTorrentObject) {
722 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
723 // Fallback if there are not valid icons
724 if (validIcons.length === 0) validIcons = videoObject.icon
726 return minBy(validIcons, 'width')
729 function getPreviewFromIcons (videoObject: VideoTorrentObject) {
730 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
732 // FIXME: don't put a fallback here for compatibility with PeerTube <2.2
734 return maxBy(validIcons, 'width')