-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathApp.axaml.cs
More file actions
1320 lines (1143 loc) · 48.2 KB
/
Copy pathApp.axaml.cs
File metadata and controls
1320 lines (1143 loc) · 48.2 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Layout;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Threading;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace GithubLauncher;
public class App : Application, INotifyPropertyChanged
{
private string _currentVersionString = string.Empty;
public string currentVersionString
{
get => _currentVersionString;
set
{
if (_currentVersionString != value)
{
_currentVersionString = value;
OnPropertyChanged();
}
}
}
public new event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private class GitHubAsset
{
public string name { get; set; } = string.Empty;
public string browser_download_url { get; set; } = string.Empty;
}
private class GitHubRelease
{
public string tag_name { get; set; } = string.Empty;
public GitHubAsset[] assets { get; set; } = [];
}
private class UpdateCheckInfo
{
public DateTime LastCheckTime { get; set; }
public string LastKnownVersion { get; set; } = string.Empty;
public string CurrentVersion { get; set; } = string.Empty;
public string ETag { get; set; } = string.Empty;
public bool UpdateAvailable { get; set; }
}
private class ProgressWindow : Window
{
private readonly TextBlock _statusText;
private readonly ProgressBar _progressBar;
private readonly TextBlock _percentText;
public ProgressWindow()
{
Title = "Updating Launcher";
Width = 450;
Height = 180;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
CanResize = false;
var panel = new StackPanel
{
Margin = new Thickness(30),
Spacing = 15
};
_statusText = new TextBlock
{
Text = "Preparing download...",
FontSize = 14,
Foreground = new SolidColorBrush(Colors.White),
TextAlignment = TextAlignment.Center
};
_progressBar = new ProgressBar
{
Height = 24,
Minimum = 0,
Maximum = 100,
Value = 0
};
_percentText = new TextBlock
{
Text = "0%",
FontSize = 12,
Foreground = new SolidColorBrush(Colors.LightGray),
TextAlignment = TextAlignment.Center,
Margin = new Thickness(0, -5, 0, 0)
};
panel.Children.Add(_statusText);
panel.Children.Add(_progressBar);
panel.Children.Add(_percentText);
Content = panel;
Background = new SolidColorBrush(Color.FromRgb(0x14, 0x14, 0x1a));
}
public void UpdateProgress(double percentage, string status)
{
Dispatcher.UIThread.Post(() =>
{
_progressBar.Value = percentage;
_percentText.Text = $"{percentage:F1}%";
_statusText.Text = status;
});
}
}
private static bool _hasCheckedForAppUpdates = false;
private static readonly object _updateLock = new object();
private const string Repository = "SirDiabo/GithubLauncher";
private const string VersionFileName = "version.txt";
private const string UpdateCheckFileName = "update_check.json";
private const string BackupDirectoryPrefix = "backup_";
private const int UpdaterProcessExitTimeoutSeconds = 120;
private static readonly TimeSpan UpdateCheckInterval = TimeSpan.FromMinutes(5);
private static readonly TimeSpan DownloadTimeout = TimeSpan.FromMinutes(10);
private static readonly TimeSpan StaleBackupCleanupThreshold = TimeSpan.FromMinutes(10);
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
CleanupStaleUpdateBackups();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow = new MainWindow
{
DataContext = this
};
}
base.OnFrameworkInitializationCompleted();
lock (_updateLock)
{
if (!_hasCheckedForAppUpdates)
{
_hasCheckedForAppUpdates = true;
Task.Run(async () => await CheckForUpdatesAndApplyAsync(isManualCheck: false));
}
}
}
private static void CleanupStaleUpdateBackups()
{
try
{
string currentAppDirectory = AppDomain.CurrentDomain.BaseDirectory;
DateTime cutoff = DateTime.UtcNow - StaleBackupCleanupThreshold;
foreach (string directory in Directory.EnumerateDirectories(currentAppDirectory, BackupDirectoryPrefix + "*", SearchOption.TopDirectoryOnly))
{
try
{
DateTime lastWriteUtc = Directory.GetLastWriteTimeUtc(directory);
if (lastWriteUtc > cutoff)
{
continue;
}
Directory.Delete(directory, recursive: true);
Trace.WriteLine($"Deleted stale update backup directory: {directory}");
}
catch (Exception ex)
{
Trace.WriteLine($"Failed to delete stale update backup directory '{directory}': {ex.Message}");
}
}
}
catch (Exception ex)
{
Trace.WriteLine($"Failed to scan for stale update backups: {ex.Message}");
}
}
public async Task CheckForAppUpdatesManually()
{
await CheckForUpdatesAndApplyAsync(isManualCheck: true);
}
private async Task CheckForUpdatesAndApplyAsync(bool isManualCheck = false)
{
string currentAppDirectory = AppDomain.CurrentDomain.BaseDirectory;
string updateCheckFilePath = Path.Combine(currentAppDirectory, UpdateCheckFileName);
UpdateCheckInfo updateCheckInfo = await LoadUpdateCheckInfo(updateCheckFilePath);
string currentVersionString = updateCheckInfo.CurrentVersion;
// get it from version.txt if it exists
if (string.IsNullOrEmpty(currentVersionString))
{
string versionFilePath = Path.Combine(currentAppDirectory, VersionFileName);
if (File.Exists(versionFilePath))
{
try
{
currentVersionString = (await File.ReadAllTextAsync(versionFilePath).ConfigureAwait(false))?.Trim() ?? "0.0";
}
catch
{
currentVersionString = "0.0";
}
}
else
{
currentVersionString = "0.0";
}
// Store it in update check info
updateCheckInfo.CurrentVersion = currentVersionString;
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
}
// Skip check if not manual and recently checked
if (!isManualCheck && ShouldSkipUpdateCheck(updateCheckInfo, currentVersionString))
{
Trace.WriteLine($"Skipping app update check - last checked {updateCheckInfo.LastCheckTime}, current version {currentVersionString}");
if (updateCheckInfo.UpdateAvailable &&
!string.IsNullOrEmpty(updateCheckInfo.LastKnownVersion) &&
IsNewerVersion(updateCheckInfo.LastKnownVersion, currentVersionString))
{
Trace.WriteLine($"Cached app update available: {updateCheckInfo.LastKnownVersion}");
if (IsBootstrapVersion(currentVersionString))
{
using (var httpClient = new HttpClient())
{
httpClient.Timeout = DownloadTimeout;
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("GithubLauncher-Updater");
var settings = AppSettings.Load();
if (!string.IsNullOrEmpty(settings?.GitHubApiToken))
{
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", settings.GitHubApiToken);
}
try
{
string apiUrl = $"https://api.github.com/repos/{Repository}/releases/latest";
var response = await httpClient.GetAsync(apiUrl);
response.EnsureSuccessStatusCode();
string releaseResponse = await response.Content.ReadAsStringAsync();
GitHubRelease? latestRelease = JsonSerializer.Deserialize<GitHubRelease>(releaseResponse);
if (latestRelease != null)
{
await DownloadAndApplyUpdate(latestRelease, AppDomain.CurrentDomain.BaseDirectory, updateCheckInfo);
}
}
catch (Exception ex)
{
await ShowMessageBoxAsync($"Failed to download bootstrap update: {ex.Message}", "Update Error");
}
}
return;
}
// Prompt user about available update
await Dispatcher.UIThread.InvokeAsync(async () =>
{
var result = await ShowMessageBoxWithChoiceAsync(
$"Launcher update {updateCheckInfo.LastKnownVersion} is available!\n\nWould you like to update now?",
"Update Available");
if (result)
{
using (var httpClient = new HttpClient())
{
httpClient.Timeout = DownloadTimeout;
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("GithubLauncher-Updater");
var settings = AppSettings.Load();
if (!string.IsNullOrEmpty(settings?.GitHubApiToken))
{
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", settings.GitHubApiToken);
}
try
{
string apiUrl = $"https://api.github.com/repos/{Repository}/releases/latest";
var response = await httpClient.GetAsync(apiUrl);
response.EnsureSuccessStatusCode();
string releaseResponse = await response.Content.ReadAsStringAsync();
GitHubRelease? latestRelease = JsonSerializer.Deserialize<GitHubRelease>(releaseResponse);
if (latestRelease != null)
{
await DownloadAndApplyUpdate(latestRelease, AppDomain.CurrentDomain.BaseDirectory, updateCheckInfo);
}
}
catch (Exception ex)
{
await ShowMessageBoxAsync($"Failed to download update: {ex.Message}", "Update Error");
}
}
}
});
}
return;
}
using (var httpClient = new HttpClient())
{
httpClient.Timeout = DownloadTimeout;
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("GithubLauncher-Updater");
var settings = AppSettings.Load();
if (!string.IsNullOrEmpty(settings?.GitHubApiToken))
{
httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", settings.GitHubApiToken);
}
if (!string.IsNullOrEmpty(updateCheckInfo.ETag))
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("If-None-Match", updateCheckInfo.ETag);
}
try
{
string apiUrl = $"https://api.github.com/repos/{Repository}/releases/latest";
var response = await httpClient.GetAsync(apiUrl);
updateCheckInfo.LastCheckTime = DateTime.UtcNow;
updateCheckInfo.CurrentVersion = currentVersionString;
if (response.StatusCode == System.Net.HttpStatusCode.NotModified)
{
Trace.WriteLine("No app updates available (304 Not Modified)");
updateCheckInfo.UpdateAvailable = false;
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
if (isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync("Launcher is up to date!", "No Updates");
});
}
return;
}
response.EnsureSuccessStatusCode();
if (response.Headers.ETag != null)
{
updateCheckInfo.ETag = response.Headers.ETag.Tag;
}
string releaseResponse = await response.Content.ReadAsStringAsync();
GitHubRelease? latestRelease = JsonSerializer.Deserialize<GitHubRelease>(releaseResponse);
if (latestRelease == null || string.IsNullOrWhiteSpace(latestRelease.tag_name))
{
Trace.WriteLine("No valid latest release information found on GitHub.");
updateCheckInfo.UpdateAvailable = false;
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
if (isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync("Could not find launcher update information.", "No Updates");
});
}
return;
}
updateCheckInfo.LastKnownVersion = latestRelease.tag_name;
if (!IsNewerVersion(latestRelease.tag_name, currentVersionString))
{
Trace.WriteLine($"Current launcher version {currentVersionString} is up to date or newer than {latestRelease.tag_name}. No update needed.");
updateCheckInfo.UpdateAvailable = false;
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
if (isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"Launcher is up to date! (v{currentVersionString})", "No Updates");
});
}
return;
}
Trace.WriteLine($"Newer launcher version {latestRelease.tag_name} available. Current version is {currentVersionString}.");
updateCheckInfo.UpdateAvailable = true;
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
if (IsBootstrapVersion(currentVersionString))
{
await DownloadAndApplyUpdate(latestRelease, currentAppDirectory, updateCheckInfo);
return;
}
if (!isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
var result = await ShowMessageBoxWithChoiceAsync(
$"Launcher update {latestRelease.tag_name} is available!\n\nWould you like to update now?",
"Update Available");
if (result)
{
await DownloadAndApplyUpdate(latestRelease, currentAppDirectory, updateCheckInfo);
}
});
}
if (isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
var result = await ShowMessageBoxWithChoiceAsync(
$"Launcher update {latestRelease.tag_name} is available!\n\nWould you like to update now?",
"Update Available");
if (result)
{
await DownloadAndApplyUpdate(latestRelease, currentAppDirectory, updateCheckInfo);
}
});
}
}
catch (HttpRequestException httpEx)
{
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
if (isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"Could not check for launcher updates (Network Error): {httpEx.Message}",
"Update Check Failed");
});
}
}
catch (Exception ex)
{
await SaveUpdateCheckInfo(updateCheckFilePath, updateCheckInfo);
if (isManualCheck)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"An error occurred during launcher update check: {ex.Message}",
"Update Check Failed");
});
}
}
}
}
private async Task<bool> ShowMessageBoxWithChoiceAsync(string message, string title)
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop &&
desktop.MainWindow != null)
{
bool result = false;
var messageBox = new Window
{
Title = title,
Width = 450,
Height = 170,
WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterOwner,
Content = new StackPanel
{
Margin = new Thickness(20),
Children =
{
new TextBlock
{
Text = message,
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 0, 0, 20)
},
new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center,
Children =
{
new Button
{
Content = "Yes",
Margin = new Thickness(0, 0, 10, 0),
MinWidth = 80
},
new Button
{
Content = "No",
MinWidth = 80
}
}
}
}
}
};
if (((StackPanel)messageBox.Content).Children[1] is StackPanel buttonPanel &&
buttonPanel.Children[0] is Button yesButton &&
buttonPanel.Children[1] is Button noButton)
{
yesButton.Click += (s, e) =>
{
result = true;
messageBox.Close();
};
noButton.Click += (s, e) =>
{
result = false;
messageBox.Close();
};
}
await messageBox.ShowDialog(desktop.MainWindow);
return result;
}
return false;
}
private async Task ShowMessageBoxAsync(string message, string title)
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop &&
desktop.MainWindow != null)
{
var messageBox = new Window
{
Title = title,
Width = 400,
Height = 150,
WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterOwner,
Content = new StackPanel
{
Margin = new Thickness(20),
Children =
{
new TextBlock { Text = message, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 0, 0, 20) },
new Button { Content = "OK", HorizontalAlignment = HorizontalAlignment.Center }
}
}
};
if (((StackPanel)messageBox.Content).Children[1] is Button okButton)
{
okButton.Click += (s, e) => messageBox.Close();
}
await messageBox.ShowDialog(desktop.MainWindow);
}
}
private async Task<UpdateCheckInfo> LoadUpdateCheckInfo(string filePath)
{
if (!File.Exists(filePath))
{
return new UpdateCheckInfo
{
LastCheckTime = DateTime.MinValue,
LastKnownVersion = string.Empty,
CurrentVersion = string.Empty,
ETag = string.Empty,
UpdateAvailable = false
};
}
try
{
string json = await File.ReadAllTextAsync(filePath);
var info = JsonSerializer.Deserialize<UpdateCheckInfo>(json) ?? new UpdateCheckInfo();
if (string.IsNullOrEmpty(info.CurrentVersion))
info.CurrentVersion = string.Empty;
return info;
}
catch (Exception ex)
{
Trace.WriteLine($"Error loading update check info: {ex.Message}");
return new UpdateCheckInfo
{
LastCheckTime = DateTime.MinValue,
LastKnownVersion = string.Empty,
CurrentVersion = string.Empty,
ETag = string.Empty,
UpdateAvailable = false
};
}
}
private async Task SaveUpdateCheckInfo(string filePath, UpdateCheckInfo info)
{
try
{
string json = JsonSerializer.Serialize(info, new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllTextAsync(filePath, json);
}
catch (Exception ex)
{
Trace.WriteLine($"Error saving update check info: {ex.Message}");
}
}
private bool ShouldSkipUpdateCheck(UpdateCheckInfo info, string currentVersion)
{
if (info.LastCheckTime == DateTime.MinValue)
return false;
if (DateTime.UtcNow - info.LastCheckTime < UpdateCheckInterval)
return true;
if (!string.IsNullOrEmpty(info.CurrentVersion) &&
!info.CurrentVersion.Equals(currentVersion.TrimStart('v'), StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!string.IsNullOrEmpty(info.LastKnownVersion) &&
!string.IsNullOrEmpty(currentVersion) &&
!IsNewerVersion(info.LastKnownVersion, currentVersion))
{
return true;
}
return false;
}
private bool IsNewerVersion(string latestVersion, string currentVersion)
{
try
{
string normalizedLatest = NormalizeVersionString(latestVersion);
string normalizedCurrent = NormalizeVersionString(currentVersion);
Trace.WriteLine($"Comparing versions - Latest: '{latestVersion}' ({normalizedLatest}) vs Current: '{currentVersion}' ({normalizedCurrent})");
Version current = new Version(normalizedCurrent);
Version latest = new Version(normalizedLatest);
bool isNewer = latest.CompareTo(current) > 0;
Trace.WriteLine($"IsNewerVersion result: {isNewer}");
return isNewer;
}
catch (Exception ex)
{
Trace.WriteLine($"Error comparing versions '{latestVersion}' vs '{currentVersion}': {ex.Message}");
bool shouldUpdate = !latestVersion.TrimStart('v', 'V').Equals(currentVersion.TrimStart('v', 'V'), StringComparison.OrdinalIgnoreCase);
Trace.WriteLine($"Version parsing failed, using string comparison: {shouldUpdate}");
return shouldUpdate;
}
}
private bool IsBootstrapVersion(string version)
{
try
{
Version parsedVersion = new Version(NormalizeVersionString(version));
return parsedVersion == new Version(0, 0);
}
catch
{
var trimmed = version.TrimStart('v', 'V').Trim();
return trimmed == "0" || trimmed == "0.0" || trimmed == "0.0.0" || trimmed == "0.0.0.0";
}
}
private string NormalizeVersionString(string version)
{
if (string.IsNullOrWhiteSpace(version))
return "0.0.0.0";
version = version.TrimStart('v', 'V').Trim();
var parts = version.Split('.');
var validParts = new List<string>();
foreach (var part in parts)
{
if (int.TryParse(part.Trim(), out int number))
{
validParts.Add(number.ToString());
}
}
while (validParts.Count < 2)
{
validParts.Add("0");
}
if (validParts.Count == 2)
{
return $"{validParts[0]}.{validParts[1]}";
}
else if (validParts.Count == 3)
{
return $"{validParts[0]}.{validParts[1]}.{validParts[2]}";
}
else
{
return $"{validParts[0]}.{validParts[1]}.{validParts[2]}.{validParts[3]}";
}
}
private async Task DownloadAndApplyUpdate(GitHubRelease latestRelease, string currentAppDirectory, UpdateCheckInfo updateCheckInfo)
{
string platformIdentifier = GetPlatformIdentifier();
var asset = latestRelease.assets.FirstOrDefault(a =>
a.name.Contains(platformIdentifier, StringComparison.OrdinalIgnoreCase) &&
(a.name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) || a.name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
);
if (asset == null)
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"No downloadable update found for your platform ({platformIdentifier}).",
"Update Error");
});
return;
}
DriveInfo? drive = null;
string? rootPath = Path.GetPathRoot(currentAppDirectory);
if (!string.IsNullOrEmpty(rootPath))
{
drive = new DriveInfo(rootPath);
}
else
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync("Could not determine the root drive for update. Update aborted.", "Update Error");
});
return;
}
ProgressWindow? progressWindow = null;
await Dispatcher.UIThread.InvokeAsync(async () =>
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop && desktop.MainWindow != null)
{
progressWindow = new ProgressWindow();
_ = progressWindow.ShowDialog(desktop.MainWindow);
}
});
using (var httpClient = new HttpClient())
{
httpClient.Timeout = DownloadTimeout;
string tempDownloadPath = Path.Combine(Path.GetTempPath(), asset.name);
try
{
progressWindow?.UpdateProgress(0, "Downloading update...");
using (var downloadResponse = await httpClient.GetAsync(asset.browser_download_url, HttpCompletionOption.ResponseHeadersRead))
{
downloadResponse.EnsureSuccessStatusCode();
var totalBytes = downloadResponse.Content.Headers.ContentLength ?? 0;
var canReportProgress = totalBytes > 0;
using var contentStream = await downloadResponse.Content.ReadAsStreamAsync();
using var fs = new FileStream(tempDownloadPath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true);
var buffer = new byte[8192];
long totalRead = 0;
int bytesRead;
while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await fs.WriteAsync(buffer, 0, bytesRead);
totalRead += bytesRead;
if (canReportProgress)
{
var percentage = (double)totalRead / totalBytes * 100;
progressWindow?.UpdateProgress(percentage, $"Downloading update... ({totalRead / 1024 / 1024:F1} MB / {totalBytes / 1024 / 1024:F1} MB)");
}
}
}
progressWindow?.UpdateProgress(100, "Download complete. Extracting...");
await Task.Delay(500); // Brief pause so user can see 100%
string tempUpdateFolder = Path.Combine(Path.GetTempPath(), "GithubLauncher_temp_update");
if (Directory.Exists(tempUpdateFolder))
{
Directory.Delete(tempUpdateFolder, true);
}
Directory.CreateDirectory(tempUpdateFolder);
try
{
if (asset.name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
ZipFile.ExtractToDirectory(tempDownloadPath, tempUpdateFolder, true);
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var appBundle = Directory.GetDirectories(tempUpdateFolder, "*.app", SearchOption.AllDirectories)
.FirstOrDefault();
if (!string.IsNullOrEmpty(appBundle))
{
var appName = Path.GetFileName(appBundle);
var newAppPath = Path.Combine(tempUpdateFolder, appName);
if (appBundle != newAppPath)
{
Directory.Move(appBundle, newAppPath);
}
}
}
}
else if (asset.name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
{
await ExtractTarGzAsync(tempDownloadPath, tempUpdateFolder);
}
else
{
progressWindow?.UpdateProgress(0, "Error: Unsupported archive format");
await Task.Delay(2000);
await Dispatcher.UIThread.InvokeAsync(() => progressWindow?.Close());
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"Unsupported archive format: {asset.name}",
"Update Error");
});
return;
}
}
catch (Exception ex)
{
progressWindow?.UpdateProgress(0, "Error during extraction");
await Task.Delay(2000);
await Dispatcher.UIThread.InvokeAsync(() => progressWindow?.Close());
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"Failed to extract update archive: {ex.Message}",
"Update Error");
});
return;
}
progressWindow?.UpdateProgress(100, "Validating update...");
if (!ValidateUpdateFiles(tempUpdateFolder))
{
await Dispatcher.UIThread.InvokeAsync(() => progressWindow?.Close());
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync("Downloaded update appears to be corrupted or incomplete.",
"Update Error");
});
return;
}
progressWindow?.UpdateProgress(100, "Preparing to install...");
await Task.Delay(500);
await Dispatcher.UIThread.InvokeAsync(() => progressWindow?.Close());
await CreateAndRunUpdaterScript(latestRelease, tempUpdateFolder, tempDownloadPath, currentAppDirectory, updateCheckInfo);
}
catch (TaskCanceledException)
{
await Dispatcher.UIThread.InvokeAsync(() => progressWindow?.Close());
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync("Update download timed out. Please check your internet connection.",
"Update Error");
});
}
catch (Exception ex)
{
await Dispatcher.UIThread.InvokeAsync(() => progressWindow?.Close());
await Dispatcher.UIThread.InvokeAsync(async () =>
{
await ShowMessageBoxAsync($"Error downloading update: {ex.Message}",
"Update Error");
});
}
}
}
private async Task ExtractTarGzAsync(string tarGzPath, string extractPath)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var process = new ProcessStartInfo
{
FileName = "tar",
Arguments = $"-xzf \"{tarGzPath}\" -C \"{extractPath}\"",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true
};
using var proc = Process.Start(process);
if (proc != null)
{
await proc.WaitForExitAsync();
if (proc.ExitCode != 0)
{
var error = await proc.StandardError.ReadToEndAsync();
throw new InvalidOperationException($"tar extraction failed: {error}");
}
}
else
{
throw new InvalidOperationException("Failed to start tar process");
}
}
else
{
throw new NotSupportedException("tar.gz extraction not supported on this platform");
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to extract tar.gz file: {ex.Message}", ex);
}
}
private bool ValidateUpdateFiles(string updateDirectory)
{
try
{
string mainExecutable;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
mainExecutable = Path.Combine(updateDirectory, "GithubLauncher.exe");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var appBundle = Directory.GetDirectories(updateDirectory, "*.app", SearchOption.TopDirectoryOnly)
.FirstOrDefault();
if (!string.IsNullOrEmpty(appBundle))
{
mainExecutable = appBundle;
}
else
{
mainExecutable = Path.Combine(updateDirectory, "GithubLauncher");
}
}
else
{
mainExecutable = Path.Combine(updateDirectory, "GithubLauncher");