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