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,
24 VideoTranscodingCreate,
26 } from '@shared/models'
27 import { environment } from '../../../../environments/environment'
28 import { Account } from '../account/account.model'
29 import { AccountService } from '../account/account.service'
30 import { VideoChannel, VideoChannelService } from '../video-channel'
31 import { VideoDetails } from './video-details.model'
32 import { VideoEdit } from './video-edit.model'
33 import { Video } from './video.model'
35 export type CommonVideoParams = {
36 videoPagination?: ComponentPaginationLight
37 sort: VideoSortField | SortMeta
38 include?: VideoInclude
40 categoryOneOf?: number[]
41 languageOneOf?: string[]
42 privacyOneOf?: VideoPrivacy[]
47 nsfwPolicy?: NSFWPolicyType
48 nsfw?: BooleanBothQuery
52 export class VideoService {
53 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
54 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
55 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
58 private authHttp: HttpClient,
59 private restExtractor: RestExtractor,
60 private restService: RestService,
61 private serverService: ServerService
64 getVideoViewUrl (uuid: string) {
65 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
68 getUserWatchingVideoUrl (uuid: string) {
69 return `${VideoService.BASE_VIDEO_URL}/${uuid}/watching`
72 getVideo (options: { videoId: string }): Observable<VideoDetails> {
73 return this.serverService.getServerLocale()
75 switchMap(translations => {
76 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
77 .pipe(map(videoHash => ({ videoHash, translations })))
79 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
80 catchError(err => this.restExtractor.handleError(err))
84 updateVideo (video: VideoEdit) {
85 const language = video.language || null
86 const licence = video.licence || null
87 const category = video.category || null
88 const description = video.description || null
89 const support = video.support || null
90 const scheduleUpdate = video.scheduleUpdate || null
91 const originallyPublishedAt = video.originallyPublishedAt || null
93 const body: VideoUpdate = {
100 channelId: video.channelId,
101 privacy: video.privacy,
104 waitTranscoding: video.waitTranscoding,
105 commentsEnabled: video.commentsEnabled,
106 downloadEnabled: video.downloadEnabled,
107 thumbnailfile: video.thumbnailfile,
108 previewfile: video.previewfile,
109 pluginData: video.pluginData,
111 originallyPublishedAt
114 const data = objectToFormData(body)
116 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
117 .pipe(catchError(err => this.restExtractor.handleError(err)))
120 uploadVideo (video: FormData) {
121 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
124 .request<{ video: { id: number, uuid: string } }>(req)
125 .pipe(catchError(err => this.restExtractor.handleError(err)))
128 getMyVideos (options: {
129 videoPagination: ComponentPaginationLight
131 userChannels?: VideoChannelServerModel[]
133 }): Observable<ResultList<Video>> {
134 const { videoPagination, sort, userChannels = [], search } = options
136 const pagination = this.restService.componentToRestPagination(videoPagination)
138 let params = new HttpParams()
139 params = this.restService.addRestGetParams(params, pagination, sort)
142 const filters = this.restService.parseQueryStringFilter(search, {
149 handler: (name: string) => {
150 const channel = userChannels.find(c => c.name === name)
152 if (channel) return channel.id
159 params = this.restService.addObjectParams(params, filters)
163 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
165 switchMap(res => this.extractVideos(res)),
166 catchError(err => this.restExtractor.handleError(err))
170 getAccountVideos (parameters: CommonVideoParams & {
171 account: Pick<Account, 'nameWithHost'>
173 }): Observable<ResultList<Video>> {
174 const { account, search } = parameters
176 let params = new HttpParams()
177 params = this.buildCommonVideosParams({ params, ...parameters })
179 if (search) params = params.set('search', search)
182 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
184 switchMap(res => this.extractVideos(res)),
185 catchError(err => this.restExtractor.handleError(err))
189 getVideoChannelVideos (parameters: CommonVideoParams & {
190 videoChannel: Pick<VideoChannel, 'nameWithHost'>
191 }): Observable<ResultList<Video>> {
192 const { videoChannel } = parameters
194 let params = new HttpParams()
195 params = this.buildCommonVideosParams({ params, ...parameters })
198 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
200 switchMap(res => this.extractVideos(res)),
201 catchError(err => this.restExtractor.handleError(err))
205 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
206 let params = new HttpParams()
207 params = this.buildCommonVideosParams({ params, ...parameters })
210 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
212 switchMap(res => this.extractVideos(res)),
213 catchError(err => this.restExtractor.handleError(err))
217 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
220 format: FeedFormat.RSS,
221 label: 'media rss 2.0',
222 url: base + FeedFormat.RSS.toLowerCase()
225 format: FeedFormat.ATOM,
227 url: base + FeedFormat.ATOM.toLowerCase()
230 format: FeedFormat.JSON,
232 url: base + FeedFormat.JSON.toLowerCase()
236 if (params && params.keys().length !== 0) {
237 for (const feed of feeds) {
238 feed.url += '?' + params.toString()
245 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
246 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
248 if (isLocal) params = params.set('isLocal', isLocal)
251 for (const c of categoryOneOf) {
252 params = params.append('categoryOneOf[]', c + '')
256 return this.buildBaseFeedUrls(params)
259 getAccountFeedUrls (accountId: number) {
260 let params = this.restService.addRestGetParams(new HttpParams())
261 params = params.set('accountId', accountId.toString())
263 return this.buildBaseFeedUrls(params)
266 getVideoChannelFeedUrls (videoChannelId: number) {
267 let params = this.restService.addRestGetParams(new HttpParams())
268 params = params.set('videoChannelId', videoChannelId.toString())
270 return this.buildBaseFeedUrls(params)
273 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
274 let params = this.restService.addRestGetParams(new HttpParams())
275 params = params.set('accountId', accountId.toString())
276 params = params.set('token', feedToken)
278 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
281 getVideoFileMetadata (metadataUrl: string) {
283 .get<VideoFileMetadata>(metadataUrl)
285 catchError(err => this.restExtractor.handleError(err))
289 removeVideo (idArg: number | number[]) {
290 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
294 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
296 catchError(err => this.restExtractor.handleError(err))
300 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
301 return from(videoIds)
303 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
305 catchError(err => this.restExtractor.handleError(err))
309 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
310 const body: VideoTranscodingCreate = { transcodingType: type }
312 return from(videoIds)
314 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
316 catchError(err => this.restExtractor.handleError(err))
320 loadCompleteDescription (descriptionPath: string) {
322 .get<{ description: string }>(environment.apiUrl + descriptionPath)
324 map(res => res.description),
325 catchError(err => this.restExtractor.handleError(err))
329 setVideoLike (id: number) {
330 return this.setVideoRate(id, 'like')
333 setVideoDislike (id: number) {
334 return this.setVideoRate(id, 'dislike')
337 unsetVideoLike (id: number) {
338 return this.setVideoRate(id, 'none')
341 getUserVideoRating (id: number) {
342 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
344 return this.authHttp.get<UserVideoRate>(url)
345 .pipe(catchError(err => this.restExtractor.handleError(err)))
348 extractVideos (result: ResultList<VideoServerModel>) {
349 return this.serverService.getServerLocale()
351 map(translations => {
352 const videosJson = result.data
353 const totalVideos = result.total
354 const videos: Video[] = []
356 for (const videoJson of videosJson) {
357 videos.push(new Video(videoJson, translations))
360 return { total: totalVideos, data: videos }
365 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
366 const descriptions = {
367 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
368 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
369 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
370 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
373 const videoPrivacies = serverPrivacies.map(p => {
377 description: descriptions[p.id]
383 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
387 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
388 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
390 for (const privacy of order) {
391 if (serverPrivacies.find(p => p.id === privacy)) {
396 throw new Error('No highest privacy available')
399 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
400 return nsfwPolicy === 'do_not_list'
405 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
421 const pagination = videoPagination
422 ? this.restService.componentToRestPagination(videoPagination)
425 let newParams = this.restService.addRestGetParams(params, pagination, sort)
427 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
429 if (isLocal) newParams = newParams.set('isLocal', isLocal)
430 if (include) newParams = newParams.set('include', include)
431 if (isLive) newParams = newParams.set('isLive', isLive)
432 if (nsfw) newParams = newParams.set('nsfw', nsfw)
433 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
434 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
435 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
436 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
441 private setVideoRate (id: number, rateType: UserVideoRateType) {
442 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
443 const body: UserVideoRateUpdate = {
449 .pipe(catchError(err => this.restExtractor.handleError(err)))