1 import { wait } from '@root-helpers/utils'
2 import { Segment } from 'p2p-media-loader-core'
3 import { basename } from 'path'
5 type SegmentsJSON = { [filename: string]: string | { [byterange: string]: string } }
9 function segmentValidatorFactory (segmentsSha256Url: string) {
10 let segmentsJSON = fetchSha256Segments(segmentsSha256Url)
11 const regex = /bytes=(\d+)-(\d+)/
13 return async function segmentValidator (segment: Segment, retry = 1) {
14 const filename = basename(segment.url)
16 const segmentValue = (await segmentsJSON)[filename]
18 if (!segmentValue && retry > maxRetries) {
19 throw new Error(`Unknown segment name ${filename} in segment validator`)
25 console.log('Refetching sha segments for %s.', filename)
27 segmentsJSON = fetchSha256Segments(segmentsSha256Url)
28 await segmentValidator(segment, retry + 1)
33 let hashShouldBe: string
36 if (typeof segmentValue === 'string') {
37 hashShouldBe = segmentValue
39 const captured = regex.exec(segment.range)
40 range = captured[1] + '-' + captured[2]
42 hashShouldBe = segmentValue[range]
45 if (hashShouldBe === undefined) {
46 throw new Error(`Unknown segment name ${filename}/${range} in segment validator`)
49 const calculatedSha = await sha256Hex(segment.data)
50 if (calculatedSha !== hashShouldBe) {
52 `Hashes does not correspond for segment ${filename}/${range}` +
53 `(expected: ${hashShouldBe} instead of ${calculatedSha})`
59 // ---------------------------------------------------------------------------
62 segmentValidatorFactory
65 // ---------------------------------------------------------------------------
67 function fetchSha256Segments (url: string) {
69 .then(res => res.json() as Promise<SegmentsJSON>)
71 console.error('Cannot get sha256 segments', err)
76 async function sha256Hex (data?: ArrayBuffer) {
77 if (!data) return undefined
79 if (window.crypto.subtle) {
80 return window.crypto.subtle.digest('SHA-256', data)
81 .then(data => bufferToHex(data))
84 // Fallback for non HTTPS context
85 const shaModule = await import('sha.js')
86 return new shaModule.sha256().update(Buffer.from(data)).digest('hex')
89 // Thanks: https://stackoverflow.com/a/53307879
90 function bufferToHex (buffer?: ArrayBuffer) {
91 if (!buffer) return ''
94 const h = '0123456789abcdef'
95 const o = new Uint8Array(buffer)
97 o.forEach((v: any) => s += h[ v >> 4 ] + h[ v & 15 ])