]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/shared/p2p-media-loader/redundancy-url-manager.ts
Prevent console error with HLS fallback
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / shared / p2p-media-loader / redundancy-url-manager.ts
1 import { basename, dirname } from 'path'
2 import { logger } from '@root-helpers/logger'
3
4 class RedundancyUrlManager {
5
6 constructor (private baseUrls: string[] = []) {
7 // empty
8 }
9
10 removeBySegmentUrl (segmentUrl: string) {
11 logger.info(`Removing redundancy of segment URL ${segmentUrl}.`)
12
13 const baseUrl = dirname(segmentUrl)
14
15 this.baseUrls = this.baseUrls.filter(u => u !== baseUrl && u !== baseUrl + '/')
16 }
17
18 buildUrl (url: string) {
19 const max = this.baseUrls.length + 1
20 const i = this.getRandomInt(max)
21
22 if (i === max - 1) return url
23
24 const newBaseUrl = this.baseUrls[i]
25 const slashPart = newBaseUrl.endsWith('/') ? '' : '/'
26
27 return newBaseUrl + slashPart + basename(url)
28 }
29
30 countBaseUrls () {
31 return this.baseUrls.length
32 }
33
34 private getRandomInt (max: number) {
35 return Math.floor(Math.random() * Math.floor(max))
36 }
37 }
38
39 // ---------------------------------------------------------------------------
40
41 export {
42 RedundancyUrlManager
43 }