1 import { maxBy, minBy } from 'lodash'
2 import * as magnetUtil from 'magnet-uri'
3 import { basename } from 'path'
4 import { isAPVideoFileUrlMetadataObject } from '@server/helpers/custom-validators/activitypub/videos'
5 import { isVideoFileInfoHashValid } from '@server/helpers/custom-validators/videos'
6 import { logger } from '@server/helpers/logger'
7 import { getExtFromMimetype } from '@server/helpers/video'
8 import { ACTIVITY_PUB, MIMETYPES, P2P_MEDIA_LOADER_PEER_VERSION, PREVIEWS_SIZE, THUMBNAILS_SIZE } from '@server/initializers/constants'
9 import { generateTorrentFileName } from '@server/lib/video-paths'
10 import { VideoCaptionModel } from '@server/models/video/video-caption'
11 import { VideoFileModel } from '@server/models/video/video-file'
12 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
13 import { FilteredModelAttributes } from '@server/types'
14 import { isStreamingPlaylist, MChannelId, MStreamingPlaylistVideo, MVideo, MVideoFile, MVideoId } from '@server/types/models'
16 ActivityHashTagObject,
17 ActivityMagnetUrlObject,
18 ActivityPlaylistSegmentHashesObject,
19 ActivityPlaylistUrlObject,
22 ActivityVideoUrlObject,
25 VideoStreamingPlaylistType
26 } from '@shared/models'
28 function getThumbnailFromIcons (videoObject: VideoObject) {
29 let validIcons = videoObject.icon.filter(i => i.width > THUMBNAILS_SIZE.minWidth)
30 // Fallback if there are not valid icons
31 if (validIcons.length === 0) validIcons = videoObject.icon
33 return minBy(validIcons, 'width')
36 function getPreviewFromIcons (videoObject: VideoObject) {
37 const validIcons = videoObject.icon.filter(i => i.width > PREVIEWS_SIZE.minWidth)
39 return maxBy(validIcons, 'width')
42 function getTagsFromObject (videoObject: VideoObject) {
43 return videoObject.tag
44 .filter(isAPHashTagObject)
48 function getFileAttributesFromUrl (
49 videoOrPlaylist: MVideo | MStreamingPlaylistVideo,
50 urls: (ActivityTagObject | ActivityUrlObject)[]
52 const fileUrls = urls.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
54 if (fileUrls.length === 0) return []
56 const attributes: FilteredModelAttributes<VideoFileModel>[] = []
57 for (const fileUrl of fileUrls) {
58 // Fetch associated magnet uri
59 const magnet = urls.filter(isAPMagnetUrlObject)
60 .find(u => u.height === fileUrl.height)
62 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
64 const parsed = magnetUtil.decode(magnet.href)
65 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) {
66 throw new Error('Cannot parse magnet URI ' + magnet.href)
69 const torrentUrl = Array.isArray(parsed.xs)
73 // Fetch associated metadata url, if any
74 const metadata = urls.filter(isAPVideoFileUrlMetadataObject)
76 return u.height === fileUrl.height &&
77 u.fps === fileUrl.fps &&
78 u.rel.includes(fileUrl.mediaType)
81 const extname = getExtFromMimetype(MIMETYPES.VIDEO.MIMETYPE_EXT, fileUrl.mediaType)
82 const resolution = fileUrl.height
83 const videoId = isStreamingPlaylist(videoOrPlaylist) ? null : videoOrPlaylist.id
84 const videoStreamingPlaylistId = isStreamingPlaylist(videoOrPlaylist) ? videoOrPlaylist.id : null
88 infoHash: parsed.infoHash,
91 fps: fileUrl.fps || -1,
92 metadataUrl: metadata?.href,
94 // Use the name of the remote file because we don't proxify video file requests
95 filename: basename(fileUrl.href),
96 fileUrl: fileUrl.href,
99 // Use our own torrent name since we proxify torrent requests
100 torrentFilename: generateTorrentFileName(videoOrPlaylist, resolution),
102 // This is a video file owned by a video or by a streaming playlist
104 videoStreamingPlaylistId
107 attributes.push(attribute)
113 function getStreamingPlaylistAttributesFromObject (video: MVideoId, videoObject: VideoObject, videoFiles: MVideoFile[]) {
114 const playlistUrls = videoObject.url.filter(u => isAPStreamingPlaylistUrlObject(u)) as ActivityPlaylistUrlObject[]
115 if (playlistUrls.length === 0) return []
117 const attributes: (FilteredModelAttributes<VideoStreamingPlaylistModel> & { tagAPObject?: ActivityTagObject[] })[] = []
118 for (const playlistUrlObject of playlistUrls) {
119 const segmentsSha256UrlObject = playlistUrlObject.tag.find(isAPPlaylistSegmentHashesUrlObject)
121 let files: unknown[] = playlistUrlObject.tag.filter(u => isAPVideoUrlObject(u)) as ActivityVideoUrlObject[]
123 // FIXME: backward compatibility introduced in v2.1.0
124 if (files.length === 0) files = videoFiles
126 if (!segmentsSha256UrlObject) {
127 logger.warn('No segment sha256 URL found in AP playlist object.', { playlistUrl: playlistUrlObject })
132 type: VideoStreamingPlaylistType.HLS,
134 playlistFilename: basename(playlistUrlObject.href),
135 playlistUrl: playlistUrlObject.href,
137 segmentsSha256Filename: basename(segmentsSha256UrlObject.href),
138 segmentsSha256Url: segmentsSha256UrlObject.href,
140 p2pMediaLoaderInfohashes: VideoStreamingPlaylistModel.buildP2PMediaLoaderInfoHashes(playlistUrlObject.href, files),
141 p2pMediaLoaderPeerVersion: P2P_MEDIA_LOADER_PEER_VERSION,
144 tagAPObject: playlistUrlObject.tag
147 attributes.push(attribute)
153 function getLiveAttributesFromObject (video: MVideoId, videoObject: VideoObject) {
155 saveReplay: videoObject.liveSaveReplay,
156 permanentLive: videoObject.permanentLive,
161 function getCaptionAttributesFromObject (video: MVideoId, videoObject: VideoObject) {
162 return videoObject.subtitleLanguage.map(c => ({
164 filename: VideoCaptionModel.generateCaptionName(c.identifier),
165 language: c.identifier,
170 function getVideoAttributesFromObject (videoChannel: MChannelId, videoObject: VideoObject, to: string[] = []) {
171 const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
172 ? VideoPrivacy.PUBLIC
173 : VideoPrivacy.UNLISTED
175 const duration = videoObject.duration.replace(/[^\d]+/, '')
176 const language = videoObject.language?.identifier
178 const category = videoObject.category
179 ? parseInt(videoObject.category.identifier, 10)
182 const licence = videoObject.licence
183 ? parseInt(videoObject.licence.identifier, 10)
186 const description = videoObject.content || null
187 const support = videoObject.support || null
190 name: videoObject.name,
191 uuid: videoObject.uuid,
198 nsfw: videoObject.sensitive,
199 commentsEnabled: videoObject.commentsEnabled,
200 downloadEnabled: videoObject.downloadEnabled,
201 waitTranscoding: videoObject.waitTranscoding,
202 isLive: videoObject.isLiveBroadcast,
203 state: videoObject.state,
204 channelId: videoChannel.id,
205 duration: parseInt(duration, 10),
206 createdAt: new Date(videoObject.published),
207 publishedAt: new Date(videoObject.published),
209 originallyPublishedAt: videoObject.originallyPublishedAt
210 ? new Date(videoObject.originallyPublishedAt)
213 updatedAt: new Date(videoObject.updated),
214 views: videoObject.views,
222 // ---------------------------------------------------------------------------
225 getThumbnailFromIcons,
230 getFileAttributesFromUrl,
231 getStreamingPlaylistAttributesFromObject,
233 getLiveAttributesFromObject,
234 getCaptionAttributesFromObject,
236 getVideoAttributesFromObject
239 // ---------------------------------------------------------------------------
241 function isAPVideoUrlObject (url: any): url is ActivityVideoUrlObject {
242 const urlMediaType = url.mediaType
244 return MIMETYPES.VIDEO.MIMETYPE_EXT[urlMediaType] && urlMediaType.startsWith('video/')
247 function isAPStreamingPlaylistUrlObject (url: any): url is ActivityPlaylistUrlObject {
248 return url && url.mediaType === 'application/x-mpegURL'
251 function isAPPlaylistSegmentHashesUrlObject (tag: any): tag is ActivityPlaylistSegmentHashesObject {
252 return tag && tag.name === 'sha256' && tag.type === 'Link' && tag.mediaType === 'application/json'
255 function isAPMagnetUrlObject (url: any): url is ActivityMagnetUrlObject {
256 return url && url.mediaType === 'application/x-bittorrent;x-scheme-handler/magnet'
259 function isAPHashTagObject (url: any): url is ActivityHashTagObject {
260 return url && url.type === 'Hashtag'