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)
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)
173 if (!this.myAccountPlaylistCache) return
175 this.myAccountPlaylistCache.total--
176 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
177 .filter(p => p.id !== videoPlaylist.id)
179 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
181 catchError(err => this.restExtractor.handleError(err))
185 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
186 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
188 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
191 const existsResult = this.videoExistsCache[body.videoId]
194 playlistElementId: res.videoPlaylistElement.id,
195 startTimestamp: body.startTimestamp,
196 stopTimestamp: body.stopTimestamp
199 this.runPlaylistCheck(body.videoId)
201 catchError(err => this.restExtractor.handleError(err))
205 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
206 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
209 const existsResult = this.videoExistsCache[videoId]
212 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
214 elem.startTimestamp = body.startTimestamp
215 elem.stopTimestamp = body.stopTimestamp
218 this.runPlaylistCheck(videoId)
220 catchError(err => this.restExtractor.handleError(err))
224 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
225 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
230 if (this.videoExistsCache[videoId]) {
231 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
232 .filter(e => e.playlistElementId !== playlistElementId)
235 this.runPlaylistCheck(videoId)
237 catchError(err => this.restExtractor.handleError(err))
241 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
242 const body: VideoPlaylistReorder = {
243 startPosition: oldPosition,
244 insertAfterPosition: newPosition
247 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
248 .pipe(catchError(err => this.restExtractor.handleError(err)))
251 getPlaylistVideos (options: {
252 videoPlaylistId: number | string
253 componentPagination: ComponentPaginationLight
254 }): Observable<ResultList<VideoPlaylistElement>> {
255 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + options.videoPlaylistId + '/videos'
256 const pagination = this.restService.componentToRestPagination(options.componentPagination)
258 let params = new HttpParams()
259 params = this.restService.addRestGetParams(params, pagination)
262 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
264 switchMap(res => this.extractVideoPlaylistElements(res)),
265 catchError(err => this.restExtractor.handleError(err))
269 listenToMyAccountPlaylistsChange () {
270 return this.myAccountPlaylistCacheSubject.asObservable()
273 listenToVideoPlaylistChange (videoId: number) {
274 if (this.videoExistsObservableCache[videoId]) {
275 return this.videoExistsObservableCache[videoId]
278 const obs = this.videoExistsInPlaylistObservable
280 map(existsResult => existsResult[videoId]),
282 tap(result => this.videoExistsCache[videoId] = result)
285 this.videoExistsObservableCache[videoId] = obs
289 runPlaylistCheck (videoId: number) {
290 logger('Running playlist check.')
292 if (this.videoExistsCache[videoId]) {
293 logger('Found cache for %d.', videoId)
295 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
298 logger('Fetching from network for %d.', videoId)
299 return this.videoExistsInPlaylistNotifier.next(videoId)
302 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
303 return this.serverService.getServerLocale()
305 map(translations => {
306 const playlistsJSON = result.data
307 const total = result.total
308 const playlists: VideoPlaylist[] = []
310 for (const playlistJSON of playlistsJSON) {
311 playlists.push(new VideoPlaylist(playlistJSON, translations))
314 return { data: playlists, total }
319 extractPlaylist (playlist: VideoPlaylistServerModel) {
320 return this.serverService.getServerLocale()
321 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
324 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
325 return this.serverService.getServerLocale()
327 map(translations => {
328 const elementsJson = result.data
329 const total = result.total
330 const elements: VideoPlaylistElement[] = []
332 for (const elementJson of elementsJson) {
333 elements.push(new VideoPlaylistElement(elementJson, translations))
336 return { total, data: elements }
341 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
342 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
344 let params = new HttpParams()
345 params = this.restService.addObjectParams(params, { videoIds })
347 return this.authHttp.get<VideoExistInPlaylist>(url, { params, context: new HttpContext().set(NGX_LOADING_BAR_IGNORED, true) })
348 .pipe(catchError(err => this.restExtractor.handleError(err)))