1 import { Observable, of, throwError } from 'rxjs'
2 import { catchError, map, mergeMap, switchMap } from 'rxjs/operators'
3 import { HttpClient, HttpErrorResponse, HttpParams, HttpRequest } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService, AuthService } from '@app/core'
6 import { objectToFormData } from '@app/helpers'
14 Video as VideoServerModel,
16 VideoDetails as VideoDetailsServerModel,
22 } from '@shared/models'
23 import { environment } from '../../../../environments/environment'
24 import { Account } from '../account/account.model'
25 import { AccountService } from '../account/account.service'
26 import { VideoChannel, VideoChannelService } from '../video-channel'
27 import { VideoDetails } from './video-details.model'
28 import { VideoEdit } from './video-edit.model'
29 import { Video } from './video.model'
31 export interface VideosProvider {
32 getVideos (parameters: {
33 videoPagination: ComponentPaginationLight,
36 categoryOneOf?: number[],
37 languageOneOf?: string[]
38 nsfwPolicy: NSFWPolicyType
39 }): Observable<ResultList<Video>>
43 export class VideoService implements VideosProvider {
44 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
45 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
46 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
49 private authHttp: HttpClient,
50 private restExtractor: RestExtractor,
51 private restService: RestService,
52 private serverService: ServerService
55 getVideoViewUrl (uuid: string) {
56 return VideoService.BASE_VIDEO_URL + uuid + '/views'
59 getUserWatchingVideoUrl (uuid: string) {
60 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
63 getVideo (options: { videoId: string }): Observable<VideoDetails> {
64 return this.serverService.getServerLocale()
66 switchMap(translations => {
67 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
68 .pipe(map(videoHash => ({ videoHash, translations })))
70 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
71 catchError(err => this.restExtractor.handleError(err))
75 updateVideo (video: VideoEdit) {
76 const language = video.language || null
77 const licence = video.licence || null
78 const category = video.category || null
79 const description = video.description || null
80 const support = video.support || null
81 const scheduleUpdate = video.scheduleUpdate || null
82 const originallyPublishedAt = video.originallyPublishedAt || null
84 const body: VideoUpdate = {
91 channelId: video.channelId,
92 privacy: video.privacy,
95 waitTranscoding: video.waitTranscoding,
96 commentsEnabled: video.commentsEnabled,
97 downloadEnabled: video.downloadEnabled,
98 thumbnailfile: video.thumbnailfile,
99 previewfile: video.previewfile,
100 pluginData: video.pluginData,
102 originallyPublishedAt
105 const data = objectToFormData(body)
107 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
109 map(this.restExtractor.extractDataBool),
110 catchError(err => this.restExtractor.handleError(err))
114 uploadVideo (video: FormData) {
115 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
118 .request<{ video: { id: number, uuid: string } }>(req)
119 .pipe(catchError(err => this.restExtractor.handleError(err)))
122 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
123 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
125 let params = new HttpParams()
126 params = this.restService.addRestGetParams(params, pagination, sort)
129 const filters = this.restService.parseQueryStringFilter(search, {
134 if (v === 'true') return v
135 if (v === 'false') return v
142 params = this.restService.addObjectParams(params, filters)
146 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
148 switchMap(res => this.extractVideos(res)),
149 catchError(err => this.restExtractor.handleError(err))
153 getAccountVideos (parameters: {
155 videoPagination: ComponentPaginationLight,
157 nsfwPolicy?: NSFWPolicyType
158 videoFilter?: VideoFilter
160 }): Observable<ResultList<Video>> {
161 const { account, videoPagination, sort, videoFilter, nsfwPolicy, search } = parameters
163 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
165 let params = new HttpParams()
166 params = this.restService.addRestGetParams(params, pagination, sort)
169 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
173 params = params.set('filter', videoFilter)
177 params = params.set('search', search)
181 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
183 switchMap(res => this.extractVideos(res)),
184 catchError(err => this.restExtractor.handleError(err))
188 getVideoChannelVideos (parameters: {
189 videoChannel: VideoChannel,
190 videoPagination: ComponentPaginationLight,
191 sort: VideoSortField,
192 nsfwPolicy?: NSFWPolicyType
193 videoFilter?: VideoFilter
194 }): Observable<ResultList<Video>> {
195 const { videoChannel, videoPagination, sort, nsfwPolicy, videoFilter } = parameters
197 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
199 let params = new HttpParams()
200 params = this.restService.addRestGetParams(params, pagination, sort)
203 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
207 params = params.set('filter', videoFilter)
211 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
213 switchMap(res => this.extractVideos(res)),
214 catchError(err => this.restExtractor.handleError(err))
218 getVideos (parameters: {
219 videoPagination: ComponentPaginationLight,
220 sort: VideoSortField,
221 filter?: VideoFilter,
222 categoryOneOf?: number[],
223 languageOneOf?: string[],
225 nsfwPolicy?: NSFWPolicyType
226 }): Observable<ResultList<Video>> {
227 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy } = parameters
229 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
231 let params = new HttpParams()
232 params = this.restService.addRestGetParams(params, pagination, sort)
234 if (filter) params = params.set('filter', filter)
235 if (skipCount) params = params.set('skipCount', skipCount + '')
238 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
242 for (const l of languageOneOf) {
243 params = params.append('languageOneOf[]', l)
248 for (const c of categoryOneOf) {
249 params = params.append('categoryOneOf[]', c + '')
254 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
256 switchMap(res => this.extractVideos(res)),
257 catchError(err => this.restExtractor.handleError(err))
261 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
264 format: FeedFormat.RSS,
265 label: 'media rss 2.0',
266 url: base + FeedFormat.RSS.toLowerCase()
269 format: FeedFormat.ATOM,
271 url: base + FeedFormat.ATOM.toLowerCase()
274 format: FeedFormat.JSON,
276 url: base + FeedFormat.JSON.toLowerCase()
280 if (params && params.keys().length !== 0) {
281 for (const feed of feeds) {
282 feed.url += '?' + params.toString()
289 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
290 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
292 if (filter) params = params.set('filter', filter)
295 for (const c of categoryOneOf) {
296 params = params.append('categoryOneOf[]', c + '')
300 return this.buildBaseFeedUrls(params)
303 getAccountFeedUrls (accountId: number) {
304 let params = this.restService.addRestGetParams(new HttpParams())
305 params = params.set('accountId', accountId.toString())
307 return this.buildBaseFeedUrls(params)
310 getVideoChannelFeedUrls (videoChannelId: number) {
311 let params = this.restService.addRestGetParams(new HttpParams())
312 params = params.set('videoChannelId', videoChannelId.toString())
314 return this.buildBaseFeedUrls(params)
317 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
318 let params = this.restService.addRestGetParams(new HttpParams())
319 params = params.set('accountId', accountId.toString())
320 params = params.set('token', feedToken)
322 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
325 getVideoFileMetadata (metadataUrl: string) {
327 .get<VideoFileMetadata>(metadataUrl)
329 catchError(err => this.restExtractor.handleError(err))
333 removeVideo (id: number) {
335 .delete(VideoService.BASE_VIDEO_URL + id)
337 map(this.restExtractor.extractDataBool),
338 catchError(err => this.restExtractor.handleError(err))
342 loadCompleteDescription (descriptionPath: string) {
344 .get<{ description: string }>(environment.apiUrl + descriptionPath)
346 map(res => res.description),
347 catchError(err => this.restExtractor.handleError(err))
351 setVideoLike (id: number) {
352 return this.setVideoRate(id, 'like')
355 setVideoDislike (id: number) {
356 return this.setVideoRate(id, 'dislike')
359 unsetVideoLike (id: number) {
360 return this.setVideoRate(id, 'none')
363 getUserVideoRating (id: number) {
364 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
366 return this.authHttp.get<UserVideoRate>(url)
367 .pipe(catchError(err => this.restExtractor.handleError(err)))
370 extractVideos (result: ResultList<VideoServerModel>) {
371 return this.serverService.getServerLocale()
373 map(translations => {
374 const videosJson = result.data
375 const totalVideos = result.total
376 const videos: Video[] = []
378 for (const videoJson of videosJson) {
379 videos.push(new Video(videoJson, translations))
382 return { total: totalVideos, data: videos }
387 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
390 id: VideoPrivacy.PRIVATE,
391 description: $localize`Only I can see this video`
394 id: VideoPrivacy.UNLISTED,
395 description: $localize`Only shareable via a private link`
398 id: VideoPrivacy.PUBLIC,
399 description: $localize`Anyone can see this video`
402 id: VideoPrivacy.INTERNAL,
403 description: $localize`Only users of this instance can see this video`
408 .filter(o => !!privacies.find(p => p.id === o.id)) // filter down to privacies that where in the input
409 .map(o => ({ ...privacies[o.id - 1], ...o })) // merge the input privacies that contain a label, and extend them with a description
412 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
413 return nsfwPolicy === 'do_not_list'
418 private setVideoRate (id: number, rateType: UserVideoRateType) {
419 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
420 const body: UserVideoRateUpdate = {
427 map(this.restExtractor.extractDataBool),
428 catchError(err => this.restExtractor.handleError(err))