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