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