-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdateChecker.cs
More file actions
79 lines (60 loc) · 2.31 KB
/
Copy pathUpdateChecker.cs
File metadata and controls
79 lines (60 loc) · 2.31 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
namespace PinWindow;
internal sealed record UpdateInfo(Version Version, string ReleaseUrl);
internal static class UpdateChecker
{
private const string LatestReleasePageUrl =
"https://github.com/helliong/pinWindow/releases/latest";
private static readonly HttpClient Client = CreateClient();
public static async Task<UpdateInfo?> CheckAsync()
{
try
{
using var response = await Client.GetAsync(
LatestReleasePageUrl,
HttpCompletionOption.ResponseHeadersRead
);
var redirectUrl = response.Headers.Location;
if (redirectUrl is null)
{
return null;
}
if (!redirectUrl.IsAbsoluteUri)
{
redirectUrl = new Uri(new Uri("https://github.com"), redirectUrl);
}
var tag = redirectUrl.Segments.LastOrDefault()?.Trim('/');
if (string.IsNullOrWhiteSpace(tag))
{
return null;
}
var normalizedTag = Uri.UnescapeDataString(tag).Trim().TrimStart('v', 'V');
if (!Version.TryParse(normalizedTag, out var latestVersion))
{
return null;
}
var currentVersion = typeof(UpdateChecker).Assembly.GetName().Version;
if (currentVersion is null || latestVersion.CompareTo(currentVersion) <= 0)
{
return null;
}
return new UpdateInfo(latestVersion, redirectUrl.ToString());
}
catch
{
// Ошибка сети не должна мешать работе PinWindow.
return null;
}
}
private static HttpClient CreateClient()
{
var handler = new HttpClientHandler { AllowAutoRedirect = false };
var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(10) };
var appVersion = typeof(UpdateChecker).Assembly.GetName().Version;
var versionText =
appVersion is null ? "unknown"
: appVersion.Build >= 0 ? $"{appVersion.Major}.{appVersion.Minor}.{appVersion.Build}"
: $"{appVersion.Major}.{appVersion.Minor}";
client.DefaultRequestHeaders.UserAgent.ParseAdd($"PinWindow/{versionText}");
return client;
}
}