]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - client/src/standalone/videos/shared/playlist-fetcher.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / client / src / standalone / videos / shared / playlist-fetcher.ts
... / ...
CommitLineData
1import { HttpStatusCode, ResultList, VideoPlaylistElement } from '../../../../../shared/models'
2import { logger } from '../../../root-helpers'
3import { AuthHTTP } from './auth-http'
4
5export class PlaylistFetcher {
6
7 constructor (private readonly http: AuthHTTP) {
8
9 }
10
11 async loadPlaylist (playlistId: string) {
12 const playlistPromise = this.loadPlaylistInfo(playlistId)
13 const playlistElementsPromise = this.loadPlaylistElements(playlistId)
14
15 let playlistResponse: Response
16 let isResponseOk: boolean
17
18 try {
19 playlistResponse = await playlistPromise
20 isResponseOk = playlistResponse.status === HttpStatusCode.OK_200
21 } catch (err) {
22 logger.error(err)
23 isResponseOk = false
24 }
25
26 if (!isResponseOk) {
27 if (playlistResponse?.status === HttpStatusCode.NOT_FOUND_404) {
28 throw new Error('This playlist does not exist.')
29 }
30
31 throw new Error('We cannot fetch the playlist. Please try again later.')
32 }
33
34 return { playlistResponse, videosResponse: await playlistElementsPromise }
35 }
36
37 async loadAllPlaylistVideos (playlistId: string, baseResult: ResultList<VideoPlaylistElement>) {
38 let elements = baseResult.data
39 let total = baseResult.total
40 let i = 0
41
42 while (total > elements.length && i < 10) {
43 const result = await this.loadPlaylistElements(playlistId, elements.length)
44
45 const json = await result.json()
46 total = json.total
47
48 elements = elements.concat(json.data)
49 i++
50 }
51
52 if (i === 10) {
53 logger.error('Cannot fetch all playlists elements, there are too many!')
54 }
55
56 return elements
57 }
58
59 private loadPlaylistInfo (playlistId: string): Promise<Response> {
60 return this.http.fetch(this.getPlaylistUrl(playlistId), { optionalAuth: true })
61 }
62
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()
66
67 return this.http.fetch(url.toString(), { optionalAuth: true })
68 }
69
70 private getPlaylistUrl (id: string) {
71 return window.location.origin + '/api/v1/video-playlists/' + id
72 }
73}