]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - client/src/app/shared/shared-main/video/video.service.ts
Add bulk action on following/followers
[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 runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') {
309 const body: VideoTranscodingCreate = { transcodingType: type }
310
311 return from(videoIds)
312 .pipe(
313 concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)),
314 toArray(),
315 catchError(err => this.restExtractor.handleError(err))
316 )
317 }
318
319 loadCompleteDescription (descriptionPath: string) {
320 return this.authHttp
321 .get<{ description: string }>(environment.apiUrl + descriptionPath)
322 .pipe(
323 map(res => res.description),
324 catchError(err => this.restExtractor.handleError(err))
325 )
326 }
327
328 getSource (videoId: number) {
329 return this.authHttp
330 .get<{ source: VideoSource }>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source')
331 .pipe(
332 catchError(err => {
333 if (err.status === 404) {
334 return of(undefined)
335 }
336
337 this.restExtractor.handleError(err)
338 })
339 )
340 }
341
342 setVideoLike (id: string) {
343 return this.setVideoRate(id, 'like')
344 }
345
346 setVideoDislike (id: string) {
347 return this.setVideoRate(id, 'dislike')
348 }
349
350 unsetVideoLike (id: string) {
351 return this.setVideoRate(id, 'none')
352 }
353
354 getUserVideoRating (id: string) {
355 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
356
357 return this.authHttp.get<UserVideoRate>(url)
358 .pipe(catchError(err => this.restExtractor.handleError(err)))
359 }
360
361 extractVideos (result: ResultList<VideoServerModel>) {
362 return this.serverService.getServerLocale()
363 .pipe(
364 map(translations => {
365 const videosJson = result.data
366 const totalVideos = result.total
367 const videos: Video[] = []
368
369 for (const videoJson of videosJson) {
370 videos.push(new Video(videoJson, translations))
371 }
372
373 return { total: totalVideos, data: videos }
374 })
375 )
376 }
377
378 explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) {
379 const descriptions = {
380 [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`,
381 [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`,
382 [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`,
383 [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video`
384 }
385
386 const videoPrivacies = serverPrivacies.map(p => {
387 return {
388 ...p,
389
390 description: descriptions[p.id]
391 }
392 })
393
394 return {
395 videoPrivacies,
396 defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id
397 }
398 }
399
400 getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) {
401 const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ]
402
403 for (const privacy of order) {
404 if (serverPrivacies.find(p => p.id === privacy)) {
405 return privacy
406 }
407 }
408
409 throw new Error('No highest privacy available')
410 }
411
412 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
413 return nsfwPolicy === 'do_not_list'
414 ? 'false'
415 : 'both'
416 }
417
418 buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) {
419 const {
420 params,
421 videoPagination,
422 sort,
423 isLocal,
424 include,
425 categoryOneOf,
426 languageOneOf,
427 privacyOneOf,
428 skipCount,
429 nsfwPolicy,
430 isLive,
431 nsfw
432 } = options
433
434 const pagination = videoPagination
435 ? this.restService.componentToRestPagination(videoPagination)
436 : undefined
437
438 let newParams = this.restService.addRestGetParams(params, pagination, this.buildListSort(sort))
439
440 if (skipCount) newParams = newParams.set('skipCount', skipCount + '')
441
442 if (isLocal !== undefined) newParams = newParams.set('isLocal', isLocal)
443 if (include !== undefined) newParams = newParams.set('include', include)
444 if (isLive !== undefined) newParams = newParams.set('isLive', isLive)
445 if (nsfw !== undefined) newParams = newParams.set('nsfw', nsfw)
446 if (nsfwPolicy !== undefined) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
447 if (languageOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf)
448 if (categoryOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf)
449 if (privacyOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf)
450
451 return newParams
452 }
453
454 private buildListSort (sortArg: VideoSortField | SortMeta) {
455 const sort = this.restService.buildSortString(sortArg)
456
457 if (typeof sort === 'string') {
458 // Silently use the best algorithm for logged in users if they chose the hot algorithm
459 if (
460 this.auth.isLoggedIn() &&
461 (sort === 'hot' || sort === '-hot')
462 ) {
463 return sort.replace('hot', 'best')
464 }
465
466 return sort
467 }
468 }
469
470 private setVideoRate (id: string, rateType: UserVideoRateType) {
471 const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate`
472 const body: UserVideoRateUpdate = {
473 rating: rateType
474 }
475
476 return this.authHttp
477 .put(url, body)
478 .pipe(catchError(err => this.restExtractor.handleError(err)))
479 }
480}