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