1 import { SortMeta } from 'primeng/api'
2 import { from, Observable, of } 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 { AuthService, 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 { VideoSource } from '@shared/models/videos/video-source'
28 import { environment } from '../../../../environments/environment'
29 import { Account } from '../account/account.model'
30 import { AccountService } from '../account/account.service'
31 import { VideoChannel, VideoChannelService } from '../video-channel'
32 import { VideoDetails } from './video-details.model'
33 import { VideoEdit } from './video-edit.model'
34 import { Video } from './video.model'
36 export type CommonVideoParams = {
37 videoPagination?: ComponentPaginationLight
38 sort: VideoSortField | SortMeta
39 include?: VideoInclude
41 categoryOneOf?: number[]
42 languageOneOf?: string[]
43 privacyOneOf?: VideoPrivacy[]
48 nsfwPolicy?: NSFWPolicyType
49 nsfw?: BooleanBothQuery
53 export class VideoService {
54 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
55 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
56 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
59 private auth: AuthService,
60 private authHttp: HttpClient,
61 private restExtractor: RestExtractor,
62 private restService: RestService,
63 private serverService: ServerService
66 getVideoViewUrl (uuid: string) {
67 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
70 getVideo (options: { videoId: string }): Observable<VideoDetails> {
71 return this.serverService.getServerLocale()
73 switchMap(translations => {
74 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
75 .pipe(map(videoHash => ({ videoHash, translations })))
77 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
78 catchError(err => this.restExtractor.handleError(err))
82 updateVideo (video: VideoEdit) {
83 const language = video.language || null
84 const licence = video.licence || null
85 const category = video.category || null
86 const description = video.description || null
87 const support = video.support || null
88 const scheduleUpdate = video.scheduleUpdate || null
89 const originallyPublishedAt = video.originallyPublishedAt || null
91 const body: VideoUpdate = {
98 channelId: video.channelId,
99 privacy: video.privacy,
102 waitTranscoding: video.waitTranscoding,
103 commentsEnabled: video.commentsEnabled,
104 downloadEnabled: video.downloadEnabled,
105 thumbnailfile: video.thumbnailfile,
106 previewfile: video.previewfile,
107 pluginData: video.pluginData,
109 originallyPublishedAt
112 const data = objectToFormData(body)
114 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
115 .pipe(catchError(err => this.restExtractor.handleError(err)))
118 uploadVideo (video: FormData) {
119 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
122 .request<{ video: { id: number, uuid: string } }>(req)
123 .pipe(catchError(err => this.restExtractor.handleError(err)))
126 getMyVideos (options: {
127 videoPagination: ComponentPaginationLight
129 userChannels?: VideoChannelServerModel[]
131 }): Observable<ResultList<Video>> {
132 const { videoPagination, sort, userChannels = [], search } = options
134 const pagination = this.restService.componentToRestPagination(videoPagination)
136 let params = new HttpParams()
137 params = this.restService.addRestGetParams(params, pagination, sort)
140 const filters = this.restService.parseQueryStringFilter(search, {
147 handler: (name: string) => {
148 const channel = userChannels.find(c => c.name === name)
150 if (channel) return channel.id
157 params = this.restService.addObjectParams(params, filters)
161 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
163 switchMap(res => this.extractVideos(res)),
164 catchError(err => this.restExtractor.handleError(err))
168 getAccountVideos (parameters: CommonVideoParams & {
169 account: Pick<Account, 'nameWithHost'>
171 }): Observable<ResultList<Video>> {
172 const { account, search } = parameters
174 let params = new HttpParams()
175 params = this.buildCommonVideosParams({ params, ...parameters })
177 if (search) params = params.set('search', search)
180 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
182 switchMap(res => this.extractVideos(res)),
183 catchError(err => this.restExtractor.handleError(err))
187 getVideoChannelVideos (parameters: CommonVideoParams & {
188 videoChannel: Pick<VideoChannel, 'nameWithHost'>
189 }): Observable<ResultList<Video>> {
190 const { videoChannel } = parameters
192 let params = new HttpParams()
193 params = this.buildCommonVideosParams({ params, ...parameters })
196 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
198 switchMap(res => this.extractVideos(res)),
199 catchError(err => this.restExtractor.handleError(err))
203 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
204 let params = new HttpParams()
205 params = this.buildCommonVideosParams({ params, ...parameters })
208 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
210 switchMap(res => this.extractVideos(res)),
211 catchError(err => this.restExtractor.handleError(err))
215 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
218 format: FeedFormat.RSS,
219 label: 'media rss 2.0',
220 url: base + FeedFormat.RSS.toLowerCase()
223 format: FeedFormat.ATOM,
225 url: base + FeedFormat.ATOM.toLowerCase()
228 format: FeedFormat.JSON,
230 url: base + FeedFormat.JSON.toLowerCase()
234 if (params && params.keys().length !== 0) {
235 for (const feed of feeds) {
236 feed.url += '?' + params.toString()
243 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
244 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
246 if (isLocal) params = params.set('isLocal', isLocal)
249 for (const c of categoryOneOf) {
250 params = params.append('categoryOneOf[]', c + '')
254 return this.buildBaseFeedUrls(params)
257 getAccountFeedUrls (accountId: number) {
258 let params = this.restService.addRestGetParams(new HttpParams())
259 params = params.set('accountId', accountId.toString())
261 return this.buildBaseFeedUrls(params)
264 getVideoChannelFeedUrls (videoChannelId: number) {
265 let params = this.restService.addRestGetParams(new HttpParams())
266 params = params.set('videoChannelId', videoChannelId.toString())
268 return this.buildBaseFeedUrls(params)
271 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
272 let params = this.restService.addRestGetParams(new HttpParams())
273 params = params.set('accountId', accountId.toString())
274 params = params.set('token', feedToken)
276 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
279 getVideoFileMetadata (metadataUrl: string) {
281 .get<VideoFileMetadata>(metadataUrl)
283 catchError(err => this.restExtractor.handleError(err))
287 removeVideo (idArg: number | number[]) {
288 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
292 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
294 catchError(err => this.restExtractor.handleError(err))
298 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
299 return from(videoIds)
301 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
303 catchError(err => this.restExtractor.handleError(err))
307 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
308 const body: VideoTranscodingCreate = { transcodingType: type }
310 return from(videoIds)
312 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
314 catchError(err => this.restExtractor.handleError(err))
318 loadCompleteDescription (descriptionPath: string) {
320 .get<{ description: string }>(environment.apiUrl + descriptionPath)
322 map(res => res.description),
323 catchError(err => this.restExtractor.handleError(err))
327 getSource (videoId: number) {
329 .get<{ source: VideoSource }>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
332 if (err.status === 404) {
336 this.restExtractor.handleError(err)
341 setVideoLike (id: number) {
342 return this.setVideoRate(id, 'like')
345 setVideoDislike (id: number) {
346 return this.setVideoRate(id, 'dislike')
349 unsetVideoLike (id: number) {
350 return this.setVideoRate(id, 'none')
353 getUserVideoRating (id: number) {
354 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
356 return this.authHttp.get<UserVideoRate>(url)
357 .pipe(catchError(err => this.restExtractor.handleError(err)))
360 extractVideos (result: ResultList<VideoServerModel>) {
361 return this.serverService.getServerLocale()
363 map(translations => {
364 const videosJson = result.data
365 const totalVideos = result.total
366 const videos: Video[] = []
368 for (const videoJson of videosJson) {
369 videos.push(new Video(videoJson, translations))
372 return { total: totalVideos, data: videos }
377 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
378 const descriptions = {
379 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
380 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
381 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
382 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
385 const videoPrivacies = serverPrivacies.map(p => {
389 description: descriptions[p.id]
395 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
399 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
400 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
402 for (const privacy of order) {
403 if (serverPrivacies.find(p => p.id === privacy)) {
408 throw new Error('No highest privacy available')
411 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
412 return nsfwPolicy === 'do_not_list'
417 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
433 const pagination = videoPagination
434 ? this.restService.componentToRestPagination(videoPagination)
437 let newParams = this.restService.addRestGetParams(params, pagination, this.buildListSort(sort))
439 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
441 if (isLocal) newParams = newParams.set('isLocal', isLocal)
442 if (include) newParams = newParams.set('include', include)
443 if (isLive) newParams = newParams.set('isLive', isLive)
444 if (nsfw) newParams = newParams.set('nsfw', nsfw)
445 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
446 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
447 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
448 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
453 private buildListSort (sortArg: VideoSortField | SortMeta) {
454 const sort = this.restService.buildSortString(sortArg)
456 if (typeof sort === 'string') {
457 // Silently use the best algorithm for logged in users if they chose the hot algorithm
459 this.auth.isLoggedIn() &&
460 (sort === 'hot' || sort === '-hot')
462 return sort.replace('hot', 'best')
469 private setVideoRate (id: number, rateType: UserVideoRateType) {
470 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
471 const body: UserVideoRateUpdate = {
477 .pipe(catchError(err => this.restExtractor.handleError(err)))