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