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, RestPagination, RestService, ServerService, UserService } from '@app/core'
7 import { objectToFormData } from '@app/helpers'
8 import { AdvancedInputFilter } from '@app/shared/shared-forms'
17 Video as VideoServerModel,
18 VideoChannel as VideoChannelServerModel,
20 VideoDetails as VideoDetailsServerModel,
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[]
46 nsfwPolicy?: NSFWPolicyType
47 nsfw?: BooleanBothQuery
51 export class VideoService {
52 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
53 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
54 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
57 private authHttp: HttpClient,
58 private restExtractor: RestExtractor,
59 private restService: RestService,
60 private serverService: ServerService
63 getVideoViewUrl (uuid: string) {
64 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
67 getUserWatchingVideoUrl (uuid: string) {
68 return `${VideoService.BASE_VIDEO_URL}/${uuid}/watching`
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)
117 map(this.restExtractor.extractDataBool),
118 catchError(err => this.restExtractor.handleError(err))
122 uploadVideo (video: FormData) {
123 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
126 .request<{ video: { id: number, uuid: string } }>(req)
127 .pipe(catchError(err => this.restExtractor.handleError(err)))
130 getMyVideos (options: {
131 videoPagination: ComponentPaginationLight
133 userChannels?: VideoChannelServerModel[]
135 }): Observable<ResultList<Video>> {
136 const { videoPagination, sort, userChannels = [], search } = options
138 const pagination = this.restService.componentToRestPagination(videoPagination)
140 let params = new HttpParams()
141 params = this.restService.addRestGetParams(params, pagination, sort)
144 const filters = this.restService.parseQueryStringFilter(search, {
151 handler: (name: string) => {
152 const channel = userChannels.find(c => c.name === name)
154 if (channel) return channel.id
161 params = this.restService.addObjectParams(params, filters)
165 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
167 switchMap(res => this.extractVideos(res)),
168 catchError(err => this.restExtractor.handleError(err))
172 getAccountVideos (parameters: CommonVideoParams & {
173 account: Pick<Account, 'nameWithHost'>
175 }): Observable<ResultList<Video>> {
176 const { account, search } = parameters
178 let params = new HttpParams()
179 params = this.buildCommonVideosParams({ params, ...parameters })
181 if (search) params = params.set('search', search)
184 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
186 switchMap(res => this.extractVideos(res)),
187 catchError(err => this.restExtractor.handleError(err))
191 getVideoChannelVideos (parameters: CommonVideoParams & {
192 videoChannel: Pick<VideoChannel, 'nameWithHost'>
193 }): Observable<ResultList<Video>> {
194 const { videoChannel } = parameters
196 let params = new HttpParams()
197 params = this.buildCommonVideosParams({ params, ...parameters })
200 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
202 switchMap(res => this.extractVideos(res)),
203 catchError(err => this.restExtractor.handleError(err))
208 options: CommonVideoParams & { pagination: RestPagination, search?: string }
209 ): Observable<ResultList<Video>> {
210 const { pagination, search } = options
212 let params = new HttpParams()
213 params = this.buildCommonVideosParams({ params, ...options })
215 params = params.set('start', pagination.start.toString())
216 .set('count', pagination.count.toString())
218 params = this.buildAdminParamsFromSearch(search, params)
221 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
223 switchMap(res => this.extractVideos(res)),
224 catchError(err => this.restExtractor.handleError(err))
228 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
229 let params = new HttpParams()
230 params = this.buildCommonVideosParams({ params, ...parameters })
233 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
235 switchMap(res => this.extractVideos(res)),
236 catchError(err => this.restExtractor.handleError(err))
240 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
243 format: FeedFormat.RSS,
244 label: 'media rss 2.0',
245 url: base + FeedFormat.RSS.toLowerCase()
248 format: FeedFormat.ATOM,
250 url: base + FeedFormat.ATOM.toLowerCase()
253 format: FeedFormat.JSON,
255 url: base + FeedFormat.JSON.toLowerCase()
259 if (params && params.keys().length !== 0) {
260 for (const feed of feeds) {
261 feed.url += '?' + params.toString()
268 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
269 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
271 if (isLocal) params = params.set('isLocal', isLocal)
274 for (const c of categoryOneOf) {
275 params = params.append('categoryOneOf[]', c + '')
279 return this.buildBaseFeedUrls(params)
282 getAccountFeedUrls (accountId: number) {
283 let params = this.restService.addRestGetParams(new HttpParams())
284 params = params.set('accountId', accountId.toString())
286 return this.buildBaseFeedUrls(params)
289 getVideoChannelFeedUrls (videoChannelId: number) {
290 let params = this.restService.addRestGetParams(new HttpParams())
291 params = params.set('videoChannelId', videoChannelId.toString())
293 return this.buildBaseFeedUrls(params)
296 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
297 let params = this.restService.addRestGetParams(new HttpParams())
298 params = params.set('accountId', accountId.toString())
299 params = params.set('token', feedToken)
301 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
304 getVideoFileMetadata (metadataUrl: string) {
306 .get<VideoFileMetadata>(metadataUrl)
308 catchError(err => this.restExtractor.handleError(err))
312 removeVideo (idArg: number | number[]) {
313 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
317 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
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 private setVideoRate (id: number, rateType: UserVideoRateType) {
409 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
410 const body: UserVideoRateUpdate = {
417 map(this.restExtractor.extractDataBool),
418 catchError(err => this.restExtractor.handleError(err))
422 private buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
437 const pagination = videoPagination
438 ? this.restService.componentToRestPagination(videoPagination)
441 let newParams = this.restService.addRestGetParams(params, pagination, sort)
443 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
445 if (isLocal) newParams = newParams.set('isLocal', isLocal)
446 if (include) newParams = newParams.set('include', include)
447 if (isLive) newParams = newParams.set('isLive', isLive)
448 if (nsfw) newParams = newParams.set('nsfw', nsfw)
449 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
450 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
451 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
456 buildAdminInputFilter (): AdvancedInputFilter[] {
459 title: $localize`Videos scope`,
462 queryParams: { search: 'isLocal:false' },
463 label: $localize`Remote videos`
466 queryParams: { search: 'isLocal:true' },
467 label: $localize`Local videos`
473 title: $localize`Include/Exclude`,
476 queryParams: { search: 'excludeMuted' },
477 label: $localize`Exclude muted accounts`
484 private buildAdminParamsFromSearch (search: string, params: HttpParams) {
485 let include = VideoInclude.BLACKLISTED |
486 VideoInclude.BLOCKED_OWNER |
487 VideoInclude.HIDDEN_PRIVACY |
488 VideoInclude.NOT_PUBLISHED_STATE |
491 if (!search) return this.restService.addObjectParams(params, { include })
493 const filters = this.restService.parseQueryStringFilter(search, {
499 prefix: 'excludeMuted',
504 if (filters.excludeMuted) {
505 include &= ~VideoInclude.BLOCKED_OWNER
507 filters.excludeMuted = undefined
510 return this.restService.addObjectParams(params, { ...filters, include })