]>
Commit | Line | Data |
---|---|---|
1 | import { SortMeta } from 'primeng/api' | |
2 | import { from, Observable, of } 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 { AuthService, ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core' | |
7 | import { objectToFormData } from '@app/helpers' | |
8 | import { arrayify } from '@shared/core-utils' | |
9 | import { | |
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' | |
28 | import { VideoSource } from '@shared/models/videos/video-source' | |
29 | import { environment } from '../../../../environments/environment' | |
30 | import { Account } from '../account/account.model' | |
31 | import { AccountService } from '../account/account.service' | |
32 | import { VideoChannel, VideoChannelService } from '../video-channel' | |
33 | import { VideoDetails } from './video-details.model' | |
34 | import { VideoEdit } from './video-edit.model' | |
35 | import { Video } from './video.model' | |
36 | ||
37 | export 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() | |
54 | export class VideoService { | |
55 | static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos' | |
56 | static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.' | |
57 | static PODCAST_FEEDS_URL = environment.apiUrl + '/feeds/podcast/videos.xml' | |
58 | static BASE_SUBSCRIPTION_FEEDS_URL = environment.apiUrl + '/feeds/subscriptions.' | |
59 | ||
60 | constructor ( | |
61 | private auth: AuthService, | |
62 | private authHttp: HttpClient, | |
63 | private restExtractor: RestExtractor, | |
64 | private restService: RestService, | |
65 | private serverService: ServerService | |
66 | ) {} | |
67 | ||
68 | getVideoViewUrl (uuid: string) { | |
69 | return `${VideoService.BASE_VIDEO_URL}/${uuid}/views` | |
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 | const feedUrls = this.buildBaseFeedUrls(params) | |
271 | ||
272 | feedUrls.push({ | |
273 | format: FeedFormat.RSS, | |
274 | label: 'podcast rss 2.0', | |
275 | url: VideoService.PODCAST_FEEDS_URL + `?videoChannelId=${videoChannelId}` | |
276 | }) | |
277 | ||
278 | return feedUrls | |
279 | } | |
280 | ||
281 | getVideoSubscriptionFeedUrls (accountId: number, feedToken: string) { | |
282 | let params = this.restService.addRestGetParams(new HttpParams()) | |
283 | params = params.set('accountId', accountId.toString()) | |
284 | params = params.set('token', feedToken) | |
285 | ||
286 | return this.buildBaseFeedUrls(params, VideoService.BASE_SUBSCRIPTION_FEEDS_URL) | |
287 | } | |
288 | ||
289 | getVideoFileMetadata (metadataUrl: string) { | |
290 | return this.authHttp | |
291 | .get<VideoFileMetadata>(metadataUrl) | |
292 | .pipe( | |
293 | catchError(err => this.restExtractor.handleError(err)) | |
294 | ) | |
295 | } | |
296 | ||
297 | removeVideo (idArg: number | number[]) { | |
298 | const ids = arrayify(idArg) | |
299 | ||
300 | return from(ids) | |
301 | .pipe( | |
302 | concatMap(id => this.authHttp.delete(`${VideoService.BASE_VIDEO_URL}/${id}`)), | |
303 | toArray(), | |
304 | catchError(err => this.restExtractor.handleError(err)) | |
305 | ) | |
306 | } | |
307 | ||
308 | removeVideoFiles (videoIds: (number | string)[], type: 'hls' | 'webtorrent') { | |
309 | return from(videoIds) | |
310 | .pipe( | |
311 | concatMap(id => this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + id + '/' + type)), | |
312 | toArray(), | |
313 | catchError(err => this.restExtractor.handleError(err)) | |
314 | ) | |
315 | } | |
316 | ||
317 | removeFile (videoId: number | string, fileId: number, type: 'hls' | 'webtorrent') { | |
318 | return this.authHttp.delete(VideoService.BASE_VIDEO_URL + '/' + videoId + '/' + type + '/' + fileId) | |
319 | .pipe(catchError(err => this.restExtractor.handleError(err))) | |
320 | } | |
321 | ||
322 | runTranscoding (videoIds: (number | string)[], type: 'hls' | 'webtorrent') { | |
323 | const body: VideoTranscodingCreate = { transcodingType: type } | |
324 | ||
325 | return from(videoIds) | |
326 | .pipe( | |
327 | concatMap(id => this.authHttp.post(VideoService.BASE_VIDEO_URL + '/' + id + '/transcoding', body)), | |
328 | toArray(), | |
329 | catchError(err => this.restExtractor.handleError(err)) | |
330 | ) | |
331 | } | |
332 | ||
333 | loadCompleteDescription (descriptionPath: string) { | |
334 | return this.authHttp | |
335 | .get<{ description: string }>(environment.apiUrl + descriptionPath) | |
336 | .pipe( | |
337 | map(res => res.description), | |
338 | catchError(err => this.restExtractor.handleError(err)) | |
339 | ) | |
340 | } | |
341 | ||
342 | getSource (videoId: number) { | |
343 | return this.authHttp | |
344 | .get<{ source: VideoSource }>(VideoService.BASE_VIDEO_URL + '/' + videoId + '/source') | |
345 | .pipe( | |
346 | catchError(err => { | |
347 | if (err.status === 404) { | |
348 | return of(undefined) | |
349 | } | |
350 | ||
351 | this.restExtractor.handleError(err) | |
352 | }) | |
353 | ) | |
354 | } | |
355 | ||
356 | setVideoLike (id: string) { | |
357 | return this.setVideoRate(id, 'like') | |
358 | } | |
359 | ||
360 | setVideoDislike (id: string) { | |
361 | return this.setVideoRate(id, 'dislike') | |
362 | } | |
363 | ||
364 | unsetVideoLike (id: string) { | |
365 | return this.setVideoRate(id, 'none') | |
366 | } | |
367 | ||
368 | getUserVideoRating (id: string) { | |
369 | const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating' | |
370 | ||
371 | return this.authHttp.get<UserVideoRate>(url) | |
372 | .pipe(catchError(err => this.restExtractor.handleError(err))) | |
373 | } | |
374 | ||
375 | extractVideos (result: ResultList<VideoServerModel>) { | |
376 | return this.serverService.getServerLocale() | |
377 | .pipe( | |
378 | map(translations => { | |
379 | const videosJson = result.data | |
380 | const totalVideos = result.total | |
381 | const videos: Video[] = [] | |
382 | ||
383 | for (const videoJson of videosJson) { | |
384 | videos.push(new Video(videoJson, translations)) | |
385 | } | |
386 | ||
387 | return { total: totalVideos, data: videos } | |
388 | }) | |
389 | ) | |
390 | } | |
391 | ||
392 | explainedPrivacyLabels (serverPrivacies: VideoConstant<VideoPrivacy>[], defaultPrivacyId = VideoPrivacy.PUBLIC) { | |
393 | const descriptions = { | |
394 | [VideoPrivacy.PRIVATE]: $localize`Only I can see this video`, | |
395 | [VideoPrivacy.UNLISTED]: $localize`Only shareable via a private link`, | |
396 | [VideoPrivacy.PUBLIC]: $localize`Anyone can see this video`, | |
397 | [VideoPrivacy.INTERNAL]: $localize`Only users of this instance can see this video` | |
398 | } | |
399 | ||
400 | const videoPrivacies = serverPrivacies.map(p => { | |
401 | return { | |
402 | ...p, | |
403 | ||
404 | description: descriptions[p.id] | |
405 | } | |
406 | }) | |
407 | ||
408 | return { | |
409 | videoPrivacies, | |
410 | defaultPrivacyId: serverPrivacies.find(p => p.id === defaultPrivacyId)?.id || serverPrivacies[0].id | |
411 | } | |
412 | } | |
413 | ||
414 | getHighestAvailablePrivacy (serverPrivacies: VideoConstant<VideoPrivacy>[]) { | |
415 | const order = [ VideoPrivacy.PRIVATE, VideoPrivacy.INTERNAL, VideoPrivacy.UNLISTED, VideoPrivacy.PUBLIC ] | |
416 | ||
417 | for (const privacy of order) { | |
418 | if (serverPrivacies.find(p => p.id === privacy)) { | |
419 | return privacy | |
420 | } | |
421 | } | |
422 | ||
423 | throw new Error('No highest privacy available') | |
424 | } | |
425 | ||
426 | nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) { | |
427 | return nsfwPolicy === 'do_not_list' | |
428 | ? 'false' | |
429 | : 'both' | |
430 | } | |
431 | ||
432 | // Choose if we display by default the account or the channel | |
433 | buildDefaultOwnerDisplayType (video: Video) { | |
434 | const accountName = video.account.name | |
435 | ||
436 | // If the video channel name is an UUID (not really displayable, we changed this behaviour in v1.0.0-beta.12) | |
437 | // Or has not been customized (default created channel display name) | |
438 | // -> Use the account name | |
439 | if ( | |
440 | video.channel.displayName === `Default ${accountName} channel` || | |
441 | video.channel.displayName === `Main ${accountName} channel` || | |
442 | video.channel.name.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/) | |
443 | ) { | |
444 | return 'account' as 'account' | |
445 | } | |
446 | ||
447 | return 'videoChannel' as 'videoChannel' | |
448 | } | |
449 | ||
450 | buildCommonVideosParams (options: CommonVideoParams & { params: HttpParams }) { | |
451 | const { | |
452 | params, | |
453 | videoPagination, | |
454 | sort, | |
455 | isLocal, | |
456 | include, | |
457 | categoryOneOf, | |
458 | languageOneOf, | |
459 | privacyOneOf, | |
460 | skipCount, | |
461 | nsfwPolicy, | |
462 | isLive, | |
463 | nsfw | |
464 | } = options | |
465 | ||
466 | const pagination = videoPagination | |
467 | ? this.restService.componentToRestPagination(videoPagination) | |
468 | : undefined | |
469 | ||
470 | let newParams = this.restService.addRestGetParams(params, pagination, this.buildListSort(sort)) | |
471 | ||
472 | if (skipCount) newParams = newParams.set('skipCount', skipCount + '') | |
473 | ||
474 | if (isLocal !== undefined) newParams = newParams.set('isLocal', isLocal) | |
475 | if (include !== undefined) newParams = newParams.set('include', include) | |
476 | if (isLive !== undefined) newParams = newParams.set('isLive', isLive) | |
477 | if (nsfw !== undefined) newParams = newParams.set('nsfw', nsfw) | |
478 | if (nsfwPolicy !== undefined) newParams = newParams.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy)) | |
479 | if (languageOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'languageOneOf', languageOneOf) | |
480 | if (categoryOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'categoryOneOf', categoryOneOf) | |
481 | if (privacyOneOf !== undefined) newParams = this.restService.addArrayParams(newParams, 'privacyOneOf', privacyOneOf) | |
482 | ||
483 | return newParams | |
484 | } | |
485 | ||
486 | private buildListSort (sortArg: VideoSortField | SortMeta) { | |
487 | const sort = this.restService.buildSortString(sortArg) | |
488 | ||
489 | if (typeof sort === 'string') { | |
490 | // Silently use the best algorithm for logged in users if they chose the hot algorithm | |
491 | if ( | |
492 | this.auth.isLoggedIn() && | |
493 | (sort === 'hot' || sort === '-hot') | |
494 | ) { | |
495 | return sort.replace('hot', 'best') | |
496 | } | |
497 | ||
498 | return sort | |
499 | } | |
500 | } | |
501 | ||
502 | private setVideoRate (id: string, rateType: UserVideoRateType) { | |
503 | const url = `${VideoService.BASE_VIDEO_URL}/${id}/rate` | |
504 | const body: UserVideoRateUpdate = { | |
505 | rating: rateType | |
506 | } | |
507 | ||
508 | return this.authHttp | |
509 | .put(url, body) | |
510 | .pipe(catchError(err => this.restExtractor.handleError(err))) | |
511 | } | |
512 | } |