1 import { generateMagnetUri } from '@server/helpers/webtorrent'
2 import { getActivityStreamDuration } from '@server/lib/activitypub/activity'
3 import { tracer } from '@server/lib/opentelemetry/tracing'
4 import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls'
5 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
6 import { uuidToShort } from '@shared/extra-utils'
15 VideosCommonQueryAfterSanitize,
16 VideoStreamingPlaylist
17 } from '@shared/models'
18 import { isArray } from '../../../helpers/custom-validators/misc'
27 } from '../../../initializers/constants'
29 getLocalVideoCommentsActivityPubUrl,
30 getLocalVideoDislikesActivityPubUrl,
31 getLocalVideoLikesActivityPubUrl,
32 getLocalVideoSharesActivityPubUrl
33 } from '../../../lib/activitypub/url'
36 MStreamingPlaylistRedundanciesOpt,
42 MVideoFormattableDetails
43 } from '../../../types/models'
44 import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
45 import { VideoCaptionModel } from '../video-caption'
47 export type VideoFormattingJSONOptions = {
48 completeDescription?: boolean
50 additionalAttributes?: {
52 waitTranscoding?: boolean
53 scheduledUpdate?: boolean
54 blacklistInfo?: boolean
56 blockedOwner?: boolean
60 function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
61 if (!query || !query.include) return {}
64 additionalAttributes: {
65 state: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
66 waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
67 scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
68 blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
69 files: !!(query.include & VideoInclude.FILES),
70 blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
75 function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
76 const span = tracer.startSpan('peertube.VideoModel.toFormattedJSON')
78 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
80 const videoObject: Video = {
83 shortUUID: uuidToShort(video.uuid),
90 label: getCategoryLabel(video.category)
94 label: getLicenceLabel(video.licence)
98 label: getLanguageLabel(video.language)
102 label: getPrivacyLabel(video.privacy)
106 truncatedDescription: video.getTruncatedDescription(),
107 description: options && options.completeDescription === true
109 : video.getTruncatedDescription(),
111 isLocal: video.isOwned(),
112 duration: video.duration,
115 viewers: VideoViewsManager.Instance.getViewers(video),
118 dislikes: video.dislikes,
119 thumbnailPath: video.getMiniatureStaticPath(),
120 previewPath: video.getPreviewStaticPath(),
121 embedPath: video.getEmbedStaticPath(),
122 createdAt: video.createdAt,
123 updatedAt: video.updatedAt,
124 publishedAt: video.publishedAt,
125 originallyPublishedAt: video.originallyPublishedAt,
127 isLive: video.isLive,
129 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
130 channel: video.VideoChannel.toFormattedSummaryJSON(),
132 userHistory: userHistory
133 ? { currentTime: userHistory.currentTime }
136 // Can be added by external plugins
137 pluginData: (video as any).pluginData
140 const add = options.additionalAttributes
141 if (add?.state === true) {
142 videoObject.state = {
144 label: getStateLabel(video.state)
148 if (add?.waitTranscoding === true) {
149 videoObject.waitTranscoding = video.waitTranscoding
152 if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
153 videoObject.scheduledUpdate = {
154 updateAt: video.ScheduleVideoUpdate.updateAt,
155 privacy: video.ScheduleVideoUpdate.privacy || undefined
159 if (add?.blacklistInfo === true) {
160 videoObject.blacklisted = !!video.VideoBlacklist
161 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
164 if (add?.blockedOwner === true) {
165 videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
167 const server = video.VideoChannel.Account.Actor.Server as MServer
168 videoObject.blockedServer = !!(server?.isBlocked())
171 if (add?.files === true) {
172 videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
173 videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
181 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
182 const span = tracer.startSpan('peertube.VideoModel.toFormattedDetailsJSON')
184 const videoJSON = video.toFormattedJSON({
185 completeDescription: true,
186 additionalAttributes: {
187 scheduledUpdate: true,
191 }) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
193 const tags = video.Tags ? video.Tags.map(t => t.name) : []
195 const detailsJSON = {
196 support: video.support,
197 descriptionPath: video.getDescriptionAPIPath(),
198 channel: video.VideoChannel.toFormattedJSON(),
199 account: video.VideoChannel.Account.toFormattedJSON(),
201 commentsEnabled: video.commentsEnabled,
202 downloadEnabled: video.downloadEnabled,
203 waitTranscoding: video.waitTranscoding,
206 label: getStateLabel(video.state)
209 trackerUrls: video.getTrackerUrls()
214 return Object.assign(videoJSON, detailsJSON)
217 function streamingPlaylistsModelToFormattedJSON (
218 video: MVideoFormattable,
219 playlists: MStreamingPlaylistRedundanciesOpt[]
220 ): VideoStreamingPlaylist[] {
221 if (isArray(playlists) === false) return []
225 const redundancies = isArray(playlist.RedundancyVideos)
226 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
229 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
234 playlistUrl: playlist.getMasterPlaylistUrl(video),
235 segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
242 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
243 if (fileA.resolution < fileB.resolution) return 1
244 if (fileA.resolution === fileB.resolution) return 0
248 function videoFilesModelToFormattedJSON (
249 video: MVideoFormattable,
250 videoFiles: MVideoFileRedundanciesOpt[],
252 includeMagnet?: boolean // default true
255 const { includeMagnet = true } = options
257 const trackerUrls = includeMagnet
258 ? video.getTrackerUrls()
261 return (videoFiles || [])
262 .filter(f => !f.isLive())
263 .sort(sortByResolutionDesc)
269 id: videoFile.resolution,
270 label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
273 magnetUri: includeMagnet && videoFile.hasTorrent()
274 ? generateMagnetUri(video, videoFile, trackerUrls)
277 size: videoFile.size,
280 torrentUrl: videoFile.getTorrentUrl(),
281 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
283 fileUrl: videoFile.getFileUrl(video),
284 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
286 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
291 function addVideoFilesInAPAcc (options: {
292 acc: ActivityUrlObject[] | ActivityTagObject[]
297 const { acc, video, files } = options
299 const trackerUrls = video.getTrackerUrls()
301 const sortedFiles = (files || [])
302 .filter(f => !f.isLive())
303 .sort(sortByResolutionDesc)
305 for (const file of sortedFiles) {
308 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
309 href: file.getFileUrl(video),
310 height: file.resolution,
317 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
318 mediaType: 'application/json' as 'application/json',
319 href: getLocalVideoFileMetadataUrl(video, file),
320 height: file.resolution,
324 if (file.hasTorrent()) {
327 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
328 href: file.getTorrentUrl(),
329 height: file.resolution
334 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
335 href: generateMagnetUri(video, file, trackerUrls),
336 height: file.resolution
342 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
343 if (!video.Tags) video.Tags = []
345 const tag = video.Tags.map(t => ({
346 type: 'Hashtag' as 'Hashtag',
351 if (video.language) {
353 identifier: video.language,
354 name: getLanguageLabel(video.language)
359 if (video.category) {
361 identifier: video.category + '',
362 name: getCategoryLabel(video.category)
369 identifier: video.licence + '',
370 name: getLicenceLabel(video.licence)
374 const url: ActivityUrlObject[] = [
375 // HTML url should be the first element in the array so Mastodon correctly displays the embed
378 mediaType: 'text/html',
379 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
383 addVideoFilesInAPAcc({ acc: url, video, files: video.VideoFiles || [] })
385 for (const playlist of (video.VideoStreamingPlaylists || [])) {
386 const tag = playlist.p2pMediaLoaderInfohashes
387 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
391 mediaType: 'application/json' as 'application/json',
392 href: playlist.getSha256SegmentsUrl(video)
395 addVideoFilesInAPAcc({ acc: tag, video, files: playlist.VideoFiles || [] })
399 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
400 href: playlist.getMasterPlaylistUrl(video),
405 for (const trackerUrl of video.getTrackerUrls()) {
406 const rel2 = trackerUrl.startsWith('http')
412 name: `tracker-${rel2}`,
413 rel: [ 'tracker', rel2 ],
418 const subtitleLanguage = []
419 for (const caption of video.VideoCaptions) {
420 subtitleLanguage.push({
421 identifier: caption.language,
422 name: VideoCaptionModel.getLanguageLabel(caption.language),
423 url: caption.getFileUrl(video)
427 const icons = [ video.getMiniature(), video.getPreview() ]
430 type: 'Video' as 'Video',
433 duration: getActivityStreamDuration(video.duration),
440 sensitive: video.nsfw,
441 waitTranscoding: video.waitTranscoding,
444 commentsEnabled: video.commentsEnabled,
445 downloadEnabled: video.downloadEnabled,
446 published: video.publishedAt.toISOString(),
448 originallyPublishedAt: video.originallyPublishedAt
449 ? video.originallyPublishedAt.toISOString()
452 updated: video.updatedAt.toISOString(),
454 mediaType: 'text/markdown',
455 content: video.description,
456 support: video.support,
460 icon: icons.map(i => ({
462 url: i.getFileUrl(video),
463 mediaType: 'image/jpeg',
470 likes: getLocalVideoLikesActivityPubUrl(video),
471 dislikes: getLocalVideoDislikesActivityPubUrl(video),
472 shares: getLocalVideoSharesActivityPubUrl(video),
473 comments: getLocalVideoCommentsActivityPubUrl(video),
478 id: video.VideoChannel.Account.Actor.url
482 id: video.VideoChannel.Actor.url
486 ...buildLiveAPAttributes(video)
490 function getCategoryLabel (id: number) {
491 return VIDEO_CATEGORIES[id] || 'Misc'
494 function getLicenceLabel (id: number) {
495 return VIDEO_LICENCES[id] || 'Unknown'
498 function getLanguageLabel (id: string) {
499 return VIDEO_LANGUAGES[id] || 'Unknown'
502 function getPrivacyLabel (id: number) {
503 return VIDEO_PRIVACIES[id] || 'Unknown'
506 function getStateLabel (id: number) {
507 return VIDEO_STATES[id] || 'Unknown'
511 videoModelToFormattedJSON,
512 videoModelToFormattedDetailsJSON,
513 videoFilesModelToFormattedJSON,
514 videoModelToActivityPubObject,
516 guessAdditionalAttributesFromQuery,
525 // ---------------------------------------------------------------------------
527 function buildLiveAPAttributes (video: MVideoAP) {
530 isLiveBroadcast: false,
531 liveSaveReplay: null,
538 isLiveBroadcast: true,
539 liveSaveReplay: video.VideoLive.saveReplay,
540 permanentLive: video.VideoLive.permanentLive,
541 latencyMode: video.VideoLive.latencyMode