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