- 新增 GC-UI/:backend(.NET 8 本地 HTTP API + 模型窗口宿主)与 frontend(Flutter 桌面应用) - 前端一套 Dart 代码 + windows/macos 两个原生 runner,共享全部界面逻辑 - 「关于」页新增「源码语言:C#」「前端:Flutter」两行,字段由 /api/about 下发 - 截图脚本覆盖首页/下载/设置/关于/外壳,需要真实后端时用 runAsync 等待请求 - README 补充平台选型理由、接口列表与截图用法
504 lines
18 KiB
C#
504 lines
18 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using GC.Download;
|
||
using GC.Models;
|
||
using GC.Services;
|
||
using GC.UI.Server;
|
||
using Microsoft.AspNetCore.Builder;
|
||
using Microsoft.AspNetCore.Hosting;
|
||
using Microsoft.AspNetCore.Http;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using Microsoft.Extensions.Hosting;
|
||
using Microsoft.Extensions.Logging;
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// GC-UI 后端:本地 HTTP 服务(只监听 127.0.0.1)。
|
||
//
|
||
// 它把原来 GC 启动器里的服务层原样复用(GC.Core / GC-DOWNLOAD),
|
||
// 只是把「界面」从 Avalonia 换成 Flutter —— 前端通过下面这些接口驱动后端。
|
||
//
|
||
// GET /api/health 健康检查 + 图形环境是否可用
|
||
// GET /api/models 已安装模型
|
||
// GET /api/models/{id}/preview 模型封面图
|
||
// POST /api/models/{id}/launch 启动模型(打开模型自己的窗口)
|
||
// DELETE /api/models/{id} 删除模型
|
||
// GET /api/settings 读取设置
|
||
// POST /api/settings 修改设置(补丁式)
|
||
// GET /api/sources 模型源列表
|
||
// POST /api/sources/select 双源测速并切到最快
|
||
// GET /api/remote/models 远端可下载模型
|
||
// POST /api/download 入队下载
|
||
// GET /api/download/jobs 下载任务
|
||
// POST /api/download/{id}/cancel|retry|remove
|
||
// POST /api/download/clear-finished 清除已完成
|
||
// POST /api/update/check 检查模型 / 启动器更新
|
||
// GET /api/about 版本 + 贡献者
|
||
// POST /api/shell/open-folder|open-url 打开目录 / 链接
|
||
// ---------------------------------------------------------------------------
|
||
|
||
var port = ResolvePort(args);
|
||
|
||
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||
|
||
var services = AppServices.Create();
|
||
var uiHost = new AvaloniaHost(services);
|
||
|
||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||
builder.Logging.ClearProviders();
|
||
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
|
||
|
||
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
|
||
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
|
||
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
|
||
.SetIsOriginAllowed(origin =>
|
||
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
||
(uri.Host == "127.0.0.1" || uri.Host == "localhost"))
|
||
.AllowAnyHeader()
|
||
.AllowAnyMethod()));
|
||
|
||
var app = builder.Build();
|
||
app.UseCors();
|
||
|
||
// ---- 健康检查 -------------------------------------------------------------
|
||
|
||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||
true,
|
||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||
LauncherRuntimeInfo.CurrentRid,
|
||
uiHost.IsAvailable,
|
||
uiHost.LastError)));
|
||
|
||
// ---- 已安装模型 -----------------------------------------------------------
|
||
|
||
app.MapGet("/api/models", () =>
|
||
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
|
||
|
||
app.MapGet("/api/models/{id}/preview", (string id) =>
|
||
{
|
||
var package = services.Models.Find(id);
|
||
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
|
||
return Results.File(package.PreviewPath, "image/png");
|
||
});
|
||
|
||
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||
{
|
||
var package = services.Models.Find(id);
|
||
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||
|
||
try
|
||
{
|
||
services.Memory.Refresh();
|
||
var message = await uiHost.LaunchAsync(package);
|
||
return Results.Ok(new LaunchResultDto(true, message));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return Results.Json(new LaunchResultDto(false, ex.Message), statusCode: 503);
|
||
}
|
||
});
|
||
|
||
app.MapDelete("/api/models/{id}", (string id) =>
|
||
{
|
||
var ok = services.Models.Delete(id);
|
||
if (ok) services.Models.NotifyChanged();
|
||
return ok
|
||
? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}"))
|
||
: Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||
});
|
||
|
||
// ---- 设置 -----------------------------------------------------------------
|
||
|
||
app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
|
||
|
||
app.MapPost("/api/settings", (SettingsPatch? patch) =>
|
||
{
|
||
if (patch == null) return Results.BadRequest(new LaunchResultDto(false, "缺少设置内容"));
|
||
|
||
services.Settings.Apply(s =>
|
||
{
|
||
if (patch.Language != null) s.Language = patch.Language;
|
||
if (patch.Theme != null) s.Theme = patch.Theme;
|
||
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
|
||
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
|
||
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
|
||
if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value;
|
||
if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value;
|
||
if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository;
|
||
if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot;
|
||
if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride;
|
||
});
|
||
|
||
if (patch.Language != null) L.I.SetLanguage(patch.Language);
|
||
if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue)
|
||
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb);
|
||
|
||
return Results.Ok(ToSettingsDto());
|
||
});
|
||
|
||
// ---- 模型源 ---------------------------------------------------------------
|
||
|
||
app.MapGet("/api/sources", () =>
|
||
Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList()));
|
||
|
||
app.MapPost("/api/sources/select", async (ForceRequest? request) =>
|
||
{
|
||
var force = request?.Force ?? false;
|
||
try
|
||
{
|
||
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
||
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
||
return Results.Ok(new LatencyDto(
|
||
fastest.Id, fastest.Name,
|
||
services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
return Results.Json(new LaunchResultDto(false, ex.Message), statusCode: 503);
|
||
}
|
||
});
|
||
|
||
app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
|
||
{
|
||
var source = ResolveSource(sourceId);
|
||
if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源"));
|
||
|
||
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
|
||
var installed = services.Models.Scan()
|
||
.ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase);
|
||
|
||
return Results.Ok(new SourceIndexDto(
|
||
index.SourceId,
|
||
index.Root,
|
||
index.FromCache,
|
||
index.Error,
|
||
index.ResolvedFrom,
|
||
index.Models.Select(m => new RemoteModelDto(
|
||
m.Id,
|
||
m.LocalizedName,
|
||
m.LocalizedDescription,
|
||
m.Manifest.Version,
|
||
m.SizeBytes,
|
||
ModelScanner.HumanSize(m.SizeBytes),
|
||
m.SourceId,
|
||
installed.ContainsKey(m.Id),
|
||
installed.TryGetValue(m.Id, out var v) ? v : null)).ToList()));
|
||
});
|
||
|
||
// ---- 下载 -----------------------------------------------------------------
|
||
|
||
app.MapPost("/api/download", async (DownloadRequest? request) =>
|
||
{
|
||
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
|
||
return Results.BadRequest(new LaunchResultDto(false, "缺少 modelId"));
|
||
|
||
var source = ResolveSource(request.SourceId);
|
||
if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源"));
|
||
|
||
var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None);
|
||
var model = index.Models.FirstOrDefault(m =>
|
||
m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase));
|
||
if (model == null)
|
||
return Results.NotFound(new LaunchResultDto(false, $"源里没有模型 {request.ModelId}"));
|
||
|
||
var job = services.Downloads.Enqueue(model);
|
||
return Results.Ok(ToJobDto(job));
|
||
});
|
||
|
||
app.MapGet("/api/download/jobs", () =>
|
||
Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList()));
|
||
|
||
app.MapPost("/api/download/{id}/cancel", (string id) =>
|
||
ActOnJob(id, job => services.Downloads.Cancel(job)));
|
||
|
||
app.MapPost("/api/download/{id}/retry", (string id) =>
|
||
ActOnJob(id, job => services.Downloads.Retry(job)));
|
||
|
||
app.MapPost("/api/download/{id}/remove", (string id) =>
|
||
ActOnJob(id, job => services.Downloads.Remove(job)));
|
||
|
||
app.MapPost("/api/download/clear-finished", () =>
|
||
{
|
||
services.Downloads.ClearFinished();
|
||
return Results.Ok(new LaunchResultDto(true, "已清除完成的任务"));
|
||
});
|
||
|
||
// ---- 更新 -----------------------------------------------------------------
|
||
|
||
app.MapPost("/api/update/check", async (ForceRequest? request) =>
|
||
{
|
||
var force = request?.Force ?? true;
|
||
var messages = new List<string>();
|
||
|
||
try
|
||
{
|
||
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
||
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
||
}
|
||
|
||
string? launcherLatest = null;
|
||
try
|
||
{
|
||
launcherLatest = await services.LauncherUpdates.CheckAsync(
|
||
services.Updates.Remote, CancellationToken.None);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}");
|
||
}
|
||
|
||
var progress = new Progress<UpdateProgress>(p =>
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message);
|
||
});
|
||
|
||
var result = await services.Updates.RunAsync(force, progress, CancellationToken.None);
|
||
|
||
return Results.Ok(new UpdateCheckDto(
|
||
result.Outcome.ToString(),
|
||
result.Message,
|
||
result.UpdatedModels,
|
||
result.ModelNames,
|
||
result.LauncherMessage,
|
||
result.Error,
|
||
launcherLatest,
|
||
services.Updates.Remote.DisplayName,
|
||
services.Selector.LastLatency
|
||
.Select(kv => new LatencyDto(
|
||
kv.Key,
|
||
SourcePreset.Find(kv.Key)?.Name ?? kv.Key,
|
||
kv.Value))
|
||
.ToList()));
|
||
});
|
||
|
||
// ---- 关于 -----------------------------------------------------------------
|
||
|
||
app.MapGet("/api/about", async () =>
|
||
{
|
||
var repository = services.Settings.Current.UpdateRepository;
|
||
var contributors = new List<ContributorDto>();
|
||
try
|
||
{
|
||
foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None))
|
||
contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}");
|
||
}
|
||
|
||
return Results.Ok(new AboutDto(
|
||
"Morris GC",
|
||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||
LauncherRuntimeInfo.CurrentRid,
|
||
repository,
|
||
contributors,
|
||
// 「关于」页展示的技术栈信息:源码语言与前端框架。
|
||
SourceLanguage: "C#",
|
||
Frontend: "Flutter"));
|
||
});
|
||
|
||
// ---- 系统集成 -------------------------------------------------------------
|
||
|
||
app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
|
||
{
|
||
var path = request?.Path;
|
||
if (string.IsNullOrWhiteSpace(path))
|
||
return Results.BadRequest(new LaunchResultDto(false, "缺少 path"));
|
||
|
||
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
|
||
if (!IsInsideKnownRoot(path!))
|
||
return Results.BadRequest(new LaunchResultDto(false, "只允许打开启动器自己的目录"));
|
||
|
||
Shell.OpenFolder(path!);
|
||
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
|
||
});
|
||
|
||
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
|
||
{
|
||
var url = request?.Url;
|
||
if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||
return Results.BadRequest(new LaunchResultDto(false, "URL 无效"));
|
||
|
||
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|
||
return Results.BadRequest(new LaunchResultDto(false, "只允许 http/https 链接"));
|
||
|
||
Shell.OpenUrl(url!);
|
||
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
|
||
});
|
||
|
||
// ---- 启动 -----------------------------------------------------------------
|
||
|
||
WriteEndpointFile(services, port);
|
||
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
|
||
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
|
||
|
||
app.Run();
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 局部辅助
|
||
// ---------------------------------------------------------------------------
|
||
|
||
static int ResolvePort(string[] args)
|
||
{
|
||
var env = Environment.GetEnvironmentVariable("GC_UI_PORT");
|
||
if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv;
|
||
|
||
for (var i = 0; i < args.Length; i++)
|
||
{
|
||
if (args[i] == "--port" && i + 1 < args.Length &&
|
||
int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536)
|
||
return next;
|
||
|
||
const string prefix = "--port=";
|
||
if (args[i].StartsWith(prefix, StringComparison.Ordinal) &&
|
||
int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536)
|
||
return inline;
|
||
}
|
||
|
||
return 17890;
|
||
}
|
||
|
||
static void WriteEndpointFile(AppServices services, int port)
|
||
{
|
||
try
|
||
{
|
||
var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json");
|
||
var payload = JsonSerializer.Serialize(new
|
||
{
|
||
port,
|
||
pid = Environment.ProcessId,
|
||
url = $"http://127.0.0.1:{port}",
|
||
version = LauncherRuntimeInfo.CurrentLauncherVersion,
|
||
platform = LauncherRuntimeInfo.CurrentRid,
|
||
startedAt = DateTimeOffset.UtcNow.ToString("o")
|
||
}, new JsonSerializerOptions { WriteIndented = true });
|
||
|
||
File.WriteAllText(file, payload);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
ModelDto ToModelDto(ModelPackage package) => new(
|
||
package.Id,
|
||
package.LocalizedName,
|
||
package.LocalizedDescription,
|
||
package.Manifest.Version,
|
||
package.Manifest.Author,
|
||
package.SizeBytes,
|
||
ModelScanner.HumanSize(package.SizeBytes),
|
||
package.Manifest.Tags ?? new List<string>(),
|
||
File.Exists(package.PreviewPath),
|
||
$"/api/models/{package.Id}/preview",
|
||
package.Directory,
|
||
package.DataDirectory);
|
||
|
||
SourceDto ToSourceDto(ModelSource source) => new(
|
||
source.Id,
|
||
string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name,
|
||
source.Url,
|
||
source.Enabled,
|
||
source.BuiltIn,
|
||
source.DisplayHost);
|
||
|
||
SettingsDto ToSettingsDto() => new(
|
||
services.Settings.Current.Language,
|
||
services.Settings.Current.Theme,
|
||
services.Settings.Current.RenderFps,
|
||
services.Settings.Current.MemoryMb,
|
||
services.Settings.Current.MemoryAuto,
|
||
services.Settings.Current.AutoUpdateOnStartup,
|
||
services.Settings.Current.RequireSignedManifest,
|
||
services.Settings.Current.UpdateRepository,
|
||
services.Settings.Current.UpdateLocalRoot,
|
||
services.Settings.Current.ModelRootOverride,
|
||
services.Memory.BudgetMb,
|
||
services.Memory.UsageText,
|
||
services.Paths.ModelRoot,
|
||
services.Paths.DataRoot,
|
||
services.Paths.SettingsFile,
|
||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||
LauncherRuntimeInfo.CurrentRid,
|
||
services.Settings.Current.Sources.Select(ToSourceDto).ToList(),
|
||
L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList());
|
||
|
||
JobDto ToJobDto(IDownloadJob job) => new(
|
||
job.Id,
|
||
job.Model.Id,
|
||
job.Name,
|
||
job.Version,
|
||
job.State.ToString(),
|
||
job.Progress,
|
||
job.StatusText,
|
||
job.DetailText,
|
||
job.Error,
|
||
job.IsActive,
|
||
job.CanRetry,
|
||
job.IsDone);
|
||
|
||
ModelSource? ResolveSource(string? sourceId)
|
||
{
|
||
var sources = services.Settings.Current.Sources;
|
||
if (!string.IsNullOrWhiteSpace(sourceId))
|
||
{
|
||
var exact = sources.FirstOrDefault(s =>
|
||
s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase));
|
||
if (exact != null) return exact;
|
||
}
|
||
|
||
return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url))
|
||
?? sources.FirstOrDefault();
|
||
}
|
||
|
||
IResult ActOnJob(string id, Action<IDownloadJob> action)
|
||
{
|
||
var job = services.Downloads.Jobs.FirstOrDefault(j =>
|
||
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||
if (job == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到任务 {id}"));
|
||
|
||
action(job);
|
||
return Results.Ok(ToJobDto(job));
|
||
}
|
||
|
||
bool IsInsideKnownRoot(string path)
|
||
{
|
||
try
|
||
{
|
||
var full = Path.GetFullPath(path);
|
||
var roots = new[]
|
||
{
|
||
services.Paths.ModelRoot,
|
||
services.Paths.DataRoot,
|
||
services.Paths.HomeRoot,
|
||
services.Paths.AppRoot
|
||
};
|
||
|
||
foreach (var root in roots)
|
||
{
|
||
if (string.IsNullOrWhiteSpace(root)) continue;
|
||
var rootFull = Path.GetFullPath(root);
|
||
if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true;
|
||
if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||
return true;
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
return false;
|
||
}
|
||
|
||
return false;
|
||
}
|