]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/video/video.service.ts
Add ability to display all channel/account videos
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / video / video.service.ts
1 import { Observable } from 'rxjs'
2 import { catchError, map, switchMap } from 'rxjs/operators'
3 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } 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 VideoCreate
23 } from '@shared/models'
24 import { environment } from '../../../../environments/environment'
25 import { Account } from '../account/account.model'
26 import { AccountService } from '../account/account.service'
27 import { VideoChannel, VideoChannelService } from '../video-channel'
28 import { VideoDetails } from './video-details.model'
29 import { VideoEdit } from './video-edit.model'
30 import { Video } from './video.model'
31
32 export interface VideosProvider {
33 getVideos (parameters: {
34 videoPagination: ComponentPaginationLight,
35 sort: VideoSortField,
36 filter?: VideoFilter,
37 categoryOneOf?: number[],
38 languageOneOf?: string[]
39 nsfwPolicy: NSFWPolicyType
40 }): Observable<ResultList<Video>>
41 }
42
43 @Injectable()
44 export class VideoService implements VideosProvider {
45 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
46 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
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 params = this.restService.addObjectParams(params, { search })
128
129 return this.authHttp
130 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
131 .pipe(
132 switchMap(res => this.extractVideos(res)),
133 catchError(err => this.restExtractor.handleError(err))
134 )
135 }
136
137 getAccountVideos (parameters: {
138 account: Account,
139 videoPagination: ComponentPaginationLight,
140 sort: VideoSortField
141 nsfwPolicy?: NSFWPolicyType
142 videoFilter?: VideoFilter
143 }): Observable<ResultList<Video>> {
144 const { account, videoPagination, sort, videoFilter, nsfwPolicy } = parameters
145
146 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
147
148 let params = new HttpParams()
149 params = this.restService.addRestGetParams(params, pagination, sort)
150
151 if (nsfwPolicy) {
152 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
153 }
154
155 if (videoFilter) {
156 params = params.set('filter', videoFilter)
157 }
158
159 return this.authHttp
160 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
161 .pipe(
162 switchMap(res => this.extractVideos(res)),
163 catchError(err => this.restExtractor.handleError(err))
164 )
165 }
166
167 getVideoChannelVideos (parameters: {
168 videoChannel: VideoChannel,
169 videoPagination: ComponentPaginationLight,
170 sort: VideoSortField,
171 nsfwPolicy?: NSFWPolicyType
172 videoFilter?: VideoFilter
173 }): Observable<ResultList<Video>> {
174 const { videoChannel, videoPagination, sort, nsfwPolicy, videoFilter } = parameters
175
176 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
177
178 let params = new HttpParams()
179 params = this.restService.addRestGetParams(params, pagination, sort)
180
181 if (nsfwPolicy) {
182 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
183 }
184
185 if (videoFilter) {
186 params = params.set('filter', videoFilter)
187 }
188
189 return this.authHttp
190 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
191 .pipe(
192 switchMap(res => this.extractVideos(res)),
193 catchError(err => this.restExtractor.handleError(err))
194 )
195 }
196
197 getVideos (parameters: {
198 videoPagination: ComponentPaginationLight,
199 sort: VideoSortField,
200 filter?: VideoFilter,
201 categoryOneOf?: number[],
202 languageOneOf?: string[],
203 skipCount?: boolean,
204 nsfwPolicy?: NSFWPolicyType
205 }): Observable<ResultList<Video>> {
206 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy } = parameters
207
208 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
209
210 let params = new HttpParams()
211 params = this.restService.addRestGetParams(params, pagination, sort)
212
213 if (filter) params = params.set('filter', filter)
214 if (skipCount) params = params.set('skipCount', skipCount + '')
215
216 if (nsfwPolicy) {
217 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
218 }
219
220 if (languageOneOf) {
221 for (const l of languageOneOf) {
222 params = params.append('languageOneOf[]', l)
223 }
224 }
225
226 if (categoryOneOf) {
227 for (const c of categoryOneOf) {
228 params = params.append('categoryOneOf[]', c + '')
229 }
230 }
231
232 return this.authHttp
233 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
234 .pipe(
235 switchMap(res => this.extractVideos(res)),
236 catchError(err => this.restExtractor.handleError(err))
237 )
238 }
239
240 buildBaseFeedUrls (params: HttpParams) {
241 const feeds = [
242 {
243 format: FeedFormat.RSS,
244 label: 'media rss 2.0',
245 url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
246 },
247 {
248 format: FeedFormat.ATOM,
249 label: 'atom 1.0',
250 url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
251 },
252 {
253 format: FeedFormat.JSON,
254 label: 'json 1.0',
255 url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
256 }
257 ]
258
259 if (params && params.keys().length !== 0) {
260 for (const feed of feeds) {
261 feed.url += '?' + params.toString()
262 }
263 }
264
265 return feeds
266 }
267
268 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
269 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
270
271 if (filter) params = params.set('filter', filter)
272
273 if (categoryOneOf) {
274 for (const c of categoryOneOf) {
275 params = params.append('categoryOneOf[]', c + '')
276 }
277 }
278
279 return this.buildBaseFeedUrls(params)
280 }
281
282 getAccountFeedUrls (accountId: number) {
283 let params = this.restService.addRestGetParams(new HttpParams())
284 params = params.set('accountId', accountId.toString())
285
286 return this.buildBaseFeedUrls(params)
287 }
288
289 getVideoChannelFeedUrls (videoChannelId: number) {
290 let params = this.restService.addRestGetParams(new HttpParams())
291 params = params.set('videoChannelId', videoChannelId.toString())
292
293 return this.buildBaseFeedUrls(params)
294 }
295
296 getVideoFileMetadata (metadataUrl: string) {
297 return this.authHttp
298 .get<VideoFileMetadata>(metadataUrl)
299 .pipe(
300 catchError(err => this.restExtractor.handleError(err))
301 )
302 }
303
304 removeVideo (id: number) {
305 return this.authHttp
306 .delete(VideoService.BASE_VIDEO_URL + id)
307 .pipe(
308 map(this.restExtractor.extractDataBool),
309 catchError(err => this.restExtractor.handleError(err))
310 )
311 }
312
313 loadCompleteDescription (descriptionPath: string) {
314 return this.authHttp
315 .get<{ description: string }>(environment.apiUrl + descriptionPath)
316 .pipe(
317 map(res => res.description),
318 catchError(err => this.restExtractor.handleError(err))
319 )
320 }
321
322 setVideoLike (id: number) {
323 return this.setVideoRate(id, 'like')
324 }
325
326 setVideoDislike (id: number) {
327 return this.setVideoRate(id, 'dislike')
328 }
329
330 unsetVideoLike (id: number) {
331 return this.setVideoRate(id, 'none')
332 }
333
334 getUserVideoRating (id: number) {
335 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
336
337 return this.authHttp.get<UserVideoRate>(url)
338 .pipe(catchError(err => this.restExtractor.handleError(err)))
339 }
340
341 extractVideos (result: ResultList<VideoServerModel>) {
342 return this.serverService.getServerLocale()
343 .pipe(
344 map(translations => {
345 const videosJson = result.data
346 const totalVideos = result.total
347 const videos: Video[] = []
348
349 for (const videoJson of videosJson) {
350 videos.push(new Video(videoJson, translations))
351 }
352
353 return { total: totalVideos, data: videos }
354 })
355 )
356 }
357
358 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
359 const base = [
360 {
361 id: VideoPrivacy.PRIVATE,
362 description: $localize`Only I can see this video`
363 },
364 {
365 id: VideoPrivacy.UNLISTED,
366 description: $localize`Only shareable via a private link`
367 },
368 {
369 id: VideoPrivacy.PUBLIC,
370 description: $localize`Anyone can see this video`
371 },
372 {
373 id: VideoPrivacy.INTERNAL,
374 description: $localize`Only users of this instance can see this video`
375 }
376 ]
377
378 return base
379 .filter(o => !!privacies.find(p => p.id === o.id)) // filter down to privacies that where in the input
380 .map(o => ({ ...privacies[o.id - 1], ...o })) // merge the input privacies that contain a label, and extend them with a description
381 }
382
383 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
384 return nsfwPolicy === 'do_not_list'
385 ? 'false'
386 : 'both'
387 }
388
389 private setVideoRate (id: number, rateType: UserVideoRateType) {
390 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
391 const body: UserVideoRateUpdate = {
392 rating: rateType
393 }
394
395 return this.authHttp
396 .put(url, body)
397 .pipe(
398 map(this.restExtractor.extractDataBool),
399 catchError(err => this.restExtractor.handleError(err))
400 )
401 }
402 }