]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/video/formatter/video-format-utils.ts
feat: show contained playlists under My videos (#5125)
[github/Chocobozzz/PeerTube.git] / server / models / video / formatter / video-format-utils.ts
CommitLineData
90a8bd30 1import { generateMagnetUri } from '@server/helpers/webtorrent'
b2111066 2import { getActivityStreamDuration } from '@server/lib/activitypub/activity'
ce6b3765 3import { tracer } from '@server/lib/opentelemetry/tracing'
0305db28 4import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls'
b2111066 5import { VideoViewsManager } from '@server/lib/views/video-views-manager'
0628157f 6import { uuidToShort } from '@shared/extra-utils'
b2111066
C
7import {
8 ActivityTagObject,
9 ActivityUrlObject,
10 Video,
11 VideoDetails,
12 VideoFile,
13 VideoInclude,
14 VideoObject,
15 VideosCommonQueryAfterSanitize,
16 VideoStreamingPlaylist
17} from '@shared/models'
e5dbd508 18import { isArray } from '../../../helpers/custom-validators/misc'
7c3a6636
C
19import {
20 MIMETYPES,
21 VIDEO_CATEGORIES,
22 VIDEO_LANGUAGES,
23 VIDEO_LICENCES,
24 VIDEO_PRIVACIES,
25 VIDEO_STATES,
26 WEBSERVER
27} from '../../../initializers/constants'
098eb377 28import {
de94ac86
C
29 getLocalVideoCommentsActivityPubUrl,
30 getLocalVideoDislikesActivityPubUrl,
31 getLocalVideoLikesActivityPubUrl,
32 getLocalVideoSharesActivityPubUrl
e5dbd508 33} from '../../../lib/activitypub/url'
d7a25329 34import {
2760b454 35 MServer,
d7a25329 36 MStreamingPlaylistRedundanciesOpt,
8efc27bf 37 MVideo,
d7a25329
C
38 MVideoAP,
39 MVideoFile,
40 MVideoFormattable,
8efc27bf 41 MVideoFormattableDetails
e5dbd508
C
42} from '../../../types/models'
43import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
e5dbd508 44import { VideoCaptionModel } from '../video-caption'
098eb377
C
45
46export type VideoFormattingJSONOptions = {
c39e86b8 47 completeDescription?: boolean
2760b454
C
48
49 additionalAttributes?: {
a1587156
C
50 state?: boolean
51 waitTranscoding?: boolean
52 scheduledUpdate?: boolean
098eb377 53 blacklistInfo?: boolean
3c10840f 54 files?: boolean
2760b454 55 blockedOwner?: boolean
098eb377
C
56 }
57}
a1587156 58
2760b454
C
59function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
60 if (!query || !query.include) return {}
61
62 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),
3c10840f 68 files: !!(query.include & VideoInclude.FILES),
2760b454
C
69 blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
70 }
71 }
72}
73
74function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
ce6b3765
C
75 const span = tracer.startSpan('peertube.VideoModel.toFormattedJSON')
76
6e46de09
C
77 const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
78
098eb377
C
79 const videoObject: Video = {
80 id: video.id,
81 uuid: video.uuid,
d4a8e7a6
C
82 shortUUID: uuidToShort(video.uuid),
83
ab4001aa
C
84 url: video.url,
85
098eb377
C
86 name: video.name,
87 category: {
88 id: video.category,
7c3a6636 89 label: getCategoryLabel(video.category)
098eb377
C
90 },
91 licence: {
92 id: video.licence,
7c3a6636 93 label: getLicenceLabel(video.licence)
098eb377
C
94 },
95 language: {
96 id: video.language,
7c3a6636 97 label: getLanguageLabel(video.language)
098eb377
C
98 },
99 privacy: {
100 id: video.privacy,
7c3a6636 101 label: getPrivacyLabel(video.privacy)
098eb377
C
102 },
103 nsfw: video.nsfw,
97816649
C
104
105 description: options && options.completeDescription === true
106 ? video.description
107 : video.getTruncatedDescription(),
108
098eb377
C
109 isLocal: video.isOwned(),
110 duration: video.duration,
b2111066 111
098eb377 112 views: video.views,
b2111066
C
113 viewers: VideoViewsManager.Instance.getViewers(video),
114
098eb377
C
115 likes: video.likes,
116 dislikes: video.dislikes,
3acc5084 117 thumbnailPath: video.getMiniatureStaticPath(),
098eb377
C
118 previewPath: video.getPreviewStaticPath(),
119 embedPath: video.getEmbedStaticPath(),
120 createdAt: video.createdAt,
121 updatedAt: video.updatedAt,
122 publishedAt: video.publishedAt,
c8034165 123 originallyPublishedAt: video.originallyPublishedAt,
418d092a 124
c6c0fa6c
C
125 isLive: video.isLive,
126
418d092a
C
127 account: video.VideoChannel.Account.toFormattedSummaryJSON(),
128 channel: video.VideoChannel.toFormattedSummaryJSON(),
6e46de09 129
ba5a8d89
C
130 userHistory: userHistory
131 ? { currentTime: userHistory.currentTime }
132 : undefined,
7294aab0
C
133
134 // Can be added by external plugins
135 pluginData: (video as any).pluginData
098eb377
C
136 }
137
2760b454
C
138 const add = options.additionalAttributes
139 if (add?.state === true) {
140 videoObject.state = {
141 id: video.state,
142 label: getStateLabel(video.state)
098eb377 143 }
2760b454 144 }
098eb377 145
2760b454
C
146 if (add?.waitTranscoding === true) {
147 videoObject.waitTranscoding = video.waitTranscoding
148 }
098eb377 149
2760b454
C
150 if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
151 videoObject.scheduledUpdate = {
152 updateAt: video.ScheduleVideoUpdate.updateAt,
153 privacy: video.ScheduleVideoUpdate.privacy || undefined
098eb377 154 }
2760b454 155 }
098eb377 156
2760b454
C
157 if (add?.blacklistInfo === true) {
158 videoObject.blacklisted = !!video.VideoBlacklist
159 videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
160 }
161
162 if (add?.blockedOwner === true) {
163 videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
164
165 const server = video.VideoChannel.Account.Actor.Server as MServer
166 videoObject.blockedServer = !!(server?.isBlocked())
098eb377
C
167 }
168
3c10840f
C
169 if (add?.files === true) {
170 videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
171 videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
172 }
173
ce6b3765
C
174 span.end()
175
098eb377
C
176 return videoObject
177}
178
1ca9f7c3 179function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
ce6b3765
C
180 const span = tracer.startSpan('peertube.VideoModel.toFormattedDetailsJSON')
181
3c10840f 182 const videoJSON = video.toFormattedJSON({
098eb377
C
183 additionalAttributes: {
184 scheduledUpdate: true,
3c10840f
C
185 blacklistInfo: true,
186 files: true
098eb377 187 }
3c10840f 188 }) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
098eb377 189
96f29c0f 190 const tags = video.Tags ? video.Tags.map(t => t.name) : []
09209296 191
3c10840f 192 const detailsJSON = {
098eb377 193 support: video.support,
96f29c0f 194 descriptionPath: video.getDescriptionAPIPath(),
098eb377
C
195 channel: video.VideoChannel.toFormattedJSON(),
196 account: video.VideoChannel.Account.toFormattedJSON(),
96f29c0f 197 tags,
098eb377 198 commentsEnabled: video.commentsEnabled,
7f2cfe3a 199 downloadEnabled: video.downloadEnabled,
098eb377
C
200 waitTranscoding: video.waitTranscoding,
201 state: {
202 id: video.state,
7c3a6636 203 label: getStateLabel(video.state)
098eb377 204 },
09209296 205
3c10840f 206 trackerUrls: video.getTrackerUrls()
098eb377
C
207 }
208
ce6b3765
C
209 span.end()
210
3c10840f 211 return Object.assign(videoJSON, detailsJSON)
098eb377
C
212}
213
90a8bd30 214function streamingPlaylistsModelToFormattedJSON (
3c10840f 215 video: MVideoFormattable,
90a8bd30
C
216 playlists: MStreamingPlaylistRedundanciesOpt[]
217): VideoStreamingPlaylist[] {
09209296
C
218 if (isArray(playlists) === false) return []
219
220 return playlists
221 .map(playlist => {
222 const redundancies = isArray(playlist.RedundancyVideos)
223 ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
224 : []
225
d9a2a031 226 const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
d7a25329 227
09209296
C
228 return {
229 id: playlist.id,
230 type: playlist.type,
764b1a14
C
231 playlistUrl: playlist.getMasterPlaylistUrl(video),
232 segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
d7a25329
C
233 redundancies,
234 files
235 }
09209296
C
236 })
237}
238
5072b909
C
239function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
240 if (fileA.resolution < fileB.resolution) return 1
241 if (fileA.resolution === fileB.resolution) return 0
242 return -1
243}
244
d7a25329 245function videoFilesModelToFormattedJSON (
3c10840f 246 video: MVideoFormattable,
f66db4d5
C
247 videoFiles: MVideoFileRedundanciesOpt[],
248 includeMagnet = true
d7a25329 249): VideoFile[] {
f66db4d5
C
250 const trackerUrls = includeMagnet
251 ? video.getTrackerUrls()
252 : []
d9a2a031 253
cd162f25 254 return (videoFiles || [])
bd54ad19 255 .filter(f => !f.isLive())
5072b909 256 .sort(sortByResolutionDesc)
098eb377 257 .map(videoFile => {
098eb377 258 return {
12d84abe
C
259 id: videoFile.id,
260
098eb377
C
261 resolution: {
262 id: videoFile.resolution,
2a408c40 263 label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
098eb377 264 },
90a8bd30 265
c4d12552 266 magnetUri: includeMagnet && videoFile.hasTorrent()
f66db4d5
C
267 ? generateMagnetUri(video, videoFile, trackerUrls)
268 : undefined,
90a8bd30 269
098eb377
C
270 size: videoFile.size,
271 fps: videoFile.fps,
90a8bd30
C
272
273 torrentUrl: videoFile.getTorrentUrl(),
274 torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
275
276 fileUrl: videoFile.getFileUrl(video),
277 fileDownloadUrl: videoFile.getFileDownloadUrl(video),
278
279 metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
098eb377
C
280 } as VideoFile
281 })
098eb377
C
282}
283
d7a25329
C
284function addVideoFilesInAPAcc (
285 acc: ActivityUrlObject[] | ActivityTagObject[],
8efc27bf 286 video: MVideo,
d7a25329
C
287 files: MVideoFile[]
288) {
d9a2a031
C
289 const trackerUrls = video.getTrackerUrls()
290
cd162f25 291 const sortedFiles = (files || [])
bd54ad19
C
292 .filter(f => !f.isLive())
293 .sort(sortByResolutionDesc)
5072b909
C
294
295 for (const file of sortedFiles) {
d7a25329
C
296 acc.push({
297 type: 'Link',
a1587156 298 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
90a8bd30 299 href: file.getFileUrl(video),
d7a25329
C
300 height: file.resolution,
301 size: file.size,
302 fps: file.fps
303 })
304
8319d6ae
RK
305 acc.push({
306 type: 'Link',
307 rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
308 mediaType: 'application/json' as 'application/json',
90a8bd30 309 href: getLocalVideoFileMetadataUrl(video, file),
8319d6ae
RK
310 height: file.resolution,
311 fps: file.fps
312 })
313
c4d12552
C
314 if (file.hasTorrent()) {
315 acc.push({
316 type: 'Link',
317 mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
318 href: file.getTorrentUrl(),
319 height: file.resolution
320 })
321
322 acc.push({
323 type: 'Link',
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
327 })
328 }
d7a25329
C
329 }
330}
331
de6310b2 332function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
098eb377
C
333 if (!video.Tags) video.Tags = []
334
335 const tag = video.Tags.map(t => ({
336 type: 'Hashtag' as 'Hashtag',
337 name: t.name
338 }))
339
340 let language
341 if (video.language) {
342 language = {
343 identifier: video.language,
7c3a6636 344 name: getLanguageLabel(video.language)
098eb377
C
345 }
346 }
347
348 let category
349 if (video.category) {
350 category = {
351 identifier: video.category + '',
7c3a6636 352 name: getCategoryLabel(video.category)
098eb377
C
353 }
354 }
355
356 let licence
357 if (video.licence) {
358 licence = {
359 identifier: video.licence + '',
7c3a6636 360 name: getLicenceLabel(video.licence)
098eb377
C
361 }
362 }
363
22f18a4a
C
364 const url: ActivityUrlObject[] = [
365 // HTML url should be the first element in the array so Mastodon correctly displays the embed
366 {
367 type: 'Link',
368 mediaType: 'text/html',
369 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
370 }
371 ]
372
d9a2a031 373 addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
098eb377 374
09209296 375 for (const playlist of (video.VideoStreamingPlaylists || [])) {
a1587156
C
376 const tag = playlist.p2pMediaLoaderInfohashes
377 .map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
09209296
C
378 tag.push({
379 type: 'Link',
380 name: 'sha256',
09209296 381 mediaType: 'application/json' as 'application/json',
764b1a14 382 href: playlist.getSha256SegmentsUrl(video)
09209296
C
383 })
384
d9a2a031 385 addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
d7a25329 386
09209296
C
387 url.push({
388 type: 'Link',
09209296 389 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
764b1a14 390 href: playlist.getMasterPlaylistUrl(video),
09209296
C
391 tag
392 })
393 }
394
d9a2a031
C
395 for (const trackerUrl of video.getTrackerUrls()) {
396 const rel2 = trackerUrl.startsWith('http')
397 ? 'http'
398 : 'websocket'
399
400 url.push({
401 type: 'Link',
402 name: `tracker-${rel2}`,
403 rel: [ 'tracker', rel2 ],
404 href: trackerUrl
405 })
406 }
407
098eb377
C
408 const subtitleLanguage = []
409 for (const caption of video.VideoCaptions) {
410 subtitleLanguage.push({
411 identifier: caption.language,
ca6d3622
C
412 name: VideoCaptionModel.getLanguageLabel(caption.language),
413 url: caption.getFileUrl(video)
098eb377
C
414 })
415 }
416
4282dafc 417 const icons = [ video.getMiniature(), video.getPreview() ]
3acc5084 418
098eb377
C
419 return {
420 type: 'Video' as 'Video',
421 id: video.url,
422 name: video.name,
423 duration: getActivityStreamDuration(video.duration),
424 uuid: video.uuid,
425 tag,
426 category,
427 licence,
428 language,
429 views: video.views,
430 sensitive: video.nsfw,
431 waitTranscoding: video.waitTranscoding,
bb4ba6d9 432
098eb377
C
433 state: video.state,
434 commentsEnabled: video.commentsEnabled,
7f2cfe3a 435 downloadEnabled: video.downloadEnabled,
098eb377 436 published: video.publishedAt.toISOString(),
af4ae64f
C
437
438 originallyPublishedAt: video.originallyPublishedAt
439 ? video.originallyPublishedAt.toISOString()
440 : null,
441
098eb377 442 updated: video.updatedAt.toISOString(),
f443a746 443
098eb377 444 mediaType: 'text/markdown',
5cb9f0f4 445 content: video.description,
098eb377 446 support: video.support,
f443a746 447
098eb377 448 subtitleLanguage,
f443a746 449
4282dafc 450 icon: icons.map(i => ({
098eb377 451 type: 'Image',
4282dafc 452 url: i.getFileUrl(video),
098eb377 453 mediaType: 'image/jpeg',
4282dafc
C
454 width: i.width,
455 height: i.height
456 })),
f443a746 457
098eb377 458 url,
f443a746 459
de94ac86
C
460 likes: getLocalVideoLikesActivityPubUrl(video),
461 dislikes: getLocalVideoDislikesActivityPubUrl(video),
462 shares: getLocalVideoSharesActivityPubUrl(video),
463 comments: getLocalVideoCommentsActivityPubUrl(video),
f443a746 464
098eb377
C
465 attributedTo: [
466 {
467 type: 'Person',
468 id: video.VideoChannel.Account.Actor.url
469 },
470 {
471 type: 'Group',
472 id: video.VideoChannel.Actor.url
473 }
f443a746
C
474 ],
475
476 ...buildLiveAPAttributes(video)
098eb377
C
477 }
478}
479
7c3a6636
C
480function getCategoryLabel (id: number) {
481 return VIDEO_CATEGORIES[id] || 'Misc'
482}
483
484function getLicenceLabel (id: number) {
485 return VIDEO_LICENCES[id] || 'Unknown'
486}
487
488function getLanguageLabel (id: string) {
489 return VIDEO_LANGUAGES[id] || 'Unknown'
490}
491
492function getPrivacyLabel (id: number) {
493 return VIDEO_PRIVACIES[id] || 'Unknown'
494}
495
496function getStateLabel (id: number) {
497 return VIDEO_STATES[id] || 'Unknown'
498}
499
098eb377
C
500export {
501 videoModelToFormattedJSON,
502 videoModelToFormattedDetailsJSON,
503 videoFilesModelToFormattedJSON,
504 videoModelToActivityPubObject,
7c3a6636 505
2760b454
C
506 guessAdditionalAttributesFromQuery,
507
7c3a6636
C
508 getCategoryLabel,
509 getLicenceLabel,
510 getLanguageLabel,
511 getPrivacyLabel,
512 getStateLabel
098eb377 513}
f443a746
C
514
515// ---------------------------------------------------------------------------
516
517function buildLiveAPAttributes (video: MVideoAP) {
518 if (!video.isLive) {
519 return {
520 isLiveBroadcast: false,
521 liveSaveReplay: null,
522 permanentLive: null,
523 latencyMode: null
524 }
525 }
526
527 return {
528 isLiveBroadcast: true,
529 liveSaveReplay: video.VideoLive.saveReplay,
530 permanentLive: video.VideoLive.permanentLive,
531 latencyMode: video.VideoLive.latencyMode
532 }
533}