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 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
303 return from(videoIds)
305 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
307 catchError(err => this.restExtractor.handleError(err))
311 loadCompleteDescription (descriptionPath: string) {
313 .get<{ description: string }>(environment.apiUrl + descriptionPath)
315 map(res => res.description),
316 catchError(err => this.restExtractor.handleError(err))
320 setVideoLike (id: number) {
321 return this.setVideoRate(id, 'like')
324 setVideoDislike (id: number) {
325 return this.setVideoRate(id, 'dislike')
328 unsetVideoLike (id: number) {
329 return this.setVideoRate(id, 'none')
332 getUserVideoRating (id: number) {
333 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
335 return this.authHttp.get<UserVideoRate>(url)
336 .pipe(catchError(err => this.restExtractor.handleError(err)))
339 extractVideos (result: ResultList<VideoServerModel>) {
340 return this.serverService.getServerLocale()
342 map(translations => {
343 const videosJson = result.data
344 const totalVideos = result.total
345 const videos: Video[] = []
347 for (const videoJson of videosJson) {
348 videos.push(new Video(videoJson, translations))
351 return { total: totalVideos, data: videos }
356 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
357 const descriptions = {
358 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
359 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
360 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
361 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
364 const videoPrivacies = serverPrivacies.map(p => {
368 description: descriptions[p.id]
374 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
378 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
379 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
381 for (const privacy of order) {
382 if (serverPrivacies.find(p => p.id === privacy)) {
387 throw new Error('No highest privacy available')
390 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
391 return nsfwPolicy === 'do_not_list'
396 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
412 const pagination = videoPagination
413 ? this.restService.componentToRestPagination(videoPagination)
416 let newParams = this.restService.addRestGetParams(params, pagination, sort)
418 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
420 if (isLocal) newParams = newParams.set('isLocal', isLocal)
421 if (include) newParams = newParams.set('include', include)
422 if (isLive) newParams = newParams.set('isLive', isLive)
423 if (nsfw) newParams = newParams.set('nsfw', nsfw)
424 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
425 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
426 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
427 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
432 private setVideoRate (id: number, rateType: UserVideoRateType) {
433 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
434 const body: UserVideoRateUpdate = {
441 map(this.restExtractor.extractDataBool),
442 catchError(err => this.restExtractor.handleError(err))