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