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'
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
52 this.videoExistsInPlaylistObservable = merge(
55 bulkGet: this.doVideosExistInPlaylist.bind(this),
56 notifierObservable: this.videoExistsInPlaylistNotifier
57 }).pipe(map(({ response }) => response)),
59 this.videoExistsInPlaylistCacheSubject
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)
67 let params = new HttpParams()
68 params = this.restService.addRestGetParams(params, pagination)
70 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
72 switchMap(res => this.extractPlaylists(res)),
73 catchError(err => this.restExtractor.handleError(err))
77 listMyPlaylistWithCache (user: AuthUser, search?: string) {
79 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
80 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
83 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
87 this.myAccountPlaylistCacheRunning = undefined
88 this.myAccountPlaylistCache = result
94 if (!search) this.myAccountPlaylistCacheRunning = obs
98 listAccountPlaylists (
100 componentPagination: ComponentPaginationLight,
103 ): Observable<ResultList<VideoPlaylist>> {
104 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
105 const pagination = componentPagination
106 ? this.restService.componentPaginationToRestPagination(componentPagination)
109 let params = new HttpParams()
110 params = this.restService.addRestGetParams(params, pagination, sort)
111 if (search) params = this.restService.addObjectParams(params, { search })
113 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
115 switchMap(res => this.extractPlaylists(res)),
116 catchError(err => this.restExtractor.handleError(err))
120 getVideoPlaylist (id: string | number) {
121 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
123 return this.authHttp.get<VideoPlaylist>(url)
125 switchMap(res => this.extractPlaylist(res)),
126 catchError(err => this.restExtractor.handleError(err))
130 createVideoPlaylist (body: VideoPlaylistCreate) {
131 const data = objectToFormData(body)
133 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
136 if (!this.myAccountPlaylistCache) return
138 this.myAccountPlaylistCache.total++
140 this.myAccountPlaylistCache.data.push({
141 id: res.videoPlaylist.id,
142 displayName: body.displayName
145 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
147 catchError(err => this.restExtractor.handleError(err))
151 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
152 const data = objectToFormData(body)
154 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
156 map(this.restExtractor.extractDataBool),
158 if (!this.myAccountPlaylistCache) return
160 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
161 playlist.displayName = body.displayName
163 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
165 catchError(err => this.restExtractor.handleError(err))
169 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
170 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
172 map(this.restExtractor.extractDataBool),
174 if (!this.myAccountPlaylistCache) return
176 this.myAccountPlaylistCache.total--
177 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
178 .filter(p => p.id !== videoPlaylist.id)
180 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
182 catchError(err => this.restExtractor.handleError(err))
186 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
187 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
189 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
192 const existsResult = this.videoExistsCache[body.videoId]
195 playlistElementId: res.videoPlaylistElement.id,
196 startTimestamp: body.startTimestamp,
197 stopTimestamp: body.stopTimestamp
200 this.runPlaylistCheck(body.videoId)
202 catchError(err => this.restExtractor.handleError(err))
206 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
207 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
209 map(this.restExtractor.extractDataBool),
211 const existsResult = this.videoExistsCache[videoId]
214 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
216 elem.startTimestamp = body.startTimestamp
217 elem.stopTimestamp = body.stopTimestamp
220 this.runPlaylistCheck(videoId)
222 catchError(err => this.restExtractor.handleError(err))
226 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
227 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
229 map(this.restExtractor.extractDataBool),
233 if (this.videoExistsCache[videoId]) {
234 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
235 .filter(e => e.playlistElementId !== playlistElementId)
238 this.runPlaylistCheck(videoId)
240 catchError(err => this.restExtractor.handleError(err))
244 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
245 const body: VideoPlaylistReorder = {
246 startPosition: oldPosition,
247 insertAfterPosition: newPosition
250 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
252 map(this.restExtractor.extractDataBool),
253 catchError(err => this.restExtractor.handleError(err))
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)
264 let params = new HttpParams()
265 params = this.restService.addRestGetParams(params, pagination)
268 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
270 switchMap(res => this.extractVideoPlaylistElements(res)),
271 catchError(err => this.restExtractor.handleError(err))
275 listenToMyAccountPlaylistsChange () {
276 return this.myAccountPlaylistCacheSubject.asObservable()
279 listenToVideoPlaylistChange (videoId: number) {
280 if (this.videoExistsObservableCache[videoId]) {
281 return this.videoExistsObservableCache[videoId]
284 const obs = this.videoExistsInPlaylistObservable
286 map(existsResult => existsResult[videoId]),
288 tap(result => this.videoExistsCache[videoId] = result)
291 this.videoExistsObservableCache[videoId] = obs
295 runPlaylistCheck (videoId: number) {
296 logger('Running playlist check.')
298 if (this.videoExistsCache[videoId]) {
299 logger('Found cache for %d.', videoId)
301 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
304 logger('Fetching from network for %d.', videoId)
305 return this.videoExistsInPlaylistNotifier.next(videoId)
308 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
309 return this.serverService.getServerLocale()
311 map(translations => {
312 const playlistsJSON = result.data
313 const total = result.total
314 const playlists: VideoPlaylist[] = []
316 for (const playlistJSON of playlistsJSON) {
317 playlists.push(new VideoPlaylist(playlistJSON, translations))
320 return { data: playlists, total }
325 extractPlaylist (playlist: VideoPlaylistServerModel) {
326 return this.serverService.getServerLocale()
327 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
330 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
331 return this.serverService.getServerLocale()
333 map(translations => {
334 const elementsJson = result.data
335 const total = result.total
336 const elements: VideoPlaylistElement[] = []
338 for (const elementJson of elementsJson) {
339 elements.push(new VideoPlaylistElement(elementJson, translations))
342 return { total, data: elements }
347 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
348 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
350 let params = new HttpParams()
351 params = this.restService.addObjectParams(params, { videoIds })
353 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
354 .pipe(catchError(err => this.restExtractor.handleError(err)))