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