-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBootImageUpdater.cs
More file actions
214 lines (193 loc) · 8.01 KB
/
Copy pathBootImageUpdater.cs
File metadata and controls
214 lines (193 loc) · 8.01 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
using System;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace ShowWrite
{
/// <summary>
/// 启动图远程更新器:启动完成后异步校验并下载最新启动图。
/// 响应示例:{"version":"1787043680","image_url":"https://github.com/.../boot-package.zip"}
/// 全流程写入 %TEMP%\showwrite_bootp.log 便于排查。
/// </summary>
public static class BootImageUpdater
{
private const string DefaultApiUrl = "https://sxvillage.dpdns.org/bootp/api/app";
/// <summary>获取实际使用的 API 地址(配置为空时回退默认地址)。</summary>
public static string GetApiUrl(string? apiUrl = null)
{
var url = apiUrl ?? Config.Load().BootImageApiUrl;
return string.IsNullOrWhiteSpace(url) ? DefaultApiUrl : url;
}
// GitHub 下载可能较慢,给足超时
private static readonly HttpClient HttpClient = new(new HttpClientHandler
{
AllowAutoRedirect = true,
MaxAutomaticRedirections = 10
})
{ Timeout = TimeSpan.FromMinutes(2) };
private static readonly string LogFile = Path.Combine(Path.GetTempPath(), "showwrite_bootp.log");
/// <summary>
/// 检查并更新启动图。force=true 时跳过版本比对强制下载。
/// 返回是否成功完成更新(版本一致跳过也返回 true)。
/// </summary>
public static async Task<bool> CheckAndUpdateAsync(string? apiUrl = null, bool force = false)
{
Log("=== 启动图更新检查开始 ===");
try
{
var url = GetApiUrl(apiUrl);
Log($"请求 API: {url}");
var server = await FetchServerInfoAsync(url);
if (server == null)
{
Log("API 返回 null,退出");
return false;
}
Log($"服务端 version={server.Version}, image_url={server.ImageUrl}");
if (string.IsNullOrEmpty(server.Version) || string.IsNullOrEmpty(server.ImageUrl))
{
Log("version 或 image_url 为空,退出");
return false;
}
var localVersion = GetLocalVersion();
Log($"本地版本: {(localVersion ?? "(无 v.json)")}");
if (!force && !string.IsNullOrEmpty(localVersion) && localVersion == server.Version)
{
Log("版本一致,跳过下载");
return true;
}
Log("版本不一致或本地无版本文件,开始下载");
var tempZip = Path.Combine(Path.GetTempPath(), $"showwrite_bootp_{server.Version}.zip");
Log($"下载到: {tempZip}");
await DownloadFileAsync(server.ImageUrl, tempZip);
var zipInfo = new FileInfo(tempZip);
Log($"下载完成,文件大小: {zipInfo.Length} 字节");
var bootPath = Config.GetBootPath();
Log($"启动图目录: {bootPath}");
if (!Directory.Exists(bootPath))
{
Directory.CreateDirectory(bootPath);
Log("创建启动图目录");
}
else
{
Log("清空启动图目录");
ClearDirectory(bootPath);
}
Log("解压中...");
ZipFile.ExtractToDirectory(tempZip, bootPath, overwriteFiles: true);
Log("解压完成,文件列表:");
foreach (var f in Directory.EnumerateFiles(bootPath))
Log($" - {Path.GetFileName(f)}");
SaveLocalVersion(server.Version);
Log($"写入 v.json version={server.Version}");
try { File.Delete(tempZip); Log("清理临时压缩包"); } catch (Exception ex) { Log($"清理临时压缩包失败: {ex.Message}"); }
Log("=== 启动图更新完成 ===");
return true;
}
catch (Exception ex)
{
Log($"[失败] {ex.GetType().Name}: {ex.Message}");
if (ex.InnerException != null)
Log($" Inner: {ex.InnerException.GetType().Name}: {ex.InnerException.Message}");
Log(ex.StackTrace ?? "(无堆栈)");
return false;
}
}
/// <summary>请求 API 获取远端启动图信息。</summary>
public static async Task<BootInfo?> FetchServerInfoAsync(string? apiUrl = null)
{
try
{
using var resp = await HttpClient.GetAsync(GetApiUrl(apiUrl));
Log($"API HTTP {(int)resp.StatusCode} {resp.StatusCode}");
resp.EnsureSuccessStatusCode();
var json = await resp.Content.ReadAsStringAsync();
Log($"API 响应: {json}");
return JsonSerializer.Deserialize<BootInfo>(json);
}
catch (Exception ex)
{
Log($"FetchServerInfo 异常: {ex.Message}");
return null;
}
}
/// <summary>读取本地 v.json 中的启动图版本。</summary>
public static string? GetLocalVersion()
{
var vFile = Path.Combine(Config.GetBootPath(), "v.json");
if (!File.Exists(vFile))
{
Log($"本地 v.json 不存在: {vFile}");
return null;
}
try
{
var json = File.ReadAllText(vFile);
Log($"本地 v.json 内容: {json}");
var info = JsonSerializer.Deserialize<BootInfo>(json);
return info?.Version;
}
catch (Exception ex)
{
Log($"读取 v.json 异常: {ex.Message}");
return null;
}
}
private static void SaveLocalVersion(string version)
{
var vFile = Path.Combine(Config.GetBootPath(), "v.json");
var json = JsonSerializer.Serialize(new BootInfo { Version = version });
File.WriteAllText(vFile, json);
}
private static async Task DownloadFileAsync(string url, string destPath)
{
try
{
using var resp = await HttpClient.GetAsync(url, HttpCompletionOption.ResponseContentRead);
Log($"下载 HTTP {(int)resp.StatusCode} {resp.StatusCode}");
resp.EnsureSuccessStatusCode();
using var fs = File.Create(destPath);
await resp.Content.CopyToAsync(fs);
}
catch (Exception ex)
{
Log($"DownloadFile 异常: {ex.Message}");
throw;
}
}
private static void ClearDirectory(string path)
{
foreach (var file in Directory.EnumerateFiles(path))
{
try { File.Delete(file); } catch (Exception ex) { Log($"删除文件失败 {file}: {ex.Message}"); }
}
foreach (var dir in Directory.EnumerateDirectories(path))
{
try { Directory.Delete(dir, recursive: true); } catch (Exception ex) { Log($"删除目录失败 {dir}: {ex.Message}"); }
}
}
private static void Log(string message)
{
try
{
var line = $"[{DateTime.Now:HH:mm:ss.fff}] {message}{Environment.NewLine}";
File.AppendAllText(LogFile, line);
}
catch { }
}
}
/// <summary>
/// 启动图远端配置 DTO。
/// </summary>
public class BootInfo
{
[JsonPropertyName("version")]
public string? Version { get; set; }
[JsonPropertyName("image_url")]
public string? ImageUrl { get; set; }
}
}