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,
17 VideoDetails as VideoDetailsServerModel,
23 } from '@shared/models'
24 import { environment } from '../../../../environments/environment'
25 import { Account } from '../account/account.model'
26 import { AccountService } from '../account/account.service'
27 import { VideoChannel, VideoChannelService } from '../video-channel'
28 import { VideoDetails } from './video-details.model'
29 import { VideoEdit } from './video-edit.model'
30 import { Video } from './video.model'
32 export type CommonVideoParams = {
33 videoPagination: ComponentPaginationLight
36 categoryOneOf?: number[]
37 languageOneOf?: string[]
41 nsfwPolicy?: NSFWPolicyType
42 nsfw?: BooleanBothQuery
46 export class VideoService {
47 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
48 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
49 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
52 private authHttp: HttpClient,
53 private restExtractor: RestExtractor,
54 private restService: RestService,
55 private serverService: ServerService
58 getVideoViewUrl (uuid: string) {
59 return VideoService.BASE_VIDEO_URL + uuid + '/views'
62 getUserWatchingVideoUrl (uuid: string) {
63 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
66 getVideo (options: { videoId: string }): Observable<VideoDetails> {
67 return this.serverService.getServerLocale()
69 switchMap(translations => {
70 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
71 .pipe(map(videoHash => ({ videoHash, translations })))
73 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
74 catchError(err => this.restExtractor.handleError(err))
78 updateVideo (video: VideoEdit) {
79 const language = video.language || null
80 const licence = video.licence || null
81 const category = video.category || null
82 const description = video.description || null
83 const support = video.support || null
84 const scheduleUpdate = video.scheduleUpdate || null
85 const originallyPublishedAt = video.originallyPublishedAt || null
87 const body: VideoUpdate = {
94 channelId: video.channelId,
95 privacy: video.privacy,
98 waitTranscoding: video.waitTranscoding,
99 commentsEnabled: video.commentsEnabled,
100 downloadEnabled: video.downloadEnabled,
101 thumbnailfile: video.thumbnailfile,
102 previewfile: video.previewfile,
103 pluginData: video.pluginData,
105 originallyPublishedAt
108 const data = objectToFormData(body)
110 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
112 map(this.restExtractor.extractDataBool),
113 catchError(err => this.restExtractor.handleError(err))
117 uploadVideo (video: FormData) {
118 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
121 .request<{ video: { id: number, uuid: string } }>(req)
122 .pipe(catchError(err => this.restExtractor.handleError(err)))
125 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
126 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
128 let params = new HttpParams()
129 params = this.restService.addRestGetParams(params, pagination, sort)
132 const filters = this.restService.parseQueryStringFilter(search, {
139 params = this.restService.addObjectParams(params, filters)
143 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
145 switchMap(res => this.extractVideos(res)),
146 catchError(err => this.restExtractor.handleError(err))
150 getAccountVideos (parameters: CommonVideoParams & {
151 account: Pick<Account, 'nameWithHost'>
153 }): Observable<ResultList<Video>> {
154 const { account, search } = parameters
156 let params = new HttpParams()
157 params = this.buildCommonVideosParams({ params, ...parameters })
159 if (search) params = params.set('search', search)
162 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
164 switchMap(res => this.extractVideos(res)),
165 catchError(err => this.restExtractor.handleError(err))
169 getVideoChannelVideos (parameters: CommonVideoParams & {
170 videoChannel: Pick<VideoChannel, 'nameWithHost'>
171 }): Observable<ResultList<Video>> {
172 const { videoChannel } = parameters
174 let params = new HttpParams()
175 params = this.buildCommonVideosParams({ params, ...parameters })
178 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
180 switchMap(res => this.extractVideos(res)),
181 catchError(err => this.restExtractor.handleError(err))
185 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
186 let params = new HttpParams()
187 params = this.buildCommonVideosParams({ params, ...parameters })
190 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
192 switchMap(res => this.extractVideos(res)),
193 catchError(err => this.restExtractor.handleError(err))
197 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
200 format: FeedFormat.RSS,
201 label: 'media rss 2.0',
202 url: base + FeedFormat.RSS.toLowerCase()
205 format: FeedFormat.ATOM,
207 url: base + FeedFormat.ATOM.toLowerCase()
210 format: FeedFormat.JSON,
212 url: base + FeedFormat.JSON.toLowerCase()
216 if (params && params.keys().length !== 0) {
217 for (const feed of feeds) {
218 feed.url += '?' + params.toString()
225 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
226 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
228 if (filter) params = params.set('filter', filter)
231 for (const c of categoryOneOf) {
232 params = params.append('categoryOneOf[]', c + '')
236 return this.buildBaseFeedUrls(params)
239 getAccountFeedUrls (accountId: number) {
240 let params = this.restService.addRestGetParams(new HttpParams())
241 params = params.set('accountId', accountId.toString())
243 return this.buildBaseFeedUrls(params)
246 getVideoChannelFeedUrls (videoChannelId: number) {
247 let params = this.restService.addRestGetParams(new HttpParams())
248 params = params.set('videoChannelId', videoChannelId.toString())
250 return this.buildBaseFeedUrls(params)
253 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
254 let params = this.restService.addRestGetParams(new HttpParams())
255 params = params.set('accountId', accountId.toString())
256 params = params.set('token', feedToken)
258 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
261 getVideoFileMetadata (metadataUrl: string) {
263 .get<VideoFileMetadata>(metadataUrl)
265 catchError(err => this.restExtractor.handleError(err))
269 removeVideo (id: number) {
271 .delete(VideoService.BASE_VIDEO_URL + id)
273 map(this.restExtractor.extractDataBool),
274 catchError(err => this.restExtractor.handleError(err))
278 loadCompleteDescription (descriptionPath: string) {
280 .get<{ description: string }>(environment.apiUrl + descriptionPath)
282 map(res => res.description),
283 catchError(err => this.restExtractor.handleError(err))
287 setVideoLike (id: number) {
288 return this.setVideoRate(id, 'like')
291 setVideoDislike (id: number) {
292 return this.setVideoRate(id, 'dislike')
295 unsetVideoLike (id: number) {
296 return this.setVideoRate(id, 'none')
299 getUserVideoRating (id: number) {
300 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
302 return this.authHttp.get<UserVideoRate>(url)
303 .pipe(catchError(err => this.restExtractor.handleError(err)))
306 extractVideos (result: ResultList<VideoServerModel>) {
307 return this.serverService.getServerLocale()
309 map(translations => {
310 const videosJson = result.data
311 const totalVideos = result.total
312 const videos: Video[] = []
314 for (const videoJson of videosJson) {
315 videos.push(new Video(videoJson, translations))
318 return { total: totalVideos, data: videos }
323 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
324 const descriptions = {
325 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
326 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
327 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
328 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
331 const videoPrivacies = serverPrivacies.map(p => {
335 description: descriptions[p.id]
341 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
345 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
346 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
348 for (const privacy of order) {
349 if (serverPrivacies.find(p => p.id === privacy)) {
354 throw new Error('No highest privacy available')
357 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
358 return nsfwPolicy === 'do_not_list'
363 private setVideoRate (id: number, rateType: UserVideoRateType) {
364 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
365 const body: UserVideoRateUpdate = {
372 map(this.restExtractor.extractDataBool),
373 catchError(err => this.restExtractor.handleError(err))
377 private buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
378 const { params, videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy, isLive, nsfw } = options
380 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
381 let newParams = this.restService.addRestGetParams(params, pagination, sort)
383 if (filter) newParams = newParams.set('filter', filter)
384 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
386 if (isLive) newParams = newParams.set('isLive', isLive)
387 if (nsfw) newParams = newParams.set('nsfw', nsfw)
388 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
389 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
390 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)