1 import { generateMagnetUri } from '@server/helpers/webtorrent'
2 import { getActivityStreamDuration } from '@server/lib/activitypub/activity'
3 import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls'
4 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
5 import { uuidToShort } from '@shared/extra-utils'
14 VideosCommonQueryAfterSanitize,
15 VideoStreamingPlaylist
16 } from '@shared/models'
17 import { isArray } from '../../../helpers/custom-validators/misc'
26 } from '../../../initializers/constants'
28 getLocalVideoCommentsActivityPubUrl,
29 getLocalVideoDislikesActivityPubUrl,
30 getLocalVideoLikesActivityPubUrl,
31 getLocalVideoSharesActivityPubUrl
32 } from '../../../lib/activitypub/url'
35 MStreamingPlaylistRedundanciesOpt,
40 MVideoFormattableDetails
41 } from '../../../types/models'
42 import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
43 import { VideoCaptionModel } from '../video-caption'
45 export type VideoFormattingJSONOptions = {
46 completeDescription?: boolean
48 additionalAttributes?: {
50 waitTranscoding?: boolean
51 scheduledUpdate?: boolean
52 blacklistInfo?: boolean
54 blockedOwner?: boolean
58 function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
59 if (!query || !query.include) return {}
62 additionalAttributes: {
63 state: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
64 waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
65 scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
66 blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
67 files: !!(query.include & VideoInclude.FILES),
68 blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
73 function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
74 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
76 const videoObject: Video = {
79 shortUUID: uuidToShort(video.uuid),
86 label: getCategoryLabel(video.category)
90 label: getLicenceLabel(video.licence)
94 label: getLanguageLabel(video.language)
98 label: getPrivacyLabel(video.privacy)
102 description: options && options.completeDescription === true
104 : video.getTruncatedDescription(),
106 isLocal: video.isOwned(),
107 duration: video.duration,
110 viewers: VideoViewsManager.Instance.getViewers(video),
113 dislikes: video.dislikes,
114 thumbnailPath: video.getMiniatureStaticPath(),
115 previewPath: video.getPreviewStaticPath(),
116 embedPath: video.getEmbedStaticPath(),
117 createdAt: video.createdAt,
118 updatedAt: video.updatedAt,
119 publishedAt: video.publishedAt,
120 originallyPublishedAt: video.originallyPublishedAt,
122 isLive: video.isLive,
124 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
125 channel: video.VideoChannel.toFormattedSummaryJSON(),
127 userHistory: userHistory
128 ? { currentTime: userHistory.currentTime }
131 // Can be added by external plugins
132 pluginData: (video as any).pluginData
135 const add = options.additionalAttributes
136 if (add?.state === true) {
137 videoObject.state = {
139 label: getStateLabel(video.state)
143 if (add?.waitTranscoding === true) {
144 videoObject.waitTranscoding = video.waitTranscoding
147 if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
148 videoObject.scheduledUpdate = {
149 updateAt: video.ScheduleVideoUpdate.updateAt,
150 privacy: video.ScheduleVideoUpdate.privacy || undefined
154 if (add?.blacklistInfo === true) {
155 videoObject.blacklisted = !!video.VideoBlacklist
156 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
159 if (add?.blockedOwner === true) {
160 videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
162 const server = video.VideoChannel.Account.Actor.Server as MServer
163 videoObject.blockedServer = !!(server?.isBlocked())
166 if (add?.files === true) {
167 videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
168 videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
174 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
175 const videoJSON = video.toFormattedJSON({
176 additionalAttributes: {
177 scheduledUpdate: true,
181 }) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
183 const tags = video.Tags ? video.Tags.map(t => t.name) : []
185 const detailsJSON = {
186 support: video.support,
187 descriptionPath: video.getDescriptionAPIPath(),
188 channel: video.VideoChannel.toFormattedJSON(),
189 account: video.VideoChannel.Account.toFormattedJSON(),
191 commentsEnabled: video.commentsEnabled,
192 downloadEnabled: video.downloadEnabled,
193 waitTranscoding: video.waitTranscoding,
196 label: getStateLabel(video.state)
199 trackerUrls: video.getTrackerUrls()
202 return Object.assign(videoJSON, detailsJSON)
205 function streamingPlaylistsModelToFormattedJSON (
206 video: MVideoFormattable,
207 playlists: MStreamingPlaylistRedundanciesOpt[]
208 ): VideoStreamingPlaylist[] {
209 if (isArray(playlists) === false) return []
213 const redundancies = isArray(playlist.RedundancyVideos)
214 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
217 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
222 playlistUrl: playlist.getMasterPlaylistUrl(video),
223 segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
230 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
231 if (fileA.resolution < fileB.resolution) return 1
232 if (fileA.resolution === fileB.resolution) return 0
236 function videoFilesModelToFormattedJSON (
237 video: MVideoFormattable,
238 videoFiles: MVideoFileRedundanciesOpt[],
241 const trackerUrls = includeMagnet
242 ? video.getTrackerUrls()
245 return (videoFiles || [])
246 .filter(f => !f.isLive())
247 .sort(sortByResolutionDesc)
251 id: videoFile.resolution,
252 label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
255 magnetUri: includeMagnet && videoFile.hasTorrent()
256 ? generateMagnetUri(video, videoFile, trackerUrls)
259 size: videoFile.size,
262 torrentUrl: videoFile.getTorrentUrl(),
263 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
265 fileUrl: videoFile.getFileUrl(video),
266 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
268 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
273 function addVideoFilesInAPAcc (
274 acc: ActivityUrlObject[] | ActivityTagObject[],
278 const trackerUrls = video.getTrackerUrls()
280 const sortedFiles = (files || [])
281 .filter(f => !f.isLive())
282 .sort(sortByResolutionDesc)
284 for (const file of sortedFiles) {
287 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
288 href: file.getFileUrl(video),
289 height: file.resolution,
296 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
297 mediaType: 'application/json' as 'application/json',
298 href: getLocalVideoFileMetadataUrl(video, file),
299 height: file.resolution,
303 if (file.hasTorrent()) {
306 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
307 href: file.getTorrentUrl(),
308 height: file.resolution
313 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
314 href: generateMagnetUri(video, file, trackerUrls),
315 height: file.resolution
321 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
322 if (!video.Tags) video.Tags = []
324 const tag = video.Tags.map(t => ({
325 type: 'Hashtag' as 'Hashtag',
330 if (video.language) {
332 identifier: video.language,
333 name: getLanguageLabel(video.language)
338 if (video.category) {
340 identifier: video.category + '',
341 name: getCategoryLabel(video.category)
348 identifier: video.licence + '',
349 name: getLicenceLabel(video.licence)
353 const url: ActivityUrlObject[] = [
354 // HTML url should be the first element in the array so Mastodon correctly displays the embed
357 mediaType: 'text/html',
358 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
362 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
364 for (const playlist of (video.VideoStreamingPlaylists || [])) {
365 const tag = playlist.p2pMediaLoaderInfohashes
366 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
370 mediaType: 'application/json' as 'application/json',
371 href: playlist.getSha256SegmentsUrl(video)
374 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
378 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
379 href: playlist.getMasterPlaylistUrl(video),
384 for (const trackerUrl of video.getTrackerUrls()) {
385 const rel2 = trackerUrl.startsWith('http')
391 name: `tracker-${rel2}`,
392 rel: [ 'tracker', rel2 ],
397 const subtitleLanguage = []
398 for (const caption of video.VideoCaptions) {
399 subtitleLanguage.push({
400 identifier: caption.language,
401 name: VideoCaptionModel.getLanguageLabel(caption.language),
402 url: caption.getFileUrl(video)
406 const icons = [ video.getMiniature(), video.getPreview() ]
409 type: 'Video' as 'Video',
412 duration: getActivityStreamDuration(video.duration),
419 sensitive: video.nsfw,
420 waitTranscoding: video.waitTranscoding,
423 commentsEnabled: video.commentsEnabled,
424 downloadEnabled: video.downloadEnabled,
425 published: video.publishedAt.toISOString(),
427 originallyPublishedAt: video.originallyPublishedAt
428 ? video.originallyPublishedAt.toISOString()
431 updated: video.updatedAt.toISOString(),
433 mediaType: 'text/markdown',
434 content: video.description,
435 support: video.support,
439 icon: icons.map(i => ({
441 url: i.getFileUrl(video),
442 mediaType: 'image/jpeg',
449 likes: getLocalVideoLikesActivityPubUrl(video),
450 dislikes: getLocalVideoDislikesActivityPubUrl(video),
451 shares: getLocalVideoSharesActivityPubUrl(video),
452 comments: getLocalVideoCommentsActivityPubUrl(video),
457 id: video.VideoChannel.Account.Actor.url
461 id: video.VideoChannel.Actor.url
465 ...buildLiveAPAttributes(video)
469 function getCategoryLabel (id: number) {
470 return VIDEO_CATEGORIES[id] || 'Misc'
473 function getLicenceLabel (id: number) {
474 return VIDEO_LICENCES[id] || 'Unknown'
477 function getLanguageLabel (id: string) {
478 return VIDEO_LANGUAGES[id] || 'Unknown'
481 function getPrivacyLabel (id: number) {
482 return VIDEO_PRIVACIES[id] || 'Unknown'
485 function getStateLabel (id: number) {
486 return VIDEO_STATES[id] || 'Unknown'
490 videoModelToFormattedJSON,
491 videoModelToFormattedDetailsJSON,
492 videoFilesModelToFormattedJSON,
493 videoModelToActivityPubObject,
495 guessAdditionalAttributesFromQuery,
504 // ---------------------------------------------------------------------------
506 function buildLiveAPAttributes (video: MVideoAP) {
509 isLiveBroadcast: false,
510 liveSaveReplay: null,
517 isLiveBroadcast: true,
518 liveSaveReplay: video.VideoLive.saveReplay,
519 permanentLive: video.VideoLive.permanentLive,
520 latencyMode: video.VideoLive.latencyMode