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