Skip to content

Commit

Permalink
f
Browse files Browse the repository at this point in the history
  • Loading branch information
share121 committed Feb 7, 2025
1 parent 40beb05 commit 887350a
Showing 1 changed file with 47 additions and 10 deletions.
57 changes: 47 additions & 10 deletions worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,53 @@ export interface EventData {
}

addEventListener("message", async ({ data }: MessageEvent<EventData>) => {
for (const item of data.chunks) {
const r = await fetch(data.url, {
headers: {
...data.headers,
Range: `bytes=${item.start}-${item.end}`,
},
});
if (r.status !== 206) throw new Error(`Invalid status code ${r.status}"}`);
const buf = new Uint8Array(await r.arrayBuffer());
self.postMessage(buf, [buf]);
const r = await fetch(data.url, {
headers: {
...data.headers,
Range: `bytes=${data.chunks[0].start}-${data.chunks.at(-1)!.end}`,
},
});
if (r.status !== 206) throw new Error(`Invalid status code ${r.status}"}`);
if (!r.body) throw new Error("No body");
const reader = r.body.getReader();
let currentChunkIndex = 0;
let currentBuffer: Uint8Array | null = null;
let bufferOffset = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
let bytesProcessed = 0;
while (bytesProcessed < value.length) {
if (!currentBuffer && currentChunkIndex < data.chunks.length) {
const chunk = data.chunks[currentChunkIndex];
currentBuffer = new Uint8Array(chunk.end - chunk.start + 1);
bufferOffset = 0;
}
if (!currentBuffer) throw new Error("Unexpected extra data received");
const remainingBytes = currentBuffer.length - bufferOffset;
const bytesToCopy = Math.min(
remainingBytes,
value.length - bytesProcessed
);
currentBuffer.set(
value.subarray(bytesProcessed, bytesProcessed + bytesToCopy),
bufferOffset
);
bufferOffset += bytesToCopy;
bytesProcessed += bytesToCopy;
if (bufferOffset === currentBuffer.length) {
postMessage(currentBuffer, [currentBuffer]);
currentChunkIndex++;
currentBuffer = null;
}
}
}
if (currentChunkIndex !== data.chunks.length || currentBuffer) {
throw new Error("Incomplete data received");
}
} finally {
reader.releaseLock();
}
});

Expand Down

0 comments on commit 887350a

Please sign in to comment.