-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdateChecker.cs
More file actions
328 lines (295 loc) · 12 KB
/
Copy pathUpdateChecker.cs
File metadata and controls
328 lines (295 loc) · 12 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
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace BreakReminder
{
/// <summary>
/// 检查程序更新的辅助类
/// 从GitHub Release API获取最新版本信息
/// </summary>
public class UpdateChecker
{
private const string GITHUB_API_URL = "https://api.github.com/repos/FDscend/BreakReminder/releases/latest";
private const string GITHUB_RELEASE_URL = "https://github.com/FDscend/BreakReminder/releases";
private const int NETWORK_TIMEOUT_MS = 5000; // 5秒网络超时
public delegate void UpdateAvailableDelegate(string latestVersion, string downloadUrl);
/// <summary>
/// 异步检查更新,如果有新版本则弹窗提示
/// </summary>
public static void CheckForUpdatesAsync(UpdateAvailableDelegate onUpdateAvailable)
{
// 在后台线程中检查更新,不阻塞主线程
Thread updateThread = new Thread(() =>
{
try
{
CheckForUpdates(onUpdateAvailable);
}
catch (Exception ex)
{
// 更新检查失败,静默处理,不影响应用运行
System.Diagnostics.Debug.WriteLine($"Update check failed: {ex.Message}");
}
})
{
IsBackground = true,
Name = "UpdateCheckerThread"
};
updateThread.Start();
}
/// <summary>
/// 检查更新的核心逻辑
/// </summary>
private static void CheckForUpdates(UpdateAvailableDelegate onUpdateAvailable)
{
try
{
// 首先检查网络连接
if (!IsNetworkAvailable())
{
System.Diagnostics.Debug.WriteLine("Network not available, skipping update check");
return;
}
// 获取当前程序版本
Version currentVersion = Assembly.GetExecutingAssembly().GetName().Version;
string currentVersionStr = $"v{currentVersion.Major}.{currentVersion.Minor}";
// 从GitHub API获取最新Release信息
string latestReleaseJson = FetchLatestRelease();
if (string.IsNullOrWhiteSpace(latestReleaseJson))
return;
// 解析JSON响应获取版本号和下载链接
string latestVersion = ExtractVersionFromJson(latestReleaseJson);
string downloadUrl = ExtractDownloadUrlFromJson(latestReleaseJson);
if (string.IsNullOrWhiteSpace(latestVersion) || string.IsNullOrWhiteSpace(downloadUrl))
return;
// 比较版本号
if (IsNewerVersion(currentVersionStr, latestVersion))
{
// 新版本可用,调用回调函数
onUpdateAvailable?.Invoke(latestVersion, downloadUrl);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"UpdateChecker error: {ex.Message}");
}
}
/// <summary>
/// 检查网络连接是否可用
/// </summary>
private static bool IsNetworkAvailable()
{
try
{
// 使用 System.Net.NetworkInformation 检查网络连接
return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
catch
{
// 无法判断,默认认为网络可用
return true;
}
}
/// <summary>
/// 从GitHub API获取最新Release信息(JSON格式)
/// </summary>
private static string FetchLatestRelease()
{
try
{
using (WebClient client = new WebClient())
{
// 设置User-Agent避免被GitHub API拒绝
client.Headers.Add("User-Agent", "BreakReminder");
client.Encoding = Encoding.UTF8;
// 设置超时(毫秒)
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.DefaultConnectionLimit = Environment.ProcessorCount * 12;
ServicePointManager.ReusePort = true;
// 使用try-with-timeout的方式
using (var cts = new System.Threading.CancellationTokenSource(NETWORK_TIMEOUT_MS))
{
var downloadTask = System.Threading.Tasks.Task.Run(() =>
{
return client.DownloadString(GITHUB_API_URL);
}, cts.Token);
if (downloadTask.Wait(NETWORK_TIMEOUT_MS))
{
return downloadTask.Result;
}
else
{
System.Diagnostics.Debug.WriteLine("Update check timeout");
return null;
}
}
}
}
catch (WebException ex)
{
// 网络错误详细处理
if (ex.Status == WebExceptionStatus.Timeout)
{
System.Diagnostics.Debug.WriteLine("GitHub API request timeout");
}
else if (ex.Status == WebExceptionStatus.ConnectFailure)
{
System.Diagnostics.Debug.WriteLine("Cannot connect to GitHub API");
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
System.Diagnostics.Debug.WriteLine("DNS resolution failed");
}
else
{
System.Diagnostics.Debug.WriteLine($"Failed to fetch release info: {ex.Status} - {ex.Message}");
}
return null;
}
catch (System.OperationCanceledException)
{
System.Diagnostics.Debug.WriteLine("Update check cancelled due to timeout");
return null;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Unexpected error fetching release: {ex.Message}");
return null;
}
}
/// <summary>
/// 从JSON响应中提取版本号(tag_name字段,格式为"v1.1")
/// </summary>
private static string ExtractVersionFromJson(string json)
{
try
{
// 查找"tag_name"字段
string tagPattern = "\"tag_name\":\"";
int startIndex = json.IndexOf(tagPattern);
if (startIndex < 0)
return null;
startIndex += tagPattern.Length;
int endIndex = json.IndexOf("\"", startIndex);
if (endIndex < startIndex)
return null;
return json.Substring(startIndex, endIndex - startIndex);
}
catch
{
return null;
}
}
/// <summary>
/// 从JSON响应中提取下载链接
/// 获取第一个.exe格式的release asset的下载链接
/// </summary>
private static string ExtractDownloadUrlFromJson(string json)
{
try
{
// 查找assets数组中的exe下载链接
string browserDownloadUrlPattern = "\"browser_download_url\":\"";
int searchStart = 0;
while (true)
{
int assetStartIndex = json.IndexOf("\"name\":\"", searchStart);
if (assetStartIndex < 0)
break;
assetStartIndex += "\"name\":\"".Length;
int assetEndIndex = json.IndexOf("\"", assetStartIndex);
if (assetEndIndex < assetStartIndex)
break;
string assetName = json.Substring(assetStartIndex, assetEndIndex - assetStartIndex);
// 检查是否是exe文件
if (assetName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
// 在这个asset之后查找browser_download_url
int urlStartIndex = json.IndexOf(browserDownloadUrlPattern, assetEndIndex);
if (urlStartIndex < 0)
break;
urlStartIndex += browserDownloadUrlPattern.Length;
int urlEndIndex = json.IndexOf("\"", urlStartIndex);
if (urlEndIndex < urlStartIndex)
break;
return json.Substring(urlStartIndex, urlEndIndex - urlStartIndex);
}
searchStart = assetEndIndex;
}
// 如果没有找到asset,尝试从HTML_url + "/download" 构建链接
string htmlUrlPattern = "\"html_url\":\"";
int htmlStartIndex = json.IndexOf(htmlUrlPattern);
if (htmlStartIndex >= 0)
{
htmlStartIndex += htmlUrlPattern.Length;
int htmlEndIndex = json.IndexOf("\"", htmlStartIndex);
if (htmlEndIndex > htmlStartIndex)
{
string releasePageUrl = json.Substring(htmlStartIndex, htmlEndIndex - htmlStartIndex);
// 返回release页面URL,用户可以手动下载
return releasePageUrl;
}
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// 比较两个版本号,检查latestVersion是否比currentVersion更新
/// 版本格式:v1.0, v1.1, v2.0等
/// </summary>
private static bool IsNewerVersion(string currentVersion, string latestVersion)
{
try
{
// 移除'v'前缀
string current = currentVersion.TrimStart('v', 'V');
string latest = latestVersion.TrimStart('v', 'V');
// 尝试解析为Version对象进行比较
if (Version.TryParse(current, out Version currentVer) &&
Version.TryParse(latest, out Version latestVer))
{
return latestVer > currentVer;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// 在默认浏览器中打开下载链接
/// </summary>
public static void OpenDownloadLink(string downloadUrl)
{
try
{
if (string.IsNullOrWhiteSpace(downloadUrl))
{
// 如果没有有效的下载链接,打开release页面
downloadUrl = GITHUB_RELEASE_URL;
}
// 使用默认浏览器打开URL
System.Diagnostics.Process.Start(
new System.Diagnostics.ProcessStartInfo
{
FileName = downloadUrl,
UseShellExecute = true
});
}
catch (Exception ex)
{
MessageBox.Show($"无法打开下载链接:{ex.Message}\n\n请访问:{GITHUB_RELEASE_URL}",
"打开链接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}