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'
8 import { arrayify } from '@shared/core-utils'
17 Video as VideoServerModel,
18 VideoChannel as VideoChannelServerModel,
20 VideoDetails as VideoDetailsServerModel,
25 VideoTranscodingCreate,
27 } from '@shared/models'
28 import { VideoSource } from '@shared/models/videos/video-source'
29 import { environment } from '../../../../environments/environment'
30 import { Account } from '../account/account.model'
31 import { AccountService } from '../account/account.service'
32 import { VideoChannel, VideoChannelService } from '../video-channel'
33 import { VideoDetails } from './video-details.model'
34 import { VideoEdit } from './video-edit.model'
35 import { Video } from './video.model'
37 export type CommonVideoParams = {
38 videoPagination?: ComponentPaginationLight
39 sort: VideoSortField | SortMeta
40 include?: VideoInclude
42 categoryOneOf?: number[]
43 languageOneOf?: string[]
44 privacyOneOf?: VideoPrivacy[]
49 nsfwPolicy?: NSFWPolicyType
50 nsfw?: BooleanBothQuery
54 export class VideoService {
55 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
56 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
57 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
60 private auth: AuthService,
61 private authHttp: HttpClient,
62 private restExtractor: RestExtractor,
63 private restService: RestService,
64 private serverService: ServerService
67 getVideoViewUrl (uuid: string) {
68 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
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)
116 .pipe(catchError(err => this.restExtractor.handleError(err)))
119 uploadVideo (video: FormData) {
120 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
123 .request<{ video: { id: number, uuid: string } }>(req)
124 .pipe(catchError(err => this.restExtractor.handleError(err)))
127 getMyVideos (options: {
128 videoPagination: ComponentPaginationLight
130 userChannels?: VideoChannelServerModel[]
132 }): Observable<ResultList<Video>> {
133 const { videoPagination, sort, userChannels = [], search } = options
135 const pagination = this.restService.componentToRestPagination(videoPagination)
137 let params = new HttpParams()
138 params = this.restService.addRestGetParams(params, pagination, sort)
141 const filters = this.restService.parseQueryStringFilter(search, {
148 handler: (name: string) => {
149 const channel = userChannels.find(c => c.name === name)
151 if (channel) return channel.id
158 params = this.restService.addObjectParams(params, filters)
162 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
164 switchMap(res => this.extractVideos(res)),
165 catchError(err => this.restExtractor.handleError(err))
169 getAccountVideos (parameters: CommonVideoParams & {
170 account: Pick<Account, 'nameWithHost'>
172 }): Observable<ResultList<Video>> {
173 const { account, search } = parameters
175 let params = new HttpParams()
176 params = this.buildCommonVideosParams({ params, ...parameters })
178 if (search) params = params.set('search', search)
181 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
183 switchMap(res => this.extractVideos(res)),
184 catchError(err => this.restExtractor.handleError(err))
188 getVideoChannelVideos (parameters: CommonVideoParams & {
189 videoChannel: Pick<VideoChannel, 'nameWithHost'>
190 }): Observable<ResultList<Video>> {
191 const { videoChannel } = parameters
193 let params = new HttpParams()
194 params = this.buildCommonVideosParams({ params, ...parameters })
197 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
199 switchMap(res => this.extractVideos(res)),
200 catchError(err => this.restExtractor.handleError(err))
204 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
205 let params = new HttpParams()
206 params = this.buildCommonVideosParams({ params, ...parameters })
209 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
211 switchMap(res => this.extractVideos(res)),
212 catchError(err => this.restExtractor.handleError(err))
216 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
219 format: FeedFormat.RSS,
220 label: 'media rss 2.0',
221 url: base + FeedFormat.RSS.toLowerCase()
224 format: FeedFormat.ATOM,
226 url: base + FeedFormat.ATOM.toLowerCase()
229 format: FeedFormat.JSON,
231 url: base + FeedFormat.JSON.toLowerCase()
235 if (params && params.keys().length !== 0) {
236 for (const feed of feeds) {
237 feed.url += '?' + params.toString()
244 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
245 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
247 if (isLocal) params = params.set('isLocal', isLocal)
250 for (const c of categoryOneOf) {
251 params = params.append('categoryOneOf[]', c + '')
255 return this.buildBaseFeedUrls(params)
258 getAccountFeedUrls (accountId: number) {
259 let params = this.restService.addRestGetParams(new HttpParams())
260 params = params.set('accountId', accountId.toString())
262 return this.buildBaseFeedUrls(params)
265 getVideoChannelFeedUrls (videoChannelId: number) {
266 let params = this.restService.addRestGetParams(new HttpParams())
267 params = params.set('videoChannelId', videoChannelId.toString())
269 return this.buildBaseFeedUrls(params)
272 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
273 let params = this.restService.addRestGetParams(new HttpParams())
274 params = params.set('accountId', accountId.toString())
275 params = params.set('token', feedToken)
277 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
280 getVideoFileMetadata (metadataUrl: string) {
282 .get<VideoFileMetadata>(metadataUrl)
284 catchError(err => this.restExtractor.handleError(err))
288 removeVideo (idArg: number | number[]) {
289 const ids = arrayify(idArg)
293 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
295 catchError(err => this.restExtractor.handleError(err))
299 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
300 return from(videoIds)
302 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
304 catchError(err => this.restExtractor.handleError(err))
308 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
309 const body: VideoTranscodingCreate = { transcodingType: type }
311 return from(videoIds)
313 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
315 catchError(err => this.restExtractor.handleError(err))
319 loadCompleteDescription (descriptionPath: string) {
321 .get<{ description: string }>(environment.apiUrl + descriptionPath)
323 map(res => res.description),
324 catchError(err => this.restExtractor.handleError(err))
328 getSource (videoId: number) {
330 .get<{ source: VideoSource }>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
333 if (err.status === 404) {
337 this.restExtractor.handleError(err)
342 setVideoLike (id: string) {
343 return this.setVideoRate(id, 'like')
346 setVideoDislike (id: string) {
347 return this.setVideoRate(id, 'dislike')
350 unsetVideoLike (id: string) {
351 return this.setVideoRate(id, 'none')
354 getUserVideoRating (id: string) {
355 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
357 return this.authHttp.get<UserVideoRate>(url)
358 .pipe(catchError(err => this.restExtractor.handleError(err)))
361 extractVideos (result: ResultList<VideoServerModel>) {
362 return this.serverService.getServerLocale()
364 map(translations => {
365 const videosJson = result.data
366 const totalVideos = result.total
367 const videos: Video[] = []
369 for (const videoJson of videosJson) {
370 videos.push(new Video(videoJson, translations))
373 return { total: totalVideos, data: videos }
378 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
379 const descriptions = {
380 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
381 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
382 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
383 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
386 const videoPrivacies = serverPrivacies.map(p => {
390 description: descriptions[p.id]
396 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
400 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
401 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
403 for (const privacy of order) {
404 if (serverPrivacies.find(p => p.id === privacy)) {
409 throw new Error('No highest privacy available')
412 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
413 return nsfwPolicy === 'do_not_list'
418 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
434 const pagination = videoPagination
435 ? this.restService.componentToRestPagination(videoPagination)
438 let newParams = this.restService.addRestGetParams(params, pagination, this.buildListSort(sort))
440 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
442 if (isLocal !== undefined) newParams = newParams.set('isLocal', isLocal)
443 if (include !== undefined) newParams = newParams.set('include', include)
444 if (isLive !== undefined) newParams = newParams.set('isLive', isLive)
445 if (nsfw !== undefined) newParams = newParams.set('nsfw', nsfw)
446 if (nsfwPolicy !== undefined) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
447 if (languageOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
448 if (categoryOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
449 if (privacyOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
454 private buildListSort (sortArg: VideoSortField | SortMeta) {
455 const sort = this.restService.buildSortString(sortArg)
457 if (typeof sort === 'string') {
458 // Silently use the best algorithm for logged in users if they chose the hot algorithm
460 this.auth.isLoggedIn() &&
461 (sort === 'hot' || sort === '-hot')
463 return sort.replace('hot', 'best')
470 private setVideoRate (id: string, rateType: UserVideoRateType) {
471 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
472 const body: UserVideoRateUpdate = {
478 .pipe(catchError(err => this.restExtractor.handleError(err)))