]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video-format-utils.ts
Fix embed on mastodon
[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 // HTML url should be the first element in the array so Mastodon correctly displays the embed
275 {
276 type: 'Link',
277 mediaType: 'text/html',
278 href: WEBSERVER.URL + '/videos/watch/' + video.uuid
279 }
280 ]
281
282 addVideoFilesInAPAcc(url, video, baseUrlHttp, baseUrlWs, video.VideoFiles || [])
283
284 for (const playlist of (video.VideoStreamingPlaylists || [])) {
285 let tag: ActivityTagObject[]
286
287 tag = playlist.p2pMediaLoaderInfohashes
288 .map(i => ({ type: 'Infohash' as 'Infohash', name: i }))
289 tag.push({
290 type: 'Link',
291 name: 'sha256',
292 mediaType: 'application/json' as 'application/json',
293 href: playlist.segmentsSha256Url
294 })
295
296 const playlistWithVideo = Object.assign(playlist, { Video: video })
297 addVideoFilesInAPAcc(tag, playlistWithVideo, baseUrlHttp, baseUrlWs, playlist.VideoFiles || [])
298
299 url.push({
300 type: 'Link',
301 mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
302 href: playlist.playlistUrl,
303 tag
304 })
305 }
306
307 const subtitleLanguage = []
308 for (const caption of video.VideoCaptions) {
309 subtitleLanguage.push({
310 identifier: caption.language,
311 name: VideoCaptionModel.getLanguageLabel(caption.language)
312 })
313 }
314
315 const miniature = video.getMiniature()
316
317 return {
318 type: 'Video' as 'Video',
319 id: video.url,
320 name: video.name,
321 duration: getActivityStreamDuration(video.duration),
322 uuid: video.uuid,
323 tag,
324 category,
325 licence,
326 language,
327 views: video.views,
328 sensitive: video.nsfw,
329 waitTranscoding: video.waitTranscoding,
330 state: video.state,
331 commentsEnabled: video.commentsEnabled,
332 downloadEnabled: video.downloadEnabled,
333 published: video.publishedAt.toISOString(),
334 originallyPublishedAt: video.originallyPublishedAt ? video.originallyPublishedAt.toISOString() : null,
335 updated: video.updatedAt.toISOString(),
336 mediaType: 'text/markdown',
337 content: video.getTruncatedDescription(),
338 support: video.support,
339 subtitleLanguage,
340 icon: {
341 type: 'Image',
342 url: miniature.getFileUrl(video.isOwned()),
343 mediaType: 'image/jpeg',
344 width: miniature.width,
345 height: miniature.height
346 },
347 url,
348 likes: getVideoLikesActivityPubUrl(video),
349 dislikes: getVideoDislikesActivityPubUrl(video),
350 shares: getVideoSharesActivityPubUrl(video),
351 comments: getVideoCommentsActivityPubUrl(video),
352 attributedTo: [
353 {
354 type: 'Person',
355 id: video.VideoChannel.Account.Actor.url
356 },
357 {
358 type: 'Group',
359 id: video.VideoChannel.Actor.url
360 }
361 ]
362 }
363 }
364
365 function getActivityStreamDuration (duration: number) {
366 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
367 return 'PT' + duration + 'S'
368 }
369
370 export {
371 videoModelToFormattedJSON,
372 videoModelToFormattedDetailsJSON,
373 videoFilesModelToFormattedJSON,
374 videoModelToActivityPubObject,
375 getActivityStreamDuration
376 }