1 import { basename, dirname } from 'path'
3 class RedundancyUrlManager {
5 // Remember by what new URL we replaced an origin URL
6 private replacedSegmentUrls: { [originUrl: string]: string } = {}
8 constructor (private baseUrls: string[] = []) {
12 removeBySegmentUrl (segmentUrl: string) {
13 console.log('Removing redundancy of segment URL %s.', segmentUrl)
15 const baseUrl = dirname(segmentUrl)
17 this.baseUrls = this.baseUrls.filter(u => u !== baseUrl && u !== baseUrl + '/')
20 removeByOriginUrl (originUrl: string) {
21 const replaced = this.replacedSegmentUrls[originUrl]
24 return this.removeBySegmentUrl(replaced)
27 buildUrl (url: string) {
28 delete this.replacedSegmentUrls[url]
30 const max = this.baseUrls.length + 1
31 const i = this.getRandomInt(max)
33 if (i === max - 1) return url
35 const newBaseUrl = this.baseUrls[i]
36 const slashPart = newBaseUrl.endsWith('/') ? '' : '/'
38 const newUrl = newBaseUrl + slashPart + basename(url)
39 this.replacedSegmentUrls[url] = newUrl
45 return this.baseUrls.length
48 private getRandomInt (max: number) {
49 return Math.floor(Math.random() * Math.floor(max))
53 // ---------------------------------------------------------------------------