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, {
136 params = this.restService.addObjectParams(params, filters)
140 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
142 switchMap(res => this.extractVideos(res)),
143 catchError(err => this.restExtractor.handleError(err))
147 getAccountVideos (parameters: {
149 videoPagination: ComponentPaginationLight,
151 nsfwPolicy?: NSFWPolicyType
152 videoFilter?: VideoFilter
154 }): Observable<ResultList<Video>> {
155 const { account, videoPagination, sort, videoFilter, nsfwPolicy, search } = parameters
157 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
159 let params = new HttpParams()
160 params = this.restService.addRestGetParams(params, pagination, sort)
163 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
167 params = params.set('filter', videoFilter)
171 params = params.set('search', search)
175 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
177 switchMap(res => this.extractVideos(res)),
178 catchError(err => this.restExtractor.handleError(err))
182 getVideoChannelVideos (parameters: {
183 videoChannel: VideoChannel,
184 videoPagination: ComponentPaginationLight,
185 sort: VideoSortField,
186 nsfwPolicy?: NSFWPolicyType
187 videoFilter?: VideoFilter
188 }): Observable<ResultList<Video>> {
189 const { videoChannel, videoPagination, sort, nsfwPolicy, videoFilter } = parameters
191 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
193 let params = new HttpParams()
194 params = this.restService.addRestGetParams(params, pagination, sort)
197 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
201 params = params.set('filter', videoFilter)
205 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
207 switchMap(res => this.extractVideos(res)),
208 catchError(err => this.restExtractor.handleError(err))
212 getVideos (parameters: {
213 videoPagination: ComponentPaginationLight,
214 sort: VideoSortField,
215 filter?: VideoFilter,
216 categoryOneOf?: number[],
217 languageOneOf?: string[],
219 nsfwPolicy?: NSFWPolicyType
220 }): Observable<ResultList<Video>> {
221 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy } = parameters
223 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
225 let params = new HttpParams()
226 params = this.restService.addRestGetParams(params, pagination, sort)
228 if (filter) params = params.set('filter', filter)
229 if (skipCount) params = params.set('skipCount', skipCount + '')
232 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
236 for (const l of languageOneOf) {
237 params = params.append('languageOneOf[]', l)
242 for (const c of categoryOneOf) {
243 params = params.append('categoryOneOf[]', c + '')
248 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
250 switchMap(res => this.extractVideos(res)),
251 catchError(err => this.restExtractor.handleError(err))
255 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
258 format: FeedFormat.RSS,
259 label: 'media rss 2.0',
260 url: base + FeedFormat.RSS.toLowerCase()
263 format: FeedFormat.ATOM,
265 url: base + FeedFormat.ATOM.toLowerCase()
268 format: FeedFormat.JSON,
270 url: base + FeedFormat.JSON.toLowerCase()
274 if (params && params.keys().length !== 0) {
275 for (const feed of feeds) {
276 feed.url += '?' + params.toString()
283 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
284 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
286 if (filter) params = params.set('filter', filter)
289 for (const c of categoryOneOf) {
290 params = params.append('categoryOneOf[]', c + '')
294 return this.buildBaseFeedUrls(params)
297 getAccountFeedUrls (accountId: number) {
298 let params = this.restService.addRestGetParams(new HttpParams())
299 params = params.set('accountId', accountId.toString())
301 return this.buildBaseFeedUrls(params)
304 getVideoChannelFeedUrls (videoChannelId: number) {
305 let params = this.restService.addRestGetParams(new HttpParams())
306 params = params.set('videoChannelId', videoChannelId.toString())
308 return this.buildBaseFeedUrls(params)
311 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
312 let params = this.restService.addRestGetParams(new HttpParams())
313 params = params.set('accountId', accountId.toString())
314 params = params.set('token', feedToken)
316 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
319 getVideoFileMetadata (metadataUrl: string) {
321 .get<VideoFileMetadata>(metadataUrl)
323 catchError(err => this.restExtractor.handleError(err))
327 removeVideo (id: number) {
329 .delete(VideoService.BASE_VIDEO_URL + id)
331 map(this.restExtractor.extractDataBool),
332 catchError(err => this.restExtractor.handleError(err))
336 loadCompleteDescription (descriptionPath: string) {
338 .get<{ description: string }>(environment.apiUrl + descriptionPath)
340 map(res => res.description),
341 catchError(err => this.restExtractor.handleError(err))
345 setVideoLike (id: number) {
346 return this.setVideoRate(id, 'like')
349 setVideoDislike (id: number) {
350 return this.setVideoRate(id, 'dislike')
353 unsetVideoLike (id: number) {
354 return this.setVideoRate(id, 'none')
357 getUserVideoRating (id: number) {
358 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
360 return this.authHttp.get<UserVideoRate>(url)
361 .pipe(catchError(err => this.restExtractor.handleError(err)))
364 extractVideos (result: ResultList<VideoServerModel>) {
365 return this.serverService.getServerLocale()
367 map(translations => {
368 const videosJson = result.data
369 const totalVideos = result.total
370 const videos: Video[] = []
372 for (const videoJson of videosJson) {
373 videos.push(new Video(videoJson, translations))
376 return { total: totalVideos, data: videos }
381 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
384 id: VideoPrivacy.PRIVATE,
385 description: $localize`Only I can see this video`
388 id: VideoPrivacy.UNLISTED,
389 description: $localize`Only shareable via a private link`
392 id: VideoPrivacy.PUBLIC,
393 description: $localize`Anyone can see this video`
396 id: VideoPrivacy.INTERNAL,
397 description: $localize`Only users of this instance can see this video`
402 .filter(o => !!privacies.find(p => p.id === o.id)) // filter down to privacies that where in the input
403 .map(o => ({ ...privacies[o.id - 1], ...o })) // merge the input privacies that contain a label, and extend them with a description
406 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
407 return nsfwPolicy === 'do_not_list'
412 private setVideoRate (id: number, rateType: UserVideoRateType) {
413 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
414 const body: UserVideoRateUpdate = {
421 map(this.restExtractor.extractDataBool),
422 catchError(err => this.restExtractor.handleError(err))