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