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