-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathUpdateInstallerService.cs
More file actions
270 lines (228 loc) · 9.46 KB
/
UpdateInstallerService.cs
File metadata and controls
270 lines (228 loc) · 9.46 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
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
namespace TidyWindow.App.Services;
public sealed class UpdateInstallerService : IUpdateInstallerService
{
private readonly HttpClient _httpClient;
private readonly ActivityLogService _activityLog;
private bool _disposed;
public UpdateInstallerService(ActivityLogService activityLog)
: this(new HttpClient(), activityLog)
{
}
internal UpdateInstallerService(HttpClient httpClient, ActivityLogService activityLog)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_activityLog = activityLog ?? throw new ArgumentNullException(nameof(activityLog));
}
public async Task<UpdateInstallationResult> DownloadAndInstallAsync(
UpdateCheckResult update,
IProgress<UpdateDownloadProgress>? progress = null,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
if (update is null)
{
throw new ArgumentNullException(nameof(update));
}
if (update.DownloadUri is null)
{
throw new InvalidOperationException("Update manifest is missing a download link.");
}
var installerPath = await DownloadInstallerAsync(update, progress, cancellationToken).ConfigureAwait(false);
var hashVerified = await VerifyInstallerAsync(installerPath, update.Sha256, cancellationToken).ConfigureAwait(false);
var launched = LaunchInstaller(installerPath);
return new UpdateInstallationResult(installerPath, hashVerified, launched);
}
public void Dispose()
{
if (_disposed)
{
return;
}
_httpClient.Dispose();
_disposed = true;
}
private async Task<string> DownloadInstallerAsync(UpdateCheckResult update, IProgress<UpdateDownloadProgress>? progress, CancellationToken cancellationToken)
{
var targetDirectory = Path.Combine(Path.GetTempPath(), "TidyWindow", "Updates");
Directory.CreateDirectory(targetDirectory);
CleanupOldInstallers(targetDirectory, keepPath: null, removeEmptyDirectory: false);
var fileName = BuildInstallerFileName(update);
var filePath = Path.Combine(targetDirectory, fileName);
using var request = new HttpRequestMessage(HttpMethod.Get, update.DownloadUri);
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var contentStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
await using var destination = File.Create(filePath);
var buffer = new byte[81920];
long totalRead = 0;
var contentLength = response.Content.Headers.ContentLength;
while (true)
{
var read = await contentStream.ReadAsync(buffer.AsMemory(0, buffer.Length), cancellationToken).ConfigureAwait(false);
if (read == 0)
{
break;
}
await destination.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false);
totalRead += read;
progress?.Report(new UpdateDownloadProgress(totalRead, contentLength));
}
_activityLog.LogInformation("Updates", $"Installer downloaded to {filePath} ({FormatBytes(totalRead)}).");
return filePath;
}
private static string BuildInstallerFileName(UpdateCheckResult update)
{
var version = string.IsNullOrWhiteSpace(update.LatestVersion) ? "latest" : update.LatestVersion.Replace(' ', '_');
return $"TidyWindow-Setup-{version}.exe";
}
private static string FormatBytes(long bytes)
{
if (bytes <= 0)
{
return "0 B";
}
string[] sizes = { "B", "KB", "MB", "GB" };
var order = (int)Math.Min(sizes.Length - 1, Math.Log(bytes, 1024));
return string.Format(CultureInfo.CurrentCulture, "{0:0.##} {1}", bytes / Math.Pow(1024, order), sizes[order]);
}
private static async Task<bool> VerifyInstallerAsync(string installerPath, string? expectedHash, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(expectedHash))
{
return false;
}
var normalizedExpected = expectedHash.Trim().Replace(" ", string.Empty, StringComparison.Ordinal);
await using var stream = File.OpenRead(installerPath);
using var sha = SHA256.Create();
var computed = await sha.ComputeHashAsync(stream, cancellationToken).ConfigureAwait(false);
var computedHex = Convert.ToHexString(computed).ToLowerInvariant();
if (!string.Equals(computedHex, normalizedExpected, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Downloaded installer failed the integrity check.");
}
return true;
}
private bool LaunchInstaller(string installerPath)
{
var prompt = $"The update installer was downloaded to:\n{installerPath}\n\nInstall it now?";
var choice = ShowInstallerPrompt(prompt);
if (choice != MessageBoxResult.Yes)
{
_activityLog.LogInformation("Updates", "Installer download completed but launch was cancelled by the user.");
return false;
}
var logPath = Path.Combine(Path.GetDirectoryName(installerPath) ?? Path.GetTempPath(), "TidyWindow-Update.log");
// Show full UI, close the running instance so binaries can be replaced, and avoid automatic relaunches; the Finish page handles relaunch.
var startInfo = new ProcessStartInfo(installerPath)
{
UseShellExecute = true,
WorkingDirectory = Path.GetDirectoryName(installerPath) ?? Environment.CurrentDirectory,
Arguments = $"/SUPPRESSMSGBOXES /NORESTART /CLOSEAPPLICATIONS /NORESTARTAPPLICATIONS /LOG=\"{logPath}\""
};
try
{
Process.Start(startInfo);
_activityLog.LogInformation("Updates", "Installer launched with user confirmation. TidyWindow will close so the update can finish; use the setup Finish page to relaunch it.");
}
catch (Exception ex)
{
_activityLog.LogError("Updates", $"Failed to launch installer: {ex.Message}");
return false;
}
// Exit the running app to avoid locked files; the setup wizard remains responsible for relaunching.
Application.Current?.Dispatcher?.BeginInvoke(() => Application.Current?.Shutdown());
_ = Task.Run(async () =>
{
try
{
await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
TryDeleteInstaller(installerPath);
CleanupOldInstallers(Path.GetDirectoryName(installerPath) ?? string.Empty, keepPath: null, removeEmptyDirectory: true);
}
catch
{
// Best-effort cleanup.
}
});
return true;
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(nameof(UpdateInstallerService));
}
}
private static MessageBoxResult ShowInstallerPrompt(string prompt)
{
var dispatcher = Application.Current?.Dispatcher;
if (dispatcher is not null && !dispatcher.CheckAccess())
{
return dispatcher.Invoke(() => ShowInstallerPrompt(prompt));
}
var owner = Application.Current?.MainWindow;
owner?.Activate();
return owner is null
? MessageBox.Show(prompt, "Run TidyWindow installer", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes)
: MessageBox.Show(owner, prompt, "Run TidyWindow installer", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
}
private static void CleanupOldInstallers(string directory, string? keepPath, bool removeEmptyDirectory)
{
if (string.IsNullOrWhiteSpace(directory) || !Directory.Exists(directory))
{
return;
}
foreach (var file in Directory.EnumerateFiles(directory, "TidyWindow-Setup-*.exe", SearchOption.TopDirectoryOnly))
{
if (!string.IsNullOrWhiteSpace(keepPath) && string.Equals(file, keepPath, StringComparison.OrdinalIgnoreCase))
{
continue;
}
TryDeleteInstaller(file);
}
if (removeEmptyDirectory && !Directory.EnumerateFileSystemEntries(directory).Any())
{
TryDeleteDirectory(directory);
}
}
private static void TryDeleteInstaller(string path)
{
try
{
if (File.Exists(path))
{
File.Delete(path);
}
}
catch
{
// Ignore failures; best-effort cleanup.
}
}
private static void TryDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, recursive: true);
}
}
catch
{
// Ignore failures; best-effort cleanup.
}
}
}