-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubUpdateService.cs
More file actions
596 lines (509 loc) · 18.5 KB
/
Copy pathGitHubUpdateService.cs
File metadata and controls
596 lines (509 loc) · 18.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
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Reflection;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace c2flux
{
public enum GitHubUpdateErrorKind
{
None,
Timeout,
Network,
Http,
InvalidJson,
InvalidResponse,
InvalidVersion,
Unexpected
}
public sealed class GitHubUpdateResult
{
public bool CanConnectToGitHub { get; set; }
public bool UpdateAvailable { get; set; }
public string LatestVersion { get; set; }
public string DownloadUrl { get; set; }
public string ReleaseNotes { get; set; }
public GitHubUpdateErrorKind ErrorKind { get; set; }
}
public static class GitHubUpdateService
{
private static readonly TimeSpan RequestTimeout =
TimeSpan.FromSeconds(10);
private static readonly Regex SemanticVersionRegex =
new Regex(
@"^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$",
RegexOptions.Compiled |
RegexOptions.CultureInvariant);
public static async Task<GitHubUpdateResult> CheckForUpdateAsync()
{
string currentVersionText = GetApplicationVersionText();
try
{
using HttpClient httpClient = new HttpClient
{
Timeout = RequestTimeout
};
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(
AppConstants.GitHubUserAgent);
string releasesApiUrl =
GetReleasesApiUrl();
using HttpResponseMessage response =
await httpClient.GetAsync(
releasesApiUrl);
response.EnsureSuccessStatusCode();
string json =
await response.Content.ReadAsStringAsync();
using JsonDocument jsonDocument =
JsonDocument.Parse(json);
JsonElement root = jsonDocument.RootElement;
if (root.ValueKind != JsonValueKind.Array)
{
return CreateFailureResult(
GitHubUpdateErrorKind.InvalidResponse,
true,
"The GitHub update response has an invalid root element.",
"URL: " +
releasesApiUrl);
}
if (!TryParseSemanticVersion(
NormalizeVersionText(currentVersionText),
out SemanticVersion currentVersion))
{
return CreateFailureResult(
GitHubUpdateErrorKind.InvalidVersion,
true,
"The current application version could not be parsed.",
"Version: " +
currentVersionText);
}
bool releaseFound = false;
SemanticVersion latestVersion = default;
string latestVersionText = string.Empty;
string downloadUrl = AppConstants.GitHubRepositoryUrl;
string releaseNotes = string.Empty;
foreach (JsonElement releaseElement in root.EnumerateArray())
{
if (releaseElement.ValueKind != JsonValueKind.Object)
{
continue;
}
if (releaseElement.TryGetProperty(
"draft",
out JsonElement draftElement) &&
draftElement.ValueKind == JsonValueKind.True)
{
continue;
}
if (!releaseElement.TryGetProperty(
"tag_name",
out JsonElement tagNameElement) ||
tagNameElement.ValueKind != JsonValueKind.String)
{
continue;
}
string candidateVersionText =
NormalizeVersionText(
tagNameElement.GetString());
if (!TryParseSemanticVersion(
candidateVersionText,
out SemanticVersion candidateVersion))
{
continue;
}
if (releaseFound &&
candidateVersion.CompareTo(latestVersion) <= 0)
{
continue;
}
releaseFound = true;
latestVersion = candidateVersion;
latestVersionText = candidateVersionText;
if (releaseElement.TryGetProperty(
"html_url",
out JsonElement htmlUrlElement) &&
htmlUrlElement.ValueKind == JsonValueKind.String &&
!string.IsNullOrWhiteSpace(
htmlUrlElement.GetString()))
{
downloadUrl = htmlUrlElement.GetString();
}
else
{
downloadUrl = AppConstants.GitHubRepositoryUrl;
}
if (releaseElement.TryGetProperty(
"body",
out JsonElement bodyElement) &&
bodyElement.ValueKind == JsonValueKind.String)
{
releaseNotes =
ExtractWhatsNew(
bodyElement.GetString());
}
else
{
releaseNotes = string.Empty;
}
}
if (!releaseFound)
{
return CreateFailureResult(
GitHubUpdateErrorKind.InvalidVersion,
true,
"No valid semantic version was found in the GitHub releases.",
"URL: " +
releasesApiUrl);
}
return new GitHubUpdateResult
{
CanConnectToGitHub = true,
UpdateAvailable =
latestVersion.CompareTo(currentVersion) > 0,
LatestVersion = latestVersionText,
DownloadUrl = downloadUrl,
ReleaseNotes = releaseNotes,
ErrorKind = GitHubUpdateErrorKind.None
};
}
catch (TaskCanceledException exception)
{
return CreateFailureResult(
GitHubUpdateErrorKind.Timeout,
false,
"The GitHub update request timed out.",
exception.ToString());
}
catch (HttpRequestException exception)
{
GitHubUpdateErrorKind errorKind =
exception.StatusCode.HasValue
? GitHubUpdateErrorKind.Http
: GitHubUpdateErrorKind.Network;
string message =
exception.StatusCode.HasValue
? "The GitHub update request returned an HTTP error."
: "The GitHub update request failed because of a network error.";
return CreateFailureResult(
errorKind,
false,
message,
exception.ToString());
}
catch (JsonException exception)
{
return CreateFailureResult(
GitHubUpdateErrorKind.InvalidJson,
true,
"The GitHub update response contains invalid JSON.",
exception.ToString());
}
catch (Exception exception)
{
return CreateFailureResult(
GitHubUpdateErrorKind.Unexpected,
false,
"The GitHub update check failed unexpectedly.",
exception.ToString());
}
}
public static string GetApplicationVersionText()
{
Assembly assembly = typeof(GitHubUpdateService).Assembly;
foreach (object attribute in assembly.GetCustomAttributes(
typeof(AssemblyInformationalVersionAttribute),
false))
{
if (attribute is AssemblyInformationalVersionAttribute
informationalVersionAttribute &&
!string.IsNullOrWhiteSpace(
informationalVersionAttribute
.InformationalVersion))
{
return informationalVersionAttribute
.InformationalVersion
.Split('+')[0];
}
}
Version version = assembly.GetName().Version;
if (version == null)
{
return LocalizationService.GetText("Common.Unknown");
}
return version.Major +
"." +
version.Minor +
"." +
version.Build;
}
private static GitHubUpdateResult CreateFailureResult(
GitHubUpdateErrorKind errorKind,
bool canConnectToGitHub,
string message,
string details)
{
AppAlertLog.AddWarning(
"GitHub update",
message,
"URL: " +
GetReleasesApiUrl() +
Environment.NewLine +
details);
return new GitHubUpdateResult
{
CanConnectToGitHub = canConnectToGitHub,
UpdateAvailable = false,
LatestVersion = string.Empty,
DownloadUrl = string.Empty,
ReleaseNotes = string.Empty,
ErrorKind = errorKind
};
}
private static string ExtractWhatsNew(
string releaseBody)
{
if (string.IsNullOrWhiteSpace(releaseBody))
{
return string.Empty;
}
string normalizedBody =
releaseBody.Replace(
"\r\n",
"\n");
string[] lines =
normalizedBody.Split('\n');
bool inWhatsNewSection = false;
List<string> releaseNoteLines =
new List<string>();
foreach (string rawLine in lines)
{
string line = rawLine.Trim();
if (!inWhatsNewSection)
{
if (string.Equals(
line,
"## What's new",
StringComparison.OrdinalIgnoreCase))
{
inWhatsNewSection = true;
}
continue;
}
if (line.StartsWith(
"#",
StringComparison.Ordinal))
{
break;
}
if (!line.StartsWith(
"- ",
StringComparison.Ordinal) &&
!line.StartsWith(
"* ",
StringComparison.Ordinal))
{
continue;
}
releaseNoteLines.Add(
"• " +
line.Substring(2).Trim());
if (releaseNoteLines.Count == 5)
{
break;
}
}
if (releaseNoteLines.Count == 0)
{
return string.Empty;
}
return "What's new:" +
Environment.NewLine +
string.Join(
Environment.NewLine,
releaseNoteLines);
}
private static string GetReleasesApiUrl()
{
string latestReleaseApiUrl =
AppConstants.GitHubLatestReleaseApiUrl.TrimEnd('/');
const string latestSuffix = "/latest";
if (latestReleaseApiUrl.EndsWith(
latestSuffix,
StringComparison.OrdinalIgnoreCase))
{
latestReleaseApiUrl =
latestReleaseApiUrl.Substring(
0,
latestReleaseApiUrl.Length -
latestSuffix.Length);
}
return latestReleaseApiUrl +
"?per_page=100";
}
private static string NormalizeVersionText(
string versionText)
{
if (string.IsNullOrWhiteSpace(versionText))
{
return string.Empty;
}
return versionText.Trim().TrimStart('v', 'V');
}
private static bool TryParseSemanticVersion(
string versionText,
out SemanticVersion semanticVersion)
{
semanticVersion = default;
Match match =
SemanticVersionRegex.Match(versionText);
if (!match.Success)
{
return false;
}
if (!int.TryParse(
match.Groups["major"].Value,
NumberStyles.None,
CultureInfo.InvariantCulture,
out int major) ||
!int.TryParse(
match.Groups["minor"].Value,
NumberStyles.None,
CultureInfo.InvariantCulture,
out int minor) ||
!int.TryParse(
match.Groups["patch"].Value,
NumberStyles.None,
CultureInfo.InvariantCulture,
out int patch))
{
return false;
}
string prerelease =
match.Groups["prerelease"].Success
? match.Groups["prerelease"].Value
: string.Empty;
semanticVersion =
new SemanticVersion(
major,
minor,
patch,
prerelease);
return true;
}
private readonly struct SemanticVersion :
IComparable<SemanticVersion>
{
private readonly int _major;
private readonly int _minor;
private readonly int _patch;
private readonly string _prerelease;
public SemanticVersion(
int major,
int minor,
int patch,
string prerelease)
{
_major = major;
_minor = minor;
_patch = patch;
_prerelease = prerelease ?? string.Empty;
}
public int CompareTo(
SemanticVersion other)
{
int result =
_major.CompareTo(other._major);
if (result != 0)
{
return result;
}
result =
_minor.CompareTo(other._minor);
if (result != 0)
{
return result;
}
result =
_patch.CompareTo(other._patch);
if (result != 0)
{
return result;
}
bool isPrerelease =
!string.IsNullOrEmpty(_prerelease);
bool otherIsPrerelease =
!string.IsNullOrEmpty(other._prerelease);
if (!isPrerelease && !otherIsPrerelease)
{
return 0;
}
if (!isPrerelease)
{
return 1;
}
if (!otherIsPrerelease)
{
return -1;
}
string[] identifiers =
_prerelease.Split('.');
string[] otherIdentifiers =
other._prerelease.Split('.');
int identifierCount =
Math.Min(
identifiers.Length,
otherIdentifiers.Length);
for (int index = 0;
index < identifierCount;
index++)
{
result =
ComparePrereleaseIdentifier(
identifiers[index],
otherIdentifiers[index]);
if (result != 0)
{
return result;
}
}
return identifiers.Length.CompareTo(
otherIdentifiers.Length);
}
private static int ComparePrereleaseIdentifier(
string identifier,
string otherIdentifier)
{
bool isNumeric =
long.TryParse(
identifier,
NumberStyles.None,
CultureInfo.InvariantCulture,
out long numericValue);
bool otherIsNumeric =
long.TryParse(
otherIdentifier,
NumberStyles.None,
CultureInfo.InvariantCulture,
out long otherNumericValue);
if (isNumeric && otherIsNumeric)
{
return numericValue.CompareTo(
otherNumericValue);
}
if (isNumeric)
{
return -1;
}
if (otherIsNumeric)
{
return 1;
}
return string.CompareOrdinal(
identifier,
otherIdentifier);
}
}
}
}