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, HttpContext, 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 { NGX_LOADING_BAR_IGNORED } from '@ngx-loading-bar/http-client'
13 VideoPlaylist as VideoPlaylistServerModel,
15 VideoPlaylistElement as ServerVideoPlaylistElement,
16 VideoPlaylistElementCreate,
17 VideoPlaylistElementUpdate,
20 VideosExistInPlaylists
21 } from '@shared/models'
22 import { environment } from '../../../environments/environment'
23 import { VideoPlaylistElement } from './video-playlist-element.model'
24 import { VideoPlaylist } from './video-playlist.model'
26 const logger = debug('peertube:playlists:VideoPlaylistService')
28 export type CachedPlaylist = VideoPlaylist | { id: number, displayName: string }
31 export class VideoPlaylistService {
32 static BASE_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/video-playlists/'
33 static MY_VIDEO_PLAYLIST_URL = environment.apiUrl + '/api/v1/users/me/video-playlists/'
35 // Use a replay subject because we "next" a value before subscribing
36 private videoExistsInPlaylistNotifier = new ReplaySubject<number>(1)
37 private videoExistsInPlaylistCacheSubject = new Subject<VideosExistInPlaylists>()
38 private readonly videoExistsInPlaylistObservable: Observable<VideosExistInPlaylists>
40 private videoExistsObservableCache: { [ id: number ]: Observable<VideoExistInPlaylist[]> } = {}
41 private videoExistsCache: { [ id: number ]: VideoExistInPlaylist[] } = {}
43 private myAccountPlaylistCache: ResultList<CachedPlaylist> = undefined
44 private myAccountPlaylistCacheRunning: Observable<ResultList<CachedPlaylist>>
45 private myAccountPlaylistCacheSubject = new Subject<ResultList<CachedPlaylist>>()
48 private authHttp: HttpClient,
49 private serverService: ServerService,
50 private restExtractor: RestExtractor,
51 private restService: RestService
53 this.videoExistsInPlaylistObservable = merge(
56 bulkGet: this.doVideosExistInPlaylist.bind(this),
57 notifierObservable: this.videoExistsInPlaylistNotifier
58 }).pipe(map(({ response }) => response)),
60 this.videoExistsInPlaylistCacheSubject
64 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
65 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
66 const pagination = this.restService.componentToRestPagination(componentPagination)
68 let params = new HttpParams()
69 params = this.restService.addRestGetParams(params, pagination)
71 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
73 switchMap(res => this.extractPlaylists(res)),
74 catchError(err => this.restExtractor.handleError(err))
78 listMyPlaylistWithCache (user: AuthUser, search?: string) {
80 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
81 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
84 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
88 this.myAccountPlaylistCacheRunning = undefined
89 this.myAccountPlaylistCache = result
95 if (!search) this.myAccountPlaylistCacheRunning = obs
99 listAccountPlaylists (
101 componentPagination: ComponentPaginationLight,
104 ): Observable<ResultList<VideoPlaylist>> {
105 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
106 const pagination = componentPagination
107 ? this.restService.componentToRestPagination(componentPagination)
110 let params = new HttpParams()
111 params = this.restService.addRestGetParams(params, pagination, sort)
112 if (search) params = this.restService.addObjectParams(params, { search })
114 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
116 switchMap(res => this.extractPlaylists(res)),
117 catchError(err => this.restExtractor.handleError(err))
121 getVideoPlaylist (id: string | number) {
122 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
124 return this.authHttp.get<VideoPlaylist>(url)
126 switchMap(res => this.extractPlaylist(res)),
127 catchError(err => this.restExtractor.handleError(err))
131 createVideoPlaylist (body: VideoPlaylistCreate) {
132 const data = objectToFormData(body)
134 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
137 if (!this.myAccountPlaylistCache) return
139 this.myAccountPlaylistCache.total++
141 this.myAccountPlaylistCache.data.push({
142 id: res.videoPlaylist.id,
143 displayName: body.displayName
146 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
148 catchError(err => this.restExtractor.handleError(err))
152 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
153 const data = objectToFormData(body)
155 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
157 map(this.restExtractor.extractDataBool),
159 if (!this.myAccountPlaylistCache) return
161 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
162 playlist.displayName = body.displayName
164 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
166 catchError(err => this.restExtractor.handleError(err))
170 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
171 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
173 map(this.restExtractor.extractDataBool),
175 if (!this.myAccountPlaylistCache) return
177 this.myAccountPlaylistCache.total--
178 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
179 .filter(p => p.id !== videoPlaylist.id)
181 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
183 catchError(err => this.restExtractor.handleError(err))
187 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
188 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
190 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
193 const existsResult = this.videoExistsCache[body.videoId]
196 playlistElementId: res.videoPlaylistElement.id,
197 startTimestamp: body.startTimestamp,
198 stopTimestamp: body.stopTimestamp
201 this.runPlaylistCheck(body.videoId)
203 catchError(err => this.restExtractor.handleError(err))
207 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
208 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
210 map(this.restExtractor.extractDataBool),
212 const existsResult = this.videoExistsCache[videoId]
215 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
217 elem.startTimestamp = body.startTimestamp
218 elem.stopTimestamp = body.stopTimestamp
221 this.runPlaylistCheck(videoId)
223 catchError(err => this.restExtractor.handleError(err))
227 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
228 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
230 map(this.restExtractor.extractDataBool),
234 if (this.videoExistsCache[videoId]) {
235 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
236 .filter(e => e.playlistElementId !== playlistElementId)
239 this.runPlaylistCheck(videoId)
241 catchError(err => this.restExtractor.handleError(err))
245 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
246 const body: VideoPlaylistReorder = {
247 startPosition: oldPosition,
248 insertAfterPosition: newPosition
251 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
253 map(this.restExtractor.extractDataBool),
254 catchError(err => this.restExtractor.handleError(err))
258 getPlaylistVideos (options: {
259 videoPlaylistId: number | string
260 componentPagination: ComponentPaginationLight
261 }): Observable<ResultList<VideoPlaylistElement>> {
262 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + options.videoPlaylistId + '/videos'
263 const pagination = this.restService.componentToRestPagination(options.componentPagination)
265 let params = new HttpParams()
266 params = this.restService.addRestGetParams(params, pagination)
269 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
271 switchMap(res => this.extractVideoPlaylistElements(res)),
272 catchError(err => this.restExtractor.handleError(err))
276 listenToMyAccountPlaylistsChange () {
277 return this.myAccountPlaylistCacheSubject.asObservable()
280 listenToVideoPlaylistChange (videoId: number) {
281 if (this.videoExistsObservableCache[videoId]) {
282 return this.videoExistsObservableCache[videoId]
285 const obs = this.videoExistsInPlaylistObservable
287 map(existsResult => existsResult[videoId]),
289 tap(result => this.videoExistsCache[videoId] = result)
292 this.videoExistsObservableCache[videoId] = obs
296 runPlaylistCheck (videoId: number) {
297 logger('Running playlist check.')
299 if (this.videoExistsCache[videoId]) {
300 logger('Found cache for %d.', videoId)
302 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
305 logger('Fetching from network for %d.', videoId)
306 return this.videoExistsInPlaylistNotifier.next(videoId)
309 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
310 return this.serverService.getServerLocale()
312 map(translations => {
313 const playlistsJSON = result.data
314 const total = result.total
315 const playlists: VideoPlaylist[] = []
317 for (const playlistJSON of playlistsJSON) {
318 playlists.push(new VideoPlaylist(playlistJSON, translations))
321 return { data: playlists, total }
326 extractPlaylist (playlist: VideoPlaylistServerModel) {
327 return this.serverService.getServerLocale()
328 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
331 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
332 return this.serverService.getServerLocale()
334 map(translations => {
335 const elementsJson = result.data
336 const total = result.total
337 const elements: VideoPlaylistElement[] = []
339 for (const elementJson of elementsJson) {
340 elements.push(new VideoPlaylistElement(elementJson, translations))
343 return { total, data: elements }
348 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
349 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
351 let params = new HttpParams()
352 params = this.restService.addObjectParams(params, { videoIds })
354 return this.authHttp.get<VideoExistInPlaylist>(url, { params, context: new HttpContext().set(NGX_LOADING_BAR_IGNORED, true) })
355 .pipe(catchError(err => this.restExtractor.handleError(err)))