1 import { HttpStatusCode, ResultList, VideoPlaylistElement } from '../../../../../shared/models'
2 import { logger } from '../../../root-helpers'
3 import { AuthHTTP } from './auth-http'
5 export class PlaylistFetcher {
7 constructor (private readonly http: AuthHTTP) {
11 async loadPlaylist (playlistId: string) {
12 const playlistPromise = this.loadPlaylistInfo(playlistId)
13 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
15 let playlistResponse: Response
16 let isResponseOk: boolean
19 playlistResponse = await playlistPromise
20 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
27 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
28 throw new Error('This playlist does not exist.')
31 throw new Error('We cannot fetch the playlist. Please try again later.')
34 return { playlistResponse, videosResponse: await playlistElementsPromise }
37 async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
38 let elements = baseResult.data
39 let total = baseResult.total
42 while (total > elements.length && i < 10) {
43 const result = await this.loadPlaylistElements(playlistId, elements.length)
45 const json = await result.json()
48 elements = elements.concat(json.data)
53 logger.error('Cannot fetch all playlists elements, there are too many!')
59 private loadPlaylistInfo (playlistId: string): Promise<Response> {
60 return this.http.fetch(this.getPlaylistUrl(playlistId), { optionalAuth: true })
63 private loadPlaylistElements (playlistId: string, start = 0): Promise<Response> {
64 const url = new URL(this.getPlaylistUrl(playlistId) + '/videos')
65 url.search = new URLSearchParams({ start: '' + start, count: '100' }).toString()
67 return this.http.fetch(url.toString(), { optionalAuth: true })
70 private getPlaylistUrl (id: string) {
71 return window.location.origin + '/api/v1/video-playlists/' + id