Skip to content

Commit

Permalink
Retry on failed chunk downloads
Browse files Browse the repository at this point in the history
  • Loading branch information
ComputerElite committed Jan 10, 2024
1 parent a9e9a39 commit 2264b1e
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions QuestAppVersionSwitcher/FastFileDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ public void DownloadFileInternal(string url, string savePath, int numConnections
Logger.Log("File saved at " + savePath);
OnDownloadComplete?.Invoke();
}

Dictionary<int, int> chunkDownloadFailiures = new Dictionary<int, int>();

public void DownloadChunk(string url, string savePath, long startPos, long endPos, int chunkIndex, ref long[] bytesDownloadedArray)
{
Expand All @@ -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)
{
Expand All @@ -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);
}
}

Expand Down

0 comments on commit 2264b1e

Please sign in to comment.