-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathUpdateDownloader.cs
More file actions
463 lines (415 loc) · 21.5 KB
/
UpdateDownloader.cs
File metadata and controls
463 lines (415 loc) · 21.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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ScreenControl
{
/// <summary>
/// 更新下载器类,负责下载新版本文件
/// </summary>
public class UpdateDownloader
{
/// <summary>
/// 显示更新对话框的静态方法,供AutoUpdateManager和MainForm共用
/// </summary>
/// <param name="updateInfo">更新信息</param>
/// <param name="currentVersion">当前版本</param>
/// <param name="statusUpdater">状态更新委托</param>
/// <param name="logWriter">日志记录委托</param>
/// <param name="parentForm">父窗体</param>
public static void ShowUpdateDialog(UpdateChecker.UpdateInfo updateInfo, string currentVersion, Action<string> statusUpdater, Action<string> logWriter, Form parentForm)
{
// 创建自定义对话框
Form customDialog = new Form();
customDialog.Text = "发现新版本";
customDialog.Size = new System.Drawing.Size(350, 200);
customDialog.StartPosition = FormStartPosition.CenterParent;
customDialog.FormBorderStyle = FormBorderStyle.FixedDialog;
customDialog.MaximizeBox = false;
customDialog.MinimizeBox = false;
// 创建消息标签
Label messageLabel = new Label();
messageLabel.Location = new System.Drawing.Point(20, 20);
messageLabel.Size = new System.Drawing.Size(300, 60);
messageLabel.Text = $"发现新版本 {updateInfo.LatestVersion}!\n您当前使用的版本是 {currentVersion}。\n\n请选择操作方式:";
messageLabel.TextAlign = System.Drawing.ContentAlignment.TopLeft;
// 创建下载按钮
Button downloadButton = new Button();
downloadButton.Location = new System.Drawing.Point(20, 90);
downloadButton.Size = new System.Drawing.Size(100, 30);
downloadButton.Text = "直接下载";
// 创建浏览器按钮
Button browserButton = new Button();
browserButton.Location = new System.Drawing.Point(130, 90);
browserButton.Size = new System.Drawing.Size(100, 30);
browserButton.Text = "浏览器查看";
// 创建取消按钮
Button cancelButton = new Button();
cancelButton.Location = new System.Drawing.Point(240, 90);
cancelButton.Size = new System.Drawing.Size(75, 30);
cancelButton.Text = "取消";
// 添加控件到对话框
customDialog.Controls.Add(messageLabel);
customDialog.Controls.Add(downloadButton);
customDialog.Controls.Add(browserButton);
customDialog.Controls.Add(cancelButton);
// 设置默认按钮
customDialog.AcceptButton = downloadButton;
customDialog.CancelButton = cancelButton;
// 设置按钮事件
bool dialogResult = false;
downloadButton.Click += (s, args) => { dialogResult = true; customDialog.Close(); };
browserButton.Click += (s, args) => {
ProcessStartInfo psi = new ProcessStartInfo(updateInfo.ReleaseUrl);
psi.UseShellExecute = true;
Process.Start(psi);
statusUpdater?.Invoke("已打开发布页面");
customDialog.Close();
};
cancelButton.Click += (s, args) => customDialog.Close();
// 显示对话框
if (parentForm != null)
{
customDialog.ShowDialog(parentForm);
}
else
{
customDialog.ShowDialog();
}
// 如果用户选择直接下载
if (dialogResult)
{
// 构建下载URL
string downloadBaseUrl = "https://gitee.com/yylmzxc/screen-control/releases/download/" + updateInfo.LatestVersion;
// 优先使用exe文件,格式为Setup-ScreenControl-{版本号}.exe
string exeFileName = $"Setup-ScreenControl-{updateInfo.LatestVersion}.exe";
string zipFileName = "ScreenControl.zip"; // 备用zip文件
// 创建下载器并开始下载
UpdateDownloader downloader = new UpdateDownloader(downloadBaseUrl, updateInfo.LatestVersion, statusUpdater, logWriter, parentForm);
downloader.ShowDownloadDialogWithFallback(exeFileName, zipFileName);
}
}
private readonly string _downloadBaseUrl;
private readonly string _version;
private readonly Action<string> _statusUpdater;
private readonly Action<string> _logWriter;
private readonly Form _parentForm;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="downloadBaseUrl">下载基础URL</param>
/// <param name="version">版本号</param>
/// <param name="statusUpdater">状态更新委托</param>
/// <param name="logWriter">日志记录委托</param>
/// <param name="parentForm">父窗体引用</param>
public UpdateDownloader(string downloadBaseUrl, string version, Action<string> statusUpdater, Action<string> logWriter, Form parentForm)
{
_downloadBaseUrl = downloadBaseUrl;
_version = version;
_statusUpdater = statusUpdater;
_logWriter = logWriter;
_parentForm = parentForm;
}
/// <summary>
/// 显示下载对话框并开始下载(带备用文件支持)
/// </summary>
/// <param name="primaryFileName">首选文件名(通常是exe)</param>
/// <param name="fallbackFileName">备用文件名(通常是zip)</param>
public void ShowDownloadDialogWithFallback(string primaryFileName, string fallbackFileName)
{
// 首先尝试下载exe文件
ShowDownloadDialog(primaryFileName, true, fallbackFileName);
}
/// <summary>
/// 显示下载对话框并开始下载
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="isPrimary">是否为主文件(失败时是否尝试备用文件)</param>
/// <param name="fallbackFileName">备用文件名(当isPrimary为true时有效)</param>
private void ShowDownloadDialog(string fileName, bool isPrimary = false, string fallbackFileName = null)
{
// 创建进度对话框并关联父窗口
DownloadProgressForm progressForm = new DownloadProgressForm();
progressForm.Text = $"正在下载 {_version} 版本...";
progressForm.Owner = _parentForm;
// 开始下载任务
Task.Run(async () => {
string filePath = null;
Exception downloadException = null;
try
{
// 创建版本文件夹(在当前程序目录下)
string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
string versionFolder = Path.Combine(appDirectory, "UpdateDownloader", _version);
Directory.CreateDirectory(versionFolder);
// 下载文件路径
filePath = Path.Combine(versionFolder, fileName);
// 更新状态
_parentForm.Invoke((MethodInvoker)delegate {
_statusUpdater?.Invoke($"正在下载 {fileName}...");
});
// 记录日志
_logWriter?.Invoke($"开始下载文件: {filePath}");
// 执行下载
await DownloadFileAsync(_downloadBaseUrl + "/" + fileName, filePath, progressForm.UpdateProgress, progressForm.UpdateStatus);
// 下载完成,更新状态
_parentForm.Invoke((MethodInvoker)delegate {
_statusUpdater?.Invoke($"下载完成: {fileName}");
});
_logWriter?.Invoke($"文件下载完成: {filePath}");
}
catch (Exception ex)
{
downloadException = ex;
_parentForm.Invoke((MethodInvoker)delegate {
_statusUpdater?.Invoke($"下载失败: {ex.Message}");
});
_logWriter?.Invoke($"文件下载失败: {ex.Message}");
}
finally
{
// 下载完成后自动关闭进度对话框
progressForm.Invoke((MethodInvoker)delegate {
progressForm.Close();
});
// 处理下载结果
_parentForm.Invoke((MethodInvoker)delegate {
if (downloadException != null)
{
// 如果是主文件下载失败且有备用文件,则尝试下载备用文件
if (isPrimary && !string.IsNullOrEmpty(fallbackFileName))
{
DialogResult result = MessageBox.Show(
_parentForm,
$"{fileName} 下载失败: {downloadException.Message}\n\n是否尝试下载备用文件 {fallbackFileName}?",
"下载失败",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// 尝试下载备用文件
ShowDownloadDialog(fallbackFileName, false);
return;
}
}
// 显示错误消息
MessageBox.Show(
_parentForm, // 关联父窗口
"下载失败: " + downloadException.Message,
"错误",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else if (filePath != null)
{
// 根据文件类型显示不同的完成对话框
string message;
if (fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
// EXE文件的提示信息
message = $"安装文件 {fileName} 下载完成!\n保存位置: {Path.GetDirectoryName(filePath)}\n\n是否打开文件位置?\n是否立即运行安装程序?";
}
else
{
// 其他文件(如ZIP)的提示信息
message = $"文件 {fileName} 下载完成!\n保存位置: {Path.GetDirectoryName(filePath)}\n\n是否打开文件位置?\n是否立即解压并安装更新?";
}
DialogResult result = MessageBox.Show(
_parentForm, // 关联父窗口
message,
"下载完成",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
// 打开文件位置
Process.Start("explorer.exe", "/select," + filePath);
}
else if (result == DialogResult.No)
{
try
{
if (fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
// 对于EXE文件,直接运行
_statusUpdater?.Invoke("正在启动安装程序...");
ProcessStartInfo psi = new ProcessStartInfo(filePath);
psi.UseShellExecute = true;
Process.Start(psi);
_statusUpdater?.Invoke("安装程序已启动,请按照提示完成安装。");
}
else
{
// 对于其他文件(如ZIP),尝试解压
_statusUpdater?.Invoke("正在解压更新文件...");
string extractPath = Path.Combine(Path.GetDirectoryName(filePath), "UpdateTemp");
if (Directory.Exists(extractPath))
{
Directory.Delete(extractPath, true);
}
Directory.CreateDirectory(extractPath);
// 这里可以添加解压逻辑,使用System.IO.Compression或其他解压库
// 由于没有引入解压库,这里只显示提示
_statusUpdater?.Invoke("更新准备完成,请手动解压并安装。");
MessageBox.Show(_parentForm, "更新文件已下载,请手动解压并安装。", "更新提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
_statusUpdater?.Invoke($"操作失败: {ex.Message}");
MessageBox.Show(_parentForm, $"操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
});
}
});
// 显示进度对话框
progressForm.ShowDialog(_parentForm);
}
/// <summary>
/// 异步下载文件
/// </summary>
/// <param name="url">下载URL</param>
/// <param name="filePath">保存路径</param>
/// <param name="progressCallback">进度回调函数</param>
/// <param name="statusCallback">状态回调函数</param>
private async Task DownloadFileAsync(string url, string filePath, Action<int> progressCallback, Action<string> statusCallback)
{
using (HttpClient client = new HttpClient())
{
// 设置超时时间为30秒
client.Timeout = TimeSpan.FromSeconds(30);
try
{
// 获取文件大小
using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
// 检查是否为403 Forbidden错误
if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
throw new Exception("下载失败: 403 Forbidden (Rate Limit Exceeded),IP访问频率限制,请稍后再试");
}
// 检查其他HTTP错误状态码
else if (!response.IsSuccessStatusCode)
{
throw new Exception($"下载失败: 网络错误 ({response.StatusCode}),请检查网络连接后重试");
}
response.EnsureSuccessStatusCode();
long totalBytes = response.Content.Headers.ContentLength ?? 0;
using (Stream contentStream = await response.Content.ReadAsStreamAsync())
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] 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 (totalBytes > 0)
{
int progress = (int)((totalRead * 100) / totalBytes);
_parentForm.Invoke((MethodInvoker)delegate {
progressCallback?.Invoke(progress);
statusCallback?.Invoke($"已下载 {FormatFileSize(totalRead)} / {FormatFileSize(totalBytes)}");
});
}
}
}
}
}
catch (HttpRequestException ex)
{
if ((int)ex.StatusCode == 403)
{
throw new Exception("下载失败: 403 Forbidden (Rate Limit Exceeded),IP访问频率限制,请稍后再试");
}
else
{
throw new Exception($"下载失败: 网络连接错误 - {ex.Message},请检查网络连接后重试");
}
}
catch (TaskCanceledException)
{
throw new Exception("下载失败: 请求超时,请检查网络连接后重试");
}
catch (IOException ex)
{
throw new Exception($"下载失败: 文件写入错误 - {ex.Message}");
}
}
}
/// <summary>
/// 格式化文件大小
/// </summary>
private string FormatFileSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB" };
int order = 0;
while (bytes >= 1024 && order < sizes.Length - 1)
{
order++;
bytes = bytes / 1024;
}
return $"{bytes} {sizes[order]}";
}
}
/// <summary>
/// 下载进度对话框
/// </summary>
public class DownloadProgressForm : Form
{
private ProgressBar _progressBar;
private Label _statusLabel;
public DownloadProgressForm()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.Text = "下载中...";
this.Size = new System.Drawing.Size(400, 150);
this.StartPosition = FormStartPosition.CenterParent;
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
// 创建进度条
_progressBar = new ProgressBar();
_progressBar.Location = new System.Drawing.Point(20, 40);
_progressBar.Size = new System.Drawing.Size(340, 20);
_progressBar.Minimum = 0;
_progressBar.Maximum = 100;
// 创建状态标签
_statusLabel = new Label();
_statusLabel.Location = new System.Drawing.Point(20, 70);
_statusLabel.Size = new System.Drawing.Size(340, 20);
_statusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
_statusLabel.Text = "准备下载...";
// 添加控件
this.Controls.Add(_progressBar);
this.Controls.Add(_statusLabel);
}
/// <summary>
/// 更新进度
/// </summary>
/// <param name="progress">进度值(0-100)</param>
public void UpdateProgress(int progress)
{
_progressBar.Value = progress;
}
/// <summary>
/// 更新状态文本
/// </summary>
/// <param name="status">状态文本</param>
public void UpdateStatus(string status)
{
_statusLabel.Text = status;
}
}
}