]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/video/video.service.ts
Add reset button for file inputs in studio page
[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(catchError(err => this.restExtractor.handleError(err)))
118 }
119
120 uploadVideo (video: FormData) {
121 const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true })
122
123 return this.authHttp
124 .request<{ video: { id: number, uuid: string } }>(req)
125 .pipe(catchError(err => this.restExtractor.handleError(err)))
126 }
127
128 getMyVideos (options: {
129 videoPagination: ComponentPaginationLight
130 sort: VideoSortField
131 userChannels?: VideoChannelServerModel[]
132 search?: string
133 }): Observable<ResultList<Video>> {
134 const { videoPagination, sort, userChannels = [], search } = options
135
136 const pagination = this.restService.componentToRestPagination(videoPagination)
137
138 let params = new HttpParams()
139 params = this.restService.addRestGetParams(params, pagination, sort)
140
141 if (search) {
142 const filters = this.restService.parseQueryStringFilter(search, {
143 isLive: {
144 prefix: 'isLive:',
145 isBoolean: true
146 },
147 channelId: {
148 prefix: 'channel:',
149 handler: (name: string) => {
150 const channel = userChannels.find(c => c.name === name)
151
152 if (channel) return channel.id
153
154 return undefined
155 }
156 }
157 })
158
159 params = this.restService.addObjectParams(params, filters)
160 }
161
162 return this.authHttp
163 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
164 .pipe(
165 switchMap(res => this.extractVideos(res)),
166 catchError(err => this.restExtractor.handleError(err))
167 )
168 }
169
170 getAccountVideos (parameters: CommonVideoParams & {
171 account: Pick<Account, 'nameWithHost'>
172 search?: string
173 }): Observable<ResultList<Video>> {
174 const { account, search } = parameters
175
176 let params = new HttpParams()
177 params = this.buildCommonVideosParams({ params, ...parameters })
178
179 if (search) params = params.set('search', search)
180
181 return this.authHttp
182 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
183 .pipe(
184 switchMap(res => this.extractVideos(res)),
185 catchError(err => this.restExtractor.handleError(err))
186 )
187 }
188
189 getVideoChannelVideos (parameters: CommonVideoParams & {
190 videoChannel: Pick<VideoChannel, 'nameWithHost'>
191 }): Observable<ResultList<Video>> {
192 const { videoChannel } = parameters
193
194 let params = new HttpParams()
195 params = this.buildCommonVideosParams({ params, ...parameters })
196
197 return this.authHttp
198 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
199 .pipe(
200 switchMap(res => this.extractVideos(res)),
201 catchError(err => this.restExtractor.handleError(err))
202 )
203 }
204
205 getVideos (parameters: CommonVideoParams): Observable<ResultList<Video>> {
206 let params = new HttpParams()
207 params = this.buildCommonVideosParams({ params, ...parameters })
208
209 return this.authHttp
210 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
211 .pipe(
212 switchMap(res => this.extractVideos(res)),
213 catchError(err => this.restExtractor.handleError(err))
214 )
215 }
216
217 buildBaseFeedUrls (params: HttpParams, base = VideoService.BASE_FEEDS_URL) {
218 const feeds = [
219 {
220 format: FeedFormat.RSS,
221 label: 'media rss 2.0',
222 url: base + FeedFormat.RSS.toLowerCase()
223 },
224 {
225 format: FeedFormat.ATOM,
226 label: 'atom 1.0',
227 url: base + FeedFormat.ATOM.toLowerCase()
228 },
229 {
230 format: FeedFormat.JSON,
231 label: 'json 1.0',
232 url: base + FeedFormat.JSON.toLowerCase()
233 }
234 ]
235
236 if (params && params.keys().length !== 0) {
237 for (const feed of feeds) {
238 feed.url += '?' + params.toString()
239 }
240 }
241
242 return feeds
243 }
244
245 getVideoFeedUrls (sort: VideoSortField, isLocal: boolean, categoryOneOf?: number[]) {
246 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
247
248 if (isLocal) params = params.set('isLocal', isLocal)
249
250 if (categoryOneOf) {
251 for (const c of categoryOneOf) {
252 params = params.append('categoryOneOf[]', c + '')
253 }
254 }
255
256 return this.buildBaseFeedUrls(params)
257 }
258
259 getAccountFeedUrls (accountId: number) {
260 let params = this.restService.addRestGetParams(new HttpParams())
261 params = params.set('accountId', accountId.toString())
262
263 return this.buildBaseFeedUrls(params)
264 }
265
266 getVideoChannelFeedUrls (videoChannelId: number) {
267 let params = this.restService.addRestGetParams(new HttpParams())
268 params = params.set('videoChannelId', videoChannelId.toString())
269
270 return this.buildBaseFeedUrls(params)
271 }
272
273 getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) {
274 let params = this.restService.addRestGetParams(new HttpParams())
275 params = params.set('accountId', accountId.toString())
276 params = params.set('token', feedToken)
277
278 return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL)
279 }
280
281 getVideoFileMetadata (metadataUrl: string) {
282 return this.authHttp
283 .get<VideoFileMetadata>(metadataUrl)
284 .pipe(
285 catchError(err => this.restExtractor.handleError(err))
286 )
287 }
288
289 removeVideo (idArg: number | number[]) {
290 const ids = Array.isArray(idArg) ? idArg : [ idArg ]
291
292 return from(ids)
293 .pipe(
294 concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)),
295 toArray(),
296 catchError(err => this.restExtractor.handleError(err))
297 )
298 }
299
300 removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
301 return from(videoIds)
302 .pipe(
303 concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)),
304 toArray(),
305 catchError(err => this.restExtractor.handleError(err))
306 )
307 }
308
309 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
310 const body: VideoTranscodingCreate = { transcodingType: type }
311
312 return from(videoIds)
313 .pipe(
314 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
315 toArray(),
316 catchError(err => this.restExtractor.handleError(err))
317 )
318 }
319
320 loadCompleteDescription (descriptionPath: string) {
321 return this.authHttp
322 .get<{ description: string }>(environment.apiUrl + descriptionPath)
323 .pipe(
324 map(res => res.description),
325 catchError(err => this.restExtractor.handleError(err))
326 )
327 }
328
329 setVideoLike (id: number) {
330 return this.setVideoRate(id, 'like')
331 }
332
333 setVideoDislike (id: number) {
334 return this.setVideoRate(id, 'dislike')
335 }
336
337 unsetVideoLike (id: number) {
338 return this.setVideoRate(id, 'none')
339 }
340
341 getUserVideoRating (id: number) {
342 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
343
344 return this.authHttp.get<UserVideoRate>(url)
345 .pipe(catchError(err => this.restExtractor.handleError(err)))
346 }
347
348 extractVideos (result: ResultList<VideoServerModel>) {
349 return this.serverService.getServerLocale()
350 .pipe(
351 map(translations => {
352 const videosJson = result.data
353 const totalVideos = result.total
354 const videos: Video[] = []
355
356 for (const videoJson of videosJson) {
357 videos.push(new Video(videoJson, translations))
358 }
359
360 return { total: totalVideos, data: videos }
361 })
362 )
363 }
364
365 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
366 const descriptions = {
367 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
368 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
369 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
370 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
371 }
372
373 const videoPrivacies = serverPrivacies.map(p => {
374 return {
375 ...p,
376
377 description: descriptions[p.id]
378 }
379 })
380
381 return {
382 videoPrivacies,
383 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
384 }
385 }
386
387 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
388 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
389
390 for (const privacy of order) {
391 if (serverPrivacies.find(p => p.id === privacy)) {
392 return privacy
393 }
394 }
395
396 throw new Error('No highest privacy available')
397 }
398
399 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
400 return nsfwPolicy === 'do_not_list'
401 ? 'false'
402 : 'both'
403 }
404
405 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
406 const {
407 params,
408 videoPagination,
409 sort,
410 isLocal,
411 include,
412 categoryOneOf,
413 languageOneOf,
414 privacyOneOf,
415 skipCount,
416 nsfwPolicy,
417 isLive,
418 nsfw
419 } = options
420
421 const pagination = videoPagination
422 ? this.restService.componentToRestPagination(videoPagination)
423 : undefined
424
425 let newParams = this.restService.addRestGetParams(params, pagination, sort)
426
427 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
428
429 if (isLocal) newParams = newParams.set('isLocal', isLocal)
430 if (include) newParams = newParams.set('include', include)
431 if (isLive) newParams = newParams.set('isLive', isLive)
432 if (nsfw) newParams = newParams.set('nsfw', nsfw)
433 if (nsfwPolicy) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
434 if (languageOneOf) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
435 if (categoryOneOf) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
436 if (privacyOneOf) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
437
438 return newParams
439 }
440
441 private setVideoRate (id: number, rateType: UserVideoRateType) {
442 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
443 const body: UserVideoRateUpdate = {
444 rating: rateType
445 }
446
447 return this.authHttp
448 .put(url, body)
449 .pipe(catchError(err => this.restExtractor.handleError(err)))
450 }
451 }