feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线
前端
- 移除全部 Avalonia 依赖,模型渲染与界面统一改用 Flutter
- 新增用户页:登录/注册(SHA-512 + 盐)、签到积分(30 天一循环)、
主题色积分购买、二选一随机、今日人品
- 新增百宝箱页、模型内嵌渲染页、自绘标题栏(最小化/最大化/关闭)
- 下载页显示模型下载进度条,下载源读取加速
- 关于页新增「重新下载启动器」并在下载后做 sha256 完整性校验
- 修复浅色主题下标题栏不跟随主题色、无法连接后端等问题
后端
- 新增 UserService:.GC/user/<用户名>.yaml 存用户名/积分/SHA-512 口令,
登录返回 session token,本地 .GC/user/user.yaml 保存登录态
- 新增 /api/user/{register,login,me,signin,theme} 接口
- 去掉 Avalonia 窗口宿主,后端只提供 HTTP API
下载源
- 新增 GitHub 镜像源(Morris-morris-cloud/GC),与 Xhmcl 并发测速
- 单源探测超时收紧到 2 秒,取最快且可用的源;GitHub 复用 GiteaRemote
(contents 带 ref、releases 带 per_page=100)
构建与 CI
- macOS 上默认只出 macOS 包,Windows 交给原生 Windows 构建
- 修复 Windows 交叉编译中 flutter-cpp-client-wrapper 双层目录嵌套
- 新增 GitHub Actions:
· nightly-prerelease:每天 21:00 编译三平台,发布 nightly 预发布
· build-bot:Issue/PR 评论 @build-bot build <mac|win-amd|win-arm|all>,
发布 ip-prerelease 预发布
· pr-review:检查能否编译、静态分析、合并冲突、是否落后 main
- 忽略 79MB 课件产物等高线.html 与工具链临时备份
This commit is contained in:
1 parent
b9cb56cb8b
commit
ea1fa6b6d1
134 files changed
+4309
-16614
No files matched your search
@@ -13,8 +13,6 @@ public sealed class AppServices
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public IUpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
@@ -34,7 +32,6 @@ public sealed class AppServices
|
||||
Sources = DownloadModule.Sources;
|
||||
Downloads = DownloadModule.Downloads;
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
|
||||
@@ -51,7 +51,8 @@ public static class ContributorsService
|
||||
private const int MaxShown = 8;
|
||||
private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(10);
|
||||
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
// 使用共享 HttpClient
|
||||
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
|
||||
|
||||
/// <summary>同一作者的多个 git 身份 -> 统一展示名。</summary>
|
||||
private static readonly Dictionary<string, string> Aliases = new(StringComparer.OrdinalIgnoreCase)
|
||||
@@ -61,6 +62,9 @@ public static class ContributorsService
|
||||
["2509_92447106"] = "Morris",
|
||||
["chenmoyuan1214@qq.com"] = "Morris",
|
||||
["morris@xhmcl.com"] = "Morris",
|
||||
// 远影科技是 Morris 的另一个 git 身份(同一邮箱),归并到 Morris
|
||||
["远影科技"] = "Morris",
|
||||
["yuanying@yuanying.tech"] = "Morris",
|
||||
// 早期提交用的是 xhgit 这个账号,展示名统一成 itxiaohui
|
||||
["xhgit"] = "itxiaohui",
|
||||
["itxiaohui"] = "itxiaohui",
|
||||
@@ -75,14 +79,6 @@ public static class ContributorsService
|
||||
private static readonly object Gate = new();
|
||||
private static (DateTimeOffset At, string Key, List<Contributor> Items)? _cache;
|
||||
|
||||
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>按仓库地址推导接口:Xhmcl(Gitea) 与 GitCode 结构不同。</summary>
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
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 services.LauncherUpdates.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 = services.LauncherUpdates.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,6 @@ 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;
|
||||
|
||||
@@ -75,8 +72,10 @@ public sealed class L : INotifyPropertyChanged
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
|
||||
using var stream = AssetLoader.Open(uri);
|
||||
// 界面已迁到 Flutter,这里不能再依赖 Avalonia 的 avares:// 资源加载
|
||||
var asm = typeof(L).Assembly;
|
||||
using var stream = asm.GetManifestResourceStream($"GC.Core.Assets.i18n.{code}.json");
|
||||
if (stream == null) return null;
|
||||
using var reader = new StreamReader(stream);
|
||||
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
|
||||
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
@@ -131,13 +130,3 @@ public sealed class LocalizedString : INotifyPropertyChanged
|
||||
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) };
|
||||
}
|
||||
@@ -1,300 +0,0 @@
|
||||
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 declaredApi = package.Manifest.ApiVersion;
|
||||
if (declaredApi < 1)
|
||||
throw new InvalidOperationException($"模型清单的 apiVersion 非法: {declaredApi}");
|
||||
|
||||
if (declaredApi > SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型需要更新的启动器(模型契约 v{declaredApi},当前支持 v{SupportedApiVersion})。" +
|
||||
"请先更新启动器,或让模型作者发布兼容版本。");
|
||||
|
||||
var minApp = package.Manifest.MinAppVersion;
|
||||
if (!string.IsNullOrWhiteSpace(minApp) &&
|
||||
CompareVersions(LauncherRuntimeInfo.CurrentLauncherVersion, minApp!) < 0)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型要求启动器 ≥ v{minApp},当前为 v{LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
|
||||
// ---- 完整性:dll 会被直接执行,加载前必须确认它没被改过 ----------------
|
||||
var integrity = ModelIntegrity.VerifyForLoad(package.Directory, package.Id);
|
||||
if (!integrity.Ok)
|
||||
{
|
||||
var message = $"模型完整性校验失败({package.Id}):{integrity.Message}。" +
|
||||
"请删除该模型目录让启动器重新下载。";
|
||||
if (Environment.GetEnvironmentVariable("GC_ALLOW_TAMPERED_MODELS") == "1")
|
||||
Console.Error.WriteLine("[warn] " + message + "(已按 GC_ALLOW_TAMPERED_MODELS 放行)");
|
||||
else
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
else if (!integrity.Present && Environment.GetEnvironmentVariable("GC_STRICT_MODELS") == "1")
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"模型缺少完整性记录({package.Id}),严格模式下拒绝加载");
|
||||
}
|
||||
|
||||
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(
|
||||
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{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;
|
||||
}
|
||||
|
||||
/// <summary>比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。</summary>
|
||||
private static int CompareVersions(string left, string right)
|
||||
{
|
||||
static int[] Parts(string value)
|
||||
{
|
||||
var text = value.Trim().TrimStart('v', 'V');
|
||||
var pieces = text.Split('.');
|
||||
var numbers = new int[Math.Max(4, pieces.Length)];
|
||||
for (var i = 0; i < pieces.Length; i++)
|
||||
{
|
||||
var digits = new string(Array.FindAll(pieces[i].ToCharArray(), char.IsDigit));
|
||||
if (digits.Length > 6) digits = digits[..6];
|
||||
numbers[i] = int.TryParse(digits, out var n) ? n : 0;
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
var a = Parts(left);
|
||||
var b = Parts(right);
|
||||
for (var i = 0; i < Math.Max(a.Length, b.Length); i++)
|
||||
{
|
||||
var x = i < a.Length ? a[i] : 0;
|
||||
var y = i < b.Length ? b[i] : 0;
|
||||
if (x != y) return x < y ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
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,47 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 共享 HttpClient 工厂:统一管理连接池,避免每个类创建独立的 HttpClient 实例。
|
||||
///
|
||||
/// .NET Core 3.1+ 的 HttpClientHandler 内部使用连接池,但每个 HttpClient 实例仍会创建
|
||||
/// 独立的 Socket 连接池。多个静态 HttpClient 实例(尤其是不同超时配置)会导致端口耗尽
|
||||
/// 或连接无法及时释放。通过单一实例 + 共享 Handler 解决此问题。
|
||||
///
|
||||
/// 注意:不同场景对超时要求差异较大(探测 6s、下载 5min),通过构造参数传递超时,
|
||||
/// 但底层 Handler 共享,避免重复创建 Socket。
|
||||
/// </summary>
|
||||
public static class SharedHttpClientFactory
|
||||
{
|
||||
/// <summary>默认 HTTP 客户端(短超时,用于探测和快速请求)。</summary>
|
||||
private static readonly HttpClient DefaultClient = CreateClient(TimeSpan.FromSeconds(20));
|
||||
|
||||
/// <summary>长超时 HTTP 客户端(用于大文件下载)。</summary>
|
||||
private static readonly HttpClient LongTimeoutClient = CreateClient(TimeSpan.FromMinutes(5));
|
||||
|
||||
private static HttpClient CreateClient(TimeSpan timeout)
|
||||
{
|
||||
var handler = new HttpClientHandler
|
||||
{
|
||||
AutomaticDecompression = DecompressionMethods.GZip |
|
||||
DecompressionMethods.Deflate,
|
||||
// 限制最大重定向次数,防止重定向循环
|
||||
MaxAutomaticRedirections = 5
|
||||
};
|
||||
var client = new HttpClient(handler, disposeHandler: false)
|
||||
{
|
||||
Timeout = timeout
|
||||
};
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
|
||||
return client;
|
||||
}
|
||||
|
||||
/// <summary>获取默认超时(20秒)的 HttpClient,用于常规 API 请求。</summary>
|
||||
public static HttpClient GetDefault() => DefaultClient;
|
||||
|
||||
/// <summary>获取长超时(5分钟)的 HttpClient,用于大文件下载。</summary>
|
||||
public static HttpClient GetLongTimeout() => LongTimeoutClient;
|
||||
}
|
||||
@@ -7,9 +7,9 @@ namespace GC.Services;
|
||||
/// <summary>
|
||||
/// 内置下载源。
|
||||
///
|
||||
/// 目前只启用 Xhmcl;GitCode 的 preset 与下载实现仍保留在代码中,
|
||||
/// 但不参与测速 / 下载 / 更新。两个源本来指向同一份仓库内容,
|
||||
/// 区别只是托管服务器;恢复双源时把 GitCode 加回 <see cref="All"/>。
|
||||
/// 当前启用 Xhmcl(Gitea)与 GitHub 两个镜像,指向同一份仓库内容;
|
||||
/// 启动 / 下载 / 更新前并发测速(2 秒超时),取最快且可用的那个。
|
||||
/// GitCode 的 preset 与下载实现仍保留在代码中,但不参与测速 / 下载 / 更新。
|
||||
/// </summary>
|
||||
public sealed class SourcePreset
|
||||
{
|
||||
@@ -31,10 +31,16 @@ public sealed class SourcePreset
|
||||
|
||||
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('/')}";
|
||||
/// <summary>拼 raw 文件下载地址(各平台的 URL 结构不同)。</summary>
|
||||
public string RawUrl(string path) => RawStyle switch
|
||||
{
|
||||
// GitHub:raw.githubusercontent.com/{owner}/{repo}/{branch}/{path}
|
||||
"raw" => $"{RawBase}/{Owner}/{Repo}/{Branch}/{path.TrimStart('/')}",
|
||||
// GitCode:raw/{branch}/{path}
|
||||
"plain" => $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}",
|
||||
// Gitea:raw/branch/{branch}/{path}
|
||||
_ => $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset Xhmcl = new()
|
||||
{
|
||||
@@ -50,6 +56,25 @@ public sealed class SourcePreset
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// GitHub 镜像:与 Xhmcl 指向同一份仓库内容(模型清单 + Release 附件)。
|
||||
/// API 与 Gitea 高度兼容(contents / releases 同构),因此复用同一个 remote 实现,
|
||||
/// 仅在 URL 拼装与分页参数上区分。
|
||||
/// </summary>
|
||||
public static readonly SourcePreset GitHub = new()
|
||||
{
|
||||
Id = "github",
|
||||
Name = "GitHub",
|
||||
HomeUrl = "https://github.com/Morris-morris-cloud/GC",
|
||||
ApiBase = "https://api.github.com",
|
||||
RawBase = "https://raw.githubusercontent.com",
|
||||
Kind = "github",
|
||||
RawStyle = "raw",
|
||||
Owner = "Morris-morris-cloud",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset GitCode = new()
|
||||
{
|
||||
Id = "gitcode",
|
||||
@@ -65,20 +90,29 @@ public sealed class SourcePreset
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 当前启用的源:暂时只保留 Xhmcl。GitCode 的定义与实现仍保留在代码里,
|
||||
/// 但不参与测速、下载与更新(需要恢复时把 GitCode 加回这个数组即可)。
|
||||
/// 当前启用的源:Xhmcl 与 GitHub 是同一份仓库的两个镜像,启动时并发测速取最快。
|
||||
/// GitCode 的定义与实现仍保留在代码里,但不参与测速、下载与更新
|
||||
/// (需要恢复时把 GitCode 加回这个数组即可)。
|
||||
/// </summary>
|
||||
public static readonly SourcePreset[] All = { Xhmcl };
|
||||
public static readonly SourcePreset[] All = { Xhmcl, GitHub };
|
||||
|
||||
public static SourcePreset? Find(string? id) =>
|
||||
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>把任意仓库地址映射到启用的内置源(用于兼容旧配置)。</summary>
|
||||
/// <summary>把任意仓库地址 / 源名映射到启用的内置源(用于兼容旧配置与调用方取值)。</summary>
|
||||
public static SourcePreset Detect(string? url)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(url) &&
|
||||
url!.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase))
|
||||
return Xhmcl;
|
||||
if (!string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
if (url!.Contains("github.com", StringComparison.OrdinalIgnoreCase) ||
|
||||
url.Equals("GitHub", StringComparison.OrdinalIgnoreCase) ||
|
||||
url.Equals("github", StringComparison.OrdinalIgnoreCase))
|
||||
return GitHub;
|
||||
if (url.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase) ||
|
||||
url.Equals("Xhmcl", StringComparison.OrdinalIgnoreCase) ||
|
||||
url.Equals("xhmcl", StringComparison.OrdinalIgnoreCase))
|
||||
return Xhmcl;
|
||||
}
|
||||
|
||||
// 旧配置里的 GitCode 地址不再作为下载源,统一落到 Xhmcl。
|
||||
return Xhmcl;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 版本号工具:Release tag 有 v1.0.6 / GCL-1.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- / GCL- / release-
|
||||
if (s.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) s = s[4..];
|
||||
else 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));
|
||||
}
|
||||
Reference in new issue
Block a user