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
37 include?: VideoInclude
39 categoryOneOf?: number[]
40 languageOneOf?: string[]
45 nsfwPolicy?: NSFWPolicyType
46 nsfw?: BooleanBothQuery
50 export class VideoService {
51 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
52 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
53 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
56 private authHttp: HttpClient,
57 private restExtractor: RestExtractor,
58 private restService: RestService,
59 private serverService: ServerService
62 getVideoViewUrl (uuid: string) {
63 return VideoService.BASE_VIDEO_URL + uuid + '/views'
66 getUserWatchingVideoUrl (uuid: string) {
67 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
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)
116 map(this.restExtractor.extractDataBool),
117 catchError(err => this.restExtractor.handleError(err))
121 uploadVideo (video: FormData) {
122 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
125 .request<{ video: { id: number, uuid: string } }>(req)
126 .pipe(catchError(err => this.restExtractor.handleError(err)))
129 getMyVideos (options: {
130 videoPagination: ComponentPaginationLight
132 userChannels?: VideoChannelServerModel[]
134 }): Observable<ResultList<Video>> {
135 const { videoPagination, sort, userChannels = [], search } = options
137 const pagination = this.restService.componentToRestPagination(videoPagination)
139 let params = new HttpParams()
140 params = this.restService.addRestGetParams(params, pagination, sort)
143 const filters = this.restService.parseQueryStringFilter(search, {
150 handler: (name: string) => {
151 const channel = userChannels.find(c => c.name === name)
153 if (channel) return channel.id
160 params = this.restService.addObjectParams(params, filters)
164 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
166 switchMap(res => this.extractVideos(res)),
167 catchError(err => this.restExtractor.handleError(err))
171 getAccountVideos (parameters: CommonVideoParams & {
172 account: Pick<Account, 'nameWithHost'>
174 }): Observable<ResultList<Video>> {
175 const { account, search } = parameters
177 let params = new HttpParams()
178 params = this.buildCommonVideosParams({ params, ...parameters })
180 if (search) params = params.set('search', search)
183 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
185 switchMap(res => this.extractVideos(res)),
186 catchError(err => this.restExtractor.handleError(err))
190 getVideoChannelVideos (parameters: CommonVideoParams & {
191 videoChannel: Pick<VideoChannel, 'nameWithHost'>
192 }): Observable<ResultList<Video>> {
193 const { videoChannel } = parameters
195 let params = new HttpParams()
196 params = this.buildCommonVideosParams({ params, ...parameters })
199 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
201 switchMap(res => this.extractVideos(res)),
202 catchError(err => this.restExtractor.handleError(err))
207 parameters: CommonVideoParams & { pagination: RestPagination, search?: string }
208 ): Observable<ResultList<Video>> {
209 const { pagination, search } = parameters
211 const include = VideoInclude.BLACKLISTED |
212 VideoInclude.BLOCKED_OWNER |
213 VideoInclude.HIDDEN_PRIVACY |
214 VideoInclude.NOT_PUBLISHED_STATE |
217 let params = new HttpParams()
218 params = this.buildCommonVideosParams({ params, include, ...parameters })
220 params = params.set('start', pagination.start.toString())
221 .set('count', pagination.count.toString())
224 params = this.buildAdminParamsFromSearch(search, params)
228 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
230 switchMap(res => this.extractVideos(res)),
231 catchError(err => this.restExtractor.handleError(err))
235 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
236 let params = new HttpParams()
237 params = this.buildCommonVideosParams({ params, ...parameters })
240 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
242 switchMap(res => this.extractVideos(res)),
243 catchError(err => this.restExtractor.handleError(err))
247 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
250 format: FeedFormat.RSS,
251 label: 'media rss 2.0',
252 url: base + FeedFormat.RSS.toLowerCase()
255 format: FeedFormat.ATOM,
257 url: base + FeedFormat.ATOM.toLowerCase()
260 format: FeedFormat.JSON,
262 url: base + FeedFormat.JSON.toLowerCase()
266 if (params && params.keys().length !== 0) {
267 for (const feed of feeds) {
268 feed.url += '?' + params.toString()
275 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
276 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
278 if (isLocal) params = params.set('isLocal', isLocal)
281 for (const c of categoryOneOf) {
282 params = params.append('categoryOneOf[]', c + '')
286 return this.buildBaseFeedUrls(params)
289 getAccountFeedUrls (accountId: number) {
290 let params = this.restService.addRestGetParams(new HttpParams())
291 params = params.set('accountId', accountId.toString())
293 return this.buildBaseFeedUrls(params)
296 getVideoChannelFeedUrls (videoChannelId: number) {
297 let params = this.restService.addRestGetParams(new HttpParams())
298 params = params.set('videoChannelId', videoChannelId.toString())
300 return this.buildBaseFeedUrls(params)
303 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
304 let params = this.restService.addRestGetParams(new HttpParams())
305 params = params.set('accountId', accountId.toString())
306 params = params.set('token', feedToken)
308 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
311 getVideoFileMetadata (metadataUrl: string) {
313 .get<VideoFileMetadata>(metadataUrl)
315 catchError(err => this.restExtractor.handleError(err))
319 removeVideo (idArg: number | number[]) {
320 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
324 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + id)),
326 catchError(err => this.restExtractor.handleError(err))
330 loadCompleteDescription (descriptionPath: string) {
332 .get<{ description: string }>(environment.apiUrl + descriptionPath)
334 map(res => res.description),
335 catchError(err => this.restExtractor.handleError(err))
339 setVideoLike (id: number) {
340 return this.setVideoRate(id, 'like')
343 setVideoDislike (id: number) {
344 return this.setVideoRate(id, 'dislike')
347 unsetVideoLike (id: number) {
348 return this.setVideoRate(id, 'none')
351 getUserVideoRating (id: number) {
352 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
354 return this.authHttp.get<UserVideoRate>(url)
355 .pipe(catchError(err => this.restExtractor.handleError(err)))
358 extractVideos (result: ResultList<VideoServerModel>) {
359 return this.serverService.getServerLocale()
361 map(translations => {
362 const videosJson = result.data
363 const totalVideos = result.total
364 const videos: Video[] = []
366 for (const videoJson of videosJson) {
367 videos.push(new Video(videoJson, translations))
370 return { total: totalVideos, data: videos }
375 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
376 const descriptions = {
377 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
378 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
379 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
380 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
383 const videoPrivacies = serverPrivacies.map(p => {
387 description: descriptions[p.id]
393 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
397 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
398 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
400 for (const privacy of order) {
401 if (serverPrivacies.find(p => p.id === privacy)) {
406 throw new Error('No highest privacy available')
409 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
410 return nsfwPolicy === 'do_not_list'
415 private setVideoRate (id: number, rateType: UserVideoRateType) {
416 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
417 const body: UserVideoRateUpdate = {
424 map(this.restExtractor.extractDataBool),
425 catchError(err => this.restExtractor.handleError(err))
429 private buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
444 const pagination = videoPagination
445 ? this.restService.componentToRestPagination(videoPagination)
448 let newParams = this.restService.addRestGetParams(params, pagination, sort)
450 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
452 if (isLocal) newParams = newParams.set('isLocal', isLocal)
453 if (include) newParams = newParams.set('include', include)
454 if (isLive) newParams = newParams.set('isLive', isLive)
455 if (nsfw) newParams = newParams.set('nsfw', nsfw)
456 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
457 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
458 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
463 private buildAdminParamsFromSearch (search: string, params: HttpParams) {
464 const filters = this.restService.parseQueryStringFilter(search, {
471 return this.restService.addObjectParams(params, filters)