]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-main/video/video.service.ts
Add ability to set custom field to video form
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-main / video / video.service.ts
1 import { Observable } from 'rxjs'
2 import { catchError, map, switchMap } from 'rxjs/operators'
3 import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http'
4 import { Injectable } from '@angular/core'
5 import { ComponentPaginationLight, RestExtractor, RestService, ServerService, UserService } from '@app/core'
6 import { objectToFormData } from '@app/helpers'
7 import {
8 FeedFormat,
9 NSFWPolicyType,
10 ResultList,
11 UserVideoRate,
12 UserVideoRateType,
13 UserVideoRateUpdate,
14 Video as VideoServerModel,
15 VideoConstant,
16 VideoDetails as VideoDetailsServerModel,
17 VideoFileMetadata,
18 VideoFilter,
19 VideoPrivacy,
20 VideoSortField,
21 VideoUpdate
22 } from '@shared/models'
23 import { environment } from '../../../../environments/environment'
24 import { Account } from '../account/account.model'
25 import { AccountService } from '../account/account.service'
26 import { VideoChannel, VideoChannelService } from '../video-channel'
27 import { VideoDetails } from './video-details.model'
28 import { VideoEdit } from './video-edit.model'
29 import { Video } from './video.model'
30
31 export interface VideosProvider {
32 getVideos (parameters: {
33 videoPagination: ComponentPaginationLight,
34 sort: VideoSortField,
35 filter?: VideoFilter,
36 categoryOneOf?: number[],
37 languageOneOf?: string[]
38 nsfwPolicy: NSFWPolicyType
39 }): Observable<ResultList<Video>>
40 }
41
42 @Injectable()
43 export class VideoService implements VideosProvider {
44 static BASE_VIDEO_URL = environment.apiUrl + '/api/v1/videos/'
45 static BASE_FEEDS_URL = environment.apiUrl + '/feeds/videos.'
46
47 constructor (
48 private authHttp: HttpClient,
49 private restExtractor: RestExtractor,
50 private restService: RestService,
51 private serverService: ServerService
52 ) {}
53
54 getVideoViewUrl (uuid: string) {
55 return VideoService.BASE_VIDEO_URL + uuid + '/views'
56 }
57
58 getUserWatchingVideoUrl (uuid: string) {
59 return VideoService.BASE_VIDEO_URL + uuid + '/watching'
60 }
61
62 getVideo (options: { videoId: string }): Observable<VideoDetails> {
63 return this.serverService.getServerLocale()
64 .pipe(
65 switchMap(translations => {
66 return this.authHttp.get<VideoDetailsServerModel>(VideoService.BASE_VIDEO_URL + options.videoId)
67 .pipe(map(videoHash => ({ videoHash, translations })))
68 }),
69 map(({ videoHash, translations }) => new VideoDetails(videoHash, translations)),
70 catchError(err => this.restExtractor.handleError(err))
71 )
72 }
73
74 updateVideo (video: VideoEdit) {
75 const language = video.language || null
76 const licence = video.licence || null
77 const category = video.category || null
78 const description = video.description || null
79 const support = video.support || null
80 const scheduleUpdate = video.scheduleUpdate || null
81 const originallyPublishedAt = video.originallyPublishedAt || null
82
83 const body: VideoUpdate = {
84 name: video.name,
85 category,
86 licence,
87 language,
88 support,
89 description,
90 channelId: video.channelId,
91 privacy: video.privacy,
92 tags: video.tags,
93 nsfw: video.nsfw,
94 waitTranscoding: video.waitTranscoding,
95 commentsEnabled: video.commentsEnabled,
96 downloadEnabled: video.downloadEnabled,
97 thumbnailfile: video.thumbnailfile,
98 previewfile: video.previewfile,
99 pluginData: video.pluginData,
100 scheduleUpdate,
101 originallyPublishedAt
102 }
103
104 const data = objectToFormData(body)
105
106 return this.authHttp.put(VideoService.BASE_VIDEO_URL + video.id, data)
107 .pipe(
108 map(this.restExtractor.extractDataBool),
109 catchError(err => this.restExtractor.handleError(err))
110 )
111 }
112
113 uploadVideo (video: FormData) {
114 const req = new HttpRequest('POST', VideoService.BASE_VIDEO_URL + 'upload', video, { reportProgress: true })
115
116 return this.authHttp
117 .request<{ video: { id: number, uuid: string } }>(req)
118 .pipe(catchError(err => this.restExtractor.handleError(err)))
119 }
120
121 getMyVideos (videoPagination: ComponentPaginationLight, sort: VideoSortField, search?: string): Observable<ResultList<Video>> {
122 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
123
124 let params = new HttpParams()
125 params = this.restService.addRestGetParams(params, pagination, sort)
126 params = this.restService.addObjectParams(params, { search })
127
128 return this.authHttp
129 .get<ResultList<Video>>(UserService.BASE_USERS_URL + 'me/videos', { params })
130 .pipe(
131 switchMap(res => this.extractVideos(res)),
132 catchError(err => this.restExtractor.handleError(err))
133 )
134 }
135
136 getAccountVideos (
137 account: Account,
138 videoPagination: ComponentPaginationLight,
139 sort: VideoSortField
140 ): Observable<ResultList<Video>> {
141 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
142
143 let params = new HttpParams()
144 params = this.restService.addRestGetParams(params, pagination, sort)
145
146 return this.authHttp
147 .get<ResultList<Video>>(AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/videos', { params })
148 .pipe(
149 switchMap(res => this.extractVideos(res)),
150 catchError(err => this.restExtractor.handleError(err))
151 )
152 }
153
154 getVideoChannelVideos (
155 videoChannel: VideoChannel,
156 videoPagination: ComponentPaginationLight,
157 sort: VideoSortField,
158 nsfwPolicy?: NSFWPolicyType
159 ): Observable<ResultList<Video>> {
160 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
161
162 let params = new HttpParams()
163 params = this.restService.addRestGetParams(params, pagination, sort)
164
165 if (nsfwPolicy) {
166 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
167 }
168
169 return this.authHttp
170 .get<ResultList<Video>>(VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/videos', { params })
171 .pipe(
172 switchMap(res => this.extractVideos(res)),
173 catchError(err => this.restExtractor.handleError(err))
174 )
175 }
176
177 getVideos (parameters: {
178 videoPagination: ComponentPaginationLight,
179 sort: VideoSortField,
180 filter?: VideoFilter,
181 categoryOneOf?: number[],
182 languageOneOf?: string[],
183 skipCount?: boolean,
184 nsfwPolicy?: NSFWPolicyType
185 }): Observable<ResultList<Video>> {
186 const { videoPagination, sort, filter, categoryOneOf, languageOneOf, skipCount, nsfwPolicy } = parameters
187
188 const pagination = this.restService.componentPaginationToRestPagination(videoPagination)
189
190 let params = new HttpParams()
191 params = this.restService.addRestGetParams(params, pagination, sort)
192
193 if (filter) params = params.set('filter', filter)
194 if (skipCount) params = params.set('skipCount', skipCount + '')
195
196 if (nsfwPolicy) {
197 params = params.set('nsfw', this.nsfwPolicyToParam(nsfwPolicy))
198 }
199
200 if (languageOneOf) {
201 for (const l of languageOneOf) {
202 params = params.append('languageOneOf[]', l)
203 }
204 }
205
206 if (categoryOneOf) {
207 for (const c of categoryOneOf) {
208 params = params.append('categoryOneOf[]', c + '')
209 }
210 }
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) {
221 const feeds = [
222 {
223 format: FeedFormat.RSS,
224 label: 'media rss 2.0',
225 url: VideoService.BASE_FEEDS_URL + FeedFormat.RSS.toLowerCase()
226 },
227 {
228 format: FeedFormat.ATOM,
229 label: 'atom 1.0',
230 url: VideoService.BASE_FEEDS_URL + FeedFormat.ATOM.toLowerCase()
231 },
232 {
233 format: FeedFormat.JSON,
234 label: 'json 1.0',
235 url: VideoService.BASE_FEEDS_URL + 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, filter?: VideoFilter, categoryOneOf?: number[]) {
249 let params = this.restService.addRestGetParams(new HttpParams(), undefined, sort)
250
251 if (filter) params = params.set('filter', filter)
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 getVideoFileMetadata (metadataUrl: string) {
277 return this.authHttp
278 .get<VideoFileMetadata>(metadataUrl)
279 .pipe(
280 catchError(err => this.restExtractor.handleError(err))
281 )
282 }
283
284 removeVideo (id: number) {
285 return this.authHttp
286 .delete(VideoService.BASE_VIDEO_URL + id)
287 .pipe(
288 map(this.restExtractor.extractDataBool),
289 catchError(err => this.restExtractor.handleError(err))
290 )
291 }
292
293 loadCompleteDescription (descriptionPath: string) {
294 return this.authHttp
295 .get<{ description: string }>(environment.apiUrl + descriptionPath)
296 .pipe(
297 map(res => res.description),
298 catchError(err => this.restExtractor.handleError(err))
299 )
300 }
301
302 setVideoLike (id: number) {
303 return this.setVideoRate(id, 'like')
304 }
305
306 setVideoDislike (id: number) {
307 return this.setVideoRate(id, 'dislike')
308 }
309
310 unsetVideoLike (id: number) {
311 return this.setVideoRate(id, 'none')
312 }
313
314 getUserVideoRating (id: number) {
315 const url = UserService.BASE_USERS_URL + 'me/videos/' + id + '/rating'
316
317 return this.authHttp.get<UserVideoRate>(url)
318 .pipe(catchError(err => this.restExtractor.handleError(err)))
319 }
320
321 extractVideos (result: ResultList<VideoServerModel>) {
322 return this.serverService.getServerLocale()
323 .pipe(
324 map(translations => {
325 const videosJson = result.data
326 const totalVideos = result.total
327 const videos: Video[] = []
328
329 for (const videoJson of videosJson) {
330 videos.push(new Video(videoJson, translations))
331 }
332
333 return { total: totalVideos, data: videos }
334 })
335 )
336 }
337
338 explainedPrivacyLabels (privacies: VideoConstant<VideoPrivacy>[]) {
339 const base = [
340 {
341 id: VideoPrivacy.PRIVATE,
342 description: $localize`Only I can see this video`
343 },
344 {
345 id: VideoPrivacy.UNLISTED,
346 description: $localize`Only shareable via a private link`
347 },
348 {
349 id: VideoPrivacy.PUBLIC,
350 description: $localize`Anyone can see this video`
351 },
352 {
353 id: VideoPrivacy.INTERNAL,
354 description: $localize`Only users of this instance can see this video`
355 }
356 ]
357
358 return base
359 .filter(o => !!privacies.find(p => p.id === o.id)) // filter down to privacies that where in the input
360 .map(o => ({ ...privacies[o.id - 1], ...o })) // merge the input privacies that contain a label, and extend them with a description
361 }
362
363 nsfwPolicyToParam (nsfwPolicy: NSFWPolicyType) {
364 return nsfwPolicy === 'do_not_list'
365 ? 'false'
366 : 'both'
367 }
368
369 private setVideoRate (id: number, rateType: UserVideoRateType) {
370 const url = VideoService.BASE_VIDEO_URL + id + '/rate'
371 const body: UserVideoRateUpdate = {
372 rating: rateType
373 }
374
375 return this.authHttp
376 .put(url, body)
377 .pipe(
378 map(this.restExtractor.extractDataBool),
379 catchError(err => this.restExtractor.handleError(err))
380 )
381 }
382 }