1 import { Observable } from 'rxjs'
2 import { catchError, map, switchMap } from 'rxjs/operators'
3 import { HttpClient, 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,
23 } from '@shared/models'
24 import { environment } from '../../../../environments/environment'
25 import { Account } from '../account/account.model'
26 import { AccountService } from '../account/account.service'
27 import { VideoChannel, VideoChannelService } from '../video-channel'
28 import { VideoDetails } from './video-details.model'
29 import { VideoEdit } from './video-edit.model'
30 import { Video } from './video.model'
32 export interface VideosProvider {
33 getVideos (parameters: {
34 videoPagination: ComponentPaginationLight,
37 categoryOneOf?: number[],
38 languageOneOf?: string[]
39 nsfwPolicy: NSFWPolicyType
40 }): Observable<ResultList<Video>>
44 export class VideoService implements VideosProvider {
45 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
46 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
49 private authHttp: HttpClient,
50 private restExtractor: RestExtractor,
51 private restService: RestService,
52 private serverService: ServerService,
53 private authService: AuthService
56 getVideoViewUrl (uuid: string) {
57 return VideoService.BASE_VIDEO_URL + uuid + '/views'
60 getUserWatchingVideoUrl (uuid: string) {
61 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
64 getVideo (options: { videoId: string }): Observable<VideoDetails> {
65 return this.serverService.getServerLocale()
67 switchMap(translations => {
68 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
69 .pipe(map(videoHash => ({ videoHash, translations })))
71 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
72 catchError(err => this.restExtractor.handleError(err))
76 updateVideo (video: VideoEdit) {
77 const language = video.language || null
78 const licence = video.licence || null
79 const category = video.category || null
80 const description = video.description || null
81 const support = video.support || null
82 const scheduleUpdate = video.scheduleUpdate || null
83 const originallyPublishedAt = video.originallyPublishedAt || null
85 const body: VideoUpdate = {
92 channelId: video.channelId,
93 privacy: video.privacy,
96 waitTranscoding: video.waitTranscoding,
97 commentsEnabled: video.commentsEnabled,
98 downloadEnabled: video.downloadEnabled,
99 thumbnailfile: video.thumbnailfile,
100 previewfile: video.previewfile,
101 pluginData: video.pluginData,
103 originallyPublishedAt
106 const data = objectToFormData(body)
108 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
110 map(this.restExtractor.extractDataBool),
111 catchError(err => this.restExtractor.handleError(err))
115 uploadVideo (video: FormData) {
116 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
119 .request<{ video: { id: number, uuid: string } }>(req)
120 .pipe(catchError(err => this.restExtractor.handleError(err)))
123 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
124 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
126 let params = new HttpParams()
127 params = this.restService.addRestGetParams(params, pagination, sort)
128 params = this.restService.addObjectParams(params, { search })
131 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
133 switchMap(res => this.extractVideos(res)),
134 catchError(err => this.restExtractor.handleError(err))
138 getAccountVideos (parameters: {
140 videoPagination: ComponentPaginationLight,
142 nsfwPolicy?: NSFWPolicyType
143 videoFilter?: VideoFilter
144 }): Observable<ResultList<Video>> {
145 const { account, videoPagination, sort, videoFilter, nsfwPolicy } = parameters
147 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
149 let params = new HttpParams()
150 params = this.restService.addRestGetParams(params, pagination, sort)
153 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
157 params = params.set('filter', videoFilter)
161 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
163 switchMap(res => this.extractVideos(res)),
164 catchError(err => this.restExtractor.handleError(err))
168 getVideoChannelVideos (parameters: {
169 videoChannel: VideoChannel,
170 videoPagination: ComponentPaginationLight,
171 sort: VideoSortField,
172 nsfwPolicy?: NSFWPolicyType
173 videoFilter?: VideoFilter
174 }): Observable<ResultList<Video>> {
175 const { videoChannel, videoPagination, sort, nsfwPolicy, videoFilter } = parameters
177 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
179 let params = new HttpParams()
180 params = this.restService.addRestGetParams(params, pagination, sort)
183 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
187 params = params.set('filter', videoFilter)
191 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
193 switchMap(res => this.extractVideos(res)),
194 catchError(err => this.restExtractor.handleError(err))
198 getVideos (parameters: {
199 videoPagination: ComponentPaginationLight,
200 sort: VideoSortField,
201 filter?: VideoFilter,
202 categoryOneOf?: number[],
203 languageOneOf?: string[],
205 nsfwPolicy?: NSFWPolicyType
206 }): Observable<ResultList<Video>> {
207 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy } = parameters
209 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
211 let params = new HttpParams()
212 params = this.restService.addRestGetParams(params, pagination, sort)
214 if (filter) params = params.set('filter', filter)
215 if (skipCount) params = params.set('skipCount', skipCount + '')
218 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
222 for (const l of languageOneOf) {
223 params = params.append('languageOneOf[]', l)
228 for (const c of categoryOneOf) {
229 params = params.append('categoryOneOf[]', c + '')
234 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
236 switchMap(res => this.extractVideos(res)),
237 catchError(err => this.restExtractor.handleError(err))
241 buildBaseFeedUrls (params: HttpParams) {
244 format: FeedFormat.RSS,
245 label: 'media rss 2.0',
246 url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
249 format: FeedFormat.ATOM,
251 url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
254 format: FeedFormat.JSON,
256 url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
260 if (params && params.keys().length !== 0) {
261 for (const feed of feeds) {
262 feed.url += '?' + params.toString()
269 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
270 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
272 if (filter) params = params.set('filter', filter)
275 for (const c of categoryOneOf) {
276 params = params.append('categoryOneOf[]', c + '')
280 return this.buildBaseFeedUrls(params)
283 getAccountFeedUrls (accountId: number) {
284 let params = this.restService.addRestGetParams(new HttpParams())
285 params = params.set('accountId', accountId.toString())
287 return this.buildBaseFeedUrls(params)
290 getVideoChannelFeedUrls (videoChannelId: number) {
291 let params = this.restService.addRestGetParams(new HttpParams())
292 params = params.set('videoChannelId', videoChannelId.toString())
294 return this.buildBaseFeedUrls(params)
297 async getVideoSubscriptionFeedUrls (accountId: number) {
298 let params = this.restService.addRestGetParams(new HttpParams())
299 params = params.set('accountId', accountId.toString())
301 const { feedToken } = await this.authService.getScopedTokens()
302 params = params.set('token', feedToken)
304 return this.buildBaseFeedUrls(params)
307 getVideoFileMetadata (metadataUrl: string) {
309 .get<VideoFileMetadata>(metadataUrl)
311 catchError(err => this.restExtractor.handleError(err))
315 removeVideo (id: number) {
317 .delete(VideoService.BASE_VIDEO_URL + id)
319 map(this.restExtractor.extractDataBool),
320 catchError(err => this.restExtractor.handleError(err))
324 loadCompleteDescription (descriptionPath: string) {
326 .get<{ description: string }>(environment.apiUrl + descriptionPath)
328 map(res => res.description),
329 catchError(err => this.restExtractor.handleError(err))
333 setVideoLike (id: number) {
334 return this.setVideoRate(id, 'like')
337 setVideoDislike (id: number) {
338 return this.setVideoRate(id, 'dislike')
341 unsetVideoLike (id: number) {
342 return this.setVideoRate(id, 'none')
345 getUserVideoRating (id: number) {
346 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
348 return this.authHttp.get<UserVideoRate>(url)
349 .pipe(catchError(err => this.restExtractor.handleError(err)))
352 extractVideos (result: ResultList<VideoServerModel>) {
353 return this.serverService.getServerLocale()
355 map(translations => {
356 const videosJson = result.data
357 const totalVideos = result.total
358 const videos: Video[] = []
360 for (const videoJson of videosJson) {
361 videos.push(new Video(videoJson, translations))
364 return { total: totalVideos, data: videos }
369 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
372 id: VideoPrivacy.PRIVATE,
373 description: $localize`Only I can see this video`
376 id: VideoPrivacy.UNLISTED,
377 description: $localize`Only shareable via a private link`
380 id: VideoPrivacy.PUBLIC,
381 description: $localize`Anyone can see this video`
384 id: VideoPrivacy.INTERNAL,
385 description: $localize`Only users of this instance can see this video`
390 .filter(o => !!privacies.find(p => p.id === o.id)) // filter down to privacies that where in the input
391 .map(o => ({ ...privacies[o.id - 1], ...o })) // merge the input privacies that contain a label, and extend them with a description
394 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
395 return nsfwPolicy === 'do_not_list'
400 private setVideoRate (id: number, rateType: UserVideoRateType) {
401 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
402 const body: UserVideoRateUpdate = {
409 map(this.restExtractor.extractDataBool),
410 catchError(err => this.restExtractor.handleError(err))