1 import * as debug from 'debug'
2 import { uniq } from 'lodash-es'
3 import { asyncScheduler, merge, Observable, of, ReplaySubject, Subject } from 'rxjs'
4 import { bufferTime, catchError, filter, map, observeOn, share, switchMap, tap } from 'rxjs/operators'
5 import { HttpClient, HttpParams } from '@angular/common/http'
6 import { Injectable, NgZone } from '@angular/core'
7 import { AuthUser, ComponentPaginationLight, RestExtractor, RestService, ServerService } from '@app/core'
8 import { enterZone, leaveZone, objectToFormData } from '@app/helpers'
9 import { Account, AccountService, VideoChannel, VideoChannelService } from '@app/shared/shared-main'
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,
52 private ngZone: NgZone
54 this.videoExistsInPlaylistObservable = merge(
55 this.videoExistsInPlaylistNotifier.pipe(
56 // We leave Angular zone so Protractor does not get stuck
57 bufferTime(500, leaveZone(this.ngZone, asyncScheduler)),
58 filter(videoIds => videoIds.length !== 0),
59 map(videoIds => uniq(videoIds)),
60 observeOn(enterZone(this.ngZone, asyncScheduler)),
61 switchMap(videoIds => this.doVideosExistInPlaylist(videoIds)),
65 this.videoExistsInPlaylistCacheSubject
69 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
70 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
71 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
73 let params = new HttpParams()
74 params = this.restService.addRestGetParams(params, pagination)
76 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
78 switchMap(res => this.extractPlaylists(res)),
79 catchError(err => this.restExtractor.handleError(err))
83 listMyPlaylistWithCache (user: AuthUser, search?: string) {
85 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
86 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
89 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
93 this.myAccountPlaylistCacheRunning = undefined
94 this.myAccountPlaylistCache = result
100 if (!search) this.myAccountPlaylistCacheRunning = obs
104 listAccountPlaylists (
106 componentPagination: ComponentPaginationLight,
109 ): Observable<ResultList<VideoPlaylist>> {
110 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
111 const pagination = componentPagination
112 ? this.restService.componentPaginationToRestPagination(componentPagination)
115 let params = new HttpParams()
116 params = this.restService.addRestGetParams(params, pagination, sort)
117 if (search) params = this.restService.addObjectParams(params, { search })
119 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
121 switchMap(res => this.extractPlaylists(res)),
122 catchError(err => this.restExtractor.handleError(err))
126 getVideoPlaylist (id: string | number) {
127 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
129 return this.authHttp.get<VideoPlaylist>(url)
131 switchMap(res => this.extractPlaylist(res)),
132 catchError(err => this.restExtractor.handleError(err))
136 createVideoPlaylist (body: VideoPlaylistCreate) {
137 const data = objectToFormData(body)
139 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
142 if (!this.myAccountPlaylistCache) return
144 this.myAccountPlaylistCache.total++
146 this.myAccountPlaylistCache.data.push({
147 id: res.videoPlaylist.id,
148 displayName: body.displayName
151 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
153 catchError(err => this.restExtractor.handleError(err))
157 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
158 const data = objectToFormData(body)
160 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
162 map(this.restExtractor.extractDataBool),
164 if (!this.myAccountPlaylistCache) return
166 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
167 playlist.displayName = body.displayName
169 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
171 catchError(err => this.restExtractor.handleError(err))
175 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
176 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
178 map(this.restExtractor.extractDataBool),
180 if (!this.myAccountPlaylistCache) return
182 this.myAccountPlaylistCache.total--
183 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
184 .filter(p => p.id !== videoPlaylist.id)
186 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
188 catchError(err => this.restExtractor.handleError(err))
192 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
193 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
195 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
198 const existsResult = this.videoExistsCache[body.videoId]
201 playlistElementId: res.videoPlaylistElement.id,
202 startTimestamp: body.startTimestamp,
203 stopTimestamp: body.stopTimestamp
206 this.runPlaylistCheck(body.videoId)
208 catchError(err => this.restExtractor.handleError(err))
212 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
213 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
215 map(this.restExtractor.extractDataBool),
217 const existsResult = this.videoExistsCache[videoId]
220 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
222 elem.startTimestamp = body.startTimestamp
223 elem.stopTimestamp = body.stopTimestamp
226 this.runPlaylistCheck(videoId)
228 catchError(err => this.restExtractor.handleError(err))
232 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
233 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
235 map(this.restExtractor.extractDataBool),
239 if (this.videoExistsCache[videoId]) {
240 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
241 .filter(e => e.playlistElementId !== playlistElementId)
244 this.runPlaylistCheck(videoId)
246 catchError(err => this.restExtractor.handleError(err))
250 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
251 const body: VideoPlaylistReorder = {
252 startPosition: oldPosition,
253 insertAfterPosition: newPosition
256 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
258 map(this.restExtractor.extractDataBool),
259 catchError(err => this.restExtractor.handleError(err))
264 videoPlaylistId: number | string,
265 componentPagination: ComponentPaginationLight
266 ): Observable<ResultList<VideoPlaylistElement>> {
267 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylistId + '/videos'
268 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
270 let params = new HttpParams()
271 params = this.restService.addRestGetParams(params, pagination)
274 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
276 switchMap(res => this.extractVideoPlaylistElements(res)),
277 catchError(err => this.restExtractor.handleError(err))
281 listenToMyAccountPlaylistsChange () {
282 return this.myAccountPlaylistCacheSubject.asObservable()
285 listenToVideoPlaylistChange (videoId: number) {
286 if (this.videoExistsObservableCache[ videoId ]) {
287 return this.videoExistsObservableCache[ videoId ]
290 const obs = this.videoExistsInPlaylistObservable
292 map(existsResult => existsResult[ videoId ]),
294 tap(result => this.videoExistsCache[ videoId ] = result)
297 this.videoExistsObservableCache[ videoId ] = obs
301 runPlaylistCheck (videoId: number) {
302 logger('Running playlist check.')
304 if (this.videoExistsCache[videoId]) {
305 logger('Found cache for %d.', videoId)
307 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
310 logger('Fetching from network for %d.', videoId)
311 return this.videoExistsInPlaylistNotifier.next(videoId)
314 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
315 return this.serverService.getServerLocale()
317 map(translations => {
318 const playlistsJSON = result.data
319 const total = result.total
320 const playlists: VideoPlaylist[] = []
322 for (const playlistJSON of playlistsJSON) {
323 playlists.push(new VideoPlaylist(playlistJSON, translations))
326 return { data: playlists, total }
331 extractPlaylist (playlist: VideoPlaylistServerModel) {
332 return this.serverService.getServerLocale()
333 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
336 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
337 return this.serverService.getServerLocale()
339 map(translations => {
340 const elementsJson = result.data
341 const total = result.total
342 const elements: VideoPlaylistElement[] = []
344 for (const elementJson of elementsJson) {
345 elements.push(new VideoPlaylistElement(elementJson, translations))
348 return { total, data: elements }
353 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
354 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
356 let params = new HttpParams()
357 params = this.restService.addObjectParams(params, { videoIds })
359 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
360 .pipe(catchError(err => this.restExtractor.handleError(err)))