-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUpdateManager.cs
More file actions
406 lines (354 loc) · 14.5 KB
/
Copy pathUpdateManager.cs
File metadata and controls
406 lines (354 loc) · 14.5 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
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Octokit;
namespace PoCXPlotterGui
{
/// <summary>
/// Result of update check operation
/// </summary>
public class UpdateCheckResult
{
public bool UpdateAvailable { get; set; }
public string LatestVersion { get; set; }
public string CurrentVersion { get; set; }
public string ReleaseNotes { get; set; }
public DateTime? PublishedAt { get; set; }
public bool IsCpuAvailable { get; set; }
public bool IsGpuAvailable { get; set; }
public List<ReleaseInfo> AvailableReleases { get; set; }
}
/// <summary>
/// Information about a specific release
/// </summary>
public class ReleaseInfo
{
public string Version { get; set; }
public string ReleaseNotes { get; set; }
public DateTime? PublishedAt { get; set; }
public bool IsPrerelease { get; set; }
public bool IsCpuAvailable { get; set; }
public bool IsGpuAvailable { get; set; }
internal Release GitHubRelease { get; set; }
public override string ToString()
{
string prefix = IsPrerelease ? "⚠ " : "";
string date = PublishedAt.HasValue ? PublishedAt.Value.ToString("yyyy-MM-dd") : "Unknown";
return $"{prefix}{Version} ({date})";
}
}
/// <summary>
/// Type of executable to download
/// </summary>
public enum ExecutableType
{
CPU,
GPU,
Both
}
/// <summary>
/// Progress information for download operation
/// </summary>
public class DownloadProgressEventArgs : EventArgs
{
public long BytesReceived { get; set; }
public long TotalBytes { get; set; }
public int ProgressPercentage { get; set; }
public string FileName { get; set; }
}
/// <summary>
/// Manages checking for updates and downloading executables from GitHub releases
/// </summary>
public class UpdateManager : IDisposable
{
private const string GITHUB_OWNER = "PoC-Consortium";
private const string GITHUB_REPO = "pocx";
private const string CPU_ASSET_PATTERN = "windows-msvc.zip";
private const string GPU_ASSET_PATTERN = "windows-msvc-opencl.zip";
private const string PLOTTER_EXE_NAME = "pocx_plotter.exe";
private const string CPU_TARGET_NAME = "pocx_plotter_cpu.exe";
private const string GPU_TARGET_NAME = "pocx_plotter_gpu.exe";
private readonly GitHubClient _githubClient;
private Release _latestRelease;
private bool _disposed = false;
public event EventHandler<DownloadProgressEventArgs> DownloadProgressChanged;
public UpdateManager()
{
_githubClient = new GitHubClient(new ProductHeaderValue("PoCXPlotterGUI"));
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// GitHubClient doesn't implement IDisposable in Octokit 14.0.0
// but we set the flag to prevent use after disposal
}
_disposed = true;
}
}
/// <summary>
/// Checks if executables are present in the application directory
/// </summary>
public static bool AreExecutablesPresent(out bool cpuMissing, out bool gpuMissing)
{
cpuMissing = !File.Exists(CPU_TARGET_NAME);
gpuMissing = !File.Exists(GPU_TARGET_NAME);
return !cpuMissing && !gpuMissing;
}
/// <summary>
/// Checks for available updates from GitHub releases
/// </summary>
public async Task<UpdateCheckResult> CheckForUpdatesAsync()
{
try
{
// Get all releases
var allReleases = await _githubClient.Repository.Release.GetAll(GITHUB_OWNER, GITHUB_REPO);
// Get latest release
_latestRelease = allReleases.FirstOrDefault();
if (_latestRelease == null)
{
throw new Exception("No releases found");
}
var result = new UpdateCheckResult
{
LatestVersion = _latestRelease.TagName,
CurrentVersion = GetCurrentVersion(),
ReleaseNotes = _latestRelease.Body,
PublishedAt = _latestRelease.PublishedAt?.DateTime,
AvailableReleases = new List<ReleaseInfo>()
};
// Check if CPU and GPU assets are available
result.IsCpuAvailable = _latestRelease.Assets.Any(a =>
a.Name.Contains(CPU_ASSET_PATTERN) && !a.Name.Contains("opencl"));
result.IsGpuAvailable = _latestRelease.Assets.Any(a =>
a.Name.Contains(GPU_ASSET_PATTERN));
// Compare versions
result.UpdateAvailable = CompareVersions(result.CurrentVersion, result.LatestVersion) < 0;
// Build list of all available releases
foreach (var release in allReleases)
{
var releaseInfo = new ReleaseInfo
{
Version = release.TagName,
ReleaseNotes = release.Body,
PublishedAt = release.PublishedAt?.DateTime,
IsPrerelease = release.Prerelease,
IsCpuAvailable = release.Assets.Any(a => a.Name.Contains(CPU_ASSET_PATTERN) && !a.Name.Contains("opencl")),
IsGpuAvailable = release.Assets.Any(a => a.Name.Contains(GPU_ASSET_PATTERN)),
GitHubRelease = release
};
result.AvailableReleases.Add(releaseInfo);
}
return result;
}
catch (Exception ex)
{
throw new Exception($"Failed to check for updates: {ex.Message}", ex);
}
}
/// <summary>
/// Downloads and installs the specified executable type(s) from latest release
/// </summary>
public async Task DownloadAndInstallAsync(ExecutableType type)
{
if (_latestRelease == null)
{
await CheckForUpdatesAsync();
}
await DownloadAndInstallAsync(type, null);
}
/// <summary>
/// Downloads and installs the specified executable type(s) from a specific release
/// </summary>
public async Task DownloadAndInstallAsync(ExecutableType type, ReleaseInfo releaseInfo)
{
Release targetRelease;
if (releaseInfo != null)
{
targetRelease = releaseInfo.GitHubRelease;
}
else
{
if (_latestRelease == null)
{
await CheckForUpdatesAsync();
}
targetRelease = _latestRelease;
}
if (type == ExecutableType.CPU || type == ExecutableType.Both)
{
await DownloadAndInstallExecutableAsync(targetRelease, CPU_ASSET_PATTERN, CPU_TARGET_NAME, false);
}
if (type == ExecutableType.GPU || type == ExecutableType.Both)
{
await DownloadAndInstallExecutableAsync(targetRelease, GPU_ASSET_PATTERN, GPU_TARGET_NAME, true);
}
// Update stored version
SaveCurrentVersion(targetRelease.TagName);
}
/// <summary>
/// Downloads and installs a specific executable from a given release
/// </summary>
private async Task DownloadAndInstallExecutableAsync(Release release, string assetPattern, string targetName, bool isOpenCl)
{
// Find the asset
var asset = release.Assets.FirstOrDefault(a =>
a.Name.Contains(assetPattern) && (isOpenCl ? a.Name.Contains("opencl") : !a.Name.Contains("opencl")));
if (asset == null)
{
throw new Exception($"Could not find {assetPattern} asset in release {release.TagName}");
}
// Download to temp directory
string tempZipPath = Path.Combine(Path.GetTempPath(), asset.Name);
string tempExtractPath = Path.Combine(Path.GetTempPath(), $"pocx_extract_{Guid.NewGuid()}");
try
{
// Download ZIP file
await DownloadFileAsync(asset.BrowserDownloadUrl, tempZipPath, asset.Name);
// Extract ZIP
Directory.CreateDirectory(tempExtractPath);
ZipFile.ExtractToDirectory(tempZipPath, tempExtractPath);
// Find pocx_plotter.exe in extracted files
string extractedPlotter = Path.Combine(tempExtractPath, PLOTTER_EXE_NAME);
if (!File.Exists(extractedPlotter))
{
throw new Exception($"{PLOTTER_EXE_NAME} not found in downloaded archive");
}
// Backup existing file if present
if (File.Exists(targetName))
{
string backupName = $"{targetName}.bak";
if (File.Exists(backupName))
{
File.Delete(backupName);
}
File.Move(targetName, backupName);
}
// Copy new file
File.Copy(extractedPlotter, targetName, true);
}
finally
{
// Cleanup temp files
if (File.Exists(tempZipPath))
{
File.Delete(tempZipPath);
}
if (Directory.Exists(tempExtractPath))
{
Directory.Delete(tempExtractPath, true);
}
}
}
/// <summary>
/// Downloads a file with progress reporting
/// </summary>
private async Task DownloadFileAsync(string url, string destinationPath, string fileName)
{
using (var httpClient = new HttpClient())
{
httpClient.Timeout = TimeSpan.FromMinutes(10);
using (var response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength ?? -1;
var canReportProgress = totalBytes != -1;
using (var contentStream = await response.Content.ReadAsStreamAsync())
using (var fileStream = new FileStream(destinationPath, System.IO.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 fileStream.WriteAsync(buffer, 0, bytesRead);
totalRead += bytesRead;
if (canReportProgress)
{
var progressPercentage = (int)((totalRead * 100) / totalBytes);
DownloadProgressChanged?.Invoke(this, new DownloadProgressEventArgs
{
BytesReceived = totalRead,
TotalBytes = totalBytes,
ProgressPercentage = progressPercentage,
FileName = fileName
});
}
}
}
}
}
}
/// <summary>
/// Gets the currently installed version
/// </summary>
private string GetCurrentVersion()
{
return Properties.Settings.Default.InstalledPlotterVersion ?? "unknown";
}
/// <summary>
/// Saves the current version to settings
/// </summary>
private void SaveCurrentVersion(string version)
{
Properties.Settings.Default.InstalledPlotterVersion = version;
Properties.Settings.Default.Save();
}
/// <summary>
/// Compares two version strings (format: v1.0.0-rc1 or v1.0.0)
/// Returns: -1 if current < latest, 0 if equal, 1 if current > latest
/// </summary>
private int CompareVersions(string current, string latest)
{
if (current == "unknown") return -1;
try
{
// Remove 'v' prefix and prerelease suffix for comparison
var currentClean = CleanVersion(current);
var latestClean = CleanVersion(latest);
var currentParts = currentClean.Split('.').Select(int.Parse).ToArray();
var latestParts = latestClean.Split('.').Select(int.Parse).ToArray();
for (int i = 0; i < Math.Min(currentParts.Length, latestParts.Length); i++)
{
if (currentParts[i] < latestParts[i]) return -1;
if (currentParts[i] > latestParts[i]) return 1;
}
return currentParts.Length.CompareTo(latestParts.Length);
}
catch
{
// If parsing fails, assume update is available
return -1;
}
}
/// <summary>
/// Cleans version string by removing 'v' prefix and prerelease suffixes
/// Example: v1.0.0-rc1 -> 1.0.0
/// </summary>
private string CleanVersion(string version)
{
if (string.IsNullOrEmpty(version)) return "0.0.0";
// Remove 'v' prefix
version = version.TrimStart('v', 'V');
// Remove prerelease suffix (-rc1, -alpha, -beta, etc.)
int dashIndex = version.IndexOf('-');
if (dashIndex > 0)
{
version = version.Substring(0, dashIndex);
}
return version;
}
}
}