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