1 import { SortMeta } from 'primeng/api'
2 import { from, Observable } from 'rxjs'
3 import { catchError, concatMap, map, switchMap, toArray } from 'rxjs/operators'
4 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
5 import { Injectable } from '@angular/core'
6 import { ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core'
7 import { objectToFormData } from '@app/helpers'
16 Video as VideoServerModel,
17 VideoChannel as VideoChannelServerModel,
19 VideoDetails as VideoDetailsServerModel,
25 } from '@shared/models'
26 import { environment } from '../../../../environments/environment'
27 import { Account } from '../account/account.model'
28 import { AccountService } from '../account/account.service'
29 import { VideoChannel, VideoChannelService } from '../video-channel'
30 import { VideoDetails } from './video-details.model'
31 import { VideoEdit } from './video-edit.model'
32 import { Video } from './video.model'
34 export type CommonVideoParams = {
35 videoPagination?: ComponentPaginationLight
36 sort: VideoSortField | SortMeta
37 include?: VideoInclude
39 categoryOneOf?: number[]
40 languageOneOf?: string[]
41 privacyOneOf?: VideoPrivacy[]
46 nsfwPolicy?: NSFWPolicyType
47 nsfw?: BooleanBothQuery
51 export class VideoService {
52 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
53 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
54 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
57 private authHttp: HttpClient,
58 private restExtractor: RestExtractor,
59 private restService: RestService,
60 private serverService: ServerService
63 getVideoViewUrl (uuid: string) {
64 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
67 getUserWatchingVideoUrl (uuid: string) {
68 return `${VideoService.BASE_VIDEO_URL}/${uuid}/watching`
71 getVideo (options: { videoId: string }): Observable<VideoDetails> {
72 return this.serverService.getServerLocale()
74 switchMap(translations => {
75 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
76 .pipe(map(videoHash => ({ videoHash, translations })))
78 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
79 catchError(err => this.restExtractor.handleError(err))
83 updateVideo (video: VideoEdit) {
84 const language = video.language || null
85 const licence = video.licence || null
86 const category = video.category || null
87 const description = video.description || null
88 const support = video.support || null
89 const scheduleUpdate = video.scheduleUpdate || null
90 const originallyPublishedAt = video.originallyPublishedAt || null
92 const body: VideoUpdate = {
99 channelId: video.channelId,
100 privacy: video.privacy,
103 waitTranscoding: video.waitTranscoding,
104 commentsEnabled: video.commentsEnabled,
105 downloadEnabled: video.downloadEnabled,
106 thumbnailfile: video.thumbnailfile,
107 previewfile: video.previewfile,
108 pluginData: video.pluginData,
110 originallyPublishedAt
113 const data = objectToFormData(body)
115 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
117 map(this.restExtractor.extractDataBool),
118 catchError(err => this.restExtractor.handleError(err))
122 uploadVideo (video: FormData) {
123 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
126 .request<{ video: { id: number, uuid: string } }>(req)
127 .pipe(catchError(err => this.restExtractor.handleError(err)))
130 getMyVideos (options: {
131 videoPagination: ComponentPaginationLight
133 userChannels?: VideoChannelServerModel[]
135 }): Observable<ResultList<Video>> {
136 const { videoPagination, sort, userChannels = [], search } = options
138 const pagination = this.restService.componentToRestPagination(videoPagination)
140 let params = new HttpParams()
141 params = this.restService.addRestGetParams(params, pagination, sort)
144 const filters = this.restService.parseQueryStringFilter(search, {
151 handler: (name: string) => {
152 const channel = userChannels.find(c => c.name === name)
154 if (channel) return channel.id
161 params = this.restService.addObjectParams(params, filters)
165 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
167 switchMap(res => this.extractVideos(res)),
168 catchError(err => this.restExtractor.handleError(err))
172 getAccountVideos (parameters: CommonVideoParams & {
173 account: Pick<Account, 'nameWithHost'>
175 }): Observable<ResultList<Video>> {
176 const { account, search } = parameters
178 let params = new HttpParams()
179 params = this.buildCommonVideosParams({ params, ...parameters })
181 if (search) params = params.set('search', search)
184 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
186 switchMap(res => this.extractVideos(res)),
187 catchError(err => this.restExtractor.handleError(err))
191 getVideoChannelVideos (parameters: CommonVideoParams & {
192 videoChannel: Pick<VideoChannel, 'nameWithHost'>
193 }): Observable<ResultList<Video>> {
194 const { videoChannel } = parameters
196 let params = new HttpParams()
197 params = this.buildCommonVideosParams({ params, ...parameters })
200 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
202 switchMap(res => this.extractVideos(res)),
203 catchError(err => this.restExtractor.handleError(err))
207 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
208 let params = new HttpParams()
209 params = this.buildCommonVideosParams({ params, ...parameters })
212 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
214 switchMap(res => this.extractVideos(res)),
215 catchError(err => this.restExtractor.handleError(err))
219 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
222 format: FeedFormat.RSS,
223 label: 'media rss 2.0',
224 url: base + FeedFormat.RSS.toLowerCase()
227 format: FeedFormat.ATOM,
229 url: base + FeedFormat.ATOM.toLowerCase()
232 format: FeedFormat.JSON,
234 url: base + FeedFormat.JSON.toLowerCase()
238 if (params && params.keys().length !== 0) {
239 for (const feed of feeds) {
240 feed.url += '?' + params.toString()
247 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
248 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
250 if (isLocal) params = params.set('isLocal', isLocal)
253 for (const c of categoryOneOf) {
254 params = params.append('categoryOneOf[]', c + '')
258 return this.buildBaseFeedUrls(params)
261 getAccountFeedUrls (accountId: number) {
262 let params = this.restService.addRestGetParams(new HttpParams())
263 params = params.set('accountId', accountId.toString())
265 return this.buildBaseFeedUrls(params)
268 getVideoChannelFeedUrls (videoChannelId: number) {
269 let params = this.restService.addRestGetParams(new HttpParams())
270 params = params.set('videoChannelId', videoChannelId.toString())
272 return this.buildBaseFeedUrls(params)
275 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
276 let params = this.restService.addRestGetParams(new HttpParams())
277 params = params.set('accountId', accountId.toString())
278 params = params.set('token', feedToken)
280 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
283 getVideoFileMetadata (metadataUrl: string) {
285 .get<VideoFileMetadata>(metadataUrl)
287 catchError(err => this.restExtractor.handleError(err))
291 removeVideo (idArg: number | number[]) {
292 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
296 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
298 catchError(err => this.restExtractor.handleError(err))
302 loadCompleteDescription (descriptionPath: string) {
304 .get<{ description: string }>(environment.apiUrl + descriptionPath)
306 map(res => res.description),
307 catchError(err => this.restExtractor.handleError(err))
311 setVideoLike (id: number) {
312 return this.setVideoRate(id, 'like')
315 setVideoDislike (id: number) {
316 return this.setVideoRate(id, 'dislike')
319 unsetVideoLike (id: number) {
320 return this.setVideoRate(id, 'none')
323 getUserVideoRating (id: number) {
324 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
326 return this.authHttp.get<UserVideoRate>(url)
327 .pipe(catchError(err => this.restExtractor.handleError(err)))
330 extractVideos (result: ResultList<VideoServerModel>) {
331 return this.serverService.getServerLocale()
333 map(translations => {
334 const videosJson = result.data
335 const totalVideos = result.total
336 const videos: Video[] = []
338 for (const videoJson of videosJson) {
339 videos.push(new Video(videoJson, translations))
342 return { total: totalVideos, data: videos }
347 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
348 const descriptions = {
349 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
350 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
351 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
352 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
355 const videoPrivacies = serverPrivacies.map(p => {
359 description: descriptions[p.id]
365 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
369 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
370 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
372 for (const privacy of order) {
373 if (serverPrivacies.find(p => p.id === privacy)) {
378 throw new Error('No highest privacy available')
381 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
382 return nsfwPolicy === 'do_not_list'
387 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
403 const pagination = videoPagination
404 ? this.restService.componentToRestPagination(videoPagination)
407 let newParams = this.restService.addRestGetParams(params, pagination, sort)
409 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
411 if (isLocal) newParams = newParams.set('isLocal', isLocal)
412 if (include) newParams = newParams.set('include', include)
413 if (isLive) newParams = newParams.set('isLive', isLive)
414 if (nsfw) newParams = newParams.set('nsfw', nsfw)
415 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
416 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
417 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
418 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
423 private setVideoRate (id: number, rateType: UserVideoRateType) {
424 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
425 const body: UserVideoRateUpdate = {
432 map(this.restExtractor.extractDataBool),
433 catchError(err => this.restExtractor.handleError(err))