]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - client/src/app/shared/shared-main/video/video.service.ts
Correctly fix table column widths
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / video / video.service.ts
... / ...
CommitLineData
1import { SortMeta } from 'primeng/api'
2import { from, Observable, of } from 'rxjs'
3import { catchError, concatMap, map, switchMap, toArray } from 'rxjs/operators'
4import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
5import { Injectable } from '@angular/core'
6import { AuthService, ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core'
7import { objectToFormData } from '@app/helpers'
8import { arrayify } from '@shared/core-utils'
9import {
10 BooleanBothQuery,
11 FeedFormat,
12 NSFWPolicyType,
13 ResultList,
14 UserVideoRate,
15 UserVideoRateType,
16 UserVideoRateUpdate,
17 Video as VideoServerModel,
18 VideoChannel as VideoChannelServerModel,
19 VideoConstant,
20 VideoDetails as VideoDetailsServerModel,
21 VideoFileMetadata,
22 VideoInclude,
23 VideoPrivacy,
24 VideoSortField,
25 VideoTranscodingCreate,
26 VideoUpdate
27} from '@shared/models'
28import { VideoSource } from '@shared/models/videos/video-source'
29import { environment } from '../../../../environments/environment'
30import { Account } from '../account/account.model'
31import { AccountService } from '../account/account.service'
32import { VideoChannel, VideoChannelService } from '../video-channel'
33import { VideoDetails } from './video-details.model'
34import { VideoEdit } from './video-edit.model'
35import { Video } from './video.model'
36
37export type CommonVideoParams = {
38 videoPagination?: ComponentPaginationLight
39 sort: VideoSortField | SortMeta
40 include?: VideoInclude
41 isLocal?: boolean
42 categoryOneOf?: number[]
43 languageOneOf?: string[]
44 privacyOneOf?: VideoPrivacy[]
45 isLive?: boolean
46 skipCount?: boolean
47
48 // FIXME: remove?
49 nsfwPolicy?: NSFWPolicyType
50 nsfw?: BooleanBothQuery
51}
52
53@Injectable()
54export class VideoService {
55 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos'
56 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
57 static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.'
58
59 constructor (
60 private auth: AuthService,
61 private authHttp: HttpClient,
62 private restExtractor: RestExtractor,
63 private restService: RestService,
64 private serverService: ServerService
65 ) {}
66
67 getVideoViewUrl (uuid: string) {
68 return `${VideoService.BASE_VIDEO_URL}/${uuid}/views`
69 }
70
71 getVideo (options: { videoId: string }): Observable<VideoDetails> {
72 return this.serverService.getServerLocale()
73 .pipe(
74 switchMap(translations => {
75 return this.authHttp.get<VideoDetailsServerModel>(`${VideoService.BASE_VIDEO_URL}/${options.videoId}`)
76 .pipe(map(videoHash => ({ videoHash, translations })))
77 }),
78 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
79 catchError(err => this.restExtractor.handleError(err))
80 )
81 }
82
83 updateVideo (video: VideoEdit) {
84 const language = video.language || null
85 const licence = video.licence || null
86 const category = video.category || null
87 const description = video.description || null
88 const support = video.support || null
89 const scheduleUpdate = video.scheduleUpdate || null
90 const originallyPublishedAt = video.originallyPublishedAt || null
91
92 const body: VideoUpdate = {
93 name: video.name,
94 category,
95 licence,
96 language,
97 support,
98 description,
99 channelId: video.channelId,
100 privacy: video.privacy,
101 tags: video.tags,
102 nsfw: video.nsfw,
103 waitTranscoding: video.waitTranscoding,
104 commentsEnabled: video.commentsEnabled,
105 downloadEnabled: video.downloadEnabled,
106 thumbnailfile: video.thumbnailfile,
107 previewfile: video.previewfile,
108 pluginData: video.pluginData,
109 scheduleUpdate,
110 originallyPublishedAt
111 }
112
113 const data = objectToFormData(body)
114
115 return this.authHttp.put(`${VideoService.BASE_VIDEO_URL}/${video.id}`, data)
116 .pipe(catchError(err => this.restExtractor.handleError(err)))
117 }
118
119 uploadVideo (video: FormData) {
120 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
121
122 return this.authHttp
123 .request<{ video: { id: number, uuid: string } }>(req)
124 .pipe(catchError(err => this.restExtractor.handleError(err)))
125 }
126
127 getMyVideos (options: {
128 videoPagination: ComponentPaginationLight
129 sort: VideoSortField
130 userChannels?: VideoChannelServerModel[]
131 search?: string
132 }): Observable<ResultList<Video>> {
133 const { videoPagination, sort, userChannels = [], search } = options
134
135 const pagination = this.restService.componentToRestPagination(videoPagination)
136
137 let params = new HttpParams()
138 params = this.restService.addRestGetParams(params, pagination, sort)
139
140 if (search) {
141 const filters = this.restService.parseQueryStringFilter(search, {
142 isLive: {
143 prefix: 'isLive:',
144 isBoolean: true
145 },
146 channelId: {
147 prefix: 'channel:',
148 handler: (name: string) => {
149 const channel = userChannels.find(c => c.name === name)
150
151 if (channel) return channel.id
152
153 return undefined
154 }
155 }
156 })
157
158 params = this.restService.addObjectParams(params, filters)
159 }
160
161 return this.authHttp
162 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
163 .pipe(
164 switchMap(res => this.extractVideos(res)),
165 catchError(err => this.restExtractor.handleError(err))
166 )
167 }
168
169 getAccountVideos (parameters: CommonVideoParams & {
170 account: Pick<Account, 'nameWithHost'>
171 search?: string
172 }): Observable<ResultList<Video>> {
173 const { account, search } = parameters
174
175 let params = new HttpParams()
176 params = this.buildCommonVideosParams({ params, ...parameters })
177
178 if (search) params = params.set('search', search)
179
180 return this.authHttp
181 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
182 .pipe(
183 switchMap(res => this.extractVideos(res)),
184 catchError(err => this.restExtractor.handleError(err))
185 )
186 }
187
188 getVideoChannelVideos (parameters: CommonVideoParams & {
189 videoChannel: Pick<VideoChannel, 'nameWithHost'>
190 }): Observable<ResultList<Video>> {
191 const { videoChannel } = parameters
192
193 let params = new HttpParams()
194 params = this.buildCommonVideosParams({ params, ...parameters })
195
196 return this.authHttp
197 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
198 .pipe(
199 switchMap(res => this.extractVideos(res)),
200 catchError(err => this.restExtractor.handleError(err))
201 )
202 }
203
204 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
205 let params = new HttpParams()
206 params = this.buildCommonVideosParams({ params, ...parameters })
207
208 return this.authHttp
209 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
210 .pipe(
211 switchMap(res => this.extractVideos(res)),
212 catchError(err => this.restExtractor.handleError(err))
213 )
214 }
215
216 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
217 const feeds = [
218 {
219 format: FeedFormat.RSS,
220 label: 'media rss 2.0',
221 url: base + FeedFormat.RSS.toLowerCase()
222 },
223 {
224 format: FeedFormat.ATOM,
225 label: 'atom 1.0',
226 url: base + FeedFormat.ATOM.toLowerCase()
227 },
228 {
229 format: FeedFormat.JSON,
230 label: 'json 1.0',
231 url: base + FeedFormat.JSON.toLowerCase()
232 }
233 ]
234
235 if (params && params.keys().length !== 0) {
236 for (const feed of feeds) {
237 feed.url += '?' + params.toString()
238 }
239 }
240
241 return feeds
242 }
243
244 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
245 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
246
247 if (isLocal) params = params.set('isLocal', isLocal)
248
249 if (categoryOneOf) {
250 for (const c of categoryOneOf) {
251 params = params.append('categoryOneOf[]', c + '')
252 }
253 }
254
255 return this.buildBaseFeedUrls(params)
256 }
257
258 getAccountFeedUrls (accountId: number) {
259 let params = this.restService.addRestGetParams(new HttpParams())
260 params = params.set('accountId', accountId.toString())
261
262 return this.buildBaseFeedUrls(params)
263 }
264
265 getVideoChannelFeedUrls (videoChannelId: number) {
266 let params = this.restService.addRestGetParams(new HttpParams())
267 params = params.set('videoChannelId', videoChannelId.toString())
268
269 return this.buildBaseFeedUrls(params)
270 }
271
272 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
273 let params = this.restService.addRestGetParams(new HttpParams())
274 params = params.set('accountId', accountId.toString())
275 params = params.set('token', feedToken)
276
277 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
278 }
279
280 getVideoFileMetadata (metadataUrl: string) {
281 return this.authHttp
282 .get<VideoFileMetadata>(metadataUrl)
283 .pipe(
284 catchError(err => this.restExtractor.handleError(err))
285 )
286 }
287
288 removeVideo (idArg: number | number[]) {
289 const ids = arrayify(idArg)
290
291 return from(ids)
292 .pipe(
293 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
294 toArray(),
295 catchError(err => this.restExtractor.handleError(err))
296 )
297 }
298
299 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
300 return from(videoIds)
301 .pipe(
302 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
303 toArray(),
304 catchError(err => this.restExtractor.handleError(err))
305 )
306 }
307
308 removeFile (videoId: number | string, fileId: number, type: 'hls' | 'webtorrent') {
309 return this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + videoId + '/' + type + '/' + fileId)
310 .pipe(catchError(err => this.restExtractor.handleError(err)))
311 }
312
313 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
314 const body: VideoTranscodingCreate = { transcodingType: type }
315
316 return from(videoIds)
317 .pipe(
318 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
319 toArray(),
320 catchError(err => this.restExtractor.handleError(err))
321 )
322 }
323
324 loadCompleteDescription (descriptionPath: string) {
325 return this.authHttp
326 .get<{ description: string }>(environment.apiUrl + descriptionPath)
327 .pipe(
328 map(res => res.description),
329 catchError(err => this.restExtractor.handleError(err))
330 )
331 }
332
333 getSource (videoId: number) {
334 return this.authHttp
335 .get<{ source: VideoSource }>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
336 .pipe(
337 catchError(err => {
338 if (err.status === 404) {
339 return of(undefined)
340 }
341
342 this.restExtractor.handleError(err)
343 })
344 )
345 }
346
347 setVideoLike (id: string) {
348 return this.setVideoRate(id, 'like')
349 }
350
351 setVideoDislike (id: string) {
352 return this.setVideoRate(id, 'dislike')
353 }
354
355 unsetVideoLike (id: string) {
356 return this.setVideoRate(id, 'none')
357 }
358
359 getUserVideoRating (id: string) {
360 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
361
362 return this.authHttp.get<UserVideoRate>(url)
363 .pipe(catchError(err => this.restExtractor.handleError(err)))
364 }
365
366 extractVideos (result: ResultList<VideoServerModel>) {
367 return this.serverService.getServerLocale()
368 .pipe(
369 map(translations => {
370 const videosJson = result.data
371 const totalVideos = result.total
372 const videos: Video[] = []
373
374 for (const videoJson of videosJson) {
375 videos.push(new Video(videoJson, translations))
376 }
377
378 return { total: totalVideos, data: videos }
379 })
380 )
381 }
382
383 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
384 const descriptions = {
385 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
386 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
387 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
388 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
389 }
390
391 const videoPrivacies = serverPrivacies.map(p => {
392 return {
393 ...p,
394
395 description: descriptions[p.id]
396 }
397 })
398
399 return {
400 videoPrivacies,
401 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
402 }
403 }
404
405 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
406 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
407
408 for (const privacy of order) {
409 if (serverPrivacies.find(p => p.id === privacy)) {
410 return privacy
411 }
412 }
413
414 throw new Error('No highest privacy available')
415 }
416
417 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
418 return nsfwPolicy === 'do_not_list'
419 ? 'false'
420 : 'both'
421 }
422
423 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
424 const {
425 params,
426 videoPagination,
427 sort,
428 isLocal,
429 include,
430 categoryOneOf,
431 languageOneOf,
432 privacyOneOf,
433 skipCount,
434 nsfwPolicy,
435 isLive,
436 nsfw
437 } = options
438
439 const pagination = videoPagination
440 ? this.restService.componentToRestPagination(videoPagination)
441 : undefined
442
443 let newParams = this.restService.addRestGetParams(params, pagination, this.buildListSort(sort))
444
445 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
446
447 if (isLocal !== undefined) newParams = newParams.set('isLocal', isLocal)
448 if (include !== undefined) newParams = newParams.set('include', include)
449 if (isLive !== undefined) newParams = newParams.set('isLive', isLive)
450 if (nsfw !== undefined) newParams = newParams.set('nsfw', nsfw)
451 if (nsfwPolicy !== undefined) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
452 if (languageOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
453 if (categoryOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
454 if (privacyOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
455
456 return newParams
457 }
458
459 private buildListSort (sortArg: VideoSortField | SortMeta) {
460 const sort = this.restService.buildSortString(sortArg)
461
462 if (typeof sort === 'string') {
463 // Silently use the best algorithm for logged in users if they chose the hot algorithm
464 if (
465 this.auth.isLoggedIn() &&
466 (sort === 'hot' || sort === '-hot')
467 ) {
468 return sort.replace('hot', 'best')
469 }
470
471 return sort
472 }
473 }
474
475 private setVideoRate (id: string, rateType: UserVideoRateType) {
476 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
477 const body: UserVideoRateUpdate = {
478 rating: rateType
479 }
480
481 return this.authHttp
482 .put(url, body)
483 .pipe(catchError(err => this.restExtractor.handleError(err)))
484 }
485}