This repository was archived by the owner on Sep 2, 2025. It is now read-only.
forked from antonpup/Aurora
-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUpdateManager.cs
More file actions
executable file
·527 lines (446 loc) · 16.4 KB
/
UpdateManager.cs
File metadata and controls
executable file
·527 lines (446 loc) · 16.4 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Windows.Forms;
using Octokit;
using Version = SemVer.Version;
namespace Aurora_Updater
{
public class LogEntry
{
private String message;
private Color color;
public LogEntry()
{
this.message = "";
this.color = Color.Black;
}
public LogEntry(String message)
{
this.message = message;
this.color = Color.Black;
}
public LogEntry(String message, Color color)
{
this.message = message;
this.color = color;
}
public Color GetColor()
{
return color;
}
public String GetMessage()
{
return message;
}
public override string ToString()
{
return message.ToString();
}
}
public enum UpdateStatus
{
None,
InProgress,
Complete,
Error
}
public class UpdateManager
{
private string infoUrl = @"http://project-aurora.com/vcheck.php";
private string[] ignoreFiles = { };
//public UpdateResponse response = new UpdateResponse();
private Queue<LogEntry> log = new Queue<LogEntry>();
private float downloadProgess = 0.0f;
private float extractProgess = 0.0f;
public UpdateStatus updateState = UpdateStatus.None;
private int downloadProgressCheck = 0;
private int secondsLeft = 15;
private Aurora.Settings.Configuration Config;
private GitHubClient gClient = new GitHubClient(new ProductHeaderValue("aurora-updater"));
public Release LatestRelease;
public UpdateManager(Version version, string author, string repoName)
{
LoadSettings();
PerformCleanup();
FetchData(version, author, repoName);
}
public void LoadSettings()
{
try
{
Config = Aurora.Settings.ConfigManager.Load();
}
catch (Exception e)
{
Config = new Aurora.Settings.Configuration();
}
}
public void ClearLog()
{
log.Clear();
}
public LogEntry[] GetLog()
{
return log.ToArray();
}
public int GetTotalProgress()
{
return (int)((downloadProgess + extractProgess) / 2.0f * 100.0f);
}
private bool FetchData(Version version, string owner, string repositoryName)
{
try
{
if (Config.GetDevReleases || !String.IsNullOrWhiteSpace(version.PreRelease))
LatestRelease = gClient.Repository.Release.GetAll(owner, repositoryName, new ApiOptions { PageCount = 1, PageSize = 1 }).Result[0];
else
LatestRelease = gClient.Repository.Release.GetLatest(owner, repositoryName).Result;
//Console.WriteLine(reply);
}
catch (Exception exc)
{
updateState = UpdateStatus.Error;
MessageBox.Show(
$"Could not find update.\r\nError:\r\n{exc}",
"Aurora Updater - Error");
return false;
}
return true;
}
public bool RetrieveUpdate(UpdateType type)
{
//string url = @"http://project-aurora.com/download.php?id=" + (type == UpdateType.Major ? response.Major.ID : response.Minor.ID);
//updateState = UpdateStatus.InProgress;
try
{
string url = LatestRelease.Assets.First(s => s.Name.StartsWith("release") || s.Name.StartsWith("Aurora-v")).BrowserDownloadUrl;
if (!String.IsNullOrWhiteSpace(url))
{
this.log.Enqueue(new LogEntry("Starting download... "));
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
// Starts the download
client.DownloadFileAsync(new Uri(url), Path.Combine(Program.exePath, "update.zip"));
}
}
catch (Exception exc)
{
log.Enqueue(new LogEntry(exc.Message, Color.Red));
updateState = UpdateStatus.Error;
return false;
}
return false;
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes;
downloadProgressCheck++;
if (downloadProgressCheck % 10 == 0)
{
log.Enqueue(new LogEntry("Download " + Math.Truncate(percentage * 100) + "%"));
this.downloadProgess = (float)(Math.Truncate(percentage * 100) / 100.0f);
}
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
this.log.Enqueue(new LogEntry("Download complete."));
this.log.Enqueue(new LogEntry());
this.downloadProgess = 1.0f;
if (ExtractUpdate())
{
System.Timers.Timer shutdownTimer = new System.Timers.Timer(1000);
shutdownTimer.Elapsed += ShutdownTimerElapsed;
shutdownTimer.Start();
updateState = UpdateStatus.Complete;
}
else
updateState = UpdateStatus.Error;
}
private void ShutdownTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (secondsLeft > 0)
{
this.log.Enqueue(new LogEntry($"Restarting Aurora in {secondsLeft} second{(secondsLeft == 1 ? "" : "s")}..."));
secondsLeft--;
}
else
{
//Kill all Aurora instances
foreach (Process proc in Process.GetProcessesByName("Aurora"))
proc.Kill();
try
{
ProcessStartInfo auroraProc = new ProcessStartInfo();
auroraProc.FileName = Path.Combine(Program.exePath, "Aurora.exe");
Process.Start(auroraProc);
Environment.Exit(0); //Exit, no further action required
}
catch (Exception exc)
{
this.log.Enqueue(new LogEntry($"Could not restart Aurora. Error:\r\n{exc}", Color.Red));
this.log.Enqueue(new LogEntry("Please restart Aurora manually.", Color.Red));
MessageBox.Show(
$"Could not restart Aurora.\r\nPlease restart Aurora manually.\r\nError:\r\n{exc}",
"Aurora Updater - Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private bool ExtractUpdate()
{
if (File.Exists(Path.Combine(Program.exePath, "update.zip")))
{
log.Enqueue(new LogEntry("Unpacking update..."));
try
{
var updateFile = ZipFile.OpenRead(Path.Combine(Program.exePath, "update.zip"));
var countOfEntries = updateFile.Entries.Count;
log.Enqueue(new LogEntry($"{countOfEntries} files detected."));
for (int i = 0; i < countOfEntries; i++)
{
float percentage = i / (float)countOfEntries;
var fileEntry = updateFile.Entries[i];
log.Enqueue(new LogEntry($"[{Math.Truncate(percentage * 100)}%] Updating: {fileEntry.FullName}"));
extractProgess = (float)(Math.Truncate(percentage * 100) / 100.0f);
if (ignoreFiles.Contains(fileEntry.FullName))
continue;
try
{
var filePath = Path.Combine(Program.exePath, fileEntry.FullName);
if (File.Exists(filePath))
File.Move(filePath, $"{filePath}.updateremove");
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
fileEntry.ExtractToFile(filePath);
}
catch (IOException e)
{
log.Enqueue(new LogEntry($"{fileEntry.FullName} is inaccessible.", Color.Red));
MessageBox.Show($"{fileEntry.FullName} is inaccessible.\r\nPlease close Aurora.\r\n\r\n {e.Message}");
i--;
}
}
updateFile.Dispose();
File.Delete(Path.Combine(Program.exePath, "update.zip"));
}
catch (Exception exc)
{
log.Enqueue(new LogEntry(exc.Message, Color.Red));
return false;
}
log.Enqueue(new LogEntry("All files updated."));
log.Enqueue(new LogEntry());
log.Enqueue(new LogEntry("Updater will automatically restart Aurora."));
this.extractProgess = 1.0f;
return true;
}
else
{
this.log.Enqueue(new LogEntry("Update file not found.", Color.Red));
return false;
}
}
private void PerformCleanup()
{
string[] _messyFiles = Directory.GetFiles(Program.exePath, "*.updateremove", SearchOption.AllDirectories);
foreach (string file in _messyFiles)
{
try
{
File.Delete(file);
}
catch (Exception exc)
{
log.Enqueue(new LogEntry("Unable to delete file - " + file, Color.Red));
}
}
if (File.Exists(Path.Combine(Program.exePath, "update.zip")))
File.Delete(Path.Combine(Program.exePath, "update.zip"));
}
}
public class UpdateResponse
{
protected Newtonsoft.Json.Linq.JObject _ParsedData;
protected string json;
private UpdateInfoNode _Major;
public UpdateInfoNode Major
{
get
{
if (_Major == null)
{
_Major = new UpdateInfoNode(_ParsedData["major"]?.ToString() ?? "");
}
return _Major;
}
}
private UpdateInfoNode _Minor;
public UpdateInfoNode Minor
{
get
{
if (_Minor == null)
{
_Minor = new UpdateInfoNode(_ParsedData["minor"]?.ToString() ?? "");
}
return _Minor;
}
}
public UpdateResponse()
{
json = "{}";
_ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json);
}
public UpdateResponse(string json_data)
{
if (String.IsNullOrWhiteSpace(json_data))
{
json_data = "{}";
}
json = json_data;
_ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json_data);
}
public UpdateResponse(UpdateResponse other_state)
{
_ParsedData = other_state._ParsedData;
json = other_state.json;
}
internal String GetNode(string name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(name, out value))
return value.ToString();
else
return "";
}
public override string ToString()
{
return json;
}
}
public class Node
{
protected Newtonsoft.Json.Linq.JObject _ParsedData;
internal Node(string json_data)
{
if (String.IsNullOrWhiteSpace(json_data))
{
json_data = "{}";
}
_ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json_data);
}
internal string GetString(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value))
return value.ToString();
else
return "";
}
internal int GetInt(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value))
return Convert.ToInt32(value.ToString());
else
return -1;
}
internal float GetFloat(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value))
return Convert.ToSingle(value.ToString());
else
return -1.0f;
}
internal long GetLong(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value))
return Convert.ToInt64(value.ToString());
else
return -1;
}
internal T GetEnum<T>(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value) && !String.IsNullOrWhiteSpace(value.ToString()))
{
var type = typeof(T);
if (!type.IsEnum) throw new InvalidOperationException();
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute != null)
{
if (attribute.Description.ToLowerInvariant().Equals(Name))
return (T)field.GetValue(null);
}
if (field.Name.ToLowerInvariant().Equals(Name))
return (T)field.GetValue(null);
}
return (T)Enum.Parse(typeof(T), "Undefined", true);
}
else
return (T)Enum.Parse(typeof(T), "Undefined", true);
}
internal bool GetBool(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value) && value.ToObject<bool>())
return value.ToObject<bool>();
else
return false;
}
internal T[] GetArray<T>(string Name)
{
Newtonsoft.Json.Linq.JToken value;
if (_ParsedData.TryGetValue(Name, out value))
return value.ToObject<T[]>();
else
return new T[] { };
}
}
public enum UpdateType
{
Undefined,
Major,
Minor
}
public class UpdateInfoNode : Node
{
public readonly int ID;
public readonly Version Version;
public readonly string Title;
public readonly string Description;
public readonly string Changelog;
public readonly string File;
public readonly UpdateType Type;
public readonly long FileSize;
public readonly bool PreRelease;
internal UpdateInfoNode(string JSON)
: base(JSON)
{
ID = GetInt("id");
Version = new Version(GetString("vnr"), true);
Title = GetString("title");
Description = GetString("desc").Replace("\\r\\n", "\r\n");
Changelog = GetString("clog").Replace("\\r\\n", "\r\n");
File = GetString("file");
Type = GetEnum<UpdateType>("type");
FileSize = GetLong("size");
PreRelease = GetInt("prerelease") == 1 ? true : false;
}
}
}