1 import { uuidToShort } from '@server/helpers/uuid'
2 import { generateMagnetUri } from '@server/helpers/webtorrent'
3 import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls'
4 import { VideoViews } from '@server/lib/video-views'
5 import { VideosCommonQueryAfterSanitize } from '@shared/models'
6 import { VideoFile } from '@shared/models/videos/video-file.model'
7 import { ActivityTagObject, ActivityUrlObject, VideoObject } from '../../../../shared/models/activitypub/objects'
8 import { Video, VideoDetails, VideoInclude } from '../../../../shared/models/videos'
9 import { VideoStreamingPlaylist } from '../../../../shared/models/videos/video-streaming-playlist.model'
10 import { isArray } from '../../../helpers/custom-validators/misc'
19 } from '../../../initializers/constants'
21 getLocalVideoCommentsActivityPubUrl,
22 getLocalVideoDislikesActivityPubUrl,
23 getLocalVideoLikesActivityPubUrl,
24 getLocalVideoSharesActivityPubUrl
25 } from '../../../lib/activitypub/url'
28 MStreamingPlaylistRedundanciesOpt,
33 MVideoFormattableDetails
34 } from '../../../types/models'
35 import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
36 import { VideoCaptionModel } from '../video-caption'
38 export type VideoFormattingJSONOptions = {
39 completeDescription?: boolean
41 additionalAttributes?: {
43 waitTranscoding?: boolean
44 scheduledUpdate?: boolean
45 blacklistInfo?: boolean
47 blockedOwner?: boolean
51 function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
52 if (!query || !query.include) return {}
55 additionalAttributes: {
56 state: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
57 waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
58 scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
59 blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
60 files: !!(query.include & VideoInclude.FILES),
61 blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
66 function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
67 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
69 const videoObject: Video = {
72 shortUUID: uuidToShort(video.uuid),
79 label: getCategoryLabel(video.category)
83 label: getLicenceLabel(video.licence)
87 label: getLanguageLabel(video.language)
91 label: getPrivacyLabel(video.privacy)
95 description: options && options.completeDescription === true
97 : video.getTruncatedDescription(),
99 isLocal: video.isOwned(),
100 duration: video.duration,
103 dislikes: video.dislikes,
104 thumbnailPath: video.getMiniatureStaticPath(),
105 previewPath: video.getPreviewStaticPath(),
106 embedPath: video.getEmbedStaticPath(),
107 createdAt: video.createdAt,
108 updatedAt: video.updatedAt,
109 publishedAt: video.publishedAt,
110 originallyPublishedAt: video.originallyPublishedAt,
112 isLive: video.isLive,
114 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
115 channel: video.VideoChannel.toFormattedSummaryJSON(),
117 userHistory: userHistory
118 ? { currentTime: userHistory.currentTime }
121 // Can be added by external plugins
122 pluginData: (video as any).pluginData
126 videoObject.viewers = VideoViews.Instance.getViewers(video)
129 const add = options.additionalAttributes
130 if (add?.state === true) {
131 videoObject.state = {
133 label: getStateLabel(video.state)
137 if (add?.waitTranscoding === true) {
138 videoObject.waitTranscoding = video.waitTranscoding
141 if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
142 videoObject.scheduledUpdate = {
143 updateAt: video.ScheduleVideoUpdate.updateAt,
144 privacy: video.ScheduleVideoUpdate.privacy || undefined
148 if (add?.blacklistInfo === true) {
149 videoObject.blacklisted = !!video.VideoBlacklist
150 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
153 if (add?.blockedOwner === true) {
154 videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
156 const server = video.VideoChannel.Account.Actor.Server as MServer
157 videoObject.blockedServer = !!(server?.isBlocked())
160 if (add?.files === true) {
161 videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
162 videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
168 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
169 const videoJSON = video.toFormattedJSON({
170 additionalAttributes: {
171 scheduledUpdate: true,
175 }) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
177 const tags = video.Tags ? video.Tags.map(t => t.name) : []
179 const detailsJSON = {
180 support: video.support,
181 descriptionPath: video.getDescriptionAPIPath(),
182 channel: video.VideoChannel.toFormattedJSON(),
183 account: video.VideoChannel.Account.toFormattedJSON(),
185 commentsEnabled: video.commentsEnabled,
186 downloadEnabled: video.downloadEnabled,
187 waitTranscoding: video.waitTranscoding,
190 label: getStateLabel(video.state)
193 trackerUrls: video.getTrackerUrls()
196 return Object.assign(videoJSON, detailsJSON)
199 function streamingPlaylistsModelToFormattedJSON (
200 video: MVideoFormattable,
201 playlists: MStreamingPlaylistRedundanciesOpt[]
202 ): VideoStreamingPlaylist[] {
203 if (isArray(playlists) === false) return []
207 const redundancies = isArray(playlist.RedundancyVideos)
208 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
211 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
216 playlistUrl: playlist.getMasterPlaylistUrl(video),
217 segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
224 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
225 if (fileA.resolution < fileB.resolution) return 1
226 if (fileA.resolution === fileB.resolution) return 0
230 function videoFilesModelToFormattedJSON (
231 video: MVideoFormattable,
232 videoFiles: MVideoFileRedundanciesOpt[],
235 const trackerUrls = includeMagnet
236 ? video.getTrackerUrls()
239 return (videoFiles || [])
240 .filter(f => !f.isLive())
241 .sort(sortByResolutionDesc)
245 id: videoFile.resolution,
246 label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
249 magnetUri: includeMagnet && videoFile.hasTorrent()
250 ? generateMagnetUri(video, videoFile, trackerUrls)
253 size: videoFile.size,
256 torrentUrl: videoFile.getTorrentUrl(),
257 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
259 fileUrl: videoFile.getFileUrl(video),
260 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
262 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
267 function addVideoFilesInAPAcc (
268 acc: ActivityUrlObject[] | ActivityTagObject[],
272 const trackerUrls = video.getTrackerUrls()
274 const sortedFiles = (files || [])
275 .filter(f => !f.isLive())
276 .sort(sortByResolutionDesc)
278 for (const file of sortedFiles) {
281 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
282 href: file.getFileUrl(video),
283 height: file.resolution,
290 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
291 mediaType: 'application/json' as 'application/json',
292 href: getLocalVideoFileMetadataUrl(video, file),
293 height: file.resolution,
297 if (file.hasTorrent()) {
300 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
301 href: file.getTorrentUrl(),
302 height: file.resolution
307 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
308 href: generateMagnetUri(video, file, trackerUrls),
309 height: file.resolution
315 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
316 if (!video.Tags) video.Tags = []
318 const tag = video.Tags.map(t => ({
319 type: 'Hashtag' as 'Hashtag',
324 if (video.language) {
326 identifier: video.language,
327 name: getLanguageLabel(video.language)
332 if (video.category) {
334 identifier: video.category + '',
335 name: getCategoryLabel(video.category)
342 identifier: video.licence + '',
343 name: getLicenceLabel(video.licence)
347 const url: ActivityUrlObject[] = [
348 // HTML url should be the first element in the array so Mastodon correctly displays the embed
351 mediaType: 'text/html',
352 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
356 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
358 for (const playlist of (video.VideoStreamingPlaylists || [])) {
359 const tag = playlist.p2pMediaLoaderInfohashes
360 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
364 mediaType: 'application/json' as 'application/json',
365 href: playlist.getSha256SegmentsUrl(video)
368 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
372 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
373 href: playlist.getMasterPlaylistUrl(video),
378 for (const trackerUrl of video.getTrackerUrls()) {
379 const rel2 = trackerUrl.startsWith('http')
385 name: `tracker-${rel2}`,
386 rel: [ 'tracker', rel2 ],
391 const subtitleLanguage = []
392 for (const caption of video.VideoCaptions) {
393 subtitleLanguage.push({
394 identifier: caption.language,
395 name: VideoCaptionModel.getLanguageLabel(caption.language),
396 url: caption.getFileUrl(video)
400 const icons = [ video.getMiniature(), video.getPreview() ]
403 type: 'Video' as 'Video',
406 duration: getActivityStreamDuration(video.duration),
413 sensitive: video.nsfw,
414 waitTranscoding: video.waitTranscoding,
415 isLiveBroadcast: video.isLive,
417 liveSaveReplay: video.isLive
418 ? video.VideoLive.saveReplay
421 permanentLive: video.isLive
422 ? video.VideoLive.permanentLive
426 commentsEnabled: video.commentsEnabled,
427 downloadEnabled: video.downloadEnabled,
428 published: video.publishedAt.toISOString(),
430 originallyPublishedAt: video.originallyPublishedAt
431 ? video.originallyPublishedAt.toISOString()
434 updated: video.updatedAt.toISOString(),
435 mediaType: 'text/markdown',
436 content: video.description,
437 support: video.support,
439 icon: icons.map(i => ({
441 url: i.getFileUrl(video),
442 mediaType: 'image/jpeg',
447 likes: getLocalVideoLikesActivityPubUrl(video),
448 dislikes: getLocalVideoDislikesActivityPubUrl(video),
449 shares: getLocalVideoSharesActivityPubUrl(video),
450 comments: getLocalVideoCommentsActivityPubUrl(video),
454 id: video.VideoChannel.Account.Actor.url
458 id: video.VideoChannel.Actor.url
464 function getActivityStreamDuration (duration: number) {
465 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
466 return 'PT' + duration + 'S'
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,
494 getActivityStreamDuration,
496 guessAdditionalAttributesFromQuery,