1 import { generateMagnetUri } from '@server/helpers/webtorrent'
2 import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls'
3 import { VideoViews } from '@server/lib/video-views'
4 import { uuidToShort } from '@shared/extra-utils'
5 import { VideoFile, VideosCommonQueryAfterSanitize } from '@shared/models'
6 import { ActivityTagObject, ActivityUrlObject, VideoObject } from '../../../../shared/models/activitypub/objects'
7 import { Video, VideoDetails, VideoInclude } from '../../../../shared/models/videos'
8 import { VideoStreamingPlaylist } from '../../../../shared/models/videos/video-streaming-playlist.model'
9 import { isArray } from '../../../helpers/custom-validators/misc'
18 } from '../../../initializers/constants'
20 getLocalVideoCommentsActivityPubUrl,
21 getLocalVideoDislikesActivityPubUrl,
22 getLocalVideoLikesActivityPubUrl,
23 getLocalVideoSharesActivityPubUrl
24 } from '../../../lib/activitypub/url'
27 MStreamingPlaylistRedundanciesOpt,
32 MVideoFormattableDetails
33 } from '../../../types/models'
34 import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
35 import { VideoCaptionModel } from '../video-caption'
37 export type VideoFormattingJSONOptions = {
38 completeDescription?: boolean
40 additionalAttributes?: {
42 waitTranscoding?: boolean
43 scheduledUpdate?: boolean
44 blacklistInfo?: boolean
46 blockedOwner?: boolean
50 function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
51 if (!query || !query.include) return {}
54 additionalAttributes: {
55 state: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
56 waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
57 scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
58 blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
59 files: !!(query.include & VideoInclude.FILES),
60 blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
65 function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
66 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
68 const videoObject: Video = {
71 shortUUID: uuidToShort(video.uuid),
78 label: getCategoryLabel(video.category)
82 label: getLicenceLabel(video.licence)
86 label: getLanguageLabel(video.language)
90 label: getPrivacyLabel(video.privacy)
94 description: options && options.completeDescription === true
96 : video.getTruncatedDescription(),
98 isLocal: video.isOwned(),
99 duration: video.duration,
102 dislikes: video.dislikes,
103 thumbnailPath: video.getMiniatureStaticPath(),
104 previewPath: video.getPreviewStaticPath(),
105 embedPath: video.getEmbedStaticPath(),
106 createdAt: video.createdAt,
107 updatedAt: video.updatedAt,
108 publishedAt: video.publishedAt,
109 originallyPublishedAt: video.originallyPublishedAt,
111 isLive: video.isLive,
113 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
114 channel: video.VideoChannel.toFormattedSummaryJSON(),
116 userHistory: userHistory
117 ? { currentTime: userHistory.currentTime }
120 // Can be added by external plugins
121 pluginData: (video as any).pluginData
125 videoObject.viewers = VideoViews.Instance.getViewers(video)
128 const add = options.additionalAttributes
129 if (add?.state === true) {
130 videoObject.state = {
132 label: getStateLabel(video.state)
136 if (add?.waitTranscoding === true) {
137 videoObject.waitTranscoding = video.waitTranscoding
140 if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
141 videoObject.scheduledUpdate = {
142 updateAt: video.ScheduleVideoUpdate.updateAt,
143 privacy: video.ScheduleVideoUpdate.privacy || undefined
147 if (add?.blacklistInfo === true) {
148 videoObject.blacklisted = !!video.VideoBlacklist
149 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
152 if (add?.blockedOwner === true) {
153 videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
155 const server = video.VideoChannel.Account.Actor.Server as MServer
156 videoObject.blockedServer = !!(server?.isBlocked())
159 if (add?.files === true) {
160 videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
161 videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
167 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
168 const videoJSON = video.toFormattedJSON({
169 additionalAttributes: {
170 scheduledUpdate: true,
174 }) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
176 const tags = video.Tags ? video.Tags.map(t => t.name) : []
178 const detailsJSON = {
179 support: video.support,
180 descriptionPath: video.getDescriptionAPIPath(),
181 channel: video.VideoChannel.toFormattedJSON(),
182 account: video.VideoChannel.Account.toFormattedJSON(),
184 commentsEnabled: video.commentsEnabled,
185 downloadEnabled: video.downloadEnabled,
186 waitTranscoding: video.waitTranscoding,
189 label: getStateLabel(video.state)
192 trackerUrls: video.getTrackerUrls()
195 return Object.assign(videoJSON, detailsJSON)
198 function streamingPlaylistsModelToFormattedJSON (
199 video: MVideoFormattable,
200 playlists: MStreamingPlaylistRedundanciesOpt[]
201 ): VideoStreamingPlaylist[] {
202 if (isArray(playlists) === false) return []
206 const redundancies = isArray(playlist.RedundancyVideos)
207 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
210 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
215 playlistUrl: playlist.getMasterPlaylistUrl(video),
216 segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
223 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
224 if (fileA.resolution < fileB.resolution) return 1
225 if (fileA.resolution === fileB.resolution) return 0
229 function videoFilesModelToFormattedJSON (
230 video: MVideoFormattable,
231 videoFiles: MVideoFileRedundanciesOpt[],
234 const trackerUrls = includeMagnet
235 ? video.getTrackerUrls()
238 return (videoFiles || [])
239 .filter(f => !f.isLive())
240 .sort(sortByResolutionDesc)
244 id: videoFile.resolution,
245 label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
248 magnetUri: includeMagnet && videoFile.hasTorrent()
249 ? generateMagnetUri(video, videoFile, trackerUrls)
252 size: videoFile.size,
255 torrentUrl: videoFile.getTorrentUrl(),
256 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
258 fileUrl: videoFile.getFileUrl(video),
259 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
261 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
266 function addVideoFilesInAPAcc (
267 acc: ActivityUrlObject[] | ActivityTagObject[],
271 const trackerUrls = video.getTrackerUrls()
273 const sortedFiles = (files || [])
274 .filter(f => !f.isLive())
275 .sort(sortByResolutionDesc)
277 for (const file of sortedFiles) {
280 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
281 href: file.getFileUrl(video),
282 height: file.resolution,
289 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
290 mediaType: 'application/json' as 'application/json',
291 href: getLocalVideoFileMetadataUrl(video, file),
292 height: file.resolution,
296 if (file.hasTorrent()) {
299 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
300 href: file.getTorrentUrl(),
301 height: file.resolution
306 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
307 href: generateMagnetUri(video, file, trackerUrls),
308 height: file.resolution
314 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
315 if (!video.Tags) video.Tags = []
317 const tag = video.Tags.map(t => ({
318 type: 'Hashtag' as 'Hashtag',
323 if (video.language) {
325 identifier: video.language,
326 name: getLanguageLabel(video.language)
331 if (video.category) {
333 identifier: video.category + '',
334 name: getCategoryLabel(video.category)
341 identifier: video.licence + '',
342 name: getLicenceLabel(video.licence)
346 const url: ActivityUrlObject[] = [
347 // HTML url should be the first element in the array so Mastodon correctly displays the embed
350 mediaType: 'text/html',
351 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
355 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
357 for (const playlist of (video.VideoStreamingPlaylists || [])) {
358 const tag = playlist.p2pMediaLoaderInfohashes
359 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
363 mediaType: 'application/json' as 'application/json',
364 href: playlist.getSha256SegmentsUrl(video)
367 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
371 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
372 href: playlist.getMasterPlaylistUrl(video),
377 for (const trackerUrl of video.getTrackerUrls()) {
378 const rel2 = trackerUrl.startsWith('http')
384 name: `tracker-${rel2}`,
385 rel: [ 'tracker', rel2 ],
390 const subtitleLanguage = []
391 for (const caption of video.VideoCaptions) {
392 subtitleLanguage.push({
393 identifier: caption.language,
394 name: VideoCaptionModel.getLanguageLabel(caption.language),
395 url: caption.getFileUrl(video)
399 const icons = [ video.getMiniature(), video.getPreview() ]
402 type: 'Video' as 'Video',
405 duration: getActivityStreamDuration(video.duration),
412 sensitive: video.nsfw,
413 waitTranscoding: video.waitTranscoding,
414 isLiveBroadcast: video.isLive,
416 liveSaveReplay: video.isLive
417 ? video.VideoLive.saveReplay
420 permanentLive: video.isLive
421 ? video.VideoLive.permanentLive
425 commentsEnabled: video.commentsEnabled,
426 downloadEnabled: video.downloadEnabled,
427 published: video.publishedAt.toISOString(),
429 originallyPublishedAt: video.originallyPublishedAt
430 ? video.originallyPublishedAt.toISOString()
433 updated: video.updatedAt.toISOString(),
434 mediaType: 'text/markdown',
435 content: video.description,
436 support: video.support,
438 icon: icons.map(i => ({
440 url: i.getFileUrl(video),
441 mediaType: 'image/jpeg',
446 likes: getLocalVideoLikesActivityPubUrl(video),
447 dislikes: getLocalVideoDislikesActivityPubUrl(video),
448 shares: getLocalVideoSharesActivityPubUrl(video),
449 comments: getLocalVideoCommentsActivityPubUrl(video),
453 id: video.VideoChannel.Account.Actor.url
457 id: video.VideoChannel.Actor.url
463 function getActivityStreamDuration (duration: number) {
464 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
465 return 'PT' + duration + 'S'
468 function getCategoryLabel (id: number) {
469 return VIDEO_CATEGORIES[id] || 'Misc'
472 function getLicenceLabel (id: number) {
473 return VIDEO_LICENCES[id] || 'Unknown'
476 function getLanguageLabel (id: string) {
477 return VIDEO_LANGUAGES[id] || 'Unknown'
480 function getPrivacyLabel (id: number) {
481 return VIDEO_PRIVACIES[id] || 'Unknown'
484 function getStateLabel (id: number) {
485 return VIDEO_STATES[id] || 'Unknown'
489 videoModelToFormattedJSON,
490 videoModelToFormattedDetailsJSON,
491 videoFilesModelToFormattedJSON,
492 videoModelToActivityPubObject,
493 getActivityStreamDuration,
495 guessAdditionalAttributesFromQuery,