]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/shared-video-playlist/video-playlist.service.ts
Fetch things in bulk for the homepage
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / shared-video-playlist / video-playlist.service.ts
CommitLineData
67ed6552 1import * as debug from 'debug'
3da38d6e
C
2import { merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
3import { catchError, filter, map, share, switchMap, tap } from 'rxjs/operators'
f0a39880 4import { HttpClient, HttpParams } from '@angular/common/http'
67ed6552
C
5import { Injectable, NgZone } from '@angular/core'
6import { AuthUser, ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
3da38d6e 7import { buildBulkObservable, objectToFormData } from '@app/helpers'
67ed6552
C
8import { Account, AccountService, VideoChannel, VideoChannelService } from '@app/shared/shared-main'
9import {
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'
830b4faf 21import { environment } from '../../../environments/environment'
67ed6552
C
22import { VideoPlaylistElement } from './video-playlist-element.model'
23import { VideoPlaylist } from './video-playlist.model'
51b34a11
C
24
25const logger = debug('peertube:playlists:VideoPlaylistService')
26
93d54cc7 27export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
830b4faf
C
28
29@Injectable()
30export class VideoPlaylistService {
31 static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
f0a39880
C
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
51b34a11
C
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
f44a284a 43 private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
51b34a11 44 private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
830b4faf
C
45
46 constructor (
47 private authHttp: HttpClient,
48 private serverService: ServerService,
f0a39880 49 private restExtractor: RestExtractor,
44d4ee4f
C
50 private restService: RestService,
51 private ngZone: NgZone
f0a39880 52 ) {
51b34a11 53 this.videoExistsInPlaylistObservable = merge(
3da38d6e
C
54 buildBulkObservable({
55 time: 500,
56 ngZone: this.ngZone,
57 bulkGet: this.doVideosExistInPlaylist.bind(this),
58 notifierObservable: this.videoExistsInPlaylistNotifier
59 }),
51b34a11
C
60
61 this.videoExistsInPlaylistCacheSubject
f0a39880
C
62 )
63 }
830b4faf 64
440d39c5 65 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
830b4faf 66 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
ad453580 67 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
830b4faf 68
ad453580
C
69 let params = new HttpParams()
70 params = this.restService.addRestGetParams(params, pagination)
71
72 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
830b4faf
C
73 .pipe(
74 switchMap(res => this.extractPlaylists(res)),
75 catchError(err => this.restExtractor.handleError(err))
76 )
77 }
78
51b34a11 79 listMyPlaylistWithCache (user: AuthUser, search?: string) {
6b0c3c7c 80 if (!search) {
f44a284a 81 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
6b0c3c7c
C
82 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
83 }
84
f44a284a 85 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
51b34a11
C
86 .pipe(
87 tap(result => {
6b0c3c7c 88 if (!search) {
f44a284a 89 this.myAccountPlaylistCacheRunning = undefined
6b0c3c7c
C
90 this.myAccountPlaylistCache = result
91 }
f44a284a
C
92 }),
93 share()
51b34a11 94 )
f44a284a
C
95
96 if (!search) this.myAccountPlaylistCacheRunning = obs
97 return obs
51b34a11
C
98 }
99
c06af501
RK
100 listAccountPlaylists (
101 account: Account,
440d39c5 102 componentPagination: ComponentPaginationLight,
c06af501
RK
103 sort: string,
104 search?: string
105 ): Observable<ResultList<VideoPlaylist>> {
830b4faf 106 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
ad453580
C
107 const pagination = componentPagination
108 ? this.restService.componentPaginationToRestPagination(componentPagination)
109 : undefined
830b4faf 110
f0a39880 111 let params = new HttpParams()
ad453580 112 params = this.restService.addRestGetParams(params, pagination, sort)
c06af501 113 if (search) params = this.restService.addObjectParams(params, { search })
f0a39880
C
114
115 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
830b4faf
C
116 .pipe(
117 switchMap(res => this.extractPlaylists(res)),
118 catchError(err => this.restExtractor.handleError(err))
119 )
120 }
121
122 getVideoPlaylist (id: string | number) {
123 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
124
125 return this.authHttp.get<VideoPlaylist>(url)
126 .pipe(
127 switchMap(res => this.extractPlaylist(res)),
128 catchError(err => this.restExtractor.handleError(err))
129 )
130 }
131
132 createVideoPlaylist (body: VideoPlaylistCreate) {
133 const data = objectToFormData(body)
134
f0a39880 135 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
830b4faf 136 .pipe(
51b34a11 137 tap(res => {
ec10e8ed
C
138 if (!this.myAccountPlaylistCache) return
139
51b34a11
C
140 this.myAccountPlaylistCache.total++
141
142 this.myAccountPlaylistCache.data.push({
143 id: res.videoPlaylist.id,
144 displayName: body.displayName
145 })
146
147 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
148 }),
830b4faf
C
149 catchError(err => this.restExtractor.handleError(err))
150 )
151 }
152
153 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
154 const data = objectToFormData(body)
155
156 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
157 .pipe(
158 map(this.restExtractor.extractDataBool),
51b34a11 159 tap(() => {
ec10e8ed
C
160 if (!this.myAccountPlaylistCache) return
161
51b34a11
C
162 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
163 playlist.displayName = body.displayName
164
165 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
166 }),
830b4faf
C
167 catchError(err => this.restExtractor.handleError(err))
168 )
169 }
170
171 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
172 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
173 .pipe(
174 map(this.restExtractor.extractDataBool),
51b34a11 175 tap(() => {
ec10e8ed
C
176 if (!this.myAccountPlaylistCache) return
177
51b34a11
C
178 this.myAccountPlaylistCache.total--
179 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
180 .filter(p => p.id !== videoPlaylist.id)
181
182 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
183 }),
830b4faf
C
184 catchError(err => this.restExtractor.handleError(err))
185 )
186 }
187
f0a39880 188 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
a3671f07
C
189 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
190
191 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
51b34a11
C
192 .pipe(
193 tap(res => {
194 const existsResult = this.videoExistsCache[body.videoId]
195 existsResult.push({
196 playlistId,
197 playlistElementId: res.videoPlaylistElement.id,
198 startTimestamp: body.startTimestamp,
199 stopTimestamp: body.stopTimestamp
200 })
201
202 this.runPlaylistCheck(body.videoId)
203 }),
204 catchError(err => this.restExtractor.handleError(err))
205 )
f0a39880
C
206 }
207
51b34a11 208 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
bfbd9128 209 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
f0a39880
C
210 .pipe(
211 map(this.restExtractor.extractDataBool),
51b34a11
C
212 tap(() => {
213 const existsResult = this.videoExistsCache[videoId]
51b34a11 214
50a1e91d
C
215 if (existsResult) {
216 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
217
218 elem.startTimestamp = body.startTimestamp
219 elem.stopTimestamp = body.stopTimestamp
220 }
51b34a11
C
221
222 this.runPlaylistCheck(videoId)
223 }),
f0a39880
C
224 catchError(err => this.restExtractor.handleError(err))
225 )
226 }
227
51b34a11 228 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
bfbd9128 229 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
f0a39880
C
230 .pipe(
231 map(this.restExtractor.extractDataBool),
51b34a11
C
232 tap(() => {
233 if (!videoId) return
234
60ea8f7a
C
235 if (this.videoExistsCache[videoId]) {
236 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
237 .filter(e => e.playlistElementId !== playlistElementId)
238 }
239
51b34a11
C
240 this.runPlaylistCheck(videoId)
241 }),
f0a39880
C
242 catchError(err => this.restExtractor.handleError(err))
243 )
244 }
245
15e9d5ca
C
246 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
247 const body: VideoPlaylistReorder = {
248 startPosition: oldPosition,
249 insertAfterPosition: newPosition
250 }
251
252 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
253 .pipe(
254 map(this.restExtractor.extractDataBool),
255 catchError(err => this.restExtractor.handleError(err))
256 )
257 }
258
bfbd9128
C
259 getPlaylistVideos (
260 videoPlaylistId: number | string,
440d39c5 261 componentPagination: ComponentPaginationLight
bfbd9128
C
262 ): Observable<ResultList<VideoPlaylistElement>> {
263 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylistId + '/videos'
264 const pagination = this.restService.componentPaginationToRestPagination(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
51b34a11
C
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 logger('Running playlist check.')
299
300 if (this.videoExistsCache[videoId]) {
301 logger('Found cache for %d.', videoId)
302
303 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
304 }
f0a39880 305
51b34a11
C
306 logger('Fetching from network for %d.', videoId)
307 return this.videoExistsInPlaylistNotifier.next(videoId)
f0a39880
C
308 }
309
830b4faf 310 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
ba430d75 311 return this.serverService.getServerLocale()
830b4faf
C
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) {
ba430d75 328 return this.serverService.getServerLocale()
830b4faf
C
329 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
330 }
f0a39880 331
bfbd9128 332 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
ba430d75 333 return this.serverService.getServerLocale()
bfbd9128
C
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
51b34a11 349 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
f0a39880 350 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
f0a39880 351
c06af501 352 let params = new HttpParams()
f0a39880
C
353 params = this.restService.addObjectParams(params, { videoIds })
354
b7819090 355 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
f0a39880
C
356 .pipe(catchError(err => this.restExtractor.handleError(err)))
357 }
830b4faf 358}