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