]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/video/video.service.ts
Add video file metadata to download modal, via ffprobe (#2411)
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / video / video.service.ts
1 import { catchError, map, switchMap } from 'rxjs/operators'
2 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
3 import { Injectable } from '@angular/core'
4 import { Observable } from 'rxjs'
5 import { Video as VideoServerModel, VideoDetails as VideoDetailsServerModel } from '../../../../../shared'
6 import { ResultList } from '../../../../../shared/models/result-list.model'
7 import {
8 UserVideoRate,
9 UserVideoRateType,
10 UserVideoRateUpdate,
11 VideoConstant,
12 VideoFilter,
13 VideoPrivacy,
14 VideoUpdate
15 } from '../../../../../shared/models/videos'
16 import { FeedFormat } from '../../../../../shared/models/feeds/feed-format.enum'
17 import { environment } from '../../../environments/environment'
18 import { ComponentPaginationLight } from '../rest/component-pagination.model'
19 import { RestExtractor } from '../rest/rest-extractor.service'
20 import { RestService } from '../rest/rest.service'
21 import { UserService } from '../users/user.service'
22 import { VideoSortField } from './sort-field.type'
23 import { VideoDetails } from './video-details.model'
24 import { VideoEdit } from './video-edit.model'
25 import { Video } from './video.model'
26 import { objectToFormData } from '@app/shared/misc/utils'
27 import { Account } from '@app/shared/account/account.model'
28 import { AccountService } from '@app/shared/account/account.service'
29 import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
30 import { ServerService, AuthService } from '@app/core'
31 import { UserSubscriptionService } from '@app/shared/user-subscription/user-subscription.service'
32 import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
33 import { I18n } from '@ngx-translate/i18n-polyfill'
34 import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
35 import { FfprobeData } from 'fluent-ffmpeg'
36
37 export interface VideosProvider {
38 getVideos (parameters: {
39 videoPagination: ComponentPaginationLight,
40 sort: VideoSortField,
41 filter?: VideoFilter,
42 categoryOneOf?: number,
43 languageOneOf?: string[]
44 }): Observable<ResultList<Video>>
45 }
46
47 @Injectable()
48 export class VideoService implements VideosProvider {
49 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
50 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
51
52 constructor (
53 private authHttp: HttpClient,
54 private authService: AuthService,
55 private userService: UserService,
56 private restExtractor: RestExtractor,
57 private restService: RestService,
58 private serverService: ServerService,
59 private i18n: I18n
60 ) {}
61
62 getVideoViewUrl (uuid: string) {
63 return VideoService.BASE_VIDEO_URL + uuid + '/views'
64 }
65
66 getUserWatchingVideoUrl (uuid: string) {
67 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
68 }
69
70 getVideo (options: { videoId: string }): Observable<VideoDetails> {
71 return this.serverService.getServerLocale()
72 .pipe(
73 switchMap(translations => {
74 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
75 .pipe(map(videoHash => ({ videoHash, translations })))
76 }),
77 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
78 catchError(err => this.restExtractor.handleError(err))
79 )
80 }
81
82 updateVideo (video: VideoEdit) {
83 const language = video.language || null
84 const licence = video.licence || null
85 const category = video.category || null
86 const description = video.description || null
87 const support = video.support || null
88 const scheduleUpdate = video.scheduleUpdate || null
89 const originallyPublishedAt = video.originallyPublishedAt || null
90
91 const body: VideoUpdate = {
92 name: video.name,
93 category,
94 licence,
95 language,
96 support,
97 description,
98 channelId: video.channelId,
99 privacy: video.privacy,
100 tags: video.tags,
101 nsfw: video.nsfw,
102 waitTranscoding: video.waitTranscoding,
103 commentsEnabled: video.commentsEnabled,
104 downloadEnabled: video.downloadEnabled,
105 thumbnailfile: video.thumbnailfile,
106 previewfile: video.previewfile,
107 scheduleUpdate,
108 originallyPublishedAt
109 }
110
111 const data = objectToFormData(body)
112
113 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
114 .pipe(
115 map(this.restExtractor.extractDataBool),
116 catchError(err => this.restExtractor.handleError(err))
117 )
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 (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
129 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
130
131 let params = new HttpParams()
132 params = this.restService.addRestGetParams(params, pagination, sort)
133 params = this.restService.addObjectParams(params, { search })
134
135 return this.authHttp
136 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
137 .pipe(
138 switchMap(res => this.extractVideos(res)),
139 catchError(err => this.restExtractor.handleError(err))
140 )
141 }
142
143 getAccountVideos (
144 account: Account,
145 videoPagination: ComponentPaginationLight,
146 sort: VideoSortField
147 ): Observable<ResultList<Video>> {
148 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
149
150 let params = new HttpParams()
151 params = this.restService.addRestGetParams(params, pagination, sort)
152
153 return this.authHttp
154 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
155 .pipe(
156 switchMap(res => this.extractVideos(res)),
157 catchError(err => this.restExtractor.handleError(err))
158 )
159 }
160
161 getVideoChannelVideos (
162 videoChannel: VideoChannel,
163 videoPagination: ComponentPaginationLight,
164 sort: VideoSortField
165 ): Observable<ResultList<Video>> {
166 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
167
168 let params = new HttpParams()
169 params = this.restService.addRestGetParams(params, pagination, sort)
170
171 return this.authHttp
172 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
173 .pipe(
174 switchMap(res => this.extractVideos(res)),
175 catchError(err => this.restExtractor.handleError(err))
176 )
177 }
178
179 getUserSubscriptionVideos (parameters: {
180 videoPagination: ComponentPaginationLight,
181 sort: VideoSortField,
182 skipCount?: boolean
183 }): Observable<ResultList<Video>> {
184 const { videoPagination, sort, skipCount } = parameters
185 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
186
187 let params = new HttpParams()
188 params = this.restService.addRestGetParams(params, pagination, sort)
189
190 if (skipCount) params = params.set('skipCount', skipCount + '')
191
192 return this.authHttp
193 .get<ResultList<Video>>(UserSubscriptionService.BASE_USER_SUBSCRIPTIONS_URL + '/videos', { params })
194 .pipe(
195 switchMap(res => this.extractVideos(res)),
196 catchError(err => this.restExtractor.handleError(err))
197 )
198 }
199
200 getVideos (parameters: {
201 videoPagination: ComponentPaginationLight,
202 sort: VideoSortField,
203 filter?: VideoFilter,
204 categoryOneOf?: number,
205 languageOneOf?: string[],
206 skipCount?: boolean,
207 nsfw?: boolean
208 }): Observable<ResultList<Video>> {
209 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfw } = parameters
210
211 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
212
213 let params = new HttpParams()
214 params = this.restService.addRestGetParams(params, pagination, sort)
215
216 if (filter) params = params.set('filter', filter)
217 if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
218 if (skipCount) params = params.set('skipCount', skipCount + '')
219
220 if (nsfw) {
221 params = params.set('nsfw', nsfw + '')
222 } else {
223 const nsfwPolicy = this.authService.isLoggedIn()
224 ? this.authService.getUser().nsfwPolicy
225 : this.userService.getAnonymousUser().nsfwPolicy
226 if (this.nsfwPolicyToFilter(nsfwPolicy)) params.set('nsfw', 'false')
227 }
228
229 if (languageOneOf) {
230 for (const l of languageOneOf) {
231 params = params.append('languageOneOf[]', l)
232 }
233 }
234
235 return this.authHttp
236 .get<ResultList<Video>>(VideoService.BASE_VIDEO_URL, { params })
237 .pipe(
238 switchMap(res => this.extractVideos(res)),
239 catchError(err => this.restExtractor.handleError(err))
240 )
241 }
242
243 buildBaseFeedUrls (params: HttpParams) {
244 const feeds = [
245 {
246 format: FeedFormat.RSS,
247 label: 'rss 2.0',
248 url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
249 },
250 {
251 format: FeedFormat.ATOM,
252 label: 'atom 1.0',
253 url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
254 },
255 {
256 format: FeedFormat.JSON,
257 label: 'json 1.0',
258 url: VideoService.BASE_FEEDS_URL + FeedFormat.JSON.toLowerCase()
259 }
260 ]
261
262 if (params && params.keys().length !== 0) {
263 for (const feed of feeds) {
264 feed.url += '?' + params.toString()
265 }
266 }
267
268 return feeds
269 }
270
271 getVideoFeedUrls (sort: VideoSortField, filter?: VideoFilter, categoryOneOf?: number) {
272 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
273
274 if (filter) params = params.set('filter', filter)
275
276 if (categoryOneOf) params = params.set('categoryOneOf', categoryOneOf + '')
277
278 return this.buildBaseFeedUrls(params)
279 }
280
281 getAccountFeedUrls (accountId: number) {
282 let params = this.restService.addRestGetParams(new HttpParams())
283 params = params.set('accountId', accountId.toString())
284
285 return this.buildBaseFeedUrls(params)
286 }
287
288 getVideoChannelFeedUrls (videoChannelId: number) {
289 let params = this.restService.addRestGetParams(new HttpParams())
290 params = params.set('videoChannelId', videoChannelId.toString())
291
292 return this.buildBaseFeedUrls(params)
293 }
294
295 getVideoFileMetadata (metadataUrl: string) {
296 return this.authHttp
297 .get<FfprobeData>(metadataUrl)
298 .pipe(
299 catchError(err => this.restExtractor.handleError(err))
300 )
301 }
302
303 removeVideo (id: number) {
304 return this.authHttp
305 .delete(VideoService.BASE_VIDEO_URL + id)
306 .pipe(
307 map(this.restExtractor.extractDataBool),
308 catchError(err => this.restExtractor.handleError(err))
309 )
310 }
311
312 loadCompleteDescription (descriptionPath: string) {
313 return this.authHttp
314 .get<{ description: string }>(environment.apiUrl + descriptionPath)
315 .pipe(
316 map(res => res.description),
317 catchError(err => this.restExtractor.handleError(err))
318 )
319 }
320
321 setVideoLike (id: number) {
322 return this.setVideoRate(id, 'like')
323 }
324
325 setVideoDislike (id: number) {
326 return this.setVideoRate(id, 'dislike')
327 }
328
329 unsetVideoLike (id: number) {
330 return this.setVideoRate(id, 'none')
331 }
332
333 getUserVideoRating (id: number) {
334 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
335
336 return this.authHttp.get<UserVideoRate>(url)
337 .pipe(catchError(err => this.restExtractor.handleError(err)))
338 }
339
340 extractVideos (result: ResultList<VideoServerModel>) {
341 return this.serverService.getServerLocale()
342 .pipe(
343 map(translations => {
344 const videosJson = result.data
345 const totalVideos = result.total
346 const videos: Video[] = []
347
348 for (const videoJson of videosJson) {
349 videos.push(new Video(videoJson, translations))
350 }
351
352 return { total: totalVideos, data: videos }
353 })
354 )
355 }
356
357 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
358 const base = [
359 {
360 id: VideoPrivacy.PRIVATE,
361 label: this.i18n('Only I can see this video')
362 },
363 {
364 id: VideoPrivacy.UNLISTED,
365 label: this.i18n('Only people with the private link can see this video')
366 },
367 {
368 id: VideoPrivacy.PUBLIC,
369 label: this.i18n('Anyone can see this video')
370 },
371 {
372 id: VideoPrivacy.INTERNAL,
373 label: this.i18n('Only users of this instance can see this video')
374 }
375 ]
376
377 return base.filter(o => !!privacies.find(p => p.id === o.id))
378 }
379
380 private setVideoRate (id: number, rateType: UserVideoRateType) {
381 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
382 const body: UserVideoRateUpdate = {
383 rating: rateType
384 }
385
386 return this.authHttp
387 .put(url, body)
388 .pipe(
389 map(this.restExtractor.extractDataBool),
390 catchError(err => this.restExtractor.handleError(err))
391 )
392 }
393
394 private nsfwPolicyToFilter (policy: NSFWPolicyType) {
395 return policy === 'do_not_list'
396 }
397 }