1 import { SortMeta } from 'primeng/api'
2 import { from, Observable, of } 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 { AuthService, ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core'
7 import { objectToFormData } from '@app/helpers'
8 import { arrayify } from '@shared/core-utils'
17 Video as VideoServerModel,
18 VideoChannel as VideoChannelServerModel,
20 VideoDetails as VideoDetailsServerModel,
25 VideoTranscodingCreate,
27 } from '@shared/models'
28 import { VideoSource } from '@shared/models/videos/video-source'
29 import { environment } from '../../../../environments/environment'
30 import { Account } from '../account/account.model'
31 import { AccountService } from '../account/account.service'
32 import { VideoChannel, VideoChannelService } from '../video-channel'
33 import { VideoDetails } from './video-details.model'
34 import { VideoEdit } from './video-edit.model'
35 import { Video } from './video.model'
37 export type CommonVideoParams = {
38 videoPagination?: ComponentPaginationLight
39 sort: VideoSortField | SortMeta
40 include?: VideoInclude
42 categoryOneOf?: number[]
43 languageOneOf?: string[]
44 privacyOneOf?: VideoPrivacy[]
49 nsfwPolicy?: NSFWPolicyType
50 nsfw?: BooleanBothQuery
54 export class VideoService {
55 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
56 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
57 static PODCAST_FEEDS_URL = environment.apiUrl + '/feeds/podcast/videos.xml'
58 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
61 private auth: AuthService,
62 private authHttp: HttpClient,
63 private restExtractor: RestExtractor,
64 private restService: RestService,
65 private serverService: ServerService
68 getVideoViewUrl (uuid: string) {
69 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
72 getVideo (options: { videoId: string }): Observable<VideoDetails> {
73 return this.serverService.getServerLocale()
75 switchMap(translations => {
76 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
77 .pipe(map(videoHash => ({ videoHash, translations })))
79 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
80 catchError(err => this.restExtractor.handleError(err))
84 updateVideo (video: VideoEdit) {
85 const language = video.language || null
86 const licence = video.licence || null
87 const category = video.category || null
88 const description = video.description || null
89 const support = video.support || null
90 const scheduleUpdate = video.scheduleUpdate || null
91 const originallyPublishedAt = video.originallyPublishedAt || null
93 const body: VideoUpdate = {
100 channelId: video.channelId,
101 privacy: video.privacy,
104 waitTranscoding: video.waitTranscoding,
105 commentsEnabled: video.commentsEnabled,
106 downloadEnabled: video.downloadEnabled,
107 thumbnailfile: video.thumbnailfile,
108 previewfile: video.previewfile,
109 pluginData: video.pluginData,
111 originallyPublishedAt
114 const data = objectToFormData(body)
116 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
117 .pipe(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 (options: {
129 videoPagination: ComponentPaginationLight
131 userChannels?: VideoChannelServerModel[]
133 }): Observable<ResultList<Video>> {
134 const { videoPagination, sort, userChannels = [], search } = options
136 const pagination = this.restService.componentToRestPagination(videoPagination)
138 let params = new HttpParams()
139 params = this.restService.addRestGetParams(params, pagination, sort)
142 const filters = this.restService.parseQueryStringFilter(search, {
149 handler: (name: string) => {
150 const channel = userChannels.find(c => c.name === name)
152 if (channel) return channel.id
159 params = this.restService.addObjectParams(params, filters)
163 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
165 switchMap(res => this.extractVideos(res)),
166 catchError(err => this.restExtractor.handleError(err))
170 getAccountVideos (parameters: CommonVideoParams & {
171 account: Pick<Account, 'nameWithHost'>
173 }): Observable<ResultList<Video>> {
174 const { account, search } = parameters
176 let params = new HttpParams()
177 params = this.buildCommonVideosParams({ params, ...parameters })
179 if (search) params = params.set('search', search)
182 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
184 switchMap(res => this.extractVideos(res)),
185 catchError(err => this.restExtractor.handleError(err))
189 getVideoChannelVideos (parameters: CommonVideoParams & {
190 videoChannel: Pick<VideoChannel, 'nameWithHost'>
191 }): Observable<ResultList<Video>> {
192 const { videoChannel } = parameters
194 let params = new HttpParams()
195 params = this.buildCommonVideosParams({ params, ...parameters })
198 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
200 switchMap(res => this.extractVideos(res)),
201 catchError(err => this.restExtractor.handleError(err))
205 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
206 let params = new HttpParams()
207 params = this.buildCommonVideosParams({ params, ...parameters })
210 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
212 switchMap(res => this.extractVideos(res)),
213 catchError(err => this.restExtractor.handleError(err))
217 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
220 format: FeedFormat.RSS,
221 label: 'media rss 2.0',
222 url: base + FeedFormat.RSS.toLowerCase()
225 format: FeedFormat.ATOM,
227 url: base + FeedFormat.ATOM.toLowerCase()
230 format: FeedFormat.JSON,
232 url: base + FeedFormat.JSON.toLowerCase()
236 if (params && params.keys().length !== 0) {
237 for (const feed of feeds) {
238 feed.url += '?' + params.toString()
245 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
246 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
248 if (isLocal) params = params.set('isLocal', isLocal)
251 for (const c of categoryOneOf) {
252 params = params.append('categoryOneOf[]', c + '')
256 return this.buildBaseFeedUrls(params)
259 getAccountFeedUrls (accountId: number) {
260 let params = this.restService.addRestGetParams(new HttpParams())
261 params = params.set('accountId', accountId.toString())
263 return this.buildBaseFeedUrls(params)
266 getVideoChannelFeedUrls (videoChannelId: number) {
267 let params = this.restService.addRestGetParams(new HttpParams())
268 params = params.set('videoChannelId', videoChannelId.toString())
270 const feedUrls = this.buildBaseFeedUrls(params)
273 format: FeedFormat.RSS,
274 label: 'podcast rss 2.0',
275 url: VideoService.PODCAST_FEEDS_URL + `?videoChannelId=${videoChannelId}`
281 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
282 let params = this.restService.addRestGetParams(new HttpParams())
283 params = params.set('accountId', accountId.toString())
284 params = params.set('token', feedToken)
286 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
289 getVideoFileMetadata (metadataUrl: string) {
291 .get<VideoFileMetadata>(metadataUrl)
293 catchError(err => this.restExtractor.handleError(err))
297 removeVideo (idArg: number | number[]) {
298 const ids = arrayify(idArg)
302 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
304 catchError(err => this.restExtractor.handleError(err))
308 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
309 return from(videoIds)
311 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
313 catchError(err => this.restExtractor.handleError(err))
317 removeFile (videoId: number | string, fileId: number, type: 'hls' | 'webtorrent') {
318 return this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + videoId + '/' + type + '/' + fileId)
319 .pipe(catchError(err => this.restExtractor.handleError(err)))
322 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
323 const body: VideoTranscodingCreate = { transcodingType: type }
325 return from(videoIds)
327 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
329 catchError(err => this.restExtractor.handleError(err))
333 loadCompleteDescription (descriptionPath: string) {
335 .get<{ description: string }>(environment.apiUrl + descriptionPath)
337 map(res => res.description),
338 catchError(err => this.restExtractor.handleError(err))
342 getSource (videoId: number) {
344 .get<{ source: VideoSource }>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
347 if (err.status === 404) {
351 this.restExtractor.handleError(err)
356 setVideoLike (id: string) {
357 return this.setVideoRate(id, 'like')
360 setVideoDislike (id: string) {
361 return this.setVideoRate(id, 'dislike')
364 unsetVideoLike (id: string) {
365 return this.setVideoRate(id, 'none')
368 getUserVideoRating (id: string) {
369 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
371 return this.authHttp.get<UserVideoRate>(url)
372 .pipe(catchError(err => this.restExtractor.handleError(err)))
375 extractVideos (result: ResultList<VideoServerModel>) {
376 return this.serverService.getServerLocale()
378 map(translations => {
379 const videosJson = result.data
380 const totalVideos = result.total
381 const videos: Video[] = []
383 for (const videoJson of videosJson) {
384 videos.push(new Video(videoJson, translations))
387 return { total: totalVideos, data: videos }
392 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
393 const descriptions = {
394 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
395 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
396 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
397 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
400 const videoPrivacies = serverPrivacies.map(p => {
404 description: descriptions[p.id]
410 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
414 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
415 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
417 for (const privacy of order) {
418 if (serverPrivacies.find(p => p.id === privacy)) {
423 throw new Error('No highest privacy available')
426 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
427 return nsfwPolicy === 'do_not_list'
432 // Choose if we display by default the account or the channel
433 buildDefaultOwnerDisplayType (video: Video) {
434 const accountName = video.account.name
436 // If the video channel name is an UUID (not really displayable, we changed this behaviour in v1.0.0-beta.12)
437 // Or has not been customized (default created channel display name)
438 // -> Use the account name
440 video.channel.displayName === `Default ${accountName} channel` ||
441 video.channel.displayName === `Main ${accountName} channel` ||
442 video.channel.name.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
444 return 'account' as 'account'
447 return 'videoChannel' as 'videoChannel'
450 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
466 const pagination = videoPagination
467 ? this.restService.componentToRestPagination(videoPagination)
470 let newParams = this.restService.addRestGetParams(params, pagination, this.buildListSort(sort))
472 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
474 if (isLocal !== undefined) newParams = newParams.set('isLocal', isLocal)
475 if (include !== undefined) newParams = newParams.set('include', include)
476 if (isLive !== undefined) newParams = newParams.set('isLive', isLive)
477 if (nsfw !== undefined) newParams = newParams.set('nsfw', nsfw)
478 if (nsfwPolicy !== undefined) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
479 if (languageOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
480 if (categoryOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
481 if (privacyOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
486 private buildListSort (sortArg: VideoSortField | SortMeta) {
487 const sort = this.restService.buildSortString(sortArg)
489 if (typeof sort === 'string') {
490 // Silently use the best algorithm for logged in users if they chose the hot algorithm
492 this.auth.isLoggedIn() &&
493 (sort === 'hot' || sort === '-hot')
495 return sort.replace('hot', 'best')
502 private setVideoRate (id: string, rateType: UserVideoRateType) {
503 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
504 const body: UserVideoRateUpdate = {
510 .pipe(catchError(err => this.restExtractor.handleError(err)))