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