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