forked from bittiez/SimpleFileUpdater
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdateHandler.cs
More file actions
291 lines (246 loc) · 9.99 KB
/
UpdateHandler.cs
File metadata and controls
291 lines (246 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Avalonia.Threading;
namespace FileUpdaterClient;
public static class UpdateHandler
{
private const int WORKER_COUNT = 2;
private static HttpClient client = new();
private static ConcurrentQueue<FileEntry> downloadQueue = new();
private static ConcurrentQueue<FileEntry> remoteFileListQueue = new();
private static MainViewModel data;
private static double currentMaxProgress;
private static Dictionary<string, int> retryMap = new();
private static long totalBytesDownloaded = 0;
private static TimeSpan totalDownloadTime = TimeSpan.Zero;
private static readonly object downloadStatsLock = new();
private static DateTime lastUiUpdateTime = DateTime.MinValue;
private static readonly CancellationTokenSource cancellationSource = new();
private static readonly CancellationToken cancellationToken = cancellationSource.Token;
public static async Task HandleUpdates(MainViewModel dataModel)
{
client.Timeout = TimeSpan.FromSeconds(5); //Initial connection
data = dataModel;
if (!await GetFileList()) return;
await StartComparingFiles();
client = new HttpClient(); //Must have new client for new timeout
client.Timeout = TimeSpan.FromMinutes(15); //Download timeout
await StartDownloading();
Dispatcher.UIThread.Post(() => //Ensure the final finished text is queued in case other text updates are already queued, making sure this is the last one ran.
{
data.Progress = 100;
data.ProgressText = Settings.Finished;
});
}
public static void Cancel()
{
cancellationSource.Cancel();
}
private static async Task<bool> GetFileList()
{
data.ProgressText = Settings.ReqFileList;
var response = await client.GetAsync(new Uri(Settings.UpdateUrl));
if (response.StatusCode == HttpStatusCode.NotFound)
{
data.ErrorMessage = Settings.ConError;
return false;
}
try
{
string json = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(json))
{
data.ErrorMessage = Settings.BadData;
return false;
}
FileEntry[] fileList = JsonSerializer.Deserialize<FileEntry[]>(json);
Console.WriteLine(
$"Received information for {fileList.Length} files from the server, comparing to local files..");
foreach (var item in fileList)
{
remoteFileListQueue.Enqueue(item);
}
data.Progress = 0;
return true;
}
catch (Exception e)
{
data.ErrorMessage = Settings.UnknownError;
Console.WriteLine(e.Message);
return false;
}
}
private static async Task StartComparingFiles()
{
if (remoteFileListQueue.IsEmpty) return;
currentMaxProgress = remoteFileListQueue.Count;
Dispatcher.UIThread.Post(() =>
{
data.Progress = 0;
data.ProgressText = string.Format(Settings.ComparingFiles, "0", currentMaxProgress);
});
var tasks = new List<Task>();
for (int i = 0; i < WORKER_COUNT; i++)
{
tasks.Add(Task.Run(BackgroundWorker_CompareFile));
}
await Task.WhenAll(tasks);
}
private static async Task StartDownloading()
{
if (downloadQueue.IsEmpty) return;
currentMaxProgress = downloadQueue.Count;
Dispatcher.UIThread.Post(() =>
{
data.Progress = 0;
data.ProgressText = string.Format(Settings.DownloadingFiles, "0", currentMaxProgress, "0");
});
var tasks = new List<Task>();
for (int i = 0; i < WORKER_COUNT; i++)
{
tasks.Add(Task.Run(() => BackgroundWorker_DoWork()));
}
await Task.WhenAll(tasks);
}
private static void BackgroundWorker_CompareFile()
{
while (!cancellationToken.IsCancellationRequested && remoteFileListQueue.TryDequeue(out FileEntry file))
{
if (File.Exists(file.name))
{
if (!file.md5.Equals(GetMD5HashFromFile(file.name)))
{
downloadQueue.Enqueue(file);
Console.WriteLine(
$"[{file.name}] does not match the version from the server, queued for download..");
}
}
else
{
downloadQueue.Enqueue(file);
Console.WriteLine($"[{file.name}] does not exist, queued for download..");
}
Dispatcher.UIThread.Post(() =>
{
data.Progress = ((currentMaxProgress - remoteFileListQueue.Count) / currentMaxProgress) * 100;
data.ProgressText = string.Format(Settings.ComparingFiles,
currentMaxProgress - remoteFileListQueue.Count, currentMaxProgress);
});
}
}
private static async void BackgroundWorker_DoWork()
{
while (!cancellationToken.IsCancellationRequested && downloadQueue.TryDequeue(out FileEntry file))
{
if (file == null)
continue;
try
{
Console.WriteLine($"Downloading [{file.name}]...");
EnsureDirectory(file.name);
Uri updateUrl = new Uri(Settings.UpdateUrl + "/file/" + file.name);
using var responseStream = await client.GetStreamAsync(updateUrl);
using var fileStream = File.Create(file.name);
byte[] buffer = new byte[81920];
int bytesRead;
long fileBytesDownloaded = 0;
var sw = Stopwatch.StartNew();
while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
if (cancellationToken.IsCancellationRequested)
return;
await fileStream.WriteAsync(buffer, 0, bytesRead);
fileBytesDownloaded += bytesRead;
lock (downloadStatsLock)
{
totalBytesDownloaded += bytesRead;
totalDownloadTime += sw.Elapsed;
}
// Limit UI updates to every 0.5 seconds
if ((DateTime.UtcNow - lastUiUpdateTime).TotalSeconds >= 0.5)
{
lastUiUpdateTime = DateTime.UtcNow;
double avgSpeed;
lock (downloadStatsLock)
{
avgSpeed = totalDownloadTime.TotalSeconds > 0
? totalBytesDownloaded / totalDownloadTime.TotalSeconds
: 0;
}
string speedStr = $"{(avgSpeed / 1024):F2} KB/s";
Dispatcher.UIThread.Post(() =>
{
double progress =
((currentMaxProgress - downloadQueue.Count) / (double)currentMaxProgress) * 100;
data.Progress = progress;
data.ProgressText = string.Format(Settings.DownloadingFiles,
currentMaxProgress - downloadQueue.Count, currentMaxProgress, speedStr);
});
sw.Restart(); // reset stopwatch for next chunk interval
}
}
}
catch (Exception ex)
{
if (!retryMap.TryGetValue(file.name, out int count))
count = 0;
if (count > 5)
{
var fname = file.name;
Console.WriteLine($"Failed to download [{file.name}] after 5 attempts, skipping..");
Dispatcher.UIThread.Post(() => data.ErrorMessage = string.Format(Settings.FileFailedError, fname));
continue;
}
retryMap[file.name] = count + 1;
downloadQueue.Enqueue(file);
Console.WriteLine(ex.ToString());
}
// Final UI update after file is done
double finalAvgSpeed;
lock (downloadStatsLock)
{
finalAvgSpeed = totalDownloadTime.TotalSeconds > 0
? totalBytesDownloaded / totalDownloadTime.TotalSeconds
: 0;
}
string finalSpeedStr = $"{(finalAvgSpeed / 1024):F2} KB/s";
Dispatcher.UIThread.Post(() =>
{
double progress = ((currentMaxProgress - downloadQueue.Count) / (double)currentMaxProgress) * 100;
data.Progress = progress;
if(progress >= 100 && downloadQueue.Count == 0)
data.ProgressText = Settings.Finished;
else
data.ProgressText = string.Format(Settings.DownloadingFiles, currentMaxProgress - downloadQueue.Count, currentMaxProgress, finalSpeedStr);
});
}
}
private static string GetMD5HashFromFile(string fileName)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(fileName))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
private static void EnsureDirectory(string filePath)
{
string dirPath = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dirPath) && !Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
}
}
public class FileEntry
{
public string name { get; set; }
public string md5 { get; set; }
}