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'
8 import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
10 getLocalVideoCommentsActivityPubUrl,
11 getLocalVideoDislikesActivityPubUrl,
12 getLocalVideoLikesActivityPubUrl,
13 getLocalVideoSharesActivityPubUrl
14 } from '../../lib/activitypub/url'
16 MStreamingPlaylistRedundanciesOpt,
21 MVideoFormattableDetails
22 } from '../../types/models'
23 import { MVideoFileRedundanciesOpt } from '../../types/models/video/video-file'
24 import { VideoModel } from './video'
25 import { VideoCaptionModel } from './video-caption'
27 export type VideoFormattingJSONOptions = {
28 completeDescription?: boolean
29 additionalAttributes: {
31 waitTranscoding?: boolean
32 scheduledUpdate?: boolean
33 blacklistInfo?: boolean
37 function videoModelToFormattedJSON (video: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
38 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
40 const videoObject: Video = {
46 label: VideoModel.getCategoryLabel(video.category)
50 label: VideoModel.getLicenceLabel(video.licence)
54 label: VideoModel.getLanguageLabel(video.language)
58 label: VideoModel.getPrivacyLabel(video.privacy)
62 description: options && options.completeDescription === true
64 : video.getTruncatedDescription(),
66 isLocal: video.isOwned(),
67 duration: video.duration,
70 dislikes: video.dislikes,
71 thumbnailPath: video.getMiniatureStaticPath(),
72 previewPath: video.getPreviewStaticPath(),
73 embedPath: video.getEmbedStaticPath(),
74 createdAt: video.createdAt,
75 updatedAt: video.updatedAt,
76 publishedAt: video.publishedAt,
77 originallyPublishedAt: video.originallyPublishedAt,
81 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
82 channel: video.VideoChannel.toFormattedSummaryJSON(),
84 userHistory: userHistory
85 ? { currentTime: userHistory.currentTime }
88 // Can be added by external plugins
89 pluginData: (video as any).pluginData
93 if (options.additionalAttributes.state === true) {
96 label: VideoModel.getStateLabel(video.state)
100 if (options.additionalAttributes.waitTranscoding === true) {
101 videoObject.waitTranscoding = video.waitTranscoding
104 if (options.additionalAttributes.scheduledUpdate === true && video.ScheduleVideoUpdate) {
105 videoObject.scheduledUpdate = {
106 updateAt: video.ScheduleVideoUpdate.updateAt,
107 privacy: video.ScheduleVideoUpdate.privacy || undefined
111 if (options.additionalAttributes.blacklistInfo === true) {
112 videoObject.blacklisted = !!video.VideoBlacklist
113 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
120 function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
121 const formattedJson = video.toFormattedJSON({
122 additionalAttributes: {
123 scheduledUpdate: true,
128 const tags = video.Tags ? video.Tags.map(t => t.name) : []
130 const streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
132 const detailsJson = {
133 support: video.support,
134 descriptionPath: video.getDescriptionAPIPath(),
135 channel: video.VideoChannel.toFormattedJSON(),
136 account: video.VideoChannel.Account.toFormattedJSON(),
138 commentsEnabled: video.commentsEnabled,
139 downloadEnabled: video.downloadEnabled,
140 waitTranscoding: video.waitTranscoding,
143 label: VideoModel.getStateLabel(video.state)
146 trackerUrls: video.getTrackerUrls(),
152 // Format and sort video files
153 detailsJson.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
155 return Object.assign(formattedJson, detailsJson)
158 function streamingPlaylistsModelToFormattedJSON (
159 video: MVideoFormattableDetails,
160 playlists: MStreamingPlaylistRedundanciesOpt[]
161 ): VideoStreamingPlaylist[] {
162 if (isArray(playlists) === false) return []
166 const redundancies = isArray(playlist.RedundancyVideos)
167 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
170 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
175 playlistUrl: playlist.playlistUrl,
176 segmentsSha256Url: playlist.segmentsSha256Url,
183 function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
184 if (fileA.resolution < fileB.resolution) return 1
185 if (fileA.resolution === fileB.resolution) return 0
189 function videoFilesModelToFormattedJSON (
190 video: MVideoFormattableDetails,
191 videoFiles: MVideoFileRedundanciesOpt[],
194 const trackerUrls = includeMagnet
195 ? video.getTrackerUrls()
198 return [ ...videoFiles ]
199 .filter(f => !f.isLive())
200 .sort(sortByResolutionDesc)
204 id: videoFile.resolution,
205 label: videoFile.resolution + 'p'
208 magnetUri: includeMagnet && videoFile.torrentFilename
209 ? generateMagnetUri(video, videoFile, trackerUrls)
212 size: videoFile.size,
215 torrentUrl: videoFile.getTorrentUrl(),
216 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
218 fileUrl: videoFile.getFileUrl(video),
219 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
221 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
226 function addVideoFilesInAPAcc (
227 acc: ActivityUrlObject[] | ActivityTagObject[],
231 const trackerUrls = video.getTrackerUrls()
233 const sortedFiles = [ ...files ]
234 .filter(f => !f.isLive())
235 .sort(sortByResolutionDesc)
237 for (const file of sortedFiles) {
240 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
241 href: file.getFileUrl(video),
242 height: file.resolution,
249 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
250 mediaType: 'application/json' as 'application/json',
251 href: getLocalVideoFileMetadataUrl(video, file),
252 height: file.resolution,
258 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
259 href: file.getTorrentUrl(),
260 height: file.resolution
265 mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
266 href: generateMagnetUri(video, file, trackerUrls),
267 height: file.resolution
272 function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
273 if (!video.Tags) video.Tags = []
275 const tag = video.Tags.map(t => ({
276 type: 'Hashtag' as 'Hashtag',
281 if (video.language) {
283 identifier: video.language,
284 name: VideoModel.getLanguageLabel(video.language)
289 if (video.category) {
291 identifier: video.category + '',
292 name: VideoModel.getCategoryLabel(video.category)
299 identifier: video.licence + '',
300 name: VideoModel.getLicenceLabel(video.licence)
304 const url: ActivityUrlObject[] = [
305 // HTML url should be the first element in the array so Mastodon correctly displays the embed
308 mediaType: 'text/html',
309 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
313 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
315 for (const playlist of (video.VideoStreamingPlaylists || [])) {
316 const tag = playlist.p2pMediaLoaderInfohashes
317 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
321 mediaType: 'application/json' as 'application/json',
322 href: playlist.segmentsSha256Url
325 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
329 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
330 href: playlist.playlistUrl,
335 for (const trackerUrl of video.getTrackerUrls()) {
336 const rel2 = trackerUrl.startsWith('http')
342 name: `tracker-${rel2}`,
343 rel: [ 'tracker', rel2 ],
348 const subtitleLanguage = []
349 for (const caption of video.VideoCaptions) {
350 subtitleLanguage.push({
351 identifier: caption.language,
352 name: VideoCaptionModel.getLanguageLabel(caption.language),
353 url: caption.getFileUrl(video)
357 const icons = [ video.getMiniature(), video.getPreview() ]
360 type: 'Video' as 'Video',
363 duration: getActivityStreamDuration(video.duration),
370 sensitive: video.nsfw,
371 waitTranscoding: video.waitTranscoding,
372 isLiveBroadcast: video.isLive,
374 liveSaveReplay: video.isLive
375 ? video.VideoLive.saveReplay
378 permanentLive: video.isLive
379 ? video.VideoLive.permanentLive
383 commentsEnabled: video.commentsEnabled,
384 downloadEnabled: video.downloadEnabled,
385 published: video.publishedAt.toISOString(),
387 originallyPublishedAt: video.originallyPublishedAt
388 ? video.originallyPublishedAt.toISOString()
391 updated: video.updatedAt.toISOString(),
392 mediaType: 'text/markdown',
393 content: video.description,
394 support: video.support,
396 icon: icons.map(i => ({
398 url: i.getFileUrl(video),
399 mediaType: 'image/jpeg',
404 likes: getLocalVideoLikesActivityPubUrl(video),
405 dislikes: getLocalVideoDislikesActivityPubUrl(video),
406 shares: getLocalVideoSharesActivityPubUrl(video),
407 comments: getLocalVideoCommentsActivityPubUrl(video),
411 id: video.VideoChannel.Account.Actor.url
415 id: video.VideoChannel.Actor.url
421 function getActivityStreamDuration (duration: number) {
422 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
423 return 'PT' + duration + 'S'
427 videoModelToFormattedJSON,
428 videoModelToFormattedDetailsJSON,
429 videoFilesModelToFormattedJSON,
430 videoModelToActivityPubObject,
431 getActivityStreamDuration