1 import { generateMagnetUri } from '@server/helpers/webtorrent'
2 import { getLocalVideoFileMetadataUrl } from '@server/lib/video-paths'
3 import { VideoFile } from '@shared/models/videos/video-file.model'
4 import { ActivityTagObject, ActivityUrlObject, VideoObject } from '../../../../shared/models/activitypub/objects'
5 import { Video, VideoDetails } from '../../../../shared/models/videos'
6 import { VideoStreamingPlaylist } from '../../../../shared/models/videos/video-streaming-playlist.model'
7 import { isArray } from '../../../helpers/custom-validators/misc'
16 } from '../../../initializers/constants'
18 getLocalVideoCommentsActivityPubUrl,
19 getLocalVideoDislikesActivityPubUrl,
20 getLocalVideoLikesActivityPubUrl,
21 getLocalVideoSharesActivityPubUrl
22 } from '../../../lib/activitypub/url'
24 MStreamingPlaylistRedundanciesOpt,
29 MVideoFormattableDetails
30 } from '../../../types/models'
31 import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
32 import { VideoCaptionModel } from '../video-caption'
34 export type VideoFormattingJSONOptions = {
35 completeDescription?: boolean
36 additionalAttributes: {
38 waitTranscoding?: boolean
39 scheduledUpdate?: boolean
40 blacklistInfo?: boolean
44 function videoModelToFormattedJSON (video: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
45 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
47 const videoObject: Video = {
53 label: getCategoryLabel(video.category)
57 label: getLicenceLabel(video.licence)
61 label: getLanguageLabel(video.language)
65 label: getPrivacyLabel(video.privacy)
69 description: options && options.completeDescription === true
71 : video.getTruncatedDescription(),
73 isLocal: video.isOwned(),
74 duration: video.duration,
77 dislikes: video.dislikes,
78 thumbnailPath: video.getMiniatureStaticPath(),
79 previewPath: video.getPreviewStaticPath(),
80 embedPath: video.getEmbedStaticPath(),
81 createdAt: video.createdAt,
82 updatedAt: video.updatedAt,
83 publishedAt: video.publishedAt,
84 originallyPublishedAt: video.originallyPublishedAt,
88 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
89 channel: video.VideoChannel.toFormattedSummaryJSON(),
91 userHistory: userHistory
92 ? { currentTime: userHistory.currentTime }
95 // Can be added by external plugins
96 pluginData: (video as any).pluginData
100 if (options.additionalAttributes.state === true) {
101 videoObject.state = {
103 label: getStateLabel(video.state)
107 if (options.additionalAttributes.waitTranscoding === true) {
108 videoObject.waitTranscoding = video.waitTranscoding
111 if (options.additionalAttributes.scheduledUpdate === true && video.ScheduleVideoUpdate) {
112 videoObject.scheduledUpdate = {
113 updateAt: video.ScheduleVideoUpdate.updateAt,
114 privacy: video.ScheduleVideoUpdate.privacy || undefined
118 if (options.additionalAttributes.blacklistInfo === true) {
119 videoObject.blacklisted = !!video.VideoBlacklist
120 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
127 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
128 const formattedJson = video.toFormattedJSON({
129 additionalAttributes: {
130 scheduledUpdate: true,
135 const tags = video.Tags ? video.Tags.map(t => t.name) : []
137 const streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
139 const detailsJson = {
140 support: video.support,
141 descriptionPath: video.getDescriptionAPIPath(),
142 channel: video.VideoChannel.toFormattedJSON(),
143 account: video.VideoChannel.Account.toFormattedJSON(),
145 commentsEnabled: video.commentsEnabled,
146 downloadEnabled: video.downloadEnabled,
147 waitTranscoding: video.waitTranscoding,
150 label: getStateLabel(video.state)
153 trackerUrls: video.getTrackerUrls(),
159 // Format and sort video files
160 detailsJson.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
162 return Object.assign(formattedJson, detailsJson)
165 function streamingPlaylistsModelToFormattedJSON (
166 video: MVideoFormattableDetails,
167 playlists: MStreamingPlaylistRedundanciesOpt[]
168 ): VideoStreamingPlaylist[] {
169 if (isArray(playlists) === false) return []
173 const redundancies = isArray(playlist.RedundancyVideos)
174 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
177 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
182 playlistUrl: playlist.playlistUrl,
183 segmentsSha256Url: playlist.segmentsSha256Url,
190 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
191 if (fileA.resolution < fileB.resolution) return 1
192 if (fileA.resolution === fileB.resolution) return 0
196 function videoFilesModelToFormattedJSON (
197 video: MVideoFormattableDetails,
198 videoFiles: MVideoFileRedundanciesOpt[],
201 const trackerUrls = includeMagnet
202 ? video.getTrackerUrls()
205 return [ ...videoFiles ]
206 .filter(f => !f.isLive())
207 .sort(sortByResolutionDesc)
211 id: videoFile.resolution,
212 label: videoFile.resolution + 'p'
215 magnetUri: includeMagnet && videoFile.hasTorrent()
216 ? generateMagnetUri(video, videoFile, trackerUrls)
219 size: videoFile.size,
222 torrentUrl: videoFile.getTorrentUrl(),
223 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
225 fileUrl: videoFile.getFileUrl(video),
226 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
228 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
233 function addVideoFilesInAPAcc (
234 acc: ActivityUrlObject[] | ActivityTagObject[],
238 const trackerUrls = video.getTrackerUrls()
240 const sortedFiles = [ ...files ]
241 .filter(f => !f.isLive())
242 .sort(sortByResolutionDesc)
244 for (const file of sortedFiles) {
247 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
248 href: file.getFileUrl(video),
249 height: file.resolution,
256 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
257 mediaType: 'application/json' as 'application/json',
258 href: getLocalVideoFileMetadataUrl(video, file),
259 height: file.resolution,
263 if (file.hasTorrent()) {
266 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
267 href: file.getTorrentUrl(),
268 height: file.resolution
273 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
274 href: generateMagnetUri(video, file, trackerUrls),
275 height: file.resolution
281 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
282 if (!video.Tags) video.Tags = []
284 const tag = video.Tags.map(t => ({
285 type: 'Hashtag' as 'Hashtag',
290 if (video.language) {
292 identifier: video.language,
293 name: getLanguageLabel(video.language)
298 if (video.category) {
300 identifier: video.category + '',
301 name: getCategoryLabel(video.category)
308 identifier: video.licence + '',
309 name: getLicenceLabel(video.licence)
313 const url: ActivityUrlObject[] = [
314 // HTML url should be the first element in the array so Mastodon correctly displays the embed
317 mediaType: 'text/html',
318 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
322 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
324 for (const playlist of (video.VideoStreamingPlaylists || [])) {
325 const tag = playlist.p2pMediaLoaderInfohashes
326 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
330 mediaType: 'application/json' as 'application/json',
331 href: playlist.segmentsSha256Url
334 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
338 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
339 href: playlist.playlistUrl,
344 for (const trackerUrl of video.getTrackerUrls()) {
345 const rel2 = trackerUrl.startsWith('http')
351 name: `tracker-${rel2}`,
352 rel: [ 'tracker', rel2 ],
357 const subtitleLanguage = []
358 for (const caption of video.VideoCaptions) {
359 subtitleLanguage.push({
360 identifier: caption.language,
361 name: VideoCaptionModel.getLanguageLabel(caption.language),
362 url: caption.getFileUrl(video)
366 const icons = [ video.getMiniature(), video.getPreview() ]
369 type: 'Video' as 'Video',
372 duration: getActivityStreamDuration(video.duration),
379 sensitive: video.nsfw,
380 waitTranscoding: video.waitTranscoding,
381 isLiveBroadcast: video.isLive,
383 liveSaveReplay: video.isLive
384 ? video.VideoLive.saveReplay
387 permanentLive: video.isLive
388 ? video.VideoLive.permanentLive
392 commentsEnabled: video.commentsEnabled,
393 downloadEnabled: video.downloadEnabled,
394 published: video.publishedAt.toISOString(),
396 originallyPublishedAt: video.originallyPublishedAt
397 ? video.originallyPublishedAt.toISOString()
400 updated: video.updatedAt.toISOString(),
401 mediaType: 'text/markdown',
402 content: video.description,
403 support: video.support,
405 icon: icons.map(i => ({
407 url: i.getFileUrl(video),
408 mediaType: 'image/jpeg',
413 likes: getLocalVideoLikesActivityPubUrl(video),
414 dislikes: getLocalVideoDislikesActivityPubUrl(video),
415 shares: getLocalVideoSharesActivityPubUrl(video),
416 comments: getLocalVideoCommentsActivityPubUrl(video),
420 id: video.VideoChannel.Account.Actor.url
424 id: video.VideoChannel.Actor.url
430 function getActivityStreamDuration (duration: number) {
431 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
432 return 'PT' + duration + 'S'
435 function getCategoryLabel (id: number) {
436 return VIDEO_CATEGORIES[id] || 'Misc'
439 function getLicenceLabel (id: number) {
440 return VIDEO_LICENCES[id] || 'Unknown'
443 function getLanguageLabel (id: string) {
444 return VIDEO_LANGUAGES[id] || 'Unknown'
447 function getPrivacyLabel (id: number) {
448 return VIDEO_PRIVACIES[id] || 'Unknown'
451 function getStateLabel (id: number) {
452 return VIDEO_STATES[id] || 'Unknown'
456 videoModelToFormattedJSON,
457 videoModelToFormattedDetailsJSON,
458 videoFilesModelToFormattedJSON,
459 videoModelToActivityPubObject,
460 getActivityStreamDuration,