]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/p2p-media-loader/segment-validator.ts
Live streaming implementation first step
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / p2p-media-loader / segment-validator.ts
1 import { Segment } from 'p2p-media-loader-core'
2 import { basename } from 'path'
3
4 type SegmentsJSON = { [filename: string]: string | { [byterange: string]: string } }
5
6 function segmentValidatorFactory (segmentsSha256Url: string) {
7 let segmentsJSON = fetchSha256Segments(segmentsSha256Url)
8 const regex = /bytes=(\d+)-(\d+)/
9
10 return async function segmentValidator (segment: Segment, canRefetchSegmentHashes = true) {
11 const filename = basename(segment.url)
12
13 const segmentValue = (await segmentsJSON)[filename]
14
15 if (!segmentValue && !canRefetchSegmentHashes) {
16 throw new Error(`Unknown segment name ${filename} in segment validator`)
17 }
18
19 if (!segmentValue) {
20 console.log('Refetching sha segments.')
21
22 // Refetch
23 segmentsJSON = fetchSha256Segments(segmentsSha256Url)
24 segmentValidator(segment, false)
25 return
26 }
27
28 let hashShouldBe: string
29 let range = ''
30
31 if (typeof segmentValue === 'string') {
32 hashShouldBe = segmentValue
33 } else {
34 const captured = regex.exec(segment.range)
35 range = captured[1] + '-' + captured[2]
36
37 hashShouldBe = segmentValue[range]
38 }
39
40 if (hashShouldBe === undefined) {
41 throw new Error(`Unknown segment name ${filename}/${range} in segment validator`)
42 }
43
44 const calculatedSha = bufferToEx(await sha256(segment.data))
45 if (calculatedSha !== hashShouldBe) {
46 throw new Error(
47 `Hashes does not correspond for segment ${filename}/${range}` +
48 `(expected: ${hashShouldBe} instead of ${calculatedSha})`
49 )
50 }
51 }
52 }
53
54 // ---------------------------------------------------------------------------
55
56 export {
57 segmentValidatorFactory
58 }
59
60 // ---------------------------------------------------------------------------
61
62 function fetchSha256Segments (url: string) {
63 return fetch(url)
64 .then(res => res.json() as Promise<SegmentsJSON>)
65 .catch(err => {
66 console.error('Cannot get sha256 segments', err)
67 return {}
68 })
69 }
70
71 function sha256 (data?: ArrayBuffer) {
72 if (!data) return undefined
73
74 return window.crypto.subtle.digest('SHA-256', data)
75 }
76
77 // Thanks: https://stackoverflow.com/a/53307879
78 function bufferToEx (buffer?: ArrayBuffer) {
79 if (!buffer) return ''
80
81 let s = ''
82 const h = '0123456789abcdef'
83 const o = new Uint8Array(buffer)
84
85 o.forEach((v: any) => s += h[ v >> 4 ] + h[ v & 15 ])
86
87 return s
88 }