]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/shared/shared-video-playlist/video-playlist.service.ts
Try to fix mock server ports
[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, NgZone } 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 private ngZone: NgZone
52 ) {
53 this.videoExistsInPlaylistObservable = merge(
54 buildBulkObservable({
55 time: 500,
56 ngZone: this.ngZone,
57 bulkGet: this.doVideosExistInPlaylist.bind(this),
58 notifierObservable: this.videoExistsInPlaylistNotifier
59 }),
60
61 this.videoExistsInPlaylistCacheSubject
62 )
63 }
64
65 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
66 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
67 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
68
69 let params = new HttpParams()
70 params = this.restService.addRestGetParams(params, pagination)
71
72 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
73 .pipe(
74 switchMap(res => this.extractPlaylists(res)),
75 catchError(err => this.restExtractor.handleError(err))
76 )
77 }
78
79 listMyPlaylistWithCache (user: AuthUser, search?: string) {
80 if (!search) {
81 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
82 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
83 }
84
85 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
86 .pipe(
87 tap(result => {
88 if (!search) {
89 this.myAccountPlaylistCacheRunning = undefined
90 this.myAccountPlaylistCache = result
91 }
92 }),
93 share()
94 )
95
96 if (!search) this.myAccountPlaylistCacheRunning = obs
97 return obs
98 }
99
100 listAccountPlaylists (
101 account: Account,
102 componentPagination: ComponentPaginationLight,
103 sort: string,
104 search?: string
105 ): Observable<ResultList<VideoPlaylist>> {
106 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
107 const pagination = componentPagination
108 ? this.restService.componentPaginationToRestPagination(componentPagination)
109 : undefined
110
111 let params = new HttpParams()
112 params = this.restService.addRestGetParams(params, pagination, sort)
113 if (search) params = this.restService.addObjectParams(params, { search })
114
115 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
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
135 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
136 .pipe(
137 tap(res => {
138 if (!this.myAccountPlaylistCache) return
139
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 }),
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),
159 tap(() => {
160 if (!this.myAccountPlaylistCache) return
161
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 }),
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),
175 tap(() => {
176 if (!this.myAccountPlaylistCache) return
177
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 }),
184 catchError(err => this.restExtractor.handleError(err))
185 )
186 }
187
188 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
189 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
190
191 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
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 )
206 }
207
208 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
209 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
210 .pipe(
211 map(this.restExtractor.extractDataBool),
212 tap(() => {
213 const existsResult = this.videoExistsCache[videoId]
214
215 if (existsResult) {
216 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
217
218 elem.startTimestamp = body.startTimestamp
219 elem.stopTimestamp = body.stopTimestamp
220 }
221
222 this.runPlaylistCheck(videoId)
223 }),
224 catchError(err => this.restExtractor.handleError(err))
225 )
226 }
227
228 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
229 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
230 .pipe(
231 map(this.restExtractor.extractDataBool),
232 tap(() => {
233 if (!videoId) return
234
235 if (this.videoExistsCache[videoId]) {
236 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
237 .filter(e => e.playlistElementId !== playlistElementId)
238 }
239
240 this.runPlaylistCheck(videoId)
241 }),
242 catchError(err => this.restExtractor.handleError(err))
243 )
244 }
245
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
259 getPlaylistVideos (
260 videoPlaylistId: number | string,
261 componentPagination: ComponentPaginationLight
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
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 }
305
306 logger('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, headers: { ignoreLoadingBar: '' } })
356 .pipe(catchError(err => this.restExtractor.handleError(err)))
357 }
358 }