feat: 升级 .NET 10 并添加外部访问服务
This commit is contained in:
1 parent
9a6ba36c6a
commit
b31da1c914
42 files changed
+1701
-74
No files matched your search
@@ -20,7 +20,7 @@ body:
|
||||
attributes:
|
||||
label: 系统环境
|
||||
description: System environment,例如操作系统版本、运行时版本、显卡驱动版本
|
||||
placeholder: Windows 11 24H2 (26100.3775) / .NET Desktop Runtime 8.0.15 / NVIDIA 572.83
|
||||
placeholder: Windows 11 24H2 (26100.3775) / NVIDIA 572.83
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
|
||||
@@ -23,26 +23,15 @@ jobs:
|
||||
latest: true
|
||||
fileName: "kachina-builder.exe"
|
||||
|
||||
- name: Embed Dotnet and VCRedist
|
||||
- name: Embed VCRedist
|
||||
shell: bash
|
||||
run: |
|
||||
# dotnet
|
||||
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
|
||||
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "Cannot get the latest version from $VERSION_URL"
|
||||
exit 1
|
||||
fi
|
||||
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
|
||||
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
|
||||
# vcredist
|
||||
echo "Downloading VCRedist"
|
||||
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
|
||||
# embed
|
||||
echo "Embedding runtimes"
|
||||
./kachina-builder.exe append -o ./BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
|
||||
echo "Embedding VCRedist"
|
||||
./kachina-builder.exe append -o ./BetterGI.Install.*.exe -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
|
||||
./kachina-builder.exe extract -i ./BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
|
||||
|
||||
- name: Extract 7z and create zip
|
||||
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 8.x
|
||||
dotnet-version: 10.x
|
||||
- name: 更新 csproj 文件版本号
|
||||
run: |
|
||||
$version = '${{ needs.validate.outputs.version }}'
|
||||
@@ -117,7 +117,7 @@ jobs:
|
||||
continue-on-error: true
|
||||
- name: 🧹 Clear & Move Files
|
||||
run: |
|
||||
$sourceDir = ".\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64"
|
||||
$sourceDir = ".\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64"
|
||||
Get-ChildItem -Path $sourceDir -Recurse -Filter "*.lib" | Remove-Item -Force
|
||||
Get-ChildItem -Path $sourceDir -Recurse -Filter "*ffmpeg*.dll" | Remove-Item -Force
|
||||
Get-ChildItem -Path $sourceDir -Recurse -Filter "*.pdb" | Remove-Item -Force
|
||||
@@ -398,26 +398,15 @@ jobs:
|
||||
event: push
|
||||
workflow_conclusion: success
|
||||
|
||||
- name: Embed Dotnet and VCRedist
|
||||
- name: Embed VCRedist
|
||||
shell: bash
|
||||
run: |
|
||||
# dotnet
|
||||
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
|
||||
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "Cannot get the latest version from $VERSION_URL"
|
||||
exit 1
|
||||
fi
|
||||
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
|
||||
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
|
||||
# vcredist
|
||||
echo "Downloading VCRedist"
|
||||
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
|
||||
# embed
|
||||
echo "Embedding runtimes"
|
||||
./kachina-builder.exe append -o ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
|
||||
echo "Embedding VCRedist"
|
||||
./kachina-builder.exe append -o ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
|
||||
./kachina-builder.exe extract -i ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
|
||||
- name: Extract 7z and create zip
|
||||
shell: bash
|
||||
|
||||
@@ -22,6 +22,8 @@ using BetterGenshinImpact.Pulonia.Executors;
|
||||
using BetterGenshinImpact.Pulonia.Services;
|
||||
using BetterGenshinImpact.Service;
|
||||
using BetterGenshinImpact.Service.ChildSession;
|
||||
using BetterGenshinImpact.Service.ExternalAccess;
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
using BetterGenshinImpact.Service.Instance;
|
||||
using BetterGenshinImpact.Service.I18n;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
@@ -84,6 +86,10 @@ public partial class App : Application
|
||||
var instanceIdentity =
|
||||
$"{instanceTypeLabel}:S{instanceContext.WindowsSessionId}:P{instanceContext.ProcessId}:T{instanceContext.StartedAt.ToUnixTimeMilliseconds()}";
|
||||
|
||||
// 外部日志分发器必须先于 Serilog 创建,确保启动阶段日志也能进入回放缓冲。
|
||||
var externalLogHub = new ExternalLogHub();
|
||||
services.AddSingleton(externalLogHub);
|
||||
|
||||
var richTextBox = new RichTextBoxImpl();
|
||||
services.AddSingleton<IRichTextBox>(richTextBox);
|
||||
|
||||
@@ -102,6 +108,9 @@ public partial class App : Application
|
||||
.MinimumLevel.Debug()
|
||||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
|
||||
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
|
||||
loggerConfiguration.WriteTo.Sink(
|
||||
new ExternalLogSink(externalLogHub, instanceIdentity),
|
||||
LogEventLevel.Debug);
|
||||
// 日志遮罩输出:仅当“遮罩启用且日志框可见”时才真正写入,隐藏时避免不必要的 UI 开销(#3161)。
|
||||
// 条件改为运行时每次写入时动态判断,因此启动后通过快捷键切换 ShowLogBox 也能即时恢复日志(#3357)。
|
||||
loggerConfiguration.WriteTo.Sink(
|
||||
@@ -138,6 +147,13 @@ public partial class App : Application
|
||||
services.AddSingleton(InstanceBootstrap.Current);
|
||||
services.AddSingleton<InstanceService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<InstanceService>());
|
||||
// 外部访问服务:协议适配层统一复用同一能力服务,仅 Primary 实例实际监听端口。
|
||||
services.AddSingleton<ExternalAccessState>();
|
||||
services.AddSingleton<ExternalAccessTokenService>();
|
||||
services.AddSingleton<IBgiExternalCapabilityService, BgiExternalCapabilityService>();
|
||||
services.AddSingleton<ExternalLogWebSocketHandler>();
|
||||
services.AddSingleton<ExternalAccessHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<ExternalAccessHost>());
|
||||
// App Host
|
||||
services.AddHostedService<ApplicationHostService>();
|
||||
// Page resolver service
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
<Version>0.66.1-alpha.1</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWPF>true</UseWPF>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<LangVersion>12.0</LangVersion>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<ApplicationIcon>Resources\Images\logo.ico</ApplicationIcon>
|
||||
<Platforms>x64</Platforms>
|
||||
@@ -69,11 +69,12 @@
|
||||
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI" Version="10.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.12" />
|
||||
<PackageReference Include="ModelContextProtocol.AspNetCore" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.21.0" />
|
||||
<!--排除掉cpu的runtime dll-->
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.21.0" IncludeAssets="none" />
|
||||
@@ -98,7 +99,7 @@
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
|
||||
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
|
||||
<PackageReference Include="System.IO.Hashing" Version="10.0.12" />
|
||||
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
|
||||
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.1.3" />
|
||||
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
|
||||
@@ -113,6 +114,10 @@
|
||||
<PackageReference Include="YoloSharp" Version="6.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -292,6 +292,11 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public ChildSessionConfig ChildSessionConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 本机外部访问服务配置
|
||||
/// </summary>
|
||||
public ExternalAccessConfig ExternalAccessConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 任意配置项变更后的回调(由 ConfigService 设置为防抖保存)
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// BetterGI 本机外部访问服务配置。
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class ExternalAccessConfig : ObservableValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否启用 HTTP API。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _httpApiEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用 WebSocket 实时日志。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _webSocketEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用 MCP Streamable HTTP 服务。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _mcpEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 本机外部访问服务共享端口。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
[NotifyDataErrorInfo]
|
||||
[Range(1024, 65535, ErrorMessage = "端口必须在 1024 到 65535 之间。")]
|
||||
private int _port = 30648;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP API 与 MCP 共用的 Bearer 访问令牌。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _accessToken = string.Empty;
|
||||
}
|
||||
@@ -6,13 +6,13 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
<PropertyGroup>
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
<PublishDir>bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\</PublishDir>
|
||||
<PublishDir>bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\</PublishDir>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<_TargetId>Folder</_TargetId>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
|
||||
<SelfContained>false</SelfContained>
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<PublishReadyToRun>false</PublishReadyToRun>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -1,12 +1,14 @@
|
||||
## 如何编译并运行整个工程?
|
||||
|
||||
构建前请安装 .NET 10 SDK 和 `10.0.22621.0` 或更高版本的 Windows SDK。
|
||||
|
||||
### Rider (推荐)
|
||||
1. `git clone https://github.com/babalae/better-genshin-impact.git`
|
||||
2. 推荐使用 [Rider](https://www.jetbrains.com/zh-cn/rider/) 打开本项目。速度快且免费!
|
||||
|
||||
### Visual Studio 2022
|
||||
### Visual Studio 2026
|
||||
1. `git clone https://github.com/babalae/better-genshin-impact.git`
|
||||
2. 需要使用 [Visual Studio 2022](https://visualstudio.microsoft.com/zh-hans/downloads/) 打开本项目。
|
||||
2. 需要使用支持 .NET 10 的 [Visual Studio](https://visualstudio.microsoft.com/zh-hans/downloads/) 打开本项目。
|
||||
|
||||
~~请注意当前 `/Asset` 目录下的部分文件过大,比如地图特征数据(300M+),需要手动从 Release 包中获取并拷贝至对应的编译目录下,软件才能够正常运行对应的功能。(当前仅影响地图追踪、自动传送相关功能)~~ 现在已经丢到 nuget 上可以直接编译构建了
|
||||
|
||||
@@ -33,4 +35,4 @@
|
||||
|
||||
## 识别用的模板资源 Recognition.json 如何编写
|
||||
|
||||
参考:[RecognitionJson编写说明](../Docs/technical/recognition-json.md)
|
||||
参考:[RecognitionJson编写说明](../Docs/technical/recognition-json.md)
|
||||
@@ -0,0 +1,42 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Models;
|
||||
using BetterGenshinImpact.Service.Instance;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess;
|
||||
|
||||
/// <summary>
|
||||
/// 提供可由多种外部传输协议复用的 BetterGI 基础能力。
|
||||
/// </summary>
|
||||
public sealed class BgiExternalCapabilityService(InstanceService instanceService) : IBgiExternalCapabilityService
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<BgiHealthDto> GetHealthAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var context = instanceService.Context;
|
||||
var uptime = DateTimeOffset.UtcNow - context.StartedAt;
|
||||
return Task.FromResult(new BgiHealthDto
|
||||
{
|
||||
Status = "healthy",
|
||||
InstanceRole = context.InstanceType.ToString(),
|
||||
ProcessId = context.ProcessId,
|
||||
StartedAtUtc = context.StartedAt.ToUniversalTime(),
|
||||
UptimeSeconds = Math.Max(0, (long)uptime.TotalSeconds)
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<BgiVersionDto> GetVersionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return Task.FromResult(new BgiVersionDto
|
||||
{
|
||||
Product = "BetterGI",
|
||||
Version = Global.Version,
|
||||
ApiVersion = "v1"
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Mcp;
|
||||
using BetterGenshinImpact.Service.Instance;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ModelContextProtocol.AspNetCore;
|
||||
using ModelContextProtocol.Server;
|
||||
using Serilog;
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess;
|
||||
|
||||
/// <summary>
|
||||
/// 在 BetterGI 主实例内托管仅监听 loopback 的 HTTP、WebSocket 与 MCP 服务。
|
||||
/// </summary>
|
||||
public sealed class ExternalAccessHost : IHostedService
|
||||
{
|
||||
/// <summary>
|
||||
/// 全局配置读写服务。
|
||||
/// </summary>
|
||||
private readonly IConfigService _configService;
|
||||
|
||||
/// <summary>
|
||||
/// BetterGI 多实例上下文服务。
|
||||
/// </summary>
|
||||
private readonly InstanceService _instanceService;
|
||||
|
||||
/// <summary>
|
||||
/// 设置页面可观察的运行状态。
|
||||
/// </summary>
|
||||
private readonly ExternalAccessState _state;
|
||||
|
||||
/// <summary>
|
||||
/// 访问令牌生成与校验服务。
|
||||
/// </summary>
|
||||
private readonly ExternalAccessTokenService _tokenService;
|
||||
|
||||
/// <summary>
|
||||
/// 与传输协议无关的 BetterGI 能力服务。
|
||||
/// </summary>
|
||||
private readonly IBgiExternalCapabilityService _capabilityService;
|
||||
|
||||
/// <summary>
|
||||
/// 实时日志分发器。
|
||||
/// </summary>
|
||||
private readonly ExternalLogHub _logHub;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket 日志连接处理器。
|
||||
/// </summary>
|
||||
private readonly ExternalLogWebSocketHandler _logWebSocketHandler;
|
||||
|
||||
/// <summary>
|
||||
/// 外部访问服务自身的日志记录器。
|
||||
/// </summary>
|
||||
private readonly ILogger<ExternalAccessHost> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// 实际承载外部协议端点的子 WebApplication。
|
||||
/// </summary>
|
||||
private WebApplication? _webApplication;
|
||||
|
||||
/// <summary>
|
||||
/// 创建 BetterGI 外部访问宿主。
|
||||
/// </summary>
|
||||
public ExternalAccessHost(
|
||||
IConfigService configService,
|
||||
InstanceService instanceService,
|
||||
ExternalAccessState state,
|
||||
ExternalAccessTokenService tokenService,
|
||||
IBgiExternalCapabilityService capabilityService,
|
||||
ExternalLogHub logHub,
|
||||
ExternalLogWebSocketHandler logWebSocketHandler,
|
||||
ILogger<ExternalAccessHost> logger)
|
||||
{
|
||||
_configService = configService;
|
||||
_instanceService = instanceService;
|
||||
_state = state;
|
||||
_tokenService = tokenService;
|
||||
_capabilityService = capabilityService;
|
||||
_logHub = logHub;
|
||||
_logWebSocketHandler = logWebSocketHandler;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按启动时配置创建并启动 loopback 子 WebApplication。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">应用启动取消令牌。</param>
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!_instanceService.Context.IsRoot)
|
||||
{
|
||||
_state.Update(ExternalAccessServiceStatus.Disabled, "仅 Primary 实例可以启动外部访问服务", "未启动");
|
||||
return;
|
||||
}
|
||||
|
||||
var config = _configService.Get().ExternalAccessConfig;
|
||||
var httpApiEnabled = config.HttpApiEnabled;
|
||||
var webSocketEnabled = config.WebSocketEnabled;
|
||||
var mcpEnabled = config.McpEnabled;
|
||||
var port = config.Port;
|
||||
|
||||
if (!httpApiEnabled && !webSocketEnabled && !mcpEnabled)
|
||||
{
|
||||
_state.Update(ExternalAccessServiceStatus.Disabled, "外部访问服务未启用", "未启动");
|
||||
return;
|
||||
}
|
||||
|
||||
if (port is < 1024 or > 65535)
|
||||
{
|
||||
_state.Update(ExternalAccessServiceStatus.Failed, "端口必须在 1024 到 65535 之间", "未启动");
|
||||
_logger.LogError("外部访问服务端口 {Port} 不合法", port);
|
||||
return;
|
||||
}
|
||||
|
||||
var address = $"http://127.0.0.1:{port}";
|
||||
_state.Update(ExternalAccessServiceStatus.Starting, "正在启动本机外部访问服务", address);
|
||||
|
||||
try
|
||||
{
|
||||
// 令牌生成和持久化也属于服务启动流程,失败时只更新状态而不终止 WPF 主程序。
|
||||
if (httpApiEnabled || mcpEnabled)
|
||||
{
|
||||
_tokenService.EnsureToken();
|
||||
}
|
||||
|
||||
_webApplication = BuildApplication(port, httpApiEnabled, webSocketEnabled, mcpEnabled);
|
||||
await _webApplication.StartAsync(cancellationToken).ConfigureAwait(false);
|
||||
_state.Update(ExternalAccessServiceStatus.Running, "配置开关和端口将在下次重启时重新加载", address);
|
||||
_logger.LogInformation(
|
||||
"外部访问服务已启动:{Address},HTTP={HttpEnabled},WebSocket={WebSocketEnabled},MCP={McpEnabled}",
|
||||
address,
|
||||
httpApiEnabled,
|
||||
webSocketEnabled,
|
||||
mcpEnabled);
|
||||
}
|
||||
catch (Exception exception) when (exception is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_state.Update(ExternalAccessServiceStatus.Failed, exception.Message, address);
|
||||
_logger.LogError(exception, "外部访问服务启动失败:{Address}", address);
|
||||
try
|
||||
{
|
||||
await DisposeWebApplicationAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception disposeException)
|
||||
{
|
||||
// 失败宿主的清理异常也不能中断 WPF 主程序启动。
|
||||
_logger.LogWarning(disposeException, "释放启动失败的外部访问服务时发生异常");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止并释放外部访问子 WebApplication。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">应用停止取消令牌。</param>
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_webApplication is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _webApplication.StopAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// 主程序正在强制结束,继续释放子宿主。
|
||||
}
|
||||
finally
|
||||
{
|
||||
await DisposeWebApplicationAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (_state.Status != ExternalAccessServiceStatus.Disabled)
|
||||
{
|
||||
_state.Update(ExternalAccessServiceStatus.Stopped, "外部访问服务已停止", "未启动");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建并配置承载外部协议的子 WebApplication。
|
||||
/// </summary>
|
||||
/// <param name="port">loopback 监听端口。</param>
|
||||
/// <param name="httpApiEnabled">是否映射 HTTP API。</param>
|
||||
/// <param name="webSocketEnabled">是否映射 WebSocket 日志。</param>
|
||||
/// <param name="mcpEnabled">是否映射 MCP。</param>
|
||||
/// <returns>尚未启动的 WebApplication。</returns>
|
||||
private WebApplication BuildApplication(
|
||||
int port,
|
||||
bool httpApiEnabled,
|
||||
bool webSocketEnabled,
|
||||
bool mcpEnabled)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
||||
{
|
||||
Args = [],
|
||||
ApplicationName = typeof(ExternalAccessHost).Assembly.GetName().Name,
|
||||
ContentRootPath = AppContext.BaseDirectory,
|
||||
EnvironmentName = Environments.Production
|
||||
});
|
||||
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddSerilog(Log.Logger, dispose: false);
|
||||
builder.WebHost.ConfigureKestrel(options => options.ListenLocalhost(port));
|
||||
|
||||
builder.Services.ConfigureHttpJsonOptions(options =>
|
||||
{
|
||||
options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||
});
|
||||
builder.Services.AddCors(options => options.AddPolicy(
|
||||
"ExternalAccess",
|
||||
policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
|
||||
builder.Services.AddSingleton(_capabilityService);
|
||||
builder.Services.AddSingleton(_tokenService);
|
||||
builder.Services.AddSingleton(_logHub);
|
||||
builder.Services.AddSingleton(_logWebSocketHandler);
|
||||
|
||||
if (mcpEnabled)
|
||||
{
|
||||
builder.Services.AddMcpServer()
|
||||
.WithHttpTransport(options => options.SessionMode = HttpServerSessionMode.Stateless)
|
||||
.WithTools<BgiMcpTools>();
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
ConfigurePipeline(app, httpApiEnabled, webSocketEnabled, mcpEnabled);
|
||||
return app;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配置 Host 校验、CORS、Bearer 鉴权及已启用的协议端点。
|
||||
/// </summary>
|
||||
/// <param name="app">外部访问子 WebApplication。</param>
|
||||
/// <param name="httpApiEnabled">是否映射 HTTP API。</param>
|
||||
/// <param name="webSocketEnabled">是否映射 WebSocket 日志。</param>
|
||||
/// <param name="mcpEnabled">是否映射 MCP。</param>
|
||||
private void ConfigurePipeline(
|
||||
WebApplication app,
|
||||
bool httpApiEnabled,
|
||||
bool webSocketEnabled,
|
||||
bool mcpEnabled)
|
||||
{
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
if (!IsLoopbackHost(context.Request.Host.Host))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsync("Host 必须是 loopback 地址。", context.RequestAborted);
|
||||
return;
|
||||
}
|
||||
|
||||
await next(context);
|
||||
});
|
||||
|
||||
app.UseRouting();
|
||||
// CORS 策略通过端点元数据按需应用,未启用的协议路径仍由框架返回 404。
|
||||
app.UseCors();
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
if (HttpMethods.IsOptions(context.Request.Method)
|
||||
|| !RequiresBearerToken(context.Request.Path, httpApiEnabled, mcpEnabled))
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_tokenService.IsAuthorized(context.Request.Headers.Authorization))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
context.Response.Headers["WWW-Authenticate"] = "Bearer";
|
||||
return;
|
||||
}
|
||||
|
||||
await next(context);
|
||||
});
|
||||
|
||||
if (httpApiEnabled)
|
||||
{
|
||||
app.MapGet("/api/v1/health", async (CancellationToken cancellationToken) =>
|
||||
Results.Ok(await _capabilityService.GetHealthAsync(cancellationToken).ConfigureAwait(false)))
|
||||
.RequireCors("ExternalAccess");
|
||||
app.MapGet("/api/v1/version", async (CancellationToken cancellationToken) =>
|
||||
Results.Ok(await _capabilityService.GetVersionAsync(cancellationToken).ConfigureAwait(false)))
|
||||
.RequireCors("ExternalAccess");
|
||||
}
|
||||
|
||||
if (webSocketEnabled)
|
||||
{
|
||||
// AllowedOrigins 为空表示按产品约定允许所有 Origin;该端点也明确不使用 Bearer 鉴权。
|
||||
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
|
||||
app.Map("/ws/v1/logs", _logWebSocketHandler.HandleAsync);
|
||||
}
|
||||
|
||||
if (mcpEnabled)
|
||||
{
|
||||
app.MapMcp("/mcp").RequireCors("ExternalAccess");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断请求 Host 是否为 localhost 或 loopback IP,阻止 DNS rebinding Host。
|
||||
/// </summary>
|
||||
/// <param name="host">HTTP Host 中不含端口的主机部分。</param>
|
||||
/// <returns>是否为本机回环地址。</returns>
|
||||
private static bool IsLoopbackHost(string host)
|
||||
{
|
||||
return host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
|
||||
|| IPAddress.TryParse(host, out var address) && IPAddress.IsLoopback(address);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断当前路径是否属于已启用且需要 Bearer 令牌的 HTTP API 或 MCP。
|
||||
/// </summary>
|
||||
/// <param name="path">请求路径。</param>
|
||||
/// <param name="httpApiEnabled">HTTP API 是否已映射。</param>
|
||||
/// <param name="mcpEnabled">MCP 是否已映射。</param>
|
||||
/// <returns>是否需要鉴权。</returns>
|
||||
private static bool RequiresBearerToken(PathString path, bool httpApiEnabled, bool mcpEnabled)
|
||||
{
|
||||
return httpApiEnabled && path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)
|
||||
|| mcpEnabled && path.StartsWithSegments("/mcp", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放当前子 WebApplication 并清空引用。
|
||||
/// </summary>
|
||||
private async ValueTask DisposeWebApplicationAsync()
|
||||
{
|
||||
var app = _webApplication;
|
||||
_webApplication = null;
|
||||
if (app is not null)
|
||||
{
|
||||
await app.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess;
|
||||
|
||||
/// <summary>
|
||||
/// 外部访问服务生命周期状态。
|
||||
/// </summary>
|
||||
public enum ExternalAccessServiceStatus
|
||||
{
|
||||
/// <summary>全部外部访问能力均未启用。</summary>
|
||||
Disabled,
|
||||
|
||||
/// <summary>服务正在启动。</summary>
|
||||
Starting,
|
||||
|
||||
/// <summary>服务正在运行。</summary>
|
||||
Running,
|
||||
|
||||
/// <summary>服务启动或运行失败。</summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>服务已停止。</summary>
|
||||
Stopped
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 向设置页面公开外部访问服务的只读运行状态。
|
||||
/// </summary>
|
||||
public sealed class ExternalAccessState : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 当前生命周期状态。
|
||||
/// </summary>
|
||||
private ExternalAccessServiceStatus _status = ExternalAccessServiceStatus.Disabled;
|
||||
|
||||
/// <summary>
|
||||
/// 当前状态的补充说明。
|
||||
/// </summary>
|
||||
private string _message = "外部访问服务未启用";
|
||||
|
||||
/// <summary>
|
||||
/// 当前服务监听地址。
|
||||
/// </summary>
|
||||
private string _address = "未启动";
|
||||
|
||||
/// <summary>
|
||||
/// 当前生命周期状态。
|
||||
/// </summary>
|
||||
public ExternalAccessServiceStatus Status
|
||||
{
|
||||
get => _status;
|
||||
private set
|
||||
{
|
||||
if (SetProperty(ref _status, value))
|
||||
{
|
||||
OnPropertyChanged(nameof(StatusText));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当前状态的本地化展示文本。
|
||||
/// </summary>
|
||||
public string StatusText => Status switch
|
||||
{
|
||||
ExternalAccessServiceStatus.Disabled => "未启用",
|
||||
ExternalAccessServiceStatus.Starting => "正在启动",
|
||||
ExternalAccessServiceStatus.Running => "运行中",
|
||||
ExternalAccessServiceStatus.Failed => "启动失败",
|
||||
ExternalAccessServiceStatus.Stopped => "已停止",
|
||||
_ => "未知"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 当前状态的补充说明。
|
||||
/// </summary>
|
||||
public string Message
|
||||
{
|
||||
get => _message;
|
||||
private set => SetProperty(ref _message, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 当前服务监听地址。
|
||||
/// </summary>
|
||||
public string Address
|
||||
{
|
||||
get => _address;
|
||||
private set => SetProperty(ref _address, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 原子更新设置页面展示的服务状态。
|
||||
/// </summary>
|
||||
/// <param name="status">新的生命周期状态。</param>
|
||||
/// <param name="message">状态补充说明。</param>
|
||||
/// <param name="address">当前监听地址。</param>
|
||||
public void Update(ExternalAccessServiceStatus status, string message, string address)
|
||||
{
|
||||
Status = status;
|
||||
Message = message;
|
||||
Address = address;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess;
|
||||
|
||||
/// <summary>
|
||||
/// 生成、持久化并校验 HTTP API 与 MCP 共用的访问令牌。
|
||||
/// </summary>
|
||||
public sealed class ExternalAccessTokenService(IConfigService configService)
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前令牌;令牌为空时生成并立即持久化。
|
||||
/// </summary>
|
||||
/// <returns>可用于 Bearer 鉴权的访问令牌。</returns>
|
||||
public string EnsureToken()
|
||||
{
|
||||
var externalAccessConfig = configService.Get().ExternalAccessConfig;
|
||||
if (!string.IsNullOrWhiteSpace(externalAccessConfig.AccessToken))
|
||||
{
|
||||
return externalAccessConfig.AccessToken;
|
||||
}
|
||||
|
||||
return RegenerateToken();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新生成 256-bit Base64Url 访问令牌并立即持久化。
|
||||
/// </summary>
|
||||
/// <returns>新生成的访问令牌。</returns>
|
||||
public string RegenerateToken()
|
||||
{
|
||||
var token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
|
||||
.TrimEnd('=')
|
||||
.Replace('+', '-')
|
||||
.Replace('/', '_');
|
||||
configService.Get().ExternalAccessConfig.AccessToken = token;
|
||||
configService.Save();
|
||||
return token;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用固定时间比较校验 Bearer 请求头。
|
||||
/// </summary>
|
||||
/// <param name="authorizationHeader">完整的 Authorization 请求头。</param>
|
||||
/// <returns>请求头中的令牌是否有效。</returns>
|
||||
public bool IsAuthorized(string? authorizationHeader)
|
||||
{
|
||||
const string bearerPrefix = "Bearer ";
|
||||
if (string.IsNullOrWhiteSpace(authorizationHeader)
|
||||
|| !authorizationHeader.StartsWith(bearerPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var expectedToken = configService.Get().ExternalAccessConfig.AccessToken;
|
||||
var suppliedToken = authorizationHeader[bearerPrefix.Length..].Trim();
|
||||
if (string.IsNullOrEmpty(expectedToken) || suppliedToken.Length != expectedToken.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(expectedToken);
|
||||
var suppliedBytes = Encoding.UTF8.GetBytes(suppliedToken);
|
||||
return CryptographicOperations.FixedTimeEquals(expectedBytes, suppliedBytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Serilog.Events;
|
||||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess;
|
||||
|
||||
/// <summary>
|
||||
/// 处理实时日志 WebSocket 连接、历史回放和连接清理。
|
||||
/// </summary>
|
||||
public sealed class ExternalLogWebSocketHandler(ExternalLogHub logHub)
|
||||
{
|
||||
/// <summary>
|
||||
/// WebSocket 消息使用的 camelCase JSON 配置。
|
||||
/// </summary>
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
/// <summary>
|
||||
/// 接受并维护一个实时日志 WebSocket 连接。
|
||||
/// </summary>
|
||||
/// <param name="context">当前 HTTP 请求上下文。</param>
|
||||
public async Task HandleAsync(HttpContext context)
|
||||
{
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsync("该端点仅接受 WebSocket 连接。", context.RequestAborted);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TryParseMinimumLevel(context.Request.Query["minimumLevel"], out var minimumLevel))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
||||
await context.Response.WriteAsync("minimumLevel 不是有效的 Serilog 日志级别。", context.RequestAborted);
|
||||
return;
|
||||
}
|
||||
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync();
|
||||
var subscription = logHub.Subscribe(minimumLevel);
|
||||
using var connectionCancellation = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
|
||||
|
||||
try
|
||||
{
|
||||
// WebSocket 允许一收一发并行:接收任务负责及时感知客户端关闭,发送任务负责日志推送。
|
||||
var sendTask = SendLogsAsync(socket, subscription, connectionCancellation.Token);
|
||||
var receiveTask = ReceiveUntilCloseAsync(socket, connectionCancellation.Token);
|
||||
await Task.WhenAny(sendTask, receiveTask).ConfigureAwait(false);
|
||||
await connectionCancellation.CancelAsync().ConfigureAwait(false);
|
||||
await AwaitConnectionTaskAsync(sendTask).ConfigureAwait(false);
|
||||
await AwaitConnectionTaskAsync(receiveTask).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
logHub.Unsubscribe(subscription.Id);
|
||||
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||
{
|
||||
try
|
||||
{
|
||||
await socket.CloseOutputAsync(
|
||||
WebSocketCloseStatus.NormalClosure,
|
||||
"BetterGI 日志流已关闭。",
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (WebSocketException)
|
||||
{
|
||||
// 对端已经断开,不需要让清理异常影响服务。
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析客户端要求的最低日志级别。
|
||||
/// </summary>
|
||||
/// <param name="value">查询参数值。</param>
|
||||
/// <param name="minimumLevel">解析后的最低日志级别。</param>
|
||||
/// <returns>参数是否合法。</returns>
|
||||
private static bool TryParseMinimumLevel(string? value, out LogEventLevel minimumLevel)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
minimumLevel = LogEventLevel.Information;
|
||||
return true;
|
||||
}
|
||||
|
||||
return Enum.TryParse(value, ignoreCase: true, out minimumLevel)
|
||||
&& Enum.IsDefined(minimumLevel);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 先发送历史快照,再持续发送实时日志和丢弃通知。
|
||||
/// </summary>
|
||||
/// <param name="socket">客户端 WebSocket。</param>
|
||||
/// <param name="subscription">日志订阅。</param>
|
||||
/// <param name="cancellationToken">连接取消令牌。</param>
|
||||
private static async Task SendLogsAsync(
|
||||
WebSocket socket,
|
||||
ExternalLogSubscription subscription,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var logEvent in subscription.Snapshot)
|
||||
{
|
||||
await SendJsonAsync(socket, logEvent, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await foreach (var logEvent in subscription.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var droppedCount = subscription.TakeDroppedCount();
|
||||
if (droppedCount > 0)
|
||||
{
|
||||
await SendJsonAsync(
|
||||
socket,
|
||||
new ExternalLogDroppedDto { Count = droppedCount },
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await SendJsonAsync(socket, logEvent, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 持续接收并忽略客户端数据,只处理关闭帧和断开状态。
|
||||
/// </summary>
|
||||
/// <param name="socket">客户端 WebSocket。</param>
|
||||
/// <param name="cancellationToken">连接取消令牌。</param>
|
||||
private static async Task ReceiveUntilCloseAsync(WebSocket socket, CancellationToken cancellationToken)
|
||||
{
|
||||
var buffer = new byte[1024];
|
||||
while (!cancellationToken.IsCancellationRequested && socket.State == WebSocketState.Open)
|
||||
{
|
||||
var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将对象序列化为一条完整的 UTF-8 WebSocket 文本消息。
|
||||
/// </summary>
|
||||
/// <param name="socket">客户端 WebSocket。</param>
|
||||
/// <param name="value">待发送对象。</param>
|
||||
/// <param name="cancellationToken">连接取消令牌。</param>
|
||||
private static Task SendJsonAsync<T>(WebSocket socket, T value, CancellationToken cancellationToken)
|
||||
{
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(value, JsonOptions);
|
||||
return socket.SendAsync(payload, WebSocketMessageType.Text, endOfMessage: true, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 忽略连接结束时预期出现的取消和 WebSocket 断开异常。
|
||||
/// </summary>
|
||||
/// <param name="task">连接收发任务。</param>
|
||||
private static async Task AwaitConnectionTaskAsync(Task task)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception) when (exception is OperationCanceledException or WebSocketException)
|
||||
{
|
||||
// 客户端断开或应用停止均属于正常连接结束。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Models;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess;
|
||||
|
||||
/// <summary>
|
||||
/// 与 HTTP、MCP 等传输协议无关的 BetterGI 外部访问能力。
|
||||
/// </summary>
|
||||
public interface IBgiExternalCapabilityService
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前 BetterGI 主实例的健康状态。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">取消操作的令牌。</param>
|
||||
/// <returns>健康状态。</returns>
|
||||
Task<BgiHealthDto> GetHealthAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// 获取 BetterGI 与外部访问 API 的版本信息。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">取消操作的令牌。</param>
|
||||
/// <returns>版本信息。</returns>
|
||||
Task<BgiVersionDto> GetVersionAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// 通知 WebSocket 客户端其消费过慢而被丢弃的日志数量。
|
||||
/// </summary>
|
||||
public sealed class ExternalLogDroppedDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 消息类型。
|
||||
/// </summary>
|
||||
public string Type { get; init; } = "dropped";
|
||||
|
||||
/// <summary>
|
||||
/// 自上次通知以来被丢弃的日志数量。
|
||||
/// </summary>
|
||||
public required long Count { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Serilog.Events;
|
||||
using System;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// 通过 WebSocket 对外传输的一条结构化日志事件。
|
||||
/// </summary>
|
||||
public sealed class ExternalLogEvent
|
||||
{
|
||||
/// <summary>
|
||||
/// 消息类型。
|
||||
/// </summary>
|
||||
public string Type { get; init; } = "log";
|
||||
|
||||
/// <summary>
|
||||
/// 进程内单调递增的日志序号。
|
||||
/// </summary>
|
||||
public required long Sequence { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 日志产生的 UTC 时间。
|
||||
/// </summary>
|
||||
public required DateTimeOffset TimestampUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 日志级别名称。
|
||||
/// </summary>
|
||||
public required string Level { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 日志来源上下文。
|
||||
/// </summary>
|
||||
public string? Source { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 已渲染的日志正文。
|
||||
/// </summary>
|
||||
public required string Message { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 异常详情;没有异常时为空。
|
||||
/// </summary>
|
||||
public string? Exception { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 产生该日志的 BetterGI 实例标识。
|
||||
/// </summary>
|
||||
public required string Instance { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 用于服务端过滤的 Serilog 日志级别,不写入外部 JSON。
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public required LogEventLevel LevelValue { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using Serilog.Events;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// 保存有限历史日志并向多个 WebSocket 客户端分发实时日志。
|
||||
/// </summary>
|
||||
public sealed class ExternalLogHub
|
||||
{
|
||||
/// <summary>
|
||||
/// 新连接最多回放的历史日志数量。
|
||||
/// </summary>
|
||||
private const int ReplayCapacity = 200;
|
||||
|
||||
/// <summary>
|
||||
/// 保护历史日志和订阅集合。
|
||||
/// </summary>
|
||||
private readonly object _locker = new();
|
||||
|
||||
/// <summary>
|
||||
/// 最近产生的日志环形缓冲。
|
||||
/// </summary>
|
||||
private readonly Queue<ExternalLogEvent> _replayBuffer = new();
|
||||
|
||||
/// <summary>
|
||||
/// 当前活动的客户端订阅。
|
||||
/// </summary>
|
||||
private readonly Dictionary<Guid, ExternalLogSubscription> _subscriptions = new();
|
||||
|
||||
/// <summary>
|
||||
/// 进程内日志序号。
|
||||
/// </summary>
|
||||
private long _sequence;
|
||||
|
||||
/// <summary>
|
||||
/// 将日志写入回放缓冲并非阻塞地投递给所有客户端。
|
||||
/// </summary>
|
||||
/// <param name="timestampUtc">日志 UTC 时间。</param>
|
||||
/// <param name="level">日志级别。</param>
|
||||
/// <param name="source">日志来源。</param>
|
||||
/// <param name="message">已渲染的日志正文。</param>
|
||||
/// <param name="exception">异常详情。</param>
|
||||
/// <param name="instance">BetterGI 实例标识。</param>
|
||||
public void Publish(
|
||||
DateTimeOffset timestampUtc,
|
||||
LogEventLevel level,
|
||||
string? source,
|
||||
string message,
|
||||
string? exception,
|
||||
string instance)
|
||||
{
|
||||
var logEvent = new ExternalLogEvent
|
||||
{
|
||||
Sequence = Interlocked.Increment(ref _sequence),
|
||||
TimestampUtc = timestampUtc,
|
||||
Level = level.ToString(),
|
||||
LevelValue = level,
|
||||
Source = source,
|
||||
Message = message,
|
||||
Exception = exception,
|
||||
Instance = instance
|
||||
};
|
||||
|
||||
lock (_locker)
|
||||
{
|
||||
_replayBuffer.Enqueue(logEvent);
|
||||
while (_replayBuffer.Count > ReplayCapacity)
|
||||
{
|
||||
_replayBuffer.Dequeue();
|
||||
}
|
||||
|
||||
foreach (var subscription in _subscriptions.Values)
|
||||
{
|
||||
if (level >= subscription.MinimumLevel)
|
||||
{
|
||||
subscription.TryPublish(logEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 建立客户端订阅,并在同一临界区内取得历史快照,避免遗漏边界日志。
|
||||
/// </summary>
|
||||
/// <param name="minimumLevel">客户端要求的最低日志级别。</param>
|
||||
/// <returns>包含历史快照的实时日志订阅。</returns>
|
||||
public ExternalLogSubscription Subscribe(LogEventLevel minimumLevel)
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
var snapshot = _replayBuffer.Where(item => item.LevelValue >= minimumLevel).ToArray();
|
||||
var subscription = new ExternalLogSubscription(id, minimumLevel, snapshot);
|
||||
_subscriptions.Add(id, subscription);
|
||||
return subscription;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除并完成指定客户端订阅。
|
||||
/// </summary>
|
||||
/// <param name="subscriptionId">订阅唯一标识。</param>
|
||||
public void Unsubscribe(Guid subscriptionId)
|
||||
{
|
||||
ExternalLogSubscription? subscription;
|
||||
lock (_locker)
|
||||
{
|
||||
if (!_subscriptions.Remove(subscriptionId, out subscription))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
subscription.Complete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Serilog.Core;
|
||||
using Serilog.Events;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// 将现有 Serilog 事件转交给非阻塞外部日志分发器。
|
||||
/// </summary>
|
||||
public sealed class ExternalLogSink(ExternalLogHub logHub, string instanceIdentity) : ILogEventSink
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Emit(LogEvent logEvent)
|
||||
{
|
||||
var source = logEvent.Properties.TryGetValue("SourceContext", out var sourceValue)
|
||||
&& sourceValue is ScalarValue { Value: string sourceContext }
|
||||
? sourceContext
|
||||
: null;
|
||||
|
||||
logHub.Publish(
|
||||
logEvent.Timestamp.ToUniversalTime(),
|
||||
logEvent.Level,
|
||||
source,
|
||||
logEvent.RenderMessage(),
|
||||
logEvent.Exception?.ToString(),
|
||||
instanceIdentity);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using Serilog.Events;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// 一个 WebSocket 日志客户端的有界、非阻塞订阅。
|
||||
/// </summary>
|
||||
public sealed class ExternalLogSubscription
|
||||
{
|
||||
/// <summary>
|
||||
/// 单客户端实时日志队列容量。
|
||||
/// </summary>
|
||||
private const int QueueCapacity = 512;
|
||||
|
||||
/// <summary>
|
||||
/// 保护队列、完成状态和丢弃计数。
|
||||
/// </summary>
|
||||
private readonly object _locker = new();
|
||||
|
||||
/// <summary>
|
||||
/// 等待中的实时日志队列。
|
||||
/// </summary>
|
||||
private readonly Queue<ExternalLogEvent> _queue = new();
|
||||
|
||||
/// <summary>
|
||||
/// 表示当前可读取日志数量的异步信号量。
|
||||
/// </summary>
|
||||
private readonly SemaphoreSlim _available = new(0);
|
||||
|
||||
/// <summary>
|
||||
/// 自上次通知以来被丢弃的日志数量。
|
||||
/// </summary>
|
||||
private long _droppedCount;
|
||||
|
||||
/// <summary>
|
||||
/// 订阅是否已结束。
|
||||
/// </summary>
|
||||
private bool _completed;
|
||||
|
||||
/// <summary>
|
||||
/// 创建一个日志客户端订阅。
|
||||
/// </summary>
|
||||
/// <param name="id">订阅唯一标识。</param>
|
||||
/// <param name="minimumLevel">客户端要求的最低日志级别。</param>
|
||||
/// <param name="snapshot">订阅建立时的历史日志快照。</param>
|
||||
internal ExternalLogSubscription(Guid id, LogEventLevel minimumLevel, IReadOnlyList<ExternalLogEvent> snapshot)
|
||||
{
|
||||
Id = id;
|
||||
MinimumLevel = minimumLevel;
|
||||
Snapshot = snapshot;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 订阅唯一标识。
|
||||
/// </summary>
|
||||
public Guid Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 客户端要求的最低日志级别。
|
||||
/// </summary>
|
||||
public LogEventLevel MinimumLevel { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 建立订阅时需要首先发送的历史日志快照。
|
||||
/// </summary>
|
||||
public IReadOnlyList<ExternalLogEvent> Snapshot { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 非阻塞写入实时日志;队列已满时移除最旧项。
|
||||
/// </summary>
|
||||
/// <param name="logEvent">待写入的日志事件。</param>
|
||||
internal void TryPublish(ExternalLogEvent logEvent)
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
if (_completed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var shouldRelease = _queue.Count < QueueCapacity;
|
||||
if (!shouldRelease)
|
||||
{
|
||||
_queue.Dequeue();
|
||||
_droppedCount++;
|
||||
}
|
||||
|
||||
_queue.Enqueue(logEvent);
|
||||
if (shouldRelease)
|
||||
{
|
||||
_available.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步读取实时日志,直至订阅完成或请求被取消。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">取消读取的令牌。</param>
|
||||
/// <returns>实时日志异步序列。</returns>
|
||||
public async IAsyncEnumerable<ExternalLogEvent> ReadAllAsync(
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
await _available.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
ExternalLogEvent? logEvent;
|
||||
lock (_locker)
|
||||
{
|
||||
if (_queue.Count > 0)
|
||||
{
|
||||
logEvent = _queue.Dequeue();
|
||||
}
|
||||
else if (_completed)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
else
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
yield return logEvent;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取并清零尚未通知客户端的丢弃数量。
|
||||
/// </summary>
|
||||
/// <returns>累计丢弃数量。</returns>
|
||||
public long TakeDroppedCount()
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
var droppedCount = _droppedCount;
|
||||
_droppedCount = 0;
|
||||
return droppedCount;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 完成订阅并唤醒等待中的读取者。
|
||||
/// </summary>
|
||||
internal void Complete()
|
||||
{
|
||||
lock (_locker)
|
||||
{
|
||||
if (_completed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_completed = true;
|
||||
_available.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using BetterGenshinImpact.Service.ExternalAccess.Models;
|
||||
using ModelContextProtocol.Server;
|
||||
using System.ComponentModel;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// 将共享 BetterGI 外部访问能力适配为 MCP 工具。
|
||||
/// </summary>
|
||||
[McpServerToolType]
|
||||
public sealed class BgiMcpTools
|
||||
{
|
||||
/// <summary>
|
||||
/// 与传输协议无关的共享能力服务。
|
||||
/// </summary>
|
||||
private readonly IBgiExternalCapabilityService _capabilityService;
|
||||
|
||||
/// <summary>
|
||||
/// 创建 BetterGI MCP 工具适配器。
|
||||
/// </summary>
|
||||
/// <param name="capabilityService">共享能力服务。</param>
|
||||
public BgiMcpTools(IBgiExternalCapabilityService capabilityService)
|
||||
{
|
||||
_capabilityService = capabilityService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前 BetterGI 主实例健康状态。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">MCP 请求取消令牌。</param>
|
||||
/// <returns>共享健康状态 DTO。</returns>
|
||||
[McpServerTool(Name = "get_bgi_health", UseStructuredContent = true)]
|
||||
[Description("获取当前 BetterGI 主实例的健康状态、进程信息与运行时长。")]
|
||||
public Task<BgiHealthDto> GetHealthAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return _capabilityService.GetHealthAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 BetterGI 与外部访问 API 版本。
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">MCP 请求取消令牌。</param>
|
||||
/// <returns>共享版本 DTO。</returns>
|
||||
[McpServerTool(Name = "get_bgi_version", UseStructuredContent = true)]
|
||||
[Description("获取 BetterGI 产品版本和外部访问 API 版本。")]
|
||||
public Task<BgiVersionDto> GetVersionAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return _capabilityService.GetVersionAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Models;
|
||||
|
||||
/// <summary>
|
||||
/// BetterGI 外部访问服务健康状态。
|
||||
/// </summary>
|
||||
public sealed class BgiHealthDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 服务健康状态。
|
||||
/// </summary>
|
||||
public required string Status { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前 BetterGI 实例角色。
|
||||
/// </summary>
|
||||
public required string InstanceRole { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前进程标识。
|
||||
/// </summary>
|
||||
public required int ProcessId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前实例的 UTC 启动时间。
|
||||
/// </summary>
|
||||
public required DateTimeOffset StartedAtUtc { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前实例已运行的秒数。
|
||||
/// </summary>
|
||||
public required long UptimeSeconds { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace BetterGenshinImpact.Service.ExternalAccess.Models;
|
||||
|
||||
/// <summary>
|
||||
/// BetterGI 产品与外部访问协议版本信息。
|
||||
/// </summary>
|
||||
public sealed class BgiVersionDto
|
||||
{
|
||||
/// <summary>
|
||||
/// 产品名称。
|
||||
/// </summary>
|
||||
public required string Product { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// BetterGI 应用版本。
|
||||
/// </summary>
|
||||
public required string Version { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// 外部访问 API 版本。
|
||||
/// </summary>
|
||||
public required string ApiVersion { get; init; }
|
||||
}
|
||||
@@ -107,6 +107,161 @@
|
||||
</ui:CardControl.Header>
|
||||
</ui:CardControl>
|
||||
|
||||
<ui:CardExpander Margin="0,0,0,12"
|
||||
ContentPadding="0"
|
||||
Icon="{ui:SymbolIcon Globe24}">
|
||||
<ui:CardExpander.Header>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<ui:TextBlock Grid.Row="0"
|
||||
FontTypography="Body"
|
||||
Text="本机外部访问服务"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:TextBlock Grid.Row="1"
|
||||
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="仅监听 loopback;功能开关和端口将在重启 BetterGI 后生效"
|
||||
TextWrapping="Wrap" />
|
||||
</Grid>
|
||||
</ui:CardExpander.Header>
|
||||
<StackPanel>
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:TextBlock Grid.Row="0" FontTypography="Body" Text="HTTP API" />
|
||||
<ui:TextBlock Grid.Row="1"
|
||||
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="提供 /api/v1/health 与 /api/v1/version"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:ToggleSwitch Grid.Row="0"
|
||||
Grid.RowSpan="2"
|
||||
Grid.Column="1"
|
||||
Margin="0,0,24,0"
|
||||
IsChecked="{Binding Config.ExternalAccessConfig.HttpApiEnabled, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:TextBlock Grid.Row="0" FontTypography="Body" Text="WebSocket 实时日志" />
|
||||
<ui:TextBlock Grid.Row="1"
|
||||
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="不鉴权并允许任意 Origin,启用后本机网页可读取日志,请注意敏感信息风险"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:ToggleSwitch Grid.Row="0"
|
||||
Grid.RowSpan="2"
|
||||
Grid.Column="1"
|
||||
Margin="0,0,24,0"
|
||||
IsChecked="{Binding Config.ExternalAccessConfig.WebSocketEnabled, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:TextBlock Grid.Row="0" FontTypography="Body" Text="MCP Streamable HTTP" />
|
||||
<ui:TextBlock Grid.Row="1"
|
||||
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="在 /mcp 暴露与 HTTP API 相同的共享能力"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:ToggleSwitch Grid.Row="0"
|
||||
Grid.RowSpan="2"
|
||||
Grid.Column="1"
|
||||
Margin="0,0,24,0"
|
||||
IsChecked="{Binding Config.ExternalAccessConfig.McpEnabled, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
|
||||
<Grid Margin="16">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Grid.Column="0">
|
||||
<ui:TextBlock FontTypography="Body" Text="监听端口" />
|
||||
<ui:TextBlock Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="有效范围 1024~65535,HTTP、WebSocket 和 MCP 共用"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ui:TextBox Grid.Column="1"
|
||||
Width="120"
|
||||
Margin="16,0,24,0"
|
||||
VerticalAlignment="Center"
|
||||
Text="{Binding Config.ExternalAccessConfig.Port, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}" />
|
||||
</Grid>
|
||||
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
|
||||
<Grid Margin="16">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Grid.Column="0">
|
||||
<ui:TextBlock FontTypography="Body" Text="访问令牌" />
|
||||
<ui:TextBlock Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="HTTP API 与 MCP 共用;令牌变更立即生效"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:TextBlock Margin="0,4,0,0"
|
||||
FontFamily="Consolas"
|
||||
Text="{Binding MaskedExternalAccessToken}" />
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1"
|
||||
Margin="16,0,24,0"
|
||||
VerticalAlignment="Center"
|
||||
Orientation="Horizontal">
|
||||
<ui:Button Margin="0,0,8,0"
|
||||
Command="{Binding CopyExternalAccessTokenCommand}"
|
||||
Content="复制" />
|
||||
<ui:Button Command="{Binding RegenerateExternalAccessTokenCommand}"
|
||||
Content="重新生成" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:TextBlock Grid.Row="0" Grid.Column="0" Margin="0,0,12,0" FontTypography="Body" Text="状态" />
|
||||
<ui:TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding ExternalAccessState.StatusText}" />
|
||||
<ui:TextBlock Grid.Row="1" Grid.Column="1"
|
||||
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="{Binding ExternalAccessState.Message}"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:TextBlock Grid.Row="2" Grid.Column="0"
|
||||
Margin="0,0,12,0"
|
||||
FontTypography="Body"
|
||||
Text="访问地址" />
|
||||
<ui:TextBlock Grid.Row="2" Grid.Column="1"
|
||||
FontFamily="Consolas"
|
||||
Text="{Binding ExternalAccessState.Address}"
|
||||
TextWrapping="Wrap" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</ui:CardExpander>
|
||||
|
||||
|
||||
<ui:CardExpander Margin="0,0,0,12"
|
||||
ContentPadding="0"
|
||||
|
||||
@@ -26,6 +26,7 @@ using BetterGenshinImpact.Helpers.Http;
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
using BetterGenshinImpact.Service;
|
||||
using BetterGenshinImpact.Service.ExternalAccess;
|
||||
using BetterGenshinImpact.Service.I18n;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
@@ -54,6 +55,12 @@ public partial class CommonSettingsPageViewModel : ViewModel
|
||||
private readonly CustomHtmlMaskService _customHtmlMaskService;
|
||||
private readonly RecognitionTemplateEditorService _recognitionTemplateEditorService;
|
||||
private readonly I18nService _i18nService;
|
||||
|
||||
/// <summary>
|
||||
/// 外部访问令牌生成与校验服务。
|
||||
/// </summary>
|
||||
private readonly ExternalAccessTokenService _externalAccessTokenService;
|
||||
|
||||
private readonly TpConfig _tpConfig = TaskContext.Instance().Config.TpConfig;
|
||||
|
||||
private string _selectedArea = string.Empty;
|
||||
@@ -78,7 +85,8 @@ public partial class CommonSettingsPageViewModel : ViewModel
|
||||
|
||||
public CommonSettingsPageViewModel(IConfigService configService, INavigationService navigationService,
|
||||
NotificationService notificationService, CustomHtmlMaskService customHtmlMaskService,
|
||||
RecognitionTemplateEditorService recognitionTemplateEditorService, I18nService i18nService)
|
||||
RecognitionTemplateEditorService recognitionTemplateEditorService, I18nService i18nService,
|
||||
ExternalAccessState externalAccessState, ExternalAccessTokenService externalAccessTokenService)
|
||||
{
|
||||
Config = configService.Get();
|
||||
_configService = configService;
|
||||
@@ -89,6 +97,15 @@ public partial class CommonSettingsPageViewModel : ViewModel
|
||||
_customHtmlMaskService = customHtmlMaskService;
|
||||
_recognitionTemplateEditorService = recognitionTemplateEditorService;
|
||||
_i18nService = i18nService;
|
||||
ExternalAccessState = externalAccessState;
|
||||
_externalAccessTokenService = externalAccessTokenService;
|
||||
Config.ExternalAccessConfig.PropertyChanged += (_, args) =>
|
||||
{
|
||||
if (args.PropertyName == nameof(ExternalAccessConfig.AccessToken))
|
||||
{
|
||||
OnPropertyChanged(nameof(MaskedExternalAccessToken));
|
||||
}
|
||||
};
|
||||
// 设置页需要可绑定对象,避免把 Dictionary<string, bool> 直接暴露给 XAML 并丢失固定枚举顺序。
|
||||
OverlayMetricItems = new ObservableCollection<OverlayMetricSettingItem>(
|
||||
OverlayMetricItemDefaults.AllItems.Select(item => new OverlayMetricSettingItem(Config.MaskWindowConfig, item, OnRefreshMaskSettings)));
|
||||
@@ -105,6 +122,30 @@ public partial class CommonSettingsPageViewModel : ViewModel
|
||||
public ObservableCollection<string> CountryList { get; } = new();
|
||||
public ObservableCollection<string> Areas { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 外部访问服务的只读运行状态。
|
||||
/// </summary>
|
||||
public ExternalAccessState ExternalAccessState { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 设置页展示的脱敏访问令牌。
|
||||
/// </summary>
|
||||
public string MaskedExternalAccessToken
|
||||
{
|
||||
get
|
||||
{
|
||||
var token = Config.ExternalAccessConfig.AccessToken;
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return "尚未生成";
|
||||
}
|
||||
|
||||
return token.Length <= 8
|
||||
? "********"
|
||||
: $"{token[..4]}…{token[^4..]}";
|
||||
}
|
||||
}
|
||||
|
||||
public ObservableCollection<string> MapPathingTypes { get; } = ["SIFT", "TemplateMatch"];
|
||||
|
||||
[ObservableProperty] private FrozenDictionary<string, string> _languageDict =
|
||||
@@ -157,6 +198,34 @@ public partial class CommonSettingsPageViewModel : ViewModel
|
||||
cookieWin.Show();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将完整外部访问令牌复制到系统剪贴板。
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void CopyExternalAccessToken()
|
||||
{
|
||||
var token = Config.ExternalAccessConfig.AccessToken;
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
ThemedMessageBox.Warning("访问令牌尚未生成。请先启用 HTTP API 或 MCP 后重启,或者点击“重新生成”。");
|
||||
return;
|
||||
}
|
||||
|
||||
Clipboard.SetDataObject(token);
|
||||
ThemedMessageBox.Information("访问令牌已复制到剪贴板。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新生成访问令牌并立即使 HTTP API 与 MCP 使用新令牌。
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private void RegenerateExternalAccessToken()
|
||||
{
|
||||
_externalAccessTokenService.RegenerateToken();
|
||||
OnPropertyChanged(nameof(MaskedExternalAccessToken));
|
||||
ThemedMessageBox.Information("访问令牌已重新生成,旧令牌立即失效。");
|
||||
}
|
||||
|
||||
private void InitializeMiyousheCookie()
|
||||
{
|
||||
OtherConfig.Miyoushe mcfg = TaskContext.Instance().Config.OtherConfig.MiyousheConfig;
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>12.0</LangVersion>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -58,7 +58,6 @@
|
||||
],
|
||||
"uacStrategy": "prefer-admin",
|
||||
"runtimes": [
|
||||
"Microsoft.DotNet.DesktopRuntime.8",
|
||||
"Microsoft.VCRedist.2015+.x64"
|
||||
]
|
||||
}
|
||||
@@ -16,15 +16,15 @@ set "tmpfolder=%~dp0dist\BetterGI"
|
||||
set "archiveFile=BetterGI_v%b%.7z"
|
||||
set "setupFile=BetterGI_Setup_v%b%.exe"
|
||||
|
||||
echo [build app using vs2022]
|
||||
echo [build app using .NET 10 SDK]
|
||||
cd /d %~dp0
|
||||
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
|
||||
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\
|
||||
cd ..\
|
||||
dotnet publish -c Release -p:PublishProfile=FolderProfile
|
||||
|
||||
echo [pack app using 7z]
|
||||
cd /d %~dp0
|
||||
cd /d ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
|
||||
cd /d ..\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\
|
||||
xcopy * "%tmpfolder%" /E /C /I /Y
|
||||
cd /d %~dp0
|
||||
del /f /q %tmpfolder%\*.lib
|
||||
|
||||
@@ -16,15 +16,15 @@ set "tmpfolder=%~dp0dist\BetterGI"
|
||||
set "archiveFile=BetterGI_v%b%.7z"
|
||||
set "setupFile=BetterGI_Setup_v%b%.exe"
|
||||
|
||||
echo [build app using vs2022]
|
||||
echo [build app using .NET 10 SDK]
|
||||
cd /d %~dp0
|
||||
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
|
||||
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\
|
||||
cd ..\
|
||||
dotnet publish -c Release -p:PublishProfile=FolderProfile
|
||||
|
||||
echo [pack app using 7z]
|
||||
cd /d %~dp0
|
||||
cd /d ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
|
||||
cd /d ..\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\
|
||||
xcopy * "%tmpfolder%" /E /C /I /Y
|
||||
cd /d %~dp0
|
||||
del /f /q %tmpfolder%\*.lib
|
||||
|
||||
@@ -16,15 +16,15 @@ set "tmpfolder=%~dp0dist\BetterGI"
|
||||
set "archiveFile=BetterGI_v%b%.7z"
|
||||
set "setupFile=BetterGI_Setup_v%b%.exe"
|
||||
|
||||
echo [build app using vs2022]
|
||||
echo [build app using .NET 10 SDK]
|
||||
cd /d %~dp0
|
||||
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
|
||||
rd /s /q ..\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\
|
||||
cd ..\
|
||||
dotnet publish -c Release -p:PublishProfile=FolderProfile
|
||||
|
||||
echo [pack app using 7z]
|
||||
cd /d %~dp0
|
||||
cd /d ..\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64\
|
||||
cd /d ..\BetterGenshinImpact\bin\x64\Release\net10.0-windows10.0.22621.0\publish\win-x64\
|
||||
xcopy * "%tmpfolder%" /E /C /I /Y
|
||||
cd /d %~dp0
|
||||
del /f /q %tmpfolder%\*.lib
|
||||
|
||||
+11
@@ -31,3 +31,14 @@ _Avoid_:用显示名称区分来自不同仓库的同名脚本。
|
||||
|
||||
**资源版本**:一份确定的脚本资源内容;同一资源的不同版本仍属于同一来源。
|
||||
_Avoid_:把资源版本与仓库身份混用。
|
||||
|
||||
### 外部访问
|
||||
|
||||
**外部访问能力**:BetterGI 明确提供给调用方使用的一项稳定功能,独立于 HTTP、MCP 等传输方式。
|
||||
_Avoid_:把同一功能在不同协议中的入口当作彼此独立的能力。
|
||||
|
||||
**外部访问服务**:BetterGI 向本机调用方提供外部访问能力和实时信息的应用边界。
|
||||
_Avoid_:把它理解为面向局域网或公网的远程管理服务。
|
||||
|
||||
**外部调用方**:通过外部访问服务使用 BetterGI 能力的本机程序、页面或工具。
|
||||
_Avoid_:默认认为调用方属于 BetterGI 主进程内部组件。
|
||||
@@ -13,3 +13,4 @@
|
||||
- [配置持久化链路(AllConfig 保存)优化](config-persistence.md)
|
||||
- [实时触发器生命周期与启停设计](realtime-trigger.md)
|
||||
- [TaskTriggerDispatcher 依赖注入改造设计](task-trigger-dispatcher-di.md)
|
||||
- [BetterGI 外部访问服务设计](external-access.md)
|
||||
@@ -0,0 +1,90 @@
|
||||
# BetterGI 外部访问服务设计
|
||||
|
||||
## 目标与边界
|
||||
|
||||
外部访问服务为本机程序和 BetterGI 内部 WebView2 页面提供统一的 HTTP、WebSocket 与 MCP 入口。首个版本只公开健康状态、版本信息和实时日志,不提供任务启动、停止等业务控制能力。
|
||||
|
||||
服务只属于 Primary 实例,只监听 loopback 地址。HTTP、WebSocket 和 MCP 共用一个端口,默认端口为 `30648`。三项功能默认关闭;全部关闭或当前进程不是 Primary 实例时,不创建监听器。端口被占用或宿主启动失败只会更新设置页状态并写入日志,不影响 WPF 主程序继续运行。
|
||||
|
||||
## 分层
|
||||
|
||||
外部访问实现分为四层:
|
||||
|
||||
1. `IBgiExternalCapabilityService` 定义与传输无关的 BetterGI 能力,并返回共享 DTO。
|
||||
2. HTTP 与 MCP 适配层把各自的请求转换为能力服务调用,不重复实现业务逻辑。
|
||||
3. `ExternalLogHub`、`ExternalLogSink` 和 `ExternalLogWebSocketHandler` 负责日志采集、回放与实时传输。
|
||||
4. `ExternalAccessHost` 管理独立 `WebApplication` 的生命周期、loopback 监听、路由与中间件。
|
||||
|
||||
## 配置与生命周期
|
||||
|
||||
配置位于 `AllConfig.ExternalAccessConfig`,并继续由现有配置服务保存到 `User/config.json`:
|
||||
|
||||
| 配置项 | 默认值 | 生效时机 |
|
||||
|---|---:|---|
|
||||
| `HttpApiEnabled` | `false` | 重启 BetterGI 后 |
|
||||
| `WebSocketEnabled` | `false` | 重启 BetterGI 后 |
|
||||
| `McpEnabled` | `false` | 重启 BetterGI 后 |
|
||||
| `Port` | `30648` | 重启 BetterGI 后 |
|
||||
| `AccessToken` | 空字符串 | 立即生效 |
|
||||
|
||||
HTTP 或 MCP 启用且令牌为空时,服务会生成 256-bit 随机值,转换为无填充的 Base64Url 字符串并立即保存。设置页只显示脱敏值,提供复制和重新生成操作;重新生成后旧令牌立即失效。BetterGI 不向 WebView2 页面自动注入令牌,调用页面必须自行提供。
|
||||
|
||||
## HTTP API
|
||||
|
||||
HTTP JSON 使用 `System.Text.Json` 和 camelCase 属性名。未启用 HTTP 时不映射下列路由,因此返回 `404`。
|
||||
|
||||
| 方法与路径 | 能力 | 返回模型 |
|
||||
|---|---|---|
|
||||
| `GET /api/v1/health` | 查询进程健康状态 | `status`、`instanceRole`、`processId`、`startedAtUtc`、`uptimeSeconds` |
|
||||
| `GET /api/v1/version` | 查询版本 | `product`、`version`、`apiVersion` |
|
||||
|
||||
示例请求:
|
||||
|
||||
```http
|
||||
GET /api/v1/health HTTP/1.1
|
||||
Host: 127.0.0.1:30648
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
## MCP
|
||||
|
||||
MCP 使用 `ModelContextProtocol.AspNetCore` 的无状态 Streamable HTTP 传输,挂载在 `/mcp`,不提供旧式 SSE 端点。未启用 MCP 时不映射该路由。
|
||||
|
||||
| Tool | 共享能力与返回模型 |
|
||||
|---|---|
|
||||
| `get_bgi_health` | 与 `GET /api/v1/health` 相同 |
|
||||
| `get_bgi_version` | 与 `GET /api/v1/version` 相同 |
|
||||
|
||||
## 鉴权、CORS 与本机边界
|
||||
|
||||
- HTTP API 与 MCP 要求 `Authorization: Bearer <token>`,缺失或错误时返回 `401`。
|
||||
- 令牌通过固定时间比较校验,服务日志不得记录令牌。
|
||||
- CORS 允许任意 Origin、Header 和 Method,不允许 Cookie 或 credentials;预检 `OPTIONS` 不要求鉴权。
|
||||
- WebSocket 日志按产品约定不鉴权并允许任意 Origin。设置页会明确提示日志可能泄露路径、脚本名、异常堆栈等信息。
|
||||
- Kestrel 只监听 loopback;额外的 Host 校验只接受 `localhost` 或 loopback IP,降低 DNS rebinding 风险。
|
||||
|
||||
## WebSocket 日志协议
|
||||
|
||||
连接地址为:
|
||||
|
||||
```text
|
||||
ws://127.0.0.1:30648/ws/v1/logs?minimumLevel=Information
|
||||
```
|
||||
|
||||
`minimumLevel` 可省略,默认值为 `Information`,并接受 Serilog 日志级别名称。值无效时握手请求返回 `400`。
|
||||
|
||||
连接建立后先按原顺序回放最近 200 条满足最低级别的日志,再持续推送实时日志。每个客户端拥有容量 512 的独立有界队列;队列满时丢弃最旧消息,不阻塞日志与业务线程,并在下一次发送前推送累计丢弃通知。
|
||||
|
||||
日志消息字段如下:
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `sequence` | 进程内递增序号 |
|
||||
| `timestampUtc` | UTC 时间戳 |
|
||||
| `level` | 日志级别 |
|
||||
| `source` | 日志来源 |
|
||||
| `message` | 已渲染消息 |
|
||||
| `exception` | 异常文本;没有异常时为空 |
|
||||
| `instance` | BetterGI 实例标识 |
|
||||
|
||||
丢弃通知为独立 JSON 消息,包含 `type: "dropped"` 与 `count`。服务支持多个并发客户端,并在客户端断开或应用退出时取消订阅并释放连接资源。
|
||||
@@ -86,7 +86,7 @@ Latest builds: [
|
||||
- [.NET 8 Runtime](https://dotnet.microsoft.com/download/dotnet/8.0) (auto-prompted if missing)
|
||||
- The release package includes the .NET 10 runtime; no separate runtime installation is required.
|
||||
|
||||
**⚠️ Notes:**
|
||||
1. Restart the app after changing window size/resolution/monitor.
|
||||
|
||||
@@ -88,7 +88,7 @@ BetterGIは、コンピュータービジョン技術を活用し、原神をよ
|
||||
**動作要件:**
|
||||
|
||||
- Windows 10/11(64ビット)
|
||||
- [.NET 8 Runtime](https://dotnet.microsoft.com/ja-jp/download/dotnet/8.0)(インストールされていない場合は自動で案内されます)
|
||||
- リリースパッケージには .NET 10 ランタイムが含まれているため、別途インストールする必要はありません。
|
||||
|
||||
**⚠️ 注意:**
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
|
||||
|
||||
你的系统需要满足以下条件:
|
||||
* Windows 10 或更高版本的64位系统
|
||||
* [.NET 8 运行时](https://dotnet.microsoft.com/zh-cn/download/dotnet/latest/runtime) (没有的话,启动程序,系统会提示下载安装)
|
||||
* 发布包已自带 .NET 10 运行时,无需额外安装
|
||||
|
||||
**⚠️注意:**
|
||||
1. 窗口大小变化、切换游戏分辨率、切换显示器的时候请重启本软件。
|
||||
|
||||
@@ -91,7 +91,7 @@ BetterGI · 更好的原神, 一個基於電腦視覺技術,意圖讓原神
|
||||
|
||||
你的系統需要滿足以下條件:
|
||||
* Windows 10 或更高版本的64位系統
|
||||
* [.NET 8 運行時](https://dotnet.microsoft.com/zh-cn/download/dotnet/latest/runtime) (沒有的話,啟動程式,系統會提示下載安裝)
|
||||
* 發佈套件已包含 .NET 10 執行階段,無需另外安裝
|
||||
|
||||
**⚠️注意:**
|
||||
1. 視窗大小變化、切換遊戲解析度、切換顯示器的時候請重啟本軟件。
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Platforms>x64</Platforms>
|
||||
<UseWindowsForms>True</UseWindowsForms>
|
||||
<UseWPF>True</UseWPF>
|
||||
<LangVersion>12.0</LangVersion>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -25,4 +25,4 @@
|
||||
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -1,11 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Platforms>x64</Platforms>
|
||||
<LangVersion>12.0</LangVersion>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<UseWindowsForms>True</UseWindowsForms>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -87,7 +87,7 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
|
||||
|
||||
你的系统需要满足以下条件:
|
||||
* Windows 10 或更高版本的64位系统
|
||||
* [.NET 8 运行时](https://dotnet.microsoft.com/zh-cn/download/dotnet/latest/runtime) (没有的话,启动程序,系统会提示下载安装)
|
||||
* 发布包已自带 .NET 10 运行时,无需额外安装
|
||||
|
||||
**⚠️注意:**
|
||||
1. 窗口大小变化、切换游戏分辨率、切换显示器的时候请重启本软件。
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UseWPF>true</UseWPF>
|
||||
@@ -17,4 +18,4 @@
|
||||
<ProjectReference Include="..\..\BetterGenshinImpact\BetterGenshinImpact.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -1,7 +1,8 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
@@ -11,8 +12,8 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.4"/>
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.2.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="10.0.12"/>
|
||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.0.12"/>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/>
|
||||
<PackageReference Include="xunit" Version="2.5.3"/>
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"/>
|
||||
|
||||
Reference in new issue
Block a user