aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts')
-rw-r--r--client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts57
1 files changed, 57 insertions, 0 deletions
diff --git a/client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts b/client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts
new file mode 100644
index 000000000..7fc2b6ab1
--- /dev/null
+++ b/client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts
@@ -0,0 +1,57 @@
1import { basename, dirname } from 'path'
2
3class RedundancyUrlManager {
4
5 // Remember by what new URL we replaced an origin URL
6 private replacedSegmentUrls: { [originUrl: string]: string } = {}
7
8 constructor (private baseUrls: string[] = []) {
9 // empty
10 }
11
12 removeBySegmentUrl (segmentUrl: string) {
13 console.log('Removing redundancy of segment URL %s.', segmentUrl)
14
15 const baseUrl = dirname(segmentUrl)
16
17 this.baseUrls = this.baseUrls.filter(u => u !== baseUrl && u !== baseUrl + '/')
18 }
19
20 removeByOriginUrl (originUrl: string) {
21 const replaced = this.replacedSegmentUrls[originUrl]
22 if (!replaced) return
23
24 return this.removeBySegmentUrl(replaced)
25 }
26
27 buildUrl (url: string) {
28 delete this.replacedSegmentUrls[url]
29
30 const max = this.baseUrls.length + 1
31 const i = this.getRandomInt(max)
32
33 if (i === max - 1) return url
34
35 const newBaseUrl = this.baseUrls[i]
36 const slashPart = newBaseUrl.endsWith('/') ? '' : '/'
37
38 const newUrl = newBaseUrl + slashPart + basename(url)
39 this.replacedSegmentUrls[url] = newUrl
40
41 return newUrl
42 }
43
44 countBaseUrls () {
45 return this.baseUrls.length
46 }
47
48 private getRandomInt (max: number) {
49 return Math.floor(Math.random() * Math.floor(max))
50 }
51}
52
53// ---------------------------------------------------------------------------
54
55export {
56 RedundancyUrlManager
57}