-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.cs
More file actions
307 lines (257 loc) · 9.43 KB
/
Copy pathUtils.cs
File metadata and controls
307 lines (257 loc) · 9.43 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
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
namespace ModBridge;
public class Utils
{
public static string AppDataDir { get; } = GetAppDataFolder("ModBridge");
public static string RoamingPath { get; } = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
public static IniConfig Config { get; } = new();
public static string GetAppDataFolder(string appFolderName, bool createIfNotExists = true)
{
// 获取 Roaming AppData 路径(对应 %APPDATA%)
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string fullPath = Path.Combine(appDataPath, appFolderName);
// 创建目录(如果不存在)
if (createIfNotExists && !Directory.Exists(fullPath)) Directory.CreateDirectory(fullPath);
return fullPath;
}
public static class Fingerprint
{
// 读取文件内容到 byte[]
public static byte[] GetJarContents(string jarFilePath)
{
if (!File.Exists(jarFilePath))
{
return [];
}
try
{
return File.ReadAllBytes(jarFilePath);
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to load {jarFilePath}: {ex.Message}");
return [];
}
}
// 计算哈希
public static uint ComputeHash(byte[] buffer)
{
const uint multiplex = 1540483477;
uint length = (uint)buffer.Length;
uint num1 = ComputeNormalizedLength(buffer);
uint num2 = 1u ^ num1;
uint num3 = 0;
uint num4 = 0;
for (uint index = 0; index < length; ++index)
{
byte b = buffer[index];
if (!IsWhitespaceCharacter(b))
{
num3 |= (uint)b << (int)num4;
num4 += 8;
if (num4 == 32)
{
uint num6 = num3 * multiplex;
uint num7 = (num6 ^ num6 >> 24) * multiplex;
num2 = num2 * multiplex ^ num7;
num3 = 0;
num4 = 0;
}
}
}
if (num4 > 0)
{
num2 = (num2 ^ num3) * multiplex;
}
uint num8 = (num2 ^ num2 >> 13) * multiplex;
return num8 ^ num8 >> 15;
}
// 计算去掉空白字符后的长度
public static uint ComputeNormalizedLength(byte[] buffer)
{
int count = 0;
foreach (byte b in buffer)
{
if (!IsWhitespaceCharacter(b))
{
count++;
}
}
return (uint)count;
}
// 判断是否是空白字符
public static bool IsWhitespaceCharacter(byte b)
{
return b == 9 || b == 10 || b == 13 || b == 32;
}
public static uint GetFingerprint(string jarFilePath)
{
byte[] buffer = GetJarContents(jarFilePath);
return ComputeHash(buffer);
}
}
/// <summary>
/// 计算文件的SHA1哈希值
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>SHA1哈希值的十六进制字符串表示</returns>
public static string ComputeSha1Hash(string filePath)
{
using var sha1 = System.Security.Cryptography.SHA1.Create();
using var stream = File.OpenRead(filePath);
byte[] hashBytes = sha1.ComputeHash(stream);
StringBuilder sb = new();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
public static async Task DownloadFileAsync(string url, string filePath, Action<double>? progressCallback = null)
{
using HttpResponseMessage response = await HttpClients.Download.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
long? contentLength = response.Content.Headers.ContentLength;
using Stream stream = await response.Content.ReadAsStreamAsync();
using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true);
byte[] buffer = new byte[8192];
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = await stream.ReadAsync(buffer)) > 0)
{
await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead));
totalBytesRead += bytesRead;
// 如果提供了进度回调且能获取到总长度,则报告进度
if (progressCallback != null && contentLength.HasValue && contentLength.Value > 0)
{
double progress = (double)totalBytesRead / contentLength.Value;
progressCallback(Math.Min(progress, 1.0)); // 确保进度不超过1.0
}
}
// 下载完成,确保报告100%进度
progressCallback?.Invoke(1.0);
}
/// <summary>
/// 从字符串数组中查找最新版本的下标
/// </summary>
/// <param name="versions">版本字符串数组</param>
/// <returns>最新版本的下标,如果没有找到有效版本则返回-1</returns>
public static int GetLatestVersionIndex(string[] versions)
{
if (versions == null || versions.Length == 0)
return -1;
Version? latestVersion = null;
int latestIndex = -1;
for (int i = 0; i < versions.Length; i++)
{
if (string.IsNullOrWhiteSpace(versions[i]))
continue;
// 使用正则表达式提取版本号
string versionString = ExtractVersionString(versions[i]);
if (string.IsNullOrEmpty(versionString))
continue;
try
{
Version currentVersion = new(versionString);
if (latestVersion == null || currentVersion > latestVersion)
{
latestVersion = currentVersion;
latestIndex = i;
}
}
catch (Exception)
{
// 忽略无法解析的版本字符串
continue;
}
}
return latestIndex;
}
public static string[] SortVersionNames(IEnumerable<string> versionNames)
{
return [.. versionNames
.OrderByDescending(name => GetVersionSortKey(name))
.ThenBy(name => name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// 从字符串中提取版本号部分
/// </summary>
/// <param name="input">输入字符串</param>
/// <returns>提取的版本号字符串</returns>
private static string ExtractVersionString(string input)
{
// 匹配常见的版本号格式,如 1.0.0, 2.1.3-beta, v3.2.1 等
var match = Regex.Match(input, @"(?:v)?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.(\d+))?(?:[-._]?[a-zA-Z]*)?");
if (match.Success)
{
// 提取版本号的主要部分
var groups = match.Groups;
var versionParts = new List<string>();
for (int i = 1; i < groups.Count; i++)
{
if (groups[i].Success && !string.IsNullOrEmpty(groups[i].Value))
{
versionParts.Add(groups[i].Value);
}
}
return string.Join(".", versionParts);
}
return input; // 如果没有匹配到,则返回原字符串
}
private static VersionSortKey GetVersionSortKey(string versionName)
{
if (string.IsNullOrWhiteSpace(versionName))
{
return VersionSortKey.Empty;
}
var loaderSplit = versionName.Split('-', 2, StringSplitOptions.TrimEntries);
var versionPart = loaderSplit[0];
var numericVersion = ExtractVersionString(versionPart);
if (Version.TryParse(numericVersion, out var parsedVersion))
{
return new VersionSortKey(true, parsedVersion);
}
return VersionSortKey.Empty;
}
private readonly record struct VersionSortKey(bool HasVersion, Version? Version) : IComparable<VersionSortKey>
{
public static VersionSortKey Empty => new(false, null);
public int CompareTo(VersionSortKey other)
{
if (HasVersion != other.HasVersion)
{
return HasVersion.CompareTo(other.HasVersion);
}
if (Version == null && other.Version == null)
{
return 0;
}
if (Version == null)
{
return -1;
}
if (other.Version == null)
{
return 1;
}
return Version.CompareTo(other.Version);
}
}
/// <summary>
/// 打开指定的网页地址
/// </summary>
/// <param name="url">要打开的网页网址</param>
public static void OpenUrl(string url)
{
ProcessStartInfo psi = new ()
{
FileName = url,
UseShellExecute = true
};
Process.Start(psi);
}
}