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 getVideo (options: { videoId: string }): Observable<VideoDetails> {
69 return this.serverService.getServerLocale()
71 switchMap(translations => {
72 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
73 .pipe(map(videoHash => ({ videoHash, translations })))
75 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
76 catchError(err => this.restExtractor.handleError(err))
80 updateVideo (video: VideoEdit) {
81 const language = video.language || null
82 const licence = video.licence || null
83 const category = video.category || null
84 const description = video.description || null
85 const support = video.support || null
86 const scheduleUpdate = video.scheduleUpdate || null
87 const originallyPublishedAt = video.originallyPublishedAt || null
89 const body: VideoUpdate = {
96 channelId: video.channelId,
97 privacy: video.privacy,
100 waitTranscoding: video.waitTranscoding,
101 commentsEnabled: video.commentsEnabled,
102 downloadEnabled: video.downloadEnabled,
103 thumbnailfile: video.thumbnailfile,
104 previewfile: video.previewfile,
105 pluginData: video.pluginData,
107 originallyPublishedAt
110 const data = objectToFormData(body)
112 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
113 .pipe(catchError(err => this.restExtractor.handleError(err)))
116 uploadVideo (video: FormData) {
117 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
120 .request<{ video: { id: number, uuid: string } }>(req)
121 .pipe(catchError(err => this.restExtractor.handleError(err)))
124 getMyVideos (options: {
125 videoPagination: ComponentPaginationLight
127 userChannels?: VideoChannelServerModel[]
129 }): Observable<ResultList<Video>> {
130 const { videoPagination, sort, userChannels = [], search } = options
132 const pagination = this.restService.componentToRestPagination(videoPagination)
134 let params = new HttpParams()
135 params = this.restService.addRestGetParams(params, pagination, sort)
138 const filters = this.restService.parseQueryStringFilter(search, {
145 handler: (name: string) => {
146 const channel = userChannels.find(c => c.name === name)
148 if (channel) return channel.id
155 params = this.restService.addObjectParams(params, filters)
159 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
161 switchMap(res => this.extractVideos(res)),
162 catchError(err => this.restExtractor.handleError(err))
166 getAccountVideos (parameters: CommonVideoParams & {
167 account: Pick<Account, 'nameWithHost'>
169 }): Observable<ResultList<Video>> {
170 const { account, search } = parameters
172 let params = new HttpParams()
173 params = this.buildCommonVideosParams({ params, ...parameters })
175 if (search) params = params.set('search', search)
178 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
180 switchMap(res => this.extractVideos(res)),
181 catchError(err => this.restExtractor.handleError(err))
185 getVideoChannelVideos (parameters: CommonVideoParams & {
186 videoChannel: Pick<VideoChannel, 'nameWithHost'>
187 }): Observable<ResultList<Video>> {
188 const { videoChannel } = parameters
190 let params = new HttpParams()
191 params = this.buildCommonVideosParams({ params, ...parameters })
194 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
196 switchMap(res => this.extractVideos(res)),
197 catchError(err => this.restExtractor.handleError(err))
201 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
202 let params = new HttpParams()
203 params = this.buildCommonVideosParams({ params, ...parameters })
206 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
208 switchMap(res => this.extractVideos(res)),
209 catchError(err => this.restExtractor.handleError(err))
213 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
216 format: FeedFormat.RSS,
217 label: 'media rss 2.0',
218 url: base + FeedFormat.RSS.toLowerCase()
221 format: FeedFormat.ATOM,
223 url: base + FeedFormat.ATOM.toLowerCase()
226 format: FeedFormat.JSON,
228 url: base + FeedFormat.JSON.toLowerCase()
232 if (params && params.keys().length !== 0) {
233 for (const feed of feeds) {
234 feed.url += '?' + params.toString()
241 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
242 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
244 if (isLocal) params = params.set('isLocal', isLocal)
247 for (const c of categoryOneOf) {
248 params = params.append('categoryOneOf[]', c + '')
252 return this.buildBaseFeedUrls(params)
255 getAccountFeedUrls (accountId: number) {
256 let params = this.restService.addRestGetParams(new HttpParams())
257 params = params.set('accountId', accountId.toString())
259 return this.buildBaseFeedUrls(params)
262 getVideoChannelFeedUrls (videoChannelId: number) {
263 let params = this.restService.addRestGetParams(new HttpParams())
264 params = params.set('videoChannelId', videoChannelId.toString())
266 return this.buildBaseFeedUrls(params)
269 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
270 let params = this.restService.addRestGetParams(new HttpParams())
271 params = params.set('accountId', accountId.toString())
272 params = params.set('token', feedToken)
274 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
277 getVideoFileMetadata (metadataUrl: string) {
279 .get<VideoFileMetadata>(metadataUrl)
281 catchError(err => this.restExtractor.handleError(err))
285 removeVideo (idArg: number | number[]) {
286 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
290 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
292 catchError(err => this.restExtractor.handleError(err))
296 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
297 return from(videoIds)
299 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
301 catchError(err => this.restExtractor.handleError(err))
305 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
306 const body: VideoTranscodingCreate = { transcodingType: type }
308 return from(videoIds)
310 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
312 catchError(err => this.restExtractor.handleError(err))
316 loadCompleteDescription (descriptionPath: string) {
318 .get<{ description: string }>(environment.apiUrl + descriptionPath)
320 map(res => res.description),
321 catchError(err => this.restExtractor.handleError(err))
325 setVideoLike (id: number) {
326 return this.setVideoRate(id, 'like')
329 setVideoDislike (id: number) {
330 return this.setVideoRate(id, 'dislike')
333 unsetVideoLike (id: number) {
334 return this.setVideoRate(id, 'none')
337 getUserVideoRating (id: number) {
338 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
340 return this.authHttp.get<UserVideoRate>(url)
341 .pipe(catchError(err => this.restExtractor.handleError(err)))
344 extractVideos (result: ResultList<VideoServerModel>) {
345 return this.serverService.getServerLocale()
347 map(translations => {
348 const videosJson = result.data
349 const totalVideos = result.total
350 const videos: Video[] = []
352 for (const videoJson of videosJson) {
353 videos.push(new Video(videoJson, translations))
356 return { total: totalVideos, data: videos }
361 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
362 const descriptions = {
363 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
364 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
365 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
366 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
369 const videoPrivacies = serverPrivacies.map(p => {
373 description: descriptions[p.id]
379 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
383 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
384 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
386 for (const privacy of order) {
387 if (serverPrivacies.find(p => p.id === privacy)) {
392 throw new Error('No highest privacy available')
395 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
396 return nsfwPolicy === 'do_not_list'
401 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
417 const pagination = videoPagination
418 ? this.restService.componentToRestPagination(videoPagination)
421 let newParams = this.restService.addRestGetParams(params, pagination, sort)
423 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
425 if (isLocal) newParams = newParams.set('isLocal', isLocal)
426 if (include) newParams = newParams.set('include', include)
427 if (isLive) newParams = newParams.set('isLive', isLive)
428 if (nsfw) newParams = newParams.set('nsfw', nsfw)
429 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
430 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
431 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
432 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
437 private setVideoRate (id: number, rateType: UserVideoRateType) {
438 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
439 const body: UserVideoRateUpdate = {
445 .pipe(catchError(err => this.restExtractor.handleError(err)))