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'
12 VideoPlaylist as VideoPlaylistServerModel,
14 VideoPlaylistElement as ServerVideoPlaylistElement,
15 VideoPlaylistElementCreate,
16 VideoPlaylistElementUpdate,
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'
25 const logger = debug('peertube:playlists:VideoPlaylistService')
27 export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
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/'
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>
39 private videoExistsObservableCache: { [ id: number ]: Observable<VideoExistInPlaylist[]> } = {}
40 private videoExistsCache: { [ id: number ]: VideoExistInPlaylist[] } = {}
42 private myAccountPlaylistCache: ResultList<CachedPlaylist> = undefined
43 private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
44 private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
47 private authHttp: HttpClient,
48 private serverService: ServerService,
49 private restExtractor: RestExtractor,
50 private restService: RestService,
51 private ngZone: NgZone
53 this.videoExistsInPlaylistObservable = merge(
57 bulkGet: this.doVideosExistInPlaylist.bind(this),
58 notifierObservable: this.videoExistsInPlaylistNotifier
61 this.videoExistsInPlaylistCacheSubject
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)
69 let params = new HttpParams()
70 params = this.restService.addRestGetParams(params, pagination)
72 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
74 switchMap(res => this.extractPlaylists(res)),
75 catchError(err => this.restExtractor.handleError(err))
79 listMyPlaylistWithCache (user: AuthUser, search?: string) {
81 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
82 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
85 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
89 this.myAccountPlaylistCacheRunning = undefined
90 this.myAccountPlaylistCache = result
96 if (!search) this.myAccountPlaylistCacheRunning = obs
100 listAccountPlaylists (
102 componentPagination: ComponentPaginationLight,
105 ): Observable<ResultList<VideoPlaylist>> {
106 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
107 const pagination = componentPagination
108 ? this.restService.componentPaginationToRestPagination(componentPagination)
111 let params = new HttpParams()
112 params = this.restService.addRestGetParams(params, pagination, sort)
113 if (search) params = this.restService.addObjectParams(params, { search })
115 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
117 switchMap(res => this.extractPlaylists(res)),
118 catchError(err => this.restExtractor.handleError(err))
122 getVideoPlaylist (id: string | number) {
123 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
125 return this.authHttp.get<VideoPlaylist>(url)
127 switchMap(res => this.extractPlaylist(res)),
128 catchError(err => this.restExtractor.handleError(err))
132 createVideoPlaylist (body: VideoPlaylistCreate) {
133 const data = objectToFormData(body)
135 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
138 if (!this.myAccountPlaylistCache) return
140 this.myAccountPlaylistCache.total++
142 this.myAccountPlaylistCache.data.push({
143 id: res.videoPlaylist.id,
144 displayName: body.displayName
147 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
149 catchError(err => this.restExtractor.handleError(err))
153 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
154 const data = objectToFormData(body)
156 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
158 map(this.restExtractor.extractDataBool),
160 if (!this.myAccountPlaylistCache) return
162 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
163 playlist.displayName = body.displayName
165 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
167 catchError(err => this.restExtractor.handleError(err))
171 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
172 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
174 map(this.restExtractor.extractDataBool),
176 if (!this.myAccountPlaylistCache) return
178 this.myAccountPlaylistCache.total--
179 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
180 .filter(p => p.id !== videoPlaylist.id)
182 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
184 catchError(err => this.restExtractor.handleError(err))
188 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
189 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
191 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
194 const existsResult = this.videoExistsCache[body.videoId]
197 playlistElementId: res.videoPlaylistElement.id,
198 startTimestamp: body.startTimestamp,
199 stopTimestamp: body.stopTimestamp
202 this.runPlaylistCheck(body.videoId)
204 catchError(err => this.restExtractor.handleError(err))
208 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
209 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
211 map(this.restExtractor.extractDataBool),
213 const existsResult = this.videoExistsCache[videoId]
216 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
218 elem.startTimestamp = body.startTimestamp
219 elem.stopTimestamp = body.stopTimestamp
222 this.runPlaylistCheck(videoId)
224 catchError(err => this.restExtractor.handleError(err))
228 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
229 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
231 map(this.restExtractor.extractDataBool),
235 if (this.videoExistsCache[videoId]) {
236 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
237 .filter(e => e.playlistElementId !== playlistElementId)
240 this.runPlaylistCheck(videoId)
242 catchError(err => this.restExtractor.handleError(err))
246 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
247 const body: VideoPlaylistReorder = {
248 startPosition: oldPosition,
249 insertAfterPosition: newPosition
252 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
254 map(this.restExtractor.extractDataBool),
255 catchError(err => this.restExtractor.handleError(err))
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)
266 let params = new HttpParams()
267 params = this.restService.addRestGetParams(params, pagination)
270 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
272 switchMap(res => this.extractVideoPlaylistElements(res)),
273 catchError(err => this.restExtractor.handleError(err))
277 listenToMyAccountPlaylistsChange () {
278 return this.myAccountPlaylistCacheSubject.asObservable()
281 listenToVideoPlaylistChange (videoId: number) {
282 if (this.videoExistsObservableCache[videoId]) {
283 return this.videoExistsObservableCache[videoId]
286 const obs = this.videoExistsInPlaylistObservable
288 map(existsResult => existsResult[videoId]),
290 tap(result => this.videoExistsCache[videoId] = result)
293 this.videoExistsObservableCache[videoId] = obs
297 runPlaylistCheck (videoId: number) {
298 logger('Running playlist check.')
300 if (this.videoExistsCache[videoId]) {
301 logger('Found cache for %d.', videoId)
303 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
306 logger('Fetching from network for %d.', videoId)
307 return this.videoExistsInPlaylistNotifier.next(videoId)
310 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
311 return this.serverService.getServerLocale()
313 map(translations => {
314 const playlistsJSON = result.data
315 const total = result.total
316 const playlists: VideoPlaylist[] = []
318 for (const playlistJSON of playlistsJSON) {
319 playlists.push(new VideoPlaylist(playlistJSON, translations))
322 return { data: playlists, total }
327 extractPlaylist (playlist: VideoPlaylistServerModel) {
328 return this.serverService.getServerLocale()
329 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
332 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
333 return this.serverService.getServerLocale()
335 map(translations => {
336 const elementsJson = result.data
337 const total = result.total
338 const elements: VideoPlaylistElement[] = []
340 for (const elementJson of elementsJson) {
341 elements.push(new VideoPlaylistElement(elementJson, translations))
344 return { total, data: elements }
349 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
350 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
352 let params = new HttpParams()
353 params = this.restService.addObjectParams(params, { videoIds })
355 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
356 .pipe(catchError(err => this.restExtractor.handleError(err)))