Rename streaming playlists routes/directories
[oweals/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 { VideoFileModel } from './video-file'
4 import {
5   ActivityPlaylistInfohashesObject,
6   ActivityPlaylistSegmentHashesObject,
7   ActivityUrlObject,
8   VideoTorrentObject
9 } from '../../../shared/models/activitypub/objects'
10 import { CONFIG, MIMETYPES, THUMBNAILS_SIZE } from '../../initializers'
11 import { VideoCaptionModel } from './video-caption'
12 import {
13   getVideoCommentsActivityPubUrl,
14   getVideoDislikesActivityPubUrl,
15   getVideoLikesActivityPubUrl,
16   getVideoSharesActivityPubUrl
17 } from '../../lib/activitypub'
18 import { isArray } from '../../helpers/custom-validators/misc'
19 import { VideoStreamingPlaylist } from '../../../shared/models/videos/video-streaming-playlist.model'
20 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
21
22 export type VideoFormattingJSONOptions = {
23   completeDescription?: boolean
24   additionalAttributes: {
25     state?: boolean,
26     waitTranscoding?: boolean,
27     scheduledUpdate?: boolean,
28     blacklistInfo?: boolean
29     playlistInfo?: boolean
30   }
31 }
32 function videoModelToFormattedJSON (video: VideoModel, 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.getThumbnailStaticPath(),
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     if (options.additionalAttributes.playlistInfo === true) {
103       // We filtered on a specific videoId/videoPlaylistId, that is unique
104       const playlistElement = video.VideoPlaylistElements[0]
105
106       videoObject.playlistElement = {
107         position: playlistElement.position,
108         startTimestamp: playlistElement.startTimestamp,
109         stopTimestamp: playlistElement.stopTimestamp
110       }
111     }
112   }
113
114   return videoObject
115 }
116
117 function videoModelToFormattedDetailsJSON (video: VideoModel): VideoDetails {
118   const formattedJson = video.toFormattedJSON({
119     additionalAttributes: {
120       scheduledUpdate: true,
121       blacklistInfo: true
122     }
123   })
124
125   const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
126
127   const tags = video.Tags ? video.Tags.map(t => t.name) : []
128
129   const streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
130
131   const detailsJson = {
132     support: video.support,
133     descriptionPath: video.getDescriptionAPIPath(),
134     channel: video.VideoChannel.toFormattedJSON(),
135     account: video.VideoChannel.Account.toFormattedJSON(),
136     tags,
137     commentsEnabled: video.commentsEnabled,
138     downloadEnabled: video.downloadEnabled,
139     waitTranscoding: video.waitTranscoding,
140     state: {
141       id: video.state,
142       label: VideoModel.getStateLabel(video.state)
143     },
144
145     trackerUrls: video.getTrackerUrls(baseUrlHttp, baseUrlWs),
146
147     files: [],
148     streamingPlaylists
149   }
150
151   // Format and sort video files
152   detailsJson.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
153
154   return Object.assign(formattedJson, detailsJson)
155 }
156
157 function streamingPlaylistsModelToFormattedJSON (video: VideoModel, playlists: VideoStreamingPlaylistModel[]): VideoStreamingPlaylist[] {
158   if (isArray(playlists) === false) return []
159
160   return playlists
161     .map(playlist => {
162       const redundancies = isArray(playlist.RedundancyVideos)
163         ? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
164         : []
165
166       return {
167         id: playlist.id,
168         type: playlist.type,
169         playlistUrl: playlist.playlistUrl,
170         segmentsSha256Url: playlist.segmentsSha256Url,
171         redundancies
172       } as VideoStreamingPlaylist
173     })
174 }
175
176 function videoFilesModelToFormattedJSON (video: VideoModel, videoFiles: VideoFileModel[]): VideoFile[] {
177   const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
178
179   return videoFiles
180     .map(videoFile => {
181       let resolutionLabel = videoFile.resolution + 'p'
182
183       return {
184         resolution: {
185           id: videoFile.resolution,
186           label: resolutionLabel
187         },
188         magnetUri: video.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
189         size: videoFile.size,
190         fps: videoFile.fps,
191         torrentUrl: video.getTorrentUrl(videoFile, baseUrlHttp),
192         torrentDownloadUrl: video.getTorrentDownloadUrl(videoFile, baseUrlHttp),
193         fileUrl: video.getVideoFileUrl(videoFile, baseUrlHttp),
194         fileDownloadUrl: video.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
195       } as VideoFile
196     })
197     .sort((a, b) => {
198       if (a.resolution.id < b.resolution.id) return 1
199       if (a.resolution.id === b.resolution.id) return 0
200       return -1
201     })
202 }
203
204 function videoModelToActivityPubObject (video: VideoModel): VideoTorrentObject {
205   const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
206   if (!video.Tags) video.Tags = []
207
208   const tag = video.Tags.map(t => ({
209     type: 'Hashtag' as 'Hashtag',
210     name: t.name
211   }))
212
213   let language
214   if (video.language) {
215     language = {
216       identifier: video.language,
217       name: VideoModel.getLanguageLabel(video.language)
218     }
219   }
220
221   let category
222   if (video.category) {
223     category = {
224       identifier: video.category + '',
225       name: VideoModel.getCategoryLabel(video.category)
226     }
227   }
228
229   let licence
230   if (video.licence) {
231     licence = {
232       identifier: video.licence + '',
233       name: VideoModel.getLicenceLabel(video.licence)
234     }
235   }
236
237   const url: ActivityUrlObject[] = []
238   for (const file of video.VideoFiles) {
239     url.push({
240       type: 'Link',
241       mimeType: MIMETYPES.VIDEO.EXT_MIMETYPE[ file.extname ] as any,
242       mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[ file.extname ] as any,
243       href: video.getVideoFileUrl(file, baseUrlHttp),
244       height: file.resolution,
245       size: file.size,
246       fps: file.fps
247     })
248
249     url.push({
250       type: 'Link',
251       mimeType: 'application/x-bittorrent' as 'application/x-bittorrent',
252       mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
253       href: video.getTorrentUrl(file, baseUrlHttp),
254       height: file.resolution
255     })
256
257     url.push({
258       type: 'Link',
259       mimeType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
260       mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
261       href: video.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
262       height: file.resolution
263     })
264   }
265
266   for (const playlist of (video.VideoStreamingPlaylists || [])) {
267     let tag: (ActivityPlaylistSegmentHashesObject | ActivityPlaylistInfohashesObject)[]
268
269     tag = playlist.p2pMediaLoaderInfohashes
270                   .map(i => ({ type: 'Infohash' as 'Infohash', name: i }))
271     tag.push({
272       type: 'Link',
273       name: 'sha256',
274       mimeType: 'application/json' as 'application/json',
275       mediaType: 'application/json' as 'application/json',
276       href: playlist.segmentsSha256Url
277     })
278
279     url.push({
280       type: 'Link',
281       mimeType: 'application/x-mpegURL' as 'application/x-mpegURL',
282       mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
283       href: playlist.playlistUrl,
284       tag
285     })
286   }
287
288   // Add video url too
289   url.push({
290     type: 'Link',
291     mimeType: 'text/html',
292     mediaType: 'text/html',
293     href: CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
294   })
295
296   const subtitleLanguage = []
297   for (const caption of video.VideoCaptions) {
298     subtitleLanguage.push({
299       identifier: caption.language,
300       name: VideoCaptionModel.getLanguageLabel(caption.language)
301     })
302   }
303
304   return {
305     type: 'Video' as 'Video',
306     id: video.url,
307     name: video.name,
308     duration: getActivityStreamDuration(video.duration),
309     uuid: video.uuid,
310     tag,
311     category,
312     licence,
313     language,
314     views: video.views,
315     sensitive: video.nsfw,
316     waitTranscoding: video.waitTranscoding,
317     state: video.state,
318     commentsEnabled: video.commentsEnabled,
319     downloadEnabled: video.downloadEnabled,
320     published: video.publishedAt.toISOString(),
321     originallyPublishedAt: video.originallyPublishedAt ? video.originallyPublishedAt.toISOString() : null,
322     updated: video.updatedAt.toISOString(),
323     mediaType: 'text/markdown',
324     content: video.getTruncatedDescription(),
325     support: video.support,
326     subtitleLanguage,
327     icon: {
328       type: 'Image',
329       url: video.getThumbnailUrl(baseUrlHttp),
330       mediaType: 'image/jpeg',
331       width: THUMBNAILS_SIZE.width,
332       height: THUMBNAILS_SIZE.height
333     },
334     url,
335     likes: getVideoLikesActivityPubUrl(video),
336     dislikes: getVideoDislikesActivityPubUrl(video),
337     shares: getVideoSharesActivityPubUrl(video),
338     comments: getVideoCommentsActivityPubUrl(video),
339     attributedTo: [
340       {
341         type: 'Person',
342         id: video.VideoChannel.Account.Actor.url
343       },
344       {
345         type: 'Group',
346         id: video.VideoChannel.Actor.url
347       }
348     ]
349   }
350 }
351
352 function getActivityStreamDuration (duration: number) {
353   // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
354   return 'PT' + duration + 'S'
355 }
356
357 export {
358   videoModelToFormattedJSON,
359   videoModelToFormattedDetailsJSON,
360   videoFilesModelToFormattedJSON,
361   videoModelToActivityPubObject,
362   getActivityStreamDuration
363 }