]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - client/src/assets/player/p2p-media-loader/segment-validator.ts
Fix prod deploy
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / p2p-media-loader / segment-validator.ts
index 8f4922daa040f0ec6e1ec3bc01eba5c8229c3e97..0614f73d2dc79bb70715cc245342a78516c27665 100644 (file)
@@ -1,20 +1,52 @@
 import { Segment } from 'p2p-media-loader-core'
 import { basename } from 'path'
 
+type SegmentsJSON = { [filename: string]: string | { [byterange: string]: string } }
+
 function segmentValidatorFactory (segmentsSha256Url: string) {
-  const segmentsJSON = fetchSha256Segments(segmentsSha256Url)
+  let segmentsJSON = fetchSha256Segments(segmentsSha256Url)
+  const regex = /bytes=(\d+)-(\d+)/
+
+  return async function segmentValidator (segment: Segment, canRefetchSegmentHashes = true) {
+    const filename = basename(segment.url)
+
+    const segmentValue = (await segmentsJSON)[filename]
+
+    if (!segmentValue && !canRefetchSegmentHashes) {
+      throw new Error(`Unknown segment name ${filename} in segment validator`)
+    }
+
+    if (!segmentValue) {
+      console.log('Refetching sha segments.')
 
-  return async function segmentValidator (segment: Segment) {
-    const segmentName = basename(segment.url)
+      // Refetch
+      segmentsJSON = fetchSha256Segments(segmentsSha256Url)
+      segmentValidator(segment, false)
+      return
+    }
+
+    let hashShouldBe: string
+    let range = ''
+
+    if (typeof segmentValue === 'string') {
+      hashShouldBe = segmentValue
+    } else {
+      const captured = regex.exec(segment.range)
+      range = captured[1] + '-' + captured[2]
+
+      hashShouldBe = segmentValue[range]
+    }
 
-    const hashShouldBe = (await segmentsJSON)[segmentName]
     if (hashShouldBe === undefined) {
-      throw new Error(`Unknown segment name ${segmentName} in segment validator`)
+      throw new Error(`Unknown segment name ${filename}/${range} in segment validator`)
     }
 
     const calculatedSha = bufferToEx(await sha256(segment.data))
     if (calculatedSha !== hashShouldBe) {
-      throw new Error(`Hashes does not correspond for segment ${segmentName} (expected: ${hashShouldBe} instead of ${calculatedSha})`)
+      throw new Error(
+        `Hashes does not correspond for segment ${filename}/${range}` +
+        `(expected: ${hashShouldBe} instead of ${calculatedSha})`
+      )
     }
   }
 }
@@ -29,7 +61,7 @@ export {
 
 function fetchSha256Segments (url: string) {
   return fetch(url)
-    .then(res => res.json())
+    .then(res => res.json() as Promise<SegmentsJSON>)
     .catch(err => {
       console.error('Cannot get sha256 segments', err)
       return {}