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