]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/video/video.service.ts
bc15c326f37ac276467bc93bfe99394973e617ad
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / video / video.service.ts
1 import { SortMeta } from 'primeng/api'
2 import { from, Observable } from 'rxjs'
3 import { catchError, concatMap, map, switchMap, toArray } from 'rxjs/operators'
4 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
5 import { Injectable } from '@angular/core'
6 import { ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core'
7 import { objectToFormData } from '@app/helpers'
8 import {
9 BooleanBothQuery,
10 FeedFormat,
11 NSFWPolicyType,
12 ResultList,
13 UserVideoRate,
14 UserVideoRateType,
15 UserVideoRateUpdate,
16 Video as VideoServerModel,
17 VideoChannel as VideoChannelServerModel,
18 VideoConstant,
19 VideoDetails as VideoDetailsServerModel,
20 VideoFileMetadata,
21 VideoInclude,
22 VideoPrivacy,
23 VideoSortField,
24 VideoTranscodingCreate,
25 VideoUpdate
26 } from '@shared/models'
27 import { environment } from '../../../../environments/environment'
28 import { Account } from '../account/account.model'
29 import { AccountService } from '../account/account.service'
30 import { VideoChannel, VideoChannelService } from '../video-channel'
31 import { VideoDetails } from './video-details.model'
32 import { VideoEdit } from './video-edit.model'
33 import { Video } from './video.model'
34
35 export type CommonVideoParams = {
36 videoPagination?: ComponentPaginationLight
37 sort: VideoSortField | SortMeta
38 include?: VideoInclude
39 isLocal?: boolean
40 categoryOneOf?: number[]
41 languageOneOf?: string[]
42 privacyOneOf?: VideoPrivacy[]
43 isLive?: boolean
44 skipCount?: boolean
45
46 // FIXME: remove?
47 nsfwPolicy?: NSFWPolicyType
48 nsfw?: BooleanBothQuery
49 }
50
51 @Injectable()
52 export class VideoService {
53 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
54 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
55 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
56
57 constructor (
58 private authHttp: HttpClient,
59 private restExtractor: RestExtractor,
60 private restService: RestService,
61 private serverService: ServerService
62 ) {}
63
64 getVideoViewUrl (uuid: string) {
65 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
66 }
67
68 getVideo (options: { videoId: string }): Observable<VideoDetails> {
69 return this.serverService.getServerLocale()
70 .pipe(
71 switchMap(translations => {
72 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
73 .pipe(map(videoHash => ({ videoHash, translations })))
74 }),
75 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
76 catchError(err => this.restExtractor.handleError(err))
77 )
78 }
79
80 updateVideo (video: VideoEdit) {
81 const language = video.language || null
82 const licence = video.licence || null
83 const category = video.category || null
84 const description = video.description || null
85 const support = video.support || null
86 const scheduleUpdate = video.scheduleUpdate || null
87 const originallyPublishedAt = video.originallyPublishedAt || null
88
89 const body: VideoUpdate = {
90 name: video.name,
91 category,
92 licence,
93 language,
94 support,
95 description,
96 channelId: video.channelId,
97 privacy: video.privacy,
98 tags: video.tags,
99 nsfw: video.nsfw,
100 waitTranscoding: video.waitTranscoding,
101 commentsEnabled: video.commentsEnabled,
102 downloadEnabled: video.downloadEnabled,
103 thumbnailfile: video.thumbnailfile,
104 previewfile: video.previewfile,
105 pluginData: video.pluginData,
106 scheduleUpdate,
107 originallyPublishedAt
108 }
109
110 const data = objectToFormData(body)
111
112 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
113 .pipe(catchError(err => this.restExtractor.handleError(err)))
114 }
115
116 uploadVideo (video: FormData) {
117 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
118
119 return this.authHttp
120 .request<{ video: { id: number, uuid: string } }>(req)
121 .pipe(catchError(err => this.restExtractor.handleError(err)))
122 }
123
124 getMyVideos (options: {
125 videoPagination: ComponentPaginationLight
126 sort: VideoSortField
127 userChannels?: VideoChannelServerModel[]
128 search?: string
129 }): Observable<ResultList<Video>> {
130 const { videoPagination, sort, userChannels = [], search } = options
131
132 const pagination = this.restService.componentToRestPagination(videoPagination)
133
134 let params = new HttpParams()
135 params = this.restService.addRestGetParams(params, pagination, sort)
136
137 if (search) {
138 const filters = this.restService.parseQueryStringFilter(search, {
139 isLive: {
140 prefix: 'isLive:',
141 isBoolean: true
142 },
143 channelId: {
144 prefix: 'channel:',
145 handler: (name: string) => {
146 const channel = userChannels.find(c => c.name === name)
147
148 if (channel) return channel.id
149
150 return undefined
151 }
152 }
153 })
154
155 params = this.restService.addObjectParams(params, filters)
156 }
157
158 return this.authHttp
159 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
160 .pipe(
161 switchMap(res => this.extractVideos(res)),
162 catchError(err => this.restExtractor.handleError(err))
163 )
164 }
165
166 getAccountVideos (parameters: CommonVideoParams & {
167 account: Pick<Account, 'nameWithHost'>
168 search?: string
169 }): Observable<ResultList<Video>> {
170 const { account, search } = parameters
171
172 let params = new HttpParams()
173 params = this.buildCommonVideosParams({ params, ...parameters })
174
175 if (search) params = params.set('search', search)
176
177 return this.authHttp
178 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
179 .pipe(
180 switchMap(res => this.extractVideos(res)),
181 catchError(err => this.restExtractor.handleError(err))
182 )
183 }
184
185 getVideoChannelVideos (parameters: CommonVideoParams & {
186 videoChannel: Pick<VideoChannel, 'nameWithHost'>
187 }): Observable<ResultList<Video>> {
188 const { videoChannel } = parameters
189
190 let params = new HttpParams()
191 params = this.buildCommonVideosParams({ params, ...parameters })
192
193 return this.authHttp
194 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
195 .pipe(
196 switchMap(res => this.extractVideos(res)),
197 catchError(err => this.restExtractor.handleError(err))
198 )
199 }
200
201 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
202 let params = new HttpParams()
203 params = this.buildCommonVideosParams({ params, ...parameters })
204
205 return this.authHttp
206 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
207 .pipe(
208 switchMap(res => this.extractVideos(res)),
209 catchError(err => this.restExtractor.handleError(err))
210 )
211 }
212
213 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
214 const feeds = [
215 {
216 format: FeedFormat.RSS,
217 label: 'media rss 2.0',
218 url: base + FeedFormat.RSS.toLowerCase()
219 },
220 {
221 format: FeedFormat.ATOM,
222 label: 'atom 1.0',
223 url: base + FeedFormat.ATOM.toLowerCase()
224 },
225 {
226 format: FeedFormat.JSON,
227 label: 'json 1.0',
228 url: base + FeedFormat.JSON.toLowerCase()
229 }
230 ]
231
232 if (params && params.keys().length !== 0) {
233 for (const feed of feeds) {
234 feed.url += '?' + params.toString()
235 }
236 }
237
238 return feeds
239 }
240
241 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
242 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
243
244 if (isLocal) params = params.set('isLocal', isLocal)
245
246 if (categoryOneOf) {
247 for (const c of categoryOneOf) {
248 params = params.append('categoryOneOf[]', c + '')
249 }
250 }
251
252 return this.buildBaseFeedUrls(params)
253 }
254
255 getAccountFeedUrls (accountId: number) {
256 let params = this.restService.addRestGetParams(new HttpParams())
257 params = params.set('accountId', accountId.toString())
258
259 return this.buildBaseFeedUrls(params)
260 }
261
262 getVideoChannelFeedUrls (videoChannelId: number) {
263 let params = this.restService.addRestGetParams(new HttpParams())
264 params = params.set('videoChannelId', videoChannelId.toString())
265
266 return this.buildBaseFeedUrls(params)
267 }
268
269 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
270 let params = this.restService.addRestGetParams(new HttpParams())
271 params = params.set('accountId', accountId.toString())
272 params = params.set('token', feedToken)
273
274 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
275 }
276
277 getVideoFileMetadata (metadataUrl: string) {
278 return this.authHttp
279 .get<VideoFileMetadata>(metadataUrl)
280 .pipe(
281 catchError(err => this.restExtractor.handleError(err))
282 )
283 }
284
285 removeVideo (idArg: number | number[]) {
286 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
287
288 return from(ids)
289 .pipe(
290 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
291 toArray(),
292 catchError(err => this.restExtractor.handleError(err))
293 )
294 }
295
296 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
297 return from(videoIds)
298 .pipe(
299 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
300 toArray(),
301 catchError(err => this.restExtractor.handleError(err))
302 )
303 }
304
305 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
306 const body: VideoTranscodingCreate = { transcodingType: type }
307
308 return from(videoIds)
309 .pipe(
310 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
311 toArray(),
312 catchError(err => this.restExtractor.handleError(err))
313 )
314 }
315
316 loadCompleteDescription (descriptionPath: string) {
317 return this.authHttp
318 .get<{ description: string }>(environment.apiUrl + descriptionPath)
319 .pipe(
320 map(res => res.description),
321 catchError(err => this.restExtractor.handleError(err))
322 )
323 }
324
325 setVideoLike (id: number) {
326 return this.setVideoRate(id, 'like')
327 }
328
329 setVideoDislike (id: number) {
330 return this.setVideoRate(id, 'dislike')
331 }
332
333 unsetVideoLike (id: number) {
334 return this.setVideoRate(id, 'none')
335 }
336
337 getUserVideoRating (id: number) {
338 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
339
340 return this.authHttp.get<UserVideoRate>(url)
341 .pipe(catchError(err => this.restExtractor.handleError(err)))
342 }
343
344 extractVideos (result: ResultList<VideoServerModel>) {
345 return this.serverService.getServerLocale()
346 .pipe(
347 map(translations => {
348 const videosJson = result.data
349 const totalVideos = result.total
350 const videos: Video[] = []
351
352 for (const videoJson of videosJson) {
353 videos.push(new Video(videoJson, translations))
354 }
355
356 return { total: totalVideos, data: videos }
357 })
358 )
359 }
360
361 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
362 const descriptions = {
363 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
364 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
365 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
366 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
367 }
368
369 const videoPrivacies = serverPrivacies.map(p => {
370 return {
371 ...p,
372
373 description: descriptions[p.id]
374 }
375 })
376
377 return {
378 videoPrivacies,
379 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
380 }
381 }
382
383 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
384 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
385
386 for (const privacy of order) {
387 if (serverPrivacies.find(p => p.id === privacy)) {
388 return privacy
389 }
390 }
391
392 throw new Error('No highest privacy available')
393 }
394
395 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
396 return nsfwPolicy === 'do_not_list'
397 ? 'false'
398 : 'both'
399 }
400
401 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
402 const {
403 params,
404 videoPagination,
405 sort,
406 isLocal,
407 include,
408 categoryOneOf,
409 languageOneOf,
410 privacyOneOf,
411 skipCount,
412 nsfwPolicy,
413 isLive,
414 nsfw
415 } = options
416
417 const pagination = videoPagination
418 ? this.restService.componentToRestPagination(videoPagination)
419 : undefined
420
421 let newParams = this.restService.addRestGetParams(params, pagination, sort)
422
423 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
424
425 if (isLocal) newParams = newParams.set('isLocal', isLocal)
426 if (include) newParams = newParams.set('include', include)
427 if (isLive) newParams = newParams.set('isLive', isLive)
428 if (nsfw) newParams = newParams.set('nsfw', nsfw)
429 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
430 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
431 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
432 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
433
434 return newParams
435 }
436
437 private setVideoRate (id: number, rateType: UserVideoRateType) {
438 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
439 const body: UserVideoRateUpdate = {
440 rating: rateType
441 }
442
443 return this.authHttp
444 .put(url, body)
445 .pipe(catchError(err => this.restExtractor.handleError(err)))
446 }
447 }