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'
15 } from '../../../../../shared/models/videos'
16 import { FeedFormat } from '../../../../../shared/models/feeds/feed-format.enum'
17 import { environment } from '../../../environments/environment'
18 import { ComponentPaginationLight } 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, AuthService } 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 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
36 export interface VideosProvider {
37 getVideos (parameters: {
38 videoPagination: ComponentPaginationLight,
41 categoryOneOf?: number,
42 languageOneOf?: string[]
43 }): Observable<ResultList<Video>>
47 export class VideoService implements VideosProvider {
48 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
49 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
52 private authHttp: HttpClient,
53 private authService: AuthService,
54 private userService: UserService,
55 private restExtractor: RestExtractor,
56 private restService: RestService,
57 private serverService: ServerService,
61 getVideoViewUrl (uuid: string) {
62 return VideoService.BASE_VIDEO_URL + uuid + '/views'
65 getUserWatchingVideoUrl (uuid: string) {
66 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
69 getVideo (options: { videoId: string }): Observable<VideoDetails> {
70 return this.serverService.getServerLocale()
72 switchMap(translations => {
73 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
74 .pipe(map(videoHash => ({ videoHash, translations })))
76 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
77 catchError(err => this.restExtractor.handleError(err))
81 updateVideo (video: VideoEdit) {
82 const language = video.language || null
83 const licence = video.licence || null
84 const category = video.category || null
85 const description = video.description || null
86 const support = video.support || null
87 const scheduleUpdate = video.scheduleUpdate || null
88 const originallyPublishedAt = video.originallyPublishedAt || null
90 const body: VideoUpdate = {
97 channelId: video.channelId,
98 privacy: video.privacy,
101 waitTranscoding: video.waitTranscoding,
102 commentsEnabled: video.commentsEnabled,
103 downloadEnabled: video.downloadEnabled,
104 thumbnailfile: video.thumbnailfile,
105 previewfile: video.previewfile,
107 originallyPublishedAt
110 const data = objectToFormData(body)
112 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
114 map(this.restExtractor.extractDataBool),
115 catchError(err => this.restExtractor.handleError(err))
119 uploadVideo (video: FormData) {
120 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
123 .request<{ video: { id: number, uuid: string } }>(req)
124 .pipe(catchError(err => this.restExtractor.handleError(err)))
127 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
128 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
130 let params = new HttpParams()
131 params = this.restService.addRestGetParams(params, pagination, sort)
132 params = this.restService.addObjectParams(params, { search })
135 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
137 switchMap(res => this.extractVideos(res)),
138 catchError(err => this.restExtractor.handleError(err))
144 videoPagination: ComponentPaginationLight,
146 ): Observable<ResultList<Video>> {
147 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
149 let params = new HttpParams()
150 params = this.restService.addRestGetParams(params, pagination, sort)
153 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
155 switchMap(res => this.extractVideos(res)),
156 catchError(err => this.restExtractor.handleError(err))
160 getVideoChannelVideos (
161 videoChannel: VideoChannel,
162 videoPagination: ComponentPaginationLight,
164 ): Observable<ResultList<Video>> {
165 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
167 let params = new HttpParams()
168 params = this.restService.addRestGetParams(params, pagination, sort)
171 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
173 switchMap(res => this.extractVideos(res)),
174 catchError(err => this.restExtractor.handleError(err))
178 getUserSubscriptionVideos (parameters: {
179 videoPagination: ComponentPaginationLight,
180 sort: VideoSortField,
182 }): Observable<ResultList<Video>> {
183 const { videoPagination, sort, skipCount } = parameters
184 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
186 let params = new HttpParams()
187 params = this.restService.addRestGetParams(params, pagination, sort)
189 if (skipCount) params = params.set('skipCount', skipCount + '')
192 .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
194 switchMap(res => this.extractVideos(res)),
195 catchError(err => this.restExtractor.handleError(err))
199 getVideos (parameters: {
200 videoPagination: ComponentPaginationLight,
201 sort: VideoSortField,
202 filter?: VideoFilter,
203 categoryOneOf?: number,
204 languageOneOf?: string[],
207 }): Observable<ResultList<Video>> {
208 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfw } = parameters
210 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
212 let params = new HttpParams()
213 params = this.restService.addRestGetParams(params, pagination, sort)
215 if (filter) params = params.set('filter', filter)
216 if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
217 if (skipCount) params = params.set('skipCount', skipCount + '')
220 params = params.set('nsfw', nsfw + '')
222 const nsfwPolicy = this.authService.isLoggedIn()
223 ? this.authService.getUser().nsfwPolicy
224 : this.userService.getAnonymousUser().nsfwPolicy
225 if (this.nsfwPolicyToFilter(nsfwPolicy)) params.set('nsfw', 'false')
229 for (const l of languageOneOf) {
230 params = params.append('languageOneOf[]', l)
235 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
237 switchMap(res => this.extractVideos(res)),
238 catchError(err => this.restExtractor.handleError(err))
242 buildBaseFeedUrls (params: HttpParams) {
245 format: FeedFormat.RSS,
247 url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
250 format: FeedFormat.ATOM,
252 url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
255 format: FeedFormat.JSON,
257 url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
261 if (params && params.keys().length !== 0) {
262 for (const feed of feeds) {
263 feed.url += '?' + params.toString()
270 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number) {
271 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
273 if (filter) params = params.set('filter', filter)
275 if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
277 return this.buildBaseFeedUrls(params)
280 getAccountFeedUrls (accountId: number) {
281 let params = this.restService.addRestGetParams(new HttpParams())
282 params = params.set('accountId', accountId.toString())
284 return this.buildBaseFeedUrls(params)
287 getVideoChannelFeedUrls (videoChannelId: number) {
288 let params = this.restService.addRestGetParams(new HttpParams())
289 params = params.set('videoChannelId', videoChannelId.toString())
291 return this.buildBaseFeedUrls(params)
294 removeVideo (id: number) {
296 .delete(VideoService.BASE_VIDEO_URL + id)
298 map(this.restExtractor.extractDataBool),
299 catchError(err => this.restExtractor.handleError(err))
303 loadCompleteDescription (descriptionPath: string) {
305 .get<{ description: string }>(environment.apiUrl + descriptionPath)
307 map(res => res.description),
308 catchError(err => this.restExtractor.handleError(err))
312 setVideoLike (id: number) {
313 return this.setVideoRate(id, 'like')
316 setVideoDislike (id: number) {
317 return this.setVideoRate(id, 'dislike')
320 unsetVideoLike (id: number) {
321 return this.setVideoRate(id, 'none')
324 getUserVideoRating (id: number) {
325 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
327 return this.authHttp.get<UserVideoRate>(url)
328 .pipe(catchError(err => this.restExtractor.handleError(err)))
331 extractVideos (result: ResultList<VideoServerModel>) {
332 return this.serverService.getServerLocale()
334 map(translations => {
335 const videosJson = result.data
336 const totalVideos = result.total
337 const videos: Video[] = []
339 for (const videoJson of videosJson) {
340 videos.push(new Video(videoJson, translations))
343 return { total: totalVideos, data: videos }
348 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
351 id: VideoPrivacy.PRIVATE,
352 label: this.i18n('Only I can see this video')
355 id: VideoPrivacy.UNLISTED,
356 label: this.i18n('Only people with the private link can see this video')
359 id: VideoPrivacy.PUBLIC,
360 label: this.i18n('Anyone can see this video')
363 id: VideoPrivacy.INTERNAL,
364 label: this.i18n('Only users of this instance can see this video')
368 return base.filter(o => !!privacies.find(p => p.id === o.id))
371 private setVideoRate (id: number, rateType: UserVideoRateType) {
372 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
373 const body: UserVideoRateUpdate = {
380 map(this.restExtractor.extractDataBool),
381 catchError(err => this.restExtractor.handleError(err))
385 private nsfwPolicyToFilter (policy: NSFWPolicyType) {
386 return policy === 'do_not_list'