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