aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/assets/player/p2p-media-loader/redundancy-url-manager.ts
blob: 7fc2b6ab1e942ce51063831661339667235ce350 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { basename, dirname } from 'path'

class RedundancyUrlManager {

  // Remember by what new URL we replaced an origin URL
  private replacedSegmentUrls: { [originUrl: string]: string } = {}

  constructor (private baseUrls: string[] = []) {
    // empty
  }

  removeBySegmentUrl (segmentUrl: string) {
    console.log('Removing redundancy of segment URL %s.', segmentUrl)

    const baseUrl = dirname(segmentUrl)

    this.baseUrls = this.baseUrls.filter(u => u !== baseUrl && u !== baseUrl + '/')
  }

  removeByOriginUrl (originUrl: string) {
    const replaced = this.replacedSegmentUrls[originUrl]
    if (!replaced) return

    return this.removeBySegmentUrl(replaced)
  }

  buildUrl (url: string) {
    delete this.replacedSegmentUrls[url]

    const max = this.baseUrls.length + 1
    const i = this.getRandomInt(max)

    if (i === max - 1) return url

    const newBaseUrl = this.baseUrls[i]
    const slashPart = newBaseUrl.endsWith('/') ? '' : '/'

    const newUrl = newBaseUrl + slashPart + basename(url)
    this.replacedSegmentUrls[url] = newUrl

    return newUrl
  }

  countBaseUrls () {
    return this.baseUrls.length
  }

  private getRandomInt (max: number) {
    return Math.floor(Math.random() * Math.floor(max))
  }
}

// ---------------------------------------------------------------------------

export {
  RedundancyUrlManager
}