feat:修复部分问题
This commit is contained in:
1 parent
153ea88f4f
commit
5760fb77b0
38 files changed
+2273
-200
No files matched your search
@@ -4,76 +4,102 @@ using System.IO;
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取:
|
||||
/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/
|
||||
/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录)
|
||||
/// 3) 安装态:模型库放到用户数据目录
|
||||
/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。
|
||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||
/// <code>
|
||||
/// <安装目录>/
|
||||
/// EarthModelStudio(.exe | .app/...)
|
||||
/// .GC/
|
||||
/// settings.json 设置与已安装版本记录
|
||||
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
|
||||
/// cache/ 下载缓存 / 原子替换暂存
|
||||
/// update/ 待下次启动应用的启动器更新包
|
||||
/// </code>
|
||||
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
|
||||
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
||||
/// </summary>
|
||||
public sealed class AppPaths
|
||||
{
|
||||
/// <summary>安装目录(开发态为仓库根)。</summary>
|
||||
public string AppRoot { get; private init; } = "";
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
public string DataRoot { get; private init; } = "";
|
||||
public bool IsPortableModelRoot { get; private init; }
|
||||
|
||||
public string CacheRoot => Path.Combine(DataRoot, "cache");
|
||||
public string SettingsFile => Path.Combine(DataRoot, "settings.json");
|
||||
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
|
||||
public string InstallDirectory { get; private init; } = "";
|
||||
|
||||
/// <summary>.GC 目录。</summary>
|
||||
public string HomeRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>模型库,恒为 <HomeRoot>/model。</summary>
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
|
||||
public string DataRoot => HomeRoot;
|
||||
|
||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
|
||||
|
||||
public bool IsDevelopment { get; private init; }
|
||||
public bool IsPortableModelRoot { get; private init; }
|
||||
|
||||
public static AppPaths Discover()
|
||||
{
|
||||
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
||||
var dataRoot = Environment.GetEnvironmentVariable("EMS_DATA")
|
||||
?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"EarthModelStudio");
|
||||
|
||||
// 显式指定模型库(模型是外置数据,可放在任意磁盘/网络盘)
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
if (!string.IsNullOrWhiteSpace(envModels))
|
||||
{
|
||||
return new AppPaths
|
||||
{
|
||||
AppRoot = baseDir,
|
||||
ModelRoot = envModels!,
|
||||
DataRoot = dataRoot,
|
||||
IsPortableModelRoot = false
|
||||
};
|
||||
}
|
||||
|
||||
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
|
||||
repoRoot = FindRepoRoot(baseDir);
|
||||
var isDev = !string.IsNullOrEmpty(repoRoot) &&
|
||||
File.Exists(Path.Combine(repoRoot!, "EarthModelStudio.sln"));
|
||||
var appRoot = isDev ? repoRoot! : baseDir;
|
||||
|
||||
var exeModelDir = Path.Combine(baseDir, "model");
|
||||
string appRoot, modelRoot;
|
||||
bool portable = false;
|
||||
|
||||
if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model")))
|
||||
// 只读安装位置(如 Program Files / /Applications)自动退回用户数据目录
|
||||
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
|
||||
string home;
|
||||
if (!string.IsNullOrWhiteSpace(explicitData))
|
||||
{
|
||||
appRoot = repoRoot!;
|
||||
modelRoot = Path.Combine(appRoot, "model");
|
||||
}
|
||||
else if (Directory.Exists(exeModelDir))
|
||||
{
|
||||
appRoot = baseDir;
|
||||
modelRoot = exeModelDir;
|
||||
portable = true;
|
||||
home = explicitData!;
|
||||
}
|
||||
else
|
||||
{
|
||||
appRoot = baseDir;
|
||||
modelRoot = Path.Combine(dataRoot, "model");
|
||||
var portableHome = Path.Combine(appRoot, ".GC");
|
||||
home = CanWrite(portableHome)
|
||||
? portableHome
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"EarthModelStudio", ".GC");
|
||||
}
|
||||
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
|
||||
? envModels!
|
||||
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
|
||||
|
||||
return new AppPaths
|
||||
{
|
||||
AppRoot = appRoot,
|
||||
InstallDirectory = baseDir,
|
||||
HomeRoot = home,
|
||||
ModelRoot = modelRoot,
|
||||
DataRoot = dataRoot,
|
||||
IsPortableModelRoot = portable
|
||||
IsDevelopment = isDev,
|
||||
IsPortableModelRoot = string.IsNullOrWhiteSpace(envModels)
|
||||
};
|
||||
}
|
||||
|
||||
private static bool CanWrite(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
var probe = Path.Combine(dir, ".write-test");
|
||||
File.WriteAllText(probe, "ok");
|
||||
File.Delete(probe);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindRepoRoot(string start)
|
||||
{
|
||||
var dir = new DirectoryInfo(start);
|
||||
@@ -86,8 +112,51 @@ public sealed class AppPaths
|
||||
|
||||
public void EnsureCreated()
|
||||
{
|
||||
Directory.CreateDirectory(DataRoot);
|
||||
Directory.CreateDirectory(HomeRoot);
|
||||
Directory.CreateDirectory(CacheRoot);
|
||||
Directory.CreateDirectory(ModelRoot);
|
||||
Directory.CreateDirectory(UpdateRoot);
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
SyncDevelopmentModels();
|
||||
}
|
||||
|
||||
private void SyncDevelopmentModels()
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
if (!Directory.Exists(source)) return;
|
||||
foreach (var dir in Directory.GetDirectories(source))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
if (id.StartsWith('_')) continue;
|
||||
var manifest = Path.Combine(dir, id + ".json");
|
||||
var data = Path.Combine(dir, id + ".model");
|
||||
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
|
||||
var dest = Path.Combine(ModelRoot, id);
|
||||
Directory.CreateDirectory(dest);
|
||||
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"同步开发模型失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (Path.GetFileName(file).StartsWith('.')) continue;
|
||||
var to = Path.Combine(dst, Path.GetRelativePath(src, file));
|
||||
var parent = Path.GetDirectoryName(to);
|
||||
if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent);
|
||||
File.Copy(file, to, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,16 +15,20 @@ public sealed class AppServices
|
||||
public ModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public UpdateService Updates { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
Paths = paths;
|
||||
Settings = new SettingsService(paths);
|
||||
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
|
||||
Models = new ModelRepository(paths);
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, Models);
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
@@ -33,7 +37,6 @@ public sealed class AppServices
|
||||
paths.EnsureCreated();
|
||||
|
||||
var services = new AppServices(paths);
|
||||
services.Settings.Load();
|
||||
L.I.Initialize(services.Settings.Current.Language);
|
||||
services.Memory.Apply(services.Settings.Current.MemoryMb);
|
||||
|
||||
@@ -41,9 +44,5 @@ public sealed class AppServices
|
||||
return services;
|
||||
}
|
||||
|
||||
public static AppServices Ensure()
|
||||
{
|
||||
if (Current == null) Create();
|
||||
return Current;
|
||||
}
|
||||
public static AppServices Ensure() => Current ?? Create();
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.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;
|
||||
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
|
||||
if (Path.IsPathRooted(url) && File.Exists(url))
|
||||
return await File.ReadAllBytesAsync(url, ct);
|
||||
if (Uri.TryCreate(url, UriKind.Absolute, out _))
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
return null;
|
||||
}
|
||||
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
||||
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"路径越界: {relative}");
|
||||
return full;
|
||||
}
|
||||
|
||||
private static string Relative(string baseDir, string file) =>
|
||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.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("EarthModelStudio-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, EarthModelStudio.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>递归列出目录树(含目录项与文件项)。</summary>
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
var repoPath = (rootPath ?? _modelDir).Trim('/');
|
||||
await WalkAsync(repoPath, "", 0, result, ct);
|
||||
return result;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
|
||||
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
|
||||
|
||||
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (!doc.RootElement.TryGetProperty("content", out var content))
|
||||
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
|
||||
return Convert.FromBase64String(content.GetString() ?? "");
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
|
||||
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
try
|
||||
{
|
||||
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(apiUrl, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("download_url", out var dl))
|
||||
url = dl.GetString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
return await _http.GetByteArrayAsync(url!, ct);
|
||||
}
|
||||
|
||||
private static string Str(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() ?? "" : "";
|
||||
|
||||
private static string? NullableStr(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static long Num(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
/// <summary>.GC/update/pending.json:已下载、等待下次启动应用的启动器版本。</summary>
|
||||
public sealed class PendingUpdate
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public string Rid { get; set; } = "";
|
||||
public string InstallDirectory { get; set; } = "";
|
||||
public string Executable { get; set; } = "";
|
||||
public string Payload { get; set; } = "payload";
|
||||
public string? DownloadedAt { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 「下次启动时应用」:主进程刚进 Main、还没建窗口时,交给一个独立脚本进程,
|
||||
/// 脚本等主进程退出后覆盖可执行文件并重启。这样 Windows 上也不会碰到文件占用。
|
||||
/// </summary>
|
||||
public static class LauncherUpdate
|
||||
{
|
||||
public static bool TryApplyPending(AppPaths paths) => TryApplyPending(paths, launch: true);
|
||||
|
||||
/// <summary>launch=false 只生成脚本、不启动进程,供离线自动更新测试使用。</summary>
|
||||
public static bool TryApplyPending(AppPaths paths, bool launch)
|
||||
{
|
||||
// 开发态、自检、显式关闭时一律不替换正在运行的程序
|
||||
if (paths.IsDevelopment) return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||
|
||||
var pendingFile = Path.Combine(paths.UpdateRoot, "pending.json");
|
||||
if (!File.Exists(pendingFile))
|
||||
{
|
||||
ClearPendingSetting(paths);
|
||||
return false;
|
||||
}
|
||||
|
||||
PendingUpdate? pending;
|
||||
try { pending = Json.Read<PendingUpdate>(pendingFile); }
|
||||
catch { pending = null; }
|
||||
|
||||
var payload = Path.Combine(paths.UpdateRoot,
|
||||
string.IsNullOrWhiteSpace(pending?.Payload) ? "payload" : pending!.Payload!);
|
||||
var installDir = string.IsNullOrWhiteSpace(pending?.InstallDirectory)
|
||||
? paths.InstallDirectory : pending!.InstallDirectory!;
|
||||
|
||||
// 版本已经生效,或包不完整:清掉标记后正常启动
|
||||
if (pending == null || string.IsNullOrWhiteSpace(pending.Version) ||
|
||||
string.Equals(pending.Version, UpdateService.CurrentLauncherVersion,
|
||||
StringComparison.OrdinalIgnoreCase) || !Directory.Exists(payload))
|
||||
{
|
||||
TryDelete(pendingFile);
|
||||
ClearPendingSetting(paths);
|
||||
return false;
|
||||
}
|
||||
|
||||
var exeName = string.IsNullOrWhiteSpace(pending.Executable)
|
||||
? (OperatingSystem.IsWindows() ? "EarthModelStudio.exe" : "EarthModelStudio")
|
||||
: pending.Executable!;
|
||||
var exePath = Path.Combine(installDir, exeName);
|
||||
|
||||
var isWindows = OperatingSystem.IsWindows();
|
||||
var script = Path.Combine(paths.UpdateRoot, isWindows ? "apply-update.bat" : "apply-update.sh");
|
||||
var content = isWindows
|
||||
? WindowsScript(payload, installDir, exePath, pendingFile, script)
|
||||
: UnixScript(payload, installDir, exePath, pendingFile, script);
|
||||
|
||||
try
|
||||
{
|
||||
File.WriteAllText(script, content, new UTF8Encoding(false));
|
||||
if (!launch)
|
||||
{
|
||||
Console.WriteLine($"(dry-run) 更新脚本已生成: {script}");
|
||||
return true;
|
||||
}
|
||||
|
||||
ProcessStartInfo psi;
|
||||
if (isWindows)
|
||||
{
|
||||
psi = new ProcessStartInfo("cmd.exe")
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
psi.ArgumentList.Add("/c");
|
||||
psi.ArgumentList.Add(script);
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
File.SetUnixFileMode(script,
|
||||
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { /* 某些文件系统不支持 */ }
|
||||
psi = new ProcessStartInfo("/bin/sh")
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
psi.ArgumentList.Add(script);
|
||||
}
|
||||
|
||||
Process.Start(psi);
|
||||
Console.WriteLine($"启动器更新 {pending.Version} 已安排,重启后生效");
|
||||
return true; // Main 直接返回,进程退出后由脚本接管
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"应用启动器更新失败(保留待更新包,下次再试): {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string WindowsScript(string payload, string installDir,
|
||||
string exePath, string pendingFile, string script)
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
text.AppendLine("@echo off");
|
||||
text.AppendLine("chcp 65001 >nul 2>&1");
|
||||
text.AppendLine($"set \"SRC={payload}\"");
|
||||
text.AppendLine($"set \"DST={installDir}\"");
|
||||
text.AppendLine($"set \"EXE={exePath}\"");
|
||||
text.AppendLine($"set \"PENDING={pendingFile}\"");
|
||||
text.AppendLine("timeout /t 2 /nobreak >nul");
|
||||
text.AppendLine("xcopy /E /Y /I /Q \"%SRC%\\*\" \"%DST%\\\" >nul 2>&1");
|
||||
text.AppendLine("if exist \"%PENDING%\" del /Q \"%PENDING%\" >nul 2>&1");
|
||||
text.AppendLine("if exist \"%EXE%\" start \"\" \"%EXE%\"");
|
||||
text.AppendLine($"del /Q \"{script}\" >nul 2>&1");
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string UnixScript(string payload, string installDir,
|
||||
string exePath, string pendingFile, string script)
|
||||
{
|
||||
static string Q(string value) => "\"" + value
|
||||
.Replace("\\", "\\\\")
|
||||
.Replace("\"", "\\\"")
|
||||
.Replace("$", "\\$")
|
||||
.Replace("`", "\\`") + "\"";
|
||||
|
||||
var text = new StringBuilder();
|
||||
text.AppendLine("#!/bin/sh");
|
||||
text.AppendLine("sleep 2");
|
||||
text.AppendLine($"cp -R {Q(payload + "/.")} {Q(installDir + "/")}");
|
||||
text.AppendLine($"chmod +x {Q(exePath)} 2>/dev/null");
|
||||
text.AppendLine($"rm -f {Q(pendingFile)}");
|
||||
text.AppendLine($"{Q(exePath)} >/dev/null 2>&1 &");
|
||||
text.AppendLine($"rm -f {Q(script)}");
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static void ClearPendingSetting(AppPaths paths)
|
||||
{
|
||||
try
|
||||
{
|
||||
var settings = Json.Read<AppSettings>(paths.SettingsFile);
|
||||
if (settings == null || string.IsNullOrEmpty(settings.PendingLauncherVersion)) return;
|
||||
settings.PendingLauncherVersion = null;
|
||||
settings.LauncherVersion = UpdateService.CurrentLauncherVersion;
|
||||
Json.Write(paths.SettingsFile, settings);
|
||||
}
|
||||
catch { /* 设置文件不可写时忽略 */ }
|
||||
}
|
||||
|
||||
private static void TryDelete(string file)
|
||||
{
|
||||
try { if (File.Exists(file)) File.Delete(file); } catch { }
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,8 @@ public sealed class SettingsService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。
|
||||
/// 这里只给一条空的自定义源占位。
|
||||
/// 自动更新由 UpdateService 负责(版本清单 version.json),这里不预置任何在线源;
|
||||
/// 只给「下载」页留一条空的自定义源占位。
|
||||
/// </summary>
|
||||
private void SeedSources()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
|
||||
public sealed class RepoVersion
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
public string Generated { get; set; } = "";
|
||||
public string Repository { get; set; } = "";
|
||||
public string Branch { get; set; } = "main";
|
||||
public string ModelDir { get; set; } = "model";
|
||||
public RepoLauncher Launcher { get; set; } = new();
|
||||
public List<RepoModel> Models { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class RepoLauncher
|
||||
{
|
||||
public string Version { get; set; } = "1.0.0";
|
||||
/// <summary>启动器源码指纹(自动算,仅展示,不触发升级)。</summary>
|
||||
public string Revision { get; set; } = "";
|
||||
public Dictionary<string, RepoPackage> Packages { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>某个平台的启动器发布包;url 优先,否则用 path 去仓库里解析下载地址。</summary>
|
||||
public sealed class RepoPackage
|
||||
{
|
||||
public string? Url { get; set; }
|
||||
public string? Path { get; set; }
|
||||
public string? Sha256 { get; set; }
|
||||
public long Size { get; set; }
|
||||
}
|
||||
|
||||
public sealed class RepoModel
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
|
||||
public string Dir { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>远端目录树里的一个条目。</summary>
|
||||
public sealed class RepoEntry
|
||||
{
|
||||
public string Name { get; init; } = "";
|
||||
/// <summary>仓库内完整路径。</summary>
|
||||
public string Path { get; init; } = "";
|
||||
/// <summary>相对所请求根目录的路径,统一用 / 分隔。</summary>
|
||||
public string RelativePath { get; init; } = "";
|
||||
public bool IsDirectory { get; init; }
|
||||
public string? DownloadUrl { get; init; }
|
||||
public long Size { get; init; }
|
||||
public string? Sha { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 远端源抽象:gitcode 是默认实现,本地目录实现用于离线教学与自动化测试。
|
||||
/// </summary>
|
||||
public interface IModelRemote
|
||||
{
|
||||
string DisplayName { get; }
|
||||
Task<RepoVersion?> GetVersionAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
|
||||
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
|
||||
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class UpdateProgress
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Message { get; init; } = "";
|
||||
public string? Detail { get; init; }
|
||||
}
|
||||
|
||||
public enum UpdateOutcome
|
||||
{
|
||||
NoChange,
|
||||
Applied,
|
||||
Partial,
|
||||
Unavailable,
|
||||
Disabled
|
||||
}
|
||||
|
||||
public sealed class UpdateResult
|
||||
{
|
||||
public UpdateOutcome Outcome { get; init; }
|
||||
public string Message { get; init; } = "";
|
||||
public int UpdatedModels { get; init; }
|
||||
public List<string> ModelNames { get; init; } = new();
|
||||
public string? LauncherMessage { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动时的自动更新:
|
||||
/// · 读远端 version.json,和 .GC/settings.json 里记录的版本比较;
|
||||
/// · 模型:下载到 cache 后原子替换 .GC/model/<id>,结果立刻刷新列表(本次启动生效);
|
||||
/// · 启动器:下载到 .GC/update/payload 并写 pending.json,下次启动才应用;
|
||||
/// · 任何失败都保留本地已装模型,绝不把模型库清空。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_remote = remote;
|
||||
}
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var v = Assembly.GetEntryAssembly()?.GetName().Version;
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var arch = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
||||
return RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
public static IModelRemote CreateRemote(AppSettings settings)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
return new GitCodeRemote(settings.UpdateManifestUrl, settings.UpdateRepository);
|
||||
}
|
||||
|
||||
public async Task<UpdateResult> RunAsync(bool force,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
|
||||
{
|
||||
// 开发态的 model/ 里有源码与工程文件,自动更新一律跳过,避免把源码目录整体替换掉。
|
||||
// 需要验证更新链路请用 ./build.sh update-test(它使用临时目录,不碰仓库)。
|
||||
if (_paths.IsDevelopment && Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1")
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Disabled,
|
||||
Message = "开发态跳过自动更新(保护仓库内模型源码)"
|
||||
};
|
||||
|
||||
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();
|
||||
|
||||
var needed = 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}");
|
||||
}
|
||||
}
|
||||
|
||||
string? launcherMessage = null;
|
||||
try
|
||||
{
|
||||
launcherMessage = await StageLauncherAsync(remote.Launcher, progress, ct);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
launcherMessage = L.I.F("update.launcherFailed", ex.Message);
|
||||
errors.Add("launcher: " + 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"] : 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('\\', '/');
|
||||
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));
|
||||
long done = 0;
|
||||
foreach (var entry in files)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var bytes = await _remote.DownloadAsync(entry, ct);
|
||||
var dest = Path.Combine(staging, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
await File.WriteAllBytesAsync(dest, bytes, ct);
|
||||
done += bytes.Length;
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)done / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = entry.RelativePath
|
||||
});
|
||||
}
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
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 async Task<string?> StageLauncherAsync(RepoLauncher launcher,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct)
|
||||
{
|
||||
var current = CurrentLauncherVersion;
|
||||
var pending = _settings.Current.PendingLauncherVersion;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(pending) &&
|
||||
string.Equals(pending, launcher.Version, StringComparison.OrdinalIgnoreCase))
|
||||
return L.I.F("update.pendingReady", launcher.Version);
|
||||
|
||||
if (!IsNewer(launcher.Version, current)) return null;
|
||||
|
||||
var rid = CurrentRid;
|
||||
if (!launcher.Packages.TryGetValue(rid, out var package) &&
|
||||
!launcher.Packages.TryGetValue("default", out package))
|
||||
return L.I.F("update.noRidPackage", launcher.Version, rid);
|
||||
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.85,
|
||||
Message = L.I.F("update.downloadingLauncher", launcher.Version)
|
||||
});
|
||||
|
||||
var bytes = await _remote.DownloadPackageAsync(package!, ct);
|
||||
if (bytes == null || bytes.Length == 0)
|
||||
return L.I.F("update.noPackageUrl", launcher.Version);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(package!.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, package.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("启动器包校验失败(sha256 不符)");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_paths.UpdateRoot);
|
||||
var payload = Path.Combine(_paths.UpdateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
try
|
||||
{
|
||||
ZipFile.ExtractToDirectory(zip, payload, true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(zip); } catch { }
|
||||
}
|
||||
FlattenPayload(payload);
|
||||
|
||||
Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate
|
||||
{
|
||||
Version = launcher.Version,
|
||||
Rid = rid,
|
||||
InstallDirectory = _paths.InstallDirectory,
|
||||
Executable = Path.GetFileName(Environment.ProcessPath ?? ""),
|
||||
Payload = "payload",
|
||||
DownloadedAt = DateTime.UtcNow.ToString("O")
|
||||
});
|
||||
|
||||
_settings.Current.PendingLauncherVersion = launcher.Version;
|
||||
_settings.Save();
|
||||
return L.I.F("update.pendingDownloaded", launcher.Version);
|
||||
}
|
||||
|
||||
private static void FlattenPayload(string dir)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(dir);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
var flat = dir + "-flat";
|
||||
if (Directory.Exists(flat)) Directory.Delete(flat, true);
|
||||
Directory.Move(inner, flat);
|
||||
Directory.Delete(dir, true);
|
||||
Directory.Move(flat, dir);
|
||||
}
|
||||
|
||||
private static bool IsNewer(string remote, string local)
|
||||
{
|
||||
if (Version.TryParse(remote, out var r) && Version.TryParse(local, out var l)) return r > l;
|
||||
return !string.Equals(remote, local, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user