Rename streaming playlists routes/directories
[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 { ComponentPagination } 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 (
37     videoPagination: ComponentPagination,
38     sort: VideoSortField,
39     filter?: VideoFilter,
40     categoryOneOf?: number
41   ): Observable<{ videos: Video[], totalVideos: number }>
42 }
43
44 @Injectable()
45 export class VideoService implements VideosProvider {
46   static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
47   static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
48
49   constructor (
50     private authHttp: HttpClient,
51     private restExtractor: RestExtractor,
52     private restService: RestService,
53     private serverService: ServerService,
54     private i18n: I18n
55   ) {}
56
57   getVideoViewUrl (uuid: string) {
58     return VideoService.BASE_VIDEO_URL + uuid + '/views'
59   }
60
61   getUserWatchingVideoUrl (uuid: string) {
62     return VideoService.BASE_VIDEO_URL + uuid + '/watching'
63   }
64
65   getVideo (uuid: string): Observable<VideoDetails> {
66     return this.serverService.localeObservable
67                .pipe(
68                  switchMap(translations => {
69                    return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + uuid)
70                               .pipe(map(videoHash => ({ videoHash, translations })))
71                  }),
72                  map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
73                  catchError(err => this.restExtractor.handleError(err))
74                )
75   }
76
77   updateVideo (video: VideoEdit) {
78     const language = video.language || null
79     const licence = video.licence || null
80     const category = video.category || null
81     const description = video.description || null
82     const support = video.support || null
83     const scheduleUpdate = video.scheduleUpdate || null
84     const originallyPublishedAt = video.originallyPublishedAt || null
85
86     const body: VideoUpdate = {
87       name: video.name,
88       category,
89       licence,
90       language,
91       support,
92       description,
93       channelId: video.channelId,
94       privacy: video.privacy,
95       tags: video.tags,
96       nsfw: video.nsfw,
97       waitTranscoding: video.waitTranscoding,
98       commentsEnabled: video.commentsEnabled,
99       downloadEnabled: video.downloadEnabled,
100       thumbnailfile: video.thumbnailfile,
101       previewfile: video.previewfile,
102       scheduleUpdate,
103       originallyPublishedAt
104     }
105
106     const data = objectToFormData(body)
107
108     return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
109                .pipe(
110                  map(this.restExtractor.extractDataBool),
111                  catchError(err => this.restExtractor.handleError(err))
112                )
113   }
114
115   uploadVideo (video: FormData) {
116     const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
117
118     return this.authHttp
119                .request<{ video: { id: number, uuid: string } }>(req)
120                .pipe(catchError(err => this.restExtractor.handleError(err)))
121   }
122
123   getMyVideos (videoPagination: ComponentPagination, sort: VideoSortField): 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>>(UserService.BASE_USERS_URL + '/me/videos', { params })
131                .pipe(
132                  switchMap(res => this.extractVideos(res)),
133                  catchError(err => this.restExtractor.handleError(err))
134                )
135   }
136
137   getAccountVideos (
138     account: Account,
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>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
149                .pipe(
150                  switchMap(res => this.extractVideos(res)),
151                  catchError(err => this.restExtractor.handleError(err))
152                )
153   }
154
155   getVideoChannelVideos (
156     videoChannel: VideoChannel,
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>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
167                .pipe(
168                  switchMap(res => this.extractVideos(res)),
169                  catchError(err => this.restExtractor.handleError(err))
170                )
171   }
172
173   getUserSubscriptionVideos (
174     videoPagination: ComponentPagination,
175     sort: VideoSortField
176   ): Observable<{ videos: Video[], totalVideos: number }> {
177     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
178
179     let params = new HttpParams()
180     params = this.restService.addRestGetParams(params, pagination, sort)
181
182     return this.authHttp
183                .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
184                .pipe(
185                  switchMap(res => this.extractVideos(res)),
186                  catchError(err => this.restExtractor.handleError(err))
187                )
188   }
189
190   getVideos (
191     videoPagination: ComponentPagination,
192     sort: VideoSortField,
193     filter?: VideoFilter,
194     categoryOneOf?: number
195   ): Observable<{ videos: Video[], totalVideos: number }> {
196     const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
197
198     let params = new HttpParams()
199     params = this.restService.addRestGetParams(params, pagination, sort)
200
201     if (filter) {
202       params = params.set('filter', filter)
203     }
204
205     if (categoryOneOf) {
206       params = params.set('categoryOneOf', categoryOneOf + '')
207     }
208
209     return this.authHttp
210                .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
211                .pipe(
212                  switchMap(res => this.extractVideos(res)),
213                  catchError(err => this.restExtractor.handleError(err))
214                )
215   }
216
217   buildBaseFeedUrls (params: HttpParams) {
218     const feeds = [
219       {
220         format: FeedFormat.RSS,
221         label: 'rss 2.0',
222         url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
223       },
224       {
225         format: FeedFormat.ATOM,
226         label: 'atom 1.0',
227         url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
228       },
229       {
230         format: FeedFormat.JSON,
231         label: 'json 1.0',
232         url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
233       }
234     ]
235
236     if (params && params.keys().length !== 0) {
237       for (const feed of feeds) {
238         feed.url += '?' + params.toString()
239       }
240     }
241
242     return feeds
243   }
244
245   getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number) {
246     let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
247
248     if (filter) params = params.set('filter', filter)
249
250     if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
251
252     return this.buildBaseFeedUrls(params)
253   }
254
255   getAccountFeedUrls (accountId: number) {
256     let params = this.restService.addRestGetParams(new HttpParams())
257     params = params.set('accountId', accountId.toString())
258
259     return this.buildBaseFeedUrls(params)
260   }
261
262   getVideoChannelFeedUrls (videoChannelId: number) {
263     let params = this.restService.addRestGetParams(new HttpParams())
264     params = params.set('videoChannelId', videoChannelId.toString())
265
266     return this.buildBaseFeedUrls(params)
267   }
268
269   removeVideo (id: number) {
270     return this.authHttp
271                .delete(VideoService.BASE_VIDEO_URL + id)
272                .pipe(
273                  map(this.restExtractor.extractDataBool),
274                  catchError(err => this.restExtractor.handleError(err))
275                )
276   }
277
278   loadCompleteDescription (descriptionPath: string) {
279     return this.authHttp
280                .get<{ description: string }>(environment.apiUrl + descriptionPath)
281                .pipe(
282                  map(res => res.description),
283                  catchError(err => this.restExtractor.handleError(err))
284                )
285   }
286
287   setVideoLike (id: number) {
288     return this.setVideoRate(id, 'like')
289   }
290
291   setVideoDislike (id: number) {
292     return this.setVideoRate(id, 'dislike')
293   }
294
295   unsetVideoLike (id: number) {
296     return this.setVideoRate(id, 'none')
297   }
298
299   getUserVideoRating (id: number) {
300     const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
301
302     return this.authHttp.get<UserVideoRate>(url)
303                .pipe(catchError(err => this.restExtractor.handleError(err)))
304   }
305
306   extractVideos (result: ResultList<VideoServerModel>) {
307     return this.serverService.localeObservable
308                .pipe(
309                  map(translations => {
310                    const videosJson = result.data
311                    const totalVideos = result.total
312                    const videos: Video[] = []
313
314                    for (const videoJson of videosJson) {
315                      videos.push(new Video(videoJson, translations))
316                    }
317
318                    return { videos, totalVideos }
319                  })
320                )
321   }
322
323   explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
324     const newPrivacies = privacies.slice()
325
326     const privatePrivacy = newPrivacies.find(p => p.id === VideoPrivacy.PRIVATE)
327     if (privatePrivacy) privatePrivacy.label = this.i18n('Only I can see this video')
328
329     const unlistedPrivacy = newPrivacies.find(p => p.id === VideoPrivacy.UNLISTED)
330     if (unlistedPrivacy) unlistedPrivacy.label = this.i18n('Only people with the private link can see this video')
331
332     const publicPrivacy = newPrivacies.find(p => p.id === VideoPrivacy.PUBLIC)
333     if (publicPrivacy) publicPrivacy.label = this.i18n('Anyone can see this video')
334
335     return privacies
336   }
337
338   private setVideoRate (id: number, rateType: UserVideoRateType) {
339     const url = VideoService.BASE_VIDEO_URL + id + '/rate'
340     const body: UserVideoRateUpdate = {
341       rating: rateType
342     }
343
344     return this.authHttp
345                .put(url, body)
346                .pipe(
347                  map(this.restExtractor.extractDataBool),
348                  catchError(err => this.restExtractor.handleError(err))
349                )
350   }
351 }