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