移动部分文件
This commit is contained in:
1 parent
0ddee422ab
commit
c95dfaf9f3
78 files changed
+102
-47
No files matched your search
@@ -0,0 +1,299 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||
/// <code>
|
||||
/// <安装目录>/
|
||||
/// GC(.exe | .app/...)
|
||||
/// .GC/
|
||||
/// settings.json 设置与已安装版本记录
|
||||
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
|
||||
/// cache/ 下载缓存 / 原子替换暂存
|
||||
/// update/ 待下次启动应用的启动器更新包
|
||||
/// </code>
|
||||
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
|
||||
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
||||
/// </summary>
|
||||
public sealed class AppPaths
|
||||
{
|
||||
private Task _developmentModelsSync = Task.CompletedTask;
|
||||
|
||||
/// <summary>安装目录(开发态为仓库根)。</summary>
|
||||
public string AppRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
|
||||
public string InstallDirectory { get; private init; } = "";
|
||||
|
||||
/// <summary>.GC 目录。</summary>
|
||||
public string HomeRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>模型库,恒为 <HomeRoot>/model。</summary>
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
|
||||
public string DataRoot => HomeRoot;
|
||||
|
||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
|
||||
|
||||
public bool IsDevelopment { get; private init; }
|
||||
public bool IsPortableModelRoot { get; private init; }
|
||||
|
||||
public static AppPaths Discover()
|
||||
{
|
||||
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
||||
|
||||
// 判定「当前目录」:程序实际所在的位置。
|
||||
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
|
||||
// · 源码版:仓库根(含 GC.sln 的目录)
|
||||
//
|
||||
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
|
||||
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
|
||||
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
|
||||
repoRoot = FindRepoRoot(baseDir);
|
||||
var isDev = !string.IsNullOrEmpty(repoRoot) &&
|
||||
File.Exists(Path.Combine(repoRoot!, "GC.sln"));
|
||||
|
||||
string installDir;
|
||||
if (isDev)
|
||||
{
|
||||
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里
|
||||
installDir = repoRoot!;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
|
||||
//
|
||||
// <运行目录>/ ← 要的就是这一层
|
||||
// GC-1.0.3-mac-arm64.app/ ← 程序包
|
||||
// .GC/ ← 用户数据放这里
|
||||
//
|
||||
// 若直接返回 Contents/MacOS,.GC 会被塞进 app 包内部,
|
||||
// 用户看不到,重装/替换时也会跟着包一起被删。
|
||||
installDir = baseDir;
|
||||
try
|
||||
{
|
||||
var exe = Environment.ProcessPath;
|
||||
if (!string.IsNullOrWhiteSpace(exe))
|
||||
{
|
||||
var exeName = Path.GetFileNameWithoutExtension(exe);
|
||||
var isDotnetHost = string.Equals(exeName, "dotnet", StringComparison.OrdinalIgnoreCase);
|
||||
var exeDir = Path.GetDirectoryName(exe);
|
||||
|
||||
if (!isDotnetHost && !string.IsNullOrWhiteSpace(exeDir) && Directory.Exists(exeDir))
|
||||
{
|
||||
// 从可执行文件所在目录向上找:如果处在 Xxx.app/Contents/MacOS,
|
||||
// 则运行目录是 Xxx.app 的**父目录**。
|
||||
installDir = ResolveRunDirectory(exeDir!);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* 取不到就沿用 BaseDirectory */ }
|
||||
}
|
||||
|
||||
// 运行目录 = 程序所在目录。.GC 永远紧挨着程序,不往系统目录放。
|
||||
var appRoot = installDir;
|
||||
|
||||
// 只读安装位置(如 Program Files / /Applications)才回退到用户数据目录;
|
||||
// 正常可写时一律用当前目录下的 .GC。
|
||||
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
|
||||
string home;
|
||||
if (!string.IsNullOrWhiteSpace(explicitData))
|
||||
{
|
||||
home = explicitData!;
|
||||
}
|
||||
else
|
||||
{
|
||||
var portableHome = Path.Combine(appRoot, ".GC");
|
||||
home = CanWrite(portableHome)
|
||||
? portableHome
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"GC", ".GC");
|
||||
}
|
||||
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
|
||||
? envModels!
|
||||
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
|
||||
|
||||
return new AppPaths
|
||||
{
|
||||
AppRoot = appRoot,
|
||||
InstallDirectory = installDir,
|
||||
HomeRoot = home,
|
||||
ModelRoot = modelRoot,
|
||||
IsDevelopment = isDev,
|
||||
IsPortableModelRoot = string.IsNullOrWhiteSpace(envModels)
|
||||
};
|
||||
}
|
||||
|
||||
private static bool CanWrite(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
var probe = Path.Combine(dir, ".write-test");
|
||||
File.WriteAllText(probe, "ok");
|
||||
File.Delete(probe);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从程序所在位置向上找仓库根(含 GC.sln 的目录)。
|
||||
///
|
||||
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
|
||||
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
|
||||
/// 被误判为开发态,导致 .GC 跑到仓库根而不是程序旁边。
|
||||
/// </summary>
|
||||
private static string? FindRepoRoot(string start)
|
||||
{
|
||||
// 在 .app 包内(.../Xxx.app/Contents/MacOS)直接视为发布版
|
||||
if (IsInsideAppBundle(start)) return null;
|
||||
|
||||
var dir = new DirectoryInfo(start);
|
||||
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
|
||||
{
|
||||
// 碰到发布产物目录也停下:dist/ 输出、或带 .GC 的运行目录都不是源码树
|
||||
var name = dir.Name;
|
||||
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln")))
|
||||
{
|
||||
// 再确认不是从「发布输出目录」里往上找来的
|
||||
if (IsUnderPublishOutput(start, dir.FullName)) return null;
|
||||
return dir.FullName;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 求「运行目录」:程序包所在的父目录。
|
||||
/// · 若路径处在 Xxx.app/Contents/MacOS 里,返回 Xxx.app 的父目录
|
||||
/// · 其它情况(Windows exe 目录)原样返回
|
||||
/// </summary>
|
||||
private static string ResolveRunDirectory(string exeDir)
|
||||
{
|
||||
var dir = new DirectoryInfo(exeDir);
|
||||
|
||||
// 走到 app 包根:.../Xxx.app
|
||||
string? appRoot = null;
|
||||
for (var cur = dir; cur != null; cur = cur.Parent)
|
||||
{
|
||||
if (cur.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
appRoot = cur.FullName;
|
||||
break;
|
||||
}
|
||||
if (cur.Parent == null) break;
|
||||
}
|
||||
|
||||
if (appRoot != null)
|
||||
{
|
||||
// 返回 .app 的父目录(即用户双击时看到的那一层)
|
||||
var parent = Path.GetDirectoryName(appRoot);
|
||||
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
|
||||
return parent!;
|
||||
return appRoot;
|
||||
}
|
||||
|
||||
return exeDir;
|
||||
}
|
||||
|
||||
/// <summary>路径是否位于某个 .app 包内部。</summary>
|
||||
private static bool IsInsideAppBundle(string path)
|
||||
{
|
||||
var p = path.Replace('\\', '/');
|
||||
var idx = p.IndexOf(".app/", StringComparison.OrdinalIgnoreCase);
|
||||
return idx >= 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 start 到 repoRoot 之间是否经过了发布输出目录(dist / bin / publish)。
|
||||
/// 经过则说明程序是打包产物,而非源码树里直接运行的进程。
|
||||
/// </summary>
|
||||
private static bool IsUnderPublishOutput(string start, string repoRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rel = Path.GetRelativePath(repoRoot, start).Replace('\\', '/');
|
||||
foreach (var seg in rel.Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (string.Equals(seg, "dist", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(seg, "publish", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(seg, "Release", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
public void EnsureCreated()
|
||||
{
|
||||
Directory.CreateDirectory(HomeRoot);
|
||||
Directory.CreateDirectory(CacheRoot);
|
||||
Directory.CreateDirectory(ModelRoot);
|
||||
Directory.CreateDirectory(UpdateRoot);
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
|
||||
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
{
|
||||
var modelRoot = ModelRoot;
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
if (Directory.Exists(source))
|
||||
_developmentModelsSync = Task.Run(() => SyncDevelopmentModels(modelRoot, source));
|
||||
}
|
||||
}
|
||||
|
||||
public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
|
||||
|
||||
private static void SyncDevelopmentModels(string modelRoot, string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(source)) return;
|
||||
foreach (var dir in Directory.GetDirectories(source))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
if (id.StartsWith('_')) continue;
|
||||
var manifest = Path.Combine(dir, id + ".json");
|
||||
var data = Path.Combine(dir, id + ".model");
|
||||
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
|
||||
var dest = Path.Combine(modelRoot, id);
|
||||
Directory.CreateDirectory(dest);
|
||||
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"同步开发模型失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (Path.GetFileName(file).StartsWith('.')) continue;
|
||||
var to = Path.Combine(dst, Path.GetRelativePath(src, file));
|
||||
var parent = Path.GetDirectoryName(to);
|
||||
if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent);
|
||||
File.Copy(file, to, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>组合根:一处初始化所有服务。</summary>
|
||||
public sealed class AppServices
|
||||
{
|
||||
public static AppServices Current { get; private set; } = null!;
|
||||
|
||||
public AppPaths Paths { get; }
|
||||
public SettingsService Settings { get; }
|
||||
public ModelRepository Models { get; }
|
||||
public DownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public ModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public UpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
public SourceSelector Selector { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
Paths = paths;
|
||||
Settings = new SettingsService(paths);
|
||||
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
|
||||
Models = new ModelRepository(paths);
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, Models);
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Selector = new SourceSelector();
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
{
|
||||
var paths = AppPaths.Discover();
|
||||
paths.EnsureCreated();
|
||||
|
||||
var services = new AppServices(paths);
|
||||
L.I.Initialize(services.Settings.Current.Language);
|
||||
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto,
|
||||
services.Settings.Current.MemoryMb);
|
||||
|
||||
Current = services;
|
||||
return services;
|
||||
}
|
||||
|
||||
public static AppServices Ensure() => Current ?? Create();
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>GitCode 仓库的一位贡献者。</summary>
|
||||
public sealed class Contributor
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string? Email { get; set; }
|
||||
/// <summary>提交次数(API 里的 contributions)。</summary>
|
||||
public int Contributions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名,
|
||||
/// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["2509_92447106"] = "Morris"
|
||||
};
|
||||
|
||||
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
|
||||
public string? AvatarUrl =>
|
||||
string.IsNullOrWhiteSpace(Email)
|
||||
? null
|
||||
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
|
||||
System.Security.Cryptography.MD5.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
|
||||
.ToLowerInvariant()}";
|
||||
|
||||
public string DisplayName
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Name)) return "匿名";
|
||||
return DisplayNames.TryGetValue(Name.Trim(), out var mapped) ? mapped : Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取 GitCode 仓库的贡献者列表(用于「关于」页面展示开发者)。
|
||||
/// 失败时静默返回空列表,不影响关于页其它内容。
|
||||
/// </summary>
|
||||
public static class ContributorsService
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>默认仓库的 contributors 接口地址。</summary>
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
|
||||
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2)
|
||||
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
|
||||
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
|
||||
}
|
||||
|
||||
public static async Task<List<Contributor>> FetchAsync(string repository, CancellationToken ct = default)
|
||||
{
|
||||
var url = BuildUrl(repository);
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
|
||||
var text = await Http.GetStringAsync(url, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return new List<Contributor>();
|
||||
|
||||
var list = JsonSerializer.Deserialize<List<Contributor>>(text, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
}) ?? new List<Contributor>();
|
||||
|
||||
// 按提交数从多到少,贡献最多的排最前
|
||||
list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions));
|
||||
return list;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取贡献者失败: {ex.Message}");
|
||||
return new List<Contributor>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
||||
/// 目录结构与远端仓库一致:version.json + model/<id>/...
|
||||
/// </summary>
|
||||
public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
|
||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||
|
||||
public string DisplayName => _root;
|
||||
|
||||
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var primary = SafePath("version.json");
|
||||
var fallback = SafePath(Path.Combine("model", "version.json"));
|
||||
var file = File.Exists(primary) ? primary : fallback;
|
||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||
return Task.FromResult(Json.Read<RepoVersion>(file));
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var baseDir = SafePath(rootPath ?? "model");
|
||||
var result = new List<RepoEntry>();
|
||||
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
|
||||
|
||||
Walk(baseDir, baseDir, 0, result);
|
||||
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
|
||||
}
|
||||
|
||||
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
foreach (var sub in Directory.GetDirectories(dir))
|
||||
{
|
||||
var name = Path.GetFileName(sub);
|
||||
if (name.StartsWith('.')) continue;
|
||||
var rel = Relative(baseDir, sub);
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = Relative(_root, sub),
|
||||
RelativePath = rel,
|
||||
IsDirectory = true
|
||||
});
|
||||
Walk(sub, baseDir, depth + 1, result);
|
||||
}
|
||||
foreach (var file in Directory.GetFiles(dir))
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.StartsWith('.')) continue;
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = Relative(_root, file),
|
||||
RelativePath = Relative(baseDir, file),
|
||||
IsDirectory = false,
|
||||
Size = new FileInfo(file).Length
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
var local = SafePath(package.Path!);
|
||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
||||
}
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
|
||||
if (Path.IsPathRooted(url) && File.Exists(url))
|
||||
return await File.ReadAllBytesAsync(url, ct);
|
||||
if (Uri.TryCreate(url, UriKind.Absolute, out _))
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
return null;
|
||||
}
|
||||
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
||||
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"路径越界: {relative}");
|
||||
return full;
|
||||
}
|
||||
|
||||
private static string Relative(string baseDir, string file) =>
|
||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
||||
public sealed partial class DownloadJob : ObservableObject
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public string Id => Model.Id;
|
||||
public string Name => Model.LocalizedName;
|
||||
public string Version => Model.Manifest.Version;
|
||||
public CancellationTokenSource Cts { get; } = new();
|
||||
|
||||
[ObservableProperty] private DownloadState _state = DownloadState.Queued;
|
||||
[ObservableProperty] private double _progress;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private string _detailText = "";
|
||||
[ObservableProperty] private string? _error;
|
||||
|
||||
public DownloadJob(RemoteModel model)
|
||||
{
|
||||
Model = model;
|
||||
RefreshText();
|
||||
}
|
||||
|
||||
public bool IsActive => State is DownloadState.Queued or DownloadState.Running;
|
||||
public bool CanRetry => State is DownloadState.Failed or DownloadState.Canceled;
|
||||
public bool IsDone => State == DownloadState.Completed;
|
||||
|
||||
public void RefreshText()
|
||||
{
|
||||
StatusText = State switch
|
||||
{
|
||||
DownloadState.Queued => L.I["dl.status.queued"],
|
||||
DownloadState.Running => L.I["dl.status.downloading"],
|
||||
DownloadState.Completed => L.I["dl.status.done"],
|
||||
DownloadState.Failed => L.I["dl.status.failed"],
|
||||
_ => L.I["dl.status.canceled"]
|
||||
};
|
||||
DetailText = State == DownloadState.Failed && !string.IsNullOrEmpty(Error)
|
||||
? Error!
|
||||
: ModelScanner.HumanSize(Model.SizeBytes);
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(CanRetry));
|
||||
OnPropertyChanged(nameof(IsDone));
|
||||
}
|
||||
|
||||
partial void OnStateChanged(DownloadState value) => RefreshText();
|
||||
partial void OnErrorChanged(string? value) => RefreshText();
|
||||
}
|
||||
|
||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
public sealed class DownloadCenter
|
||||
{
|
||||
private readonly ModelRepository _repository;
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SemaphoreSlim _slots = new(2);
|
||||
|
||||
public ObservableCollection<DownloadJob> Jobs { get; } = new();
|
||||
public event Action? Installed;
|
||||
|
||||
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
||||
{
|
||||
_paths = paths;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public DownloadJob Enqueue(RemoteModel model)
|
||||
{
|
||||
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
||||
if (running != null) return running;
|
||||
|
||||
var job = new DownloadJob(model);
|
||||
Jobs.Insert(0, job);
|
||||
_ = RunAsync(job);
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task RunAsync(DownloadJob job)
|
||||
{
|
||||
// 在 UI 线程构造,回调自动回到 UI 线程
|
||||
var progress = new Progress<(long Done, long Total)>(p =>
|
||||
{
|
||||
job.Progress = p.Total > 0 ? Math.Clamp((double)p.Done / p.Total, 0, 1) : 0;
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
await _slots.WaitAsync(job.Cts.Token).ConfigureAwait(true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
job.State = DownloadState.Canceled;
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
job.State = DownloadState.Running;
|
||||
await ModelInstaller.InstallAsync(job.Model, _paths.ModelRoot, progress, job.Cts.Token)
|
||||
.ConfigureAwait(true);
|
||||
job.Progress = 1;
|
||||
job.State = DownloadState.Completed;
|
||||
_repository.NotifyChanged();
|
||||
Installed?.Invoke();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
job.State = DownloadState.Canceled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
job.Error = ex.Message;
|
||||
job.State = DownloadState.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(DownloadJob job)
|
||||
{
|
||||
try { job.Cts.Cancel(); } catch { }
|
||||
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
||||
}
|
||||
|
||||
public void Retry(DownloadJob job)
|
||||
{
|
||||
if (job.IsActive) return;
|
||||
Jobs.Remove(job);
|
||||
Enqueue(job.Model);
|
||||
}
|
||||
|
||||
public void Remove(DownloadJob job)
|
||||
{
|
||||
Cancel(job);
|
||||
Jobs.Remove(job);
|
||||
}
|
||||
|
||||
public void ClearFinished()
|
||||
{
|
||||
for (var i = Jobs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (Jobs[i].State is DownloadState.Completed or DownloadState.Canceled)
|
||||
Jobs.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
public int ActiveCount => Jobs.Count(j => j.IsActive);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
||||
///
|
||||
/// · 版本判定:最新 Release 的 tag_name(如 v1.0.1 / GC-1.0.1)与本地程序集版本比较;
|
||||
/// · 发布包:按附件名识别平台(如 GC-1.0.1-Win-amd64.zip),用 browser_download_url 下载;
|
||||
/// · 校验:附件自带的 sha256/size(Gitee/GitCode 的 assets 可能没有 sha256,
|
||||
/// 此时退回 version.json 里同名 RID 条目的 sha256,两者都没有则只校验非空);
|
||||
/// · 模型清单与模型文件:完全委托给内部 GitCodeRemote,保持原有链路不变。
|
||||
///
|
||||
/// Release API 失败(仓库还没有 Release / 断网)时静默回退到 version.json 的
|
||||
/// launcher 字段,保证「只发仓库、不发 Release」的旧发布方式仍然可用。
|
||||
/// </summary>
|
||||
public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
private readonly GitCodeRemote _content;
|
||||
private readonly string _releasesUrl;
|
||||
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
|
||||
|
||||
// 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
|
||||
// headers 只在一处设置,多个线程并发读取是线程安全的。
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return client;
|
||||
}
|
||||
|
||||
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
|
||||
{
|
||||
_content = new GitCodeRemote(manifestUrl, repository);
|
||||
var (owner, repo) = ParseOwnerRepo(repository);
|
||||
_releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases";
|
||||
DisplayName = (string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)";
|
||||
}
|
||||
|
||||
private static (string Owner, string Repo) ParseOwnerRepo(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC");
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return (parts[0], repo);
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => SourcePreset.Detect(_content.DisplayName).Id;
|
||||
|
||||
/// <summary>
|
||||
/// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 只认 Release:拿不到任何 Release 就返回 null,由上层去问另一个源。
|
||||
/// 仓库里的 version.json 只用来补全「模型清单」与平台包兜底地址,
|
||||
/// 不再用它充当版本号来源。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var version = await _content.GetVersionAsync(ct);
|
||||
|
||||
bool gotRelease;
|
||||
try
|
||||
{
|
||||
gotRelease = await ApplyReleaseAsync(version, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
|
||||
gotRelease = false;
|
||||
}
|
||||
|
||||
if (!gotRelease)
|
||||
{
|
||||
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器),
|
||||
// 但模型清单仍然有效,保证模型能正常同步。
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)");
|
||||
if (version != null)
|
||||
{
|
||||
version.Launcher.Version = "";
|
||||
version.Launcher.Packages.Clear();
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<bool> ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
{
|
||||
if (version == null) return false;
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(12));
|
||||
var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
ReleaseInfo? latest = null;
|
||||
foreach (var el in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
var info = ParseRelease(el);
|
||||
if (info == null || info.Draft || info.Prerelease) continue;
|
||||
// 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层)
|
||||
if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info;
|
||||
}
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||
|
||||
version.Launcher.Version = latest.Version;
|
||||
|
||||
_assets.Clear();
|
||||
foreach (var asset in latest.Assets)
|
||||
{
|
||||
var rid = asset.RidFromName(asset.Name);
|
||||
if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue;
|
||||
// 同名平台取第一个有效附件
|
||||
if (!_assets.ContainsKey(rid))
|
||||
_assets[rid] = (asset.Url, asset.Sha256, asset.Size, asset.Name);
|
||||
}
|
||||
|
||||
// 把附件地址写回 packages:有附件就用附件的直链与校验值,
|
||||
// 没有对应平台附件时保留 version.json 里原来的 path/url 兜底。
|
||||
foreach (var (rid, info) in _assets)
|
||||
{
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg))
|
||||
{
|
||||
pkg = new RepoPackage();
|
||||
version.Launcher.Packages[rid] = pkg;
|
||||
}
|
||||
pkg.Url = info.Url;
|
||||
pkg.AssetName = info.Name;
|
||||
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
|
||||
if (info.Size > 0) pkg.Size = info.Size;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int CompareVersion(string a, string b)
|
||||
{
|
||||
if (Version.TryParse(a, out var va) && Version.TryParse(b, out var vb)) return va.CompareTo(vb);
|
||||
return string.Compare(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static ReleaseInfo? ParseRelease(JsonElement el)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new ReleaseInfo
|
||||
{
|
||||
TagName = Str(el, "tag_name") ?? Str(el, "tag") ?? "",
|
||||
Name = Str(el, "name") ?? "",
|
||||
Draft = Bool(el, "draft") ?? false,
|
||||
Prerelease = Bool(el, "prerelease") ?? Bool(el, "pre_release") ?? false,
|
||||
PublishedAt = Str(el, "published_at") ?? Str(el, "created_at")
|
||||
};
|
||||
if (el.TryGetProperty("assets", out var assets) && assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
// 跳过 GitCode 自动生成的源码包(type=source),只取真正的发布附件
|
||||
var type = Str(a, "type");
|
||||
if (string.Equals(type, "source", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? Str(a, "file_name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url"),
|
||||
DownloadUrl = Str(a, "download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size"),
|
||||
Sha256 = Str(a, "sha256") ?? Str(a, "digest"),
|
||||
Type = type
|
||||
});
|
||||
}
|
||||
}
|
||||
// 有些平台把附件放在顶层 assets_link / attachments
|
||||
if (info.Assets.Count == 0 &&
|
||||
el.TryGetProperty("attachments", out var att) && att.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in att.EnumerateArray())
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size")
|
||||
});
|
||||
}
|
||||
return info;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static string? Str(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static bool? Bool(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) &&
|
||||
(v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
|
||||
? v.GetBoolean() : null;
|
||||
|
||||
private static long Num(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
|
||||
// ---- 模型链路:原样委托,不做任何改动 ----
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
=> _content.ListTreeAsync(rootPath, ct);
|
||||
|
||||
public Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
=> _content.DownloadAsync(entry, ct);
|
||||
|
||||
/// <summary>启动器包:优先用 Release 附件直链下载(url 已被 ApplyReleaseAsync 覆盖)。</summary>
|
||||
public Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
=> _content.DownloadPackageAsync(package, ct);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
|
||||
/// https://gitcode.com/<owner>/<repo>/tree/<branch>/model 这样的地址。
|
||||
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
|
||||
/// 文件项自带 download_url(raw.gitcode.com/blobs/<sha>/...),可直接下载二进制。
|
||||
/// </summary>
|
||||
public sealed class GitCodeRemote : IModelRemote
|
||||
{
|
||||
public const string DefaultRepository = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _api;
|
||||
private readonly string _branch;
|
||||
private readonly string _versionUrl;
|
||||
private readonly string? _fallbackUrl;
|
||||
private readonly string _displayName;
|
||||
private string _modelDir = "model";
|
||||
|
||||
public string DisplayName => _displayName;
|
||||
|
||||
public GitCodeRemote(string? manifestUrl = null, string? repository = null)
|
||||
{
|
||||
var (owner, repo, branch) = ParseRepository(repository);
|
||||
_branch = branch;
|
||||
_api = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/contents/";
|
||||
_displayName = string.IsNullOrWhiteSpace(repository)
|
||||
? DefaultRepository : repository!.TrimEnd('/');
|
||||
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||
{
|
||||
_versionUrl = _api + "version.json?ref=" + _branch;
|
||||
_fallbackUrl = _api + "model/version.json?ref=" + _branch;
|
||||
}
|
||||
else
|
||||
{
|
||||
_versionUrl = manifestUrl!;
|
||||
_fallbackUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从仓库 URL 解析 owner / repo / branch,解析失败回退到默认仓库。</summary>
|
||||
private static (string Owner, string Repo, string Branch) ParseRepository(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC", "main");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
|
||||
var owner = parts[0];
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
var branch = parts.Length >= 4 && parts[2].Equals("tree", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[3] : "main";
|
||||
return (owner, repo, branch);
|
||||
}
|
||||
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
RepoVersion? version = await ReadVersionFromAsync(_versionUrl, ct);
|
||||
if (version == null && _fallbackUrl != null)
|
||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||
_modelDir = version.ModelDir.Trim('/');
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
||||
{
|
||||
string text;
|
||||
try
|
||||
{
|
||||
// 离线 / 网络不通时最多等 10 秒,不能让启动界面一直卡在「检查更新」
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
text = await _http.GetStringAsync(url, timeout.Token);
|
||||
}
|
||||
catch (HttpRequestException) { return null; }
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; }
|
||||
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '{') return null;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var payload = text;
|
||||
if (doc.RootElement.TryGetProperty("encoding", out _) &&
|
||||
doc.RootElement.TryGetProperty("content", out var content))
|
||||
{
|
||||
var raw = Convert.FromBase64String(content.GetString() ?? "");
|
||||
payload = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
|
||||
payload, GC.Services.Json.Options);
|
||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归列出目录树(含目录项与文件项)。
|
||||
/// 每个子目录一次 HTTP 请求,因此并行展开同一层的所有目录,
|
||||
/// 否则 3 个模型、十几个目录串行请求会非常慢。
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
var bag = new System.Collections.Concurrent.ConcurrentBag<RepoEntry>();
|
||||
var repoPath = (rootPath ?? _modelDir).Trim('/');
|
||||
await WalkParallelAsync(repoPath, "", 0, bag, ct);
|
||||
|
||||
// 稳定排序:目录在前、按路径字典序,保证调用方拿到确定顺序
|
||||
result = bag.OrderBy(e => e.IsDirectory ? 0 : 1)
|
||||
.ThenBy(e => e.RelativePath, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkParallelAsync(string repoPath, string relative, int depth,
|
||||
System.Collections.Concurrent.ConcurrentBag<RepoEntry> bag, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
string text;
|
||||
try { text = await GetWithRetryAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
var subDirs = new List<(string Path, string Relative)>();
|
||||
|
||||
using (var doc = JsonDocument.Parse(text))
|
||||
{
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
// 这些目录不是模型运行数据,跳过可显著减少请求
|
||||
// (模型目录里常见的 src/ bin/ obj/ 是源码与构建产物)
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
bag.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) subDirs.Add((path!, childRelative));
|
||||
}
|
||||
}
|
||||
|
||||
if (subDirs.Count == 0) return;
|
||||
|
||||
// 同层并行;并发保持很低——GitCode API 对突发请求会返回 429
|
||||
using var gate = new SemaphoreSlim(2);
|
||||
var tasks = subDirs.Select(async d =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try { await WalkParallelAsync(d.Path, d.Relative, depth + 1, bag, ct); }
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string repoPath, string relative, int depth,
|
||||
List<RepoEntry> result, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) await WalkAsync(path!, childRelative, depth + 1, result, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>遍历时忽略的目录:源码与构建产物不属于模型运行数据。</summary>
|
||||
private static bool IsIgnoredDir(string name) => name switch
|
||||
{
|
||||
"src" => true,
|
||||
"bin" => true,
|
||||
"obj" => true,
|
||||
"node_modules" => true,
|
||||
".git" => true,
|
||||
".vs" => true,
|
||||
_ => false
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 带退避重试的 GET。GitCode API 对突发请求返回 429,
|
||||
/// 这里做 3 次指数退避,避免并行遍历时直接失败。
|
||||
/// </summary>
|
||||
private async Task<string> GetWithRetryAsync(string url, CancellationToken ct,
|
||||
int maxAttempts = 3)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _http.GetStringAsync(url, ct);
|
||||
}
|
||||
catch (HttpRequestException ex) when (attempt < maxAttempts)
|
||||
{
|
||||
// 429 / 5xx 才重试,其余直接抛
|
||||
var retriable = ex.StatusCode is null ||
|
||||
(int)ex.StatusCode == 429 ||
|
||||
(int)ex.StatusCode >= 500;
|
||||
if (!retriable) throw;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(400 * attempt * attempt), ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
|
||||
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
|
||||
|
||||
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (!doc.RootElement.TryGetProperty("content", out var content))
|
||||
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
|
||||
return Convert.FromBase64String(content.GetString() ?? "");
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
|
||||
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
try
|
||||
{
|
||||
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(apiUrl, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("download_url", out var dl))
|
||||
url = dl.GetString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
return await _http.GetByteArrayAsync(url!, ct);
|
||||
}
|
||||
|
||||
private static string Str(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() ?? "" : "";
|
||||
|
||||
private static string? NullableStr(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static long Num(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
|
||||
///
|
||||
/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path}
|
||||
/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url
|
||||
/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path}
|
||||
/// · Release:GET /api/v1/repos/{owner}/{repo}/releases
|
||||
/// 版本取 tag_name;附件取 assets[].browser_download_url
|
||||
///
|
||||
/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。
|
||||
/// </summary>
|
||||
public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
private readonly SourcePreset _preset;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
public GiteaRemote(SourcePreset preset)
|
||||
{
|
||||
_preset = preset;
|
||||
DisplayName = preset.Name;
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => _preset.Id;
|
||||
|
||||
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
|
||||
|
||||
// ---------------------------------------------------------------- 清单
|
||||
|
||||
/// <summary>
|
||||
/// 两件事分开取:
|
||||
/// · **模型清单**永远来自仓库 version.json(模型不需要发 Release)
|
||||
/// · **启动器版本**只认 Release;没有 Release 时把版本号留空,
|
||||
/// 由上层去问另一个源(LeaderUpdater 会横向比较)。
|
||||
/// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var fromRepo = await TryGetVersionFromRepoAsync(ct);
|
||||
var fromRelease = await TryGetVersionFromReleasesAsync(ct);
|
||||
|
||||
// 模型清单:仓库里有就用仓库的(保证模型能更新)
|
||||
var result = fromRepo ?? new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch
|
||||
};
|
||||
|
||||
if (fromRelease != null)
|
||||
{
|
||||
// Release 提供启动器版本与平台附件
|
||||
result.Launcher.Version = fromRelease.Launcher.Version;
|
||||
foreach (var kv in fromRelease.Launcher.Packages)
|
||||
result.Launcher.Packages[kv.Key] = kv.Value;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
|
||||
result.Launcher.Version = "";
|
||||
result.Launcher.Packages.Clear();
|
||||
|
||||
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
||||
return result.Models.Count > 0 ? result : null;
|
||||
}
|
||||
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") })
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = await Http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options);
|
||||
if (doc != null) return doc;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个),
|
||||
/// 并把它对应平台的附件填进 packages。
|
||||
/// </summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromReleasesAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
|
||||
|
||||
var candidates = new List<(string Version, JsonElement Node)>();
|
||||
foreach (var rel in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True)
|
||||
continue; // 草稿不算发布
|
||||
var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";
|
||||
var ver = VersionUtil.Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(ver)) continue;
|
||||
candidates.Add((ver, rel));
|
||||
}
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
// 还没发布 Release 是正常状态:交给上层去问另一个源
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
var best = candidates
|
||||
.OrderByDescending(c => VersionUtil.Parse(c.Version))
|
||||
.First();
|
||||
|
||||
var result = new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch,
|
||||
Launcher = new RepoLauncher { Version = best.Version }
|
||||
};
|
||||
|
||||
// 附件:按文件名识别平台
|
||||
if (best.Node.TryGetProperty("assets", out var assets) &&
|
||||
assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";
|
||||
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue;
|
||||
|
||||
var rid = PlatformFromAssetName(name);
|
||||
if (rid == null) continue;
|
||||
|
||||
var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
result.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = url,
|
||||
AssetName = name,
|
||||
Size = size
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result.Launcher.Packages.Count > 0 ? result : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64</summary>
|
||||
private static string? PlatformFromAssetName(string name)
|
||||
{
|
||||
var n = name.ToLowerInvariant();
|
||||
if (!n.EndsWith(".zip")) return null;
|
||||
if (n.Contains("win") && n.Contains("arm64")) return "win-arm64";
|
||||
if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64";
|
||||
if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64";
|
||||
if (n.Contains("mac") && n.Contains("x64")) return "osx-x64";
|
||||
if (n.Contains("linux") && n.Contains("x64")) return "linux-x64";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 目录
|
||||
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string apiPath, string relPrefix, List<RepoEntry> sink,
|
||||
CancellationToken ct, int depth)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
|
||||
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
|
||||
string json;
|
||||
try { json = await Http.GetStringAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// 单文件
|
||||
if (root.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
AddFile(root, relPrefix, sink);
|
||||
return;
|
||||
}
|
||||
if (root.ValueKind != JsonValueKind.Array) return;
|
||||
|
||||
var subdirs = new List<(string Path, string Rel)>();
|
||||
foreach (var item in root.EnumerateArray())
|
||||
{
|
||||
var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : "";
|
||||
var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : "";
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
// 跳过构建产物与源码,模型包只需要清单与数据
|
||||
if (type == "dir")
|
||||
{
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
subdirs.Add((apiPath + "/" + name, relPrefix + name + "/"));
|
||||
}
|
||||
else
|
||||
{
|
||||
AddFile(item, relPrefix, sink);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (p, rel) in subdirs)
|
||||
await WalkAsync(p, rel, sink, ct, depth + 1);
|
||||
}
|
||||
|
||||
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
|
||||
|
||||
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
|
||||
{
|
||||
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name;
|
||||
var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null;
|
||||
var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null;
|
||||
|
||||
sink.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path,
|
||||
RelativePath = relPrefix + name,
|
||||
IsDirectory = false,
|
||||
DownloadUrl = dl,
|
||||
Size = size,
|
||||
Sha = sha
|
||||
});
|
||||
}
|
||||
|
||||
private static bool IsIgnoredDir(string name) =>
|
||||
name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs"
|
||||
or ".idea" or ".vscode";
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
// 优先用 API 提供的 download_url;没有就按 raw 规约拼
|
||||
var url = entry.DownloadUrl;
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
url = _preset.RawUrl(entry.Path);
|
||||
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(package.Url)) return null;
|
||||
try { return await Http.GetByteArrayAsync(package.Url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Json
|
||||
{
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip
|
||||
};
|
||||
|
||||
public static T? Read<T>(string path)
|
||||
{
|
||||
if (!System.IO.File.Exists(path)) return default;
|
||||
return JsonSerializer.Deserialize<T>(System.IO.File.ReadAllText(path), Options);
|
||||
}
|
||||
|
||||
public static void Write<T>(string path, T value)
|
||||
{
|
||||
var dir = System.IO.Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
|
||||
var tmp = path + ".tmp";
|
||||
System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options));
|
||||
System.IO.File.Move(tmp, path, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
|
||||
/// 1. 关闭主窗口与所有模型窗口;
|
||||
/// 2. 弹出圆角进度窗;
|
||||
/// 3. 下载最新版到当前目录(与旧版并列);
|
||||
/// 4. 安排替换脚本、关进度窗、退出进程。
|
||||
/// 失败时恢复主窗口,继续使用当前版本。
|
||||
/// </summary>
|
||||
public static class LauncherUpdateFlow
|
||||
{
|
||||
private static bool _running;
|
||||
public static bool IsRunning => _running;
|
||||
|
||||
public static async Task RunAsync(AppServices services, string title)
|
||||
{
|
||||
if (_running) return;
|
||||
_running = true;
|
||||
|
||||
var desktop = Application.Current?.ApplicationLifetime
|
||||
as IClassicDesktopStyleApplicationLifetime;
|
||||
var mainWindow = desktop?.MainWindow;
|
||||
var progressWindow = new UpdaterWindow(title);
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 关闭所有窗口
|
||||
if (desktop != null) desktop.MainWindow = null;
|
||||
try { mainWindow?.Close(); } catch { }
|
||||
foreach (var w in OpenWindows().ToList())
|
||||
{
|
||||
try { w.Close(); } catch { }
|
||||
}
|
||||
|
||||
// 2. 进度窗
|
||||
progressWindow.Show();
|
||||
progressWindow.Report(0, "准备更新…");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
|
||||
|
||||
// 3. 下载
|
||||
var progress = new Progress<UpdateProgressInfo>(p =>
|
||||
progressWindow.Report(p.Value, p.Stage));
|
||||
|
||||
var result = await LauncherUpdater.DownloadAsync(
|
||||
services.Paths, services.Updates.Remote, progress);
|
||||
|
||||
if (result.State == UpdateRunState.Failed)
|
||||
{
|
||||
progressWindow.Report(0, "更新失败", result.Message);
|
||||
await Task.Delay(2200);
|
||||
_running = false;
|
||||
progressWindow.Close();
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
return;
|
||||
}
|
||||
|
||||
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
|
||||
|
||||
// 4. 安排替换(下次启动生效 / 脚本接管重启)
|
||||
var scheduled = LauncherUpdater.ScheduleApply(
|
||||
services.Paths, result.PackageName ?? "");
|
||||
|
||||
if (!scheduled)
|
||||
{
|
||||
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
|
||||
await Task.Delay(2200);
|
||||
_running = false;
|
||||
progressWindow.Close();
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(400);
|
||||
progressWindow.Close();
|
||||
desktop?.Shutdown();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"更新流程异常: {ex}");
|
||||
_running = false;
|
||||
try { progressWindow.Close(); } catch { }
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RestoreMainWindow(
|
||||
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
|
||||
{
|
||||
if (desktop == null || mainWindow == null) return;
|
||||
try
|
||||
{
|
||||
desktop.MainWindow = mainWindow;
|
||||
mainWindow.Show();
|
||||
mainWindow.Activate();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<Window> OpenWindows()
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime
|
||||
is not IClassicDesktopStyleApplicationLifetime d)
|
||||
yield break;
|
||||
foreach (var w in d.Windows)
|
||||
{
|
||||
if (w is UpdaterWindow) continue;
|
||||
yield return w;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
// ===========================================================================
|
||||
// 启动器更新模块(唯一实现)
|
||||
//
|
||||
// 需求(按用户):
|
||||
// · 只认 GitCode Release 的 latest 版本号(tag),文件名格式:
|
||||
// GC-<版本>-<系统>-<架构>.exe / .app
|
||||
// 例 GC-1.0.3-win-amd64.exe / GC-1.0.3-mac-arm64.app
|
||||
// · 当前运行版本与 latest 不同 => 提示更新;相同 => 无需更新
|
||||
// · 下载的新版解压到「当前运行目录」,与旧版并列;.GC 完全不动
|
||||
// · 更新完成后:删除同系统同架构、版本号 != latest 的其它 GC-* 文件;
|
||||
// 异系统 / 异架构的文件一律不碰
|
||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||
// ===========================================================================
|
||||
|
||||
public sealed class UpdateProgressInfo
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Stage { get; init; } = "";
|
||||
}
|
||||
|
||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
||||
|
||||
public sealed class UpdateRunResult
|
||||
{
|
||||
public UpdateRunState State { get; init; }
|
||||
public string Version { get; init; } = "";
|
||||
public string Message { get; init; } = "";
|
||||
public string? PackageName { get; init; }
|
||||
public string? NewAppPath { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||
public static class LauncherUpdater
|
||||
{
|
||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||
public static string RunningVersion => UpdateService.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||
public static string CurrentRid => UpdateService.CurrentRid;
|
||||
|
||||
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
||||
public static string PlatformLabel => CurrentRid switch
|
||||
{
|
||||
"win-x64" => "win-amd64",
|
||||
"win-arm64" => "win-arm64",
|
||||
"osx-arm64" => "mac-arm64",
|
||||
"osx-x64" => "mac-x64",
|
||||
"linux-x64" => "linux-amd64",
|
||||
_ => CurrentRid
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 检查
|
||||
|
||||
/// <summary>
|
||||
/// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。
|
||||
/// 只比版本号,不比 sha256。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**,
|
||||
/// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。
|
||||
/// </summary>
|
||||
public static async Task<string?> CheckAsync(CancellationToken ct = default)
|
||||
=> await CheckAllAsync(null, ct);
|
||||
|
||||
/// <summary>兼容旧调用:优先用给定 remote,同时仍会比对另一个源。</summary>
|
||||
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
|
||||
=> await CheckAllAsync(remote, ct);
|
||||
|
||||
private static async Task<string?> CheckAllAsync(IModelRemote? preferred, CancellationToken ct)
|
||||
{
|
||||
var candidates = new List<(string Source, string Version)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 优先复用调用方已建好的 remote(避免重复建实例)
|
||||
var remote = preferred != null &&
|
||||
SourcePreset.Detect(preferred.DisplayName).Id == preset.Id
|
||||
? preferred
|
||||
: SourceSelector.CreateRemote(preset);
|
||||
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
if (v.Length == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: {v}");
|
||||
candidates.Add((preset.Name, v));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.Count == 0) return null;
|
||||
|
||||
// 取版本号最高的(第 7 项)
|
||||
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
|
||||
Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})");
|
||||
|
||||
var cmp = VersionUtil.Compare(best.Version, RunningVersion);
|
||||
|
||||
// 远端版本更新 → 提示更新
|
||||
if (cmp > 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新");
|
||||
return best.Version;
|
||||
}
|
||||
|
||||
// 远端版本更旧 → 不提示
|
||||
if (cmp < 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本号相同:比对当前程序的 sha256 与 Release 包
|
||||
// 相符 → 视为最新,不提示
|
||||
// 不相符 → 说明是重新编译的同版本程序,必须提示下载
|
||||
var same = await SameFingerprintAsync(best.Source, best.Version, ct);
|
||||
if (same == null)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理");
|
||||
return null;
|
||||
}
|
||||
if (same.Value)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本相同但指纹不同:是自行编译的构建,不提示更新
|
||||
Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新");
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 比对「当前运行程序」与「Release 平台包」的 sha256。
|
||||
/// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。
|
||||
/// </summary>
|
||||
private static async Task<bool?> SameFingerprintAsync(string sourceName, string version,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var preset = SourcePreset.All.FirstOrDefault(p =>
|
||||
string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase));
|
||||
if (preset == null) return null;
|
||||
|
||||
var rid = CurrentRid;
|
||||
Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…");
|
||||
|
||||
// 定位进程对应的可执行文件 / .app
|
||||
var self = Environment.ProcessPath;
|
||||
if (string.IsNullOrWhiteSpace(self)) return null;
|
||||
var selfPath = self!;
|
||||
// 单文件 / dotnet 宿主时退回到程序集位置
|
||||
if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
selfPath = typeof(LauncherUpdater).Assembly.Location;
|
||||
|
||||
var selfHash = await HashFileAsync(selfPath, ct);
|
||||
Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…");
|
||||
|
||||
// 下载 Release 对应平台包,取包内主程序再算
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null)
|
||||
return null;
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg, ct);
|
||||
if (bytes == null || bytes.Length == 0) return null;
|
||||
|
||||
var remoteHash = await HashZipPayloadAsync(bytes, ct);
|
||||
if (remoteHash == null) return null;
|
||||
Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…");
|
||||
|
||||
return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[update] sha256 比对失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var fs = File.OpenRead(path);
|
||||
var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct);
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
|
||||
/// <summary>从发布包(zip)里取出主程序并算 sha256。</summary>
|
||||
private static async Task<string?> HashZipPayloadAsync(byte[] zip, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var ms = new MemoryStream(zip);
|
||||
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
||||
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
|
||||
var entry = archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
|
||||
e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
|
||||
if (entry == null) return null;
|
||||
|
||||
await using var es = entry.Open();
|
||||
using var buf = new MemoryStream();
|
||||
await es.CopyToAsync(buf, ct);
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray());
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。
|
||||
/// 某个源没有 Release(返回 null)时自动跳过。
|
||||
/// </summary>
|
||||
private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync(
|
||||
IModelRemote fallback, CancellationToken ct)
|
||||
{
|
||||
var rid = CurrentRid;
|
||||
var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 无 Release");
|
||||
continue;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包");
|
||||
continue;
|
||||
}
|
||||
var hasPkg = v.Launcher.Packages.ContainsKey(rid) ||
|
||||
v.Launcher.Packages.ContainsKey("default");
|
||||
if (!hasPkg)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用");
|
||||
found.Add((preset.Name, v, remote));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (found.Count == 0) return null;
|
||||
|
||||
var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First();
|
||||
Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})");
|
||||
return (best.Version, best.Remote);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
/// <summary>
|
||||
/// 下载 latest 版本到当前运行目录(与旧版并列)。
|
||||
/// 返回新版包名,供后续替换脚本使用。
|
||||
/// </summary>
|
||||
public static async Task<UpdateRunResult> DownloadAsync(
|
||||
AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" });
|
||||
|
||||
// 两个源都问一遍:某个源没发 Release 时自动换另一个,
|
||||
// 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
|
||||
// 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。
|
||||
// 注意:模型清单可能仍然有效,但启动器升级必须有 Release。
|
||||
var hasUsable = version != null &&
|
||||
!string.IsNullOrWhiteSpace(version.Launcher.Version) &&
|
||||
version.Launcher.Packages.Count > 0;
|
||||
|
||||
if (!hasUsable)
|
||||
{
|
||||
var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName;
|
||||
Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源");
|
||||
var pick = await GetBestReleaseAsync(remote, ct);
|
||||
if (pick == null) return Fail("两个源都没有可用的 Release 发布包");
|
||||
version = pick.Value.Version;
|
||||
remote = pick.Value.Remote; // 后续下载必须用这个源的 remote
|
||||
}
|
||||
|
||||
var latest = (version!.Launcher.Version ?? "").Trim();
|
||||
var rid = CurrentRid;
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) &&
|
||||
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
||||
return Fail($"该平台({rid})没有对应发布包");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
||||
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
||||
|
||||
// sha256 校验(Release 提供时)
|
||||
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return Fail("下载文件校验失败(sha256 不符)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压到当前目录" });
|
||||
|
||||
// 解压到临时中转目录,再搬到当前运行目录
|
||||
var installDir = paths.InstallDirectory;
|
||||
Directory.CreateDirectory(installDir);
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
try { ZipSafety.ExtractToDirectory(zip, staging); }
|
||||
finally { try { File.Delete(zip); } catch { } }
|
||||
|
||||
// 只展平「单个非 .app 顶层目录」的 zip
|
||||
FlattenStaging(staging);
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" });
|
||||
|
||||
var packageName = MoveToInstallDir(staging, installDir, latest);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
|
||||
Directory.CreateDirectory(paths.UpdateRoot);
|
||||
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
|
||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
return new UpdateRunResult
|
||||
{
|
||||
State = UpdateRunState.Ready,
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已下载到当前目录",
|
||||
PackageName = packageName,
|
||||
NewAppPath = Path.Combine(installDir, packageName)
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
catch (Exception ex) { return Fail(ex.Message); }
|
||||
}
|
||||
|
||||
private static UpdateRunResult Fail(string msg) => new()
|
||||
{
|
||||
State = UpdateRunState.Failed,
|
||||
Message = msg
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 应用(下次启动)
|
||||
|
||||
/// <summary>
|
||||
/// 生成替换脚本并启动。脚本等本进程退出后:
|
||||
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。
|
||||
/// 返回 true 表示调用方应立即退出进程。
|
||||
/// </summary>
|
||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
||||
{
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||
{
|
||||
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var isWin = OperatingSystem.IsWindows();
|
||||
var script = Path.Combine(paths.UpdateRoot, isWin ? "apply.bat" : "apply.sh");
|
||||
var content = isWin ? WindowsScript() : UnixScript();
|
||||
File.WriteAllText(script, content, new System.Text.UTF8Encoding(false));
|
||||
|
||||
if (!isWin)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.SetUnixFileMode(script,
|
||||
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
var psi = isWin
|
||||
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
||||
{ UseShellExecute = false, CreateNoWindow = true }
|
||||
: new System.Diagnostics.ProcessStartInfo("/bin/sh")
|
||||
{ UseShellExecute = false, CreateNoWindow = true };
|
||||
if (isWin) psi.ArgumentList.Add("/c");
|
||||
psi.ArgumentList.Add(script);
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"启动替换脚本失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary>
|
||||
public static bool TryApplyPending(AppPaths paths)
|
||||
{
|
||||
if (paths.IsDevelopment) return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
var name = ReadMarker(marker, "NAME");
|
||||
if (string.IsNullOrWhiteSpace(name)) return false;
|
||||
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!)))
|
||||
return false; // 新版本不在了,放弃
|
||||
|
||||
return ScheduleApply(paths, name!);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 脚本(全部相对路径)
|
||||
|
||||
private static string UnixScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("#!/bin/sh");
|
||||
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up");
|
||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && pwd)");
|
||||
s.AppendLine("MARKER=\"$HERE/update.txt\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# read marker");
|
||||
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
||||
s.AppendLine("if [ ! -e \"$NEW\" ]; then");
|
||||
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# wait for old process to exit (this script is started by it)");
|
||||
s.AppendLine("sleep 2");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# launch new version first");
|
||||
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
|
||||
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
||||
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
|
||||
s.AppendLine(" [ -e \"$item\" ] || continue");
|
||||
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
||||
s.AppendLine(" base=$(basename \"$item\")");
|
||||
s.AppendLine(" stem=${base#GC-}");
|
||||
s.AppendLine(" case \"$base\" in");
|
||||
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
||||
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
||||
s.AppendLine(" *) continue ;;");
|
||||
s.AppendLine(" esac");
|
||||
s.AppendLine(" ver=${stem%%-*}");
|
||||
s.AppendLine(" rest=${stem#*-}");
|
||||
s.AppendLine(" plat=\"${rest%-*}-${rest##*-}\"");
|
||||
s.AppendLine(" # skip other platforms entirely");
|
||||
s.AppendLine(" [ \"$plat\" != \"$NEWPLAT\" ] && continue");
|
||||
s.AppendLine(" # same platform: keep only latest version");
|
||||
s.AppendLine(" if [ \"$ver\" = \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"keep: $base\"");
|
||||
s.AppendLine(" else");
|
||||
s.AppendLine(" echo \"remove (version $ver != $NEWVER): $base\"");
|
||||
s.AppendLine(" rm -rf \"$item\" 2>/dev/null");
|
||||
s.AppendLine(" fi");
|
||||
s.AppendLine("done");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rm -f \"$MARKER\"");
|
||||
s.AppendLine("rm -f \"$HERE\"/*.sh 2>/dev/null");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
private static string WindowsScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("@echo off");
|
||||
s.AppendLine("chcp 65001 >nul 2>&1");
|
||||
s.AppendLine("set \"HERE=%~dp0\"");
|
||||
s.AppendLine("set \"DST=%~dp0..\\..\"");
|
||||
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
|
||||
s.AppendLine("timeout /t 2 /nobreak >nul");
|
||||
s.AppendLine();
|
||||
s.AppendLine("set \"NEWNAME=\"");
|
||||
s.AppendLine("set \"NEWVER=\"");
|
||||
s.AppendLine("set \"NEWPLAT=\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
|
||||
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("if not exist \"%DST%\\%NEWNAME%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem launch new version");
|
||||
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("powershell -NoProfile -ExecutionPolicy Bypass -Command \"^");
|
||||
s.AppendLine("$dst='%DST%'; $new='%NEWNAME%'; $ver='%NEWVER%'; $plat='%NEWPLAT%';^");
|
||||
s.AppendLine("Get-ChildItem -LiteralPath $dst -Filter 'GC-*' | ForEach-Object {^");
|
||||
s.AppendLine(" $n=$_.Name; if($n -eq $new){return};^");
|
||||
s.AppendLine(" $m=[regex]::Match($n,'^GC-(.+?)-([^-]+)-([^-]+)\\.(app|exe)$');^");
|
||||
s.AppendLine(" if(-not $m.Success){return};^");
|
||||
s.AppendLine(" $fver=$m.Groups[1].Value; $fplat=$m.Groups[2].Value+'-'+$m.Groups[3].Value;^");
|
||||
s.AppendLine(" if($fplat -ne $plat){return};^");
|
||||
s.AppendLine(" if($fver -eq $ver){ Write-Host \\\"keep: $n\\\" }^");
|
||||
s.AppendLine(" else { Write-Host \\\"remove: $n\\\"; Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }^");
|
||||
s.AppendLine("}\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("del /Q \"%MARKER%\" >nul 2>&1");
|
||||
s.AppendLine("del /Q \"%~f0\" >nul 2>&1");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
/// <summary>展平只有一个顶层目录、且不是 .app 的 zip。</summary>
|
||||
private static void FlattenStaging(string dir)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(dir);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var flat = dir + "-flat";
|
||||
if (Directory.Exists(flat)) Directory.Delete(flat, true);
|
||||
Directory.Move(inner, flat);
|
||||
Directory.Delete(dir, true);
|
||||
Directory.Move(flat, dir);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把 staging 里的新版搬到当前目录,与旧版并列。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。.GC 绝不覆盖。
|
||||
/// </summary>
|
||||
private static string? MoveToInstallDir(string staging, string installDir, string latest)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(staging))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var dest = Path.Combine(installDir, name);
|
||||
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
|
||||
// 保证 .app 里可执行文件可执行
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(dest))
|
||||
{
|
||||
var macOs = Path.Combine(dest, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var f in Directory.GetFiles(macOs, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var mode = File.GetUnixFileMode(f);
|
||||
File.SetUnixFileMode(f, mode | UnixFileMode.UserExecute);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return name;
|
||||
}
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"安装新版失败: {ex.Message}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ReadMarker(string file, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file))
|
||||
{
|
||||
if (line.StartsWith(key + "=", StringComparison.Ordinal))
|
||||
return line[(key.Length + 1)..].Trim();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Data;
|
||||
using Avalonia.Platform;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
|
||||
public sealed class L : INotifyPropertyChanged
|
||||
{
|
||||
private static readonly L _instance = new();
|
||||
public static L I => _instance;
|
||||
|
||||
private Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<WeakReference<LocalizedString>> _watchers = new();
|
||||
|
||||
public string Language { get; private set; } = "zh-CN";
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
public event Action? LanguageChanged;
|
||||
|
||||
public static readonly (string Code, string Label)[] Supported =
|
||||
{
|
||||
("zh-CN", "简体中文"),
|
||||
("en", "English")
|
||||
};
|
||||
|
||||
public void Initialize(string? preference)
|
||||
{
|
||||
var code = Resolve(preference);
|
||||
LoadLanguage(code, force: true);
|
||||
}
|
||||
|
||||
public static string Resolve(string? pref)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(pref) && !pref.Equals("auto", StringComparison.OrdinalIgnoreCase))
|
||||
return pref!.StartsWith("en", StringComparison.OrdinalIgnoreCase) ? "en" : "zh-CN";
|
||||
var ui = CultureInfo.CurrentUICulture;
|
||||
return ui.TwoLetterISOLanguageName.Equals("zh", StringComparison.OrdinalIgnoreCase) ? "zh-CN" : "en";
|
||||
}
|
||||
|
||||
public void SetLanguage(string code)
|
||||
{
|
||||
code = Resolve(code);
|
||||
if (code == Language) return;
|
||||
LoadLanguage(code, force: false);
|
||||
}
|
||||
|
||||
private void LoadLanguage(string code, bool force)
|
||||
{
|
||||
var loaded = ReadTable(code) ?? ReadTable("en") ?? new Dictionary<string, string>();
|
||||
if (code != "zh-CN")
|
||||
{
|
||||
// 中文兜底,避免缺键出现空白
|
||||
foreach (var kv in ReadTable("zh-CN") ?? new Dictionary<string, string>())
|
||||
loaded.TryAdd(kv.Key, kv.Value);
|
||||
}
|
||||
_map = loaded;
|
||||
if (!force && code == Language) return;
|
||||
Language = code;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language)));
|
||||
// 顺带清理已回收的弱引用,避免 _watchers 只增不减
|
||||
_watchers.RemoveAll(w => !w.TryGetTarget(out _));
|
||||
foreach (var w in _watchers)
|
||||
if (w.TryGetTarget(out var ls)) ls.Refresh();
|
||||
LanguageChanged?.Invoke();
|
||||
}
|
||||
|
||||
private static Dictionary<string, string>? ReadTable(string code)
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
|
||||
using var stream = AssetLoader.Open(uri);
|
||||
using var reader = new StreamReader(stream);
|
||||
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
|
||||
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public string this[string key]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrEmpty(key)) return "";
|
||||
return _map.TryGetValue(key, out var v) ? v : key;
|
||||
}
|
||||
}
|
||||
|
||||
public string F(string key, params object?[] args)
|
||||
{
|
||||
var fmt = this[key];
|
||||
try { return string.Format(fmt, args); }
|
||||
catch (FormatException) { return fmt; }
|
||||
}
|
||||
|
||||
public LocalizedString For(string key)
|
||||
{
|
||||
var ls = new LocalizedString(key);
|
||||
_watchers.Add(new WeakReference<LocalizedString>(ls));
|
||||
return ls;
|
||||
}
|
||||
|
||||
/// <summary>按 i18n 字典取值:当前语言 -> 英文 -> zh-CN -> 默认名。</summary>
|
||||
public string Pick(Dictionary<string, string>? dict, string fallback)
|
||||
{
|
||||
if (dict == null || dict.Count == 0) return fallback;
|
||||
if (dict.TryGetValue(Language, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
|
||||
if (Language != "en" && dict.TryGetValue("en", out var en) && !string.IsNullOrWhiteSpace(en)) return en;
|
||||
if (dict.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
|
||||
foreach (var kv in dict) if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value;
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class LocalizedString : INotifyPropertyChanged
|
||||
{
|
||||
public string Key { get; }
|
||||
public LocalizedString(string key) => Key = key;
|
||||
public string Value => L.I[Key];
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
|
||||
}
|
||||
|
||||
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
|
||||
public sealed class LocExtension : MarkupExtension
|
||||
{
|
||||
public LocExtension() { }
|
||||
public LocExtension(string key) => Key = key;
|
||||
public string Key { get; set; } = "";
|
||||
|
||||
public override object ProvideValue(IServiceProvider serviceProvider)
|
||||
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动时运行内存分配(类似启动器的 -Xmx)。
|
||||
/// 启动器只负责把这份预算通过 <c>IModelContext.MemoryBudgetMb</c> 交给模型,
|
||||
/// 具体怎么用(贴图分辨率、缓存大小)由模型自己决定。
|
||||
/// </summary>
|
||||
public sealed class MemoryBudget
|
||||
{
|
||||
public int BudgetMb { get; private set; } = 2048;
|
||||
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
|
||||
public long ManagedBytes => System.GC.GetTotalMemory(false);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public void Apply(int mb)
|
||||
{
|
||||
BudgetMb = Math.Clamp(mb, 256, 16384);
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动预算:取设备可用物理内存的一部分(约 1/4),
|
||||
/// 夹在 512–8192 MB 之间,低配设备也不会因为预算过大而卡顿。
|
||||
/// </summary>
|
||||
public static int AutoComputeMb()
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = System.GC.GetGCMemoryInfo();
|
||||
var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0);
|
||||
if (totalMb > 0)
|
||||
return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192);
|
||||
}
|
||||
catch { /* 平台不支持时回退默认值 */ }
|
||||
return 2048;
|
||||
}
|
||||
|
||||
/// <summary>按设置应用:auto 时自动计算,否则用手动值。</summary>
|
||||
public void ApplyAuto(bool auto, int manualMb)
|
||||
=> Apply(auto ? AutoComputeMb() : manualMb);
|
||||
|
||||
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
|
||||
public void Refresh() => Changed?.Invoke();
|
||||
|
||||
public double UsageRatio => BudgetBytes <= 0 ? 0 : Math.Clamp((double)ManagedBytes / BudgetBytes, 0, 1);
|
||||
|
||||
public string UsageText => $"{ModelScanner.HumanSize(ManagedBytes)} / {BudgetMb} MB";
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using GC.Models;
|
||||
using GC.ModelSdk;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
|
||||
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
|
||||
/// </summary>
|
||||
public sealed class ModelHost
|
||||
{
|
||||
public const int SupportedApiVersion = 1;
|
||||
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly MemoryBudget _memory;
|
||||
|
||||
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_memory = memory;
|
||||
}
|
||||
|
||||
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
|
||||
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
|
||||
{
|
||||
var session = CreateSession(package, requestClose, progress);
|
||||
try
|
||||
{
|
||||
session.Runtime.Prepare(session.Context);
|
||||
var view = session.Runtime.CreateView(session.Context)
|
||||
?? throw new InvalidOperationException("模型没有返回界面");
|
||||
return session.Complete(view);
|
||||
}
|
||||
catch
|
||||
{
|
||||
session.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
|
||||
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
|
||||
/// </summary>
|
||||
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
|
||||
Action<double, string?>? progress = null)
|
||||
{
|
||||
var session = CreateSession(package, requestClose, progress);
|
||||
try
|
||||
{
|
||||
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
|
||||
var view = session.Runtime.CreateView(session.Context)
|
||||
?? throw new InvalidOperationException("模型没有返回界面");
|
||||
return session.Complete(view);
|
||||
}
|
||||
catch
|
||||
{
|
||||
session.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
|
||||
{
|
||||
var assemblyPath = package.AssemblyPath;
|
||||
if (!File.Exists(assemblyPath))
|
||||
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
|
||||
|
||||
var directory = Path.GetDirectoryName(assemblyPath)!;
|
||||
var context = new ModelLoadContext(directory);
|
||||
try
|
||||
{
|
||||
var assembly = context.LoadFromAssemblyPath(assemblyPath);
|
||||
var type = ResolveFactoryType(assembly, package.Manifest.Type);
|
||||
if (type == null)
|
||||
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
|
||||
|
||||
if (Activator.CreateInstance(type) is not IModelFactory factory)
|
||||
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
|
||||
|
||||
if (factory.ApiVersion != SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致");
|
||||
|
||||
var runtime = factory.Create();
|
||||
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
|
||||
return new Session(context, runtime, modelContext);
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.Unload();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(typeName))
|
||||
{
|
||||
var exact = assembly.GetType(typeName!, throwOnError: false);
|
||||
if (exact != null) return exact;
|
||||
}
|
||||
|
||||
foreach (var type in assembly.GetTypes())
|
||||
{
|
||||
if (type.IsAbstract || type.IsInterface) continue;
|
||||
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed class Session : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
|
||||
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
|
||||
{
|
||||
_context = context;
|
||||
Runtime = runtime;
|
||||
Context = modelContext;
|
||||
}
|
||||
|
||||
public IModelRuntime Runtime { get; }
|
||||
public ModelContext Context { get; }
|
||||
|
||||
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
|
||||
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
|
||||
public sealed class LoadedModel : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
private readonly IModelRuntime _runtime;
|
||||
private bool _disposed;
|
||||
|
||||
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
|
||||
{
|
||||
_context = context;
|
||||
_runtime = runtime;
|
||||
View = view;
|
||||
}
|
||||
|
||||
public Control View { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
|
||||
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
|
||||
try { (View as IDisposable)?.Dispose(); }
|
||||
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
|
||||
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
|
||||
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
|
||||
public sealed class ModelLoadContext : AssemblyLoadContext
|
||||
{
|
||||
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"GC.ModelSdk",
|
||||
"Avalonia",
|
||||
"Avalonia.Base",
|
||||
"Avalonia.Controls",
|
||||
"Avalonia.Desktop",
|
||||
"Avalonia.Skia",
|
||||
"Avalonia.Themes.Fluent",
|
||||
"SkiaSharp",
|
||||
"HarfBuzzSharp"
|
||||
};
|
||||
|
||||
private readonly string _directory;
|
||||
|
||||
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
|
||||
=> _directory = directory;
|
||||
|
||||
protected override Assembly? Load(AssemblyName assemblyName)
|
||||
{
|
||||
var name = assemblyName.Name;
|
||||
if (string.IsNullOrEmpty(name)) return null;
|
||||
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
|
||||
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
if (name is "System" or "netstandard" or "mscorlib") return null;
|
||||
|
||||
var candidate = Path.Combine(_directory, name + ".dll");
|
||||
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动器提供给模型的环境。</summary>
|
||||
public sealed class ModelContext : IModelContext
|
||||
{
|
||||
private readonly Action _requestClose;
|
||||
private readonly Action<double, string?>? _progress;
|
||||
|
||||
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
|
||||
Action<double, string?>? progress)
|
||||
{
|
||||
_progress = progress;
|
||||
ModelId = package.Id;
|
||||
ModelDirectory = package.Directory;
|
||||
DataDirectory = package.DataDirectory;
|
||||
Language = language;
|
||||
MemoryBudgetMb = memoryMb;
|
||||
_requestClose = requestClose;
|
||||
}
|
||||
|
||||
public string ModelId { get; }
|
||||
public string ModelDirectory { get; }
|
||||
public string DataDirectory { get; }
|
||||
public string Language { get; }
|
||||
public int MemoryBudgetMb { get; }
|
||||
|
||||
public void RequestClose() => _requestClose();
|
||||
|
||||
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
|
||||
|
||||
public void Log(string message) => Console.WriteLine(message);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelInstaller
|
||||
{
|
||||
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
|
||||
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
|
||||
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
|
||||
{
|
||||
var target = Path.Combine(modelRoot, model.Id);
|
||||
var staging = target + ".installing";
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
long total = 0;
|
||||
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
|
||||
foreach (var file in files)
|
||||
{
|
||||
try { total += new FileInfo(file).Length; } catch { }
|
||||
}
|
||||
|
||||
long done = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var relative = Path.GetRelativePath(model.Directory, file);
|
||||
// 路径穿越防护:相对路径必须完整落在 staging 目录内
|
||||
var dest = Path.GetFullPath(Path.Combine(staging, relative));
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
|
||||
await using (var src = File.OpenRead(file))
|
||||
await using (var dst = File.Create(dest))
|
||||
{
|
||||
await src.CopyToAsync(dst, 81920, ct);
|
||||
}
|
||||
long length = 0;
|
||||
try { length = new FileInfo(dest).Length; } catch { }
|
||||
done += length;
|
||||
progress?.Report((done, total <= 0 ? done : total));
|
||||
}
|
||||
|
||||
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
var hasBackup = false;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(target))
|
||||
{
|
||||
Directory.Move(target, backup);
|
||||
hasBackup = true;
|
||||
}
|
||||
Directory.Move(staging, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
|
||||
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
|
||||
Directory.Move(backup, target);
|
||||
throw;
|
||||
}
|
||||
if (hasBackup)
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
|
||||
progress?.Report((total, total));
|
||||
return target;
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
|
||||
/// 场景、贴图、界面都由模型自己的程序集负责。
|
||||
/// </summary>
|
||||
public sealed class ModelRepository
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
|
||||
public ModelRepository(AppPaths paths) => _paths = paths;
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public IReadOnlyList<ModelPackage> Scan()
|
||||
{
|
||||
_paths.WaitForDevelopmentModels();
|
||||
var result = new List<ModelPackage>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
|
||||
{
|
||||
result.Add(new ModelPackage
|
||||
{
|
||||
Manifest = manifest,
|
||||
Directory = dir,
|
||||
SizeBytes = ModelScanner.DirectorySize(dir)
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public ModelPackage? Find(string id) => Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public bool Delete(string id)
|
||||
{
|
||||
var package = Find(id);
|
||||
if (package == null) return false;
|
||||
try
|
||||
{
|
||||
Directory.Delete(package.Directory, true);
|
||||
Changed?.Invoke();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"删除模型失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifyChanged() => Changed?.Invoke();
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelScanner
|
||||
{
|
||||
/// <summary>扫描模型库:model/<id>/<id>.json + <id>.model/</summary>
|
||||
public static List<(ModelManifest Manifest, string Dir)> Scan(string modelRoot)
|
||||
{
|
||||
var list = new List<(ModelManifest, string)>();
|
||||
if (!Directory.Exists(modelRoot)) return list;
|
||||
|
||||
foreach (var dir in Directory.GetDirectories(modelRoot))
|
||||
{
|
||||
var folder = Path.GetFileName(dir);
|
||||
if (folder.StartsWith(".")) continue;
|
||||
|
||||
var manifestPath = Path.Combine(dir, folder + ".json");
|
||||
if (!File.Exists(manifestPath))
|
||||
{
|
||||
var candidates = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly);
|
||||
if (candidates.Length == 0) continue;
|
||||
manifestPath = candidates[0];
|
||||
}
|
||||
|
||||
ModelManifest? manifest;
|
||||
try { manifest = Json.Read<ModelManifest>(manifestPath); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"模型清单解析失败 {manifestPath}: {ex.Message}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (manifest == null) continue;
|
||||
if (string.IsNullOrWhiteSpace(manifest.Id)) manifest.Id = folder;
|
||||
list.Add((manifest, dir));
|
||||
}
|
||||
|
||||
list.Sort((a, b) => string.Compare(a.Item1.Id, b.Item1.Id, StringComparison.OrdinalIgnoreCase));
|
||||
return list;
|
||||
}
|
||||
|
||||
public static long DirectorySize(string dir)
|
||||
{
|
||||
if (!Directory.Exists(dir)) return 0;
|
||||
long total = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
try { total += new FileInfo(file).Length; }
|
||||
catch { /* 忽略被占用的文件 */ }
|
||||
}
|
||||
}
|
||||
catch { /* 忽略权限问题 */ }
|
||||
return total;
|
||||
}
|
||||
|
||||
public static string HumanSize(long bytes)
|
||||
{
|
||||
string[] units = { "B", "KB", "MB", "GB" };
|
||||
double value = bytes;
|
||||
var unit = 0;
|
||||
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
|
||||
return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 从链接导入模型源。
|
||||
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。
|
||||
/// </summary>
|
||||
public sealed class ModelSourceClient
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
public ModelSourceClient(AppPaths paths) => _paths = paths;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(source.Url))
|
||||
return new SourceIndex { SourceId = source.Id, Error = "dl.error.emptyUrl" };
|
||||
|
||||
try
|
||||
{
|
||||
var (root, fromCache) = await ResolveRootAsync(source, force, log, ct);
|
||||
var models = new List<RemoteModel>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(Path.Combine(root, "model")))
|
||||
{
|
||||
models.Add(new RemoteModel
|
||||
{
|
||||
Manifest = manifest,
|
||||
Directory = dir,
|
||||
SizeBytes = ModelScanner.DirectorySize(dir),
|
||||
SourceId = source.Id
|
||||
});
|
||||
}
|
||||
|
||||
return new SourceIndex
|
||||
{
|
||||
SourceId = source.Id,
|
||||
Root = root,
|
||||
Models = models,
|
||||
FromCache = fromCache,
|
||||
ResolvedFrom = root
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return new SourceIndex { SourceId = source.Id, Error = "dl.error.canceled" };
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new SourceIndex { SourceId = source.Id, Error = ex.Message };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(string Root, bool FromCache)> ResolveRootAsync(ModelSource source, bool force,
|
||||
IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
var raw = source.Url.Trim();
|
||||
|
||||
// 1) 本地目录(开发模型源最方便)
|
||||
var localPath = raw.StartsWith("file://", StringComparison.OrdinalIgnoreCase)
|
||||
? new Uri(raw).LocalPath
|
||||
: raw;
|
||||
if (Directory.Exists(localPath))
|
||||
{
|
||||
log?.Report("local");
|
||||
return (localPath, true);
|
||||
}
|
||||
|
||||
var cacheDir = Path.Combine(_paths.CacheRoot, "sources", source.Id);
|
||||
if (!force && Directory.Exists(Path.Combine(cacheDir, "model")))
|
||||
{
|
||||
log?.Report("cache");
|
||||
return (cacheDir, true);
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
|
||||
// 2) zip 直链 / 托管平台归档
|
||||
foreach (var url in ArchiveCandidates(raw, source.Branch))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
log?.Report("zip:" + url);
|
||||
await DownloadZipAsync(url, cacheDir, ct);
|
||||
if (Directory.Exists(Path.Combine(cacheDir, "model")))
|
||||
return (cacheDir, false);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
log?.Report("zip-failed:" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// 3) git clone(需要本机安装 git)
|
||||
log?.Report("git");
|
||||
if (await TryGitCloneAsync(raw, cacheDir, source.Branch, ct))
|
||||
return (cacheDir, false);
|
||||
|
||||
throw new InvalidOperationException("dl.error.unreachable");
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ArchiveCandidates(string url, string? branch)
|
||||
{
|
||||
if (url.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
yield return url;
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) yield break;
|
||||
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments.Length < 2) yield break;
|
||||
|
||||
var owner = segments[0];
|
||||
var repo = segments[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? segments[1][..^4]
|
||||
: segments[1];
|
||||
var host = uri.Host.ToLowerInvariant();
|
||||
|
||||
var branches = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(branch)) branches.Add(branch!);
|
||||
else if (host.Contains("gitee")) { branches.Add("master"); branches.Add("main"); }
|
||||
else { branches.Add("main"); branches.Add("master"); }
|
||||
|
||||
foreach (var b in branches)
|
||||
{
|
||||
if (host.Contains("github.com"))
|
||||
yield return $"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{b}";
|
||||
else if (host.Contains("gitlab"))
|
||||
yield return $"https://gitlab.com/{owner}/{repo}/-/archive/{b}/{repo}-{b}.zip";
|
||||
else if (host.Contains("gitee.com"))
|
||||
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
||||
else
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
||||
{
|
||||
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(tmpRoot);
|
||||
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
||||
try
|
||||
{
|
||||
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var input = await response.Content.ReadAsStreamAsync(ct);
|
||||
await using var output = File.Create(zipPath);
|
||||
await input.CopyToAsync(output, 81920, ct);
|
||||
}
|
||||
|
||||
var extractDir = Path.Combine(tmpRoot, "extract");
|
||||
Directory.CreateDirectory(extractDir);
|
||||
ZipSafety.ExtractToDirectory(zipPath, extractDir);
|
||||
|
||||
var root = FindModelRoot(extractDir) ?? extractDir;
|
||||
foreach (var entry in Directory.GetFileSystemEntries(root))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
var dest = Path.Combine(cacheDir, name);
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpRoot)) Directory.Delete(tmpRoot, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindModelRoot(string dir, int depth = 0)
|
||||
{
|
||||
if (Directory.Exists(Path.Combine(dir, "model"))) return dir;
|
||||
if (depth >= 2) return null;
|
||||
foreach (var child in Directory.GetDirectories(dir))
|
||||
{
|
||||
var found = FindModelRoot(child, depth + 1);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<bool> TryGitCloneAsync(string url, string cacheDir, string? branch, CancellationToken ct)
|
||||
{
|
||||
if (cacheDir.Length > 0 && Directory.Exists(cacheDir))
|
||||
{
|
||||
foreach (var f in Directory.GetFileSystemEntries(cacheDir))
|
||||
{
|
||||
if (Directory.Exists(f)) Directory.Delete(f, true);
|
||||
else File.Delete(f);
|
||||
}
|
||||
}
|
||||
|
||||
// 只拉取 model/ 目录:整仓 clone 会把 .git / src / dist 一起拖下来
|
||||
// (实测 700MB+),既慢又容易超时,表现就是「读不到模型源」。
|
||||
// 先浅克隆到临时目录,再用 sparse-checkout 只检出 model/。
|
||||
var tmpDir = cacheDir + ".tmp";
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true);
|
||||
|
||||
// 1) 初始化 + 加远程(比 clone 更快,避免先拉全量)
|
||||
var initArgs = new List<string> { "init", "--quiet", tmpDir };
|
||||
if (!await RunGitAsync(initArgs, ct)) return false;
|
||||
|
||||
var remoteArgs = new List<string> { "-C", tmpDir, "remote", "add", "origin", url };
|
||||
if (!await RunGitAsync(remoteArgs, ct)) return false;
|
||||
|
||||
// 2) 只允许 model 目录参与检出
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "config", "core.sparseCheckout", "true" }, ct);
|
||||
var sparseFile = Path.Combine(tmpDir, ".git", "info", "sparse-checkout");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sparseFile)!);
|
||||
File.WriteAllText(sparseFile, "model/\n");
|
||||
|
||||
// 3) 浅拉指定分支
|
||||
var branchName = string.IsNullOrWhiteSpace(branch) ? "main" : branch!;
|
||||
var fetchArgs = new List<string>
|
||||
{
|
||||
"-C", tmpDir, "fetch", "--depth", "1", "--filter=blob:none", "origin", branchName
|
||||
};
|
||||
if (!await RunGitAsync(fetchArgs, ct)) return false;
|
||||
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "checkout", "FETCH_HEAD" }, ct);
|
||||
|
||||
// 4) 把 model/ 移到缓存根,与原有目录结构一致
|
||||
var modelDir = Path.Combine(tmpDir, "model");
|
||||
if (!Directory.Exists(modelDir))
|
||||
{
|
||||
Console.Error.WriteLine("git sparse-checkout 后未找到 model/ 目录");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
Directory.Move(modelDir, Path.Combine(cacheDir, "model"));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 拉取异常: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>安静地跑一条 git 命令,返回是否成功。</summary>
|
||||
private static async Task<bool> RunGitAsync(List<string> args, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("git")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
foreach (var a in args) psi.ArgumentList.Add(a);
|
||||
|
||||
using var process = Process.Start(psi);
|
||||
if (process == null) return false;
|
||||
var errTask = process.StandardError.ReadToEndAsync(ct);
|
||||
await process.WaitForExitAsync(ct);
|
||||
var err = await errTask;
|
||||
if (process.ExitCode != 0)
|
||||
Console.Error.WriteLine($"git {string.Join(' ', args)} 失败: {err.Trim()}");
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 执行失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// GitCode/Gitee v5 releases API 的一条 Release(字段做宽松解析,兼容多种返回格式)。
|
||||
/// </summary>
|
||||
public sealed class ReleaseInfo
|
||||
{
|
||||
public string TagName { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public bool Draft { get; set; }
|
||||
public bool Prerelease { get; set; }
|
||||
public string? PublishedAt { get; set; }
|
||||
public List<ReleaseAsset> Assets { get; set; } = new();
|
||||
|
||||
/// <summary>从 tag_name / name 里抽出的版本号(去掉前缀 v、GC- 等)。</summary>
|
||||
public string Version => NormalizeVersion(TagName, Name);
|
||||
|
||||
private static readonly string[] VersionPrefixes =
|
||||
{ "v", "V", "GC-", "gc-", "release-", "Release-" };
|
||||
|
||||
private static readonly string[] PrereleaseTags =
|
||||
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
|
||||
|
||||
public static string NormalizeVersion(string tag, string name)
|
||||
{
|
||||
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
|
||||
if (string.IsNullOrWhiteSpace(raw)) return "";
|
||||
raw = raw!.Trim();
|
||||
// "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
|
||||
foreach (var prefix in VersionPrefixes)
|
||||
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
|
||||
// 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
|
||||
// 用「后缀是否常见预发布标签」区分,避免把 "-Win" 误当成预发布。
|
||||
var dash = raw.IndexOf('-');
|
||||
if (dash > 0 && System.Version.TryParse(raw[..dash], out _))
|
||||
{
|
||||
var tail = raw[(dash + 1)..].ToLowerInvariant();
|
||||
var isPrerelease = Array.Exists(PrereleaseTags, p => tail.StartsWith(p, StringComparison.Ordinal));
|
||||
if (!isPrerelease) raw = raw[..dash];
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ReleaseAsset
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string? BrowserDownloadUrl { get; set; }
|
||||
public string? DownloadUrl { get; set; }
|
||||
public long Size { get; set; }
|
||||
/// <summary>附件类型:GitCode 用 "source" 表示自动生成的源码压缩包,需跳过。</summary>
|
||||
public string? Type { get; set; }
|
||||
|
||||
private string? _sha256;
|
||||
/// <summary>
|
||||
/// 校验值。真实 Release 的 digest 形如 "sha256:899fc1...",
|
||||
/// 这里统一剥掉算法前缀,只留 hex,便于与 SHA256.HashData 结果比较。
|
||||
/// </summary>
|
||||
public string? Sha256
|
||||
{
|
||||
get => _sha256;
|
||||
set
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) { _sha256 = null; return; }
|
||||
var v = value!.Trim();
|
||||
var colon = v.IndexOf(':');
|
||||
if (colon > 0 && v[..colon].Equals("sha256", StringComparison.OrdinalIgnoreCase))
|
||||
v = v[(colon + 1)..];
|
||||
_sha256 = v.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public string Url => BrowserDownloadUrl ?? DownloadUrl ?? "";
|
||||
|
||||
/// <summary>单文件发布包(.exe 等)不能走解压,需要直接作为 payload 内容。</summary>
|
||||
public bool IsSingleFile
|
||||
{
|
||||
get
|
||||
{
|
||||
var n = Name.ToLowerInvariant();
|
||||
// macOS 的 .app 以 zip 分发(.app 或 .app.zip),内含 .app 目录,需要解压
|
||||
if (n.EndsWith(".app", StringComparison.Ordinal) ||
|
||||
n.EndsWith(".app.zip", StringComparison.Ordinal)) return false;
|
||||
return !n.EndsWith(".zip", StringComparison.Ordinal) &&
|
||||
!n.EndsWith(".tar.gz", StringComparison.Ordinal) &&
|
||||
!n.EndsWith(".tgz", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>解析附件名里的系统/架构,映射到 .NET RID。</summary>
|
||||
/// <returns>如 win-x64 / win-arm64 / osx-arm64;无法识别返回 null。</returns>
|
||||
public string? RidFromName(string fullName)
|
||||
{
|
||||
var n = fullName ?? "";
|
||||
// 统一大小写与分隔符后再判断,兼容 "GC-1.0.1-Win-amd64.zip"
|
||||
var lower = n.ToLowerInvariant().Replace('_', '-');
|
||||
|
||||
bool win = lower.Contains("win") || lower.Contains("windows");
|
||||
bool mac = lower.Contains("osx") || lower.Contains("mac") || lower.Contains("darwin");
|
||||
bool linux = lower.Contains("linux");
|
||||
if (!win && !mac && !linux) return null;
|
||||
|
||||
bool arm64 = lower.Contains("arm64") || lower.Contains("aarch64") || lower.Contains("win-arm");
|
||||
// x86_64 / x86-64 / amd64 / x64 都是 64 位;只有裸 "x86"/"win-x86" 才是 32 位
|
||||
bool is64 = lower.Contains("x64") || lower.Contains("amd64") ||
|
||||
lower.Contains("x86-64") || lower.Contains("x86_64");
|
||||
bool x86 = !is64 && !arm64 &&
|
||||
(lower.Contains("x86") || lower.Contains("win32") || lower.Contains("i386"));
|
||||
// 其余(未显式标注 32 位)一律按 64 位处理,覆盖 "GC-1.0.1-Windows.zip" 这类简写
|
||||
var arch = arm64 ? "arm64" : x86 ? "x86" : "x64";
|
||||
|
||||
if (win) return "win-" + arch;
|
||||
if (mac) return "osx-" + arch;
|
||||
return "linux-" + arch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public sealed class SettingsService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
|
||||
public AppSettings Current { get; private set; } = new();
|
||||
public event Action? Changed;
|
||||
|
||||
public SettingsService(AppPaths paths) => _paths = paths;
|
||||
|
||||
public void Load()
|
||||
{
|
||||
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
|
||||
SeedDefaultSource();
|
||||
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。
|
||||
/// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条,
|
||||
/// 老配置里的自定义源会被清理掉。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
var rebuilt = new List<ModelSource>();
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
// 保留用户对「启用/停用」的选择,其余字段以内置定义为准
|
||||
var old = Current.Sources.FirstOrDefault(s =>
|
||||
SourcePreset.Detect(s.Url).Id == preset.Id);
|
||||
rebuilt.Add(new ModelSource
|
||||
{
|
||||
Id = preset.Id,
|
||||
Name = preset.Name,
|
||||
Url = preset.HomeUrl,
|
||||
Enabled = old?.Enabled ?? true,
|
||||
BuiltIn = true
|
||||
});
|
||||
}
|
||||
|
||||
var changed = Current.Sources.Count != rebuilt.Count ||
|
||||
Current.Sources.Any(s => !s.BuiltIn);
|
||||
Current.Sources = rebuilt;
|
||||
if (changed) Save();
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
Json.Write(_paths.SettingsFile, Current);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply(Action<AppSettings> mutate)
|
||||
{
|
||||
mutate(Current);
|
||||
Save();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Notify()
|
||||
{
|
||||
Save();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Shell
|
||||
{
|
||||
public static void OpenFolder(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
|
||||
StartWith(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>用系统默认浏览器打开一个 URL。</summary>
|
||||
public static void OpenUrl(string url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return;
|
||||
try
|
||||
{
|
||||
StartWith(url);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"打开链接失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void StartWith(string argument)
|
||||
{
|
||||
var info = new ProcessStartInfo
|
||||
{
|
||||
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
|
||||
: OperatingSystem.IsMacOS() ? "open"
|
||||
: "xdg-open",
|
||||
UseShellExecute = false
|
||||
};
|
||||
info.ArgumentList.Add(argument);
|
||||
Process.Start(info);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内置下载源。只允许这两个,不再支持用户自定义源。
|
||||
///
|
||||
/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型),
|
||||
/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。
|
||||
/// </summary>
|
||||
public sealed class SourcePreset
|
||||
{
|
||||
public string Id { get; init; } = "";
|
||||
public string Name { get; init; } = "";
|
||||
/// <summary>仓库主页(用于展示与打开)。</summary>
|
||||
public string HomeUrl { get; init; } = "";
|
||||
/// <summary>API 根地址(Gitea: /api/v1,GitCode: /api/v5)。</summary>
|
||||
public string ApiBase { get; init; } = "";
|
||||
/// <summary>原始文件下载前缀(用于拼 raw 地址)。</summary>
|
||||
public string RawBase { get; init; } = "";
|
||||
/// <summary>后端类型:gitea / gitcode。</summary>
|
||||
public string Kind { get; init; } = "";
|
||||
public string Owner { get; init; } = "";
|
||||
public string Repo { get; init; } = "";
|
||||
public string Branch { get; init; } = "main";
|
||||
/// <summary>raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。</summary>
|
||||
public string RawStyle { get; init; } = "branch";
|
||||
|
||||
public string Repository => HomeUrl;
|
||||
|
||||
/// <summary>拼 raw 文件下载地址(两个平台的 URL 结构不同)。</summary>
|
||||
public string RawUrl(string path) => RawStyle == "plain"
|
||||
? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}"
|
||||
: $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}";
|
||||
|
||||
public static readonly SourcePreset Xhmcl = new()
|
||||
{
|
||||
Id = "xhmcl",
|
||||
Name = "Xhmcl",
|
||||
HomeUrl = "https://git.xhmcl.com/Morris/GC",
|
||||
ApiBase = "https://git.xhmcl.com/api/v1",
|
||||
RawBase = "https://git.xhmcl.com",
|
||||
Kind = "gitea",
|
||||
RawStyle = "branch",
|
||||
Owner = "Morris",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset GitCode = new()
|
||||
{
|
||||
Id = "gitcode",
|
||||
Name = "GitCode",
|
||||
HomeUrl = "https://gitcode.com/2509_92447106/GC",
|
||||
ApiBase = "https://api.gitcode.com/api/v5",
|
||||
RawBase = "https://gitcode.com",
|
||||
Kind = "gitcode",
|
||||
RawStyle = "plain",
|
||||
Owner = "2509_92447106",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset[] All = { Xhmcl, GitCode };
|
||||
|
||||
public static SourcePreset? Find(string? id) =>
|
||||
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。</summary>
|
||||
public static SourcePreset Detect(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return GitCode;
|
||||
var u = url!.ToLowerInvariant();
|
||||
if (u.Contains("xhmcl.com")) return Xhmcl;
|
||||
return GitCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
||||
///
|
||||
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
|
||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||
/// 避免每次点下载都重新测速。
|
||||
/// </summary>
|
||||
public sealed class SourceSelector
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
|
||||
return c;
|
||||
}
|
||||
|
||||
private readonly object _lock = new();
|
||||
private SourcePreset? _cached;
|
||||
private DateTime _cachedAt = DateTime.MinValue;
|
||||
private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3);
|
||||
|
||||
/// <summary>最近一次选中的源(未探测时为空)。</summary>
|
||||
public SourcePreset? Current { get { lock (_lock) return _cached; } }
|
||||
|
||||
/// <summary>每个源的探测耗时(毫秒),供界面展示。</summary>
|
||||
public IReadOnlyDictionary<string, long> LastLatency { get; private set; } =
|
||||
new Dictionary<string, long>();
|
||||
|
||||
/// <summary>
|
||||
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
||||
/// 两个都失败时返回 GitCode(默认源)。
|
||||
/// </summary>
|
||||
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl)
|
||||
return _cached;
|
||||
}
|
||||
|
||||
var probes = SourcePreset.All.Select(async p =>
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var ok = await ProbeAsync(p, ct);
|
||||
sw.Stop();
|
||||
return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds);
|
||||
});
|
||||
|
||||
var results = await Task.WhenAll(probes);
|
||||
|
||||
var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms);
|
||||
LastLatency = latencies;
|
||||
|
||||
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
||||
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_cached = chosen;
|
||||
_cachedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
|
||||
+ $" → 选择 {chosen.Name}");
|
||||
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 探测:能拿到合法 JSON 才算可用。
|
||||
/// 注意两个平台取文件的方式不同:
|
||||
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
|
||||
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
|
||||
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
|
||||
/// </summary>
|
||||
private static async Task<bool> ProbeAsync(SourcePreset preset, CancellationToken ct)
|
||||
{
|
||||
if (preset.Kind == "gitcode")
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, api);
|
||||
req.Headers.Accept.ParseAdd("application/json");
|
||||
using var resp = await Http.SendAsync(req, cts.Token);
|
||||
if (!resp.IsSuccessStatusCode) return false;
|
||||
var text = await resp.Content.ReadAsStringAsync(cts.Token);
|
||||
return text.TrimStart().StartsWith('{');
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") };
|
||||
|
||||
foreach (var url in urls)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var text = await Http.GetStringAsync(url, cts.Token);
|
||||
if (text.TrimStart().StartsWith('{')) return true;
|
||||
}
|
||||
catch { /* 换下一个地址 */ }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>为指定源创建对应的 remote 实现。</summary>
|
||||
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
|
||||
{
|
||||
"gitea" => new GiteaRemote(preset),
|
||||
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
|
||||
public sealed class RepoVersion
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
public string Generated { get; set; } = "";
|
||||
public string Repository { get; set; } = "";
|
||||
public string Branch { get; set; } = "main";
|
||||
public string ModelDir { get; set; } = "model";
|
||||
public RepoLauncher Launcher { get; set; } = new();
|
||||
public List<RepoModel> Models { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class RepoLauncher
|
||||
{
|
||||
public string Version { get; set; } = "1.0.0";
|
||||
/// <summary>启动器源码指纹(自动算,仅展示,不触发升级)。</summary>
|
||||
public string Revision { get; set; } = "";
|
||||
public Dictionary<string, RepoPackage> Packages { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>某个平台的启动器发布包;url 优先,否则用 path 去仓库里解析下载地址。</summary>
|
||||
public sealed class RepoPackage
|
||||
{
|
||||
public string? Url { get; set; }
|
||||
public string? Path { get; set; }
|
||||
public string? Sha256 { get; set; }
|
||||
public long Size { get; set; }
|
||||
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
|
||||
public string? AssetName { get; set; }
|
||||
}
|
||||
|
||||
public sealed class RepoModel
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
|
||||
public string Dir { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>远端目录树里的一个条目。</summary>
|
||||
public sealed class RepoEntry
|
||||
{
|
||||
public string Name { get; init; } = "";
|
||||
/// <summary>仓库内完整路径。</summary>
|
||||
public string Path { get; init; } = "";
|
||||
/// <summary>相对所请求根目录的路径,统一用 / 分隔。</summary>
|
||||
public string RelativePath { get; init; } = "";
|
||||
public bool IsDirectory { get; init; }
|
||||
public string? DownloadUrl { get; init; }
|
||||
public long Size { get; init; }
|
||||
public string? Sha { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 远端源抽象:gitcode 是默认实现,本地目录实现用于离线教学与自动化测试。
|
||||
/// </summary>
|
||||
public interface IModelRemote
|
||||
{
|
||||
string DisplayName { get; }
|
||||
|
||||
/// <summary>源标识(xhmcl / gitcode / local),用于判断当前是哪个源。</summary>
|
||||
string SourceId => SourcePreset.Detect(DisplayName).Id;
|
||||
Task<RepoVersion?> GetVersionAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
|
||||
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
|
||||
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class UpdateProgress
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Message { get; init; } = "";
|
||||
public string? Detail { get; init; }
|
||||
}
|
||||
|
||||
public enum UpdateOutcome
|
||||
{
|
||||
NoChange,
|
||||
Applied,
|
||||
Partial,
|
||||
Unavailable,
|
||||
Disabled
|
||||
}
|
||||
|
||||
public sealed class UpdateResult
|
||||
{
|
||||
public UpdateOutcome Outcome { get; init; }
|
||||
public string Message { get; init; } = "";
|
||||
public int UpdatedModels { get; init; }
|
||||
public List<string> ModelNames { get; init; } = new();
|
||||
public string? LauncherMessage { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_remote = remote;
|
||||
}
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||
|
||||
private static string? _versionOverride;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
||||
|
||||
// 用**本程序集**的版本,而不是 GetEntryAssembly()。
|
||||
// EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序,
|
||||
// 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。
|
||||
var asm = typeof(UpdateService).Assembly;
|
||||
var v = asm.GetName().Version;
|
||||
if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0))
|
||||
{
|
||||
// 兜底:读 InformationalVersion(Directory.Build.props 里的 <Version>)
|
||||
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
if (!string.IsNullOrWhiteSpace(info))
|
||||
{
|
||||
var core = info!.Split('+')[0].Trim();
|
||||
if (Version.TryParse(core, out var iv))
|
||||
v = iv;
|
||||
}
|
||||
}
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>测试 / 自检时临时指定版本号。</summary>
|
||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var arch = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
||||
return RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
||||
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
||||
/// </summary>
|
||||
public static IModelRemote CreateRemote(AppSettings settings)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
return SourceSelector.CreateRemote(SourcePreset.Detect(settings.UpdateRepository));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步版本:先探测 Xhmcl / GitCode 两个源,取最快的那个。
|
||||
/// 启动更新、下载页、检查更新统一走这里,保证「用同一个源、同一种下载方式」。
|
||||
/// </summary>
|
||||
public static async Task<IModelRemote> CreateRemoteAsync(AppSettings settings,
|
||||
SourceSelector selector, bool forceProbe = false, CancellationToken ct = default)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
|
||||
var preset = await selector.PickFastestAsync(forceProbe, ct);
|
||||
return SourceSelector.CreateRemote(preset);
|
||||
}
|
||||
|
||||
public async Task<UpdateResult> RunAsync(bool force,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
|
||||
{
|
||||
// 开发态的 model/ 里有源码与工程文件,模型自动替换会破坏源码目录,
|
||||
// 因此开发态只做「启动器版本检查」(下载到 .GC/update 暂存,可验证链路),
|
||||
// 跳过模型替换。要用正式流程验证请跑 ./build.sh update-test。
|
||||
var devMode = _paths.IsDevelopment &&
|
||||
Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1";
|
||||
|
||||
if (!force && !_settings.Current.AutoUpdateOnStartup)
|
||||
return new UpdateResult { Outcome = UpdateOutcome.Disabled, Message = L.I["update.disabled"] };
|
||||
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.02,
|
||||
Message = L.I["update.checking"],
|
||||
Detail = _remote.DisplayName
|
||||
});
|
||||
|
||||
RepoVersion? remote;
|
||||
try
|
||||
{
|
||||
remote = await _remote.GetVersionAsync(ct);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = L.I["update.offline"],
|
||||
Error = ex.Message
|
||||
};
|
||||
}
|
||||
|
||||
if (remote == null)
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = L.I["update.noManifest"]
|
||||
};
|
||||
|
||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||
_settings.Save();
|
||||
|
||||
// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,
|
||||
// 这里只做「模型同步到最新版」。
|
||||
string? launcherMessage = null;
|
||||
|
||||
// ---- 同步所有模型到最新版 ----
|
||||
// 开发态跳过:仓库 model/ 里有源码,整体替换会破坏工程目录。
|
||||
var needed = devMode
|
||||
? new List<RepoModel>()
|
||||
: remote.Models.Where(NeedsModel).ToList();
|
||||
var updated = new List<string>();
|
||||
var errors = new List<string>();
|
||||
|
||||
for (var i = 0; i < needed.Count; i++)
|
||||
{
|
||||
var model = needed[i];
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * i / Math.Max(1, needed.Count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = model.Version
|
||||
});
|
||||
try
|
||||
{
|
||||
await InstallModelAsync(model, progress, i, needed.Count, ct);
|
||||
_settings.Current.InstalledModelVersions[model.Id] = model.Version;
|
||||
_settings.Save();
|
||||
updated.Add(model.Id);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
errors.Add($"{model.Id}: {ex.Message}");
|
||||
Console.Error.WriteLine($"模型更新失败 {model.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgress { Value = 1, Message = L.I["update.done"] });
|
||||
|
||||
var outcome = errors.Count > 0
|
||||
? UpdateOutcome.Partial
|
||||
: (updated.Count > 0 || launcherMessage != null)
|
||||
? UpdateOutcome.Applied
|
||||
: UpdateOutcome.NoChange;
|
||||
|
||||
var message = updated.Count > 0
|
||||
? L.I.F("update.applied", updated.Count)
|
||||
: launcherMessage != null
|
||||
? L.I["update.modelsLatest"]
|
||||
: devMode
|
||||
? "开发态:已检查启动器,模型替换已跳过(保护仓库源码)"
|
||||
: L.I["update.noChange"];
|
||||
if (errors.Count > 0) message += L.I.F("update.partial", errors.Count);
|
||||
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = outcome,
|
||||
Message = message,
|
||||
UpdatedModels = updated.Count,
|
||||
ModelNames = updated,
|
||||
LauncherMessage = launcherMessage,
|
||||
Error = errors.Count > 0 ? string.Join("; ", errors) : null
|
||||
};
|
||||
}
|
||||
|
||||
private bool NeedsModel(RepoModel model)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(model.Id) || string.IsNullOrWhiteSpace(model.Version)) return false;
|
||||
var dir = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
if (!Directory.Exists(dir)) return true;
|
||||
if (!File.Exists(Path.Combine(dir, model.Id + ".json"))) return true;
|
||||
return !_settings.Current.InstalledModelVersions.TryGetValue(model.Id, out var local) ||
|
||||
!string.Equals(local, model.Version, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>只下载模型清单与模型数据目录,源码 / 文档不进运行目录。</summary>
|
||||
private static bool IsPayload(string id, string relative)
|
||||
{
|
||||
var rel = relative.Replace('\\', '/');
|
||||
// 拒绝任何形式的父目录穿越与绝对路径
|
||||
if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false;
|
||||
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private async Task InstallModelAsync(RepoModel model, IProgress<UpdateProgress>? progress,
|
||||
int index, int count, CancellationToken ct)
|
||||
{
|
||||
var rootPath = string.IsNullOrWhiteSpace(model.Dir) ? "model/" + model.Id : model.Dir;
|
||||
var entries = await _remote.ListTreeAsync(rootPath, ct);
|
||||
var files = entries.Where(e => !e.IsDirectory && IsPayload(model.Id, e.RelativePath)).ToList();
|
||||
|
||||
if (!files.Any(e => e.RelativePath.Equals(model.Id + ".json", StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"远端缺少模型清单 {model.Id}.json");
|
||||
if (!files.Any(e => e.RelativePath.StartsWith(model.Id + ".model/", StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"远端缺少模型数据 {model.Id}.model/");
|
||||
|
||||
var staging = Path.Combine(_paths.CacheRoot, "models", model.Id + "-" + Safe(model.Version));
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
try
|
||||
{
|
||||
var total = files.Sum(f => Math.Max(1L, f.Size));
|
||||
// 并行下载:模型包通常有几十个文件,串行下载会明显拖慢启动。
|
||||
// 并发上限 6,避免被服务端限流;进度用原子计数汇总。
|
||||
long done = 0;
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
using var gate = new SemaphoreSlim(6);
|
||||
|
||||
var tasks = files.Select(async entry =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var bytes = await _remote.DownloadAsync(entry, ct);
|
||||
|
||||
// 路径穿越防护
|
||||
var dest = Path.GetFullPath(Path.Combine(staging,
|
||||
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
|
||||
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
await File.WriteAllBytesAsync(dest, bytes, ct);
|
||||
|
||||
var now = Interlocked.Add(ref done, bytes.Length);
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)now / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = entry.RelativePath
|
||||
});
|
||||
}
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
Directory.CreateDirectory(_paths.ModelRoot);
|
||||
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
// 双保险:任何情况下都不允许把含 src/ 源码的模型目录整体换掉
|
||||
if (Directory.Exists(Path.Combine(target, "src")))
|
||||
throw new InvalidOperationException($"目标目录含模型源码 src/,拒绝覆盖: {target}");
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
if (Directory.Exists(target)) Directory.Move(target, backup);
|
||||
try
|
||||
{
|
||||
Directory.Move(staging, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (Directory.Exists(backup) && !Directory.Exists(target)) Directory.Move(backup, target);
|
||||
throw;
|
||||
}
|
||||
if (Directory.Exists(backup))
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
||||
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
||||
/// </summary>
|
||||
public static class VersionUtil
|
||||
{
|
||||
/// <summary>把 tag 规整成 "1.0.6" 这样的纯数字版本。</summary>
|
||||
public static string Normalize(string? tag)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tag)) return "";
|
||||
var s = tag!.Trim();
|
||||
|
||||
// 去掉前缀:v / V / GC- / release-
|
||||
if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
||||
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
||||
s = s.TrimStart('v', 'V');
|
||||
|
||||
// 只保留开头的 数字与点
|
||||
var end = 0;
|
||||
while (end < s.Length && (char.IsDigit(s[end]) || s[end] == '.')) end++;
|
||||
s = s[..end].Trim('.');
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>解析成 Version;无法解析时返回 0.0。</summary>
|
||||
public static Version Parse(string? tag)
|
||||
{
|
||||
var n = Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(n)) return new Version(0, 0);
|
||||
return Version.TryParse(n, out var v) ? v : new Version(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>比较两个版本号,a>b 返回正、a<b 返回负、相等返回 0。</summary>
|
||||
public static int Compare(string? a, string? b) => Parse(a).CompareTo(Parse(b));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符),
|
||||
/// 并在解压前逐条校验目标路径完整落在目标目录内。
|
||||
/// </summary>
|
||||
public static class ZipSafety
|
||||
{
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
var destFull = Path.GetFullPath(destination)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
|
||||
using (var archive = ZipFile.OpenRead(zipPath))
|
||||
{
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var name = entry.FullName.Replace('\\', '/');
|
||||
if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) ||
|
||||
(name.Length >= 2 && name[1] == ':'))
|
||||
throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}");
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
}
|
||||
}
|
||||
|
||||
// 校验通过后交给框架解压(保留 overwrite 语义)
|
||||
ZipFile.ExtractToDirectory(zipPath, destination, true);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user