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