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