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