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