Skip to content

Commit 2264b1e

Browse files
committed
Retry on failed chunk downloads
1 parent a9e9a39 commit 2264b1e

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

QuestAppVersionSwitcher/FastFileDownloader.cs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ public void DownloadFileInternal(string url, string savePath, int numConnections
151151
Logger.Log("File saved at " + savePath);
152152
OnDownloadComplete?.Invoke();
153153
}
154+
155+
Dictionary<int, int> chunkDownloadFailiures = new Dictionary<int, int>();
154156

155157
public void DownloadChunk(string url, string savePath, long startPos, long endPos, int chunkIndex, ref long[] bytesDownloadedArray)
156158
{
@@ -162,12 +164,13 @@ public void DownloadChunk(string url, string savePath, long startPos, long endPo
162164
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
163165
Stream stream = response.GetResponseStream();
164166

165-
byte[] buffer = new byte[4096];
167+
byte[] buffer = new byte[0xFFFF];
166168
int bytesRead;
167169
long totalBytesRead = 0;
168-
170+
string fileName = savePath + "." + chunkIndex;
171+
if(File.Exists(fileName)) File.Delete(fileName);
169172
using (FileStream fileStream =
170-
new FileStream(savePath + "." + chunkIndex, FileMode.Create, FileAccess.Write))
173+
new FileStream(fileName, FileMode.Create, FileAccess.Write))
171174
{
172175
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
173176
{
@@ -190,11 +193,19 @@ public void DownloadChunk(string url, string savePath, long startPos, long endPo
190193
}
191194
catch (Exception e)
192195
{
193-
Logger.Log("Error while downloading file chunk " + chunkIndex + ": " + e);
194-
Cancel();
195-
error = true;
196-
exception = e;
197-
OnDownloadError.Invoke();
196+
if(!chunkDownloadFailiures.ContainsKey(chunkIndex)) chunkDownloadFailiures.Add(chunkIndex, 0);
197+
chunkDownloadFailiures[chunkIndex]++;
198+
if (chunkDownloadFailiures[chunkIndex] >= 3)
199+
{
200+
Logger.Log("Error while downloading file chunk " + chunkIndex + ": " + e);
201+
Cancel();
202+
error = true;
203+
exception = e;
204+
OnDownloadError.Invoke();
205+
return;
206+
}
207+
Logger.Log("Error while downloading file chunk " + chunkIndex + ": " + e + ". Retrying... (" + chunkDownloadFailiures[chunkIndex] + "/3)");
208+
DownloadChunk(url, savePath, startPos, endPos, chunkIndex, ref bytesDownloadedArray);
198209
}
199210
}
200211

0 commit comments

Comments
 (0)