1 import { Observable } from 'rxjs'
2 import { catchError, map, switchMap } from 'rxjs/operators'
3 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core'
6 import { objectToFormData } from '@app/helpers'
15 Video as VideoServerModel,
16 VideoChannel as VideoChannelServerModel,
18 VideoDetails as VideoDetailsServerModel,
24 } from '@shared/models'
25 import { environment } from '../../../../environments/environment'
26 import { Account } from '../account/account.model'
27 import { AccountService } from '../account/account.service'
28 import { VideoChannel, VideoChannelService } from '../video-channel'
29 import { VideoDetails } from './video-details.model'
30 import { VideoEdit } from './video-edit.model'
31 import { Video } from './video.model'
33 export type CommonVideoParams = {
34 videoPagination: ComponentPaginationLight
37 categoryOneOf?: number[]
38 languageOneOf?: string[]
42 nsfwPolicy?: NSFWPolicyType
43 nsfw?: BooleanBothQuery
47 export class VideoService {
48 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
49 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
50 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
53 private authHttp: HttpClient,
54 private restExtractor: RestExtractor,
55 private restService: RestService,
56 private serverService: ServerService
59 getVideoViewUrl (uuid: string) {
60 return VideoService.BASE_VIDEO_URL + uuid + '/views'
63 getUserWatchingVideoUrl (uuid: string) {
64 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
67 getVideo (options: { videoId: string }): Observable<VideoDetails> {
68 return this.serverService.getServerLocale()
70 switchMap(translations => {
71 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
72 .pipe(map(videoHash => ({ videoHash, translations })))
74 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
75 catchError(err => this.restExtractor.handleError(err))
79 updateVideo (video: VideoEdit) {
80 const language = video.language || null
81 const licence = video.licence || null
82 const category = video.category || null
83 const description = video.description || null
84 const support = video.support || null
85 const scheduleUpdate = video.scheduleUpdate || null
86 const originallyPublishedAt = video.originallyPublishedAt || null
88 const body: VideoUpdate = {
95 channelId: video.channelId,
96 privacy: video.privacy,
99 waitTranscoding: video.waitTranscoding,
100 commentsEnabled: video.commentsEnabled,
101 downloadEnabled: video.downloadEnabled,
102 thumbnailfile: video.thumbnailfile,
103 previewfile: video.previewfile,
104 pluginData: video.pluginData,
106 originallyPublishedAt
109 const data = objectToFormData(body)
111 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
113 map(this.restExtractor.extractDataBool),
114 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, filter?: VideoFilter, categoryOneOf?: number[]) {
244 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
246 if (filter) params = params.set('filter', filter)
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 (id: number) {
289 .delete(VideoService.BASE_VIDEO_URL + id)
291 map(this.restExtractor.extractDataBool),
292 catchError(err => this.restExtractor.handleError(err))
296 loadCompleteDescription (descriptionPath: string) {
298 .get<{ description: string }>(environment.apiUrl + descriptionPath)
300 map(res => res.description),
301 catchError(err => this.restExtractor.handleError(err))
305 setVideoLike (id: number) {
306 return this.setVideoRate(id, 'like')
309 setVideoDislike (id: number) {
310 return this.setVideoRate(id, 'dislike')
313 unsetVideoLike (id: number) {
314 return this.setVideoRate(id, 'none')
317 getUserVideoRating (id: number) {
318 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
320 return this.authHttp.get<UserVideoRate>(url)
321 .pipe(catchError(err => this.restExtractor.handleError(err)))
324 extractVideos (result: ResultList<VideoServerModel>) {
325 return this.serverService.getServerLocale()
327 map(translations => {
328 const videosJson = result.data
329 const totalVideos = result.total
330 const videos: Video[] = []
332 for (const videoJson of videosJson) {
333 videos.push(new Video(videoJson, translations))
336 return { total: totalVideos, data: videos }
341 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
342 const descriptions = {
343 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
344 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
345 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
346 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
349 const videoPrivacies = serverPrivacies.map(p => {
353 description: descriptions[p.id]
359 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
363 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
364 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
366 for (const privacy of order) {
367 if (serverPrivacies.find(p => p.id === privacy)) {
372 throw new Error('No highest privacy available')
375 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
376 return nsfwPolicy === 'do_not_list'
381 private setVideoRate (id: number, rateType: UserVideoRateType) {
382 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
383 const body: UserVideoRateUpdate = {
390 map(this.restExtractor.extractDataBool),
391 catchError(err => this.restExtractor.handleError(err))
395 private buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
396 const { params, videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy, isLive, nsfw } = options
398 const pagination = this.restService.componentToRestPagination(videoPagination)
399 let newParams = this.restService.addRestGetParams(params, pagination, sort)
401 if (filter) newParams = newParams.set('filter', filter)
402 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
404 if (isLive) newParams = newParams.set('isLive', isLive)
405 if (nsfw) newParams = newParams.set('nsfw', nsfw)
406 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
407 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
408 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)