]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/video/video.service.ts
60cc9d16012a0c9e13c78a6733813f5dea652bdf
[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 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 }
134 })
135
136 params = this.restService.addObjectParams(params, filters)
137 }
138
139 return this.authHttp
140 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
141 .pipe(
142 switchMap(res => this.extractVideos(res)),
143 catchError(err => this.restExtractor.handleError(err))
144 )
145 }
146
147 getAccountVideos (parameters: {
148 account: Pick<Account, 'nameWithHost'>
149 videoPagination: ComponentPaginationLight
150 sort: VideoSortField
151 nsfwPolicy?: NSFWPolicyType
152 videoFilter?: VideoFilter
153 search?: string
154 }): Observable<ResultList<Video>> {
155 const { account, videoPagination, sort, videoFilter, nsfwPolicy, search } = parameters
156
157 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
158
159 let params = new HttpParams()
160 params = this.restService.addRestGetParams(params, pagination, sort)
161
162 if (nsfwPolicy) {
163 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
164 }
165
166 if (videoFilter) {
167 params = params.set('filter', videoFilter)
168 }
169
170 if (search) {
171 params = params.set('search', search)
172 }
173
174 return this.authHttp
175 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
176 .pipe(
177 switchMap(res => this.extractVideos(res)),
178 catchError(err => this.restExtractor.handleError(err))
179 )
180 }
181
182 getVideoChannelVideos (parameters: {
183 videoChannel: Pick<VideoChannel, 'nameWithHost'>
184 videoPagination: ComponentPaginationLight
185 sort: VideoSortField
186 nsfwPolicy?: NSFWPolicyType
187 videoFilter?: VideoFilter
188 }): Observable<ResultList<Video>> {
189 const { videoChannel, videoPagination, sort, nsfwPolicy, videoFilter } = parameters
190
191 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
192
193 let params = new HttpParams()
194 params = this.restService.addRestGetParams(params, pagination, sort)
195
196 if (nsfwPolicy) {
197 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
198 }
199
200 if (videoFilter) {
201 params = params.set('filter', videoFilter)
202 }
203
204 return this.authHttp
205 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
206 .pipe(
207 switchMap(res => this.extractVideos(res)),
208 catchError(err => this.restExtractor.handleError(err))
209 )
210 }
211
212 getVideos (parameters: {
213 videoPagination: ComponentPaginationLight
214 sort: VideoSortField
215 filter?: VideoFilter
216 categoryOneOf?: number[]
217 languageOneOf?: string[]
218 isLive?: boolean
219 skipCount?: boolean
220 nsfwPolicy?: NSFWPolicyType
221 }): Observable<ResultList<Video>> {
222 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy, isLive } = parameters
223
224 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
225
226 let params = new HttpParams()
227 params = this.restService.addRestGetParams(params, pagination, sort)
228
229 if (filter) params = params.set('filter', filter)
230 if (skipCount) params = params.set('skipCount', skipCount + '')
231
232 if (isLive) params = params.set('isLive', isLive)
233 if (nsfwPolicy) params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
234 if (languageOneOf) this.restService.addArrayParams(params, 'languageOneOf', languageOneOf)
235 if (categoryOneOf) this.restService.addArrayParams(params, 'categoryOneOf', categoryOneOf)
236
237 return this.authHttp
238 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
239 .pipe(
240 switchMap(res => this.extractVideos(res)),
241 catchError(err => this.restExtractor.handleError(err))
242 )
243 }
244
245 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
246 const feeds = [
247 {
248 format: FeedFormat.RSS,
249 label: 'media rss 2.0',
250 url: base + FeedFormat.RSS.toLowerCase()
251 },
252 {
253 format: FeedFormat.ATOM,
254 label: 'atom 1.0',
255 url: base + FeedFormat.ATOM.toLowerCase()
256 },
257 {
258 format: FeedFormat.JSON,
259 label: 'json 1.0',
260 url: base + FeedFormat.JSON.toLowerCase()
261 }
262 ]
263
264 if (params && params.keys().length !== 0) {
265 for (const feed of feeds) {
266 feed.url += '?' + params.toString()
267 }
268 }
269
270 return feeds
271 }
272
273 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
274 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
275
276 if (filter) params = params.set('filter', filter)
277
278 if (categoryOneOf) {
279 for (const c of categoryOneOf) {
280 params = params.append('categoryOneOf[]', c + '')
281 }
282 }
283
284 return this.buildBaseFeedUrls(params)
285 }
286
287 getAccountFeedUrls (accountId: number) {
288 let params = this.restService.addRestGetParams(new HttpParams())
289 params = params.set('accountId', accountId.toString())
290
291 return this.buildBaseFeedUrls(params)
292 }
293
294 getVideoChannelFeedUrls (videoChannelId: number) {
295 let params = this.restService.addRestGetParams(new HttpParams())
296 params = params.set('videoChannelId', videoChannelId.toString())
297
298 return this.buildBaseFeedUrls(params)
299 }
300
301 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
302 let params = this.restService.addRestGetParams(new HttpParams())
303 params = params.set('accountId', accountId.toString())
304 params = params.set('token', feedToken)
305
306 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
307 }
308
309 getVideoFileMetadata (metadataUrl: string) {
310 return this.authHttp
311 .get<VideoFileMetadata>(metadataUrl)
312 .pipe(
313 catchError(err => this.restExtractor.handleError(err))
314 )
315 }
316
317 removeVideo (id: number) {
318 return this.authHttp
319 .delete(VideoService.BASE_VIDEO_URL + id)
320 .pipe(
321 map(this.restExtractor.extractDataBool),
322 catchError(err => this.restExtractor.handleError(err))
323 )
324 }
325
326 loadCompleteDescription (descriptionPath: string) {
327 return this.authHttp
328 .get<{ description: string }>(environment.apiUrl + descriptionPath)
329 .pipe(
330 map(res => res.description),
331 catchError(err => this.restExtractor.handleError(err))
332 )
333 }
334
335 setVideoLike (id: number) {
336 return this.setVideoRate(id, 'like')
337 }
338
339 setVideoDislike (id: number) {
340 return this.setVideoRate(id, 'dislike')
341 }
342
343 unsetVideoLike (id: number) {
344 return this.setVideoRate(id, 'none')
345 }
346
347 getUserVideoRating (id: number) {
348 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
349
350 return this.authHttp.get<UserVideoRate>(url)
351 .pipe(catchError(err => this.restExtractor.handleError(err)))
352 }
353
354 extractVideos (result: ResultList<VideoServerModel>) {
355 return this.serverService.getServerLocale()
356 .pipe(
357 map(translations => {
358 const videosJson = result.data
359 const totalVideos = result.total
360 const videos: Video[] = []
361
362 for (const videoJson of videosJson) {
363 videos.push(new Video(videoJson, translations))
364 }
365
366 return { total: totalVideos, data: videos }
367 })
368 )
369 }
370
371 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
372 const descriptions = {
373 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
374 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
375 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
376 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
377 }
378
379 const videoPrivacies = serverPrivacies.map(p => {
380 return {
381 ...p,
382
383 description: descriptions[p.id]
384 }
385 })
386
387 return {
388 videoPrivacies,
389 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
390 }
391 }
392
393 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
394 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
395
396 for (const privacy of order) {
397 if (serverPrivacies.find(p => p.id === privacy)) {
398 return privacy
399 }
400 }
401
402 throw new Error('No highest privacy available')
403 }
404
405 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
406 return nsfwPolicy === 'do_not_list'
407 ? 'false'
408 : 'both'
409 }
410
411 private setVideoRate (id: number, rateType: UserVideoRateType) {
412 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
413 const body: UserVideoRateUpdate = {
414 rating: rateType
415 }
416
417 return this.authHttp
418 .put(url, body)
419 .pipe(
420 map(this.restExtractor.extractDataBool),
421 catchError(err => this.restExtractor.handleError(err))
422 )
423 }
424 }