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'
16 Video as VideoServerModel,
17 VideoChannel as VideoChannelServerModel,
19 VideoDetails as VideoDetailsServerModel,
25 } from '@shared/models'
26 import { environment } from '../../../../environments/environment'
27 import { Account } from '../account/account.model'
28 import { AccountService } from '../account/account.service'
29 import { VideoChannel, VideoChannelService } from '../video-channel'
30 import { VideoDetails } from './video-details.model'
31 import { VideoEdit } from './video-edit.model'
32 import { Video } from './video.model'
34 export type CommonVideoParams = {
35 videoPagination?: ComponentPaginationLight
36 sort: VideoSortField | SortMeta
38 categoryOneOf?: number[]
39 languageOneOf?: string[]
43 nsfwPolicy?: NSFWPolicyType
44 nsfw?: BooleanBothQuery
48 export class VideoService {
49 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
50 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
51 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
54 private authHttp: HttpClient,
55 private restExtractor: RestExtractor,
56 private restService: RestService,
57 private serverService: ServerService
60 getVideoViewUrl (uuid: string) {
61 return VideoService.BASE_VIDEO_URL + uuid + '/views'
64 getUserWatchingVideoUrl (uuid: string) {
65 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
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)
114 map(this.restExtractor.extractDataBool),
115 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))
205 parameters: Omit<CommonVideoParams, 'filter'> & { pagination: RestPagination, search?: string }
206 ): Observable<ResultList<Video>> {
207 const { pagination, search } = parameters
209 let params = new HttpParams()
210 params = this.buildCommonVideosParams({ params, ...parameters })
212 params = params.set('start', pagination.start.toString())
213 .set('count', pagination.count.toString())
216 params = this.buildAdminParamsFromSearch(search, params)
219 if (!params.has('filter')) params = params.set('filter', 'all')
222 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
224 switchMap(res => this.extractVideos(res)),
225 catchError(err => this.restExtractor.handleError(err))
229 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
230 let params = new HttpParams()
231 params = this.buildCommonVideosParams({ params, ...parameters })
234 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
236 switchMap(res => this.extractVideos(res)),
237 catchError(err => this.restExtractor.handleError(err))
241 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
244 format: FeedFormat.RSS,
245 label: 'media rss 2.0',
246 url: base + FeedFormat.RSS.toLowerCase()
249 format: FeedFormat.ATOM,
251 url: base + FeedFormat.ATOM.toLowerCase()
254 format: FeedFormat.JSON,
256 url: base + FeedFormat.JSON.toLowerCase()
260 if (params && params.keys().length !== 0) {
261 for (const feed of feeds) {
262 feed.url += '?' + params.toString()
269 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
270 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
272 if (filter) params = params.set('filter', filter)
275 for (const c of categoryOneOf) {
276 params = params.append('categoryOneOf[]', c + '')
280 return this.buildBaseFeedUrls(params)
283 getAccountFeedUrls (accountId: number) {
284 let params = this.restService.addRestGetParams(new HttpParams())
285 params = params.set('accountId', accountId.toString())
287 return this.buildBaseFeedUrls(params)
290 getVideoChannelFeedUrls (videoChannelId: number) {
291 let params = this.restService.addRestGetParams(new HttpParams())
292 params = params.set('videoChannelId', videoChannelId.toString())
294 return this.buildBaseFeedUrls(params)
297 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
298 let params = this.restService.addRestGetParams(new HttpParams())
299 params = params.set('accountId', accountId.toString())
300 params = params.set('token', feedToken)
302 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
305 getVideoFileMetadata (metadataUrl: string) {
307 .get<VideoFileMetadata>(metadataUrl)
309 catchError(err => this.restExtractor.handleError(err))
313 removeVideo (idArg: number | number[]) {
314 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
318 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + id)),
320 catchError(err => this.restExtractor.handleError(err))
324 loadCompleteDescription (descriptionPath: string) {
326 .get<{ description: string }>(environment.apiUrl + descriptionPath)
328 map(res => res.description),
329 catchError(err => this.restExtractor.handleError(err))
333 setVideoLike (id: number) {
334 return this.setVideoRate(id, 'like')
337 setVideoDislike (id: number) {
338 return this.setVideoRate(id, 'dislike')
341 unsetVideoLike (id: number) {
342 return this.setVideoRate(id, 'none')
345 getUserVideoRating (id: number) {
346 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
348 return this.authHttp.get<UserVideoRate>(url)
349 .pipe(catchError(err => this.restExtractor.handleError(err)))
352 extractVideos (result: ResultList<VideoServerModel>) {
353 return this.serverService.getServerLocale()
355 map(translations => {
356 const videosJson = result.data
357 const totalVideos = result.total
358 const videos: Video[] = []
360 for (const videoJson of videosJson) {
361 videos.push(new Video(videoJson, translations))
364 return { total: totalVideos, data: videos }
369 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
370 const descriptions = {
371 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
372 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
373 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
374 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
377 const videoPrivacies = serverPrivacies.map(p => {
381 description: descriptions[p.id]
387 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
391 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
392 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
394 for (const privacy of order) {
395 if (serverPrivacies.find(p => p.id === privacy)) {
400 throw new Error('No highest privacy available')
403 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
404 return nsfwPolicy === 'do_not_list'
409 private setVideoRate (id: number, rateType: UserVideoRateType) {
410 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
411 const body: UserVideoRateUpdate = {
418 map(this.restExtractor.extractDataBool),
419 catchError(err => this.restExtractor.handleError(err))
423 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 (filter) newParams = newParams.set('filter', filter)
444 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
446 if (isLive) newParams = newParams.set('isLive', isLive)
447 if (nsfw) newParams = newParams.set('nsfw', nsfw)
448 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
449 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
450 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
455 private buildAdminParamsFromSearch (search: string, params: HttpParams) {
456 const filters = this.restService.parseQueryStringFilter(search, {
460 if (v === 'true') return 'all-local'
467 return this.restService.addObjectParams(params, filters)