fix: 416 HTTP error deleting local files fix

This commit is contained in:
Moyasee
2026-04-05 22:44:57 +03:00
parent 1ae2a59243
commit f06f4a5b13
2 changed files with 27 additions and 17 deletions
@@ -335,6 +335,17 @@ export class JsHttpDownloader {
}
}
private parseTotalSizeFrom416(response: Response): number | null {
const contentRange = response.headers.get("content-range");
if (!contentRange) return null;
const match = /bytes\s+\*\/(\d+)/i.exec(contentRange);
if (!match) return null;
const total = Number.parseInt(match[1], 10);
return Number.isFinite(total) && total > 0 ? total : null;
}
private async executeDownload(
url: string,
requestHeaders: Record<string, string>,
@@ -355,25 +366,23 @@ export class JsHttpDownloader {
);
if (response.status === 416 && startByte > 0) {
logger.log(
"[JsHttpDownloader] Range not satisfiable, deleting existing file and restarting"
);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
const remoteTotalSize = this.parseTotalSizeFrom416(response);
if (remoteTotalSize !== null && startByte === remoteTotalSize) {
this.fileSize = remoteTotalSize;
this.bytesDownloaded = remoteTotalSize;
this.status = "complete";
this.retryCount = 0;
this.downloadSpeed = 0;
logger.log(
"[JsHttpDownloader] Range not satisfiable but local file already complete"
);
return;
}
this.bytesDownloaded = 0;
this.resetSpeedTracking();
const headersWithoutRange = { ...requestHeaders };
delete headersWithoutRange["Range"];
return this.executeDownload(
url,
headersWithoutRange,
filePath,
0,
savePath,
usedFallback
throw new Error(
`[JsHttpDownloader] Range not satisfiable for resumed download (local=${startByte}, remote=${remoteTotalSize ?? "unknown"}). Keeping local file and aborting to avoid restart from zero.`
);
}
File diff suppressed because one or more lines are too long