添加GC-DOWNLOAD项目
This commit is contained in:
1 parent
c95dfaf9f3
commit
791db4fe12
47 files changed
+869
-313
No files matched your search
@@ -11,11 +11,11 @@ namespace GC.Services;
|
||||
/// 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
|
||||
@@ -31,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>
|
||||
@@ -54,7 +54,8 @@ public sealed class AppPaths
|
||||
//
|
||||
// 重要:源码版由 `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) &&
|
||||
@@ -63,9 +64,13 @@ public sealed class AppPaths
|
||||
string installDir;
|
||||
if (isDev)
|
||||
{
|
||||
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里
|
||||
// 源码版:安装目录 = 仓库根
|
||||
installDir = repoRoot!;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(explicitHome) && Directory.Exists(explicitHome))
|
||||
{
|
||||
installDir = explicitHome;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
|
||||
@@ -120,7 +125,7 @@ public sealed class AppPaths
|
||||
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
|
||||
{
|
||||
@@ -140,7 +145,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
|
||||
|
||||
@@ -10,15 +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 SourceSelector Selector { get; }
|
||||
public ISourceSelector Selector { get; }
|
||||
public ILauncherUpdateService LauncherUpdates { get; }
|
||||
public IDownloadModule DownloadModule { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
@@ -26,12 +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);
|
||||
Selector = new SourceSelector();
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
|
||||
@@ -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>
|
||||
@@ -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];
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
||||
/// 目录结构与远端仓库一致:version.json + model/<id>/...
|
||||
/// </summary>
|
||||
public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
|
||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||
|
||||
public string DisplayName => _root;
|
||||
|
||||
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var primary = SafePath("version.json");
|
||||
var fallback = SafePath(Path.Combine("model", "version.json"));
|
||||
var file = File.Exists(primary) ? primary : fallback;
|
||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||
return Task.FromResult(Json.Read<RepoVersion>(file));
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var baseDir = SafePath(rootPath ?? "model");
|
||||
var result = new List<RepoEntry>();
|
||||
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
|
||||
|
||||
Walk(baseDir, baseDir, 0, result);
|
||||
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
|
||||
}
|
||||
|
||||
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
foreach (var sub in Directory.GetDirectories(dir))
|
||||
{
|
||||
var name = Path.GetFileName(sub);
|
||||
if (name.StartsWith('.')) continue;
|
||||
var rel = Relative(baseDir, sub);
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = Relative(_root, sub),
|
||||
RelativePath = rel,
|
||||
IsDirectory = true
|
||||
});
|
||||
Walk(sub, baseDir, depth + 1, result);
|
||||
}
|
||||
foreach (var file in Directory.GetFiles(dir))
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.StartsWith('.')) continue;
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = Relative(_root, file),
|
||||
RelativePath = Relative(baseDir, file),
|
||||
IsDirectory = false,
|
||||
Size = new FileInfo(file).Length
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
var local = SafePath(package.Path!);
|
||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
||||
}
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
|
||||
if (Path.IsPathRooted(url) && File.Exists(url))
|
||||
return await File.ReadAllBytesAsync(url, ct);
|
||||
if (Uri.TryCreate(url, UriKind.Absolute, out _))
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
return null;
|
||||
}
|
||||
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
||||
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"路径越界: {relative}");
|
||||
return full;
|
||||
}
|
||||
|
||||
private static string Relative(string baseDir, string file) =>
|
||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
||||
public sealed partial class DownloadJob : ObservableObject
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public string Id => Model.Id;
|
||||
public string Name => Model.LocalizedName;
|
||||
public string Version => Model.Manifest.Version;
|
||||
public CancellationTokenSource Cts { get; } = new();
|
||||
|
||||
[ObservableProperty] private DownloadState _state = DownloadState.Queued;
|
||||
[ObservableProperty] private double _progress;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private string _detailText = "";
|
||||
[ObservableProperty] private string? _error;
|
||||
|
||||
public DownloadJob(RemoteModel model)
|
||||
{
|
||||
Model = model;
|
||||
RefreshText();
|
||||
}
|
||||
|
||||
public bool IsActive => State is DownloadState.Queued or DownloadState.Running;
|
||||
public bool CanRetry => State is DownloadState.Failed or DownloadState.Canceled;
|
||||
public bool IsDone => State == DownloadState.Completed;
|
||||
|
||||
public void RefreshText()
|
||||
{
|
||||
StatusText = State switch
|
||||
{
|
||||
DownloadState.Queued => L.I["dl.status.queued"],
|
||||
DownloadState.Running => L.I["dl.status.downloading"],
|
||||
DownloadState.Completed => L.I["dl.status.done"],
|
||||
DownloadState.Failed => L.I["dl.status.failed"],
|
||||
_ => L.I["dl.status.canceled"]
|
||||
};
|
||||
DetailText = State == DownloadState.Failed && !string.IsNullOrEmpty(Error)
|
||||
? Error!
|
||||
: ModelScanner.HumanSize(Model.SizeBytes);
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(CanRetry));
|
||||
OnPropertyChanged(nameof(IsDone));
|
||||
}
|
||||
|
||||
partial void OnStateChanged(DownloadState value) => RefreshText();
|
||||
partial void OnErrorChanged(string? value) => RefreshText();
|
||||
}
|
||||
|
||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
public sealed class DownloadCenter
|
||||
{
|
||||
private readonly ModelRepository _repository;
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SemaphoreSlim _slots = new(2);
|
||||
|
||||
public ObservableCollection<DownloadJob> Jobs { get; } = new();
|
||||
public event Action? Installed;
|
||||
|
||||
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
||||
{
|
||||
_paths = paths;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public DownloadJob Enqueue(RemoteModel model)
|
||||
{
|
||||
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
||||
if (running != null) return running;
|
||||
|
||||
var job = new DownloadJob(model);
|
||||
Jobs.Insert(0, job);
|
||||
_ = RunAsync(job);
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task RunAsync(DownloadJob job)
|
||||
{
|
||||
// 在 UI 线程构造,回调自动回到 UI 线程
|
||||
var progress = new Progress<(long Done, long Total)>(p =>
|
||||
{
|
||||
job.Progress = p.Total > 0 ? Math.Clamp((double)p.Done / p.Total, 0, 1) : 0;
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
await _slots.WaitAsync(job.Cts.Token).ConfigureAwait(true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
job.State = DownloadState.Canceled;
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
job.State = DownloadState.Running;
|
||||
await ModelInstaller.InstallAsync(job.Model, _paths.ModelRoot, progress, job.Cts.Token)
|
||||
.ConfigureAwait(true);
|
||||
job.Progress = 1;
|
||||
job.State = DownloadState.Completed;
|
||||
_repository.NotifyChanged();
|
||||
Installed?.Invoke();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
job.State = DownloadState.Canceled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
job.Error = ex.Message;
|
||||
job.State = DownloadState.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(DownloadJob job)
|
||||
{
|
||||
try { job.Cts.Cancel(); } catch { }
|
||||
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
||||
}
|
||||
|
||||
public void Retry(DownloadJob job)
|
||||
{
|
||||
if (job.IsActive) return;
|
||||
Jobs.Remove(job);
|
||||
Enqueue(job.Model);
|
||||
}
|
||||
|
||||
public void Remove(DownloadJob job)
|
||||
{
|
||||
Cancel(job);
|
||||
Jobs.Remove(job);
|
||||
}
|
||||
|
||||
public void ClearFinished()
|
||||
{
|
||||
for (var i = Jobs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (Jobs[i].State is DownloadState.Completed or DownloadState.Canceled)
|
||||
Jobs.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
public int ActiveCount => Jobs.Count(j => j.IsActive);
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
||||
///
|
||||
/// · 版本判定:最新 Release 的 tag_name(如 v1.0.1 / GC-1.0.1)与本地程序集版本比较;
|
||||
/// · 发布包:按附件名识别平台(如 GC-1.0.1-Win-amd64.zip),用 browser_download_url 下载;
|
||||
/// · 校验:附件自带的 sha256/size(Gitee/GitCode 的 assets 可能没有 sha256,
|
||||
/// 此时退回 version.json 里同名 RID 条目的 sha256,两者都没有则只校验非空);
|
||||
/// · 模型清单与模型文件:完全委托给内部 GitCodeRemote,保持原有链路不变。
|
||||
///
|
||||
/// Release API 失败(仓库还没有 Release / 断网)时静默回退到 version.json 的
|
||||
/// launcher 字段,保证「只发仓库、不发 Release」的旧发布方式仍然可用。
|
||||
/// </summary>
|
||||
public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
private readonly GitCodeRemote _content;
|
||||
private readonly string _releasesUrl;
|
||||
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
|
||||
|
||||
// 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
|
||||
// headers 只在一处设置,多个线程并发读取是线程安全的。
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return client;
|
||||
}
|
||||
|
||||
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
|
||||
{
|
||||
_content = new GitCodeRemote(manifestUrl, repository);
|
||||
var (owner, repo) = ParseOwnerRepo(repository);
|
||||
_releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases";
|
||||
DisplayName = (string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)";
|
||||
}
|
||||
|
||||
private static (string Owner, string Repo) ParseOwnerRepo(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC");
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return (parts[0], repo);
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => SourcePreset.Detect(_content.DisplayName).Id;
|
||||
|
||||
/// <summary>
|
||||
/// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 只认 Release:拿不到任何 Release 就返回 null,由上层去问另一个源。
|
||||
/// 仓库里的 version.json 只用来补全「模型清单」与平台包兜底地址,
|
||||
/// 不再用它充当版本号来源。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var version = await _content.GetVersionAsync(ct);
|
||||
|
||||
bool gotRelease;
|
||||
try
|
||||
{
|
||||
gotRelease = await ApplyReleaseAsync(version, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
|
||||
gotRelease = false;
|
||||
}
|
||||
|
||||
if (!gotRelease)
|
||||
{
|
||||
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器),
|
||||
// 但模型清单仍然有效,保证模型能正常同步。
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)");
|
||||
if (version != null)
|
||||
{
|
||||
version.Launcher.Version = "";
|
||||
version.Launcher.Packages.Clear();
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<bool> ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
{
|
||||
if (version == null) return false;
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(12));
|
||||
var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
ReleaseInfo? latest = null;
|
||||
foreach (var el in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
var info = ParseRelease(el);
|
||||
if (info == null || info.Draft || info.Prerelease) continue;
|
||||
// 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层)
|
||||
if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info;
|
||||
}
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||
|
||||
version.Launcher.Version = latest.Version;
|
||||
|
||||
_assets.Clear();
|
||||
foreach (var asset in latest.Assets)
|
||||
{
|
||||
var rid = asset.RidFromName(asset.Name);
|
||||
if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue;
|
||||
// 同名平台取第一个有效附件
|
||||
if (!_assets.ContainsKey(rid))
|
||||
_assets[rid] = (asset.Url, asset.Sha256, asset.Size, asset.Name);
|
||||
}
|
||||
|
||||
// 把附件地址写回 packages:有附件就用附件的直链与校验值,
|
||||
// 没有对应平台附件时保留 version.json 里原来的 path/url 兜底。
|
||||
foreach (var (rid, info) in _assets)
|
||||
{
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg))
|
||||
{
|
||||
pkg = new RepoPackage();
|
||||
version.Launcher.Packages[rid] = pkg;
|
||||
}
|
||||
pkg.Url = info.Url;
|
||||
pkg.AssetName = info.Name;
|
||||
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
|
||||
if (info.Size > 0) pkg.Size = info.Size;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int CompareVersion(string a, string b)
|
||||
{
|
||||
if (Version.TryParse(a, out var va) && Version.TryParse(b, out var vb)) return va.CompareTo(vb);
|
||||
return string.Compare(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static ReleaseInfo? ParseRelease(JsonElement el)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new ReleaseInfo
|
||||
{
|
||||
TagName = Str(el, "tag_name") ?? Str(el, "tag") ?? "",
|
||||
Name = Str(el, "name") ?? "",
|
||||
Draft = Bool(el, "draft") ?? false,
|
||||
Prerelease = Bool(el, "prerelease") ?? Bool(el, "pre_release") ?? false,
|
||||
PublishedAt = Str(el, "published_at") ?? Str(el, "created_at")
|
||||
};
|
||||
if (el.TryGetProperty("assets", out var assets) && assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
// 跳过 GitCode 自动生成的源码包(type=source),只取真正的发布附件
|
||||
var type = Str(a, "type");
|
||||
if (string.Equals(type, "source", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? Str(a, "file_name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url"),
|
||||
DownloadUrl = Str(a, "download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size"),
|
||||
Sha256 = Str(a, "sha256") ?? Str(a, "digest"),
|
||||
Type = type
|
||||
});
|
||||
}
|
||||
}
|
||||
// 有些平台把附件放在顶层 assets_link / attachments
|
||||
if (info.Assets.Count == 0 &&
|
||||
el.TryGetProperty("attachments", out var att) && att.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in att.EnumerateArray())
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size")
|
||||
});
|
||||
}
|
||||
return info;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static string? Str(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static bool? Bool(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) &&
|
||||
(v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
|
||||
? v.GetBoolean() : null;
|
||||
|
||||
private static long Num(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
|
||||
// ---- 模型链路:原样委托,不做任何改动 ----
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
=> _content.ListTreeAsync(rootPath, ct);
|
||||
|
||||
public Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
=> _content.DownloadAsync(entry, ct);
|
||||
|
||||
/// <summary>启动器包:优先用 Release 附件直链下载(url 已被 ApplyReleaseAsync 覆盖)。</summary>
|
||||
public Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
=> _content.DownloadPackageAsync(package, ct);
|
||||
}
|
||||
@@ -1,318 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
|
||||
/// https://gitcode.com/<owner>/<repo>/tree/<branch>/model 这样的地址。
|
||||
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
|
||||
/// 文件项自带 download_url(raw.gitcode.com/blobs/<sha>/...),可直接下载二进制。
|
||||
/// </summary>
|
||||
public sealed class GitCodeRemote : IModelRemote
|
||||
{
|
||||
public const string DefaultRepository = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _api;
|
||||
private readonly string _branch;
|
||||
private readonly string _versionUrl;
|
||||
private readonly string? _fallbackUrl;
|
||||
private readonly string _displayName;
|
||||
private string _modelDir = "model";
|
||||
|
||||
public string DisplayName => _displayName;
|
||||
|
||||
public GitCodeRemote(string? manifestUrl = null, string? repository = null)
|
||||
{
|
||||
var (owner, repo, branch) = ParseRepository(repository);
|
||||
_branch = branch;
|
||||
_api = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/contents/";
|
||||
_displayName = string.IsNullOrWhiteSpace(repository)
|
||||
? DefaultRepository : repository!.TrimEnd('/');
|
||||
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||
{
|
||||
_versionUrl = _api + "version.json?ref=" + _branch;
|
||||
_fallbackUrl = _api + "model/version.json?ref=" + _branch;
|
||||
}
|
||||
else
|
||||
{
|
||||
_versionUrl = manifestUrl!;
|
||||
_fallbackUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从仓库 URL 解析 owner / repo / branch,解析失败回退到默认仓库。</summary>
|
||||
private static (string Owner, string Repo, string Branch) ParseRepository(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC", "main");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
|
||||
var owner = parts[0];
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
var branch = parts.Length >= 4 && parts[2].Equals("tree", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[3] : "main";
|
||||
return (owner, repo, branch);
|
||||
}
|
||||
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
RepoVersion? version = await ReadVersionFromAsync(_versionUrl, ct);
|
||||
if (version == null && _fallbackUrl != null)
|
||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||
_modelDir = version.ModelDir.Trim('/');
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
||||
{
|
||||
string text;
|
||||
try
|
||||
{
|
||||
// 离线 / 网络不通时最多等 10 秒,不能让启动界面一直卡在「检查更新」
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
text = await _http.GetStringAsync(url, timeout.Token);
|
||||
}
|
||||
catch (HttpRequestException) { return null; }
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; }
|
||||
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '{') return null;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var payload = text;
|
||||
if (doc.RootElement.TryGetProperty("encoding", out _) &&
|
||||
doc.RootElement.TryGetProperty("content", out var content))
|
||||
{
|
||||
var raw = Convert.FromBase64String(content.GetString() ?? "");
|
||||
payload = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
|
||||
payload, GC.Services.Json.Options);
|
||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归列出目录树(含目录项与文件项)。
|
||||
/// 每个子目录一次 HTTP 请求,因此并行展开同一层的所有目录,
|
||||
/// 否则 3 个模型、十几个目录串行请求会非常慢。
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
var bag = new System.Collections.Concurrent.ConcurrentBag<RepoEntry>();
|
||||
var repoPath = (rootPath ?? _modelDir).Trim('/');
|
||||
await WalkParallelAsync(repoPath, "", 0, bag, ct);
|
||||
|
||||
// 稳定排序:目录在前、按路径字典序,保证调用方拿到确定顺序
|
||||
result = bag.OrderBy(e => e.IsDirectory ? 0 : 1)
|
||||
.ThenBy(e => e.RelativePath, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkParallelAsync(string repoPath, string relative, int depth,
|
||||
System.Collections.Concurrent.ConcurrentBag<RepoEntry> bag, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
string text;
|
||||
try { text = await GetWithRetryAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
var subDirs = new List<(string Path, string Relative)>();
|
||||
|
||||
using (var doc = JsonDocument.Parse(text))
|
||||
{
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
// 这些目录不是模型运行数据,跳过可显著减少请求
|
||||
// (模型目录里常见的 src/ bin/ obj/ 是源码与构建产物)
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
bag.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) subDirs.Add((path!, childRelative));
|
||||
}
|
||||
}
|
||||
|
||||
if (subDirs.Count == 0) return;
|
||||
|
||||
// 同层并行;并发保持很低——GitCode API 对突发请求会返回 429
|
||||
using var gate = new SemaphoreSlim(2);
|
||||
var tasks = subDirs.Select(async d =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try { await WalkParallelAsync(d.Path, d.Relative, depth + 1, bag, ct); }
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string repoPath, string relative, int depth,
|
||||
List<RepoEntry> result, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) await WalkAsync(path!, childRelative, depth + 1, result, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>遍历时忽略的目录:源码与构建产物不属于模型运行数据。</summary>
|
||||
private static bool IsIgnoredDir(string name) => name switch
|
||||
{
|
||||
"src" => true,
|
||||
"bin" => true,
|
||||
"obj" => true,
|
||||
"node_modules" => true,
|
||||
".git" => true,
|
||||
".vs" => true,
|
||||
_ => false
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 带退避重试的 GET。GitCode API 对突发请求返回 429,
|
||||
/// 这里做 3 次指数退避,避免并行遍历时直接失败。
|
||||
/// </summary>
|
||||
private async Task<string> GetWithRetryAsync(string url, CancellationToken ct,
|
||||
int maxAttempts = 3)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _http.GetStringAsync(url, ct);
|
||||
}
|
||||
catch (HttpRequestException ex) when (attempt < maxAttempts)
|
||||
{
|
||||
// 429 / 5xx 才重试,其余直接抛
|
||||
var retriable = ex.StatusCode is null ||
|
||||
(int)ex.StatusCode == 429 ||
|
||||
(int)ex.StatusCode >= 500;
|
||||
if (!retriable) throw;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(400 * attempt * attempt), ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
|
||||
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
|
||||
|
||||
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (!doc.RootElement.TryGetProperty("content", out var content))
|
||||
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
|
||||
return Convert.FromBase64String(content.GetString() ?? "");
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
|
||||
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
try
|
||||
{
|
||||
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(apiUrl, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("download_url", out var dl))
|
||||
url = dl.GetString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
return await _http.GetByteArrayAsync(url!, ct);
|
||||
}
|
||||
|
||||
private static string Str(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() ?? "" : "";
|
||||
|
||||
private static string? NullableStr(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static long Num(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
|
||||
///
|
||||
/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path}
|
||||
/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url
|
||||
/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path}
|
||||
/// · Release:GET /api/v1/repos/{owner}/{repo}/releases
|
||||
/// 版本取 tag_name;附件取 assets[].browser_download_url
|
||||
///
|
||||
/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。
|
||||
/// </summary>
|
||||
public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
private readonly SourcePreset _preset;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
public GiteaRemote(SourcePreset preset)
|
||||
{
|
||||
_preset = preset;
|
||||
DisplayName = preset.Name;
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => _preset.Id;
|
||||
|
||||
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
|
||||
|
||||
// ---------------------------------------------------------------- 清单
|
||||
|
||||
/// <summary>
|
||||
/// 两件事分开取:
|
||||
/// · **模型清单**永远来自仓库 version.json(模型不需要发 Release)
|
||||
/// · **启动器版本**只认 Release;没有 Release 时把版本号留空,
|
||||
/// 由上层去问另一个源(LeaderUpdater 会横向比较)。
|
||||
/// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var fromRepo = await TryGetVersionFromRepoAsync(ct);
|
||||
var fromRelease = await TryGetVersionFromReleasesAsync(ct);
|
||||
|
||||
// 模型清单:仓库里有就用仓库的(保证模型能更新)
|
||||
var result = fromRepo ?? new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch
|
||||
};
|
||||
|
||||
if (fromRelease != null)
|
||||
{
|
||||
// Release 提供启动器版本与平台附件
|
||||
result.Launcher.Version = fromRelease.Launcher.Version;
|
||||
foreach (var kv in fromRelease.Launcher.Packages)
|
||||
result.Launcher.Packages[kv.Key] = kv.Value;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
|
||||
result.Launcher.Version = "";
|
||||
result.Launcher.Packages.Clear();
|
||||
|
||||
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
||||
return result.Models.Count > 0 ? result : null;
|
||||
}
|
||||
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") })
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = await Http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options);
|
||||
if (doc != null) return doc;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个),
|
||||
/// 并把它对应平台的附件填进 packages。
|
||||
/// </summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromReleasesAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
|
||||
|
||||
var candidates = new List<(string Version, JsonElement Node)>();
|
||||
foreach (var rel in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True)
|
||||
continue; // 草稿不算发布
|
||||
var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";
|
||||
var ver = VersionUtil.Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(ver)) continue;
|
||||
candidates.Add((ver, rel));
|
||||
}
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
// 还没发布 Release 是正常状态:交给上层去问另一个源
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
var best = candidates
|
||||
.OrderByDescending(c => VersionUtil.Parse(c.Version))
|
||||
.First();
|
||||
|
||||
var result = new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch,
|
||||
Launcher = new RepoLauncher { Version = best.Version }
|
||||
};
|
||||
|
||||
// 附件:按文件名识别平台
|
||||
if (best.Node.TryGetProperty("assets", out var assets) &&
|
||||
assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";
|
||||
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue;
|
||||
|
||||
var rid = PlatformFromAssetName(name);
|
||||
if (rid == null) continue;
|
||||
|
||||
var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
result.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = url,
|
||||
AssetName = name,
|
||||
Size = size
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result.Launcher.Packages.Count > 0 ? result : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64</summary>
|
||||
private static string? PlatformFromAssetName(string name)
|
||||
{
|
||||
var n = name.ToLowerInvariant();
|
||||
if (!n.EndsWith(".zip")) return null;
|
||||
if (n.Contains("win") && n.Contains("arm64")) return "win-arm64";
|
||||
if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64";
|
||||
if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64";
|
||||
if (n.Contains("mac") && n.Contains("x64")) return "osx-x64";
|
||||
if (n.Contains("linux") && n.Contains("x64")) return "linux-x64";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 目录
|
||||
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string apiPath, string relPrefix, List<RepoEntry> sink,
|
||||
CancellationToken ct, int depth)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
|
||||
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
|
||||
string json;
|
||||
try { json = await Http.GetStringAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// 单文件
|
||||
if (root.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
AddFile(root, relPrefix, sink);
|
||||
return;
|
||||
}
|
||||
if (root.ValueKind != JsonValueKind.Array) return;
|
||||
|
||||
var subdirs = new List<(string Path, string Rel)>();
|
||||
foreach (var item in root.EnumerateArray())
|
||||
{
|
||||
var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : "";
|
||||
var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : "";
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
// 跳过构建产物与源码,模型包只需要清单与数据
|
||||
if (type == "dir")
|
||||
{
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
subdirs.Add((apiPath + "/" + name, relPrefix + name + "/"));
|
||||
}
|
||||
else
|
||||
{
|
||||
AddFile(item, relPrefix, sink);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (p, rel) in subdirs)
|
||||
await WalkAsync(p, rel, sink, ct, depth + 1);
|
||||
}
|
||||
|
||||
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
|
||||
|
||||
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
|
||||
{
|
||||
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name;
|
||||
var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null;
|
||||
var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null;
|
||||
|
||||
sink.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path,
|
||||
RelativePath = relPrefix + name,
|
||||
IsDirectory = false,
|
||||
DownloadUrl = dl,
|
||||
Size = size,
|
||||
Sha = sha
|
||||
});
|
||||
}
|
||||
|
||||
private static bool IsIgnoredDir(string name) =>
|
||||
name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs"
|
||||
or ".idea" or ".vscode";
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
// 优先用 API 提供的 download_url;没有就按 raw 规约拼
|
||||
var url = entry.DownloadUrl;
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
url = _preset.RawUrl(entry.Path);
|
||||
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(package.Url)) return null;
|
||||
try { return await Http.GetByteArrayAsync(package.Url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -1,643 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
// ===========================================================================
|
||||
// 启动器更新模块(唯一实现)
|
||||
//
|
||||
// 需求(按用户):
|
||||
// · 只认 GitCode Release 的 latest 版本号(tag),文件名格式:
|
||||
// GC-<版本>-<系统>-<架构>.exe / .app
|
||||
// 例 GC-1.0.3-win-amd64.exe / GC-1.0.3-mac-arm64.app
|
||||
// · 当前运行版本与 latest 不同 => 提示更新;相同 => 无需更新
|
||||
// · 下载的新版解压到「当前运行目录」,与旧版并列;.GC 完全不动
|
||||
// · 更新完成后:删除同系统同架构、版本号 != latest 的其它 GC-* 文件;
|
||||
// 异系统 / 异架构的文件一律不碰
|
||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||
// ===========================================================================
|
||||
|
||||
public sealed class UpdateProgressInfo
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Stage { get; init; } = "";
|
||||
}
|
||||
|
||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
||||
|
||||
public sealed class UpdateRunResult
|
||||
{
|
||||
public UpdateRunState State { get; init; }
|
||||
public string Version { get; init; } = "";
|
||||
public string Message { get; init; } = "";
|
||||
public string? PackageName { get; init; }
|
||||
public string? NewAppPath { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||
public static class LauncherUpdater
|
||||
{
|
||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||
public static string RunningVersion => UpdateService.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||
public static string CurrentRid => UpdateService.CurrentRid;
|
||||
|
||||
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
||||
public static string PlatformLabel => CurrentRid switch
|
||||
{
|
||||
"win-x64" => "win-amd64",
|
||||
"win-arm64" => "win-arm64",
|
||||
"osx-arm64" => "mac-arm64",
|
||||
"osx-x64" => "mac-x64",
|
||||
"linux-x64" => "linux-amd64",
|
||||
_ => CurrentRid
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 检查
|
||||
|
||||
/// <summary>
|
||||
/// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。
|
||||
/// 只比版本号,不比 sha256。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**,
|
||||
/// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。
|
||||
/// </summary>
|
||||
public static async Task<string?> CheckAsync(CancellationToken ct = default)
|
||||
=> await CheckAllAsync(null, ct);
|
||||
|
||||
/// <summary>兼容旧调用:优先用给定 remote,同时仍会比对另一个源。</summary>
|
||||
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
|
||||
=> await CheckAllAsync(remote, ct);
|
||||
|
||||
private static async Task<string?> CheckAllAsync(IModelRemote? preferred, CancellationToken ct)
|
||||
{
|
||||
var candidates = new List<(string Source, string Version)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 优先复用调用方已建好的 remote(避免重复建实例)
|
||||
var remote = preferred != null &&
|
||||
SourcePreset.Detect(preferred.DisplayName).Id == preset.Id
|
||||
? preferred
|
||||
: SourceSelector.CreateRemote(preset);
|
||||
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
if (v.Length == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: {v}");
|
||||
candidates.Add((preset.Name, v));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.Count == 0) return null;
|
||||
|
||||
// 取版本号最高的(第 7 项)
|
||||
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
|
||||
Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})");
|
||||
|
||||
var cmp = VersionUtil.Compare(best.Version, RunningVersion);
|
||||
|
||||
// 远端版本更新 → 提示更新
|
||||
if (cmp > 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新");
|
||||
return best.Version;
|
||||
}
|
||||
|
||||
// 远端版本更旧 → 不提示
|
||||
if (cmp < 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本号相同:比对当前程序的 sha256 与 Release 包
|
||||
// 相符 → 视为最新,不提示
|
||||
// 不相符 → 说明是重新编译的同版本程序,必须提示下载
|
||||
var same = await SameFingerprintAsync(best.Source, best.Version, ct);
|
||||
if (same == null)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理");
|
||||
return null;
|
||||
}
|
||||
if (same.Value)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本相同但指纹不同:是自行编译的构建,不提示更新
|
||||
Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新");
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 比对「当前运行程序」与「Release 平台包」的 sha256。
|
||||
/// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。
|
||||
/// </summary>
|
||||
private static async Task<bool?> SameFingerprintAsync(string sourceName, string version,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var preset = SourcePreset.All.FirstOrDefault(p =>
|
||||
string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase));
|
||||
if (preset == null) return null;
|
||||
|
||||
var rid = CurrentRid;
|
||||
Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…");
|
||||
|
||||
// 定位进程对应的可执行文件 / .app
|
||||
var self = Environment.ProcessPath;
|
||||
if (string.IsNullOrWhiteSpace(self)) return null;
|
||||
var selfPath = self!;
|
||||
// 单文件 / dotnet 宿主时退回到程序集位置
|
||||
if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
selfPath = typeof(LauncherUpdater).Assembly.Location;
|
||||
|
||||
var selfHash = await HashFileAsync(selfPath, ct);
|
||||
Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…");
|
||||
|
||||
// 下载 Release 对应平台包,取包内主程序再算
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null)
|
||||
return null;
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg, ct);
|
||||
if (bytes == null || bytes.Length == 0) return null;
|
||||
|
||||
var remoteHash = await HashZipPayloadAsync(bytes, ct);
|
||||
if (remoteHash == null) return null;
|
||||
Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…");
|
||||
|
||||
return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[update] sha256 比对失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var fs = File.OpenRead(path);
|
||||
var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct);
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
|
||||
/// <summary>从发布包(zip)里取出主程序并算 sha256。</summary>
|
||||
private static async Task<string?> HashZipPayloadAsync(byte[] zip, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var ms = new MemoryStream(zip);
|
||||
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
||||
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
|
||||
var entry = archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
|
||||
e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
|
||||
if (entry == null) return null;
|
||||
|
||||
await using var es = entry.Open();
|
||||
using var buf = new MemoryStream();
|
||||
await es.CopyToAsync(buf, ct);
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray());
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。
|
||||
/// 某个源没有 Release(返回 null)时自动跳过。
|
||||
/// </summary>
|
||||
private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync(
|
||||
IModelRemote fallback, CancellationToken ct)
|
||||
{
|
||||
var rid = CurrentRid;
|
||||
var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 无 Release");
|
||||
continue;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包");
|
||||
continue;
|
||||
}
|
||||
var hasPkg = v.Launcher.Packages.ContainsKey(rid) ||
|
||||
v.Launcher.Packages.ContainsKey("default");
|
||||
if (!hasPkg)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用");
|
||||
found.Add((preset.Name, v, remote));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (found.Count == 0) return null;
|
||||
|
||||
var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First();
|
||||
Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})");
|
||||
return (best.Version, best.Remote);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
/// <summary>
|
||||
/// 下载 latest 版本到当前运行目录(与旧版并列)。
|
||||
/// 返回新版包名,供后续替换脚本使用。
|
||||
/// </summary>
|
||||
public static async Task<UpdateRunResult> DownloadAsync(
|
||||
AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" });
|
||||
|
||||
// 两个源都问一遍:某个源没发 Release 时自动换另一个,
|
||||
// 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
|
||||
// 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。
|
||||
// 注意:模型清单可能仍然有效,但启动器升级必须有 Release。
|
||||
var hasUsable = version != null &&
|
||||
!string.IsNullOrWhiteSpace(version.Launcher.Version) &&
|
||||
version.Launcher.Packages.Count > 0;
|
||||
|
||||
if (!hasUsable)
|
||||
{
|
||||
var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName;
|
||||
Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源");
|
||||
var pick = await GetBestReleaseAsync(remote, ct);
|
||||
if (pick == null) return Fail("两个源都没有可用的 Release 发布包");
|
||||
version = pick.Value.Version;
|
||||
remote = pick.Value.Remote; // 后续下载必须用这个源的 remote
|
||||
}
|
||||
|
||||
var latest = (version!.Launcher.Version ?? "").Trim();
|
||||
var rid = CurrentRid;
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) &&
|
||||
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
||||
return Fail($"该平台({rid})没有对应发布包");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
||||
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
||||
|
||||
// sha256 校验(Release 提供时)
|
||||
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return Fail("下载文件校验失败(sha256 不符)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压到当前目录" });
|
||||
|
||||
// 解压到临时中转目录,再搬到当前运行目录
|
||||
var installDir = paths.InstallDirectory;
|
||||
Directory.CreateDirectory(installDir);
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
try { ZipSafety.ExtractToDirectory(zip, staging); }
|
||||
finally { try { File.Delete(zip); } catch { } }
|
||||
|
||||
// 只展平「单个非 .app 顶层目录」的 zip
|
||||
FlattenStaging(staging);
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" });
|
||||
|
||||
var packageName = MoveToInstallDir(staging, installDir, latest);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
|
||||
Directory.CreateDirectory(paths.UpdateRoot);
|
||||
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
|
||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
return new UpdateRunResult
|
||||
{
|
||||
State = UpdateRunState.Ready,
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已下载到当前目录",
|
||||
PackageName = packageName,
|
||||
NewAppPath = Path.Combine(installDir, packageName)
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
catch (Exception ex) { return Fail(ex.Message); }
|
||||
}
|
||||
|
||||
private static UpdateRunResult Fail(string msg) => new()
|
||||
{
|
||||
State = UpdateRunState.Failed,
|
||||
Message = msg
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 应用(下次启动)
|
||||
|
||||
/// <summary>
|
||||
/// 生成替换脚本并启动。脚本等本进程退出后:
|
||||
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。
|
||||
/// 返回 true 表示调用方应立即退出进程。
|
||||
/// </summary>
|
||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
||||
{
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||
{
|
||||
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var isWin = OperatingSystem.IsWindows();
|
||||
var script = Path.Combine(paths.UpdateRoot, isWin ? "apply.bat" : "apply.sh");
|
||||
var content = isWin ? WindowsScript() : UnixScript();
|
||||
File.WriteAllText(script, content, new System.Text.UTF8Encoding(false));
|
||||
|
||||
if (!isWin)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.SetUnixFileMode(script,
|
||||
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
var psi = isWin
|
||||
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
||||
{ UseShellExecute = false, CreateNoWindow = true }
|
||||
: new System.Diagnostics.ProcessStartInfo("/bin/sh")
|
||||
{ UseShellExecute = false, CreateNoWindow = true };
|
||||
if (isWin) psi.ArgumentList.Add("/c");
|
||||
psi.ArgumentList.Add(script);
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"启动替换脚本失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary>
|
||||
public static bool TryApplyPending(AppPaths paths)
|
||||
{
|
||||
if (paths.IsDevelopment) return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
var name = ReadMarker(marker, "NAME");
|
||||
if (string.IsNullOrWhiteSpace(name)) return false;
|
||||
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!)))
|
||||
return false; // 新版本不在了,放弃
|
||||
|
||||
return ScheduleApply(paths, name!);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 脚本(全部相对路径)
|
||||
|
||||
private static string UnixScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("#!/bin/sh");
|
||||
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up");
|
||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && pwd)");
|
||||
s.AppendLine("MARKER=\"$HERE/update.txt\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# read marker");
|
||||
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
||||
s.AppendLine("if [ ! -e \"$NEW\" ]; then");
|
||||
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# wait for old process to exit (this script is started by it)");
|
||||
s.AppendLine("sleep 2");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# launch new version first");
|
||||
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
|
||||
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
||||
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
|
||||
s.AppendLine(" [ -e \"$item\" ] || continue");
|
||||
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
||||
s.AppendLine(" base=$(basename \"$item\")");
|
||||
s.AppendLine(" stem=${base#GC-}");
|
||||
s.AppendLine(" case \"$base\" in");
|
||||
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
||||
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
||||
s.AppendLine(" *) continue ;;");
|
||||
s.AppendLine(" esac");
|
||||
s.AppendLine(" ver=${stem%%-*}");
|
||||
s.AppendLine(" rest=${stem#*-}");
|
||||
s.AppendLine(" plat=\"${rest%-*}-${rest##*-}\"");
|
||||
s.AppendLine(" # skip other platforms entirely");
|
||||
s.AppendLine(" [ \"$plat\" != \"$NEWPLAT\" ] && continue");
|
||||
s.AppendLine(" # same platform: keep only latest version");
|
||||
s.AppendLine(" if [ \"$ver\" = \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"keep: $base\"");
|
||||
s.AppendLine(" else");
|
||||
s.AppendLine(" echo \"remove (version $ver != $NEWVER): $base\"");
|
||||
s.AppendLine(" rm -rf \"$item\" 2>/dev/null");
|
||||
s.AppendLine(" fi");
|
||||
s.AppendLine("done");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rm -f \"$MARKER\"");
|
||||
s.AppendLine("rm -f \"$HERE\"/*.sh 2>/dev/null");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
private static string WindowsScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("@echo off");
|
||||
s.AppendLine("chcp 65001 >nul 2>&1");
|
||||
s.AppendLine("set \"HERE=%~dp0\"");
|
||||
s.AppendLine("set \"DST=%~dp0..\\..\"");
|
||||
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
|
||||
s.AppendLine("timeout /t 2 /nobreak >nul");
|
||||
s.AppendLine();
|
||||
s.AppendLine("set \"NEWNAME=\"");
|
||||
s.AppendLine("set \"NEWVER=\"");
|
||||
s.AppendLine("set \"NEWPLAT=\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
|
||||
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("if not exist \"%DST%\\%NEWNAME%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem launch new version");
|
||||
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("powershell -NoProfile -ExecutionPolicy Bypass -Command \"^");
|
||||
s.AppendLine("$dst='%DST%'; $new='%NEWNAME%'; $ver='%NEWVER%'; $plat='%NEWPLAT%';^");
|
||||
s.AppendLine("Get-ChildItem -LiteralPath $dst -Filter 'GC-*' | ForEach-Object {^");
|
||||
s.AppendLine(" $n=$_.Name; if($n -eq $new){return};^");
|
||||
s.AppendLine(" $m=[regex]::Match($n,'^GC-(.+?)-([^-]+)-([^-]+)\\.(app|exe)$');^");
|
||||
s.AppendLine(" if(-not $m.Success){return};^");
|
||||
s.AppendLine(" $fver=$m.Groups[1].Value; $fplat=$m.Groups[2].Value+'-'+$m.Groups[3].Value;^");
|
||||
s.AppendLine(" if($fplat -ne $plat){return};^");
|
||||
s.AppendLine(" if($fver -eq $ver){ Write-Host \\\"keep: $n\\\" }^");
|
||||
s.AppendLine(" else { Write-Host \\\"remove: $n\\\"; Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }^");
|
||||
s.AppendLine("}\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("del /Q \"%MARKER%\" >nul 2>&1");
|
||||
s.AppendLine("del /Q \"%~f0\" >nul 2>&1");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
/// <summary>展平只有一个顶层目录、且不是 .app 的 zip。</summary>
|
||||
private static void FlattenStaging(string dir)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(dir);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var flat = dir + "-flat";
|
||||
if (Directory.Exists(flat)) Directory.Delete(flat, true);
|
||||
Directory.Move(inner, flat);
|
||||
Directory.Delete(dir, true);
|
||||
Directory.Move(flat, dir);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把 staging 里的新版搬到当前目录,与旧版并列。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。.GC 绝不覆盖。
|
||||
/// </summary>
|
||||
private static string? MoveToInstallDir(string staging, string installDir, string latest)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(staging))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var dest = Path.Combine(installDir, name);
|
||||
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
|
||||
// 保证 .app 里可执行文件可执行
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(dest))
|
||||
{
|
||||
var macOs = Path.Combine(dest, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var f in Directory.GetFiles(macOs, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var mode = File.GetUnixFileMode(f);
|
||||
File.SetUnixFileMode(f, mode | UnixFileMode.UserExecute);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return name;
|
||||
}
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"安装新版失败: {ex.Message}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ReadMarker(string file, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file))
|
||||
{
|
||||
if (line.StartsWith(key + "=", StringComparison.Ordinal))
|
||||
return line[(key.Length + 1)..].Trim();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelInstaller
|
||||
{
|
||||
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
|
||||
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
|
||||
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
|
||||
{
|
||||
var target = Path.Combine(modelRoot, model.Id);
|
||||
var staging = target + ".installing";
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
long total = 0;
|
||||
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
|
||||
foreach (var file in files)
|
||||
{
|
||||
try { total += new FileInfo(file).Length; } catch { }
|
||||
}
|
||||
|
||||
long done = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var relative = Path.GetRelativePath(model.Directory, file);
|
||||
// 路径穿越防护:相对路径必须完整落在 staging 目录内
|
||||
var dest = Path.GetFullPath(Path.Combine(staging, relative));
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
|
||||
await using (var src = File.OpenRead(file))
|
||||
await using (var dst = File.Create(dest))
|
||||
{
|
||||
await src.CopyToAsync(dst, 81920, ct);
|
||||
}
|
||||
long length = 0;
|
||||
try { length = new FileInfo(dest).Length; } catch { }
|
||||
done += length;
|
||||
progress?.Report((done, total <= 0 ? done : total));
|
||||
}
|
||||
|
||||
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
var hasBackup = false;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(target))
|
||||
{
|
||||
Directory.Move(target, backup);
|
||||
hasBackup = true;
|
||||
}
|
||||
Directory.Move(staging, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
|
||||
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
|
||||
Directory.Move(backup, target);
|
||||
throw;
|
||||
}
|
||||
if (hasBackup)
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
|
||||
progress?.Report((total, total));
|
||||
return target;
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,302 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 从链接导入模型源。
|
||||
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。
|
||||
/// </summary>
|
||||
public sealed class ModelSourceClient
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
public ModelSourceClient(AppPaths paths) => _paths = paths;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(source.Url))
|
||||
return new SourceIndex { SourceId = source.Id, Error = "dl.error.emptyUrl" };
|
||||
|
||||
try
|
||||
{
|
||||
var (root, fromCache) = await ResolveRootAsync(source, force, log, ct);
|
||||
var models = new List<RemoteModel>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(Path.Combine(root, "model")))
|
||||
{
|
||||
models.Add(new RemoteModel
|
||||
{
|
||||
Manifest = manifest,
|
||||
Directory = dir,
|
||||
SizeBytes = ModelScanner.DirectorySize(dir),
|
||||
SourceId = source.Id
|
||||
});
|
||||
}
|
||||
|
||||
return new SourceIndex
|
||||
{
|
||||
SourceId = source.Id,
|
||||
Root = root,
|
||||
Models = models,
|
||||
FromCache = fromCache,
|
||||
ResolvedFrom = root
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return new SourceIndex { SourceId = source.Id, Error = "dl.error.canceled" };
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new SourceIndex { SourceId = source.Id, Error = ex.Message };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(string Root, bool FromCache)> ResolveRootAsync(ModelSource source, bool force,
|
||||
IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
var raw = source.Url.Trim();
|
||||
|
||||
// 1) 本地目录(开发模型源最方便)
|
||||
var localPath = raw.StartsWith("file://", StringComparison.OrdinalIgnoreCase)
|
||||
? new Uri(raw).LocalPath
|
||||
: raw;
|
||||
if (Directory.Exists(localPath))
|
||||
{
|
||||
log?.Report("local");
|
||||
return (localPath, true);
|
||||
}
|
||||
|
||||
var cacheDir = Path.Combine(_paths.CacheRoot, "sources", source.Id);
|
||||
if (!force && Directory.Exists(Path.Combine(cacheDir, "model")))
|
||||
{
|
||||
log?.Report("cache");
|
||||
return (cacheDir, true);
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
|
||||
// 2) zip 直链 / 托管平台归档
|
||||
foreach (var url in ArchiveCandidates(raw, source.Branch))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
log?.Report("zip:" + url);
|
||||
await DownloadZipAsync(url, cacheDir, ct);
|
||||
if (Directory.Exists(Path.Combine(cacheDir, "model")))
|
||||
return (cacheDir, false);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
log?.Report("zip-failed:" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// 3) git clone(需要本机安装 git)
|
||||
log?.Report("git");
|
||||
if (await TryGitCloneAsync(raw, cacheDir, source.Branch, ct))
|
||||
return (cacheDir, false);
|
||||
|
||||
throw new InvalidOperationException("dl.error.unreachable");
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ArchiveCandidates(string url, string? branch)
|
||||
{
|
||||
if (url.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
yield return url;
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) yield break;
|
||||
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments.Length < 2) yield break;
|
||||
|
||||
var owner = segments[0];
|
||||
var repo = segments[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? segments[1][..^4]
|
||||
: segments[1];
|
||||
var host = uri.Host.ToLowerInvariant();
|
||||
|
||||
var branches = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(branch)) branches.Add(branch!);
|
||||
else if (host.Contains("gitee")) { branches.Add("master"); branches.Add("main"); }
|
||||
else { branches.Add("main"); branches.Add("master"); }
|
||||
|
||||
foreach (var b in branches)
|
||||
{
|
||||
if (host.Contains("github.com"))
|
||||
yield return $"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{b}";
|
||||
else if (host.Contains("gitlab"))
|
||||
yield return $"https://gitlab.com/{owner}/{repo}/-/archive/{b}/{repo}-{b}.zip";
|
||||
else if (host.Contains("gitee.com"))
|
||||
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
||||
else
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
||||
{
|
||||
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(tmpRoot);
|
||||
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
||||
try
|
||||
{
|
||||
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var input = await response.Content.ReadAsStreamAsync(ct);
|
||||
await using var output = File.Create(zipPath);
|
||||
await input.CopyToAsync(output, 81920, ct);
|
||||
}
|
||||
|
||||
var extractDir = Path.Combine(tmpRoot, "extract");
|
||||
Directory.CreateDirectory(extractDir);
|
||||
ZipSafety.ExtractToDirectory(zipPath, extractDir);
|
||||
|
||||
var root = FindModelRoot(extractDir) ?? extractDir;
|
||||
foreach (var entry in Directory.GetFileSystemEntries(root))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
var dest = Path.Combine(cacheDir, name);
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpRoot)) Directory.Delete(tmpRoot, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindModelRoot(string dir, int depth = 0)
|
||||
{
|
||||
if (Directory.Exists(Path.Combine(dir, "model"))) return dir;
|
||||
if (depth >= 2) return null;
|
||||
foreach (var child in Directory.GetDirectories(dir))
|
||||
{
|
||||
var found = FindModelRoot(child, depth + 1);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<bool> TryGitCloneAsync(string url, string cacheDir, string? branch, CancellationToken ct)
|
||||
{
|
||||
if (cacheDir.Length > 0 && Directory.Exists(cacheDir))
|
||||
{
|
||||
foreach (var f in Directory.GetFileSystemEntries(cacheDir))
|
||||
{
|
||||
if (Directory.Exists(f)) Directory.Delete(f, true);
|
||||
else File.Delete(f);
|
||||
}
|
||||
}
|
||||
|
||||
// 只拉取 model/ 目录:整仓 clone 会把 .git / src / dist 一起拖下来
|
||||
// (实测 700MB+),既慢又容易超时,表现就是「读不到模型源」。
|
||||
// 先浅克隆到临时目录,再用 sparse-checkout 只检出 model/。
|
||||
var tmpDir = cacheDir + ".tmp";
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true);
|
||||
|
||||
// 1) 初始化 + 加远程(比 clone 更快,避免先拉全量)
|
||||
var initArgs = new List<string> { "init", "--quiet", tmpDir };
|
||||
if (!await RunGitAsync(initArgs, ct)) return false;
|
||||
|
||||
var remoteArgs = new List<string> { "-C", tmpDir, "remote", "add", "origin", url };
|
||||
if (!await RunGitAsync(remoteArgs, ct)) return false;
|
||||
|
||||
// 2) 只允许 model 目录参与检出
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "config", "core.sparseCheckout", "true" }, ct);
|
||||
var sparseFile = Path.Combine(tmpDir, ".git", "info", "sparse-checkout");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sparseFile)!);
|
||||
File.WriteAllText(sparseFile, "model/\n");
|
||||
|
||||
// 3) 浅拉指定分支
|
||||
var branchName = string.IsNullOrWhiteSpace(branch) ? "main" : branch!;
|
||||
var fetchArgs = new List<string>
|
||||
{
|
||||
"-C", tmpDir, "fetch", "--depth", "1", "--filter=blob:none", "origin", branchName
|
||||
};
|
||||
if (!await RunGitAsync(fetchArgs, ct)) return false;
|
||||
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "checkout", "FETCH_HEAD" }, ct);
|
||||
|
||||
// 4) 把 model/ 移到缓存根,与原有目录结构一致
|
||||
var modelDir = Path.Combine(tmpDir, "model");
|
||||
if (!Directory.Exists(modelDir))
|
||||
{
|
||||
Console.Error.WriteLine("git sparse-checkout 后未找到 model/ 目录");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
Directory.Move(modelDir, Path.Combine(cacheDir, "model"));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 拉取异常: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>安静地跑一条 git 命令,返回是否成功。</summary>
|
||||
private static async Task<bool> RunGitAsync(List<string> args, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("git")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
foreach (var a in args) psi.ArgumentList.Add(a);
|
||||
|
||||
using var process = Process.Start(psi);
|
||||
if (process == null) return false;
|
||||
var errTask = process.StandardError.ReadToEndAsync(ct);
|
||||
await process.WaitForExitAsync(ct);
|
||||
var err = await errTask;
|
||||
if (process.ExitCode != 0)
|
||||
Console.Error.WriteLine($"git {string.Join(' ', args)} 失败: {err.Trim()}");
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 执行失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,12 @@ public sealed class SettingsService
|
||||
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;
|
||||
}
|
||||
@@ -28,7 +34,7 @@ public sealed class SettingsService
|
||||
/// 老配置里的自定义源会被清理掉。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
|
||||
@@ -53,12 +53,12 @@ public sealed class SourcePreset
|
||||
{
|
||||
Id = "gitcode",
|
||||
Name = "GitCode",
|
||||
HomeUrl = "https://gitcode.com/2509_92447106/GC",
|
||||
HomeUrl = "https://gitcode.com/Morris_1/GC",
|
||||
ApiBase = "https://api.gitcode.com/api/v5",
|
||||
RawBase = "https://gitcode.com",
|
||||
Kind = "gitcode",
|
||||
RawStyle = "plain",
|
||||
Owner = "2509_92447106",
|
||||
Owner = "Morris_1",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
||||
///
|
||||
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
|
||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||
/// 避免每次点下载都重新测速。
|
||||
/// </summary>
|
||||
public sealed class SourceSelector
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
|
||||
return c;
|
||||
}
|
||||
|
||||
private readonly object _lock = new();
|
||||
private SourcePreset? _cached;
|
||||
private DateTime _cachedAt = DateTime.MinValue;
|
||||
private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3);
|
||||
|
||||
/// <summary>最近一次选中的源(未探测时为空)。</summary>
|
||||
public SourcePreset? Current { get { lock (_lock) return _cached; } }
|
||||
|
||||
/// <summary>每个源的探测耗时(毫秒),供界面展示。</summary>
|
||||
public IReadOnlyDictionary<string, long> LastLatency { get; private set; } =
|
||||
new Dictionary<string, long>();
|
||||
|
||||
/// <summary>
|
||||
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
||||
/// 两个都失败时返回 GitCode(默认源)。
|
||||
/// </summary>
|
||||
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl)
|
||||
return _cached;
|
||||
}
|
||||
|
||||
var probes = SourcePreset.All.Select(async p =>
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var ok = await ProbeAsync(p, ct);
|
||||
sw.Stop();
|
||||
return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds);
|
||||
});
|
||||
|
||||
var results = await Task.WhenAll(probes);
|
||||
|
||||
var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms);
|
||||
LastLatency = latencies;
|
||||
|
||||
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
||||
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_cached = chosen;
|
||||
_cachedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
|
||||
+ $" → 选择 {chosen.Name}");
|
||||
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 探测:能拿到合法 JSON 才算可用。
|
||||
/// 注意两个平台取文件的方式不同:
|
||||
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
|
||||
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
|
||||
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
|
||||
/// </summary>
|
||||
private static async Task<bool> ProbeAsync(SourcePreset preset, CancellationToken ct)
|
||||
{
|
||||
if (preset.Kind == "gitcode")
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, api);
|
||||
req.Headers.Accept.ParseAdd("application/json");
|
||||
using var resp = await Http.SendAsync(req, cts.Token);
|
||||
if (!resp.IsSuccessStatusCode) return false;
|
||||
var text = await resp.Content.ReadAsStringAsync(cts.Token);
|
||||
return text.TrimStart().StartsWith('{');
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") };
|
||||
|
||||
foreach (var url in urls)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var text = await Http.GetStringAsync(url, cts.Token);
|
||||
if (text.TrimStart().StartsWith('{')) return true;
|
||||
}
|
||||
catch { /* 换下一个地址 */ }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>为指定源创建对应的 remote 实现。</summary>
|
||||
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
|
||||
{
|
||||
"gitea" => new GiteaRemote(preset),
|
||||
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
|
||||
};
|
||||
}
|
||||
@@ -1,335 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_remote = remote;
|
||||
}
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||
|
||||
private static string? _versionOverride;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
||||
|
||||
// 用**本程序集**的版本,而不是 GetEntryAssembly()。
|
||||
// EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序,
|
||||
// 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。
|
||||
var asm = typeof(UpdateService).Assembly;
|
||||
var v = asm.GetName().Version;
|
||||
if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0))
|
||||
{
|
||||
// 兜底:读 InformationalVersion(Directory.Build.props 里的 <Version>)
|
||||
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
if (!string.IsNullOrWhiteSpace(info))
|
||||
{
|
||||
var core = info!.Split('+')[0].Trim();
|
||||
if (Version.TryParse(core, out var iv))
|
||||
v = iv;
|
||||
}
|
||||
}
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>测试 / 自检时临时指定版本号。</summary>
|
||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var arch = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
||||
return RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
||||
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
||||
/// </summary>
|
||||
public static IModelRemote CreateRemote(AppSettings settings)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
return SourceSelector.CreateRemote(SourcePreset.Detect(settings.UpdateRepository));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步版本:先探测 Xhmcl / GitCode 两个源,取最快的那个。
|
||||
/// 启动更新、下载页、检查更新统一走这里,保证「用同一个源、同一种下载方式」。
|
||||
/// </summary>
|
||||
public static async Task<IModelRemote> CreateRemoteAsync(AppSettings settings,
|
||||
SourceSelector selector, bool forceProbe = false, CancellationToken ct = default)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
|
||||
var preset = await selector.PickFastestAsync(forceProbe, ct);
|
||||
return SourceSelector.CreateRemote(preset);
|
||||
}
|
||||
|
||||
public async Task<UpdateResult> RunAsync(bool force,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
|
||||
{
|
||||
// 开发态的 model/ 里有源码与工程文件,模型自动替换会破坏源码目录,
|
||||
// 因此开发态只做「启动器版本检查」(下载到 .GC/update 暂存,可验证链路),
|
||||
// 跳过模型替换。要用正式流程验证请跑 ./build.sh update-test。
|
||||
var devMode = _paths.IsDevelopment &&
|
||||
Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1";
|
||||
|
||||
if (!force && !_settings.Current.AutoUpdateOnStartup)
|
||||
return new UpdateResult { Outcome = UpdateOutcome.Disabled, Message = L.I["update.disabled"] };
|
||||
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.02,
|
||||
Message = L.I["update.checking"],
|
||||
Detail = _remote.DisplayName
|
||||
});
|
||||
|
||||
RepoVersion? remote;
|
||||
try
|
||||
{
|
||||
remote = await _remote.GetVersionAsync(ct);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = L.I["update.offline"],
|
||||
Error = ex.Message
|
||||
};
|
||||
}
|
||||
|
||||
if (remote == null)
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = L.I["update.noManifest"]
|
||||
};
|
||||
|
||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||
_settings.Save();
|
||||
|
||||
// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,
|
||||
// 这里只做「模型同步到最新版」。
|
||||
string? launcherMessage = null;
|
||||
|
||||
// ---- 同步所有模型到最新版 ----
|
||||
// 开发态跳过:仓库 model/ 里有源码,整体替换会破坏工程目录。
|
||||
var needed = devMode
|
||||
? new List<RepoModel>()
|
||||
: remote.Models.Where(NeedsModel).ToList();
|
||||
var updated = new List<string>();
|
||||
var errors = new List<string>();
|
||||
|
||||
for (var i = 0; i < needed.Count; i++)
|
||||
{
|
||||
var model = needed[i];
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * i / Math.Max(1, needed.Count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = model.Version
|
||||
});
|
||||
try
|
||||
{
|
||||
await InstallModelAsync(model, progress, i, needed.Count, ct);
|
||||
_settings.Current.InstalledModelVersions[model.Id] = model.Version;
|
||||
_settings.Save();
|
||||
updated.Add(model.Id);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
errors.Add($"{model.Id}: {ex.Message}");
|
||||
Console.Error.WriteLine($"模型更新失败 {model.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgress { Value = 1, Message = L.I["update.done"] });
|
||||
|
||||
var outcome = errors.Count > 0
|
||||
? UpdateOutcome.Partial
|
||||
: (updated.Count > 0 || launcherMessage != null)
|
||||
? UpdateOutcome.Applied
|
||||
: UpdateOutcome.NoChange;
|
||||
|
||||
var message = updated.Count > 0
|
||||
? L.I.F("update.applied", updated.Count)
|
||||
: launcherMessage != null
|
||||
? L.I["update.modelsLatest"]
|
||||
: devMode
|
||||
? "开发态:已检查启动器,模型替换已跳过(保护仓库源码)"
|
||||
: L.I["update.noChange"];
|
||||
if (errors.Count > 0) message += L.I.F("update.partial", errors.Count);
|
||||
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = outcome,
|
||||
Message = message,
|
||||
UpdatedModels = updated.Count,
|
||||
ModelNames = updated,
|
||||
LauncherMessage = launcherMessage,
|
||||
Error = errors.Count > 0 ? string.Join("; ", errors) : null
|
||||
};
|
||||
}
|
||||
|
||||
private bool NeedsModel(RepoModel model)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(model.Id) || string.IsNullOrWhiteSpace(model.Version)) return false;
|
||||
var dir = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
if (!Directory.Exists(dir)) return true;
|
||||
if (!File.Exists(Path.Combine(dir, model.Id + ".json"))) return true;
|
||||
return !_settings.Current.InstalledModelVersions.TryGetValue(model.Id, out var local) ||
|
||||
!string.Equals(local, model.Version, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>只下载模型清单与模型数据目录,源码 / 文档不进运行目录。</summary>
|
||||
private static bool IsPayload(string id, string relative)
|
||||
{
|
||||
var rel = relative.Replace('\\', '/');
|
||||
// 拒绝任何形式的父目录穿越与绝对路径
|
||||
if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false;
|
||||
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private async Task InstallModelAsync(RepoModel model, IProgress<UpdateProgress>? progress,
|
||||
int index, int count, CancellationToken ct)
|
||||
{
|
||||
var rootPath = string.IsNullOrWhiteSpace(model.Dir) ? "model/" + model.Id : model.Dir;
|
||||
var entries = await _remote.ListTreeAsync(rootPath, ct);
|
||||
var files = entries.Where(e => !e.IsDirectory && IsPayload(model.Id, e.RelativePath)).ToList();
|
||||
|
||||
if (!files.Any(e => e.RelativePath.Equals(model.Id + ".json", StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"远端缺少模型清单 {model.Id}.json");
|
||||
if (!files.Any(e => e.RelativePath.StartsWith(model.Id + ".model/", StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"远端缺少模型数据 {model.Id}.model/");
|
||||
|
||||
var staging = Path.Combine(_paths.CacheRoot, "models", model.Id + "-" + Safe(model.Version));
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
try
|
||||
{
|
||||
var total = files.Sum(f => Math.Max(1L, f.Size));
|
||||
// 并行下载:模型包通常有几十个文件,串行下载会明显拖慢启动。
|
||||
// 并发上限 6,避免被服务端限流;进度用原子计数汇总。
|
||||
long done = 0;
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
using var gate = new SemaphoreSlim(6);
|
||||
|
||||
var tasks = files.Select(async entry =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var bytes = await _remote.DownloadAsync(entry, ct);
|
||||
|
||||
// 路径穿越防护
|
||||
var dest = Path.GetFullPath(Path.Combine(staging,
|
||||
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
|
||||
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
await File.WriteAllBytesAsync(dest, bytes, ct);
|
||||
|
||||
var now = Interlocked.Add(ref done, bytes.Length);
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)now / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = entry.RelativePath
|
||||
});
|
||||
}
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
Directory.CreateDirectory(_paths.ModelRoot);
|
||||
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
// 双保险:任何情况下都不允许把含 src/ 源码的模型目录整体换掉
|
||||
if (Directory.Exists(Path.Combine(target, "src")))
|
||||
throw new InvalidOperationException($"目标目录含模型源码 src/,拒绝覆盖: {target}");
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
if (Directory.Exists(target)) Directory.Move(target, backup);
|
||||
try
|
||||
{
|
||||
Directory.Move(staging, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (Directory.Exists(backup) && !Directory.Exists(target)) Directory.Move(backup, target);
|
||||
throw;
|
||||
}
|
||||
if (Directory.Exists(backup))
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
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));
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符),
|
||||
/// 并在解压前逐条校验目标路径完整落在目标目录内。
|
||||
/// </summary>
|
||||
public static class ZipSafety
|
||||
{
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
var destFull = Path.GetFullPath(destination)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
|
||||
using (var archive = ZipFile.OpenRead(zipPath))
|
||||
{
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var name = entry.FullName.Replace('\\', '/');
|
||||
if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) ||
|
||||
(name.Length >= 2 && name[1] == ':'))
|
||||
throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}");
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
}
|
||||
}
|
||||
|
||||
// 校验通过后交给框架解压(保留 overwrite 语义)
|
||||
ZipFile.ExtractToDirectory(zipPath, destination, true);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user