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