From 2264b1e48c13cf08959d134441176993e8faedd4 Mon Sep 17 00:00:00 2001 From: ComputerElite <71177995+ComputerElite@users.noreply.github.com> Date: Wed, 10 Jan 2024 09:24:15 +0100 Subject: [PATCH] Retry on failed chunk downloads --- QuestAppVersionSwitcher/FastFileDownloader.cs | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/QuestAppVersionSwitcher/FastFileDownloader.cs b/QuestAppVersionSwitcher/FastFileDownloader.cs index ac69e76..2ef11af 100644 --- a/QuestAppVersionSwitcher/FastFileDownloader.cs +++ b/QuestAppVersionSwitcher/FastFileDownloader.cs @@ -151,6 +151,8 @@ public void DownloadFileInternal(string url, string savePath, int numConnections Logger.Log("File saved at " + savePath); OnDownloadComplete?.Invoke(); } + + Dictionary chunkDownloadFailiures = new Dictionary(); public void DownloadChunk(string url, string savePath, long startPos, long endPos, int chunkIndex, ref long[] bytesDownloadedArray) { @@ -162,12 +164,13 @@ public void DownloadChunk(string url, string savePath, long startPos, long endPo HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); - byte[] buffer = new byte[4096]; + byte[] buffer = new byte[0xFFFF]; int bytesRead; long totalBytesRead = 0; - + string fileName = savePath + "." + chunkIndex; + if(File.Exists(fileName)) File.Delete(fileName); using (FileStream fileStream = - new FileStream(savePath + "." + chunkIndex, FileMode.Create, FileAccess.Write)) + new FileStream(fileName, FileMode.Create, FileAccess.Write)) { while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { @@ -190,11 +193,19 @@ public void DownloadChunk(string url, string savePath, long startPos, long endPo } catch (Exception e) { - Logger.Log("Error while downloading file chunk " + chunkIndex + ": " + e); - Cancel(); - error = true; - exception = e; - OnDownloadError.Invoke(); + if(!chunkDownloadFailiures.ContainsKey(chunkIndex)) chunkDownloadFailiures.Add(chunkIndex, 0); + chunkDownloadFailiures[chunkIndex]++; + if (chunkDownloadFailiures[chunkIndex] >= 3) + { + Logger.Log("Error while downloading file chunk " + chunkIndex + ": " + e); + Cancel(); + error = true; + exception = e; + OnDownloadError.Invoke(); + return; + } + Logger.Log("Error while downloading file chunk " + chunkIndex + ": " + e + ". Retrying... (" + chunkDownloadFailiures[chunkIndex] + "/3)"); + DownloadChunk(url, savePath, startPos, endPos, chunkIndex, ref bytesDownloadedArray); } }