]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-playlist/video-playlist.service.ts
Fix ngx loading bar deprecation
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-playlist / video-playlist.service.ts
1 import * as debug from 'debug'
2 import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
3 import { catchError, filter, map, share, switchMap, tap } from 'rxjs/operators'
4 import { HttpClient, HttpContext, HttpParams } from '@angular/common/http'
5 import { Injectable } from '@angular/core'
6 import { AuthUser, ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
7 import { buildBulkObservable, objectToFormData } from '@app/helpers'
8 import { Account, AccountService, VideoChannel, VideoChannelService } from '@app/shared/shared-main'
9 import { NGX_LOADING_BAR_IGNORED } from '@ngx-loading-bar/http-client'
10 import {
11 ResultList,
12 VideoExistInPlaylist,
13 VideoPlaylist as VideoPlaylistServerModel,
14 VideoPlaylistCreate,
15 VideoPlaylistElement as ServerVideoPlaylistElement,
16 VideoPlaylistElementCreate,
17 VideoPlaylistElementUpdate,
18 VideoPlaylistReorder,
19 VideoPlaylistUpdate,
20 VideosExistInPlaylists
21 } from '@shared/models'
22 import { environment } from '../../../environments/environment'
23 import { VideoPlaylistElement } from './video-playlist-element.model'
24 import { VideoPlaylist } from './video-playlist.model'
25
26 const logger = debug('peertube:playlists:VideoPlaylistService')
27
28 export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
29
30 @Injectable()
31 export class VideoPlaylistService {
32 static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
33 static MY_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/users/me/video-playlists/'
34
35 // Use a replay subject because we "next" a value before subscribing
36 private videoExistsInPlaylistNotifier = new ReplaySubject<number>(1)
37 private videoExistsInPlaylistCacheSubject = new Subject<VideosExistInPlaylists>()
38 private readonly videoExistsInPlaylistObservable: Observable<VideosExistInPlaylists>
39
40 private videoExistsObservableCache: { [ id: number ]: Observable<VideoExistInPlaylist[]> } = {}
41 private videoExistsCache: { [ id: number ]: VideoExistInPlaylist[] } = {}
42
43 private myAccountPlaylistCache: ResultList<CachedPlaylist> = undefined
44 private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
45 private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
46
47 constructor (
48 private authHttp: HttpClient,
49 private serverService: ServerService,
50 private restExtractor: RestExtractor,
51 private restService: RestService
52 ) {
53 this.videoExistsInPlaylistObservable = merge(
54 buildBulkObservable({
55 time: 500,
56 bulkGet: this.doVideosExistInPlaylist.bind(this),
57 notifierObservable: this.videoExistsInPlaylistNotifier
58 }).pipe(map(({ response }) => response)),
59
60 this.videoExistsInPlaylistCacheSubject
61 )
62 }
63
64 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
65 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
66 const pagination = this.restService.componentToRestPagination(componentPagination)
67
68 let params = new HttpParams()
69 params = this.restService.addRestGetParams(params, pagination)
70
71 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
72 .pipe(
73 switchMap(res => this.extractPlaylists(res)),
74 catchError(err => this.restExtractor.handleError(err))
75 )
76 }
77
78 listMyPlaylistWithCache (user: AuthUser, search?: string) {
79 if (!search) {
80 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
81 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
82 }
83
84 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
85 .pipe(
86 tap(result => {
87 if (!search) {
88 this.myAccountPlaylistCacheRunning = undefined
89 this.myAccountPlaylistCache = result
90 }
91 }),
92 share()
93 )
94
95 if (!search) this.myAccountPlaylistCacheRunning = obs
96 return obs
97 }
98
99 listAccountPlaylists (
100 account: Account,
101 componentPagination: ComponentPaginationLight,
102 sort: string,
103 search?: string
104 ): Observable<ResultList<VideoPlaylist>> {
105 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
106 const pagination = componentPagination
107 ? this.restService.componentToRestPagination(componentPagination)
108 : undefined
109
110 let params = new HttpParams()
111 params = this.restService.addRestGetParams(params, pagination, sort)
112 if (search) params = this.restService.addObjectParams(params, { search })
113
114 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
115 .pipe(
116 switchMap(res => this.extractPlaylists(res)),
117 catchError(err => this.restExtractor.handleError(err))
118 )
119 }
120
121 getVideoPlaylist (id: string | number) {
122 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
123
124 return this.authHttp.get<VideoPlaylist>(url)
125 .pipe(
126 switchMap(res => this.extractPlaylist(res)),
127 catchError(err => this.restExtractor.handleError(err))
128 )
129 }
130
131 createVideoPlaylist (body: VideoPlaylistCreate) {
132 const data = objectToFormData(body)
133
134 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
135 .pipe(
136 tap(res => {
137 if (!this.myAccountPlaylistCache) return
138
139 this.myAccountPlaylistCache.total++
140
141 this.myAccountPlaylistCache.data.push({
142 id: res.videoPlaylist.id,
143 displayName: body.displayName
144 })
145
146 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
147 }),
148 catchError(err => this.restExtractor.handleError(err))
149 )
150 }
151
152 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
153 const data = objectToFormData(body)
154
155 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
156 .pipe(
157 map(this.restExtractor.extractDataBool),
158 tap(() => {
159 if (!this.myAccountPlaylistCache) return
160
161 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
162 playlist.displayName = body.displayName
163
164 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
165 }),
166 catchError(err => this.restExtractor.handleError(err))
167 )
168 }
169
170 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
171 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
172 .pipe(
173 map(this.restExtractor.extractDataBool),
174 tap(() => {
175 if (!this.myAccountPlaylistCache) return
176
177 this.myAccountPlaylistCache.total--
178 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
179 .filter(p => p.id !== videoPlaylist.id)
180
181 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
182 }),
183 catchError(err => this.restExtractor.handleError(err))
184 )
185 }
186
187 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
188 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
189
190 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
191 .pipe(
192 tap(res => {
193 const existsResult = this.videoExistsCache[body.videoId]
194 existsResult.push({
195 playlistId,
196 playlistElementId: res.videoPlaylistElement.id,
197 startTimestamp: body.startTimestamp,
198 stopTimestamp: body.stopTimestamp
199 })
200
201 this.runPlaylistCheck(body.videoId)
202 }),
203 catchError(err => this.restExtractor.handleError(err))
204 )
205 }
206
207 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
208 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
209 .pipe(
210 map(this.restExtractor.extractDataBool),
211 tap(() => {
212 const existsResult = this.videoExistsCache[videoId]
213
214 if (existsResult) {
215 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
216
217 elem.startTimestamp = body.startTimestamp
218 elem.stopTimestamp = body.stopTimestamp
219 }
220
221 this.runPlaylistCheck(videoId)
222 }),
223 catchError(err => this.restExtractor.handleError(err))
224 )
225 }
226
227 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
228 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
229 .pipe(
230 map(this.restExtractor.extractDataBool),
231 tap(() => {
232 if (!videoId) return
233
234 if (this.videoExistsCache[videoId]) {
235 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
236 .filter(e => e.playlistElementId !== playlistElementId)
237 }
238
239 this.runPlaylistCheck(videoId)
240 }),
241 catchError(err => this.restExtractor.handleError(err))
242 )
243 }
244
245 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
246 const body: VideoPlaylistReorder = {
247 startPosition: oldPosition,
248 insertAfterPosition: newPosition
249 }
250
251 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
252 .pipe(
253 map(this.restExtractor.extractDataBool),
254 catchError(err => this.restExtractor.handleError(err))
255 )
256 }
257
258 getPlaylistVideos (options: {
259 videoPlaylistId: number | string
260 componentPagination: ComponentPaginationLight
261 }): Observable<ResultList<VideoPlaylistElement>> {
262 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + options.videoPlaylistId + '/videos'
263 const pagination = this.restService.componentToRestPagination(options.componentPagination)
264
265 let params = new HttpParams()
266 params = this.restService.addRestGetParams(params, pagination)
267
268 return this.authHttp
269 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
270 .pipe(
271 switchMap(res => this.extractVideoPlaylistElements(res)),
272 catchError(err => this.restExtractor.handleError(err))
273 )
274 }
275
276 listenToMyAccountPlaylistsChange () {
277 return this.myAccountPlaylistCacheSubject.asObservable()
278 }
279
280 listenToVideoPlaylistChange (videoId: number) {
281 if (this.videoExistsObservableCache[videoId]) {
282 return this.videoExistsObservableCache[videoId]
283 }
284
285 const obs = this.videoExistsInPlaylistObservable
286 .pipe(
287 map(existsResult => existsResult[videoId]),
288 filter(r => !!r),
289 tap(result => this.videoExistsCache[videoId] = result)
290 )
291
292 this.videoExistsObservableCache[videoId] = obs
293 return obs
294 }
295
296 runPlaylistCheck (videoId: number) {
297 logger('Running playlist check.')
298
299 if (this.videoExistsCache[videoId]) {
300 logger('Found cache for %d.', videoId)
301
302 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
303 }
304
305 logger('Fetching from network for %d.', videoId)
306 return this.videoExistsInPlaylistNotifier.next(videoId)
307 }
308
309 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
310 return this.serverService.getServerLocale()
311 .pipe(
312 map(translations => {
313 const playlistsJSON = result.data
314 const total = result.total
315 const playlists: VideoPlaylist[] = []
316
317 for (const playlistJSON of playlistsJSON) {
318 playlists.push(new VideoPlaylist(playlistJSON, translations))
319 }
320
321 return { data: playlists, total }
322 })
323 )
324 }
325
326 extractPlaylist (playlist: VideoPlaylistServerModel) {
327 return this.serverService.getServerLocale()
328 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
329 }
330
331 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
332 return this.serverService.getServerLocale()
333 .pipe(
334 map(translations => {
335 const elementsJson = result.data
336 const total = result.total
337 const elements: VideoPlaylistElement[] = []
338
339 for (const elementJson of elementsJson) {
340 elements.push(new VideoPlaylistElement(elementJson, translations))
341 }
342
343 return { total, data: elements }
344 })
345 )
346 }
347
348 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
349 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
350
351 let params = new HttpParams()
352 params = this.restService.addObjectParams(params, { videoIds })
353
354 return this.authHttp.get<VideoExistInPlaylist>(url, { params, context: new HttpContext().set(NGX_LOADING_BAR_IGNORED, true) })
355 .pipe(catchError(err => this.restExtractor.handleError(err)))
356 }
357 }