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