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, distinctUntilChanged } 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 distinctUntilChanged(),
57 // We leave Angular zone so Protractor does not get stuck
58 bufferTime(500, leaveZone(this.ngZone, asyncScheduler)),
59 filter(videoIds => videoIds.length !== 0),
60 map(videoIds => uniq(videoIds)),
61 observeOn(enterZone(this.ngZone, asyncScheduler)),
62 switchMap(videoIds => this.doVideosExistInPlaylist(videoIds)),
66 this.videoExistsInPlaylistCacheSubject
70 listChannelPlaylists (videoChannel: VideoChannel, componentPagination: ComponentPaginationLight): Observable<ResultList<VideoPlaylist>> {
71 const url = VideoChannelService.BASE_VIDEO_CHANNEL_URL + videoChannel.nameWithHost + '/video-playlists'
72 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
74 let params = new HttpParams()
75 params = this.restService.addRestGetParams(params, pagination)
77 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
79 switchMap(res => this.extractPlaylists(res)),
80 catchError(err => this.restExtractor.handleError(err))
84 listMyPlaylistWithCache (user: AuthUser, search?: string) {
86 if (this.myAccountPlaylistCacheRunning) return this.myAccountPlaylistCacheRunning
87 if (this.myAccountPlaylistCache) return of(this.myAccountPlaylistCache)
90 const obs = this.listAccountPlaylists(user.account, undefined, '-updatedAt', search)
94 this.myAccountPlaylistCacheRunning = undefined
95 this.myAccountPlaylistCache = result
101 if (!search) this.myAccountPlaylistCacheRunning = obs
105 listAccountPlaylists (
107 componentPagination: ComponentPaginationLight,
110 ): Observable<ResultList<VideoPlaylist>> {
111 const url = AccountService.BASE_ACCOUNT_URL + account.nameWithHost + '/video-playlists'
112 const pagination = componentPagination
113 ? this.restService.componentPaginationToRestPagination(componentPagination)
116 let params = new HttpParams()
117 params = this.restService.addRestGetParams(params, pagination, sort)
118 if (search) params = this.restService.addObjectParams(params, { search })
120 return this.authHttp.get<ResultList<VideoPlaylist>>(url, { params })
122 switchMap(res => this.extractPlaylists(res)),
123 catchError(err => this.restExtractor.handleError(err))
127 getVideoPlaylist (id: string | number) {
128 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + id
130 return this.authHttp.get<VideoPlaylist>(url)
132 switchMap(res => this.extractPlaylist(res)),
133 catchError(err => this.restExtractor.handleError(err))
137 createVideoPlaylist (body: VideoPlaylistCreate) {
138 const data = objectToFormData(body)
140 return this.authHttp.post<{ videoPlaylist: { id: number } }>(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL, data)
143 if (!this.myAccountPlaylistCache) return
145 this.myAccountPlaylistCache.total++
147 this.myAccountPlaylistCache.data.push({
148 id: res.videoPlaylist.id,
149 displayName: body.displayName
152 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
154 catchError(err => this.restExtractor.handleError(err))
158 updateVideoPlaylist (videoPlaylist: VideoPlaylist, body: VideoPlaylistUpdate) {
159 const data = objectToFormData(body)
161 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id, data)
163 map(this.restExtractor.extractDataBool),
165 if (!this.myAccountPlaylistCache) return
167 const playlist = this.myAccountPlaylistCache.data.find(p => p.id === videoPlaylist.id)
168 playlist.displayName = body.displayName
170 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
172 catchError(err => this.restExtractor.handleError(err))
176 removeVideoPlaylist (videoPlaylist: VideoPlaylist) {
177 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylist.id)
179 map(this.restExtractor.extractDataBool),
181 if (!this.myAccountPlaylistCache) return
183 this.myAccountPlaylistCache.total--
184 this.myAccountPlaylistCache.data = this.myAccountPlaylistCache.data
185 .filter(p => p.id !== videoPlaylist.id)
187 this.myAccountPlaylistCacheSubject.next(this.myAccountPlaylistCache)
189 catchError(err => this.restExtractor.handleError(err))
193 addVideoInPlaylist (playlistId: number, body: VideoPlaylistElementCreate) {
194 const url = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos'
196 return this.authHttp.post<{ videoPlaylistElement: { id: number } }>(url, body)
199 const existsResult = this.videoExistsCache[body.videoId]
202 playlistElementId: res.videoPlaylistElement.id,
203 startTimestamp: body.startTimestamp,
204 stopTimestamp: body.stopTimestamp
207 this.runPlaylistCheck(body.videoId)
209 catchError(err => this.restExtractor.handleError(err))
213 updateVideoOfPlaylist (playlistId: number, playlistElementId: number, body: VideoPlaylistElementUpdate, videoId: number) {
214 return this.authHttp.put(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId, body)
216 map(this.restExtractor.extractDataBool),
218 const existsResult = this.videoExistsCache[videoId]
221 const elem = existsResult.find(e => e.playlistElementId === playlistElementId)
223 elem.startTimestamp = body.startTimestamp
224 elem.stopTimestamp = body.stopTimestamp
227 this.runPlaylistCheck(videoId)
229 catchError(err => this.restExtractor.handleError(err))
233 removeVideoFromPlaylist (playlistId: number, playlistElementId: number, videoId?: number) {
234 return this.authHttp.delete(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/' + playlistElementId)
236 map(this.restExtractor.extractDataBool),
240 if (this.videoExistsCache[videoId]) {
241 this.videoExistsCache[videoId] = this.videoExistsCache[videoId]
242 .filter(e => e.playlistElementId !== playlistElementId)
245 this.runPlaylistCheck(videoId)
247 catchError(err => this.restExtractor.handleError(err))
251 reorderPlaylist (playlistId: number, oldPosition: number, newPosition: number) {
252 const body: VideoPlaylistReorder = {
253 startPosition: oldPosition,
254 insertAfterPosition: newPosition
257 return this.authHttp.post(VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + playlistId + '/videos/reorder', body)
259 map(this.restExtractor.extractDataBool),
260 catchError(err => this.restExtractor.handleError(err))
265 videoPlaylistId: number | string,
266 componentPagination: ComponentPaginationLight
267 ): Observable<ResultList<VideoPlaylistElement>> {
268 const path = VideoPlaylistService.BASE_VIDEO_PLAYLIST_URL + videoPlaylistId + '/videos'
269 const pagination = this.restService.componentPaginationToRestPagination(componentPagination)
271 let params = new HttpParams()
272 params = this.restService.addRestGetParams(params, pagination)
275 .get<ResultList<ServerVideoPlaylistElement>>(path, { params })
277 switchMap(res => this.extractVideoPlaylistElements(res)),
278 catchError(err => this.restExtractor.handleError(err))
282 listenToMyAccountPlaylistsChange () {
283 return this.myAccountPlaylistCacheSubject.asObservable()
286 listenToVideoPlaylistChange (videoId: number) {
287 if (this.videoExistsObservableCache[ videoId ]) {
288 return this.videoExistsObservableCache[ videoId ]
291 const obs = this.videoExistsInPlaylistObservable
293 map(existsResult => existsResult[ videoId ]),
295 tap(result => this.videoExistsCache[ videoId ] = result)
298 this.videoExistsObservableCache[ videoId ] = obs
302 runPlaylistCheck (videoId: number) {
303 logger('Running playlist check.')
305 if (this.videoExistsCache[videoId]) {
306 logger('Found cache for %d.', videoId)
308 return this.videoExistsInPlaylistCacheSubject.next({ [videoId]: this.videoExistsCache[videoId] })
311 logger('Fetching from network for %d.', videoId)
312 return this.videoExistsInPlaylistNotifier.next(videoId)
315 extractPlaylists (result: ResultList<VideoPlaylistServerModel>) {
316 return this.serverService.getServerLocale()
318 map(translations => {
319 const playlistsJSON = result.data
320 const total = result.total
321 const playlists: VideoPlaylist[] = []
323 for (const playlistJSON of playlistsJSON) {
324 playlists.push(new VideoPlaylist(playlistJSON, translations))
327 return { data: playlists, total }
332 extractPlaylist (playlist: VideoPlaylistServerModel) {
333 return this.serverService.getServerLocale()
334 .pipe(map(translations => new VideoPlaylist(playlist, translations)))
337 extractVideoPlaylistElements (result: ResultList<ServerVideoPlaylistElement>) {
338 return this.serverService.getServerLocale()
340 map(translations => {
341 const elementsJson = result.data
342 const total = result.total
343 const elements: VideoPlaylistElement[] = []
345 for (const elementJson of elementsJson) {
346 elements.push(new VideoPlaylistElement(elementJson, translations))
349 return { total, data: elements }
354 private doVideosExistInPlaylist (videoIds: number[]): Observable<VideosExistInPlaylists> {
355 const url = VideoPlaylistService.MY_VIDEO_PLAYLIST_URL + 'videos-exist'
357 let params = new HttpParams()
358 params = this.restService.addObjectParams(params, { videoIds })
360 return this.authHttp.get<VideoExistInPlaylist>(url, { params, headers: { ignoreLoadingBar: '' } })
361 .pipe(catchError(err => this.restExtractor.handleError(err)))