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