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)
127 params = this.restService.addObjectParams(params, { search })
130 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
132 switchMap(res => this.extractVideos(res)),
133 catchError(err => this.restExtractor.handleError(err))
137 getAccountVideos (parameters: {
139 videoPagination: ComponentPaginationLight,
141 nsfwPolicy?: NSFWPolicyType
142 videoFilter?: VideoFilter
143 }): Observable<ResultList<Video>> {
144 const { account, videoPagination, sort, videoFilter, nsfwPolicy } = parameters
146 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
148 let params = new HttpParams()
149 params = this.restService.addRestGetParams(params, pagination, sort)
152 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
156 params = params.set('filter', videoFilter)
160 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
162 switchMap(res => this.extractVideos(res)),
163 catchError(err => this.restExtractor.handleError(err))
167 getVideoChannelVideos (parameters: {
168 videoChannel: VideoChannel,
169 videoPagination: ComponentPaginationLight,
170 sort: VideoSortField,
171 nsfwPolicy?: NSFWPolicyType
172 videoFilter?: VideoFilter
173 }): Observable<ResultList<Video>> {
174 const { videoChannel, videoPagination, sort, nsfwPolicy, videoFilter } = parameters
176 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
178 let params = new HttpParams()
179 params = this.restService.addRestGetParams(params, pagination, sort)
182 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
186 params = params.set('filter', videoFilter)
190 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
192 switchMap(res => this.extractVideos(res)),
193 catchError(err => this.restExtractor.handleError(err))
197 getVideos (parameters: {
198 videoPagination: ComponentPaginationLight,
199 sort: VideoSortField,
200 filter?: VideoFilter,
201 categoryOneOf?: number[],
202 languageOneOf?: string[],
204 nsfwPolicy?: NSFWPolicyType
205 }): Observable<ResultList<Video>> {
206 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy } = parameters
208 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
210 let params = new HttpParams()
211 params = this.restService.addRestGetParams(params, pagination, sort)
213 if (filter) params = params.set('filter', filter)
214 if (skipCount) params = params.set('skipCount', skipCount + '')
217 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
221 for (const l of languageOneOf) {
222 params = params.append('languageOneOf[]', l)
227 for (const c of categoryOneOf) {
228 params = params.append('categoryOneOf[]', c + '')
233 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
235 switchMap(res => this.extractVideos(res)),
236 catchError(err => this.restExtractor.handleError(err))
240 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
243 format: FeedFormat.RSS,
244 label: 'media rss 2.0',
245 url: base + FeedFormat.RSS.toLowerCase()
248 format: FeedFormat.ATOM,
250 url: base + FeedFormat.ATOM.toLowerCase()
253 format: FeedFormat.JSON,
255 url: base + FeedFormat.JSON.toLowerCase()
259 if (params && params.keys().length !== 0) {
260 for (const feed of feeds) {
261 feed.url += '?' + params.toString()
268 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
269 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
271 if (filter) params = params.set('filter', filter)
274 for (const c of categoryOneOf) {
275 params = params.append('categoryOneOf[]', c + '')
279 return this.buildBaseFeedUrls(params)
282 getAccountFeedUrls (accountId: number) {
283 let params = this.restService.addRestGetParams(new HttpParams())
284 params = params.set('accountId', accountId.toString())
286 return this.buildBaseFeedUrls(params)
289 getVideoChannelFeedUrls (videoChannelId: number) {
290 let params = this.restService.addRestGetParams(new HttpParams())
291 params = params.set('videoChannelId', videoChannelId.toString())
293 return this.buildBaseFeedUrls(params)
296 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
297 let params = this.restService.addRestGetParams(new HttpParams())
298 params = params.set('accountId', accountId.toString())
299 params = params.set('token', feedToken)
301 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
304 getVideoFileMetadata (metadataUrl: string) {
306 .get<VideoFileMetadata>(metadataUrl)
308 catchError(err => this.restExtractor.handleError(err))
312 removeVideo (id: number) {
314 .delete(VideoService.BASE_VIDEO_URL + id)
316 map(this.restExtractor.extractDataBool),
317 catchError(err => this.restExtractor.handleError(err))
321 loadCompleteDescription (descriptionPath: string) {
323 .get<{ description: string }>(environment.apiUrl + descriptionPath)
325 map(res => res.description),
326 catchError(err => this.restExtractor.handleError(err))
330 setVideoLike (id: number) {
331 return this.setVideoRate(id, 'like')
334 setVideoDislike (id: number) {
335 return this.setVideoRate(id, 'dislike')
338 unsetVideoLike (id: number) {
339 return this.setVideoRate(id, 'none')
342 getUserVideoRating (id: number) {
343 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
345 return this.authHttp.get<UserVideoRate>(url)
346 .pipe(catchError(err => this.restExtractor.handleError(err)))
349 extractVideos (result: ResultList<VideoServerModel>) {
350 return this.serverService.getServerLocale()
352 map(translations => {
353 const videosJson = result.data
354 const totalVideos = result.total
355 const videos: Video[] = []
357 for (const videoJson of videosJson) {
358 videos.push(new Video(videoJson, translations))
361 return { total: totalVideos, data: videos }
366 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
369 id: VideoPrivacy.PRIVATE,
370 description: $localize`Only I can see this video`
373 id: VideoPrivacy.UNLISTED,
374 description: $localize`Only shareable via a private link`
377 id: VideoPrivacy.PUBLIC,
378 description: $localize`Anyone can see this video`
381 id: VideoPrivacy.INTERNAL,
382 description: $localize`Only users of this instance can see this video`
387 .filter(o => !!privacies.find(p => p.id === o.id)) // filter down to privacies that where in the input
388 .map(o => ({ ...privacies[o.id - 1], ...o })) // merge the input privacies that contain a label, and extend them with a description
391 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
392 return nsfwPolicy === 'do_not_list'
397 private setVideoRate (id: number, rateType: UserVideoRateType) {
398 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
399 const body: UserVideoRateUpdate = {
406 map(this.restExtractor.extractDataBool),
407 catchError(err => this.restExtractor.handleError(err))