1 import { catchError, map, switchMap } from 'rxjs/operators'
2 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
3 import { Injectable } from '@angular/core'
4 import { Observable } from 'rxjs'
5 import { Video as VideoServerModel, VideoDetails as VideoDetailsServerModel } from '../../../../../shared'
6 import { ResultList } from '../../../../../shared/models/result-list.model'
15 } from '../../../../../shared/models/videos'
16 import { FeedFormat } from '../../../../../shared/models/feeds/feed-format.enum'
17 import { environment } from '../../../environments/environment'
18 import { ComponentPaginationLight } from '../rest/component-pagination.model'
19 import { RestExtractor } from '../rest/rest-extractor.service'
20 import { RestService } from '../rest/rest.service'
21 import { UserService } from '../users/user.service'
22 import { VideoSortField } from './sort-field.type'
23 import { VideoDetails } from './video-details.model'
24 import { VideoEdit } from './video-edit.model'
25 import { Video } from './video.model'
26 import { objectToFormData } from '@app/shared/misc/utils'
27 import { Account } from '@app/shared/account/account.model'
28 import { AccountService } from '@app/shared/account/account.service'
29 import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
30 import { ServerService, AuthService } from '@app/core'
31 import { UserSubscriptionService } from '@app/shared/user-subscription/user-subscription.service'
32 import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
33 import { I18n } from '@ngx-translate/i18n-polyfill'
34 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
35 import { FfprobeData } from 'fluent-ffmpeg'
37 export interface VideosProvider {
38 getVideos (parameters: {
39 videoPagination: ComponentPaginationLight,
42 categoryOneOf?: number,
43 languageOneOf?: string[]
44 }): Observable<ResultList<Video>>
48 export class VideoService implements VideosProvider {
49 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
50 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
53 private authHttp: HttpClient,
54 private authService: AuthService,
55 private userService: UserService,
56 private restExtractor: RestExtractor,
57 private restService: RestService,
58 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,
108 originallyPublishedAt
111 const data = objectToFormData(body)
113 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
115 map(this.restExtractor.extractDataBool),
116 catchError(err => this.restExtractor.handleError(err))
120 uploadVideo (video: FormData) {
121 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
124 .request<{ video: { id: number, uuid: string } }>(req)
125 .pipe(catchError(err => this.restExtractor.handleError(err)))
128 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
129 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
131 let params = new HttpParams()
132 params = this.restService.addRestGetParams(params, pagination, sort)
133 params = this.restService.addObjectParams(params, { search })
136 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
138 switchMap(res => this.extractVideos(res)),
139 catchError(err => this.restExtractor.handleError(err))
145 videoPagination: ComponentPaginationLight,
147 ): Observable<ResultList<Video>> {
148 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
150 let params = new HttpParams()
151 params = this.restService.addRestGetParams(params, pagination, sort)
154 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
156 switchMap(res => this.extractVideos(res)),
157 catchError(err => this.restExtractor.handleError(err))
161 getVideoChannelVideos (
162 videoChannel: VideoChannel,
163 videoPagination: ComponentPaginationLight,
165 ): Observable<ResultList<Video>> {
166 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
168 let params = new HttpParams()
169 params = this.restService.addRestGetParams(params, pagination, sort)
172 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
174 switchMap(res => this.extractVideos(res)),
175 catchError(err => this.restExtractor.handleError(err))
179 getUserSubscriptionVideos (parameters: {
180 videoPagination: ComponentPaginationLight,
181 sort: VideoSortField,
183 }): Observable<ResultList<Video>> {
184 const { videoPagination, sort, skipCount } = parameters
185 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
187 let params = new HttpParams()
188 params = this.restService.addRestGetParams(params, pagination, sort)
190 if (skipCount) params = params.set('skipCount', skipCount + '')
193 .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
195 switchMap(res => this.extractVideos(res)),
196 catchError(err => this.restExtractor.handleError(err))
200 getVideos (parameters: {
201 videoPagination: ComponentPaginationLight,
202 sort: VideoSortField,
203 filter?: VideoFilter,
204 categoryOneOf?: number,
205 languageOneOf?: string[],
208 }): Observable<ResultList<Video>> {
209 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfw } = parameters
211 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
213 let params = new HttpParams()
214 params = this.restService.addRestGetParams(params, pagination, sort)
216 if (filter) params = params.set('filter', filter)
217 if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
218 if (skipCount) params = params.set('skipCount', skipCount + '')
221 params = params.set('nsfw', nsfw + '')
223 const nsfwPolicy = this.authService.isLoggedIn()
224 ? this.authService.getUser().nsfwPolicy
225 : this.userService.getAnonymousUser().nsfwPolicy
226 if (this.nsfwPolicyToFilter(nsfwPolicy)) params.set('nsfw', 'false')
230 for (const l of languageOneOf) {
231 params = params.append('languageOneOf[]', l)
236 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
238 switchMap(res => this.extractVideos(res)),
239 catchError(err => this.restExtractor.handleError(err))
243 buildBaseFeedUrls (params: HttpParams) {
246 format: FeedFormat.RSS,
248 url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
251 format: FeedFormat.ATOM,
253 url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
256 format: FeedFormat.JSON,
258 url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
262 if (params && params.keys().length !== 0) {
263 for (const feed of feeds) {
264 feed.url += '?' + params.toString()
271 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number) {
272 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
274 if (filter) params = params.set('filter', filter)
276 if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
278 return this.buildBaseFeedUrls(params)
281 getAccountFeedUrls (accountId: number) {
282 let params = this.restService.addRestGetParams(new HttpParams())
283 params = params.set('accountId', accountId.toString())
285 return this.buildBaseFeedUrls(params)
288 getVideoChannelFeedUrls (videoChannelId: number) {
289 let params = this.restService.addRestGetParams(new HttpParams())
290 params = params.set('videoChannelId', videoChannelId.toString())
292 return this.buildBaseFeedUrls(params)
295 getVideoFileMetadata (metadataUrl: string) {
297 .get<FfprobeData>(metadataUrl)
299 catchError(err => this.restExtractor.handleError(err))
303 removeVideo (id: number) {
305 .delete(VideoService.BASE_VIDEO_URL + id)
307 map(this.restExtractor.extractDataBool),
308 catchError(err => this.restExtractor.handleError(err))
312 loadCompleteDescription (descriptionPath: string) {
314 .get<{ description: string }>(environment.apiUrl + descriptionPath)
316 map(res => res.description),
317 catchError(err => this.restExtractor.handleError(err))
321 setVideoLike (id: number) {
322 return this.setVideoRate(id, 'like')
325 setVideoDislike (id: number) {
326 return this.setVideoRate(id, 'dislike')
329 unsetVideoLike (id: number) {
330 return this.setVideoRate(id, 'none')
333 getUserVideoRating (id: number) {
334 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
336 return this.authHttp.get<UserVideoRate>(url)
337 .pipe(catchError(err => this.restExtractor.handleError(err)))
340 extractVideos (result: ResultList<VideoServerModel>) {
341 return this.serverService.getServerLocale()
343 map(translations => {
344 const videosJson = result.data
345 const totalVideos = result.total
346 const videos: Video[] = []
348 for (const videoJson of videosJson) {
349 videos.push(new Video(videoJson, translations))
352 return { total: totalVideos, data: videos }
357 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
360 id: VideoPrivacy.PRIVATE,
361 label: this.i18n('Only I can see this video')
364 id: VideoPrivacy.UNLISTED,
365 label: this.i18n('Only people with the private link can see this video')
368 id: VideoPrivacy.PUBLIC,
369 label: this.i18n('Anyone can see this video')
372 id: VideoPrivacy.INTERNAL,
373 label: this.i18n('Only users of this instance can see this video')
377 return base.filter(o => !!privacies.find(p => p.id === o.id))
380 private setVideoRate (id: number, rateType: UserVideoRateType) {
381 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
382 const body: UserVideoRateUpdate = {
389 map(this.restExtractor.extractDataBool),
390 catchError(err => this.restExtractor.handleError(err))
394 private nsfwPolicyToFilter (policy: NSFWPolicyType) {
395 return policy === 'do_not_list'