Try to fix subscriptions inconsistencies
[oweals/peertube.git] / client / src / app / shared / video / video.service.ts
1 import { catchError, map, switchMap } from 'rxjs/operators'
2 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
3 import { Injectable } from '@angular/core'
4 import { Observable } from 'rxjs'
5 import { Video as VideoServerModel, VideoDetails as VideoDetailsServerModel } from '../../../../../shared'
6 import { ResultList } from '../../../../../shared/models/result-list.model'
7 import {
8   UserVideoRate,
9   UserVideoRateType,
10   UserVideoRateUpdate,
11   VideoConstant,
12   VideoFilter,
13   VideoPrivacy,
14   VideoUpdate
15 } from '../../../../../shared/models/videos'
16 import { FeedFormat } from '../../../../../shared/models/feeds/feed-format.enum'
17 import { environment } from '../../../environments/environment'
18 import { ComponentPaginationLight } from '../rest/component-pagination.model'
19 import { RestExtractor } from '../rest/rest-extractor.service'
20 import { RestService } from '../rest/rest.service'
21 import { UserService } from '../users/user.service'
22 import { VideoSortField } from './sort-field.type'
23 import { VideoDetails } from './video-details.model'
24 import { VideoEdit } from './video-edit.model'
25 import { Video } from './video.model'
26 import { objectToFormData } from '@app/shared/misc/utils'
27 import { Account } from '@app/shared/account/account.model'
28 import { AccountService } from '@app/shared/account/account.service'
29 import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
30 import { ServerService } from '@app/core'
31 import { UserSubscriptionService } from '@app/shared/user-subscription/user-subscription.service'
32 import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
33 import { I18n } from '@ngx-translate/i18n-polyfill'
34
35 export interface VideosProvider {
36   getVideos (parameters: {
37     videoPagination: ComponentPaginationLight,
38     sort: VideoSortField,
39     filter?: VideoFilter,
40     categoryOneOf?: number,
41     languageOneOf?: string[]
42   }): Observable<ResultList<Video>>
43 }
44
45 @Injectable()
46 export class VideoService implements VideosProvider {
47   static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
48   static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
49
50   constructor (
51     private authHttp: HttpClient,
52     private restExtractor: RestExtractor,
53     private restService: RestService,
54     private serverService: ServerService,
55     private i18n: I18n
56   ) {}
57
58   getVideoViewUrl (uuid: string) {
59     return VideoService.BASE_VIDEO_URL + uuid + '/views'
60   }
61
62   getUserWatchingVideoUrl (uuid: string) {
63     return VideoService.BASE_VIDEO_URL + uuid + '/watching'
64   }
65
66   getVideo (options: { videoId: string }): Observable<VideoDetails> {
67     return this.serverService.getServerLocale()
68                .pipe(
69                  switchMap(translations => {
70                    return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
71                               .pipe(map(videoHash => ({ videoHash, translations })))
72                  }),
73                  map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
74                  catchError(err => this.restExtractor.handleError(err))
75                )
76   }
77
78   updateVideo (video: VideoEdit) {
79     const language = video.language || null
80     const licence = video.licence || null
81     const category = video.category || null
82     const description = video.description || null
83     const support = video.support || null
84     const scheduleUpdate = video.scheduleUpdate || null
85     const originallyPublishedAt = video.originallyPublishedAt || null
86
87     const body: VideoUpdate = {
88       name: video.name,
89       category,
90       licence,
91       language,
92       support,
93       description,
94       channelId: video.channelId,
95       privacy: video.privacy,
96       tags: video.tags,
97       nsfw: video.nsfw,
98       waitTranscoding: video.waitTranscoding,
99       commentsEnabled: video.commentsEnabled,
100       downloadEnabled: video.downloadEnabled,
101       thumbnailfile: video.thumbnailfile,
102       previewfile: video.previewfile,
103       scheduleUpdate,
104       originallyPublishedAt
105     }
106
107     const data = objectToFormData(body)
108
109     return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
110                .pipe(
111                  map(this.restExtractor.extractDataBool),
112                  catchError(err => this.restExtractor.handleError(err))
113                )
114   }
115
116   uploadVideo (video: FormData) {
117     const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
118
119     return this.authHttp
120                .request<{ video: { id: number, uuid: string } }>(req)
121                .pipe(catchError(err => this.restExtractor.handleError(err)))
122   }
123
124   getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
125     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
126
127     let params = new HttpParams()
128     params = this.restService.addRestGetParams(params, pagination, sort)
129     params = this.restService.addObjectParams(params, { search })
130
131     return this.authHttp
132                .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
133                .pipe(
134                  switchMap(res => this.extractVideos(res)),
135                  catchError(err => this.restExtractor.handleError(err))
136                )
137   }
138
139   getAccountVideos (
140     account: Account,
141     videoPagination: ComponentPaginationLight,
142     sort: VideoSortField
143   ): Observable<ResultList<Video>> {
144     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
145
146     let params = new HttpParams()
147     params = this.restService.addRestGetParams(params, pagination, sort)
148
149     return this.authHttp
150                .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
151                .pipe(
152                  switchMap(res => this.extractVideos(res)),
153                  catchError(err => this.restExtractor.handleError(err))
154                )
155   }
156
157   getVideoChannelVideos (
158     videoChannel: VideoChannel,
159     videoPagination: ComponentPaginationLight,
160     sort: VideoSortField
161   ): Observable<ResultList<Video>> {
162     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
163
164     let params = new HttpParams()
165     params = this.restService.addRestGetParams(params, pagination, sort)
166
167     return this.authHttp
168                .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
169                .pipe(
170                  switchMap(res => this.extractVideos(res)),
171                  catchError(err => this.restExtractor.handleError(err))
172                )
173   }
174
175   getUserSubscriptionVideos (parameters: {
176     videoPagination: ComponentPaginationLight,
177     sort: VideoSortField,
178     skipCount?: boolean
179   }): Observable<ResultList<Video>> {
180     const { videoPagination, sort, skipCount } = parameters
181     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
182
183     let params = new HttpParams()
184     params = this.restService.addRestGetParams(params, pagination, sort)
185
186     if (skipCount) params = params.set('skipCount', skipCount + '')
187
188     return this.authHttp
189                .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
190                .pipe(
191                  switchMap(res => this.extractVideos(res)),
192                  catchError(err => this.restExtractor.handleError(err))
193                )
194   }
195
196   getVideos (parameters: {
197     videoPagination: ComponentPaginationLight,
198     sort: VideoSortField,
199     filter?: VideoFilter,
200     categoryOneOf?: number,
201     languageOneOf?: string[],
202     skipCount?: boolean
203   }): Observable<ResultList<Video>> {
204     const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount } = parameters
205
206     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
207
208     let params = new HttpParams()
209     params = this.restService.addRestGetParams(params, pagination, sort)
210
211     if (filter) params = params.set('filter', filter)
212     if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
213     if (skipCount) params = params.set('skipCount', skipCount + '')
214
215     if (languageOneOf) {
216       for (const l of languageOneOf) {
217         params = params.append('languageOneOf[]', l)
218       }
219     }
220
221     return this.authHttp
222                .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
223                .pipe(
224                  switchMap(res => this.extractVideos(res)),
225                  catchError(err => this.restExtractor.handleError(err))
226                )
227   }
228
229   buildBaseFeedUrls (params: HttpParams) {
230     const feeds = [
231       {
232         format: FeedFormat.RSS,
233         label: 'rss 2.0',
234         url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
235       },
236       {
237         format: FeedFormat.ATOM,
238         label: 'atom 1.0',
239         url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
240       },
241       {
242         format: FeedFormat.JSON,
243         label: 'json 1.0',
244         url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
245       }
246     ]
247
248     if (params && params.keys().length !== 0) {
249       for (const feed of feeds) {
250         feed.url += '?' + params.toString()
251       }
252     }
253
254     return feeds
255   }
256
257   getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number) {
258     let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
259
260     if (filter) params = params.set('filter', filter)
261
262     if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
263
264     return this.buildBaseFeedUrls(params)
265   }
266
267   getAccountFeedUrls (accountId: number) {
268     let params = this.restService.addRestGetParams(new HttpParams())
269     params = params.set('accountId', accountId.toString())
270
271     return this.buildBaseFeedUrls(params)
272   }
273
274   getVideoChannelFeedUrls (videoChannelId: number) {
275     let params = this.restService.addRestGetParams(new HttpParams())
276     params = params.set('videoChannelId', videoChannelId.toString())
277
278     return this.buildBaseFeedUrls(params)
279   }
280
281   removeVideo (id: number) {
282     return this.authHttp
283                .delete(VideoService.BASE_VIDEO_URL + id)
284                .pipe(
285                  map(this.restExtractor.extractDataBool),
286                  catchError(err => this.restExtractor.handleError(err))
287                )
288   }
289
290   loadCompleteDescription (descriptionPath: string) {
291     return this.authHttp
292                .get<{ description: string }>(environment.apiUrl + descriptionPath)
293                .pipe(
294                  map(res => res.description),
295                  catchError(err => this.restExtractor.handleError(err))
296                )
297   }
298
299   setVideoLike (id: number) {
300     return this.setVideoRate(id, 'like')
301   }
302
303   setVideoDislike (id: number) {
304     return this.setVideoRate(id, 'dislike')
305   }
306
307   unsetVideoLike (id: number) {
308     return this.setVideoRate(id, 'none')
309   }
310
311   getUserVideoRating (id: number) {
312     const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
313
314     return this.authHttp.get<UserVideoRate>(url)
315                .pipe(catchError(err => this.restExtractor.handleError(err)))
316   }
317
318   extractVideos (result: ResultList<VideoServerModel>) {
319     return this.serverService.getServerLocale()
320                .pipe(
321                  map(translations => {
322                    const videosJson = result.data
323                    const totalVideos = result.total
324                    const videos: Video[] = []
325
326                    for (const videoJson of videosJson) {
327                      videos.push(new Video(videoJson, translations))
328                    }
329
330                    return { total: totalVideos, data: videos }
331                  })
332                )
333   }
334
335   explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
336     const base = [
337       {
338         id: VideoPrivacy.PRIVATE,
339         label: this.i18n('Only I can see this video')
340       },
341       {
342         id: VideoPrivacy.UNLISTED,
343         label: this.i18n('Only people with the private link can see this video')
344       },
345       {
346         id: VideoPrivacy.PUBLIC,
347         label: this.i18n('Anyone can see this video')
348       },
349       {
350         id: VideoPrivacy.INTERNAL,
351         label: this.i18n('Only users of this instance can see this video')
352       }
353     ]
354
355     return base.filter(o => !!privacies.find(p => p.id === o.id))
356   }
357
358   private setVideoRate (id: number, rateType: UserVideoRateType) {
359     const url = VideoService.BASE_VIDEO_URL + id + '/rate'
360     const body: UserVideoRateUpdate = {
361       rating: rateType
362     }
363
364     return this.authHttp
365                .put(url, body)
366                .pipe(
367                  map(this.restExtractor.extractDataBool),
368                  catchError(err => this.restExtractor.handleError(err))
369                )
370   }
371 }