Compare commits
17
Commits
1.0.4
...
2f3a8682c9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f3a8682c9 | ||
|
|
791db4fe12 | ||
|
|
c95dfaf9f3 | ||
|
|
0ddee422ab | ||
|
|
a1211521eb | ||
|
|
512b1814e1 | ||
|
|
663efa5c75 | ||
|
|
8dcbd6f9d7 | ||
|
|
1cca045f08 | ||
|
|
4f5beb5109 | ||
|
|
6d4d098681 | ||
|
|
9293fee3bf | ||
|
|
f1787dff9d | ||
|
|
b6dc5649d6 | ||
|
|
4b5aa7799f | ||
|
|
0f19921dd4 | ||
|
|
0e86c17056 |
No files matched your search
@@ -1,6 +1,9 @@
|
||||
# 运行数据目录(settings/model/cache/update),绝不入库
|
||||
.GC/
|
||||
|
||||
# 签名私钥:绝对不入库(公钥写在 GC/src/Security/SignatureKeyring.cs 里)
|
||||
.signing/
|
||||
|
||||
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
|
||||
bin/
|
||||
obj/
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# 2026-11-14
|
||||
|
||||
## GC 启动器安全加固(补完)
|
||||
|
||||
- **GC-SAVEDOG 裁剪发布**:`PublishTrimmed=true` + `TrimMode=full` +
|
||||
`JsonSerializerIsReflectionEnabledByDefault=false`(已写进 csproj 与两套构建脚本)。
|
||||
体积 70MB → 14MB。裁剪后反射式 JSON 会失效,因此新增
|
||||
`GC-SAVEDOG/SavedogJson.cs`(`JsonSerializerContext` 源生成)并通过
|
||||
`Json.TypeInfoProvider` 钩子接进共享的 `GC.Download/GC.Services.Json`。
|
||||
→ 新增 JSON 类型必须登记到 `SavedogJsonContext`,否则只有发布产物会炸。
|
||||
- **构建产物布局改为 `dist/<系统>-<架构>/`**(mac-arm64 / win-amd64 / win-arm64),
|
||||
更新包路径 `dist/<平台>/GC-<版本>-<平台>.zip`;`pack_launcher` 之后调
|
||||
`VersionStamp --launcher-only` 把 `path/dir/name/sha256/size` 写进清单并重新签名。
|
||||
原始 `.app`/`.exe` 移到 `build/trash/`(避免递归删除几百个文件)。
|
||||
- **启动器更新支持「只发产物、不发 Release」**:新增 `GC-DOWNLOAD/LauncherArtifacts.cs`
|
||||
(平台标签/别名、候选目录与文件名推导,构建端 VersionStamp 也链接同一份)。
|
||||
`GitCodeRemote/GiteaRemote/DirectoryRemote.DownloadPackageAsync` 改成
|
||||
多候选尝试:url → 清单 path → `dist/<系统>-<架构>/` 目录扫描 → dist 根目录命名,
|
||||
每个候选都必须匹配已签名清单的 sha256。
|
||||
`GitCodeReleaseRemote` 在「没有 Release」时不再清空 launcher 字段(清单已签名)。
|
||||
- **测试**:`--update-test` 新增两条用例(dist 目录能找到并下载 / dist 目录里哈希不符被拒绝),
|
||||
当前 33 项全部通过。
|
||||
- 触发过的坑:`rm -rf` 大批文件被沙箱批量删除保护拦截 → 构建脚本改用 `mv` 到 `build/trash`。
|
||||
- **收尾验证(19:35–19:37)**:`./build.sh pack-launcher` 24s 完成三平台打包,
|
||||
清单已写入真实 `sha256/size`(win-amd64 44MB / win-arm64 42MB / mac-arm64 8.7MB,
|
||||
osx-x64 与 linux-amd64 无产物故留空,下载端会跳过)。根 `version.json` 与
|
||||
`model/version.json` 字节一致、签名 `gc-2026-11` 校验 Verified。
|
||||
从 mac 包里解出的 GC-SAVEDOG(14MB 裁剪版)实跑 `verify` / `status` 正常;
|
||||
`./build.sh check` 全流程通过。
|
||||
@@ -1,8 +1,9 @@
|
||||
<Project>
|
||||
<!--
|
||||
多目录结构公共属性:
|
||||
src/main/dotnet/<module> 生产代码
|
||||
src/test/dotnet/<module> 测试 / 离屏渲染校验
|
||||
GC-BOOT 启动入口
|
||||
GC/src/ 启动器核心代码
|
||||
GC/src/test/dotnet/<module> 测试 / 离屏渲染校验
|
||||
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
|
||||
-->
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == ''">
|
||||
@@ -21,9 +22,9 @@
|
||||
-->
|
||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||
<MvvmVersion>8.2.2</MvvmVersion>
|
||||
<Version>1.0.4</Version>
|
||||
<Version>1.0.7</Version>
|
||||
<Company>NeoRF</Company>
|
||||
<Product>Earth Model Studio</Product>
|
||||
<Product>GC</Product>
|
||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>GC.Boot</RootNamespace>
|
||||
<AssemblyName>GC</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<!-- 应用图标(Windows exe / 任务栏) -->
|
||||
<ApplicationIcon>..\GC\src\Assets\icon.ico</ApplicationIcon>
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,20 +1,22 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Services;
|
||||
using GC.Download;
|
||||
|
||||
namespace EarthModelStudio;
|
||||
namespace GC;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
|
||||
var paths = AppPaths.Discover();
|
||||
paths.EnsureCreated();
|
||||
|
||||
// 上次下载的启动器新版,到这次启动才应用
|
||||
if (LauncherUpdater.TryApplyPending(paths)) return;
|
||||
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
||||
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="EarthModelStudio.Desktop" />
|
||||
<assemblyIdentity version="1.0.0.0" name="GC.Desktop" />
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||
+49
-5
@@ -5,7 +5,7 @@ using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
||||
@@ -15,6 +15,8 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
private string? _rawManifest;
|
||||
private string _launcherVersion = "";
|
||||
|
||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||
|
||||
@@ -26,9 +28,20 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
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));
|
||||
|
||||
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的
|
||||
var text = File.ReadAllText(file);
|
||||
_rawManifest = text;
|
||||
var version = ManifestLoader.Parse(text, out _);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||
_launcherVersion = version.Launcher.Version.Trim();
|
||||
return Task.FromResult(version);
|
||||
}
|
||||
|
||||
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var baseDir = SafePath(rootPath ?? "model");
|
||||
@@ -76,11 +89,21 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(package.Path))
|
||||
// 清单路径 / dist 根目录命名:按仓库内相对路径直接找
|
||||
foreach (var rel in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||
{
|
||||
var local = SafePath(package.Path!);
|
||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
||||
string full;
|
||||
try { full = SafePath(rel); }
|
||||
catch (InvalidOperationException) { continue; }
|
||||
if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct);
|
||||
}
|
||||
|
||||
// dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则):
|
||||
// 本地源同样要能跑通「只发产物、不发 Release」的更新方式。
|
||||
var fromDist = FindInDist(package);
|
||||
if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct);
|
||||
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
@@ -93,6 +116,27 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。</summary>
|
||||
private string? FindInDist(RepoPackage package)
|
||||
{
|
||||
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||
{
|
||||
string full;
|
||||
try { full = SafePath(dir); }
|
||||
catch (InvalidOperationException) { continue; }
|
||||
if (!Directory.Exists(full)) continue;
|
||||
|
||||
var zips = Directory.GetFiles(full, "*.zip");
|
||||
if (zips.Length == 0) continue;
|
||||
|
||||
foreach (var zip in zips)
|
||||
if (LauncherArtifacts.LooksLikePackage(Path.GetFileName(zip), _launcherVersion, package.Rid))
|
||||
return zip;
|
||||
if (zips.Length == 1) return zips[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
+10
-19
@@ -5,21 +5,12 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
||||
public sealed partial class DownloadJob : ObservableObject
|
||||
public sealed partial class DownloadJob : ObservableObject, IDownloadJob
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public string Id => Model.Id;
|
||||
@@ -66,13 +57,13 @@ public sealed partial class DownloadJob : ObservableObject
|
||||
}
|
||||
|
||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
public sealed class DownloadCenter
|
||||
public sealed class DownloadCenter : IDownloadCenter
|
||||
{
|
||||
private readonly ModelRepository _repository;
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SemaphoreSlim _slots = new(2);
|
||||
|
||||
public ObservableCollection<DownloadJob> Jobs { get; } = new();
|
||||
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
|
||||
public event Action? Installed;
|
||||
|
||||
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
||||
@@ -81,7 +72,7 @@ public sealed class DownloadCenter
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public DownloadJob Enqueue(RemoteModel model)
|
||||
public IDownloadJob Enqueue(RemoteModel model)
|
||||
{
|
||||
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
||||
if (running != null) return running;
|
||||
@@ -92,7 +83,7 @@ public sealed class DownloadCenter
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task RunAsync(DownloadJob job)
|
||||
private async Task RunAsync(IDownloadJob job)
|
||||
{
|
||||
// 在 UI 线程构造,回调自动回到 UI 线程
|
||||
var progress = new Progress<(long Done, long Total)>(p =>
|
||||
@@ -135,20 +126,20 @@ public sealed class DownloadCenter
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(DownloadJob job)
|
||||
public void Cancel(IDownloadJob job)
|
||||
{
|
||||
try { job.Cts.Cancel(); } catch { }
|
||||
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
||||
}
|
||||
|
||||
public void Retry(DownloadJob job)
|
||||
public void Retry(IDownloadJob job)
|
||||
{
|
||||
if (job.IsActive) return;
|
||||
Jobs.Remove(job);
|
||||
Enqueue(job.Model);
|
||||
}
|
||||
|
||||
public void Remove(DownloadJob job)
|
||||
public void Remove(IDownloadJob job)
|
||||
{
|
||||
Cancel(job);
|
||||
Jobs.Remove(job);
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Download;
|
||||
|
||||
public sealed class DownloadModuleFactory : IDownloadModuleFactory
|
||||
{
|
||||
public IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models) =>
|
||||
new DownloadModule(paths, settings, models);
|
||||
|
||||
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
|
||||
}
|
||||
|
||||
internal sealed class DownloadModule : IDownloadModule
|
||||
{
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
public IUpdateService Updates { get; }
|
||||
public ISourceSelector Selector { get; }
|
||||
public ILauncherUpdateService LauncherUpdates { get; }
|
||||
|
||||
public DownloadModule(AppPaths paths, SettingsService settings, ModelRepository models)
|
||||
{
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, models);
|
||||
Selector = new SourceSelector();
|
||||
Updates = new UpdateService(paths, settings, UpdateService.CreateRemote(settings.Current));
|
||||
LauncherUpdates = new LauncherUpdateService();
|
||||
}
|
||||
|
||||
public IModelRemote CreateRemote(SourcePreset preset) => SourceSelector.CreateRemote(preset);
|
||||
}
|
||||
|
||||
internal sealed class LauncherUpdateService : ILauncherUpdateService
|
||||
{
|
||||
public Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default) =>
|
||||
LauncherUpdater.CheckAsync(remote, ct);
|
||||
|
||||
public Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default) =>
|
||||
LauncherUpdater.DownloadAsync(paths, remote, progress, ct);
|
||||
|
||||
public bool ScheduleApply(AppPaths paths, string packageName) =>
|
||||
LauncherUpdater.ScheduleApply(paths, packageName);
|
||||
|
||||
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Download</RootNamespace>
|
||||
<AssemblyName>GC.Download</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+39
-11
@@ -5,7 +5,7 @@ using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
||||
@@ -32,7 +32,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return client;
|
||||
}
|
||||
@@ -50,43 +50,69 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC");
|
||||
return ("Morris_1", "GC");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC");
|
||||
if (parts.Length < 2) return ("Morris_1", "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
|
||||
{
|
||||
await ApplyReleaseAsync(version, ct);
|
||||
gotRelease = await ApplyReleaseAsync(version, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 没有 Release / 断网 / 格式不符:回退到 version.json,不影响模型更新
|
||||
Console.Error.WriteLine($"读取 Release 失败,回退仓库清单: {ex.Message}");
|
||||
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
|
||||
gotRelease = false;
|
||||
}
|
||||
|
||||
if (!gotRelease)
|
||||
{
|
||||
// 没有 Release ≠ 不能更新:清单已签名,且每个平台包都写了 sha256,
|
||||
// 走「仓库 dist/<系统>-<架构>/ 里的编译产物」同样可信。
|
||||
// 这里保留清单里的 launcher 版本与包信息,让下载端去 dist 目录找包。
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
var n = version?.Launcher.Packages.Count ?? 0;
|
||||
if (v.Length == 0 || n == 0)
|
||||
{
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
private async Task<bool> ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
{
|
||||
if (version == null) return;
|
||||
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; // 可能是错误页/对象
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
ReleaseInfo? latest = null;
|
||||
@@ -97,9 +123,10 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
// 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层)
|
||||
if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info;
|
||||
}
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return;
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||
|
||||
version.Launcher.Version = latest.Version;
|
||||
_content.SetLauncherVersion(latest.Version);
|
||||
|
||||
_assets.Clear();
|
||||
foreach (var asset in latest.Assets)
|
||||
@@ -125,6 +152,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
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)
|
||||
+154
-21
@@ -2,23 +2,24 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
|
||||
/// (https://gitcode.com/Morris_1/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";
|
||||
public const string DefaultRepository = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _api;
|
||||
@@ -27,6 +28,9 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
private readonly string? _fallbackUrl;
|
||||
private readonly string _displayName;
|
||||
private string _modelDir = "model";
|
||||
private string? _rawManifest;
|
||||
/// <summary>最近一次读到的启动器版本号,用于推导 dist 目录里的包名。</summary>
|
||||
private string _launcherVersion = "";
|
||||
|
||||
public string DisplayName => _displayName;
|
||||
|
||||
@@ -39,7 +43,7 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
? DefaultRepository : repository!.TrimEnd('/');
|
||||
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||
@@ -59,9 +63,9 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC", "main");
|
||||
return ("Morris_1", "GC", "main");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
|
||||
if (parts.Length < 2) return ("Morris_1", "GC", "main");
|
||||
var owner = parts[0];
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
@@ -77,9 +81,24 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||
_modelDir = version.ModelDir.Trim('/');
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||
_launcherVersion = version.Launcher.Version.Trim();
|
||||
return version;
|
||||
}
|
||||
|
||||
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
/// <summary>
|
||||
/// 由 Release 覆盖版本号后同步一次,保证 dist 目录里的包名推导用的是
|
||||
/// 「真正要装的那个版本」,而不是仓库清单里可能滞后的版本号。
|
||||
/// </summary>
|
||||
internal void SetLauncherVersion(string? version)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(version)) _launcherVersion = version!.Trim();
|
||||
}
|
||||
|
||||
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
||||
{
|
||||
string text;
|
||||
@@ -107,10 +126,20 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
payload = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
|
||||
payload, EarthModelStudio.Services.Json.Options);
|
||||
|
||||
// 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」
|
||||
var version = ManifestLoader.Parse(payload, out var verification);
|
||||
if (version == null) return null;
|
||||
|
||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
|
||||
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
|
||||
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
|
||||
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
|
||||
_rawManifest = payload;
|
||||
return version;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -283,25 +312,129 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
|
||||
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))
|
||||
// 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。
|
||||
var direct = await TryFetchAsync(package.Url, package.Sha256, ct);
|
||||
if (direct != null) return direct;
|
||||
|
||||
// url 不可用或校验不符:再去找仓库里的编译产物。
|
||||
// 顺序:清单 path → dist/<系统>-<架构>/ 里的 zip → dist 根目录命名。
|
||||
// 每个候选都要和已签名清单的 sha256 对一遍,对不上就换下一个,
|
||||
// 因此「多来源」不放宽校验,只是让「不发 Release 也能更新」成立。
|
||||
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||
{
|
||||
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();
|
||||
var url = await ResolveFileUrlAsync(path, ct);
|
||||
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||
{
|
||||
var url = await FindZipInDirAsync(dir, package, ct);
|
||||
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>下载一个候选地址;<paramref name="sha256"/> 非空时必须与内容一致。</summary>
|
||||
private async Task<byte[]?> TryFetchAsync(string? url, string? sha256, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
|
||||
byte[] bytes;
|
||||
try { bytes = await _http.GetByteArrayAsync(url!, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
||||
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
if (bytes.Length == 0) return null;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
return await _http.GetByteArrayAsync(url!, ct);
|
||||
|
||||
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static string Short(string url)
|
||||
=> url.Length <= 96 ? url : url[..60] + "…" + url[^24..];
|
||||
|
||||
/// <summary>把仓库内路径解析成直链;路径不存在或其实是目录时返回 null。</summary>
|
||||
private async Task<string?> ResolveFileUrlAsync(string path, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = _api + path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("type", out var type) &&
|
||||
string.Equals(type.GetString(), "dir", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
return doc.RootElement.TryGetProperty("download_url", out var dl)
|
||||
? dl.GetString() : null;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null; // 404 / 网络问题都当作「这个路径没有」
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在 <paramref name="dir"/> 里找启动器包。
|
||||
/// 先按「版本 + 平台」精确筛,其次接受目录里唯一的 zip(发布者可能改了命名规则),
|
||||
/// 最终仍由 sha256 兜底。
|
||||
/// </summary>
|
||||
private async Task<string?> FindZipInDirAsync(string dir, RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = _api + dir.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return null;
|
||||
|
||||
var zips = new List<(string Path, string Name)>();
|
||||
using (var doc = JsonDocument.Parse(text))
|
||||
{
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
if (Str(item, "type") != "file") continue;
|
||||
var name = Str(item, "name");
|
||||
if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var path = Str(item, "path");
|
||||
zips.Add((path.Length > 0 ? path : dir + "/" + name, name));
|
||||
}
|
||||
}
|
||||
if (zips.Count == 0) return null;
|
||||
|
||||
var version = _launcherVersion;
|
||||
var match = zips.FindIndex(z =>
|
||||
LauncherArtifacts.LooksLikePackage(z.Name, version, package.Rid));
|
||||
if (match < 0)
|
||||
{
|
||||
if (zips.Count != 1) return null;
|
||||
match = 0;
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}");
|
||||
return await ResolveFileUrlAsync(zips[match].Path, ct);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Str(JsonElement item, string name)
|
||||
@@ -0,0 +1,338 @@
|
||||
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 string? _rawManifest;
|
||||
|
||||
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)
|
||||
{
|
||||
// Release 只能说明"哪个附件",完整性必须回到已签名清单取 sha256,
|
||||
// 否则「有仓库写权限的人发个 Release」就能绕过验签。
|
||||
if (fromRepo != null &&
|
||||
fromRepo.Launcher.Packages.TryGetValue(kv.Key, out var signed) &&
|
||||
!string.IsNullOrWhiteSpace(signed?.Sha256))
|
||||
{
|
||||
kv.Value.Sha256 = signed!.Sha256;
|
||||
if (signed.Size > 0) kv.Value.Size = signed.Size;
|
||||
}
|
||||
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>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
/// <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 = ManifestLoader.Parse(text, out var verification);
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
|
||||
if (doc != null)
|
||||
{
|
||||
_rawManifest = text;
|
||||
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)
|
||||
{
|
||||
// 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。
|
||||
// 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。
|
||||
var candidates = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(package.Url)) candidates.Add(package.Url!.Trim());
|
||||
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, ""))
|
||||
candidates.Add(_preset.RawUrl(path));
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
byte[] bytes;
|
||||
try { bytes = await Http.GetByteArrayAsync(candidate, ct); }
|
||||
catch (Exception) { continue; }
|
||||
if (bytes.Length == 0) continue;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(package.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(
|
||||
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
|
||||
return bytes;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 平台标签与「仓库里的编译产物位置」的推导规则。
|
||||
///
|
||||
/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物
|
||||
/// 提交(或上传)到仓库的 <c>dist/<系统>-<架构></c> 目录,例如
|
||||
/// <c>dist/mac-arm64/GC-1.0.7-mac-arm64.zip</c>,根本没有发 Release。
|
||||
/// 于是下载端需要一套「同一个平台有哪几种叫法」的映射,才能把这些目录找出来。
|
||||
///
|
||||
/// 安全性说明:多来源尝试**不会**降低安全性——每个候选下载完都要和已签名清单里的
|
||||
/// sha256 对一遍,对不上就换下一个来源,全都不对就失败。sha256 来自签名清单,
|
||||
/// 攻击者即使往 dist/ 里塞包也拿不到匹配的哈希。
|
||||
///
|
||||
/// 本文件同时被启动器(GC-DOWNLOAD)与构建端(VersionStamp)链接编译,
|
||||
/// 保证「写进清单的路径」与「运行时找的路径」永远一致。
|
||||
/// </summary>
|
||||
public static class LauncherArtifacts
|
||||
{
|
||||
/// <summary>
|
||||
/// RID → 文件名里的「系统-架构」标签(与 <c>LauncherUpdater.PlatformLabel</c> 一致)。
|
||||
/// </summary>
|
||||
public static string LabelOf(string rid) => rid switch
|
||||
{
|
||||
"win-x64" => "win-amd64",
|
||||
"win-arm64" => "win-arm64",
|
||||
"osx-arm64" => "mac-arm64",
|
||||
"osx-x64" => "mac-x64",
|
||||
"linux-x64" => "linux-amd64",
|
||||
_ => rid
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 同一平台在仓库里可能用的目录名(按优先级)。
|
||||
/// 既接受 <c>mac-arm64</c> 这种标签,也接受 <c>osx-arm64</c> 这种 RID,
|
||||
/// 因为 dist 目录名历史上两种写法都出现过。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> PlatformAliases(string rid)
|
||||
{
|
||||
var label = LabelOf(rid);
|
||||
if (string.Equals(label, rid, StringComparison.OrdinalIgnoreCase))
|
||||
return new[] { rid };
|
||||
return new[] { label, rid };
|
||||
}
|
||||
|
||||
/// <summary>启动器包应有的文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>。</summary>
|
||||
public static string PackageFileName(string version, string rid)
|
||||
=> $"GC-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
|
||||
|
||||
/// <summary>
|
||||
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
|
||||
/// 只做粗筛(版本串 + 平台别名),最终仍以 sha256 为准。
|
||||
/// </summary>
|
||||
public static bool LooksLikePackage(string fileName, string version, string rid)
|
||||
{
|
||||
if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
|
||||
var v = version.Trim().TrimStart('v', 'V');
|
||||
if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false;
|
||||
|
||||
var haystack = fileName.ToLowerInvariant();
|
||||
foreach (var alias in PlatformAliases(rid))
|
||||
if (haystack.Contains(alias.ToLowerInvariant(), StringComparison.Ordinal))
|
||||
return true;
|
||||
|
||||
return haystack.Contains(rid.ToLowerInvariant(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 候选目录:清单显式给的 dir 优先,其次是 <c>dist/<标签></c> 与 <c>dist/<RID></c>。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> CandidateDirs(string rid, string? declaredDir)
|
||||
{
|
||||
var dirs = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(declaredDir))
|
||||
dirs.Add(declaredDir!.Trim().Trim('/'));
|
||||
|
||||
foreach (var alias in PlatformAliases(rid))
|
||||
dirs.Add("dist/" + alias);
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var result = new List<string>();
|
||||
foreach (var dir in dirs)
|
||||
if (dir.Length > 0 && seen.Add(dir)) result.Add(dir);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 候选文件路径(不含目录扫描):清单给的 path / name,以及 dist 根目录里的两种命名。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> CandidateFiles(string rid, string? declaredDir,
|
||||
string? declaredPath, string? declaredName, string version)
|
||||
{
|
||||
var files = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(declaredPath))
|
||||
files.Add(declaredPath!.Trim().Trim('/'));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(declaredName))
|
||||
foreach (var dir in CandidateDirs(rid, declaredDir))
|
||||
files.Add(dir + "/" + declaredName!.Trim());
|
||||
|
||||
if (version.Length > 0)
|
||||
{
|
||||
files.Add("dist/" + PackageFileName(version, rid));
|
||||
foreach (var alias in PlatformAliases(rid))
|
||||
files.Add($"dist/GC-{version.Trim().TrimStart('v', 'V')}-{alias}.zip");
|
||||
}
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var result = new List<string>();
|
||||
foreach (var file in files)
|
||||
if (file.Length > 0 && seen.Add(file)) result.Add(file);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
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-* 文件;
|
||||
// 异系统 / 异架构的文件一律不碰
|
||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||
// ===========================================================================
|
||||
|
||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||
public static class LauncherUpdater
|
||||
{
|
||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||
public static string RunningVersion => LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||
public static string CurrentRid => LauncherRuntimeInfo.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})没有对应发布包");
|
||||
|
||||
// ---- 信任闸门 ---------------------------------------------------
|
||||
// 启动器更新会替换可执行文件,风险最高:清单没签名就一律不动。
|
||||
// 只有显式设置 GC_ALLOW_UNSIGNED_MANIFEST=1(自建私有构建)才放行。
|
||||
var allowUnsigned =
|
||||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||
|
||||
if (!version.IsTrusted && !allowUnsigned)
|
||||
{
|
||||
var reason = version.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||
? "清单签名无效"
|
||||
: "清单未签名";
|
||||
Console.Error.WriteLine($"[update] 启动器更新被拒绝:{reason}");
|
||||
return Fail($"{reason},已拒绝下载启动器更新");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
{
|
||||
Console.Error.WriteLine("[update] 清单没有提供 sha256,拒绝下载启动器更新");
|
||||
return Fail("清单缺少该平台的 sha256,已拒绝下载(无法校验完整性)");
|
||||
}
|
||||
|
||||
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 校验(清单已验签,这里的 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.55, Stage = "正在校验更新包" });
|
||||
|
||||
var updateRoot = paths.UpdateRoot;
|
||||
Directory.CreateDirectory(updateRoot);
|
||||
|
||||
// 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录",
|
||||
// 避免「解压后被替换」的中间窗口。
|
||||
var zip = Path.Combine(updateRoot, "package.zip");
|
||||
if (File.Exists(zip)) File.Delete(zip);
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var inspection = SafeArchive.Inspect(zip);
|
||||
Console.WriteLine($"[update] 更新包检查通过:{inspection.Entries} 个条目," +
|
||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { File.Delete(zip); } catch { }
|
||||
return Fail("更新包安全性检查失败: " + ex.Message);
|
||||
}
|
||||
|
||||
// 二次验签用的清单副本:SAVEDOG 不信任"启动器说它验过了"
|
||||
var rawManifest = await remote.GetRawVersionTextAsync(ct);
|
||||
var manifestCopy = Path.Combine(updateRoot, "version.json");
|
||||
if (!string.IsNullOrWhiteSpace(rawManifest))
|
||||
File.WriteAllText(manifestCopy, rawManifest!);
|
||||
else if (File.Exists(manifestCopy))
|
||||
File.Delete(manifestCopy);
|
||||
|
||||
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
|
||||
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
|
||||
|
||||
var request = new SavedogRequest
|
||||
{
|
||||
Version = latest,
|
||||
Rid = rid,
|
||||
PlatformLabel = PlatformLabel,
|
||||
PackageName = packageName,
|
||||
PackageZip = "package.zip",
|
||||
PayloadDir = "payload",
|
||||
ManifestPath = "version.json",
|
||||
PackageSha256 = pkg.Sha256!.Trim().ToLowerInvariant(),
|
||||
PackageSize = bytes.LongLength,
|
||||
RequireSignature = version.IsTrusted,
|
||||
InstallRelative = Path.GetRelativePath(updateRoot, paths.InstallDirectory),
|
||||
CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
};
|
||||
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||
|
||||
// 兼容兜底:没有 SAVEDOG 的旧安装,仍然按老方式预解压 + 脚本替换
|
||||
string? legacyPath = null;
|
||||
if (SavedogLauncher.Find(paths) == null)
|
||||
{
|
||||
Console.WriteLine("[update] 未找到 GC-SAVEDOG,使用兼容脚本流程");
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.7, Stage = "正在解压更新包" });
|
||||
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
SafeArchive.ExtractToDirectory(zip, staging);
|
||||
FlattenStaging(staging);
|
||||
|
||||
var payload = Path.Combine(updateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
Directory.CreateDirectory(payload);
|
||||
var legacyName = MoveToPayload(staging, payload);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (legacyName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
packageName = legacyName;
|
||||
request.PackageName = legacyName;
|
||||
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||
legacyPath = Path.Combine(payload, legacyName);
|
||||
|
||||
// 老脚本读这个纯文本标记,只含相对信息
|
||||
File.WriteAllText(Path.Combine(updateRoot, "update.txt"),
|
||||
$"NAME={legacyName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
|
||||
$"INSTALL_REL={request.InstallRelative}\n");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
return new UpdateRunResult
|
||||
{
|
||||
State = UpdateRunState.Ready,
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已暂存到 .GC/update",
|
||||
PackageName = packageName,
|
||||
NewAppPath = legacyPath
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
catch (Exception ex) { return Fail(ex.Message); }
|
||||
}
|
||||
|
||||
private static UpdateRunResult Fail(string msg) => new()
|
||||
{
|
||||
State = UpdateRunState.Failed,
|
||||
Message = msg
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 应用(下次启动)
|
||||
|
||||
/// <summary>
|
||||
/// 安排应用已下载的新版。
|
||||
/// 首选 <b>GC-SAVEDOG</b>:二次验签、原子替换、启动后健康检查、失败自动回滚;
|
||||
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
|
||||
/// 返回 true 表示调用方应立即退出进程。
|
||||
/// </summary>
|
||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
||||
{
|
||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||
{
|
||||
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (File.Exists(Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest)))
|
||||
{
|
||||
string? savedogError = null;
|
||||
if (SavedogLauncher.TryStart(paths, Environment.ProcessId, out savedogError))
|
||||
return true;
|
||||
Console.Error.WriteLine($"[update] {savedogError},改用兼容脚本");
|
||||
}
|
||||
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) 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>启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。</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;
|
||||
|
||||
// 新协议:apply-request.json + package.zip(SAVEDOG 自己解压 + 验签)
|
||||
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||
if (File.Exists(requestPath))
|
||||
{
|
||||
var request = Json.Read<SavedogRequest>(requestPath);
|
||||
var zipPath = request == null
|
||||
? null
|
||||
: Path.Combine(paths.UpdateRoot, request.PackageZip);
|
||||
|
||||
if (request != null && zipPath != null && File.Exists(zipPath))
|
||||
return ScheduleApply(paths, request.PackageName);
|
||||
|
||||
Console.Error.WriteLine("[update] 更新申请不完整,已清理");
|
||||
try { File.Delete(requestPath); } catch { }
|
||||
}
|
||||
|
||||
// 旧协议:update.txt + payload(从老版本升级时仍可能遇到)
|
||||
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;
|
||||
var payloadPath = Path.Combine(paths.UpdateRoot, "payload", name!);
|
||||
if (!File.Exists(payloadPath) && !Directory.Exists(payloadPath))
|
||||
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 path is recorded relatively");
|
||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && 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("INSTALLREL=$(sed -n 's/^INSTALL_REL=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ] || [ -z \"$INSTALLREL\" ]; then");
|
||||
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/$INSTALLREL\" && pwd)");
|
||||
s.AppendLine("PAYLOAD=\"$HERE/payload/$NEWNAME\"");
|
||||
s.AppendLine("if [ ! -e \"$PAYLOAD\" ]; 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("# move the staged package into the install directory");
|
||||
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
||||
s.AppendLine("rm -rf \"$NEW\"");
|
||||
s.AppendLine("mv \"$PAYLOAD\" \"$NEW\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# launch new version");
|
||||
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 \"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("set \"INSTALLREL=\"");
|
||||
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("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"INSTALL_REL=\" \"%MARKER%\" 2^>nul') do set \"INSTALLREL=%%A\"");
|
||||
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("if \"%INSTALLREL%\"==\"\" (echo install path missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("for %%I in (\"%HERE%%INSTALLREL%\") do set \"DST=%%~fI\"");
|
||||
s.AppendLine("set \"PAYLOAD=%HERE%payload\\%NEWNAME%\"");
|
||||
s.AppendLine("if not exist \"%PAYLOAD%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem move the staged package into the install directory");
|
||||
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" rmdir /S /Q \"%DST%\\%NEWNAME%\" 2>nul");
|
||||
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" del /Q \"%DST%\\%NEWNAME%\" 2>nul");
|
||||
s.AppendLine("move \"%PAYLOAD%\" \"%DST%\\%NEWNAME%\" >nul");
|
||||
s.AppendLine("if errorlevel 1 (echo failed to install update & 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 里的新版搬入下载目录的 payload。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。
|
||||
/// </summary>
|
||||
private static string? MoveToPayload(string staging, string payload)
|
||||
{
|
||||
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(payload, 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(' ', '-');
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,9 +2,9 @@ using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelInstaller
|
||||
{
|
||||
+5
-5
@@ -7,16 +7,16 @@ using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 从链接导入模型源。
|
||||
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存在应用缓存目录。
|
||||
/// </summary>
|
||||
public sealed class ModelSourceClient
|
||||
public sealed class ModelSourceClient : IModelSourceClient
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
@@ -26,7 +26,7 @@ public sealed class ModelSourceClient
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)");
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 找到并启动 GC-SAVEDOG(启动器更新的守护进程)。
|
||||
///
|
||||
/// 为什么要独立进程:启动器正在运行时无法安全覆盖自己;一旦覆盖失败,
|
||||
/// 启动器已退出,就没人能回滚。把"替换 + 看护"交给一个只做这件事的小程序,
|
||||
/// 风险面被压缩到最小,也便于审计。
|
||||
/// </summary>
|
||||
public static class SavedogLauncher
|
||||
{
|
||||
/// <summary>在安装目录里寻找 SAVEDOG 可执行文件。</summary>
|
||||
public static string? Find(AppPaths paths)
|
||||
{
|
||||
var name = SavedogFiles.ExecutableName;
|
||||
var install = paths.InstallDirectory;
|
||||
|
||||
var direct = Path.Combine(install, name);
|
||||
if (File.Exists(direct)) return direct;
|
||||
|
||||
// macOS:可能放在 .app 内部
|
||||
try
|
||||
{
|
||||
foreach (var app in Directory.GetDirectories(install, "*.app"))
|
||||
{
|
||||
var inside = Path.Combine(app, "Contents", "MacOS", name);
|
||||
if (File.Exists(inside)) return inside;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
var bin = Path.Combine(paths.HomeRoot, "bin", name);
|
||||
if (File.Exists(bin)) return bin;
|
||||
|
||||
try
|
||||
{
|
||||
var exe = Environment.ProcessPath;
|
||||
if (!string.IsNullOrWhiteSpace(exe))
|
||||
{
|
||||
var beside = Path.Combine(Path.GetDirectoryName(exe)!, name);
|
||||
if (File.Exists(beside)) return beside;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动 SAVEDOG 应用更新。<paramref name="waitForPid"/> 是当前启动器进程,
|
||||
/// SAVEDOG 会等它退出后再动文件。
|
||||
/// </summary>
|
||||
public static bool TryStart(AppPaths paths, int waitForPid, out string? error)
|
||||
{
|
||||
error = null;
|
||||
var exe = Find(paths);
|
||||
if (exe == null)
|
||||
{
|
||||
error = "未找到 GC-SAVEDOG";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||
if (!File.Exists(requestPath))
|
||||
{
|
||||
error = "缺少 apply-request.json";
|
||||
return false;
|
||||
}
|
||||
|
||||
var psi = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
WorkingDirectory = paths.InstallDirectory
|
||||
};
|
||||
psi.ArgumentList.Add("apply");
|
||||
psi.ArgumentList.Add("--update");
|
||||
psi.ArgumentList.Add(paths.UpdateRoot);
|
||||
psi.ArgumentList.Add("--install");
|
||||
psi.ArgumentList.Add(paths.InstallDirectory);
|
||||
psi.ArgumentList.Add("--wait-pid");
|
||||
psi.ArgumentList.Add(waitForPid.ToString());
|
||||
psi.ArgumentList.Add("--timeout");
|
||||
psi.ArgumentList.Add("45");
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
try
|
||||
{
|
||||
var mode = File.GetUnixFileMode(exe);
|
||||
File.SetUnixFileMode(exe, mode | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
Process.Start(psi);
|
||||
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>读取 SAVEDOG 最近一次的执行结果(供界面展示)。</summary>
|
||||
public static SavedogState? ReadState(AppPaths paths)
|
||||
=> Json.Read<SavedogState>(Path.Combine(paths.UpdateRoot, SavedogFiles.State));
|
||||
|
||||
/// <summary>上次成功启动的版本(回滚依据)。</summary>
|
||||
public static LastGoodVersion? ReadLastGood(AppPaths paths)
|
||||
=> Json.Read<LastGoodVersion>(Path.Combine(paths.UpdateRoot, SavedogFiles.LastGood));
|
||||
}
|
||||
@@ -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 : ISourceSelector
|
||||
{
|
||||
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)
|
||||
};
|
||||
}
|
||||
+96
-34
@@ -8,20 +8,20 @@ using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
public sealed class UpdateService : IUpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly IModelRemote _remote;
|
||||
private IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
@@ -32,41 +32,34 @@ public sealed class UpdateService
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var v = Assembly.GetEntryAssembly()?.GetName().Version;
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
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>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||
|
||||
/// <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!); // 离线 U 盘源:仍读本地 version.json
|
||||
// 在线源:启动器版本与发布包走 GitCode Release(tag + 附件),
|
||||
// 模型清单/文件仍走仓库 contents API;无 Release 时自动回退仓库 version.json。
|
||||
return new GitCodeReleaseRemote(settings.UpdateManifestUrl, settings.UpdateRepository);
|
||||
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,
|
||||
@@ -111,6 +104,37 @@ public sealed class UpdateService
|
||||
Message = L.I["update.noManifest"]
|
||||
};
|
||||
|
||||
// ---- 清单信任策略 --------------------------------------------------
|
||||
// 签名有效 → 通过;没有签名 / 签名不符 → 默认拒绝(可用设置或环境变量放开)。
|
||||
// 这一道闸门挡住的是「仓库被改、模型 dll 被换成木马」这类攻击。
|
||||
var allowUnsigned = devMode ||
|
||||
!_settings.Current.RequireSignedManifest ||
|
||||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||
|
||||
if (!remote.IsTrusted)
|
||||
{
|
||||
var reason = remote.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||
? "清单签名无效(内容可能被篡改)"
|
||||
: "清单未签名";
|
||||
|
||||
if (!allowUnsigned)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {reason},已拒绝本次更新");
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = $"{reason},已拒绝更新",
|
||||
Error = remote.SignatureError
|
||||
};
|
||||
}
|
||||
|
||||
Console.Error.WriteLine($"[update] {reason},当前为开发/放宽模式,继续");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"[update] 清单验签通过({remote.SignatureKeyId})");
|
||||
}
|
||||
|
||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||
_settings.Save();
|
||||
|
||||
@@ -255,6 +279,22 @@ public sealed class UpdateService
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// ---- 完整性校验:清单是签过名的,里面的哈希就是"正版"的定义 --------
|
||||
// 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装。
|
||||
var computed = ModelIntegrity.Compute(staging, model.Id);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(model.ManifestSha256) &&
|
||||
!string.Equals(computed.ManifestSha256, model.ManifestSha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(
|
||||
$"模型清单哈希不符(期望 {Short(model.ManifestSha256)},实际 {Short(computed.ManifestSha256)})");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(model.FilesSha256) &&
|
||||
!string.Equals(computed.FilesSha256, model.FilesSha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(
|
||||
$"模型文件哈希不符(期望 {Short(model.FilesSha256)},实际 {Short(computed.FilesSha256)}),已丢弃");
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
Directory.CreateDirectory(_paths.ModelRoot);
|
||||
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
@@ -277,6 +317,25 @@ public sealed class UpdateService
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
|
||||
// 安装成功:把完整性记录写进模型目录,加载 dll 前会再抽查一次
|
||||
try
|
||||
{
|
||||
ModelIntegrity.Write(target, model.Id, new ModelIntegrityFile
|
||||
{
|
||||
Id = model.Id,
|
||||
Version = model.Version,
|
||||
ManifestSha256 = computed.ManifestSha256,
|
||||
FilesSha256 = computed.FilesSha256,
|
||||
Files = computed.Files,
|
||||
InstalledAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
Source = _remote.DisplayName
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"写入完整性记录失败 {model.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -290,4 +349,7 @@ public sealed class UpdateService
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
|
||||
private static string Short(string? hash)
|
||||
=> string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8];
|
||||
}
|
||||
@@ -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,22 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压的统一入口(实现在 <see cref="SafeArchive"/>)。
|
||||
/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用,
|
||||
/// 真正的校验逻辑集中在一处,避免两套实现走偏。
|
||||
/// </summary>
|
||||
public static class ZipSafety
|
||||
{
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
if (!File.Exists(zipPath))
|
||||
throw new FileNotFoundException("压缩包不存在", zipPath);
|
||||
SafeArchive.ExtractToDirectory(zipPath, destination);
|
||||
}
|
||||
|
||||
/// <summary>只检查不落盘:给下载完成后的预检用。</summary>
|
||||
public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath);
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Shapes = Avalonia.Controls.Shapes;
|
||||
using Avalonia.VisualTree;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口:**只做窗口宿主**。
|
||||
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
|
||||
/// 快捷键:Esc 关闭窗口,F11 全屏。
|
||||
/// </summary>
|
||||
public sealed class PlayerWindow : Window
|
||||
{
|
||||
private LoadedModel? _model;
|
||||
private bool _closing;
|
||||
private Button? _maximizeButton;
|
||||
private Border? _frame;
|
||||
private TextBlock? _titleText;
|
||||
private Border? _titleBar;
|
||||
private readonly List<Button> _titleButtons = new();
|
||||
private readonly List<Shapes.Path> _titleGlyphs = new();
|
||||
private Shapes.Path? _maximizeGlyph;
|
||||
private Shapes.Path? _restoreGlyph;
|
||||
private string _maxMaxPath = "";
|
||||
private string _maxRestorePath = "";
|
||||
private Button? _helpButton;
|
||||
/// <summary>基准尺寸(1240×820 时的标题栏高度与按钮尺寸)。</summary>
|
||||
private const double BaseWidth = 1240;
|
||||
private const double BaseTitleBarHeight = 34;
|
||||
private const double BaseButtonWidth = 38;
|
||||
private const double BaseButtonHeight = 28;
|
||||
private const double BaseTitleFont = 11.5;
|
||||
private const double BaseHelpFont = 11.5;
|
||||
|
||||
public PlayerWindow(ModelPackage package, LoadedModel model)
|
||||
{
|
||||
_model = model;
|
||||
Title = package.LocalizedName;
|
||||
Width = 1240;
|
||||
Height = 820;
|
||||
MinWidth = 1000;
|
||||
MinHeight = 680;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
|
||||
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
|
||||
|
||||
// 标题栏配色来自模型清单,跟随模型自己的界面风格:
|
||||
// 地球模型是深色舞台,比例尺计算器是浅色卡片,两者不能共用一套深色。
|
||||
var chrome = package.Manifest.Chrome;
|
||||
var barBg = ParseColor(chrome?.TitleBar, "#0C1828");
|
||||
var barBorder = ParseColor(chrome?.TitleBorder, "#1B2740");
|
||||
var barText = ParseColor(chrome?.TitleText, "#EAF2FF");
|
||||
var btnText = ParseColor(chrome?.Button, "#9FB4D4");
|
||||
var frameBg = ParseColor(chrome?.Frame, "#0A1524");
|
||||
|
||||
var titleText = new TextBlock
|
||||
{
|
||||
Text = package.LocalizedName,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 11.5,
|
||||
Margin = new Thickness(14, 0, 0, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
[Grid.ColumnProperty] = 0
|
||||
};
|
||||
_titleText = titleText;
|
||||
|
||||
var helpButton = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "How to use?" : "如何使用?",
|
||||
Height = 26,
|
||||
Padding = new Thickness(12, 0),
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
BorderThickness = new Thickness(0),
|
||||
FontSize = 11.5,
|
||||
CornerRadius = new CornerRadius(7),
|
||||
Margin = new Thickness(0, 0, 6, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = 1
|
||||
};
|
||||
helpButton.Click += (_, _) => ShowHelp(package, barBg, barBorder, barText, btnText, frameBg);
|
||||
|
||||
// 标题栏三键:最小化 / 最大化 / 关闭 —— 卡通画风。
|
||||
// 每颗按钮 = 彩色实心圆底 + 粗圆头描边图标,像一颗小糖豆。
|
||||
(Button Btn, Shapes.Path Icon) MakeBadge(int column, string iconPath)
|
||||
{
|
||||
// 纯矢量图标,没有彩色圆圈
|
||||
var icon = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse(iconPath),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
StrokeJoin = PenLineJoin.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10,
|
||||
Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
var layer = new Grid
|
||||
{
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
layer.Children.Add(icon);
|
||||
|
||||
var b = new Button
|
||||
{
|
||||
Width = 38,
|
||||
Height = 28,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(2, 0, 0, 0),
|
||||
Content = layer,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = column
|
||||
};
|
||||
var hoverBg = IsLight(barBg)
|
||||
? new SolidColorBrush(Color.Parse("#EEF1F7"))
|
||||
: new SolidColorBrush(Color.Parse("#1E2C46"));
|
||||
var isCloseBtn = column == 4;
|
||||
b.PointerEntered += (_, _) =>
|
||||
{
|
||||
b.Background = hoverBg;
|
||||
icon.Stroke = new SolidColorBrush(isCloseBtn ? Colors.White
|
||||
: IsLight(barBg) ? Color.Parse("#111A2E") : Colors.White);
|
||||
};
|
||||
b.PointerExited += (_, _) =>
|
||||
{
|
||||
b.Background = Brushes.Transparent;
|
||||
icon.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
b.Classes.Add("model-titlebtn");
|
||||
_titleButtons.Add(b);
|
||||
_titleGlyphs.Add(icon);
|
||||
return (b, icon);
|
||||
}
|
||||
|
||||
// 卡通配色:暖黄 / 薄荷绿 / 珊瑚红
|
||||
var minBadge = MakeBadge(2, "M1.5,5 L8.5,5");
|
||||
var maxBadge = MakeBadge(3, "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
var closeBadge = MakeBadge(4, "M2,2 L8,8 M8,2 L2,8");
|
||||
|
||||
var minimizeButton = minBadge.Btn;
|
||||
var maximizeButton = maxBadge.Btn;
|
||||
var closeButton = closeBadge.Btn;
|
||||
|
||||
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
|
||||
maximizeButton.Click += (_, _) => ToggleMaximize();
|
||||
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
|
||||
_maximizeGlyph = maxBadge.Icon;
|
||||
_restoreGlyph = maxBadge.Icon;
|
||||
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
|
||||
_maxMaxPath = "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z";
|
||||
|
||||
var titleBar = new Border
|
||||
{
|
||||
Height = 34,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto,Auto,Auto"),
|
||||
Margin = new Thickness(0, 0, 10, 0),
|
||||
Children = { titleText, helpButton, minimizeButton, maximizeButton, closeButton }
|
||||
}
|
||||
};
|
||||
titleBar.PointerPressed += OnTitleBarPointerPressed;
|
||||
// 双击标题栏 = 最大化 / 还原(与系统标题栏一致)
|
||||
titleBar.DoubleTapped += (_, e) =>
|
||||
{
|
||||
if (e.Source is Button) return;
|
||||
ToggleMaximize();
|
||||
};
|
||||
_maximizeButton = maximizeButton;
|
||||
_titleBar = titleBar;
|
||||
_helpButton = helpButton;
|
||||
_titleButtons.Add(minimizeButton);
|
||||
_titleButtons.Add(maximizeButton);
|
||||
_titleButtons.Add(closeButton);
|
||||
|
||||
var dock = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(titleBar, Dock.Top);
|
||||
dock.Children.Add(titleBar);
|
||||
dock.Children.Add(model.View);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
ClipToBounds = true,
|
||||
Child = dock
|
||||
};
|
||||
_frame = (Border)Content;
|
||||
|
||||
// 最大化 / 还原时同步圆角与按钮图标
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == WindowStateProperty) UpdateMaximizeVisual();
|
||||
};
|
||||
|
||||
// 窗口随心拉大 / 拉小时,标题栏文字与按钮同比缩放。
|
||||
// 同时监听 Bounds 属性(不只是 SizeChanged),保证最大化/还原也立刻生效。
|
||||
SizeChanged += (_, _) => ApplyChromeScale();
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == BoundsProperty) ApplyChromeScale();
|
||||
};
|
||||
ApplyChromeScale();
|
||||
|
||||
KeyDown += OnKeyDown;
|
||||
Closed += OnClosed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让标题栏的文字与按钮尺寸跟随窗口大小。
|
||||
/// 以 1240px 宽为基准线性缩放,限制在 0.85–1.9 倍,
|
||||
/// 避免最大化到 4K 时按钮大得离谱、缩到最小又点不中。
|
||||
/// </summary>
|
||||
private void ApplyChromeScale()
|
||||
{
|
||||
if (Bounds.Width < 100) return;
|
||||
var scale = Math.Clamp(Bounds.Width / BaseWidth, 0.85, 1.9);
|
||||
|
||||
if (_titleBar != null) _titleBar.Height = Math.Round(BaseTitleBarHeight * scale);
|
||||
foreach (var b in _titleButtons)
|
||||
{
|
||||
b.Width = Math.Round(BaseButtonWidth * scale);
|
||||
b.Height = Math.Round(BaseButtonHeight * scale);
|
||||
b.FontSize = Math.Round(13 * scale, 1);
|
||||
b.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
if (_helpButton != null)
|
||||
{
|
||||
_helpButton.Height = Math.Round(26 * scale);
|
||||
_helpButton.FontSize = Math.Round(BaseHelpFont * scale, 1);
|
||||
_helpButton.Padding = new Thickness(Math.Round(12 * scale), 0);
|
||||
_helpButton.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
foreach (var g in _titleGlyphs)
|
||||
{
|
||||
g.Width = Math.Round(10 * scale, 1);
|
||||
g.Height = Math.Round(10 * scale, 1);
|
||||
g.StrokeThickness = Math.Round(1.5 * scale, 2);
|
||||
}
|
||||
if (_titleText != null)
|
||||
{
|
||||
_titleText.FontSize = Math.Round(BaseTitleFont * scale, 1);
|
||||
_titleText.Margin = new Thickness(Math.Round(14 * scale), 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>判断颜色是否属于浅色系(用于决定悬停用深色还是浅色)。</summary>
|
||||
private static bool IsLight(Color c)
|
||||
{
|
||||
// 相对亮度(sRGB 近似)
|
||||
var lum = (0.299 * c.R + 0.587 * c.G + 0.114 * c.B) / 255.0;
|
||||
return lum > 0.6;
|
||||
}
|
||||
|
||||
private void ToggleMaximize()
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
}
|
||||
|
||||
private void UpdateMaximizeVisual()
|
||||
{
|
||||
var max = WindowState == WindowState.Maximized || WindowState == WindowState.FullScreen;
|
||||
if (_maximizeGlyph != null)
|
||||
{
|
||||
// 只换 Data,不换控件对象(换对象会触发 "already has a parent")
|
||||
_maximizeGlyph.Data = Geometry.Parse(max ? _maxRestorePath : _maxMaxPath);
|
||||
}
|
||||
if (_maximizeButton != null)
|
||||
{
|
||||
Avalonia.Controls.ToolTip.SetTip(_maximizeButton, max
|
||||
? (IsEnglish() ? "Restore" : "还原")
|
||||
: (IsEnglish() ? "Maximize" : "最大化"));
|
||||
}
|
||||
// 最大化后同样保留圆角(用户要求:任何状态都要圆角)
|
||||
if (_frame != null) _frame.CornerRadius = new CornerRadius(16);
|
||||
}
|
||||
|
||||
private static Color ParseColor(string? hex, string fallback)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(hex))
|
||||
{
|
||||
try { return Color.Parse(hex!); }
|
||||
catch { /* 模型写错颜色时退回默认 */ }
|
||||
}
|
||||
return Color.Parse(fallback);
|
||||
}
|
||||
|
||||
private static bool IsEnglish() => L.I.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 「如何使用?」:读取模型自带数据目录里的 help.json(中英双语),
|
||||
/// 用与标题栏一致的配色弹出一个独立小窗。说明内容完全由模型提供,启动器不内置文案。
|
||||
/// </summary>
|
||||
private void ShowHelp(ModelPackage package, Color barBg, Color barBorder, Color barText,
|
||||
Color btnText, Color frameBg)
|
||||
{
|
||||
var lang = IsEnglish() ? "en" : "zh-CN";
|
||||
var file = Path.Combine(package.DataDirectory, "help.json");
|
||||
string title = IsEnglish() ? "How to use" : "如何使用";
|
||||
// 分节内容:每节一个标题 + 若干条说明;兼容旧的扁平 lines 格式
|
||||
var sections = new List<(string Heading, List<string> Lines)>();
|
||||
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var root = doc.RootElement;
|
||||
var node = root.TryGetProperty(lang, out var exact) ? exact
|
||||
: root.TryGetProperty("zh-CN", out var zh) ? zh : root;
|
||||
if (node.TryGetProperty("title", out var t)) title = t.GetString() ?? title;
|
||||
|
||||
if (node.TryGetProperty("sections", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var sec in arr.EnumerateArray())
|
||||
{
|
||||
var heading = sec.TryGetProperty("h", out var h) ? h.GetString() ?? "" : "";
|
||||
var items = new List<string>();
|
||||
if (sec.TryGetProperty("lines", out var ls) && ls.ValueKind == JsonValueKind.Array)
|
||||
foreach (var item in ls.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add((heading, items));
|
||||
}
|
||||
}
|
||||
else if (node.TryGetProperty("lines", out var flat) && flat.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
var items = new List<string>();
|
||||
foreach (var item in flat.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add(("", items));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型帮助失败 {file}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
if (sections.Count == 0)
|
||||
sections.Add(("", new List<string>
|
||||
{
|
||||
IsEnglish() ? "This model has no usage notes yet." : "该模型暂未提供使用说明。"
|
||||
}));
|
||||
|
||||
var body = new StackPanel { Spacing = 6 };
|
||||
foreach (var (heading, items) in sections)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(heading))
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = heading,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 13.5,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
Margin = new Thickness(0, 12, 0, 2)
|
||||
});
|
||||
foreach (var line in items)
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = "• " + line,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
FontSize = 12.5,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 19
|
||||
});
|
||||
}
|
||||
|
||||
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
|
||||
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
|
||||
var helpCross = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10, Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpClose = new Button
|
||||
{
|
||||
Content = helpCross,
|
||||
Width = 34,
|
||||
Height = 26,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(6, 0, 0, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
helpClose.PointerEntered += (_, _) =>
|
||||
{
|
||||
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
|
||||
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
|
||||
helpCross.Stroke = new SolidColorBrush(Colors.White);
|
||||
};
|
||||
helpClose.PointerExited += (_, _) =>
|
||||
{
|
||||
helpClose.Background = Brushes.Transparent;
|
||||
helpCross.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
|
||||
var helpTitle = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpBarGrid = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
|
||||
Margin = new Thickness(22, 0, 14, 0)
|
||||
};
|
||||
helpBarGrid.Children.Add(helpTitle);
|
||||
Grid.SetColumn(helpClose, 1);
|
||||
helpBarGrid.Children.Add(helpClose);
|
||||
|
||||
var helpTitleBar = new Border
|
||||
{
|
||||
Height = 48,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = helpBarGrid
|
||||
};
|
||||
helpTitleBar.PointerPressed += (_, e) =>
|
||||
{
|
||||
if (e.GetCurrentPoint(helpTitleBar).Properties.IsLeftButtonPressed)
|
||||
helpClose.FindAncestorOfType<Window>()?.BeginMoveDrag(e);
|
||||
};
|
||||
|
||||
// ── 底部固定操作条:无论正文多长,「知道了」始终可见 ──
|
||||
var ok = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "Got it" : "知道了",
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Padding = new Thickness(20, 8),
|
||||
Background = new SolidColorBrush(Color.Parse("#2F6BFF")),
|
||||
Foreground = new SolidColorBrush(Colors.White),
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
var footer = new Border
|
||||
{
|
||||
Padding = new Thickness(24, 10, 24, 14),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 1, 0, 0),
|
||||
Child = ok
|
||||
};
|
||||
|
||||
// 标题栏(顶) + 正文(中,滚动) + 操作条(底,固定)
|
||||
var rootPanel = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(helpTitleBar, Dock.Top);
|
||||
rootPanel.Children.Add(helpTitleBar);
|
||||
DockPanel.SetDock(footer, Dock.Bottom);
|
||||
rootPanel.Children.Add(footer);
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
Content = new Border
|
||||
{
|
||||
Margin = new Thickness(24, 14, 24, 10),
|
||||
Child = body
|
||||
},
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled
|
||||
};
|
||||
rootPanel.Children.Add(scroll);
|
||||
|
||||
var win = new Window
|
||||
{
|
||||
Title = title,
|
||||
Width = 660,
|
||||
Height = Math.Min(760, 230 + sections.Sum(s => s.Lines.Count * 24 + 40)),
|
||||
MinWidth = 480,
|
||||
MinHeight = 320,
|
||||
Background = Brushes.Transparent,
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent },
|
||||
SystemDecorations = SystemDecorations.None,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = rootPanel
|
||||
}
|
||||
};
|
||||
ok.Click += (_, _) => win.Close();
|
||||
helpClose.Click += (_, _) => win.Close();
|
||||
win.Show(this);
|
||||
}
|
||||
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Escape:
|
||||
_ = CloseWithAnimationAsync();
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.F11:
|
||||
WindowState = WindowState == WindowState.FullScreen
|
||||
? WindowState.Normal
|
||||
: WindowState.FullScreen;
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
|
||||
/// 与主窗口的关闭动画保持同一节奏(180ms)。
|
||||
/// </summary>
|
||||
private async Task CloseWithAnimationAsync()
|
||||
{
|
||||
if (_closing) return;
|
||||
_closing = true;
|
||||
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(180),
|
||||
Easing = new CubicEaseIn()
|
||||
}
|
||||
};
|
||||
Opacity = 0;
|
||||
|
||||
await Task.Delay(190);
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
Content = null;
|
||||
_model?.Dispose();
|
||||
_model = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
|
||||
public sealed class ModelErrorWindow : Window
|
||||
{
|
||||
public ModelErrorWindow(string title, string message)
|
||||
{
|
||||
Title = title;
|
||||
Width = 560;
|
||||
Height = 340;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var lines = new List<Control>
|
||||
{
|
||||
new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
},
|
||||
new TextBlock
|
||||
{
|
||||
Text = message,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
},
|
||||
new Button
|
||||
{
|
||||
Content = "确定",
|
||||
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
|
||||
Padding = new Thickness(18, 6)
|
||||
}
|
||||
};
|
||||
|
||||
var panel = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(24),
|
||||
Spacing = 14
|
||||
};
|
||||
foreach (var line in lines) panel.Children.Add(line);
|
||||
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(12),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
internal sealed class ApplyOptions
|
||||
{
|
||||
public string UpdateDir { get; set; } = "";
|
||||
public string? InstallDir { get; set; }
|
||||
public int WaitPid { get; set; }
|
||||
public int TimeoutSeconds { get; set; } = 45;
|
||||
public bool RequireSignature { get; set; } = true;
|
||||
public bool DryRun { get; set; }
|
||||
public bool Force { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。
|
||||
/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。
|
||||
/// </summary>
|
||||
internal sealed class Applier
|
||||
{
|
||||
private static readonly Regex ArtifactPattern = new(
|
||||
@"^GC-(?<ver>.+?)-(?<plat>[^\-]+-[^\-]+)\.(app|exe)$",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private readonly ApplyOptions _options;
|
||||
private readonly Log _log;
|
||||
|
||||
public Applier(ApplyOptions options, Log log)
|
||||
{
|
||||
_options = options;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public int Run()
|
||||
{
|
||||
var updateDir = Path.GetFullPath(_options.UpdateDir);
|
||||
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
|
||||
|
||||
if (!File.Exists(requestPath))
|
||||
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3);
|
||||
|
||||
var request = Json.Read<SavedogRequest>(requestPath);
|
||||
if (request == null || string.IsNullOrWhiteSpace(request.Version))
|
||||
return Fail(updateDir, "更新申请内容不完整", 3);
|
||||
|
||||
if (!ValidName(request.PackageName))
|
||||
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3);
|
||||
|
||||
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})");
|
||||
|
||||
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
|
||||
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
|
||||
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试");
|
||||
|
||||
// 2. 安装目录定位与安全检查
|
||||
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
|
||||
? Path.GetFullPath(Path.Combine(updateDir, request.InstallRelative))
|
||||
: Path.GetFullPath(_options.InstallDir!);
|
||||
|
||||
if (!Directory.Exists(installDir))
|
||||
return Fail(updateDir, "安装目录不存在: " + installDir, 4);
|
||||
|
||||
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
|
||||
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4);
|
||||
|
||||
// 3. 二次验签:不信任「启动器说它验过了」
|
||||
var require = request.RequireSignature && SignatureKeyring.Enforced;
|
||||
var manifestPath = Path.Combine(updateDir, request.ManifestPath);
|
||||
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
||||
var verification = ManifestSignature.Verify(manifestText, require);
|
||||
|
||||
if (verification.IsRejected)
|
||||
{
|
||||
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}");
|
||||
return Refuse(updateDir, request, verification);
|
||||
}
|
||||
_log.Info($"清单可信度:{verification.Trust}" +
|
||||
(verification.KeyId != null ? $"({verification.KeyId})" : ""));
|
||||
|
||||
// 4. 校验更新包
|
||||
var zipPath = Path.Combine(updateDir, request.PackageZip);
|
||||
if (!File.Exists(zipPath))
|
||||
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5);
|
||||
|
||||
var zipInfo = new FileInfo(zipPath);
|
||||
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
|
||||
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5);
|
||||
|
||||
var actualSha = ContentHash.Sha256File(zipPath);
|
||||
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
|
||||
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.PackageSha256))
|
||||
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验");
|
||||
|
||||
SafeArchive.Inspection inspection;
|
||||
try
|
||||
{
|
||||
inspection = SafeArchive.Inspect(zipPath);
|
||||
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
|
||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5);
|
||||
}
|
||||
|
||||
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
|
||||
var stage = Path.Combine(updateDir, "stage");
|
||||
ClearDirectory(stage);
|
||||
try
|
||||
{
|
||||
SafeArchive.ExtractToDirectory(zipPath, stage);
|
||||
FlattenSingleDirectory(stage);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "解压失败: " + ex.Message, 6);
|
||||
}
|
||||
|
||||
var artifact = FindArtifact(stage, request.PackageName);
|
||||
if (artifact == null)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6);
|
||||
}
|
||||
|
||||
var target = Path.Combine(installDir, Path.GetFileName(artifact));
|
||||
var alreadyInstalled = File.Exists(target) || Directory.Exists(target);
|
||||
|
||||
if (_options.DryRun)
|
||||
{
|
||||
_log.Info($"[dry-run] 校验全部通过,将安装到 {target}");
|
||||
ClearDirectory(stage);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (alreadyInstalled)
|
||||
{
|
||||
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
|
||||
_log.Info("目标版本已存在,视为已安装");
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "applied",
|
||||
Version = request.Version,
|
||||
PackageName = Path.GetFileName(artifact),
|
||||
Verified = true,
|
||||
Message = "目标版本已存在,无需替换"
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 6. 移入安装目录(不覆盖任何已有文件)
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(installDir);
|
||||
if (Directory.Exists(artifact)) Directory.Move(artifact, target);
|
||||
else File.Move(artifact, target);
|
||||
_log.Info("新版已就位: " + Path.GetFileName(target));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7);
|
||||
}
|
||||
|
||||
// 7. 启动并看护
|
||||
var previous = ReadLastGood(updateDir);
|
||||
StartupHealth.Clear(updateDir);
|
||||
|
||||
Process? child;
|
||||
try
|
||||
{
|
||||
child = Launch(target);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
child = null;
|
||||
_log.Error("启动新版失败: " + ex.Message);
|
||||
}
|
||||
|
||||
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
|
||||
TimeSpan.FromSeconds(_options.TimeoutSeconds));
|
||||
|
||||
if (healthy)
|
||||
{
|
||||
_log.Info($"v{request.Version} 启动正常,更新完成");
|
||||
CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel);
|
||||
WriteLastGood(updateDir, request.Version, Path.GetFileName(target));
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "applied",
|
||||
Version = request.Version,
|
||||
PreviousVersion = previous?.Version,
|
||||
PackageName = Path.GetFileName(target),
|
||||
Verified = true,
|
||||
Message = "更新已应用"
|
||||
});
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 8. 回滚
|
||||
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚");
|
||||
TryKill(child);
|
||||
var removed = RemoveNewVersion(target);
|
||||
_log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除");
|
||||
|
||||
var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "rolledback",
|
||||
Version = request.Version,
|
||||
PreviousVersion = previous?.Version,
|
||||
PackageName = Path.GetFileName(target),
|
||||
Verified = true,
|
||||
Message = restored
|
||||
? "新版本未通过启动检查,已回滚到上一个版本"
|
||||
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
|
||||
});
|
||||
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
return 8;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 校验辅助
|
||||
|
||||
private static bool ValidName(string name)
|
||||
=> name.Length > 0 && name.Length < 200 &&
|
||||
name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 &&
|
||||
(name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static bool WaitForExit(int pid, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(pid);
|
||||
if (process.HasExited) return true;
|
||||
}
|
||||
catch (ArgumentException) { return true; } // 进程已不存在
|
||||
catch { return true; }
|
||||
Thread.Sleep(200);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void FlattenSingleDirectory(string stage)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(stage);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var temp = stage + "-flat";
|
||||
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
||||
Directory.Move(inner, temp);
|
||||
Directory.Delete(stage, true);
|
||||
Directory.Move(temp, stage);
|
||||
}
|
||||
|
||||
private static string? FindArtifact(string stage, string packageName)
|
||||
{
|
||||
var direct = Path.Combine(stage, packageName);
|
||||
if (File.Exists(direct) || Directory.Exists(direct)) return direct;
|
||||
|
||||
foreach (var entry in Directory.GetFileSystemEntries(stage))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry))
|
||||
return entry;
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry))
|
||||
return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 启动与看护
|
||||
|
||||
private Process? Launch(string target)
|
||||
{
|
||||
if (Directory.Exists(target))
|
||||
{
|
||||
// .app:优先直接启动内部可执行文件,这样才能拿到 pid 做看护
|
||||
var macOs = Path.Combine(target, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
var exe = Directory.GetFiles(macOs)
|
||||
.OrderByDescending(f => Path.GetFileName(f) == "GC")
|
||||
.FirstOrDefault();
|
||||
if (exe != null)
|
||||
{
|
||||
MakeExecutable(exe);
|
||||
return StartProcess(exe, Path.GetDirectoryName(exe)!);
|
||||
}
|
||||
}
|
||||
MakeExecutable(Path.Combine(target, "Contents", "MacOS", "GC"));
|
||||
var psi = new ProcessStartInfo("open") { UseShellExecute = false };
|
||||
psi.ArgumentList.Add("-n");
|
||||
psi.ArgumentList.Add(target);
|
||||
return Process.Start(psi);
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) MakeExecutable(target);
|
||||
return StartProcess(target, Path.GetDirectoryName(target)!);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Process? StartProcess(string exe, string workingDirectory)
|
||||
{
|
||||
var psi = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = workingDirectory
|
||||
};
|
||||
return Process.Start(psi);
|
||||
}
|
||||
|
||||
private static void MakeExecutable(string path)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return;
|
||||
var mode = File.GetUnixFileMode(path);
|
||||
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||
UnixFileMode.GroupExecute |
|
||||
UnixFileMode.OtherExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private bool WaitForHealth(string updateDir, string version, Process child, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
var health = StartupHealth.Read(updateDir);
|
||||
if (health != null && health.Ok && SameVersion(health.Version, version))
|
||||
{
|
||||
_log.Info($"收到健康标记(pid {health.Pid})");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (child.HasExited)
|
||||
{
|
||||
_log.Error($"新版进程已退出(退出码 {child.ExitCode})");
|
||||
return false;
|
||||
}
|
||||
Thread.Sleep(250);
|
||||
}
|
||||
|
||||
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
|
||||
if (!child.HasExited)
|
||||
{
|
||||
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool SameVersion(string a, string b)
|
||||
=> string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Normalize(string version)
|
||||
{
|
||||
var trimmed = version.Trim().TrimStart('v', 'V');
|
||||
var parts = trimmed.Split('.');
|
||||
var numbers = new List<string>();
|
||||
foreach (var part in parts)
|
||||
{
|
||||
if (!int.TryParse(part, out var n)) break;
|
||||
numbers.Add(n.ToString());
|
||||
}
|
||||
while (numbers.Count > 0 && numbers[^1] == "0") numbers.RemoveAt(numbers.Count - 1);
|
||||
return numbers.Count == 0 ? trimmed : string.Join('.', numbers);
|
||||
}
|
||||
|
||||
private static void TryKill(Process? process)
|
||||
{
|
||||
if (process == null) return;
|
||||
try
|
||||
{
|
||||
if (!process.HasExited) process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 清理 / 回滚
|
||||
|
||||
private void CleanupOldVersions(string installDir, string keepName, string platformLabel)
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
var match = ArtifactPattern.Match(name);
|
||||
if (!match.Success) continue;
|
||||
|
||||
var platform = match.Groups["plat"].Value;
|
||||
if (!string.Equals(platform, platformLabel, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_log.Info($"保留其它平台版本: {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(entry)) Directory.Delete(entry, true);
|
||||
else File.Delete(entry);
|
||||
_log.Info("清理旧版本: " + name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"清理旧版本失败 {name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool RemoveNewVersion(string target)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(target)) Directory.Delete(target, true);
|
||||
else if (File.Exists(target)) File.Delete(target);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("移除新版失败: " + ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
|
||||
string platformLabel)
|
||||
{
|
||||
// 优先用上次成功的版本;否则挑一个同平台的其它版本
|
||||
var candidates = new List<string>();
|
||||
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
|
||||
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
|
||||
|
||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
var match = ArtifactPattern.Match(name);
|
||||
if (!match.Success) continue;
|
||||
if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
candidates.Add(entry);
|
||||
}
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
|
||||
try
|
||||
{
|
||||
Launch(candidate);
|
||||
_log.Info("已回滚启动: " + Path.GetFileName(candidate));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 状态文件
|
||||
|
||||
private void WriteState(string updateDir, SavedogState state)
|
||||
{
|
||||
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
|
||||
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message); }
|
||||
}
|
||||
|
||||
private int Fail(string updateDir, string message, int code)
|
||||
{
|
||||
_log.Error(message);
|
||||
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
|
||||
return code;
|
||||
}
|
||||
|
||||
private int Refuse(string updateDir, SavedogRequest request, ManifestVerification verification)
|
||||
{
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "refused",
|
||||
Version = request.Version,
|
||||
PackageName = request.PackageName,
|
||||
Verified = false,
|
||||
Message = $"清单验签失败:{verification.Error}"
|
||||
});
|
||||
return 2;
|
||||
}
|
||||
|
||||
private static LastGoodVersion? ReadLastGood(string updateDir)
|
||||
=> Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||
|
||||
private static void WriteLastGood(string updateDir, string version, string packageName)
|
||||
{
|
||||
try
|
||||
{
|
||||
Json.Write(Path.Combine(updateDir, SavedogFiles.LastGood), new LastGoodVersion
|
||||
{
|
||||
Version = version,
|
||||
PackageName = packageName
|
||||
});
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void ClearDirectory(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try { if (File.Exists(path)) File.Delete(path); } catch { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
GC-SAVEDOG —— 启动器更新守护进程。
|
||||
|
||||
为什么不把替换逻辑留在启动器里:
|
||||
· 启动器正在运行,Windows 上无法覆盖自己的 exe;
|
||||
· 覆盖失败(断电 / 占用 / 权限)时启动器已经退出,没人能回滚;
|
||||
· 更新逻辑需要访问私钥验签,放在独立的最小进程里更容易审计。
|
||||
|
||||
本进程只做四件事:验签 → 校验 → 替换 → 看护(不健康就回滚)。
|
||||
它不引用 Avalonia,也不引用启动器程序集,源码里只链接 GC/src/Security/ 下的
|
||||
安全原语,保证「校验逻辑与启动器完全同一份实现」。
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Savedog</RootNamespace>
|
||||
<AssemblyName>GC-SAVEDOG</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
|
||||
<!--
|
||||
裁剪发布:自包含单文件不裁剪约 70MB,裁剪后 14MB 左右。
|
||||
守护进程要跟着更新包一起下发,体积直接影响下载与校验时间。
|
||||
|
||||
裁剪的前提是**不用运行时反射**:JSON 全部走 SavedogJsonContext 的源生成类型信息
|
||||
(见 SavedogJson.cs)。若给这里新加类型却忘了注册,未裁剪的调试构建看不出来,
|
||||
只有发布产物会在运行时报 NotSupportedException —— 测试用例里有一次真实 apply,
|
||||
会覆盖到。
|
||||
-->
|
||||
<PublishTrimmed>true</PublishTrimmed>
|
||||
<TrimMode>full</TrimMode>
|
||||
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||
|
||||
<!-- 只保留必要的卫星资源,裁剪后再压一层体积 -->
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
||||
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
||||
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
|
||||
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。</summary>
|
||||
internal sealed class Log
|
||||
{
|
||||
private readonly string? _path;
|
||||
private readonly object _gate = new();
|
||||
|
||||
public Log(string? path) => _path = path;
|
||||
|
||||
public void Info(string message) => Write("INFO ", message);
|
||||
public void Warn(string message) => Write("WARN ", message);
|
||||
public void Error(string message) => Write("ERROR", message);
|
||||
|
||||
private void Write(string level, string message)
|
||||
{
|
||||
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
|
||||
Console.WriteLine(line);
|
||||
if (string.IsNullOrWhiteSpace(_path)) return;
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(_path!);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.AppendAllText(_path!, line + "\n");
|
||||
}
|
||||
}
|
||||
catch { /* 日志失败不能影响更新 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 命令行。
|
||||
///
|
||||
/// GC-SAVEDOG apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||
/// [--timeout 45] [--dry-run] [--json]
|
||||
/// GC-SAVEDOG verify --manifest <version.json> [--require 1] [--json]
|
||||
/// GC-SAVEDOG verify-model --dir <model/<id>> --id <id> [--json]
|
||||
/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11]
|
||||
/// GC-SAVEDOG sign --manifest <version.json> [--key .signing/gc-signing.pem]
|
||||
/// [--key-id ...] [--out <file>]
|
||||
/// GC-SAVEDOG status --update <.GC/update> [--json]
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private const string DefaultKeyId = "gc-2026-11";
|
||||
private const string DefaultKeyPath = ".signing/gc-signing.pem";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
try { Console.OutputEncoding = Encoding.UTF8; } catch { }
|
||||
|
||||
// 必须在任何 Json.Read/Write 之前接上源生成上下文(裁剪构建必需)
|
||||
SavedogJson.Initialize();
|
||||
|
||||
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||
{
|
||||
Help();
|
||||
return 0;
|
||||
}
|
||||
|
||||
var command = args[0].ToLowerInvariant();
|
||||
var rest = args.Skip(1).ToArray();
|
||||
var options = Parse(rest);
|
||||
|
||||
return command switch
|
||||
{
|
||||
"apply" => Apply(options),
|
||||
"verify" => Verify(options),
|
||||
"verify-model" => VerifyModel(options),
|
||||
"keygen" => Keygen(options),
|
||||
"sign" => Sign(options),
|
||||
"status" => Status(options),
|
||||
"version" or "--version" => PrintVersion(),
|
||||
_ => Unknown(command)
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ apply
|
||||
|
||||
private static int Apply(Dictionary<string, string> options)
|
||||
{
|
||||
var updateDir = Option(options, "update", "");
|
||||
if (string.IsNullOrWhiteSpace(updateDir))
|
||||
{
|
||||
Console.Error.WriteLine("apply 需要 --update <.GC/update>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var log = new Log(Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.Log));
|
||||
var applyOptions = new ApplyOptions
|
||||
{
|
||||
UpdateDir = updateDir,
|
||||
InstallDir = Option(options, "install", null),
|
||||
WaitPid = Int(options, "wait-pid", 0),
|
||||
TimeoutSeconds = Int(options, "timeout", 45),
|
||||
DryRun = Flag(options, "dry-run"),
|
||||
Force = Flag(options, "force"),
|
||||
RequireSignature = Int(options, "require-signature", 1) != 0
|
||||
};
|
||||
|
||||
var applier = new Applier(applyOptions, log);
|
||||
var code = applier.Run();
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
if (applyOptions.DryRun)
|
||||
{
|
||||
// dry-run 不落盘,state.json 里是上一次的真实结果,直接打印会误导调用方
|
||||
var request = Json.Read<SavedogRequest>(
|
||||
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.ApplyRequest));
|
||||
Console.WriteLine(Json.Serialize(new SavedogState
|
||||
{
|
||||
Status = code == 0 ? "checked" : "failed",
|
||||
Version = request?.Version ?? "",
|
||||
PackageName = request?.PackageName ?? "",
|
||||
Verified = code == 0,
|
||||
Message = code == 0 ? "校验全部通过(未安装,dry-run)" : "校验未通过(dry-run)"
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
var state = Json.Read<SavedogState>(
|
||||
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State));
|
||||
Console.WriteLine(Json.Serialize(state));
|
||||
}
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ verify
|
||||
|
||||
private static int Verify(Dictionary<string, string> options)
|
||||
{
|
||||
var manifest = Option(options, "manifest", "");
|
||||
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||
{
|
||||
Console.Error.WriteLine("verify 需要 --manifest <version.json>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var require = Int(options, "require", 1) != 0;
|
||||
var text = File.ReadAllText(manifest);
|
||||
var result = ManifestSignature.Verify(text, require);
|
||||
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
var report = new VerifyReport
|
||||
{
|
||||
Trust = result.Trust.ToString(),
|
||||
KeyId = result.KeyId,
|
||||
Error = result.Error
|
||||
};
|
||||
foreach (var key in SignatureKeyring.Keys)
|
||||
report.TrustedKeys.Add(new TrustedKey
|
||||
{
|
||||
KeyId = key.KeyId,
|
||||
Fingerprint = ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)
|
||||
});
|
||||
Console.WriteLine(Json.Serialize(report));
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"信任状态: {result.Trust}");
|
||||
if (result.KeyId != null) Console.WriteLine($"密钥: {result.KeyId}");
|
||||
if (result.Error != null) Console.WriteLine($"说明: {result.Error}");
|
||||
foreach (var key in SignatureKeyring.Keys)
|
||||
Console.WriteLine($"受信任公钥: {key.KeyId} ({ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)})");
|
||||
}
|
||||
|
||||
return result.IsTrusted ? 0 : 2;
|
||||
}
|
||||
|
||||
private static int VerifyModel(Dictionary<string, string> options)
|
||||
{
|
||||
var dir = Option(options, "dir", "");
|
||||
var id = Option(options, "id", "");
|
||||
if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
Console.Error.WriteLine("verify-model 需要 --dir <model 目录> --id <模型 id>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var result = ModelIntegrity.VerifyForLoad(Path.GetFullPath(dir), id);
|
||||
if (Flag(options, "json"))
|
||||
Console.WriteLine(Json.Serialize(new VerifyModelReport
|
||||
{
|
||||
Ok = result.Ok,
|
||||
Present = result.Present,
|
||||
Message = result.Message
|
||||
}));
|
||||
else
|
||||
Console.WriteLine($"{(result.Ok ? "OK" : "FAIL")} 记录={(result.Present ? "有" : "无")} {result.Message}");
|
||||
|
||||
return result.Ok ? 0 : 2;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ keygen / sign
|
||||
|
||||
private static int Keygen(Dictionary<string, string> options)
|
||||
{
|
||||
var outDir = Option(options, "out", ".signing")!;
|
||||
var keyId = Option(options, "key-id", DefaultKeyId)!;
|
||||
Directory.CreateDirectory(outDir);
|
||||
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var privatePath = Path.Combine(outDir, "gc-signing.pem");
|
||||
var publicPath = Path.Combine(outDir, "gc-signing.pub");
|
||||
|
||||
File.WriteAllText(privatePath, key.ExportPkcs8PrivateKeyPem());
|
||||
var publicBase64 = ManifestSignature.ExportPublicKeyBase64(key);
|
||||
File.WriteAllText(publicPath, publicBase64 + "\n");
|
||||
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(privatePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
catch { }
|
||||
|
||||
Console.WriteLine("已生成 ECDSA P-256 密钥对:");
|
||||
Console.WriteLine(" 私钥(绝不要提交): " + privatePath);
|
||||
Console.WriteLine(" 公钥(写进源码) : " + publicPath);
|
||||
Console.WriteLine(" keyId : " + keyId);
|
||||
Console.WriteLine(" 公钥 Base64 : " + publicBase64);
|
||||
Console.WriteLine(" 公钥指纹 : " + ManifestSignature.PublicKeyFingerprint(publicBase64));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("把下面一行加进 GC/src/Security/SignatureKeyring.cs 的 Keys 列表:");
|
||||
Console.WriteLine($" new KeyEntry(\"{keyId}\", \"{publicBase64}\"),");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Sign(Dictionary<string, string> options)
|
||||
{
|
||||
var manifest = Option(options, "manifest", "");
|
||||
var keyPath = Option(options, "key", DefaultKeyPath)!;
|
||||
var keyId = Option(options, "key-id",
|
||||
Environment.GetEnvironmentVariable("GC_SIGNING_KEY_ID") ?? DefaultKeyId)!;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||
{
|
||||
Console.Error.WriteLine("sign 需要 --manifest <version.json>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
using var key = ManifestSignature.TryLoadPrivateKey(keyPath);
|
||||
if (key == null)
|
||||
{
|
||||
Console.Error.WriteLine($"找不到可用的签名私钥: {Path.GetFullPath(keyPath)}");
|
||||
return 4;
|
||||
}
|
||||
|
||||
var text = File.ReadAllText(manifest);
|
||||
var signed = ManifestSignature.SignDocument(text, key, keyId);
|
||||
var output = Option(options, "out", manifest)!;
|
||||
File.WriteAllText(output, signed);
|
||||
|
||||
var check = ManifestSignature.Verify(signed, requireSignature: true);
|
||||
Console.WriteLine($"已签名: {output}({check.Trust})");
|
||||
return check.Trust == ManifestTrust.Verified ? 0 : 5;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status
|
||||
|
||||
private static int Status(Dictionary<string, string> options)
|
||||
{
|
||||
var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!);
|
||||
var state = Json.Read<SavedogState>(Path.Combine(updateDir, SavedogFiles.State));
|
||||
var lastGood = Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||
var health = StartupHealth.Read(updateDir);
|
||||
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
Console.WriteLine(Json.Serialize(new StatusReport
|
||||
{
|
||||
State = state,
|
||||
LastGood = lastGood,
|
||||
Health = health
|
||||
}));
|
||||
return 0;
|
||||
}
|
||||
|
||||
Console.WriteLine(state == null
|
||||
? "没有更新记录"
|
||||
: $"最近更新: {state.Status} v{state.Version} -> {state.Message}({state.At})");
|
||||
Console.WriteLine(lastGood == null
|
||||
? "上次成功版本: 未知"
|
||||
: $"上次成功版本: v{lastGood.Version}({lastGood.PackageName})");
|
||||
Console.WriteLine(health == null
|
||||
? "健康标记: 无"
|
||||
: $"健康标记: v{health.Version} pid={health.Pid} ok={health.Ok}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int PrintVersion()
|
||||
{
|
||||
Console.WriteLine("GC-SAVEDOG 1.0.0");
|
||||
Console.WriteLine("签名算法: " + ManifestSignature.Algorithm);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Unknown(string command)
|
||||
{
|
||||
Console.Error.WriteLine($"未知命令: {command}");
|
||||
Help();
|
||||
return 3;
|
||||
}
|
||||
|
||||
private static void Help()
|
||||
{
|
||||
Console.WriteLine("""
|
||||
GC-SAVEDOG —— 启动器更新守护进程
|
||||
|
||||
apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||
[--timeout 45] [--dry-run] [--force] [--json]
|
||||
verify --manifest <version.json> [--require 1] [--json]
|
||||
verify-model --dir <model/ID> --id <ID> [--json]
|
||||
keygen [--out .signing] [--key-id gc-2026-11]
|
||||
sign --manifest <version.json> [--key .signing/gc-signing.pem] [--out <file>]
|
||||
status --update <.GC/update> [--json]
|
||||
|
||||
退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚
|
||||
""");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 参数
|
||||
|
||||
private static Dictionary<string, string> Parse(string[] args)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var arg = args[i];
|
||||
if (!arg.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
map[arg] = "1";
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = arg[2..];
|
||||
var eq = name.IndexOf('=');
|
||||
if (eq > 0)
|
||||
{
|
||||
map[name[..eq]] = name[(eq + 1)..];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
map[name] = args[++i];
|
||||
continue;
|
||||
}
|
||||
map[name] = "1";
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static string? Option(Dictionary<string, string> options, string name, string? fallback)
|
||||
=> options.TryGetValue(name, out var value) ? value : fallback;
|
||||
|
||||
private static int Int(Dictionary<string, string> options, string name, int fallback)
|
||||
=> options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed)
|
||||
? parsed : fallback;
|
||||
|
||||
private static bool Flag(Dictionary<string, string> options, string name)
|
||||
=> options.TryGetValue(name, out var value) &&
|
||||
(value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效:
|
||||
/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛
|
||||
/// <c>NotSupportedException</c>。因此守护进程把所有 JSON 类型都注册进源生成上下文,
|
||||
/// 编译期生成类型信息,运行时零反射。
|
||||
///
|
||||
/// 新增需要读写的 JSON 类型时,记得在这里补一行 <c>[JsonSerializable]</c>,
|
||||
/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。
|
||||
/// </summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip)]
|
||||
[JsonSerializable(typeof(SavedogRequest))]
|
||||
[JsonSerializable(typeof(SavedogState))]
|
||||
[JsonSerializable(typeof(LastGoodVersion))]
|
||||
[JsonSerializable(typeof(StartupHealth.HealthRecord))]
|
||||
[JsonSerializable(typeof(ModelIntegrityFile))]
|
||||
[JsonSerializable(typeof(VerifyReport))]
|
||||
[JsonSerializable(typeof(StatusReport))]
|
||||
[JsonSerializable(typeof(VerifyModelReport))]
|
||||
internal partial class SavedogJsonContext : JsonSerializerContext
|
||||
{
|
||||
// 源生成器已提供 (JsonSerializerOptions) 构造函数;实例化时传入启动器的那套选项,
|
||||
// 让两边写出的 JSON 完全同款(中文不转成 \uXXXX、缩进一致),便于直接 diff 排查。
|
||||
}
|
||||
|
||||
/// <summary><c>verify --json</c> 的输出。</summary>
|
||||
internal sealed class VerifyReport
|
||||
{
|
||||
public string Trust { get; set; } = "";
|
||||
public string? KeyId { get; set; }
|
||||
public string? Error { get; set; }
|
||||
public List<TrustedKey> TrustedKeys { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class TrustedKey
|
||||
{
|
||||
public string KeyId { get; set; } = "";
|
||||
public string Fingerprint { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary><c>status --json</c> 的输出。</summary>
|
||||
internal sealed class StatusReport
|
||||
{
|
||||
public SavedogState? State { get; set; }
|
||||
public LastGoodVersion? LastGood { get; set; }
|
||||
public StartupHealth.HealthRecord? Health { get; set; }
|
||||
}
|
||||
|
||||
/// <summary><c>verify-model --json</c> 的输出。</summary>
|
||||
internal sealed class VerifyModelReport
|
||||
{
|
||||
public bool Ok { get; set; }
|
||||
public bool Present { get; set; }
|
||||
public string Message { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>把共享的 <see cref="Json"/> 接到源生成上下文上。</summary>
|
||||
internal static class SavedogJson
|
||||
{
|
||||
private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options));
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
Json.TypeInfoProvider = type => Context.GetTypeInfo(type);
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,21 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-BOOT", "GC-BOOT", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "main", "main", "{ABAA6554-252E-13CE-1B40-0464A7DBA771}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-DOWNLOAD", "GC-DOWNLOAD", "{BCA2AA3E-F98F-43A1-9D31-239103C303F7}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{F2BBD9FE-F148-5687-ED21-3ABA515A9B22}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-BOOT", "GC-BOOT\GC-BOOT.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio", "src\main\dotnet\EarthModelStudio\EarthModelStudio.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC", "GC", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.Tests", "src\test\dotnet\EarthModelStudio.Tests\EarthModelStudio.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Tests", "GC\src\test\dotnet\GC.Tests\GC.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.ModelSdk", "model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.ModelSdk", "model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}"
|
||||
EndProject
|
||||
@@ -35,6 +33,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Core", "GC\src\GC.Core.csproj", "{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{6C38EF76-7D14-0C76-0B88-84F29EAA96CD}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-DOWNLOAD", "GC-DOWNLOAD\GC-DOWNLOAD.csproj", "{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-SAVEDOG", "GC-SAVEDOG\GC-SAVEDOG.csproj", "{B169F2BF-9E60-40BF-824E-0486573DA65E}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -105,15 +111,48 @@ Global
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.Build.0 = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.Build.0 = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{ABAA6554-252E-13CE-1B40-0464A7DBA771} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{F2BBD9FE-F148-5687-ED21-3ABA515A9B22} = {ABAA6554-252E-13CE-1B40-0464A7DBA771}
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {F2BBD9FE-F148-5687-ED21-3ABA515A9B22}
|
||||
{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}
|
||||
@@ -123,5 +162,8 @@ Global
|
||||
{0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C}
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB}
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
|
||||
{6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,8 +1,8 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:EarthModelStudio.ViewModels"
|
||||
xmlns:views="using:EarthModelStudio.Views"
|
||||
x:Class="EarthModelStudio.App"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
xmlns:views="using:GC.Views"
|
||||
x:Class="GC.App"
|
||||
RequestedThemeVariant="Light">
|
||||
|
||||
<Application.DataTemplates>
|
||||
@@ -43,6 +43,6 @@
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://EarthModelStudio/Styles/AppTheme.axaml" />
|
||||
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -4,11 +4,11 @@ using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
using EarthModelStudio.Views;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
|
||||
namespace EarthModelStudio;
|
||||
namespace GC;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
@@ -29,9 +29,58 @@ public partial class App : Application
|
||||
return;
|
||||
}
|
||||
|
||||
var vm = new MainViewModel(services);
|
||||
var window = new MainWindow { DataContext = vm };
|
||||
// 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
|
||||
// MainViewModel 会扫描模型、加载封面、读设置,同步做会让
|
||||
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
|
||||
var window = new MainWindow();
|
||||
window.Show();
|
||||
|
||||
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
|
||||
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
|
||||
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion);
|
||||
|
||||
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
|
||||
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
|
||||
// 会导致 DataContext 一直是 null、主页面白屏。
|
||||
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
|
||||
// 这样窗口能立刻响应,不会卡在白屏。
|
||||
MainViewModel vm = null!;
|
||||
Task.Run(() => new MainViewModel(services))
|
||||
.ContinueWith(t =>
|
||||
{
|
||||
vm = t.Result;
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
window.DataContext = vm;
|
||||
WireMainViewModel(vm, window, services, desktop);
|
||||
}, Avalonia.Threading.DispatcherPriority.Background);
|
||||
}, System.Threading.Tasks.TaskScheduler.Default);
|
||||
|
||||
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
|
||||
try
|
||||
{
|
||||
using var iconStream = Avalonia.Platform.AssetLoader.Open(
|
||||
new Uri("avares://GC.Core/Assets/icon.png"));
|
||||
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
|
||||
}
|
||||
catch { /* 图标缺失不影响启动 */ }
|
||||
|
||||
desktop.MainWindow = window;
|
||||
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
|
||||
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
|
||||
/// </summary>
|
||||
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
|
||||
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
_ = desktop;
|
||||
vm.ConfirmHandler = async message =>
|
||||
{
|
||||
var dialog = new ConfirmWindow(message);
|
||||
@@ -51,19 +100,7 @@ public partial class App : Application
|
||||
return await dialog.ShowDialog<bool>(window);
|
||||
};
|
||||
|
||||
// 应用图标:窗口标题栏与任务栏也使用同一图标
|
||||
try
|
||||
{
|
||||
using var iconStream = Avalonia.Platform.AssetLoader.Open(
|
||||
new Uri("avares://EarthModelStudio/Assets/icon.png"));
|
||||
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
|
||||
}
|
||||
catch { /* 图标缺失不影响启动 */ }
|
||||
|
||||
desktop.MainWindow = window;
|
||||
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
|
||||
|
||||
// 主窗口已建好,后台检查模型 / 启动器更新,不阻塞界面
|
||||
// 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
|
||||
{
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(
|
||||
@@ -72,9 +109,6 @@ public partial class App : Application
|
||||
}
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
|
||||
private static int SelfTest(AppServices services)
|
||||
{
|
||||
@@ -15,7 +15,7 @@
|
||||
"home.installed": "Installed models",
|
||||
"home.count": "{0} models",
|
||||
"home.empty": "No models yet",
|
||||
"home.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.",
|
||||
"home.emptyHint": "Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.",
|
||||
"home.emptyAction": "Get models",
|
||||
"home.open": "Open folder",
|
||||
"home.delete": "Delete",
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
"home.installed": "已安装模型",
|
||||
"home.count": "{0} 个模型",
|
||||
"home.empty": "模型库还是空的",
|
||||
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。",
|
||||
"home.emptyHint": "启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。",
|
||||
"home.emptyAction": "去下载模型",
|
||||
"home.open": "打开目录",
|
||||
"home.delete": "删除",
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,21 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>EarthModelStudio</RootNamespace>
|
||||
<AssemblyName>EarthModelStudio</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<!-- 应用图标(Windows exe / 任务栏) -->
|
||||
<ApplicationIcon>Assets\icon.ico</ApplicationIcon>
|
||||
<RootNamespace>GC</RootNamespace>
|
||||
<AssemblyName>GC.Core</AssemblyName>
|
||||
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
|
||||
<Compile Remove="test\**\*.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -25,9 +22,8 @@
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- 模型契约:启动器与模型唯一的共享代码(不含任何渲染/业务) -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
|
||||
<ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+8
-2
@@ -2,7 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.Models;
|
||||
namespace GC.Models;
|
||||
|
||||
/// <summary>应用设置,持久化到 data/settings.json。</summary>
|
||||
public sealed class AppSettings
|
||||
@@ -38,7 +38,7 @@ public sealed class AppSettings
|
||||
public bool AutoUpdateOnStartup { get; set; } = true;
|
||||
|
||||
/// <summary>默认更新仓库地址。</summary>
|
||||
public string UpdateRepository { get; set; } = "https://gitcode.com/2509_92447106/GC";
|
||||
public string UpdateRepository { get; set; } = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
|
||||
public string? UpdateManifestUrl { get; set; }
|
||||
@@ -46,6 +46,12 @@ public sealed class AppSettings
|
||||
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
|
||||
public string? UpdateLocalRoot { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 要求版本清单必须带**有效签名**。默认开启:关闭后只警告不拦截,
|
||||
/// 等于放弃「清单被篡改」的防护,只建议在自建私有构建里临时关闭。
|
||||
/// </summary>
|
||||
public bool RequireSignedManifest { get; set; } = true;
|
||||
|
||||
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
|
||||
public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
|
||||
|
||||
+13
-1
@@ -1,7 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.Models;
|
||||
namespace GC.Models;
|
||||
|
||||
/// <summary>model/<id>/<id>.json 的内容。</summary>
|
||||
public sealed class ModelManifest
|
||||
@@ -28,6 +28,18 @@ public sealed class ModelManifest
|
||||
public string? License { get; set; }
|
||||
public string? UpdatedAt { get; set; }
|
||||
public string? MinAppVersion { get; set; }
|
||||
/// <summary>模型窗口标题栏配色(模型自带,跟随模型界面风格);缺省时用深色。</summary>
|
||||
public WindowChrome? Chrome { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>模型窗口自建标题栏的颜色,由模型清单提供。</summary>
|
||||
public sealed class WindowChrome
|
||||
{
|
||||
public string? TitleBar { get; set; }
|
||||
public string? TitleBorder { get; set; }
|
||||
public string? TitleText { get; set; }
|
||||
public string? Button { get; set; }
|
||||
public string? Frame { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ModelPackage
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 规范化 JSON:签名与验签必须对完全相同的字节做运算,
|
||||
/// 否则「同一份内容、不同缩进/键序」会得出不同签名。
|
||||
///
|
||||
/// 规则(写进 README,第三方可复现):
|
||||
/// 1. 对象键按 Unicode 码点升序递归排序
|
||||
/// 2. 无缩进、无多余空白,UTF-8 编码,不带 BOM
|
||||
/// 3. 数字沿用源文本(不做浮点重排)
|
||||
/// 4. 非 ASCII 字符不转义(Encoder = UnsafeRelaxedJsonEscaping)
|
||||
/// 5. 签名时先移除根级 <c>signature</c> 字段
|
||||
/// </summary>
|
||||
public static class CanonicalJson
|
||||
{
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
/// <summary>把 JSON 文本规范化;解析失败返回 null。</summary>
|
||||
public static byte[]? Normalize(string text, bool dropSignatureField)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
try
|
||||
{
|
||||
var node = JsonNode.Parse(text);
|
||||
if (node is not JsonObject obj) return null;
|
||||
if (dropSignatureField) obj.Remove("signature");
|
||||
var sorted = SortNode(obj);
|
||||
return Encoding.UTF8.GetBytes(sorted?.ToJsonString(Options) ?? "{}");
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode? SortNode(JsonNode? node)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case JsonObject obj:
|
||||
var result = new JsonObject();
|
||||
foreach (var pair in obj.OrderBy(p => p.Key, StringComparer.Ordinal))
|
||||
result[pair.Key] = SortNode(pair.Value);
|
||||
return result;
|
||||
|
||||
case JsonArray array:
|
||||
var list = new JsonArray();
|
||||
foreach (var item in array) list.Add(SortNode(item));
|
||||
return list;
|
||||
|
||||
default:
|
||||
return node?.DeepClone();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内容哈希(可复现的指纹算法)。
|
||||
///
|
||||
/// 算法固定如下,构建端与客户端必须完全一致,否则会误判为「被篡改」:
|
||||
/// <code>
|
||||
/// fileHash = SHA256(文件字节)
|
||||
/// dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接
|
||||
/// "<相对路径>\0<fileHash>\n" )
|
||||
/// </code>
|
||||
/// 相对路径统一用 <c>/</c> 分隔;跳过以 <c>.</c> 开头的文件、<c>bin/</c>、<c>obj/</c>、
|
||||
/// <c>*.user</c>;不包含时间戳、权限位、文件顺序等元数据 —— 同样内容必然同样哈希。
|
||||
/// </summary>
|
||||
public static class ContentHash
|
||||
{
|
||||
public static string Sha256Hex(byte[] data)
|
||||
=> Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant();
|
||||
|
||||
public static string Sha256Hex(string text)
|
||||
=> Sha256Hex(Encoding.UTF8.GetBytes(text));
|
||||
|
||||
public static string Sha256File(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>目录内所有参与分发的文件 -> { 相对路径 : sha256 }。</summary>
|
||||
public static Dictionary<string, string> MapFiles(string directory)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
if (!Directory.Exists(directory)) return map;
|
||||
|
||||
foreach (var file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var rel = Path.GetRelativePath(directory, file).Replace('\\', '/');
|
||||
if (!Distributable(rel)) continue;
|
||||
map[rel] = Sha256File(file);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>按上述算法计算目录指纹。</summary>
|
||||
public static string DirectoryHash(string directory)
|
||||
=> DirectoryHash(MapFiles(directory));
|
||||
|
||||
public static string DirectoryHash(IReadOnlyDictionary<string, string> files)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var pair in files.OrderBy(p => p.Key, StringComparer.Ordinal))
|
||||
builder.Append(pair.Key).Append('\0').Append(pair.Value).Append('\n');
|
||||
|
||||
return Sha256Hex(Encoding.UTF8.GetBytes(builder.ToString()));
|
||||
}
|
||||
|
||||
/// <summary>目录指纹;目录不存在时返回空串(区别于空目录的哈希)。</summary>
|
||||
public static string DirectoryHashOrEmpty(string directory)
|
||||
=> Directory.Exists(directory) ? DirectoryHash(directory) : "";
|
||||
|
||||
public static bool Distributable(string relativePath)
|
||||
{
|
||||
var rel = relativePath.Replace('\\', '/');
|
||||
if (rel.StartsWith('.')) return false;
|
||||
if (rel.Contains("/.")) return false;
|
||||
if (rel.StartsWith("bin/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.StartsWith("obj/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 把「远端拿到的清单文本」变成 <see cref="RepoVersion"/>,同时带上验签结论。
|
||||
///
|
||||
/// 设计上把「验签」和「允不允许用」分开:
|
||||
/// · 本方法只负责**如实报告**信任状态;
|
||||
/// · 允不允许安装由 <c>UpdateService</c> / <c>LauncherUpdater</c> 按策略决定。
|
||||
/// 这样开发态可以「警告但继续」,发布版可以「直接拒绝」,而解析逻辑只有一份。
|
||||
/// </summary>
|
||||
public static class ManifestLoader
|
||||
{
|
||||
public static RepoVersion? Parse(string? text, out ManifestVerification verification)
|
||||
{
|
||||
verification = ManifestSignature.Verify(text, requireSignature: true);
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
|
||||
RepoVersion? version;
|
||||
try
|
||||
{
|
||||
version = JsonSerializer.Deserialize<RepoVersion>(text!, Json.Options);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (version == null) return null;
|
||||
|
||||
// 平台键回填:RepoPackage 自己要能说出「我属于哪个 RID」,
|
||||
// 否则下载端无法推导 dist/<系统>-<架构> 这类兜底路径。
|
||||
foreach (var pair in version.Launcher.Packages)
|
||||
if (pair.Value != null) pair.Value.Rid = pair.Key;
|
||||
|
||||
version.SignatureTrust = verification.Trust.ToString();
|
||||
version.SignatureKeyId = verification.KeyId;
|
||||
version.SignatureError = verification.Error;
|
||||
return version;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>清单可信度。</summary>
|
||||
public enum ManifestTrust
|
||||
{
|
||||
/// <summary>签名有效,且密钥在受信任列表里。</summary>
|
||||
Verified,
|
||||
/// <summary>本机构建没有配置受信任密钥 —— 只能跳过验签(会打警告)。</summary>
|
||||
Skipped,
|
||||
/// <summary>清单没有签名,但客户端要求签名。</summary>
|
||||
Unsigned,
|
||||
/// <summary>有签名但验证失败:内容被改过 / 密钥不对 / 结构损坏。</summary>
|
||||
Invalid
|
||||
}
|
||||
|
||||
public sealed record ManifestVerification(ManifestTrust Trust, string? KeyId, string? Error)
|
||||
{
|
||||
public bool IsTrusted => Trust is ManifestTrust.Verified or ManifestTrust.Skipped;
|
||||
public bool IsRejected => Trust is ManifestTrust.Unsigned or ManifestTrust.Invalid;
|
||||
|
||||
public static ManifestVerification Ok(string keyId) => new(ManifestTrust.Verified, keyId, null);
|
||||
public static ManifestVerification Skip() => new(ManifestTrust.Skipped, null,
|
||||
"未配置受信任公钥,已跳过验签");
|
||||
public static ManifestVerification Bad(string error) => new(ManifestTrust.Invalid, null, error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 版本清单签名(ECDSA P-256 / SHA-256)。
|
||||
///
|
||||
/// 为什么不用 sha256 了事:sha256 只能证明「下载没坏」,不能证明「这份清单是我发的」。
|
||||
/// 仓库被入侵时攻击者可以同时改清单和 sha256 —— 只有签名需要**没有放进仓库**的私钥,
|
||||
/// 才能把「篡改清单」这条路堵死。
|
||||
///
|
||||
/// 为什么不自己实现 Ed25519:手写椭圆曲线实现出错就是静默失效。.NET 8 自带
|
||||
/// ECDSA P-256,跨平台、无第三方依赖,安全性等价于工程需要。
|
||||
///
|
||||
/// 信任链:内置公钥 → 验证 version.json → 得到各发布包的 sha256 → 校验下载到的 zip
|
||||
/// → 校验解压出的模型文件 → 加载 dll。
|
||||
/// </summary>
|
||||
public static class ManifestSignature
|
||||
{
|
||||
public const string Algorithm = "ECDSA-P256-SHA256";
|
||||
|
||||
private static readonly JsonSerializerOptions WriteOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 验签
|
||||
|
||||
/// <summary>
|
||||
/// 校验清单文本的签名。<paramref name="requireSignature"/> 为 true 时,
|
||||
/// 无签名视为失败;为 false 时无签名只返回 <see cref="ManifestTrust.Unsigned"/>,
|
||||
/// 由调用方决定是否放行(开发态用)。
|
||||
/// </summary>
|
||||
public static ManifestVerification Verify(string? text, bool requireSignature)
|
||||
{
|
||||
if (SignatureKeyring.Keys.Count == 0) return ManifestVerification.Skip();
|
||||
if (string.IsNullOrWhiteSpace(text)) return ManifestVerification.Bad("清单内容为空");
|
||||
|
||||
JsonObject root;
|
||||
try
|
||||
{
|
||||
root = JsonNode.Parse(text!) as JsonObject ?? throw new JsonException("根节点不是对象");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ManifestVerification.Bad("清单不是合法 JSON: " + ex.Message);
|
||||
}
|
||||
|
||||
if (root["signature"] is not JsonObject signature)
|
||||
return requireSignature
|
||||
? new ManifestVerification(ManifestTrust.Unsigned, null, "清单缺少签名")
|
||||
: new ManifestVerification(ManifestTrust.Unsigned, null, "清单未签名");
|
||||
|
||||
var keyId = signature["keyId"]?.GetValue<string>() ?? "";
|
||||
var value = signature["value"]?.GetValue<string>() ?? "";
|
||||
var alg = signature["alg"]?.GetValue<string>() ?? Algorithm;
|
||||
|
||||
if (!string.Equals(alg, Algorithm, StringComparison.OrdinalIgnoreCase))
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"不支持的签名算法: {alg}");
|
||||
if (value.Length == 0)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "签名为空");
|
||||
|
||||
var key = SignatureKeyring.Find(keyId);
|
||||
if (key == null)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"未知签名密钥: {keyId}");
|
||||
|
||||
var payload = CanonicalJson.Normalize(text!, dropSignatureField: true);
|
||||
if (payload == null)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "无法规范化清单");
|
||||
|
||||
try
|
||||
{
|
||||
var sig = Convert.FromBase64String(value);
|
||||
using var ecdsa = ECDsa.Create();
|
||||
ecdsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(key.PublicKeyBase64), out _);
|
||||
var ok = ecdsa.VerifyData(payload, sig, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
return ok
|
||||
? ManifestVerification.Ok(key.KeyId)
|
||||
: new ManifestVerification(ManifestTrust.Invalid, keyId, "签名与内容不符");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "验签异常: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 签名
|
||||
|
||||
/// <summary>用私钥给清单签名,返回写入了 <c>signature</c> 字段的新清单文本。</summary>
|
||||
public static string SignDocument(string text, ECDsa key, string keyId)
|
||||
{
|
||||
var payload = CanonicalJson.Normalize(text, dropSignatureField: true)
|
||||
?? throw new InvalidOperationException("清单不是合法 JSON,无法签名");
|
||||
|
||||
var signature = key.SignData(payload, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
var contentHash = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
|
||||
|
||||
var root = JsonNode.Parse(text) as JsonObject
|
||||
?? throw new InvalidOperationException("清单根节点不是对象");
|
||||
|
||||
root["signature"] = new JsonObject
|
||||
{
|
||||
["alg"] = Algorithm,
|
||||
["keyId"] = keyId,
|
||||
["value"] = Convert.ToBase64String(signature),
|
||||
["contentSha256"] = contentHash,
|
||||
["signedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
};
|
||||
|
||||
return root.ToJsonString(WriteOptions) + "\n";
|
||||
}
|
||||
|
||||
/// <summary>从 PEM 文件加载私钥(PKCS#8 或 SEC1 均可)。</summary>
|
||||
public static ECDsa? TryLoadPrivateKey(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
var pem = File.ReadAllText(path);
|
||||
if (pem.Contains("BEGIN", StringComparison.Ordinal) == false) return null;
|
||||
var key = ECDsa.Create();
|
||||
key.ImportFromPem(pem);
|
||||
return key;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>导出公钥(SPKI / Base64),用于写入客户端受信任列表。</summary>
|
||||
public static string ExportPublicKeyBase64(ECDsa key)
|
||||
=> Convert.ToBase64String(key.ExportSubjectPublicKeyInfo());
|
||||
|
||||
/// <summary>公钥指纹,便于人工核对两边的公钥是否一致。</summary>
|
||||
public static string PublicKeyFingerprint(string publicKeyBase64)
|
||||
=> Convert.ToHexString(SHA256.HashData(Convert.FromBase64String(publicKeyBase64)))
|
||||
.ToLowerInvariant()[..16];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>模型安装后落盘的完整性记录。</summary>
|
||||
public sealed class ModelIntegrityFile
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
public string Id { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型清单文件的 sha256。</summary>
|
||||
public string ManifestSha256 { get; set; } = "";
|
||||
/// <summary><id>.model 目录的目录指纹。</summary>
|
||||
public string FilesSha256 { get; set; } = "";
|
||||
/// <summary>关键文件(dll / json)逐文件哈希,用于加载前快速校验。</summary>
|
||||
public Dictionary<string, string> Files { get; set; } = new();
|
||||
public string InstalledAt { get; set; } = "";
|
||||
/// <summary>来源(远端源名 / 本地目录),便于排查。</summary>
|
||||
public string Source { get; set; } = "";
|
||||
}
|
||||
|
||||
public sealed record IntegrityResult(bool Ok, bool Present, string Message)
|
||||
{
|
||||
public static readonly IntegrityResult Missing =
|
||||
new(true, false, "没有完整性记录(本地/开发模型),跳过校验");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型包完整性校验:下载后复算、安装后落盘、加载前抽查。
|
||||
///
|
||||
/// 威胁模型:模型 dll 会被 <c>AssemblyLoadContext</c> 直接执行,等于任意代码。
|
||||
/// 如果版本清单被篡改(或本地文件被替换),攻击者就能让启动器加载他的 dll。
|
||||
/// 因此:
|
||||
/// 1. version.json(已签名)里带 manifestSha256 / filesSha256;
|
||||
/// 2. 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装;
|
||||
/// 3. 安装成功后写 <c><id>.integrity.json</c>;
|
||||
/// 4. 每次加载 dll 前抽查 dll / json 的哈希。
|
||||
/// </summary>
|
||||
public static class ModelIntegrity
|
||||
{
|
||||
public const string FileNameSuffix = ".integrity.json";
|
||||
|
||||
public static string IntegrityPath(string modelDirectory, string id)
|
||||
=> Path.Combine(modelDirectory, id + FileNameSuffix);
|
||||
|
||||
public static ModelIntegrityFile? Read(string modelDirectory, string id)
|
||||
=> Json.Read<ModelIntegrityFile>(IntegrityPath(modelDirectory, id));
|
||||
|
||||
public static void Write(string modelDirectory, string id, ModelIntegrityFile data)
|
||||
=> Json.Write(IntegrityPath(modelDirectory, id), data);
|
||||
|
||||
/// <summary>
|
||||
/// 计算某个模型包(清单 + 数据目录)的哈希。
|
||||
/// <paramref name="packageDirectory"/> 是包含 <c><id>.json</c> 与
|
||||
/// <c><id>.model/</c> 的那一层。
|
||||
/// </summary>
|
||||
public static (string ManifestSha256, string FilesSha256, Dictionary<string, string> Files)
|
||||
Compute(string packageDirectory, string id)
|
||||
{
|
||||
var manifestPath = Path.Combine(packageDirectory, id + ".json");
|
||||
var dataDir = Path.Combine(packageDirectory, id + ".model");
|
||||
|
||||
var manifestSha = File.Exists(manifestPath) ? ContentHash.Sha256File(manifestPath) : "";
|
||||
var files = ContentHash.MapFiles(dataDir);
|
||||
var filesSha = ContentHash.DirectoryHash(files);
|
||||
|
||||
var critical = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var pair in files)
|
||||
{
|
||||
if (!IsCritical(pair.Key)) continue;
|
||||
critical[id + ".model/" + pair.Key] = pair.Value;
|
||||
}
|
||||
if (manifestSha.Length > 0) critical[id + ".json"] = manifestSha;
|
||||
|
||||
return (manifestSha, filesSha, critical);
|
||||
}
|
||||
|
||||
/// <summary>加载前校验:只查会被执行 / 解析的文件,保证 <c>OpenModel</c> 不被明显拖慢。</summary>
|
||||
public static IntegrityResult VerifyForLoad(string packageDirectory, string id)
|
||||
{
|
||||
var record = Read(packageDirectory, id);
|
||||
if (record == null) return IntegrityResult.Missing;
|
||||
|
||||
if (!string.Equals(record.Id, id, StringComparison.Ordinal))
|
||||
return new IntegrityResult(false, true, $"完整性记录与模型 id 不符: {record.Id}");
|
||||
|
||||
foreach (var pair in record.Files)
|
||||
{
|
||||
var path = Path.Combine(packageDirectory, pair.Key.Replace('/', Path.DirectorySeparatorChar));
|
||||
if (!File.Exists(path))
|
||||
return new IntegrityResult(false, true, $"缺少文件: {pair.Key}");
|
||||
|
||||
var actual = ContentHash.Sha256File(path);
|
||||
if (!string.Equals(actual, pair.Value, StringComparison.OrdinalIgnoreCase))
|
||||
return new IntegrityResult(false, true, $"文件已被修改: {pair.Key}");
|
||||
}
|
||||
|
||||
return new IntegrityResult(true, true, "完整性校验通过");
|
||||
}
|
||||
|
||||
private static bool IsCritical(string relativePath)
|
||||
{
|
||||
var rel = relativePath.Replace('\\', '/');
|
||||
return rel.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".dylib", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".so", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:更新包来自网络,必须当成不可信输入处理。
|
||||
///
|
||||
/// 拦截:
|
||||
/// · zip slip(<c>../</c>、绝对路径、盘符、UNC)
|
||||
/// · 符号链接 / 硬链接条目(解压后可指向系统任意文件)
|
||||
/// · zip 炸弹(条目数过多、解压后总体积过大、压缩比异常)
|
||||
/// 逐条校验通过后**自己写文件**,不使用 <see cref="ZipFile.ExtractToDirectory(string,string)"/>,
|
||||
/// 避免框架在写入阶段才发现问题、留下半成品。
|
||||
/// </summary>
|
||||
public static class SafeArchive
|
||||
{
|
||||
/// <summary>单个包最多条目数。</summary>
|
||||
public const int MaxEntries = 20000;
|
||||
|
||||
/// <summary>解压后总体积上限(2 GiB)。</summary>
|
||||
public const long MaxUncompressedBytes = 2L * 1024 * 1024 * 1024;
|
||||
|
||||
/// <summary>单个条目解压上限(1 GiB)。</summary>
|
||||
public const long MaxSingleEntryBytes = 1L * 1024 * 1024 * 1024;
|
||||
|
||||
/// <summary>压缩比上限:超过视为 zip 炸弹。</summary>
|
||||
public const int MaxCompressionRatio = 200;
|
||||
|
||||
public sealed record Inspection(int Entries, long UncompressedBytes, long CompressedBytes)
|
||||
{
|
||||
public double Ratio => CompressedBytes <= 0 ? 0 : (double)UncompressedBytes / CompressedBytes;
|
||||
}
|
||||
|
||||
/// <summary>只检查不解压:条目数、体积、路径、链接。发现问题抛异常。</summary>
|
||||
public static Inspection Inspect(string zipPath)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(zipPath);
|
||||
long total = 0;
|
||||
var count = 0;
|
||||
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
count++;
|
||||
if (count > MaxEntries)
|
||||
throw new InvalidOperationException($"压缩包条目过多(>{MaxEntries}),疑似恶意包");
|
||||
|
||||
ValidateName(entry.FullName);
|
||||
AssertNotLink(entry);
|
||||
|
||||
if (entry.Length > MaxSingleEntryBytes)
|
||||
throw new InvalidOperationException($"条目过大: {entry.FullName}");
|
||||
|
||||
total += entry.Length;
|
||||
if (total > MaxUncompressedBytes)
|
||||
throw new InvalidOperationException("解压后体积超出上限,疑似 zip 炸弹");
|
||||
}
|
||||
|
||||
var compressed = new FileInfo(zipPath).Length;
|
||||
var inspection = new Inspection(count, total, compressed);
|
||||
if (compressed > 0 && inspection.Ratio > MaxCompressionRatio && total > 64L * 1024 * 1024)
|
||||
throw new InvalidOperationException($"压缩比异常({inspection.Ratio:0.#}:1),疑似 zip 炸弹");
|
||||
|
||||
return inspection;
|
||||
}
|
||||
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
Inspect(zipPath);
|
||||
|
||||
Directory.CreateDirectory(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.EndsWith("/", StringComparison.Ordinal))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetFullPath(Path.Combine(destFull, name)));
|
||||
continue;
|
||||
}
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
|
||||
var dir = Path.GetDirectoryName(target);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
|
||||
using (var source = entry.Open())
|
||||
using (var output = new FileStream(target, FileMode.Create, FileAccess.Write,
|
||||
FileShare.None, 81920, FileOptions.None))
|
||||
{
|
||||
source.CopyTo(output);
|
||||
}
|
||||
|
||||
TryApplyUnixMode(entry, target);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>校验条目名,拒绝一切能逃出目标目录的写法。</summary>
|
||||
public static void ValidateName(string fullName)
|
||||
{
|
||||
var name = fullName.Replace('\\', '/');
|
||||
if (name.Length == 0) throw new InvalidOperationException("压缩包含空文件名条目");
|
||||
if (name.StartsWith('/')) throw new InvalidOperationException($"压缩包含绝对路径: {fullName}");
|
||||
if (name.StartsWith("//")) throw new InvalidOperationException($"压缩包含 UNC 路径: {fullName}");
|
||||
if (name.Length >= 2 && name[1] == ':')
|
||||
throw new InvalidOperationException($"压缩包含盘符路径: {fullName}");
|
||||
|
||||
foreach (var segment in name.Split('/'))
|
||||
{
|
||||
if (segment == "..")
|
||||
throw new InvalidOperationException($"压缩包含父目录穿越: {fullName}");
|
||||
}
|
||||
|
||||
if (name.Contains('\0'))
|
||||
throw new InvalidOperationException($"压缩包含非法字符: {fullName}");
|
||||
}
|
||||
|
||||
/// <summary>Unix 模式下 S_IFLNK = 0xA000,符号链接条目一律拒绝。</summary>
|
||||
private static void AssertNotLink(ZipArchiveEntry entry)
|
||||
{
|
||||
var mode = (entry.ExternalAttributes >> 16) & 0xF000;
|
||||
if (mode == 0xA000)
|
||||
throw new InvalidOperationException($"压缩包含符号链接条目: {entry.FullName}");
|
||||
}
|
||||
|
||||
private static void TryApplyUnixMode(ZipArchiveEntry entry, string target)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
var mode = (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF);
|
||||
if (mode == 0) return;
|
||||
File.SetUnixFileMode(target, mode);
|
||||
}
|
||||
catch { /* 权限位设置失败不影响文件内容 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器 ↔ GC-SAVEDOG 的握手协议(都在 <c>.GC/update/</c> 下,全部相对路径)。
|
||||
///
|
||||
/// 流程:
|
||||
/// <code>
|
||||
/// launcher 下载并校验更新包
|
||||
/// -> 解压到 update/payload/
|
||||
/// -> 写 apply-request.json + 已验签的 version.json 副本
|
||||
/// -> 启动 GC-SAVEDOG apply --wait-pid <自己>
|
||||
/// -> 自己退出
|
||||
///
|
||||
/// GC-SAVEDOG
|
||||
/// -> 等父进程退出
|
||||
/// -> 重验签名 + 包 sha256 + 解压安全性
|
||||
/// -> 把 payload 移到安装目录(绝不覆盖已有版本)
|
||||
/// -> 启动新版,等 update/health.json
|
||||
/// -> 健康:删同平台旧版本;不健康:删新版、重启旧版
|
||||
/// -> 写 state.json(applied / rolledback / failed)
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static class SavedogFiles
|
||||
{
|
||||
public const string ApplyRequest = "apply-request.json";
|
||||
public const string State = "state.json";
|
||||
public const string Log = "savedog.log";
|
||||
public const string Health = StartupHealth.FileName;
|
||||
public const string LastGood = "last-good.json";
|
||||
|
||||
/// <summary>SAVEDOG 可执行文件名(各平台一致,Windows 带 .exe)。</summary>
|
||||
public static string ExecutableName =>
|
||||
OperatingSystem.IsWindows() ? "GC-SAVEDOG.exe" : "GC-SAVEDOG";
|
||||
}
|
||||
|
||||
/// <summary>启动器写入的更新申请。</summary>
|
||||
public sealed class SavedogRequest
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
|
||||
/// <summary>新版本号,如 1.0.8。</summary>
|
||||
public string Version { get; set; } = "";
|
||||
|
||||
public string Rid { get; set; } = "";
|
||||
|
||||
/// <summary>文件名里的平台标签,如 mac-arm64。</summary>
|
||||
public string PlatformLabel { get; set; } = "";
|
||||
|
||||
/// <summary>payload 里的新版本包名(GC-1.0.8-mac-arm64.app / .exe)。</summary>
|
||||
public string PackageName { get; set; } = "";
|
||||
|
||||
/// <summary>payload 目录(相对 update 目录)。</summary>
|
||||
public string PayloadDir { get; set; } = "payload";
|
||||
|
||||
/// <summary>已验签清单的副本(相对 update 目录),用于二次验签。</summary>
|
||||
public string ManifestPath { get; set; } = "version.json";
|
||||
|
||||
/// <summary>更新包 zip 路径(相对 update 目录),SAVEDOG 自己解压,不信任预解压目录。</summary>
|
||||
public string PackageZip { get; set; } = "package.zip";
|
||||
|
||||
/// <summary>更新包 sha256(来自已验签清单)。</summary>
|
||||
public string? PackageSha256 { get; set; }
|
||||
|
||||
public long PackageSize { get; set; }
|
||||
|
||||
/// <summary>是否强制要求清单签名。</summary>
|
||||
public bool RequireSignature { get; set; } = true;
|
||||
|
||||
/// <summary>安装目录(相对 update 目录),由启动器按实际路径算出。</summary>
|
||||
public string InstallRelative { get; set; } = "../..";
|
||||
|
||||
public string CreatedAt { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
}
|
||||
|
||||
/// <summary>SAVEDOG 的执行结果,写入 state.json 供界面显示。</summary>
|
||||
public sealed class SavedogState
|
||||
{
|
||||
public string Status { get; set; } = "unknown"; // applied | rolledback | failed | refused
|
||||
public string Version { get; set; } = "";
|
||||
public string? PreviousVersion { get; set; }
|
||||
public string PackageName { get; set; } = "";
|
||||
public string Message { get; set; } = "";
|
||||
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
public bool Verified { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>上次成功启动的版本信息,回滚时用。</summary>
|
||||
public sealed class LastGoodVersion
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public string PackageName { get; set; } = "";
|
||||
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 受信任的签名公钥。
|
||||
///
|
||||
/// 公钥是公开的,写在源码里没有问题;**私钥永远不进仓库**
|
||||
/// (放在仓库根 <c>.signing/</c>,已在 .gitignore 中)。
|
||||
///
|
||||
/// 轮换密钥:用 <c>GC-SAVEDOG keygen</c> 生成新的一对,把新公钥追加到这里,
|
||||
/// 旧公钥保留一个版本周期,避免老客户端直接失效。
|
||||
/// 也可用环境变量临时注入(测试 / 私有构建):
|
||||
/// <c>GC_TRUSTED_KEYS="id1:base64;id2:base64"</c>
|
||||
/// </summary>
|
||||
public static class SignatureKeyring
|
||||
{
|
||||
public sealed record KeyEntry(string KeyId, string PublicKeyBase64, string? Note = null);
|
||||
|
||||
private static readonly List<KeyEntry> KeysInternal = new()
|
||||
{
|
||||
// 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed
|
||||
new KeyEntry(
|
||||
"gc-2026-11",
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
|
||||
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
|
||||
"GC 主发布密钥")
|
||||
};
|
||||
|
||||
static SignatureKeyring() => LoadFromEnvironment();
|
||||
|
||||
public static IReadOnlyList<KeyEntry> Keys => KeysInternal;
|
||||
|
||||
/// <summary>是否配置了受信任密钥(配置了就必须验签)。</summary>
|
||||
public static bool Enforced => KeysInternal.Count > 0;
|
||||
|
||||
public static KeyEntry? Find(string? keyId)
|
||||
{
|
||||
if (KeysInternal.Count == 0) return null;
|
||||
foreach (var key in KeysInternal)
|
||||
if (string.Equals(key.KeyId, keyId, StringComparison.Ordinal))
|
||||
return key;
|
||||
// 未写 keyId 且只有一个密钥时容忍(早期构建产物)
|
||||
if (string.IsNullOrWhiteSpace(keyId) && KeysInternal.Count == 1) return KeysInternal[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>测试 / 私有分发用:追加一个受信任公钥。</summary>
|
||||
public static void Add(KeyEntry key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key.KeyId) || string.IsNullOrWhiteSpace(key.PublicKeyBase64)) return;
|
||||
if (Find(key.KeyId) != null) return;
|
||||
KeysInternal.Add(key);
|
||||
}
|
||||
|
||||
/// <summary>测试用:替换整个密钥环。</summary>
|
||||
public static void ReplaceAll(IEnumerable<KeyEntry> keys)
|
||||
{
|
||||
KeysInternal.Clear();
|
||||
foreach (var key in keys) KeysInternal.Add(key);
|
||||
}
|
||||
|
||||
private static void LoadFromEnvironment()
|
||||
{
|
||||
var raw = Environment.GetEnvironmentVariable("GC_TRUSTED_KEYS");
|
||||
if (string.IsNullOrWhiteSpace(raw)) return;
|
||||
foreach (var part in raw!.Split(';', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var idx = part.IndexOf(':');
|
||||
if (idx <= 0 || idx >= part.Length - 1) continue;
|
||||
var keyId = part[..idx].Trim();
|
||||
var value = part[(idx + 1)..].Trim();
|
||||
if (keyId.Length == 0 || value.Length == 0) continue;
|
||||
if (Find(keyId) != null) continue;
|
||||
KeysInternal.Add(new KeyEntry(keyId, value, "来自 GC_TRUSTED_KEYS"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动成功的健康标记。
|
||||
///
|
||||
/// 新版启动器启动后写这个文件;GC-SAVEDOG 在替换完程序后会等它出现,
|
||||
/// 等不到就回滚到旧版本 —— 这样「新版本一启动就崩」不会把用户卡死。
|
||||
/// </summary>
|
||||
public static class StartupHealth
|
||||
{
|
||||
public const string FileName = "health.json";
|
||||
|
||||
public static string PathFor(string updateRoot) => Path.Combine(updateRoot, FileName);
|
||||
|
||||
/// <summary>主窗口显示后调用:证明本次启动真的跑起来了。</summary>
|
||||
public static void MarkHealthy(string updateRoot, string version)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(updateRoot);
|
||||
Json.Write(PathFor(updateRoot), new HealthRecord
|
||||
{
|
||||
Version = version,
|
||||
Pid = Environment.ProcessId,
|
||||
At = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
Ok = true
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"写入健康标记失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static HealthRecord? Read(string updateRoot)
|
||||
=> Json.Read<HealthRecord>(PathFor(updateRoot));
|
||||
|
||||
public static void Clear(string updateRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = PathFor(updateRoot);
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public sealed class HealthRecord
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public int Pid { get; set; }
|
||||
public string At { get; set; } = "";
|
||||
public bool Ok { get; set; }
|
||||
}
|
||||
}
|
||||
+62
-20
@@ -1,24 +1,27 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||
/// <code>
|
||||
/// <安装目录>/
|
||||
/// EarthModelStudio(.exe | .app/...)
|
||||
/// GC(.exe | .app/...)
|
||||
/// .GC/
|
||||
/// settings.json 设置与已安装版本记录
|
||||
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
|
||||
/// model/ 模型(启动时下载)
|
||||
/// cache/ 下载缓存 / 原子替换暂存
|
||||
/// update/ 待下次启动应用的启动器更新包
|
||||
/// </code>
|
||||
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
|
||||
/// 开发态同样使用仓库根 .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; } = "";
|
||||
|
||||
@@ -28,7 +31,7 @@ public sealed class AppPaths
|
||||
/// <summary>.GC 目录。</summary>
|
||||
public string HomeRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>模型库,恒为 <HomeRoot>/model。</summary>
|
||||
/// <summary>模型库。</summary>
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
|
||||
@@ -36,7 +39,11 @@ public sealed class AppPaths
|
||||
|
||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
|
||||
|
||||
/// <summary>用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。</summary>
|
||||
public string ConfigRoot => Path.Combine(HomeRoot, "config");
|
||||
|
||||
public string SettingsFile => Path.Combine(ConfigRoot, "settings.json");
|
||||
|
||||
public bool IsDevelopment { get; private init; }
|
||||
public bool IsPortableModelRoot { get; private init; }
|
||||
@@ -47,22 +54,27 @@ public sealed class AppPaths
|
||||
|
||||
// 判定「当前目录」:程序实际所在的位置。
|
||||
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
|
||||
// · 源码版:仓库根(含 EarthModelStudio.sln 的目录)
|
||||
// · 源码版:仓库根(含 GC.sln 的目录)
|
||||
//
|
||||
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
|
||||
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
|
||||
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
var explicitHome = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
var repoRoot = explicitHome;
|
||||
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
|
||||
repoRoot = FindRepoRoot(baseDir);
|
||||
var isDev = !string.IsNullOrEmpty(repoRoot) &&
|
||||
File.Exists(Path.Combine(repoRoot!, "EarthModelStudio.sln"));
|
||||
File.Exists(Path.Combine(repoRoot!, "GC.sln"));
|
||||
|
||||
string installDir;
|
||||
if (isDev)
|
||||
{
|
||||
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里
|
||||
// 源码版:安装目录 = 仓库根
|
||||
installDir = repoRoot!;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(explicitHome) && Directory.Exists(explicitHome))
|
||||
{
|
||||
installDir = explicitHome;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
|
||||
@@ -111,13 +123,13 @@ public sealed class AppPaths
|
||||
home = CanWrite(portableHome)
|
||||
? portableHome
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"EarthModelStudio", ".GC");
|
||||
"GC", ".GC");
|
||||
}
|
||||
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
|
||||
? envModels!
|
||||
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
|
||||
: Path.Combine(home, "model");
|
||||
|
||||
return new AppPaths
|
||||
{
|
||||
@@ -137,7 +149,6 @@ public sealed class AppPaths
|
||||
Directory.CreateDirectory(dir);
|
||||
var probe = Path.Combine(dir, ".write-test");
|
||||
File.WriteAllText(probe, "ok");
|
||||
File.Delete(probe);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
@@ -147,7 +158,7 @@ public sealed class AppPaths
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从程序所在位置向上找仓库根(含 EarthModelStudio.sln 的目录)。
|
||||
/// 从程序所在位置向上找仓库根(含 GC.sln 的目录)。
|
||||
///
|
||||
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
|
||||
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
|
||||
@@ -165,7 +176,7 @@ public sealed class AppPaths
|
||||
var name = dir.Name;
|
||||
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
|
||||
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln")))
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln")))
|
||||
{
|
||||
// 再确认不是从「发布输出目录」里往上找来的
|
||||
if (IsUnderPublishOutput(start, dir.FullName)) return null;
|
||||
@@ -240,20 +251,51 @@ public sealed class AppPaths
|
||||
public void EnsureCreated()
|
||||
{
|
||||
Directory.CreateDirectory(HomeRoot);
|
||||
Directory.CreateDirectory(ConfigRoot);
|
||||
Directory.CreateDirectory(CacheRoot);
|
||||
Directory.CreateDirectory(ModelRoot);
|
||||
Directory.CreateDirectory(UpdateRoot);
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)
|
||||
MigrateLegacySettings();
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
|
||||
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
SyncDevelopmentModels();
|
||||
{
|
||||
var modelRoot = ModelRoot;
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
if (Directory.Exists(source))
|
||||
_developmentModelsSync = Task.Run(() => SyncDevelopmentModels(modelRoot, source));
|
||||
}
|
||||
}
|
||||
|
||||
private void SyncDevelopmentModels()
|
||||
public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>
|
||||
/// 老版本把设置放在 .GC/settings.json。现在设置归到 .GC/config/,
|
||||
/// 与 cache/ 分开(清缓存不会连带清掉语言、内存预算、离线源等配置)。
|
||||
/// 迁移只做一次:新位置不存在时才搬旧的。
|
||||
/// </summary>
|
||||
private void MigrateLegacySettings()
|
||||
{
|
||||
try
|
||||
{
|
||||
var legacy = Path.Combine(HomeRoot, "settings.json");
|
||||
if (!File.Exists(legacy) || File.Exists(SettingsFile)) return;
|
||||
Directory.CreateDirectory(ConfigRoot);
|
||||
File.Move(legacy, SettingsFile);
|
||||
Console.WriteLine("[paths] 设置已迁移到 .GC/config/settings.json");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"迁移旧设置失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SyncDevelopmentModels(string modelRoot, string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
if (!Directory.Exists(source)) return;
|
||||
foreach (var dir in Directory.GetDirectories(source))
|
||||
{
|
||||
@@ -262,7 +304,7 @@ public sealed class AppPaths
|
||||
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);
|
||||
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"));
|
||||
+16
-7
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>组合根:一处初始化所有服务。</summary>
|
||||
public sealed class AppServices
|
||||
@@ -10,13 +10,17 @@ public sealed class AppServices
|
||||
public AppPaths Paths { get; }
|
||||
public SettingsService Settings { get; }
|
||||
public ModelRepository Models { get; }
|
||||
public DownloadCenter Downloads { get; }
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public ModelSourceClient Sources { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public UpdateService Updates { get; }
|
||||
public IUpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
public ISourceSelector Selector { get; }
|
||||
public ILauncherUpdateService LauncherUpdates { get; }
|
||||
public IDownloadModule DownloadModule { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
@@ -24,11 +28,16 @@ public sealed class AppServices
|
||||
Settings = new SettingsService(paths);
|
||||
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
|
||||
Models = new ModelRepository(paths);
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, Models);
|
||||
var factory = DownloadModuleHost.Factory
|
||||
?? throw new InvalidOperationException("GC-DOWNLOAD 模块尚未注册");
|
||||
DownloadModule = factory.Create(paths, Settings, Models);
|
||||
Sources = DownloadModule.Sources;
|
||||
Downloads = DownloadModule.Downloads;
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
+6
-6
@@ -5,7 +5,7 @@ using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>GitCode 仓库的一位贡献者。</summary>
|
||||
public sealed class Contributor
|
||||
@@ -21,7 +21,7 @@ public sealed class Contributor
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["2509_92447106"] = "Morris"
|
||||
["Morris_1"] = "Morris"
|
||||
};
|
||||
|
||||
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
|
||||
@@ -54,7 +54,7 @@ public static class ContributorsService
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0");
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
@@ -63,13 +63,13 @@ public static class ContributorsService
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository.Trim();
|
||||
? SourcePreset.GitCode.HomeUrl : repository.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
|
||||
return "https://api.gitcode.com/api/v5/repos/Morris_1/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";
|
||||
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
|
||||
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
public interface IDownloadJob : INotifyPropertyChanged
|
||||
{
|
||||
RemoteModel Model { get; }
|
||||
string Id { get; }
|
||||
string Name { get; }
|
||||
string Version { get; }
|
||||
CancellationTokenSource Cts { get; }
|
||||
DownloadState State { get; set; }
|
||||
double Progress { get; set; }
|
||||
string StatusText { get; }
|
||||
string DetailText { get; }
|
||||
string? Error { get; set; }
|
||||
bool IsActive { get; }
|
||||
bool CanRetry { get; }
|
||||
bool IsDone { get; }
|
||||
void RefreshText();
|
||||
}
|
||||
|
||||
public interface IDownloadCenter
|
||||
{
|
||||
ObservableCollection<IDownloadJob> Jobs { get; }
|
||||
event Action? Installed;
|
||||
IDownloadJob Enqueue(RemoteModel model);
|
||||
void Cancel(IDownloadJob job);
|
||||
void Retry(IDownloadJob job);
|
||||
void Remove(IDownloadJob job);
|
||||
void ClearFinished();
|
||||
int ActiveCount { get; }
|
||||
}
|
||||
|
||||
public interface IModelSourceClient
|
||||
{
|
||||
Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IUpdateService
|
||||
{
|
||||
IModelRemote Remote { get; }
|
||||
void UseRemote(IModelRemote remote);
|
||||
Task<UpdateResult> RunAsync(bool force, IProgress<UpdateProgress>? progress, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface ISourceSelector
|
||||
{
|
||||
SourcePreset? Current { get; }
|
||||
System.Collections.Generic.IReadOnlyDictionary<string, long> LastLatency { get; }
|
||||
Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface ILauncherUpdateService
|
||||
{
|
||||
Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default);
|
||||
Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default);
|
||||
bool ScheduleApply(AppPaths paths, string packageName);
|
||||
bool TryApplyPending(AppPaths paths);
|
||||
}
|
||||
|
||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
||||
|
||||
public sealed class UpdateProgressInfo
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Stage { get; init; } = "";
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
public interface IDownloadModule
|
||||
{
|
||||
IDownloadCenter Downloads { get; }
|
||||
IModelSourceClient Sources { get; }
|
||||
IUpdateService Updates { get; }
|
||||
ISourceSelector Selector { get; }
|
||||
ILauncherUpdateService LauncherUpdates { get; }
|
||||
IModelRemote CreateRemote(SourcePreset preset);
|
||||
}
|
||||
|
||||
public interface IDownloadModuleFactory
|
||||
{
|
||||
IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models);
|
||||
bool TryApplyPending(AppPaths paths);
|
||||
}
|
||||
|
||||
public static class DownloadModuleHost
|
||||
{
|
||||
public static IDownloadModuleFactory? Factory { get; set; }
|
||||
}
|
||||
|
||||
public static class LauncherRuntimeInfo
|
||||
{
|
||||
private static string? _versionOverride;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
||||
var assembly = typeof(AppServices).Assembly;
|
||||
var version = assembly.GetName().Version;
|
||||
if (version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0))
|
||||
{
|
||||
var info = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<
|
||||
System.Reflection.AssemblyInformationalVersionAttribute>(assembly)?.InformationalVersion;
|
||||
if (!string.IsNullOrWhiteSpace(info) && Version.TryParse(info.Split('+')[0].Trim(), out var parsed))
|
||||
version = parsed;
|
||||
}
|
||||
return version == null
|
||||
? "0.0.0"
|
||||
: $"{Math.Max(0, version.Major)}.{Math.Max(0, version.Minor)}.{Math.Max(0, version.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var architecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
|
||||
System.Runtime.InteropServices.Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + architecture;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + architecture;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + architecture;
|
||||
return System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 源生成类型信息的提供者(可选)。
|
||||
///
|
||||
/// 启动器本身不做裁剪,走默认的反射序列化即可;GC-SAVEDOG 会被 PublishTrimmed
|
||||
/// 裁掉无参构造,反射序列化在运行时直接抛 <c>NotSupportedException</c>。
|
||||
/// 因此守护进程在启动时把本钩子指向 <c>JsonSerializerContext</c>,
|
||||
/// 让所有读写都走编译期生成的 <see cref="JsonTypeInfo{T}"/>。
|
||||
/// 这样「安全模块只有一份实现」的前提没有被破坏,只是换了元数据来源。
|
||||
/// </summary>
|
||||
public static Func<Type, JsonTypeInfo?>? TypeInfoProvider { get; set; }
|
||||
|
||||
public static T? Read<T>(string path)
|
||||
{
|
||||
if (!System.IO.File.Exists(path)) return default;
|
||||
return Deserialize<T>(System.IO.File.ReadAllText(path));
|
||||
}
|
||||
|
||||
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, Serialize(value));
|
||||
System.IO.File.Move(tmp, path, true);
|
||||
}
|
||||
|
||||
public static T? Deserialize<T>(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return default;
|
||||
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
|
||||
return info != null
|
||||
? JsonSerializer.Deserialize(text, info)
|
||||
: JsonSerializer.Deserialize<T>(text, Options);
|
||||
}
|
||||
|
||||
public static string Serialize<T>(T value)
|
||||
{
|
||||
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
|
||||
return info != null
|
||||
? JsonSerializer.Serialize(value, info)
|
||||
: JsonSerializer.Serialize(value, Options);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -6,9 +6,9 @@ using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using EarthModelStudio.Views;
|
||||
using GC.Views;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
|
||||
@@ -52,7 +52,7 @@ public static class LauncherUpdateFlow
|
||||
var progress = new Progress<UpdateProgressInfo>(p =>
|
||||
progressWindow.Report(p.Value, p.Stage));
|
||||
|
||||
var result = await LauncherUpdater.DownloadAsync(
|
||||
var result = await services.LauncherUpdates.DownloadAsync(
|
||||
services.Paths, services.Updates.Remote, progress);
|
||||
|
||||
if (result.State == UpdateRunState.Failed)
|
||||
@@ -68,7 +68,7 @@ public static class LauncherUpdateFlow
|
||||
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
|
||||
|
||||
// 4. 安排替换(下次启动生效 / 脚本接管重启)
|
||||
var scheduled = LauncherUpdater.ScheduleApply(
|
||||
var scheduled = services.LauncherUpdates.ScheduleApply(
|
||||
services.Paths, result.PackageName ?? "");
|
||||
|
||||
if (!scheduled)
|
||||
+2
-2
@@ -8,7 +8,7 @@ using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Data;
|
||||
using Avalonia.Platform;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
|
||||
public sealed class L : INotifyPropertyChanged
|
||||
@@ -75,7 +75,7 @@ public sealed class L : INotifyPropertyChanged
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"avares://EarthModelStudio/Assets/i18n/{code}.json");
|
||||
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(),
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动时运行内存分配(类似启动器的 -Xmx)。
|
||||
@@ -11,7 +11,7 @@ public sealed class MemoryBudget
|
||||
{
|
||||
public int BudgetMb { get; private set; } = 2048;
|
||||
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
|
||||
public long ManagedBytes => GC.GetTotalMemory(false);
|
||||
public long ManagedBytes => System.GC.GetTotalMemory(false);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
@@ -29,7 +29,7 @@ public sealed class MemoryBudget
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = GC.GetGCMemoryInfo();
|
||||
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);
|
||||
+68
-5
@@ -5,10 +5,10 @@ using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.ModelSdk;
|
||||
using GC.Models;
|
||||
using GC.ModelSdk;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
|
||||
@@ -71,6 +71,40 @@ public sealed class ModelHost
|
||||
|
||||
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);
|
||||
@@ -89,7 +123,8 @@ public sealed class ModelHost
|
||||
|
||||
if (factory.ApiVersion != SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致");
|
||||
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
|
||||
"请更新到匹配的版本");
|
||||
|
||||
var runtime = factory.Create();
|
||||
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
|
||||
@@ -118,6 +153,34 @@ public sealed class ModelHost
|
||||
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;
|
||||
@@ -176,7 +239,7 @@ public sealed class ModelLoadContext : AssemblyLoadContext
|
||||
{
|
||||
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"EarthModelStudio.ModelSdk",
|
||||
"GC.ModelSdk",
|
||||
"Avalonia",
|
||||
"Avalonia.Base",
|
||||
"Avalonia.Controls",
|
||||
+3
-2
@@ -2,9 +2,9 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
|
||||
@@ -20,6 +20,7 @@ public sealed class ModelRepository
|
||||
|
||||
public IReadOnlyList<ModelPackage> Scan()
|
||||
{
|
||||
_paths.WaitForDevelopmentModels();
|
||||
var result = new List<ModelPackage>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
|
||||
{
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelScanner
|
||||
{
|
||||
+1
-1
@@ -3,7 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// GitCode/Gitee v5 releases API 的一条 Release(字段做宽松解析,兼容多种返回格式)。
|
||||
@@ -0,0 +1,87 @@
|
||||
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();
|
||||
if (Current.UpdateRepository.Contains("gitcode.com/2509_92447106/GC", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Current.UpdateRepository = Current.UpdateRepository.Replace(
|
||||
"2509_92447106", "Morris_1", StringComparison.OrdinalIgnoreCase);
|
||||
Save();
|
||||
}
|
||||
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/Morris_1/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();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Shell
|
||||
{
|
||||
@@ -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/Morris_1/GC",
|
||||
ApiBase = "https://api.gitcode.com/api/v5",
|
||||
RawBase = "https://gitcode.com",
|
||||
Kind = "gitcode",
|
||||
RawStyle = "plain",
|
||||
Owner = "Morris_1",
|
||||
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;
|
||||
}
|
||||
}
|
||||
+52
-1
@@ -1,9 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
|
||||
public sealed class RepoVersion
|
||||
@@ -15,6 +16,20 @@ public sealed class RepoVersion
|
||||
public string ModelDir { get; set; } = "model";
|
||||
public RepoLauncher Launcher { get; set; } = new();
|
||||
public List<RepoModel> Models { get; set; } = new();
|
||||
|
||||
// ---- 验签结论(解析时填入,不参与序列化) ----------------------------
|
||||
|
||||
/// <summary>Verified / Skipped / Unsigned / Invalid。</summary>
|
||||
[JsonIgnore] public string SignatureTrust { get; set; } = "";
|
||||
|
||||
[JsonIgnore] public string? SignatureKeyId { get; set; }
|
||||
|
||||
[JsonIgnore] public string? SignatureError { get; set; }
|
||||
|
||||
/// <summary>清单是否可用:签名有效,或本机没有配置公钥(兼容期)。</summary>
|
||||
[JsonIgnore]
|
||||
public bool IsTrusted =>
|
||||
SignatureTrust is nameof(ManifestTrust.Verified) or nameof(ManifestTrust.Skipped);
|
||||
}
|
||||
|
||||
public sealed class RepoLauncher
|
||||
@@ -34,6 +49,19 @@ public sealed class RepoPackage
|
||||
public long Size { get; set; }
|
||||
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
|
||||
public string? AssetName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 仓库里的平台产物目录,如 <c>dist/mac-arm64</c>。
|
||||
/// 不发 Release、只把编译产物提交进仓库时,更新包就在这里找。
|
||||
/// 清单没写时由 <see cref="Rid"/> 推导。
|
||||
/// </summary>
|
||||
public string? Dir { get; set; }
|
||||
|
||||
/// <summary>包文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>;清单没写时按版本与平台标签拼。</summary>
|
||||
public string? Name { get; set; }
|
||||
|
||||
/// <summary>所属平台键(win-x64 / win-arm64 / osx-arm64 …),解析清单时按字典键填入。</summary>
|
||||
[JsonIgnore] public string Rid { get; set; } = "";
|
||||
}
|
||||
|
||||
public sealed class RepoModel
|
||||
@@ -42,6 +70,20 @@ public sealed class RepoModel
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
|
||||
public string Dir { get; set; } = "";
|
||||
|
||||
// ---- 完整性(由 VersionStamp 计算,签名覆盖这几个字段) ----------------
|
||||
|
||||
/// <summary>内容指纹(构建溯源,不参与版本比较)。</summary>
|
||||
public string? Build { get; set; }
|
||||
|
||||
/// <summary>模型清单 <id>.json 的 sha256。</summary>
|
||||
public string? ManifestSha256 { get; set; }
|
||||
|
||||
/// <summary><id>.model 目录的目录指纹(算法见 ContentHash)。</summary>
|
||||
public string? FilesSha256 { get; set; }
|
||||
|
||||
/// <summary>参与分发的文件数。</summary>
|
||||
public int Files { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>远端目录树里的一个条目。</summary>
|
||||
@@ -64,10 +106,19 @@ public sealed class RepoEntry
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次读到的清单**原始文本**(含 signature 字段),供 SAVEDOG 二次验签。
|
||||
/// 默认返回 null,表示该源不支持(调用方会退化为单次验签)。
|
||||
/// </summary>
|
||||
Task<string?> GetRawVersionTextAsync(CancellationToken ct) => Task.FromResult<string?>(null);
|
||||
}
|
||||
|
||||
public sealed class UpdateProgress
|
||||
File renamed without changes.
+4
-4
@@ -4,9 +4,9 @@ using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
|
||||
public partial class AboutViewModel : ObservableObject
|
||||
@@ -29,10 +29,10 @@ public partial class AboutViewModel : ObservableObject
|
||||
public string AppName => "Morris GC";
|
||||
|
||||
/// <summary>启动器版本号,如 v1.0.2。</summary>
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
|
||||
public string PlatformText => UpdateService.CurrentRid;
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public string RepositoryText => _services.Settings.Current.UpdateRepository;
|
||||
|
||||
+46
-28
@@ -9,10 +9,10 @@ using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class DownloadViewModel : ObservableObject
|
||||
{
|
||||
@@ -25,7 +25,7 @@ public partial class DownloadViewModel : ObservableObject
|
||||
|
||||
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
|
||||
public ObservableCollection<DownloadJob> Jobs => _services.Downloads.Jobs;
|
||||
public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
|
||||
|
||||
[ObservableProperty] private SourceItemViewModel? _selectedSource;
|
||||
[ObservableProperty] private string _importUrl = "";
|
||||
@@ -109,30 +109,30 @@ public partial class DownloadViewModel : ObservableObject
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
|
||||
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task ImportAsync()
|
||||
{
|
||||
var url = ImportUrl.Trim();
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
var fastest = await _services.Selector.PickFastestAsync(force: true);
|
||||
var target = Sources.FirstOrDefault(x =>
|
||||
SourcePreset.Find(fastest.Id) != null &&
|
||||
SourcePreset.Detect(x.Model.Url).Id == fastest.Id);
|
||||
|
||||
if (target == null)
|
||||
{
|
||||
StatusMessage = L.I["dl.error.emptyUrl"];
|
||||
StatusMessage = "没有可用的下载源";
|
||||
return;
|
||||
}
|
||||
|
||||
var source = new ModelSource
|
||||
{
|
||||
Name = DeriveName(url),
|
||||
Url = url,
|
||||
Enabled = true
|
||||
};
|
||||
_services.Settings.Current.Sources.Add(source);
|
||||
_services.Settings.Save();
|
||||
|
||||
var item = new SourceItemViewModel(source, this, _services);
|
||||
Sources.Add(item);
|
||||
ImportUrl = "";
|
||||
SelectedSource = item;
|
||||
await LoadAsync(item, force: true);
|
||||
SelectedSource = target;
|
||||
var lat = _services.Selector.LastLatency;
|
||||
StatusMessage = $"已切换到 {fastest.Name}" +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
|
||||
await LoadAsync(target, force: true);
|
||||
}
|
||||
|
||||
private static string DeriveName(string url)
|
||||
@@ -173,6 +173,24 @@ public partial class DownloadViewModel : ObservableObject
|
||||
StatusMessage = L.I["dl.syncing"];
|
||||
try
|
||||
{
|
||||
// 第 6 项:下载页与启动更新用同一个源、同一种下载方式。
|
||||
// 每次加载前先让选择器给出最快源(有缓存,不会真的每次都测)。
|
||||
try
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(false, ct);
|
||||
if (fastest.Id != SourcePreset.Detect(source.Model.Url).Id)
|
||||
{
|
||||
var prefer = Sources.FirstOrDefault(x =>
|
||||
SourcePreset.Detect(x.Model.Url).Id == fastest.Id && x.Model.Enabled);
|
||||
if (prefer != null && prefer != source)
|
||||
{
|
||||
SelectedSource = prefer;
|
||||
source = prefer;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* 测速失败就沿用当前源 */ }
|
||||
|
||||
var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
|
||||
// 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
|
||||
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
|
||||
@@ -246,19 +264,19 @@ public partial class DownloadViewModel : ObservableObject
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void CancelJob(DownloadJob? job)
|
||||
private void CancelJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Cancel(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RetryJob(DownloadJob? job)
|
||||
private void RetryJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Retry(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveJob(DownloadJob? job)
|
||||
private void RemoveJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Remove(job);
|
||||
}
|
||||
@@ -273,17 +291,17 @@ public partial class DownloadViewModel : ObservableObject
|
||||
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.NewItems != null)
|
||||
foreach (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
if (e.OldItems != null)
|
||||
foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(DownloadJob.State))
|
||||
if (e.PropertyName == nameof(IDownloadJob.State))
|
||||
{
|
||||
if (sender is DownloadJob { State: DownloadState.Completed })
|
||||
if (sender is IDownloadJob { State: DownloadState.Completed })
|
||||
_services.Models.NotifyChanged();
|
||||
}
|
||||
UpdateJobState();
|
||||
+3
-3
@@ -6,11 +6,11 @@ using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
using Avalonia.Media.Imaging;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class HomeViewModel : ObservableObject
|
||||
{
|
||||
+34
-6
@@ -1,11 +1,12 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class MainViewModel : ObservableObject
|
||||
{
|
||||
@@ -45,8 +46,8 @@ public partial class MainViewModel : ObservableObject
|
||||
|
||||
public event Action<ModelPackage>? PlayerRequested;
|
||||
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
public string PlatformText => UpdateService.CurrentRid;
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public MainViewModel(AppServices services)
|
||||
{
|
||||
@@ -135,8 +136,26 @@ public partial class MainViewModel : ObservableObject
|
||||
UpdateDetail = p.Detail ?? "";
|
||||
});
|
||||
|
||||
// 双源测速:Xhmcl / GitCode 取快的那个(第 5 项)。
|
||||
// 启动更新与下载页共用同一个选择器,保证两处用同一个源、同一种下载方式。
|
||||
UpdateStatus = "正在选择最快的下载源…";
|
||||
try
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(
|
||||
force, default);
|
||||
_services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
|
||||
var lat = _services.Selector.LastLatency;
|
||||
UpdateDetail = "源:" + fastest.Name +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
||||
}
|
||||
|
||||
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
|
||||
var latest = await LauncherUpdater.CheckAsync(_services.Updates.Remote);
|
||||
var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
|
||||
if (latest != null)
|
||||
{
|
||||
var agreed = LauncherUpdateHandler != null &&
|
||||
@@ -162,6 +181,15 @@ public partial class MainViewModel : ObservableObject
|
||||
UpdateDetail = result.Error ?? "";
|
||||
LauncherNotice = result.LauncherMessage ?? "";
|
||||
|
||||
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
|
||||
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
|
||||
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
|
||||
{
|
||||
UpdateStatus = "暂时连不上模型源,模型库为空";
|
||||
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
|
||||
return;
|
||||
}
|
||||
|
||||
// 模型下载完成后本次启动就刷新列表,立刻可用
|
||||
if (result.UpdatedModels > 0) Home.Refresh();
|
||||
|
||||
+5
-5
@@ -5,10 +5,10 @@ using System.Runtime.InteropServices;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public sealed class LanguageOption
|
||||
{
|
||||
@@ -156,8 +156,8 @@ public partial class SettingsViewModel : ObservableObject
|
||||
private void ClearCache()
|
||||
{
|
||||
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
System.GC.Collect();
|
||||
System.GC.WaitForPendingFinalizers();
|
||||
_services.Memory.Refresh();
|
||||
StatusMessage = L.I["set.cacheCleared"];
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
+28
-3
@@ -1,8 +1,8 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
xmlns:vm="using:EarthModelStudio.ViewModels"
|
||||
x:Class="EarthModelStudio.Views.AboutView"
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
x:Class="GC.Views.AboutView"
|
||||
x:DataType="vm:AboutViewModel">
|
||||
|
||||
<ScrollViewer>
|
||||
@@ -55,6 +55,31 @@
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock Classes="h2" Text="感谢" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="地理学科内容指导" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 开发者 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class AboutView : UserControl
|
||||
{
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.ConfirmWindow"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.ConfirmWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="440" SizeToContent="Height"
|
||||
CanResize="False" ShowInTaskbar="False"
|
||||
+1
-1
@@ -4,7 +4,7 @@ using Avalonia.Interactivity;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class ConfirmWindow : Window
|
||||
{
|
||||
+5
-6
@@ -1,7 +1,7 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.DownloadView">
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.DownloadView">
|
||||
|
||||
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
|
||||
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
|
||||
|
||||
<!-- 只允许 Xhmcl / GitCode 两个内置源;这里是对比测速并自动切换 -->
|
||||
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
|
||||
<TextBox Text="{Binding ImportUrl}" Watermark="{loc:Loc dl.importPlaceholder}" />
|
||||
<Button Classes="primary" Content="{loc:Loc dl.import}"
|
||||
<Button Classes="primary" Content="测速并切换到最快源"
|
||||
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
|
||||
</StackPanel>
|
||||
|
||||
@@ -31,8 +31,7 @@
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="✕"
|
||||
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
|
||||
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class DownloadView : UserControl
|
||||
{
|
||||
@@ -1,8 +1,8 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
xmlns:controls="using:EarthModelStudio.Controls"
|
||||
x:Class="EarthModelStudio.Views.HomeView">
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:controls="using:GC.Controls"
|
||||
x:Class="GC.Views.HomeView">
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="26,24,26,28" Spacing="18">
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class HomeView : UserControl
|
||||
{
|
||||
+1
-1
@@ -8,7 +8,7 @@ using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
|
||||
+22
-6
@@ -1,7 +1,7 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.MainWindow"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.MainWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="1220" Height="800"
|
||||
MinWidth="1040" MinHeight="700"
|
||||
@@ -22,7 +22,7 @@
|
||||
<!-- 自建标题栏 -->
|
||||
<Border x:Name="TitleBar" Grid.Row="0" Background="{DynamicResource TitleBarBg}"
|
||||
PointerPressed="OnTitleBarPointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto" Margin="16,0,8,0">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto,Auto" Margin="16,0,10,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
|
||||
<Border Width="22" Height="22" CornerRadius="7" Background="#1C2C4C">
|
||||
<TextBlock Text="◎" FontSize="13" Foreground="#8FB6FF"
|
||||
@@ -31,10 +31,26 @@
|
||||
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="12.5"
|
||||
FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<!-- 与模型窗口一致的纯矢量图标:无圆圈 -->
|
||||
<Button x:Name="MinimizeButton" Grid.Column="1" Classes="titlebtn"
|
||||
Content="—" Click="OnMinimizeClick" />
|
||||
<Button x:Name="CloseButton" Grid.Column="2" Classes="titlebtn close"
|
||||
Content="✕" Click="OnCloseClick" />
|
||||
Click="OnMinimizeClick">
|
||||
<Path Data="M1.5,5 L8.5,5" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="MaximizeButton" Grid.Column="2" Classes="titlebtn"
|
||||
Click="OnMaximizeClick">
|
||||
<Path x:Name="MaximizeGlyph" Data="M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z"
|
||||
Stroke="#A9B8D4" StrokeThickness="1.5" StrokeLineCap="Round"
|
||||
StrokeJoin="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="CloseButton" Grid.Column="3" Classes="titlebtn close"
|
||||
Click="OnCloseClick">
|
||||
<Path Data="M2,2 L8,8 M8,2 L2,8" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
+30
-4
@@ -10,11 +10,11 @@ using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
@@ -40,8 +40,21 @@ public partial class MainWindow : Window
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
Closed += OnClosed;
|
||||
|
||||
// 最大化 / 还原:切换图标(单框 ⇄ 双框),圆角始终保持
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property != WindowStateProperty) return;
|
||||
var max = WindowState == WindowState.Maximized;
|
||||
if (this.FindControl<Avalonia.Controls.Shapes.Path>("MaximizeGlyph") is { } glyph)
|
||||
glyph.Data = Avalonia.Media.Geometry.Parse(max
|
||||
? "M2.6,3.4 L7.4,3.4 L7.4,8.4 L2.6,8.4 Z M2.6,3.4 L2.6,1.6 L7.4,1.6 L7.4,6.6"
|
||||
: "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
if (Content is Border frame) frame.CornerRadius = new Avalonia.CornerRadius(16);
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>当前打开的模型窗口(每个模型一个独立窗口)。</summary>
|
||||
@@ -148,6 +161,14 @@ public partial class MainWindow : Window
|
||||
// ---- 自建标题栏 ------------------------------------------------------
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
// 双击标题栏 = 最大化 / 还原
|
||||
if (e.ClickCount == 2)
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
return;
|
||||
}
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
@@ -155,6 +176,11 @@ public partial class MainWindow : Window
|
||||
private void OnMinimizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState.Minimized;
|
||||
|
||||
private void OnMaximizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
|
||||
// 关闭动画:先淡出再真正 Close(第 4 项)
|
||||
private async void OnCloseClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.SettingsView">
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.SettingsView">
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="26,24,26,32" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class SettingsView : UserControl
|
||||
{
|
||||
+2
-2
@@ -4,9 +4,9 @@ using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。
|
||||
+4
-3
@@ -4,8 +4,8 @@
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>EarthModelStudio.Tests</RootNamespace>
|
||||
<AssemblyName>EarthModelStudio.Tests</AssemblyName>
|
||||
<RootNamespace>GC.Tests</RootNamespace>
|
||||
<AssemblyName>GC.Tests</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -14,7 +14,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../main/dotnet/EarthModelStudio/EarthModelStudio.csproj" />
|
||||
<ProjectReference Include="../../../GC.Core.csproj" />
|
||||
<ProjectReference Include="../../../../../GC-DOWNLOAD/GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+136
-26
@@ -2,25 +2,29 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using EarthModelStudio.Models;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using GC.Models;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using EarthModelStudio;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
using EarthModelStudio.Views;
|
||||
using GC;
|
||||
using GC.Download;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
|
||||
namespace EarthModelStudio.Tests;
|
||||
namespace GC.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
|
||||
/// 用法:dotnet run --project src/test/dotnet/EarthModelStudio.Tests -- build/screenshots
|
||||
/// 用法:dotnet run --project GC/src/test/dotnet/GC.Tests -- build/screenshots
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
@@ -29,6 +33,7 @@ internal static class Program
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
if (args.Length > 0 && args[0] == "--update-test")
|
||||
return RunUpdateTest(args.Length > 1 ? args[1] : FindRepoRoot());
|
||||
|
||||
@@ -76,7 +81,9 @@ internal static class Program
|
||||
|
||||
// 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/
|
||||
Directory.CreateDirectory(Path.Combine(remote, "model"));
|
||||
File.Copy(versionFile, Path.Combine(remote, "version.json"), true);
|
||||
var fixtureVersion = Json.Read<RepoVersion>(versionFile)!;
|
||||
fixtureVersion.Models.RemoveAll(model =>
|
||||
model.Id is not "earth-rotation" and not "earth-revolution");
|
||||
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
@@ -90,10 +97,32 @@ internal static class Program
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
|
||||
// 按远端实际内容重算完整性哈希(与 VersionStamp 同一算法),然后签名。
|
||||
// 客户端会复算这两项,不一致就拒绝安装 —— 这一步必须与构建端一致。
|
||||
foreach (var m in fixtureVersion.Models)
|
||||
{
|
||||
var computed = ModelIntegrity.Compute(Path.Combine(remote, "model", m.Id), m.Id);
|
||||
m.ManifestSha256 = computed.ManifestSha256;
|
||||
m.FilesSha256 = computed.FilesSha256;
|
||||
m.Files = computed.Files.Count;
|
||||
}
|
||||
|
||||
var signer = ManifestSignature.TryLoadPrivateKey(
|
||||
Path.Combine(repoRoot, ".signing", "gc-signing.pem"));
|
||||
if (signer == null)
|
||||
{
|
||||
Console.WriteLine("FAIL: 缺少签名私钥 .signing/gc-signing.pem,无法构造可信清单");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var remoteManifest = Path.Combine(remote, "version.json");
|
||||
WriteSigned(remoteManifest, fixtureVersion, signer);
|
||||
Console.WriteLine($"远端清单已签名({ManifestSignature.Algorithm})");
|
||||
|
||||
// EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局
|
||||
Environment.SetEnvironmentVariable("EMS_HOME", tmp);
|
||||
Environment.SetEnvironmentVariable("EMS_DATA", home);
|
||||
Environment.SetEnvironmentVariable("EMS_MODELS", modelRoot);
|
||||
Environment.SetEnvironmentVariable("EMS_MODELS", null);
|
||||
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1");
|
||||
|
||||
var paths = AppPaths.Discover();
|
||||
@@ -111,11 +140,13 @@ internal static class Program
|
||||
|
||||
Console.WriteLine($"运行目录: {paths.HomeRoot}");
|
||||
Console.WriteLine($"模型库: {paths.ModelRoot}");
|
||||
Check(paths.ModelRoot == modelRoot, ".GC/model 是下载目标");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/settings.json 已创建");
|
||||
Check(paths.ModelRoot == modelRoot, "模型安装目录位于 .GC/model");
|
||||
Check(paths.CacheRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "模型与启动器下载暂存位于 .GC/cache");
|
||||
Check(paths.UpdateRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "启动器更新位于 .GC/update");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/config/settings.json 已创建");
|
||||
|
||||
// 1) 首次启动:模型全部下载并立即落地
|
||||
var r1 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
var r1 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"首次启动: {r1.Message} 更新数={r1.UpdatedModels}");
|
||||
Check(r1.UpdatedModels == 2, "首次启动下载 2 个模型");
|
||||
foreach (var id in new[] { "earth-rotation", "earth-revolution" })
|
||||
@@ -128,12 +159,12 @@ internal static class Program
|
||||
}
|
||||
|
||||
// 2) 版本没变:不重复下载
|
||||
var r2 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
var r2 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"二次检查: {r2.Message} 更新数={r2.UpdatedModels}");
|
||||
Check(r2.UpdatedModels == 0, "版本未变时不重复下载");
|
||||
|
||||
// 3) 远端模型改版:只更新这一个,并且本次启动立即生效
|
||||
var rv = Json.Read<RepoVersion>(Path.Combine(remote, "version.json"))!;
|
||||
var rv = Json.Read<RepoVersion>(remoteManifest)!;
|
||||
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
|
||||
"version.json 里模型版本由构建自动生成");
|
||||
var changed = rv.Models[0];
|
||||
@@ -141,16 +172,25 @@ internal static class Program
|
||||
var stampName = "_version-stamp.txt";
|
||||
File.WriteAllText(Path.Combine(remote, "model", changed.Id,
|
||||
changed.Id + ".model", stampName), "new content");
|
||||
Json.Write(Path.Combine(remote, "version.json"), rv);
|
||||
var r3 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
|
||||
// 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝
|
||||
var changedHash = ModelIntegrity.Compute(Path.Combine(remote, "model", changed.Id), changed.Id);
|
||||
changed.ManifestSha256 = changedHash.ManifestSha256;
|
||||
changed.FilesSha256 = changedHash.FilesSha256;
|
||||
changed.Files = changedHash.Files.Count;
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var r3 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}");
|
||||
Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".model", stampName)),
|
||||
"新版本本次启动立即生效");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".integrity.json")),
|
||||
"安装后写入完整性记录");
|
||||
|
||||
// 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
|
||||
var rid = UpdateService.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {UpdateService.CurrentLauncherVersion}");
|
||||
var rid = LauncherRuntimeInfo.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
var stage = Path.Combine(tmp, "launcher-stage");
|
||||
Directory.CreateDirectory(stage);
|
||||
File.WriteAllText(Path.Combine(stage, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + ".exe"),
|
||||
@@ -158,19 +198,29 @@ internal static class Program
|
||||
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
|
||||
ZipFile.CreateFromDirectory(stage, zip);
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage { Url = zip };
|
||||
Json.Write(Path.Combine(remote, "version.json"), rv);
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(zip))).ToLowerInvariant(),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 造一个旧版在当前目录
|
||||
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe";
|
||||
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
|
||||
|
||||
var dl = LauncherUpdater.DownloadAsync(paths, updater.Remote, null).GetAwaiter().GetResult();
|
||||
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"启动器下载: {dl.Message}");
|
||||
Check(dl.State == UpdateRunState.Ready, "启动器下载成功");
|
||||
Check(!string.IsNullOrWhiteSpace(dl.PackageName), "得到新版包名");
|
||||
Check(File.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")),
|
||||
"新版已存到当前目录");
|
||||
Check(File.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")) ||
|
||||
Directory.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")),
|
||||
"新版暂存于 .GC/update/payload");
|
||||
Check(!File.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")),
|
||||
"下载阶段不会把新版写入安装目录");
|
||||
Check(File.Exists(Path.Combine(paths.InstallDirectory, oldName)),
|
||||
"旧版仍在(删除由替换脚本在重启后做)");
|
||||
|
||||
@@ -188,10 +238,63 @@ internal static class Program
|
||||
Check(script.Contains("GC-*.app") || script.Contains("GC-*"), "脚本按 GC-* 匹配删除");
|
||||
}
|
||||
|
||||
// 6) 断网兜底:保留本地模型,不清空
|
||||
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
|
||||
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
|
||||
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
|
||||
Directory.CreateDirectory(distDir);
|
||||
var distName = "GC-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip";
|
||||
var distZip = Path.Combine(distDir, distName);
|
||||
File.Copy(zip, distZip, true);
|
||||
|
||||
string Sha(string file) =>
|
||||
Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file))).ToLowerInvariant();
|
||||
|
||||
rv.Launcher.Version = "9.9.10";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Dir = "dist/" + LauncherUpdater.PlatformLabel,
|
||||
Name = distName,
|
||||
Sha256 = Sha(distZip),
|
||||
Size = new FileInfo(distZip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var dlDist = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"dist 目录更新: {dlDist.Message}");
|
||||
Check(dlDist.State == UpdateRunState.Ready, "仓库 dist/<系统>-<架构>/ 里的产物能找到并下载");
|
||||
// 包名来自 zip 内容(这里仍是 9.9.9 的文件),所以要断言清单版本
|
||||
Check(dlDist.Version == "9.9.10", "下载的确实是 dist 目录里声明的那个版本");
|
||||
|
||||
// 5c) 往 dist/ 里塞一个哈希不匹配的包:必须拒绝(sha256 来自已签名清单)
|
||||
File.WriteAllText(distZip, "evil payload");
|
||||
var dlEvil = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Check(dlEvil.State == UpdateRunState.Failed, "dist 目录里哈希不符的包被拒绝");
|
||||
|
||||
// 还原到 9.9.9,后面的篡改 / 断网用例继续用这份清单
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Sha(zip),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 6) 篡改检测:改一个字节但不重新签名 -> 必须判为不可信
|
||||
var tampered = File.ReadAllText(remoteManifest).Replace("\"9.9.9\"", "\"9.9.8\"");
|
||||
var tamperResult = ManifestSignature.Verify(tampered, requireSignature: true);
|
||||
Check(tamperResult.Trust == ManifestTrust.Invalid, "被篡改的清单验签失败");
|
||||
File.WriteAllText(remoteManifest, tampered);
|
||||
var r6 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r6.Outcome == UpdateOutcome.Unavailable, "清单被篡改时拒绝更新");
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 7) 断网兜底:保留本地模型,不清空
|
||||
var offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope"));
|
||||
var beforeCount = settings.Current.InstalledModelVersions.Count;
|
||||
var r5 = offline.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
var r5 = Task.Run(() => offline.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r5.Outcome == UpdateOutcome.Unavailable &&
|
||||
settings.Current.InstalledModelVersions.Count == beforeCount &&
|
||||
Directory.Exists(Path.Combine(modelRoot, "earth-rotation")),
|
||||
@@ -204,6 +307,13 @@ internal static class Program
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
|
||||
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
|
||||
{
|
||||
var text = JsonSerializer.Serialize(version, Json.Options) + "\n";
|
||||
File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-11"));
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
@@ -221,7 +331,7 @@ internal static class Program
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln"))) return dir.FullName;
|
||||
}
|
||||
return Directory.GetCurrentDirectory();
|
||||
}
|
||||
@@ -1,110 +1,216 @@
|
||||
# Earth Model Studio
|
||||
# GC
|
||||
|
||||
天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。
|
||||
|
||||
> **分层约定(重要)**
|
||||
> - `src/` = 启动器:扫描、下载、开窗口、显示加载进度、自检更新。**不渲染、不含任何模型内容、发布包不内置模型**。
|
||||
> - `GC/` = 启动器:扫描、下载、开窗口、显示加载进度。**不渲染、不含任何模型内容、发布包不内置模型**。
|
||||
> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。
|
||||
> - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。
|
||||
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,`src` 一行都不用改,客户端启动自动更新。
|
||||
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,启动器一行都不用改,客户端启动自动更新。
|
||||
> - `GC-SAVEDOG/` = 更新守护进程:验签、原子替换、启动后健康检查、失败回滚。
|
||||
|
||||
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
|
||||
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
|
||||
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译
|
||||
- 更新仓库:<https://gitcode.com/2509_92447106/GC>,模型目录 <https://gitcode.com/2509_92447106/GC/tree/main/model>
|
||||
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵)
|
||||
- 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model>
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 依赖:.NET 8 SDK(macOS 另需 Xcode Command Line Tools,用于 .icns / ditto)
|
||||
dotnet --version # 8.0.x
|
||||
./build.sh build # 三平台完整发布 -> dist/
|
||||
./build.sh run # 开发态直接运行(读仓库 model/,跳过在线替换)
|
||||
./build.sh check # 编译 + 自检 + 离屏渲染 + 产物检查
|
||||
```
|
||||
|
||||
Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run / test / update-test / pack-models / clean / doctor`)。
|
||||
`build.sh test` 的离屏渲染需要图形栈:Linux CI 上用 `xvfb-run ./build.sh test`。
|
||||
|
||||
## 运行目录(发布包里就长这样)
|
||||
|
||||
```
|
||||
<安装目录>/
|
||||
EarthModelStudio.exe | EarthModelStudio.app/
|
||||
GC.exe | GC.app/
|
||||
GC-SAVEDOG[.exe] 更新守护进程(与主程序同目录,macOS 在 .app/Contents/MacOS 内)
|
||||
.GC/
|
||||
settings.json 设置 + 已安装版本记录
|
||||
config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置)
|
||||
model/ 启动时下载的模型
|
||||
cache/ 下载暂存 / 原子替换
|
||||
update/ 待下次启动应用的启动器更新
|
||||
update/ 待应用的启动器更新(apply-request.json + package.zip)
|
||||
```
|
||||
|
||||
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
|
||||
安装目录不可写时自动退回用户数据目录。`.GC/` 可以随程序一起搬迁,也可以整个删掉重新下载。
|
||||
安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载;
|
||||
`.GC/config/settings.json` 删掉等于恢复出厂设置。
|
||||
|
||||
## 自动更新
|
||||
|
||||
| 检查项 | 不是最新版时 | 生效时机 |
|
||||
| --- | --- | --- |
|
||||
| 模型 | 从 gitcode 下载到 `cache/`,校验后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
|
||||
| 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) |
|
||||
| 模型 | 按文件清单下载到 `cache/`,校验哈希后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
|
||||
| 启动器 | 下载对应平台 zip 到 `.GC/update/`,交给 `GC-SAVEDOG` | **下次启动时应用**(重启后自动替换) |
|
||||
|
||||
- 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`:
|
||||
`https://gitcode.com/2509_92447106/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
||||
- 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**,
|
||||
所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。
|
||||
- `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。
|
||||
- 断网、仓库还没推 `version.json`、下载失败:**一律保留本地模型,绝不把模型库清空**,底部状态条说明原因。
|
||||
- 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。
|
||||
启动器更新的完整流程:
|
||||
|
||||
```
|
||||
启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出
|
||||
GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage
|
||||
-> 移入安装目录(绝不覆盖已有版本)
|
||||
-> 启动新版,等 .GC/update/health.json
|
||||
-> 收到:删同平台旧版本,写 last-good.json
|
||||
-> 没收到/进程退出:删新版、重启旧版,写 state.json = rolledback
|
||||
```
|
||||
|
||||
也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。
|
||||
|
||||
- 默认更新仓库写在 `.GC/config/settings.json` 的 `updateRepository`:
|
||||
`https://gitcode.com/Morris_1/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
||||
- 断网、仓库没推 `version.json`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
|
||||
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
|
||||
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
|
||||
`updateLocalRoot` 指向它,即可完全离线更新。
|
||||
- 发新版:把 `dist/GC-<rid>.zip` 上传到 Release / 仓库 `dist/`,把直链填进 `version.json`
|
||||
对应平台的 `url`(`./build.sh publish` 会生成 zip 并自动写入 `sha256` / `size`)。
|
||||
更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。
|
||||
`updateLocalRoot` 指向它,即可完全离线更新(同样会验签)
|
||||
|
||||
## 安全模型
|
||||
|
||||
威胁模型很直接:**模型 dll 会被 `AssemblyLoadContext` 直接执行**,启动器更新包会替换可执行文件。
|
||||
只要仓库被入侵,攻击者就能让所有客户端跑他的代码。因此信任链是:
|
||||
|
||||
```
|
||||
内置公钥(源码)
|
||||
└─ 验证 version.json 的 ECDSA P-256 签名
|
||||
├─ 得到启动器包 sha256 → 校验下载到的 zip
|
||||
│ └─ GC-SAVEDOG 再次验签 + 复算 sha256 + 检查 zip 结构 → 原子替换
|
||||
└─ 得到每个模型的 manifestSha256 / filesSha256
|
||||
└─ 下载后复算,比对通过才安装
|
||||
└─ 加载 dll 前抽查 dll / json 哈希(.integrity.json)
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
| 机制 | 防的是什么 | 代码位置 |
|
||||
| --- | --- | --- |
|
||||
| 清单签名(ECDSA P-256 / SHA-256) | 仓库被改、清单被替换 | `GC/src/Security/ManifestSignature.cs` |
|
||||
| 规范化 JSON(键排序、去 signature) | 「同内容不同字节」导致签名不可复现 | `GC/src/Security/CanonicalJson.cs` |
|
||||
| 包 sha256(取自已签名清单) | 下载被替换 / 传输损坏 | `GC/src/Security/ContentHash.cs` |
|
||||
| 模型 manifestSha256 / filesSha256 | 下载后、安装前被掉包 | `GC/src/Security/ModelIntegrity.cs` |
|
||||
| 加载前抽查 dll 哈希 | 本地模型文件被替换 | `GC/src/Services/ModelHost.cs` |
|
||||
| `SafeArchive`(条目数/体积/压缩比/符号链接/穿越) | zip 炸弹、zip slip、链接攻击 | `GC/src/Security/SafeArchive.cs` |
|
||||
| `GC-SAVEDOG` 独立进程 | 覆盖失败、断电、新版本起不来 | `GC-SAVEDOG/Applier.cs` |
|
||||
| 健康标记 + 回滚 | 新版启动即崩 | `GC/src/Security/StartupHealth.cs` |
|
||||
|
||||
默认策略:**清单没签名或签名不符一律拒绝更新**。
|
||||
自建私有构建可临时放开:`settings.json` 里 `requireSignedManifest: false`,
|
||||
或环境变量 `GC_ALLOW_UNSIGNED_MANIFEST=1`(只建议调试用)。
|
||||
|
||||
### 签名密钥
|
||||
|
||||
- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份)
|
||||
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`,指纹 `b41b1dd6259ea9ed`
|
||||
- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen`
|
||||
- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),再重新签名清单
|
||||
- 部署前核对两边公钥一致:
|
||||
`dotnet run --project GC-SAVEDOG -- verify --manifest version.json`
|
||||
|
||||
### zip 解压加固
|
||||
|
||||
更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接;
|
||||
条目数 ≤ 20000、解压后 ≤ 2 GiB、压缩比异常(>200:1 且体积较大)直接判为 zip 炸弹。
|
||||
|
||||
## 版本与指纹
|
||||
|
||||
- **启动器版本**:`Directory.Build.props` 的 `<Version>`;`./build.sh build -version=1.0.8` 可覆盖,
|
||||
只影响启动器(程序集版本、关于页、`version.json` 的 `launcher.version`)。
|
||||
- **模型版本**:模型清单里**作者手写**的 `version`(如 `1.6`),`./build.sh stamp` 不会改它。
|
||||
客户端按字符串比较是否变化,所以改模型内容后必须手动升版本号,否则用户不会更新。
|
||||
- **`build` 字段**:模型内容的构建指纹,只用于溯源;`updatedAt` / `build` 都不参与指纹计算,
|
||||
保证「同一份内容重复构建得到同一个值」。
|
||||
- **内容哈希算法**(构建端与客户端必须一致):
|
||||
|
||||
```
|
||||
fileHash = SHA256(文件字节)
|
||||
dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0<fileHash>\n" )
|
||||
```
|
||||
|
||||
相对路径统一 `/` 分隔,跳过 `.` 开头的文件、`bin/`、`obj/`、`*.user`;
|
||||
不含时间戳、权限位、文件顺序。实现见 `GC/src/Security/ContentHash.cs`,构建端由
|
||||
`VersionStamp` 直接链接同一份源码,不会出现两套算法。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
EarthModelStudio/
|
||||
├── EarthModelStudio.sln
|
||||
├── Directory.Build.props # 公共构建属性
|
||||
├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效)
|
||||
├── build.sh / build.ps1 # 构建脚本
|
||||
├── src/ # ★ 启动器(没有渲染逻辑)
|
||||
│ └── main/dotnet/EarthModelStudio/
|
||||
│ ├── Models/ Services/ # 清单/设置/目录探测/i18n/模型库/下载/自动更新
|
||||
│ │ # UpdateService · GitCodeRemote · DirectoryRemote · LauncherUpdate
|
||||
│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳、启动更新状态条
|
||||
│ └── Assets/i18n/ # 启动器界面语言包
|
||||
├── src/test/dotnet/…Tests/ # 离屏校验 + --update-test 离线更新链路验证
|
||||
Repository/
|
||||
├── GC.sln
|
||||
├── Directory.Build.props # 公共构建属性(版本号在这里)
|
||||
├── version.json # ★ 自动生成并签名的版本清单(推送到仓库后才生效)
|
||||
├── build.sh / build.ps1 # 构建脚本(实际实现在 buildsh/ 与 buildps1/)
|
||||
├── GC/ # 启动器
|
||||
│ └── src/
|
||||
│ ├── GC.Core.csproj
|
||||
│ ├── Security/ # ★ 验签、哈希、安全解压、完整性、健康标记
|
||||
│ ├── Models/ Services/
|
||||
│ ├── ViewModels/ Views/
|
||||
│ ├── Assets/i18n/ # 界面语言包
|
||||
│ └── test/dotnet/GC.Tests/ # 离屏校验 + --update-test 离线更新链路验证
|
||||
├── GC-BOOT/ # 轻量启动入口
|
||||
├── GC-DOWNLOAD/ # 源仓库 / 模型 / 启动器下载更新
|
||||
├── GC-DRAW/PlayerWindow.cs # 模型窗口宿主;绘制由模型提供
|
||||
├── GC-SAVEDOG/ # ★ 更新守护进程(apply / verify / keygen / sign / status)
|
||||
├── model/ # ★ 模型的一切
|
||||
│ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取)
|
||||
│ ├── _sdk/EarthModelStudio.ModelSdk/
|
||||
│ ├── _engine/
|
||||
│ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView …
|
||||
│ │ ├── PreviewGen/ # 用模型渲染器生成封面
|
||||
│ │ └── VersionStamp/ # 按内容指纹自动打版本、生成 version.json
|
||||
│ ├── earth-rotation/
|
||||
│ │ ├── earth-rotation.json
|
||||
│ │ ├── src/ # 本模型源码
|
||||
│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n
|
||||
│ ├── version.json # 与根 version.json 完全相同(同一份签名)
|
||||
│ ├── _sdk/GC.ModelSdk/
|
||||
│ ├── _engine/{src,PreviewGen,VersionStamp}/
|
||||
│ ├── earth-rotation/{earth-rotation.json,src/,earth-rotation.model/}
|
||||
│ └── earth-revolution/
|
||||
└── dist/ # 发布产物(只有启动器 + .GC 骨架)
|
||||
├── dist/ # 发布产物(.gitignore,只通过 Release 分发)
|
||||
└── .signing/ # 签名私钥(.gitignore,绝不入库)
|
||||
```
|
||||
|
||||
模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。
|
||||
|
||||
`dist/` 不进仓库:二进制放 Git 会让 clone 变慢,也会让「仓库被改」的爆炸半径变大。
|
||||
发布有两种方式,`version.json` 里两条路都写清楚了:
|
||||
|
||||
| 方式 | 清单字段 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| Release 附件(推荐) | `url` | `.../releases/download/v<版本>/GC-<版本>-<系统>-<架构>.zip` |
|
||||
| 仓库编译产物 | `path` / `dir` / `name` | `dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip` |
|
||||
|
||||
下载端按 `url` → `path` → `dist/<系统>-<架构>/` 目录扫描的顺序尝试,
|
||||
**每个候选都必须与清单里的 `sha256` 一致**(`sha256` 由签名保护),
|
||||
所以「多发一个地方」不会放宽校验,只是让「只提交产物、不发 Release」也能更新。
|
||||
清单缺 `sha256` 的平台会被直接跳过,不再退化成「只校验非空」。
|
||||
|
||||
## 构建与运行
|
||||
|
||||
```bash
|
||||
./build.sh build # 编译整个解决方案
|
||||
./build.sh models # 编译模型 dll + 生成封面 + 自动打版本
|
||||
./build.sh stamp # 只重新生成 version.json 与模型版本
|
||||
./build.sh run # 运行
|
||||
./build.sh test # 离屏校验:页面 + 真实加载模型窗口截图
|
||||
./build.sh update-test # 离线验证自动更新链路(不联网、不替换程序)
|
||||
./build.sh publish # 三平台发布(不内置模型)+ 建 .GC 骨架 + 生成更新包
|
||||
./build.sh pack-models # 单独打包模型 -> dist/models-<version>.zip
|
||||
./build.sh pack-launcher # 生成三个平台的启动器更新包 zip
|
||||
./build.sh clean
|
||||
./build.sh build # 三平台完整发布:启动器 + SAVEDOG + 运行骨架 + 更新包 ZIP
|
||||
./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查
|
||||
./build.sh models # 编译模型 dll、生成封面、更新并签名版本清单
|
||||
./build.sh stamp # 只重新生成 + 签名 version.json
|
||||
./build.sh run # Debug 运行启动器
|
||||
./build.sh test # 离屏校验,截图写入 build/screenshots/
|
||||
./build.sh update-test # 离线验证自动更新链路(验签 / 立即生效 / 篡改拒绝 / 断网兜底)
|
||||
./build.sh pack-models # 编译模型并打包 dist/models-<版本>.zip
|
||||
./build.sh pack-launcher # 把已有平台发布目录打成启动器更新 ZIP
|
||||
./build.sh doctor # dotnet 环境信息
|
||||
./build.sh dist # 列出 dist/ 产物
|
||||
./build.sh clean # 清理 build/ 与 dist/
|
||||
```
|
||||
|
||||
Windows 用 `.\build.ps1`(参数相同)。
|
||||
|
||||
| 产物 | 平台 |
|
||||
| --- | --- |
|
||||
| `dist/mac-arm64/EarthModelStudio.app` | macOS Apple Silicon |
|
||||
| `dist/win-x64/EarthModelStudio.exe` | Windows x64 |
|
||||
| `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM |
|
||||
| `dist/mac-arm64/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包(含 GC-SAVEDOG) |
|
||||
| `dist/win-amd64/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 + `GC-SAVEDOG.exe` |
|
||||
| `dist/win-arm64/GC-<版本>-win-arm64.zip` | Windows on ARM 同上 |
|
||||
|
||||
均为自包含单文件启动器,**发布包内不含模型**。改完模型:
|
||||
`./build.sh models` → 把 `version.json` 和 `model/` 推送到 gitcode → 客户端下次启动自动更新。
|
||||
平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe`
|
||||
会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。
|
||||
|
||||
发新版:`./build.sh build -version=1.0.8` → 把 `dist/<平台>/GC-1.0.8-<平台>.zip`
|
||||
上传到 gitcode Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
|
||||
`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。
|
||||
两种都能被客户端识别,客户端下次启动就会看到更新。
|
||||
|
||||
## 模型契约
|
||||
|
||||
@@ -134,8 +240,25 @@ public interface IModelContext
|
||||
}
|
||||
```
|
||||
|
||||
启动器先弹进度窗,在后台调用 `Prepare`(模型用 `ReportProgress` 汇报真实进度),
|
||||
再在 UI 线程调用 `CreateView`,把返回的控件直接铺满窗口 —— 除此之外什么都不做。
|
||||
**线程约定**
|
||||
|
||||
| 成员 | 允许的线程 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `Prepare` | 后台线程(调用一次) | 可耗时;用 `ReportProgress` 汇报真实进度;此时**不要**创建控件 |
|
||||
| `CreateView` | UI 线程(`Prepare` 之后调用一次) | 只在这里创建/操作 Avalonia 控件 |
|
||||
| `ReportProgress` / `Log` | 任意线程 | 线程安全,内部自行封送到 UI |
|
||||
| `RequestClose` | 任意线程 | 线程安全,等价于点窗口关闭按钮 |
|
||||
| `Dispose` | UI 线程 | 释放后不要再调用 `Log` / `ReportProgress` |
|
||||
|
||||
**契约版本协商**
|
||||
|
||||
- `IModelFactory.ApiVersion` 与启动器支持的版本(当前 `1`)必须相等,否则拒绝加载并提示更新启动器。
|
||||
- 模型清单可写 `minAppVersion`(如 `"1.0.8"`):启动器版本更低时直接拒绝,并给出明确提示。
|
||||
- 提升契约版本时必须保留旧接口的适配层,或在启动器里明确「最低启动器版本」,避免老客户端加载新模型后崩溃。
|
||||
|
||||
**卸载注意**:关窗即 `Unload()` 收集式 AssemblyLoadContext。只要有静态字段、未解绑的事件、
|
||||
或缓存里还拿着模型内的类型/控件,程序集就回收不掉(内存持续增长)。
|
||||
模型作者应避免静态持有 `Control` / `IModelContext`,并在 `Dispose` 里解绑事件。
|
||||
|
||||
详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。
|
||||
|
||||
@@ -143,7 +266,7 @@ public interface IModelContext
|
||||
|
||||
- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口
|
||||
- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集
|
||||
- 启动器快捷键 `Esc` 关闭、`F11` 全屏;模型窗口内的快捷键由模型自己定义
|
||||
- 所有由启动器打开的窗口(模型窗、加载窗、确认框、更新窗)都是 16px 圆角
|
||||
|
||||
## 地球模型(model/_engine + model/<id>/src)
|
||||
|
||||
@@ -155,20 +278,12 @@ public interface IModelContext
|
||||
**没有节气定位**(节气属于公转)
|
||||
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期)
|
||||
- **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮;
|
||||
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**,
|
||||
俯视角只由「俯视」按钮显式切换
|
||||
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**
|
||||
- **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明;
|
||||
右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位;
|
||||
快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角
|
||||
- 节气日期、直射纬度、现象说明、教学要点全部写在 `scene.json` 里;夸张倾角只改示意图形,不改教学读数
|
||||
|
||||
## 模型源(手动导入)
|
||||
|
||||
除了启动时自动更新,「下载」页还支持手动导入普通 git 仓库:
|
||||
**仓库根目录下的 `model/` 文件夹即模型列表**。支持 GitHub / GitLab / Gitee(zip 归档,
|
||||
失败回退 `git clone --depth 1`)、zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`。
|
||||
|
||||
## 启动时运行内存分配
|
||||
|
||||
设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
|
||||
设置页的「启动时运行内存分配」类似启动器的 `-Xmx`:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
|
||||
交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。
|
||||
@@ -0,0 +1,78 @@
|
||||
# GC v1.0.6
|
||||
|
||||
## 新模型:等高线地形图
|
||||
|
||||
依据人教版七年级上册「地形图的判读」制作,把课本最难讲清的一件事——**立体地形如何转成平面等高线图**——变成可交互的双图联动。
|
||||
|
||||
- **左右双图联动**:左边是三维地形块(斜视图),右边是等比例的分层设色等高线图。鼠标移到任一侧,两侧同步标出该点位置、海拔、相对高度和地形部位。
|
||||
- **五种地形部位判读**:山峰、山脊、山谷、鞍部、陡崖。鼠标停在哪里,底部就实时显示该处属于哪种部位,并给出对应颜色。
|
||||
- **等高线自动生成**:Marching Squares 算法从 192×192 高度场实时提取,等高距 100 m,共 14 条;每 5 条加粗为计曲线并标注海拔。
|
||||
- **分层设色**:绿 → 黄绿 → 土黄 → 棕 → 雪白,与课本配色一致。
|
||||
- **判读要点面板**:右侧列出五种部位的特征(如「山脊:等高线凸向低处,脊线是分水线」)和四条核心规则(等高距、疏密与坡度、计曲线、海拔与相对高度)。
|
||||
- 地形本身包含主峰、次峰(之间形成鞍部)、两条山脊、一条河谷、一侧陡坡、一侧缓坡和一处陡崖,海拔 0~1322 m。
|
||||
|
||||
## 更新系统:双源支持
|
||||
|
||||
启动器现在同时对接 **Xhmcl** 和 **GitCode** 两个仓库(同一份内容的镜像)。
|
||||
|
||||
- **自动测速选源**:检查更新与下载前并发探测两边的 `version.json` 响应时间,自动选用更快的那一个。结果缓存 3 分钟,不会每次都测。
|
||||
- **Release 交叉检查**:两个源的 Release 都会查询,取版本号最高且包含当前平台发布包的那个。某个源没发 Release 时自动跳到另一个,不影响使用。
|
||||
- **版本号优先于发布时间**:Release 列表按版本号数值比较(`1.0.10 > 1.0.9`),不受发布时间顺序影响。草稿状态(draft)的 Release 不计入。
|
||||
- **模型与启动器分开取**:模型清单始终读仓库里的 `version.json`(模型不需要发 Release),启动器版本只认 Release。这样即使某个源没发 Release,模型仍能正常更新。
|
||||
- **同版本比对指纹**:远端版本与本地相同时,下载对应平台的发布包比对 sha256。一致则视为最新;不一致说明是自行编译的构建,不打扰用户。
|
||||
- **修复版本读取**:此前 `Assembly.GetEntryAssembly()` 在某些宿主下会返回 `1.0.0`,导致明明是最新版却一直提示更新;现在改为读取本程序集版本。
|
||||
|
||||
## 下载页面
|
||||
|
||||
- **取消自定义模型源**:不再接受任意仓库地址,只保留 Xhmcl 与 GitCode 两个内置源,避免来源不明的模型。
|
||||
- **一键测速切换**:原来的「导入模型源」输入框改为「测速并切换到最快源」按钮,点击后自动比对并切到更快的那个源。
|
||||
- **下载与更新统一**:下载页面和启动更新现在共用同一个源选择器,不再出现两处下载速度不一致的情况。
|
||||
|
||||
## 窗口标题栏
|
||||
|
||||
- **去掉彩色圆圈**:最小化 / 最大化 / 关闭三个按钮改回纯矢量图标,不再有黄、绿、红圆底。
|
||||
- **主窗口补齐最大化**:此前主窗口只有最小化和关闭,现在补上最大化,并支持双击标题栏切换。
|
||||
- **图标随状态切换**:最大化后图标变为两个重叠小方框(还原),还原后变回单方框。
|
||||
- **圆角始终保留**:任何窗口状态下都保持 16px 圆角,不再最大化后变成直角贴边。
|
||||
- **尺寸自适应**:标题栏文字、按钮、图标随窗口宽度同比缩放(0.85–1.9 倍),全屏时不会小得点不中。
|
||||
|
||||
## 缩放动画
|
||||
|
||||
- **地理模型**:此前滚轮缩放直接跳变,现在改为指数逼近的平滑动画(60Hz),差值小于阈值自动停下,不空转耗 CPU。
|
||||
- **地球模型**:本就带平滑缩放,保持原样。
|
||||
|
||||
## 关于页面
|
||||
|
||||
- 新增「**感谢**」卡片,样式与「开发者」卡片一致:**地理洪老师 — 地理学科内容指导**。
|
||||
|
||||
## 开发者工具
|
||||
|
||||
新增 `git.sh` / `git.bat` 与 `gitshell/` 目录,把仓库操作从手动命令变成可交互流程:
|
||||
|
||||
- **`./git.sh autogit`**:交互式提交。依次询问①选哪个仓库(支持多选、可选全部、可连续输入多个新地址)②确认仓库地址③确认提交分支④输入提交信息⑤最终确认,然后逐个推送并汇总结果。
|
||||
- **自动排除构建产物**:`dist/` `build/` `bin/` `obj/` `.GC/` 无论是否被跟踪都不会提交,历史上被跟踪的会先从索引移出(本地文件保留)。
|
||||
- **`./git.sh status`**:一眼看清当前分支、改动数量、最近提交,以及每个远程仓库的领先/落后情况。
|
||||
|
||||
## 模型版本
|
||||
|
||||
| 模型 | 版本 |
|
||||
| --- | --- |
|
||||
| 等高线地形图 contour-map | **1.0**(新) |
|
||||
| 地球地理 earth-geography | 1.8 |
|
||||
| 地球自转 earth-rotation | 1.6 |
|
||||
| 地球公转 earth-revolution | 1.6 |
|
||||
| 比例尺计算器 scale-calculator | 1.5 |
|
||||
|
||||
---
|
||||
|
||||
**安装包**
|
||||
|
||||
| 平台 | 文件 |
|
||||
| --- | --- |
|
||||
| Windows x64 | `GC-win-x64.zip` |
|
||||
| Windows ARM64 | `GC-win-arm64.zip` |
|
||||
| macOS Apple Silicon | `GC-osx-arm64.zip` |
|
||||
| macOS Intel | `GC-osx-x64.zip` |
|
||||
| Linux x64 | `GC-linux-x64.zip` |
|
||||
|
||||
下载后解压即可运行。模型会在首次启动时自动下载到程序目录旁的 `.GC/model/`。
|
||||
@@ -1,75 +1,8 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# Earth Model Studio 构建入口(Windows PowerShell,薄封装)
|
||||
# 实际代码在 buildsh/ 里。Windows 上若无 sh,则走内置的最小实现。
|
||||
# .\build.ps1 build | check | models | stamp | run | test | clean | doctor
|
||||
# ---------------------------------------------------------------------------
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
||||
'run','test','update-test','clean','doctor','dist')]
|
||||
[string]$Task = 'build'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Root = $PSScriptRoot
|
||||
Set-Location $Root
|
||||
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
|
||||
|
||||
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
|
||||
$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj'
|
||||
$StampProj= 'model/_engine/VersionStamp/VersionStamp.csproj'
|
||||
$Sln = 'EarthModelStudio.sln'
|
||||
$Version = ([regex]::Match((Get-Content Directory.Build.props -Raw), '<Version>(.*?)</Version>')).Groups[1].Value
|
||||
if (-not $Version) { $Version = '1.0.0' }
|
||||
New-Item -ItemType Directory -Force -Path "$Root/build/logs" | Out-Null
|
||||
|
||||
# 优先复用 buildsh 的 shell 实现(Git Bash / WSL / sh 可用时)
|
||||
$sh = Get-Command sh -ErrorAction SilentlyContinue
|
||||
if ($sh) {
|
||||
& $sh.Source "$Root/build.sh" $Task
|
||||
exit $LASTEXITCODE
|
||||
try {
|
||||
& (Join-Path $PSScriptRoot 'buildps1/build.ps1') @args
|
||||
exit 0
|
||||
}
|
||||
|
||||
function Stamp { dotnet run --project $StampProj -c Release -- $Root $Version }
|
||||
function Build-Models {
|
||||
Get-ChildItem "$Root/model" -Directory | ForEach-Object {
|
||||
$id = $_.Name
|
||||
$src = Join-Path $_.FullName 'src'
|
||||
if (-not (Test-Path $src)) { return }
|
||||
$proj = Get-ChildItem $src -Filter *.csproj | Select-Object -First 1
|
||||
if (-not $proj) { return }
|
||||
dotnet build $proj.FullName -c Release
|
||||
}
|
||||
Stamp
|
||||
}
|
||||
|
||||
switch ($Task) {
|
||||
'build' {
|
||||
Write-Host '==> 编译三平台(进度见 buildsh/lib/progress.sh,建议用 Git Bash 运行 ./build.sh build)'
|
||||
Remove-Item -Recurse -Force "$Root/dist" -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
|
||||
Stamp
|
||||
foreach ($rid in @('osx-arm64','win-x64','win-arm64')) {
|
||||
dotnet publish $AppProj -c Release -r $rid --self-contained true `
|
||||
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false `
|
||||
-o "$Root/dist/$rid"
|
||||
}
|
||||
Write-Host '==> 完成(详细打包请用 ./build.sh build)'
|
||||
}
|
||||
'check' {
|
||||
dotnet build $Sln -c Debug
|
||||
$env:EMS_SELFTEST = '1'; dotnet run --project $AppProj -c Debug --no-build; Remove-Item Env:\EMS_SELFTEST
|
||||
dotnet run --project $TestProj -c Debug --no-build -- "$Root/build/screenshots"
|
||||
}
|
||||
'models' { Build-Models }
|
||||
'stamp' { Stamp }
|
||||
'pack-models' { Build-Models }
|
||||
'pack-launcher' { Write-Host '请用 ./build.sh pack-launcher' }
|
||||
'run' { dotnet run --project $AppProj -c Debug }
|
||||
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
|
||||
'update-test' { dotnet run --project $TestProj -c Debug -- '--update-test' $Root }
|
||||
'clean' { Remove-Item -Recurse -Force "$Root/build","$Root/dist" -ErrorAction SilentlyContinue; Write-Host '==> 已清理' }
|
||||
'doctor' { dotnet --info | Select-Object -First 20 }
|
||||
'dist' { Get-ChildItem "$Root/dist" -ErrorAction SilentlyContinue }
|
||||
catch {
|
||||
[Console]::Error.WriteLine($_)
|
||||
exit 1
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/bin/sh
|
||||
# ---------------------------------------------------------------------------
|
||||
# Earth Model Studio 构建入口(薄封装)
|
||||
# GC 构建入口(薄封装)
|
||||
#
|
||||
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
|
||||
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
|
||||
@@ -21,11 +21,12 @@ export AVALONIA_TELEMETRY_OPTOUT=1
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj"
|
||||
APP_PROJ="GC-BOOT/GC-BOOT.csproj"
|
||||
SAVEDOG_PROJ="GC-SAVEDOG/GC-SAVEDOG.csproj"
|
||||
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
|
||||
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
|
||||
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
|
||||
SLN="EarthModelStudio.sln"
|
||||
TEST_PROJ="GC/src/test/dotnet/GC.Tests/GC.Tests.csproj"
|
||||
SLN="GC.sln"
|
||||
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1)
|
||||
[ -n "$VERSION" ] || VERSION="1.0.0"
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
function Invoke-BuildCheck {
|
||||
Initialize-BuildProgress @('编译检查', '模型自检', '离屏渲染', '产物检查')
|
||||
$failures = [System.Collections.Generic.List[string]]::new()
|
||||
try {
|
||||
Start-BuildStep '编译检查'
|
||||
try { Invoke-LoggedDotNet -Name 'check-build' -Arguments @('build', $script:Solution, '-c', 'Debug', '-v', 'quiet') }
|
||||
catch { $failures.Add('编译失败,见 build/logs/check-build.log'); Write-Host "!! $($failures[-1])" }
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '模型自检'
|
||||
$previousSelfTest = $env:EMS_SELFTEST
|
||||
try {
|
||||
$env:EMS_SELFTEST = '1'
|
||||
Invoke-LoggedDotNet -Name 'check-selftest' -Arguments @('run', '--project', $script:AppProject, '-c', 'Debug', '--no-build')
|
||||
if (Select-String -Path 'build/logs/check-selftest.log' -Pattern 'FAIL' -Quiet) {
|
||||
$failures.Add('模型自检有失败项')
|
||||
Write-Host "!! $($failures[-1])"
|
||||
}
|
||||
}
|
||||
catch { $failures.Add('模型自检异常'); Write-Host "!! $($failures[-1])" }
|
||||
finally { $env:EMS_SELFTEST = $previousSelfTest }
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '离屏渲染'
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path 'build/screenshots' | Out-Null
|
||||
Invoke-LoggedDotNet -Name 'check-render' -Arguments @('run', '--project', $script:TestProject, '-c', 'Debug', '--no-build', '--', (Join-Path $script:BuildRoot 'build/screenshots'))
|
||||
}
|
||||
catch { $failures.Add('离屏渲染失败,见 build/logs/check-render.log'); Write-Host "!! $($failures[-1])" }
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '产物检查'
|
||||
$packageCount = @(Get-ChildItem 'dist' -Filter "GC-$script:BuildVersion-*.zip" -ErrorAction SilentlyContinue).Count
|
||||
if ($packageCount -lt 3) {
|
||||
$failures.Add("产物不足 3 个(当前 $packageCount)")
|
||||
Write-Host "!! $($failures[-1])"
|
||||
}
|
||||
Complete-BuildStep
|
||||
}
|
||||
finally { Complete-BuildProgress }
|
||||
|
||||
if ($failures.Count -eq 0) { Write-Host '==> 全部通过'; return }
|
||||
Write-Host '==> 有失败项'
|
||||
throw ($failures -join "`n")
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
function Invoke-BuildTool {
|
||||
param([Parameter(Mandatory)][string]$Name)
|
||||
switch ($Name) {
|
||||
'models' { Build-Models }
|
||||
'stamp' { Invoke-VersionStamp }
|
||||
'pack-models' { Build-Models; Pack-Models }
|
||||
'pack-launcher'{ Pack-Launcher }
|
||||
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
|
||||
'test' { & dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots'); if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" } }
|
||||
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
|
||||
'clean' {
|
||||
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
foreach ($projectRoot in @('GC', 'GC-BOOT', 'GC-DRAW', 'model')) {
|
||||
$path = Join-Path $script:BuildRoot $projectRoot
|
||||
if (Test-Path $path) {
|
||||
Get-ChildItem $path -Directory -Recurse -Force | Where-Object Name -in @('bin', 'obj') | Sort-Object FullName -Descending | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
Write-Host '==> 已清理'
|
||||
}
|
||||
'doctor' { & dotnet --info | Select-Object -First 20; if ($LASTEXITCODE -ne 0) { throw "dotnet --info 失败,退出码 $LASTEXITCODE" } }
|
||||
'dist' {
|
||||
Write-Host '==> dist 产物:'
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -ErrorAction SilentlyContinue | Select-Object Name, Length
|
||||
}
|
||||
default { throw "未知任务:$Name" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
||||
'run','test','update-test','clean','doctor','dist')]
|
||||
[string]$Task = 'build',
|
||||
[string]$Version = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:BuildRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
$script:AppProject = 'GC-BOOT/GC-BOOT.csproj'
|
||||
$script:PreviewProject = 'model/_engine/PreviewGen/PreviewGen.csproj'
|
||||
$script:StampProject = 'model/_engine/VersionStamp/VersionStamp.csproj'
|
||||
$script:TestProject = 'GC/src/test/dotnet/GC.Tests/GC.Tests.csproj'
|
||||
$script:Solution = 'GC.sln'
|
||||
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
|
||||
|
||||
Push-Location $script:BuildRoot
|
||||
try {
|
||||
$props = [xml](Get-Content 'Directory.Build.props' -Raw)
|
||||
$versionNode = $props.SelectSingleNode('/Project/PropertyGroup/Version')
|
||||
if (-not $Version) { $Version = $versionNode.InnerText }
|
||||
if (-not $Version) { $Version = '1.0.0' }
|
||||
$script:BuildVersion = $Version
|
||||
|
||||
if ($PSBoundParameters.ContainsKey('Version')) {
|
||||
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
|
||||
$versionNode.InnerText = $Version
|
||||
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
|
||||
Write-Host "==> 版本号设为 $Version"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path 'build/logs' | Out-Null
|
||||
. (Join-Path $PSScriptRoot 'lib/Progress.ps1')
|
||||
. (Join-Path $PSScriptRoot 'lib/Build-Funcs.ps1')
|
||||
. (Join-Path $PSScriptRoot 'Build-Check.ps1')
|
||||
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
|
||||
|
||||
switch ($Task) {
|
||||
'build' { Invoke-FullBuild }
|
||||
'check' { Invoke-BuildCheck }
|
||||
default { Invoke-BuildTool $Task }
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
function Invoke-LoggedDotNet {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Name,
|
||||
[Parameter(Mandatory)][string[]]$Arguments
|
||||
)
|
||||
$logPath = Join-Path $script:BuildRoot "build/logs/$Name.log"
|
||||
& dotnet @Arguments *> $logPath
|
||||
$exitCode = $LASTEXITCODE
|
||||
if ($exitCode -ne 0) {
|
||||
Get-Content $logPath | Write-Host
|
||||
throw "dotnet $($Arguments -join ' ') 失败,退出码 $exitCode;日志:$logPath"
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-ManifestSign {
|
||||
$key = Join-Path $script:BuildRoot '.signing/gc-signing.pem'
|
||||
if (-not (Test-Path $key)) {
|
||||
Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)'
|
||||
return
|
||||
}
|
||||
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-11' }
|
||||
Write-Host "==> 签名 version.json ($keyId)"
|
||||
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
|
||||
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
|
||||
'-c', 'Release', '--', 'sign',
|
||||
'--manifest', (Join-Path $script:BuildRoot 'version.json'),
|
||||
'--key', $key, '--key-id', $keyId
|
||||
)
|
||||
Copy-Item (Join-Path $script:BuildRoot 'version.json') (Join-Path $script:BuildRoot 'model/version.json') -Force
|
||||
}
|
||||
|
||||
function Invoke-VersionStamp {
|
||||
param([switch]$LauncherOnly)
|
||||
if ($LauncherOnly) {
|
||||
Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)'
|
||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||
'run', '--project', $script:StampProject, '-c', 'Release', '--',
|
||||
$script:BuildRoot, $script:BuildVersion, '--launcher-only'
|
||||
)
|
||||
}
|
||||
else {
|
||||
Write-Host '==> 自动计算模型版本并生成 version.json'
|
||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||
'run', '--project', $script:StampProject, '-c', 'Release', '--',
|
||||
$script:BuildRoot, $script:BuildVersion
|
||||
)
|
||||
}
|
||||
Invoke-ManifestSign
|
||||
}
|
||||
|
||||
function Build-Models {
|
||||
Write-Host '==> 编译模型功能程序集(源码位于各模型目录的 src/)'
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'model') -Directory | ForEach-Object {
|
||||
$modelId = $_.Name
|
||||
$sourceDir = Join-Path $_.FullName 'src'
|
||||
if (-not (Test-Path $sourceDir)) { return }
|
||||
$project = Get-ChildItem $sourceDir -Filter '*.csproj' | Select-Object -First 1
|
||||
if ($null -eq $project) { return }
|
||||
|
||||
Invoke-LoggedDotNet -Name "model-$modelId" -Arguments @('build', $project.FullName, '-c', 'Release')
|
||||
$packageDir = Join-Path $_.FullName "$modelId.model"
|
||||
$outputDir = Join-Path $sourceDir 'bin/Release/net8.0'
|
||||
if (Test-Path $packageDir) {
|
||||
Get-ChildItem $outputDir -Filter '*.dll' -ErrorAction SilentlyContinue | Where-Object Name -ne 'GC.ModelSdk.dll' | ForEach-Object {
|
||||
Copy-Item $_.FullName (Join-Path $packageDir $_.Name) -Force
|
||||
Write-Host " -> model/$modelId/$modelId.model/$($_.Name)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host '==> 用模型自己的渲染器生成封面'
|
||||
Invoke-LoggedDotNet -Name 'preview' -Arguments @('run', '--project', $script:PreviewProject, '-c', 'Release', '--', $script:BuildRoot)
|
||||
Invoke-VersionStamp
|
||||
}
|
||||
|
||||
function Prepare-RuntimeLayout {
|
||||
param([Parameter(Mandatory)][string]$RelativePath)
|
||||
$destination = Join-Path $script:BuildRoot $RelativePath
|
||||
if (-not (Test-Path $destination)) { return }
|
||||
|
||||
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update'), (Join-Path $destination '.GC/config') | Out-Null
|
||||
Set-Content -Path (Join-Path $destination '.GC/model/README.txt') -Encoding UTF8 -Value @'
|
||||
模型库目录(.GC/model/)
|
||||
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
|
||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
||||
|
||||
运行目录:
|
||||
<可执行文件>
|
||||
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
|
||||
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
|
||||
.GC/model/ 本目录(下载的模型)
|
||||
.GC/cache/ 下载暂存
|
||||
.GC/update/ 待下次启动应用的启动器更新
|
||||
'@
|
||||
$settingsPath = Join-Path $destination '.GC/config/settings.json'
|
||||
if (-not (Test-Path $settingsPath)) {
|
||||
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
|
||||
{
|
||||
"language": "auto",
|
||||
"theme": "light",
|
||||
"renderFps": 30,
|
||||
"memoryMb": 2048,
|
||||
"autoUpdateOnStartup": true,
|
||||
"requireSignedManifest": true,
|
||||
"updateRepository": "https://gitcode.com/Morris_1/GC",
|
||||
"updateManifestUrl": "",
|
||||
"updateLocalRoot": "",
|
||||
"installedModelVersions": {},
|
||||
"launcherVersion": "",
|
||||
"pendingLauncherVersion": "",
|
||||
"lastUpdateCheck": "",
|
||||
"sources": [],
|
||||
"recentModels": []
|
||||
}
|
||||
'@
|
||||
}
|
||||
Write-Host " 运行目录 -> $RelativePath/.GC"
|
||||
}
|
||||
|
||||
function Publish-Rid {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Rid,
|
||||
[Parameter(Mandatory)][string]$Output,
|
||||
[bool]$SingleFile = $true
|
||||
)
|
||||
$outputPath = Join-Path $script:BuildRoot $Output
|
||||
Remove-Item $outputPath -Recurse -Force -ErrorAction SilentlyContinue
|
||||
$singleValue = $SingleFile.ToString().ToLowerInvariant()
|
||||
Write-Host "==> 编译 $Rid (single-file=$singleValue) -> $Output"
|
||||
Invoke-LoggedDotNet -Name "publish-$($Rid -replace '-', '')" -Arguments @(
|
||||
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
|
||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
|
||||
'-p:PublishTrimmed=false', '-o', $outputPath
|
||||
)
|
||||
|
||||
# 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB)
|
||||
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)
|
||||
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
|
||||
if (Test-Path $savedogProj) {
|
||||
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪单文件)"
|
||||
Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @(
|
||||
'publish', $savedogProj, '-c', 'Release', '-r', $Rid,
|
||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||
'-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true',
|
||||
'-p:PublishTrimmed=true', '-p:TrimMode=full',
|
||||
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
|
||||
)
|
||||
}
|
||||
|
||||
Remove-Item (Join-Path $outputPath 'model'), (Join-Path $outputPath 'examples') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function Pack-Models {
|
||||
$zipPath = Join-Path $script:BuildRoot "dist/models-$script:BuildVersion.zip"
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
Write-Host "==> 打包模型数据 -> dist/models-$script:BuildVersion.zip"
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$modelRoot = Join-Path $script:BuildRoot 'model'
|
||||
$archive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
|
||||
try {
|
||||
Get-ChildItem $modelRoot -File -Recurse | Where-Object {
|
||||
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
|
||||
$_.Name -ne '.DS_Store' -and
|
||||
$_.Extension -ne '.user' -and
|
||||
$relativePath -notmatch '(^|/)(bin|obj)/'
|
||||
} | ForEach-Object {
|
||||
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
|
||||
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile(
|
||||
$archive, $_.FullName, "model/$relativePath", [System.IO.Compression.CompressionLevel]::Optimal
|
||||
) | Out-Null
|
||||
}
|
||||
}
|
||||
finally { $archive.Dispose() }
|
||||
Get-Item $zipPath | Select-Object Name, Length
|
||||
}
|
||||
|
||||
function Pack-Launcher {
|
||||
$dist = Join-Path $script:BuildRoot 'dist'
|
||||
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
|
||||
|
||||
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
|
||||
# 产物落点 dist/<系统>-<架构>/,与 dist/mac-arm64 一致
|
||||
$sourceDir = Join-Path $dist $platform.Label
|
||||
if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid }
|
||||
if (-not (Test-Path $sourceDir)) { continue }
|
||||
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
|
||||
$executable = Get-ChildItem $sourceDir -Filter '*.exe' |
|
||||
Where-Object { $_.Name -notlike 'GC-SAVEDOG*' } | Select-Object -First 1
|
||||
if ($null -eq $executable) { continue }
|
||||
|
||||
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
|
||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path $temp | Out-Null
|
||||
Copy-Item $executable.FullName (Join-Path $temp "GC-$script:BuildVersion-$($platform.Label).exe") -Force
|
||||
$savedogExe = Join-Path $sourceDir 'GC-SAVEDOG.exe'
|
||||
if (Test-Path $savedogExe) { Copy-Item $savedogExe (Join-Path $temp 'GC-SAVEDOG.exe') -Force }
|
||||
|
||||
$zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal
|
||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
||||
}
|
||||
|
||||
$macApp = Join-Path $dist 'mac-arm64/GC.app'
|
||||
if (Test-Path $macApp) {
|
||||
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
|
||||
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Move-Item $macApp $finalApp
|
||||
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
|
||||
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
|
||||
$plist = Join-Path $finalApp 'Contents/Info.plist'
|
||||
if ((Test-Path $plist) -and (Test-Path '/usr/libexec/PlistBuddy')) {
|
||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
|
||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
|
||||
}
|
||||
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
|
||||
}
|
||||
|
||||
# Windows 的 zip 已在上面的循环里生成(含 GC-SAVEDOG.exe),这里只处理 .app
|
||||
Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object {
|
||||
$label = $_.BaseName -replace "^GC-$([regex]::Escape($script:BuildVersion))-", ''
|
||||
$targetDir = Join-Path $dist $label
|
||||
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
|
||||
$zipPath = Join-Path $targetDir ($_.BaseName + '.zip')
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
if ($_.PSIsContainer) {
|
||||
Remove-Item (Join-Path $_.FullName 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($_.PSIsContainer -and (Get-Command ditto -ErrorAction SilentlyContinue)) {
|
||||
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
|
||||
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
|
||||
}
|
||||
else {
|
||||
Compress-Archive -Path $_.FullName -DestinationPath $zipPath -CompressionLevel Optimal
|
||||
}
|
||||
Write-Host " -> dist/$label/$($_.BaseName).zip"
|
||||
}
|
||||
|
||||
# 原始产物(.exe / .app 目录)不再保留:只发布 zip
|
||||
$trash = Join-Path $script:BuildRoot 'build/trash'
|
||||
New-Item -ItemType Directory -Force -Path $trash | Out-Null
|
||||
Get-ChildItem $dist -Force | Where-Object {
|
||||
$_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app"
|
||||
} | ForEach-Object {
|
||||
Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Remove-IntermediateDirectories
|
||||
Invoke-VersionStamp -LauncherOnly
|
||||
Write-Host '==> dist 可发布 zip:'
|
||||
Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||
}
|
||||
|
||||
function Remove-IntermediateDirectories {
|
||||
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
|
||||
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) {
|
||||
$dir = Join-Path $script:BuildRoot "dist/$name"
|
||||
if (-not (Test-Path $dir)) { continue }
|
||||
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GC-$script:BuildVersion-*.zip" } |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
|
||||
}
|
||||
|
||||
function New-MacAppBundle {
|
||||
$dist = Join-Path $script:BuildRoot 'dist/mac-arm64'
|
||||
$app = Join-Path $dist 'GC.app'
|
||||
Remove-Item $app -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $app 'Contents/MacOS'), (Join-Path $app 'Contents/Resources') | Out-Null
|
||||
$plist = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleName</key><string>GC</string>
|
||||
<key>CFBundleDisplayName</key><string>GC</string>
|
||||
<key>CFBundleIdentifier</key><string>cn.neorf.GC</string>
|
||||
<key>CFBundleVersion</key><string>$script:BuildVersion</string>
|
||||
<key>CFBundleShortVersionString</key><string>$script:BuildVersion</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleExecutable</key><string>GC</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
|
||||
<key>LSMinimumSystemVersion</key><string>11.0</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
</dict></plist>
|
||||
"@
|
||||
Set-Content -Path (Join-Path $app 'Contents/Info.plist') -Encoding UTF8 -Value $plist
|
||||
Get-ChildItem $dist -Force | Where-Object Name -notin @('GC.app', '.DS_Store') | Move-Item -Destination (Join-Path $app 'Contents/MacOS')
|
||||
Remove-Item (Join-Path $app 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
$binary = Join-Path $app 'Contents/MacOS/GC'
|
||||
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
|
||||
|
||||
$iconSource = Join-Path $script:BuildRoot 'GC/src/Assets/icon-1024.png'
|
||||
if ((Test-Path $iconSource) -and (Get-Command iconutil -ErrorAction SilentlyContinue) -and (Get-Command sips -ErrorAction SilentlyContinue)) {
|
||||
$iconset = Join-Path $dist 'AppIcon.iconset'
|
||||
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path $iconset | Out-Null
|
||||
foreach ($size in @(16, 32, 64, 128, 256, 512)) {
|
||||
& sips -z $size $size $iconSource --out (Join-Path $iconset "icon_${size}x${size}.png") *> $null
|
||||
$doubleSize = $size * 2
|
||||
& sips -z $doubleSize $doubleSize $iconSource --out (Join-Path $iconset "icon_${size}x${size}@2x.png") *> $null
|
||||
}
|
||||
$iconFile = Join-Path $app 'Contents/Resources/AppIcon.icns'
|
||||
& iconutil -c icns $iconset -o $iconFile
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$infoPlist = Join-Path $app 'Contents/Info.plist'
|
||||
if (Test-Path '/usr/libexec/PlistBuddy') {
|
||||
& /usr/libexec/PlistBuddy -c 'Add :CFBundleIconFile string AppIcon' $infoPlist 2>$null
|
||||
}
|
||||
}
|
||||
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Write-Host "==> 已打包 $app"
|
||||
}
|
||||
|
||||
function Invoke-FullBuild {
|
||||
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
|
||||
try {
|
||||
Start-BuildStep '清理旧产物'
|
||||
Remove-Item (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $script:BuildRoot 'dist') | Out-Null
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '版本戳'; Invoke-VersionStamp; Complete-BuildStep
|
||||
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $false; Complete-BuildStep
|
||||
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep
|
||||
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
|
||||
|
||||
Start-BuildStep '运行骨架'
|
||||
New-MacAppBundle
|
||||
Prepare-RuntimeLayout 'dist/win-amd64'
|
||||
Prepare-RuntimeLayout 'dist/win-arm64'
|
||||
Prepare-RuntimeLayout 'dist/mac-arm64/GC.app/Contents/MacOS'
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
|
||||
Start-BuildStep '收尾'; Complete-BuildStep
|
||||
Write-Host '==> 完成,产物:'
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||
}
|
||||
finally { Complete-BuildProgress }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
$script:ProgressSteps = @()
|
||||
$script:ProgressIndex = 0
|
||||
$script:ProgressActivity = 'GC 构建'
|
||||
|
||||
function Initialize-BuildProgress {
|
||||
param([string[]]$Steps)
|
||||
$script:ProgressSteps = $Steps
|
||||
$script:ProgressIndex = 0
|
||||
Write-Progress -Activity $script:ProgressActivity -Status '准备' -PercentComplete 0
|
||||
}
|
||||
|
||||
function Start-BuildStep {
|
||||
param([string]$Name)
|
||||
$script:ProgressIndex++
|
||||
$percent = [math]::Min(99, [int](($script:ProgressIndex - 1) * 100 / [math]::Max(1, $script:ProgressSteps.Count)))
|
||||
Write-Progress -Activity $script:ProgressActivity -Status $Name -PercentComplete $percent
|
||||
Write-Host "==> $Name"
|
||||
}
|
||||
|
||||
function Complete-BuildStep {
|
||||
$percent = [int]($script:ProgressIndex * 100 / [math]::Max(1, $script:ProgressSteps.Count))
|
||||
Write-Progress -Activity $script:ProgressActivity -Status '进行中' -PercentComplete $percent
|
||||
}
|
||||
|
||||
function Complete-BuildProgress {
|
||||
Write-Progress -Activity $script:ProgressActivity -Completed
|
||||
}
|
||||
Loaded 100 of 1213 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user