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)
118 map(this.restExtractor.extractDataBool),
119 catchError(err => this.restExtractor.handleError(err))
123 uploadVideo (video: FormData) {
124 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
127 .request<{ video: { id: number, uuid: string } }>(req)
128 .pipe(catchError(err => this.restExtractor.handleError(err)))
131 getMyVideos (options: {
132 videoPagination: ComponentPaginationLight
134 userChannels?: VideoChannelServerModel[]
136 }): Observable<ResultList<Video>> {
137 const { videoPagination, sort, userChannels = [], search } = options
139 const pagination = this.restService.componentToRestPagination(videoPagination)
141 let params = new HttpParams()
142 params = this.restService.addRestGetParams(params, pagination, sort)
145 const filters = this.restService.parseQueryStringFilter(search, {
152 handler: (name: string) => {
153 const channel = userChannels.find(c => c.name === name)
155 if (channel) return channel.id
162 params = this.restService.addObjectParams(params, filters)
166 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
168 switchMap(res => this.extractVideos(res)),
169 catchError(err => this.restExtractor.handleError(err))
173 getAccountVideos (parameters: CommonVideoParams & {
174 account: Pick<Account, 'nameWithHost'>
176 }): Observable<ResultList<Video>> {
177 const { account, search } = parameters
179 let params = new HttpParams()
180 params = this.buildCommonVideosParams({ params, ...parameters })
182 if (search) params = params.set('search', search)
185 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
187 switchMap(res => this.extractVideos(res)),
188 catchError(err => this.restExtractor.handleError(err))
192 getVideoChannelVideos (parameters: CommonVideoParams & {
193 videoChannel: Pick<VideoChannel, 'nameWithHost'>
194 }): Observable<ResultList<Video>> {
195 const { videoChannel } = parameters
197 let params = new HttpParams()
198 params = this.buildCommonVideosParams({ params, ...parameters })
201 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
203 switchMap(res => this.extractVideos(res)),
204 catchError(err => this.restExtractor.handleError(err))
208 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
209 let params = new HttpParams()
210 params = this.buildCommonVideosParams({ params, ...parameters })
213 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
215 switchMap(res => this.extractVideos(res)),
216 catchError(err => this.restExtractor.handleError(err))
220 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
223 format: FeedFormat.RSS,
224 label: 'media rss 2.0',
225 url: base + FeedFormat.RSS.toLowerCase()
228 format: FeedFormat.ATOM,
230 url: base + FeedFormat.ATOM.toLowerCase()
233 format: FeedFormat.JSON,
235 url: base + FeedFormat.JSON.toLowerCase()
239 if (params && params.keys().length !== 0) {
240 for (const feed of feeds) {
241 feed.url += '?' + params.toString()
248 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
249 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
251 if (isLocal) params = params.set('isLocal', isLocal)
254 for (const c of categoryOneOf) {
255 params = params.append('categoryOneOf[]', c + '')
259 return this.buildBaseFeedUrls(params)
262 getAccountFeedUrls (accountId: number) {
263 let params = this.restService.addRestGetParams(new HttpParams())
264 params = params.set('accountId', accountId.toString())
266 return this.buildBaseFeedUrls(params)
269 getVideoChannelFeedUrls (videoChannelId: number) {
270 let params = this.restService.addRestGetParams(new HttpParams())
271 params = params.set('videoChannelId', videoChannelId.toString())
273 return this.buildBaseFeedUrls(params)
276 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
277 let params = this.restService.addRestGetParams(new HttpParams())
278 params = params.set('accountId', accountId.toString())
279 params = params.set('token', feedToken)
281 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
284 getVideoFileMetadata (metadataUrl: string) {
286 .get<VideoFileMetadata>(metadataUrl)
288 catchError(err => this.restExtractor.handleError(err))
292 removeVideo (idArg: number | number[]) {
293 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
297 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
299 catchError(err => this.restExtractor.handleError(err))
303 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
304 return from(videoIds)
306 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
308 catchError(err => this.restExtractor.handleError(err))
312 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
313 const body: VideoTranscodingCreate = { transcodingType: type }
315 return from(videoIds)
317 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
319 catchError(err => this.restExtractor.handleError(err))
323 loadCompleteDescription (descriptionPath: string) {
325 .get<{ description: string }>(environment.apiUrl + descriptionPath)
327 map(res => res.description),
328 catchError(err => this.restExtractor.handleError(err))
332 setVideoLike (id: number) {
333 return this.setVideoRate(id, 'like')
336 setVideoDislike (id: number) {
337 return this.setVideoRate(id, 'dislike')
340 unsetVideoLike (id: number) {
341 return this.setVideoRate(id, 'none')
344 getUserVideoRating (id: number) {
345 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
347 return this.authHttp.get<UserVideoRate>(url)
348 .pipe(catchError(err => this.restExtractor.handleError(err)))
351 extractVideos (result: ResultList<VideoServerModel>) {
352 return this.serverService.getServerLocale()
354 map(translations => {
355 const videosJson = result.data
356 const totalVideos = result.total
357 const videos: Video[] = []
359 for (const videoJson of videosJson) {
360 videos.push(new Video(videoJson, translations))
363 return { total: totalVideos, data: videos }
368 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
369 const descriptions = {
370 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
371 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
372 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
373 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
376 const videoPrivacies = serverPrivacies.map(p => {
380 description: descriptions[p.id]
386 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
390 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
391 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
393 for (const privacy of order) {
394 if (serverPrivacies.find(p => p.id === privacy)) {
399 throw new Error('No highest privacy available')
402 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
403 return nsfwPolicy === 'do_not_list'
408 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
424 const pagination = videoPagination
425 ? this.restService.componentToRestPagination(videoPagination)
428 let newParams = this.restService.addRestGetParams(params, pagination, sort)
430 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
432 if (isLocal) newParams = newParams.set('isLocal', isLocal)
433 if (include) newParams = newParams.set('include', include)
434 if (isLive) newParams = newParams.set('isLive', isLive)
435 if (nsfw) newParams = newParams.set('nsfw', nsfw)
436 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
437 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
438 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
439 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
444 private setVideoRate (id: number, rateType: UserVideoRateType) {
445 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
446 const body: UserVideoRateUpdate = {
453 map(this.restExtractor.extractDataBool),
454 catchError(err => this.restExtractor.handleError(err))