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