- LoginWindow:服务器地址 / 账号 / 密码 / 记住账号 → POST /api/web/auth/login 拿 user JWT; 本地已有令牌时先用 GET /api/web/me 验证,有效就跳过登录(窗口一闪而过),无效清掉令牌留下重登。 - TrayIconService(WinForms NotifyIcon,csproj 开 UseWindowsForms): 关窗口 = 隐藏到托盘(本机服务继续跑),双击托盘恢复,右键菜单「打开主界面 / 服务地址 / 版本 / 退出」; 第一次缩到托盘冒一次气泡提示。退出只走托盘「退出」(App 改 ShutdownMode=OnExplicitShutdown)。 - 防多开:SingleInstance(Local\ 命名互斥体 + 命名管道)。第二个实例不抢 17311 端口, 把 yuncang://open?code=… 转给已运行实例(在托盘里也会被弹出来并按 code 查询)后自己退出; 还在登录界面时先把 URL 存起来,登录完成后再查。 - 生命周期调整:本机 HTTP 服务与托盘在 App 里创建(登录前就可用),主窗口只管展示与操作; 日志改成全局 AppLog(窗口没开时的日志也会在窗口打开后补上)。 - 新增 AppSettings / SessionStore:%LOCALAPPDATA%\YuncangTrace\settings.json、session.json (服务器地址默认 http://127.0.0.1:7300;换服务器不会复用旧令牌)。 - 新增 ApiClient(登录 / 校验令牌)、MainWindow「退出登录」(清令牌回登录页)。 - 程序/托盘图标:Assets/app.ico + tools/make-icon.ps1(品牌蓝 + 白色播放三角)。 - csproj 关闭 ImplicitUsings:WPF 与 WinForms 同时开启时隐式命名空间会让 MessageBox / Application / Clipboard 等产生歧义。 ⚠️ 本机没有 .NET SDK,无法编译验证;已做 XAML/XML 良构与括号平衡检查。
182 lines
6.4 KiB
C#
182 lines
6.4 KiB
C#
using System;
|
||
using System.Net.Http;
|
||
using System.Text;
|
||
using System.Text.Json;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>接口调用失败(能拿到后端的 message 就透出去)</summary>
|
||
public sealed class ApiException : Exception
|
||
{
|
||
public ApiException(string message, int statusCode = 0) : base(message)
|
||
{
|
||
StatusCode = statusCode;
|
||
}
|
||
|
||
/// <summary>HTTP 状态码(网络层失败为 0)</summary>
|
||
public int StatusCode { get; }
|
||
}
|
||
|
||
/// <summary>登录用户(后端 `/api/web/auth/login` 返回的 user 子集)</summary>
|
||
public sealed record ApiUser(int Id, string? Username, string? Nickname)
|
||
{
|
||
/// <summary>界面显示名</summary>
|
||
public string DisplayName =>
|
||
!string.IsNullOrWhiteSpace(Nickname) ? Nickname!
|
||
: !string.IsNullOrWhiteSpace(Username) ? Username!
|
||
: $"#{Id}";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 后端接口客户端(只用到登录 + 校验令牌,够桌面端跑起来)
|
||
///
|
||
/// 契约见 frontend/README:成功 `{ ok:true, data }`,失败 `{ ok:false, message }`。
|
||
/// </summary>
|
||
public sealed class ApiClient
|
||
{
|
||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(15) };
|
||
|
||
private static readonly JsonSerializerOptions Json = new()
|
||
{
|
||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||
};
|
||
|
||
public ApiClient(string serverBaseUrl)
|
||
{
|
||
BaseUrl = AppSettings.Normalize(serverBaseUrl);
|
||
}
|
||
|
||
/// <summary>后端根地址(已去掉末尾斜杠)</summary>
|
||
public string BaseUrl { get; }
|
||
|
||
/// <summary>
|
||
/// 账号密码登录(`POST /api/web/auth/login`)
|
||
/// </summary>
|
||
/// <exception cref="ApiException">账号密码错 / 网络不通 / 返回格式不对</exception>
|
||
public async Task<(Session Session, ApiUser User)> LoginAsync(
|
||
string account, string password, CancellationToken ct = default)
|
||
{
|
||
var body = JsonSerializer.Serialize(new { account, password }, Json);
|
||
|
||
using var content = new StringContent(body, Encoding.UTF8, "application/json");
|
||
using var response = await SendAsync(
|
||
() => new HttpRequestMessage(HttpMethod.Post, $"{BaseUrl}/api/web/auth/login") { Content = content },
|
||
"登录", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, message) = ReadEnvelope(response, text);
|
||
if (data is null)
|
||
{
|
||
throw new ApiException(message, (int)response.StatusCode);
|
||
}
|
||
|
||
var token = GetString(data.Value, "token")
|
||
?? throw new ApiException("登录返回里没有令牌");
|
||
var user = ReadUser(data.Value);
|
||
|
||
var session = new Session
|
||
{
|
||
Token = token,
|
||
UserId = user.Id,
|
||
DisplayName = user.DisplayName,
|
||
ServerBaseUrl = BaseUrl,
|
||
};
|
||
return (session, user);
|
||
}
|
||
|
||
/// <summary>校验令牌是否还有效(`GET /api/web/me`),无效返回 null</summary>
|
||
public async Task<ApiUser?> MeAsync(string token, CancellationToken ct = default)
|
||
{
|
||
try
|
||
{
|
||
using var response = await SendAsync(() =>
|
||
{
|
||
var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseUrl}/api/web/me");
|
||
request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {token}");
|
||
return request;
|
||
}, "校验登录态", ct).ConfigureAwait(false);
|
||
|
||
var text = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||
var (data, _) = ReadEnvelope(response, text);
|
||
return data is null ? null : ReadUser(data.Value);
|
||
}
|
||
catch (ApiException)
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>发请求:连不上时翻成「无法连接服务器」这种能看懂的提示</summary>
|
||
private async Task<HttpResponseMessage> SendAsync(
|
||
Func<HttpRequestMessage> createRequest, string action, CancellationToken ct)
|
||
{
|
||
try
|
||
{
|
||
using var request = createRequest();
|
||
return await Http.SendAsync(request, ct).ConfigureAwait(false);
|
||
}
|
||
catch (TaskCanceledException)
|
||
{
|
||
throw new ApiException("连接服务器超时,请检查服务器地址或网络");
|
||
}
|
||
catch (HttpRequestException ex)
|
||
{
|
||
throw new ApiException($"无法连接服务器({BaseUrl}):{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 解析 `{ ok, data, message }`:成功返回 data(JSON 片段),失败返回 message
|
||
/// </summary>
|
||
private static (JsonElement? Data, string Message) ReadEnvelope(HttpResponseMessage response, string text)
|
||
{
|
||
JsonDocument document;
|
||
try
|
||
{
|
||
document = JsonDocument.Parse(string.IsNullOrWhiteSpace(text) ? "{}" : text);
|
||
}
|
||
catch (JsonException)
|
||
{
|
||
return (null, $"服务器返回了非 JSON 内容(HTTP {(int)response.StatusCode})");
|
||
}
|
||
|
||
using (document)
|
||
{
|
||
var root = document.RootElement;
|
||
|
||
var ok = root.TryGetProperty("ok", out var okElement)
|
||
&& okElement.ValueKind == JsonValueKind.True;
|
||
|
||
if (ok && root.TryGetProperty("data", out var dataElement))
|
||
{
|
||
// 复制一份出来(document 释放后就失效了)
|
||
return (dataElement.Clone(), "ok");
|
||
}
|
||
|
||
var message = GetString(root, "message")
|
||
?? $"请求失败(HTTP {(int)response.StatusCode})";
|
||
return (null, message);
|
||
}
|
||
}
|
||
|
||
private static ApiUser ReadUser(JsonElement data)
|
||
{
|
||
// 登录接口是 { token, user },/api/web/me 是直接一个 user
|
||
var userElement = data.TryGetProperty("user", out var nested) ? nested : data;
|
||
|
||
var id = userElement.TryGetProperty("id", out var idElement) && idElement.TryGetInt32(out var value) ? value : 0;
|
||
var username = GetString(userElement, "username");
|
||
var nickname = GetString(userElement, "nickname");
|
||
return new ApiUser(id, username, nickname);
|
||
}
|
||
|
||
private static string? GetString(JsonElement element, string property)
|
||
{
|
||
return element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String
|
||
? value.GetString()
|
||
: null;
|
||
}
|
||
}
|