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,
41 MVideoFormattableDetails
42 } from '../../../types/models'
43 import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
44 import { VideoCaptionModel } from '../video-caption'
46 export type VideoFormattingJSONOptions = {
47 completeDescription?: boolean
49 additionalAttributes?: {
51 waitTranscoding?: boolean
52 scheduledUpdate?: boolean
53 blacklistInfo?: boolean
55 blockedOwner?: boolean
59 function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
60 if (!query || !query.include) return {}
63 additionalAttributes: {
64 state: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
65 waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
66 scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
67 blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
68 files: !!(query.include & VideoInclude.FILES),
69 blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
74 function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
75 const span = tracer.startSpan('peertube.VideoModel.toFormattedJSON')
77 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
79 const videoObject: Video = {
82 shortUUID: uuidToShort(video.uuid),
89 label: getCategoryLabel(video.category)
93 label: getLicenceLabel(video.licence)
97 label: getLanguageLabel(video.language)
101 label: getPrivacyLabel(video.privacy)
105 description: options && options.completeDescription === true
107 : video.getTruncatedDescription(),
109 isLocal: video.isOwned(),
110 duration: video.duration,
113 viewers: VideoViewsManager.Instance.getViewers(video),
116 dislikes: video.dislikes,
117 thumbnailPath: video.getMiniatureStaticPath(),
118 previewPath: video.getPreviewStaticPath(),
119 embedPath: video.getEmbedStaticPath(),
120 createdAt: video.createdAt,
121 updatedAt: video.updatedAt,
122 publishedAt: video.publishedAt,
123 originallyPublishedAt: video.originallyPublishedAt,
125 isLive: video.isLive,
127 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
128 channel: video.VideoChannel.toFormattedSummaryJSON(),
130 userHistory: userHistory
131 ? { currentTime: userHistory.currentTime }
134 // Can be added by external plugins
135 pluginData: (video as any).pluginData
138 const add = options.additionalAttributes
139 if (add?.state === true) {
140 videoObject.state = {
142 label: getStateLabel(video.state)
146 if (add?.waitTranscoding === true) {
147 videoObject.waitTranscoding = video.waitTranscoding
150 if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
151 videoObject.scheduledUpdate = {
152 updateAt: video.ScheduleVideoUpdate.updateAt,
153 privacy: video.ScheduleVideoUpdate.privacy || undefined
157 if (add?.blacklistInfo === true) {
158 videoObject.blacklisted = !!video.VideoBlacklist
159 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
162 if (add?.blockedOwner === true) {
163 videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
165 const server = video.VideoChannel.Account.Actor.Server as MServer
166 videoObject.blockedServer = !!(server?.isBlocked())
169 if (add?.files === true) {
170 videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
171 videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
179 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
180 const span = tracer.startSpan('peertube.VideoModel.toFormattedDetailsJSON')
182 const videoJSON = video.toFormattedJSON({
183 additionalAttributes: {
184 scheduledUpdate: true,
188 }) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
190 const tags = video.Tags ? video.Tags.map(t => t.name) : []
192 const detailsJSON = {
193 support: video.support,
194 descriptionPath: video.getDescriptionAPIPath(),
195 channel: video.VideoChannel.toFormattedJSON(),
196 account: video.VideoChannel.Account.toFormattedJSON(),
198 commentsEnabled: video.commentsEnabled,
199 downloadEnabled: video.downloadEnabled,
200 waitTranscoding: video.waitTranscoding,
203 label: getStateLabel(video.state)
206 trackerUrls: video.getTrackerUrls()
211 return Object.assign(videoJSON, detailsJSON)
214 function streamingPlaylistsModelToFormattedJSON (
215 video: MVideoFormattable,
216 playlists: MStreamingPlaylistRedundanciesOpt[]
217 ): VideoStreamingPlaylist[] {
218 if (isArray(playlists) === false) return []
222 const redundancies = isArray(playlist.RedundancyVideos)
223 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
226 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
231 playlistUrl: playlist.getMasterPlaylistUrl(video),
232 segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
239 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
240 if (fileA.resolution < fileB.resolution) return 1
241 if (fileA.resolution === fileB.resolution) return 0
245 function videoFilesModelToFormattedJSON (
246 video: MVideoFormattable,
247 videoFiles: MVideoFileRedundanciesOpt[],
250 const trackerUrls = includeMagnet
251 ? video.getTrackerUrls()
254 return (videoFiles || [])
255 .filter(f => !f.isLive())
256 .sort(sortByResolutionDesc)
262 id: videoFile.resolution,
263 label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
266 magnetUri: includeMagnet && videoFile.hasTorrent()
267 ? generateMagnetUri(video, videoFile, trackerUrls)
270 size: videoFile.size,
273 torrentUrl: videoFile.getTorrentUrl(),
274 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
276 fileUrl: videoFile.getFileUrl(video),
277 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
279 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
284 function addVideoFilesInAPAcc (
285 acc: ActivityUrlObject[] | ActivityTagObject[],
289 const trackerUrls = video.getTrackerUrls()
291 const sortedFiles = (files || [])
292 .filter(f => !f.isLive())
293 .sort(sortByResolutionDesc)
295 for (const file of sortedFiles) {
298 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
299 href: file.getFileUrl(video),
300 height: file.resolution,
307 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
308 mediaType: 'application/json' as 'application/json',
309 href: getLocalVideoFileMetadataUrl(video, file),
310 height: file.resolution,
314 if (file.hasTorrent()) {
317 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
318 href: file.getTorrentUrl(),
319 height: file.resolution
324 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
325 href: generateMagnetUri(video, file, trackerUrls),
326 height: file.resolution
332 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
333 if (!video.Tags) video.Tags = []
335 const tag = video.Tags.map(t => ({
336 type: 'Hashtag' as 'Hashtag',
341 if (video.language) {
343 identifier: video.language,
344 name: getLanguageLabel(video.language)
349 if (video.category) {
351 identifier: video.category + '',
352 name: getCategoryLabel(video.category)
359 identifier: video.licence + '',
360 name: getLicenceLabel(video.licence)
364 const url: ActivityUrlObject[] = [
365 // HTML url should be the first element in the array so Mastodon correctly displays the embed
368 mediaType: 'text/html',
369 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
373 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
375 for (const playlist of (video.VideoStreamingPlaylists || [])) {
376 const tag = playlist.p2pMediaLoaderInfohashes
377 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
381 mediaType: 'application/json' as 'application/json',
382 href: playlist.getSha256SegmentsUrl(video)
385 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
389 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
390 href: playlist.getMasterPlaylistUrl(video),
395 for (const trackerUrl of video.getTrackerUrls()) {
396 const rel2 = trackerUrl.startsWith('http')
402 name: `tracker-${rel2}`,
403 rel: [ 'tracker', rel2 ],
408 const subtitleLanguage = []
409 for (const caption of video.VideoCaptions) {
410 subtitleLanguage.push({
411 identifier: caption.language,
412 name: VideoCaptionModel.getLanguageLabel(caption.language),
413 url: caption.getFileUrl(video)
417 const icons = [ video.getMiniature(), video.getPreview() ]
420 type: 'Video' as 'Video',
423 duration: getActivityStreamDuration(video.duration),
430 sensitive: video.nsfw,
431 waitTranscoding: video.waitTranscoding,
434 commentsEnabled: video.commentsEnabled,
435 downloadEnabled: video.downloadEnabled,
436 published: video.publishedAt.toISOString(),
438 originallyPublishedAt: video.originallyPublishedAt
439 ? video.originallyPublishedAt.toISOString()
442 updated: video.updatedAt.toISOString(),
444 mediaType: 'text/markdown',
445 content: video.description,
446 support: video.support,
450 icon: icons.map(i => ({
452 url: i.getFileUrl(video),
453 mediaType: 'image/jpeg',
460 likes: getLocalVideoLikesActivityPubUrl(video),
461 dislikes: getLocalVideoDislikesActivityPubUrl(video),
462 shares: getLocalVideoSharesActivityPubUrl(video),
463 comments: getLocalVideoCommentsActivityPubUrl(video),
468 id: video.VideoChannel.Account.Actor.url
472 id: video.VideoChannel.Actor.url
476 ...buildLiveAPAttributes(video)
480 function getCategoryLabel (id: number) {
481 return VIDEO_CATEGORIES[id] || 'Misc'
484 function getLicenceLabel (id: number) {
485 return VIDEO_LICENCES[id] || 'Unknown'
488 function getLanguageLabel (id: string) {
489 return VIDEO_LANGUAGES[id] || 'Unknown'
492 function getPrivacyLabel (id: number) {
493 return VIDEO_PRIVACIES[id] || 'Unknown'
496 function getStateLabel (id: number) {
497 return VIDEO_STATES[id] || 'Unknown'
501 videoModelToFormattedJSON,
502 videoModelToFormattedDetailsJSON,
503 videoFilesModelToFormattedJSON,
504 videoModelToActivityPubObject,
506 guessAdditionalAttributesFromQuery,
515 // ---------------------------------------------------------------------------
517 function buildLiveAPAttributes (video: MVideoAP) {
520 isLiveBroadcast: false,
521 liveSaveReplay: null,
528 isLiveBroadcast: true,
529 liveSaveReplay: video.VideoLive.saveReplay,
530 permanentLive: video.VideoLive.permanentLive,
531 latencyMode: video.VideoLive.latencyMode