]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/video/video.service.ts
Add video filters to common video pages
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / video / video.service.ts
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'
7 import {
8 BooleanBothQuery,
9 FeedFormat,
10 NSFWPolicyType,
11 ResultList,
12 UserVideoRate,
13 UserVideoRateType,
14 UserVideoRateUpdate,
15 Video as VideoServerModel,
16 VideoConstant,
17 VideoDetails as VideoDetailsServerModel,
18 VideoFileMetadata,
19 VideoFilter,
20 VideoPrivacy,
21 VideoSortField,
22 VideoUpdate
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'
31
32 export type CommonVideoParams = {
33 videoPagination: ComponentPaginationLight
34 sort: VideoSortField
35 filter?: VideoFilter
36 categoryOneOf?: number[]
37 languageOneOf?: string[]
38 isLive?: boolean
39 skipCount?: boolean
40 // FIXME: remove?
41 nsfwPolicy?: NSFWPolicyType
42 nsfw?: BooleanBothQuery
43 }
44
45 @Injectable()
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.'
50
51 constructor (
52 private authHttp: HttpClient,
53 private restExtractor: RestExtractor,
54 private restService: RestService,
55 private serverService: ServerService
56 ) {}
57
58 getVideoViewUrl (uuid: string) {
59 return VideoService.BASE_VIDEO_URL + uuid + '/views'
60 }
61
62 getUserWatchingVideoUrl (uuid: string) {
63 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
64 }
65
66 getVideo (options: { videoId: string }): Observable<VideoDetails> {
67 return this.serverService.getServerLocale()
68 .pipe(
69 switchMap(translations => {
70 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
71 .pipe(map(videoHash => ({ videoHash, translations })))
72 }),
73 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
74 catchError(err => this.restExtractor.handleError(err))
75 )
76 }
77
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
86
87 const body: VideoUpdate = {
88 name: video.name,
89 category,
90 licence,
91 language,
92 support,
93 description,
94 channelId: video.channelId,
95 privacy: video.privacy,
96 tags: video.tags,
97 nsfw: video.nsfw,
98 waitTranscoding: video.waitTranscoding,
99 commentsEnabled: video.commentsEnabled,
100 downloadEnabled: video.downloadEnabled,
101 thumbnailfile: video.thumbnailfile,
102 previewfile: video.previewfile,
103 pluginData: video.pluginData,
104 scheduleUpdate,
105 originallyPublishedAt
106 }
107
108 const data = objectToFormData(body)
109
110 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
111 .pipe(
112 map(this.restExtractor.extractDataBool),
113 catchError(err => this.restExtractor.handleError(err))
114 )
115 }
116
117 uploadVideo (video: FormData) {
118 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
119
120 return this.authHttp
121 .request<{ video: { id: number, uuid: string } }>(req)
122 .pipe(catchError(err => this.restExtractor.handleError(err)))
123 }
124
125 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
126 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
127
128 let params = new HttpParams()
129 params = this.restService.addRestGetParams(params, pagination, sort)
130
131 if (search) {
132 const filters = this.restService.parseQueryStringFilter(search, {
133 isLive: {
134 prefix: 'isLive:',
135 isBoolean: true
136 }
137 })
138
139 params = this.restService.addObjectParams(params, filters)
140 }
141
142 return this.authHttp
143 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
144 .pipe(
145 switchMap(res => this.extractVideos(res)),
146 catchError(err => this.restExtractor.handleError(err))
147 )
148 }
149
150 getAccountVideos (parameters: CommonVideoParams & {
151 account: Pick<Account, 'nameWithHost'>
152 search?: string
153 }): Observable<ResultList<Video>> {
154 const { account, search } = parameters
155
156 let params = new HttpParams()
157 params = this.buildCommonVideosParams({ params, ...parameters })
158
159 if (search) params = params.set('search', search)
160
161 return this.authHttp
162 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
163 .pipe(
164 switchMap(res => this.extractVideos(res)),
165 catchError(err => this.restExtractor.handleError(err))
166 )
167 }
168
169 getVideoChannelVideos (parameters: CommonVideoParams & {
170 videoChannel: Pick<VideoChannel, 'nameWithHost'>
171 }): Observable<ResultList<Video>> {
172 const { videoChannel } = parameters
173
174 let params = new HttpParams()
175 params = this.buildCommonVideosParams({ params, ...parameters })
176
177 return this.authHttp
178 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
179 .pipe(
180 switchMap(res => this.extractVideos(res)),
181 catchError(err => this.restExtractor.handleError(err))
182 )
183 }
184
185 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
186 let params = new HttpParams()
187 params = this.buildCommonVideosParams({ params, ...parameters })
188
189 return this.authHttp
190 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
191 .pipe(
192 switchMap(res => this.extractVideos(res)),
193 catchError(err => this.restExtractor.handleError(err))
194 )
195 }
196
197 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
198 const feeds = [
199 {
200 format: FeedFormat.RSS,
201 label: 'media rss 2.0',
202 url: base + FeedFormat.RSS.toLowerCase()
203 },
204 {
205 format: FeedFormat.ATOM,
206 label: 'atom 1.0',
207 url: base + FeedFormat.ATOM.toLowerCase()
208 },
209 {
210 format: FeedFormat.JSON,
211 label: 'json 1.0',
212 url: base + FeedFormat.JSON.toLowerCase()
213 }
214 ]
215
216 if (params && params.keys().length !== 0) {
217 for (const feed of feeds) {
218 feed.url += '?' + params.toString()
219 }
220 }
221
222 return feeds
223 }
224
225 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number[]) {
226 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
227
228 if (filter) params = params.set('filter', filter)
229
230 if (categoryOneOf) {
231 for (const c of categoryOneOf) {
232 params = params.append('categoryOneOf[]', c + '')
233 }
234 }
235
236 return this.buildBaseFeedUrls(params)
237 }
238
239 getAccountFeedUrls (accountId: number) {
240 let params = this.restService.addRestGetParams(new HttpParams())
241 params = params.set('accountId', accountId.toString())
242
243 return this.buildBaseFeedUrls(params)
244 }
245
246 getVideoChannelFeedUrls (videoChannelId: number) {
247 let params = this.restService.addRestGetParams(new HttpParams())
248 params = params.set('videoChannelId', videoChannelId.toString())
249
250 return this.buildBaseFeedUrls(params)
251 }
252
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)
257
258 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
259 }
260
261 getVideoFileMetadata (metadataUrl: string) {
262 return this.authHttp
263 .get<VideoFileMetadata>(metadataUrl)
264 .pipe(
265 catchError(err => this.restExtractor.handleError(err))
266 )
267 }
268
269 removeVideo (id: number) {
270 return this.authHttp
271 .delete(VideoService.BASE_VIDEO_URL + id)
272 .pipe(
273 map(this.restExtractor.extractDataBool),
274 catchError(err => this.restExtractor.handleError(err))
275 )
276 }
277
278 loadCompleteDescription (descriptionPath: string) {
279 return this.authHttp
280 .get<{ description: string }>(environment.apiUrl + descriptionPath)
281 .pipe(
282 map(res => res.description),
283 catchError(err => this.restExtractor.handleError(err))
284 )
285 }
286
287 setVideoLike (id: number) {
288 return this.setVideoRate(id, 'like')
289 }
290
291 setVideoDislike (id: number) {
292 return this.setVideoRate(id, 'dislike')
293 }
294
295 unsetVideoLike (id: number) {
296 return this.setVideoRate(id, 'none')
297 }
298
299 getUserVideoRating (id: number) {
300 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
301
302 return this.authHttp.get<UserVideoRate>(url)
303 .pipe(catchError(err => this.restExtractor.handleError(err)))
304 }
305
306 extractVideos (result: ResultList<VideoServerModel>) {
307 return this.serverService.getServerLocale()
308 .pipe(
309 map(translations => {
310 const videosJson = result.data
311 const totalVideos = result.total
312 const videos: Video[] = []
313
314 for (const videoJson of videosJson) {
315 videos.push(new Video(videoJson, translations))
316 }
317
318 return { total: totalVideos, data: videos }
319 })
320 )
321 }
322
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`
329 }
330
331 const videoPrivacies = serverPrivacies.map(p => {
332 return {
333 ...p,
334
335 description: descriptions[p.id]
336 }
337 })
338
339 return {
340 videoPrivacies,
341 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
342 }
343 }
344
345 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
346 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
347
348 for (const privacy of order) {
349 if (serverPrivacies.find(p => p.id === privacy)) {
350 return privacy
351 }
352 }
353
354 throw new Error('No highest privacy available')
355 }
356
357 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
358 return nsfwPolicy === 'do_not_list'
359 ? 'false'
360 : 'both'
361 }
362
363 private setVideoRate (id: number, rateType: UserVideoRateType) {
364 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
365 const body: UserVideoRateUpdate = {
366 rating: rateType
367 }
368
369 return this.authHttp
370 .put(url, body)
371 .pipe(
372 map(this.restExtractor.extractDataBool),
373 catchError(err => this.restExtractor.handleError(err))
374 )
375 }
376
377 private buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
378 const { params, videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy, isLive, nsfw } = options
379
380 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
381 let newParams = this.restService.addRestGetParams(params, pagination, sort)
382
383 if (filter) newParams = newParams.set('filter', filter)
384 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
385
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)
391
392 return newParams
393 }
394 }