packServer/desktop/LoginWindow.xaml.cs
liufumingren 228723e0c3 设备端扫码上报 + 桌面端/Android 正式包发布脚手架
AndroidStation(原中控改造为纯设备端)
- 只做三件事:UDP 48899 被桌面端发现、TCP 8087 推送 USB 扫码结果、离线语音播报
- 扫码不再经过 UI:去掉逐键重绘,50ms 自动提交,同一码重复扫码也一律上报
- 离线语音种子(数字/字母/“开始打包”/欢迎语)随包安装,MediaPlayer 播放,启动把音量拉满
- 启动播报「欢迎使用溯源系统,初始化已经完成,扫码即可开始打包」
- 移除 Device Owner / 设备管理员 / lock task / 网络与 IP 设置等非普通应用能力(仅保留开机自启)
- 正式签名 keystore + release 签名配置,versionName/versionCode 可由打包脚本覆盖

发布脚手架
- backend/android_client:Android 正式包构建(build.ps1 + package.config.json)
- backend/scripts/deploy/publish-android.cjs + npm run android:build / android:publish
- 桌面端安装包改为 download/desktop,Android 为 download/android_client;
  version.json 仍走 /download/version.json(老客户端写死),新增 /download/android_client/version.json
- 谷歌插件随桌面端 MSI 安装到 <安装目录>\extension,工具菜单新增「复制谷歌插件地址」
- git-safety-check 增加仓库级禁区(keystore.properties / *.jks / local.properties)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-21 05:53:27 +08:00

368 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using YuncangTrace.LocalService.Services;
namespace YuncangTrace.LocalService;
/// <summary>
/// 登录窗
///
/// - 账号密码登录:`POST /api/web/auth/login` 拿 user JWT(顺带下发主体列表);
/// - **微信扫码登录**:`GET /api/wechat/login` 发码 → 显示二维码(GIF,WPF 可直接显示)→ 长轮询
/// `GET /api/wechat/login?code=&amp;wait=25`,手机确认后直接拿到令牌;
/// - 本地已有令牌时,先调 `GET /api/web/me` 验证,还有效就直接跳过登录(窗口一闪而过);
/// - 成功后把令牌存到 `%LOCALAPPDATA%\YuncangTrace\session.json`。
/// </summary>
public partial class LoginWindow : Window
{
private readonly AppSettings _settings;
private readonly Session? _saved;
private bool _busy;
/// <summary>微信扫码的长轮询取消源(离开扫码面板 / 关窗口时取消)</summary>
private CancellationTokenSource? _wechatCts;
/// <summary>登录成功后的会话(ShowDialog 返回 true 时可用)</summary>
public Session? Session { get; private set; }
/// <summary>登录用户</summary>
public ApiUser? User { get; private set; }
/// <summary>登录时后端下发的主体列表</summary>
public IReadOnlyList<ApiSubject> Subjects { get; private set; } = Array.Empty<ApiSubject>();
public LoginWindow(AppSettings settings, Session? saved)
{
InitializeComponent();
_settings = settings;
_saved = saved;
AccountBox.Text = settings.LastAccount;
RememberBox.IsChecked = settings.RememberAccount;
Loaded += OnLoaded;
Closed += (_, _) => StopWechatPolling();
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
if (_saved is null)
{
AccountBox.Focus();
return;
}
await ResumeAsync();
}
/// <summary>本地有令牌:问一下服务端还在不在,有效就直接进主界面</summary>
private async Task ResumeAsync()
{
SetBusy(true, "正在恢复登录…");
try
{
var api = new ApiClient(_saved!.ServerBaseUrl);
var me = await api.MeAsync(_saved.Token);
if (me is null)
{
AppLog.Write("本地登录态已失效,请重新登录");
SessionStore.Clear();
SetBusy(false);
AccountBox.Focus();
return;
}
Session = _saved;
User = me;
Subjects = await LoadSubjectsSafeAsync(api, _saved.Token);
AppLog.Write($"已恢复登录:{me.DisplayName}(主体 {Subjects.Count} 个)");
DialogResult = true;
}
catch (Exception ex)
{
AppLog.Write($"恢复登录失败:{ex.Message}");
SetBusy(false);
ShowError($"恢复登录失败:{ex.Message}");
}
}
// ---------------- 账号密码登录 ----------------
private void Login_Click(object sender, RoutedEventArgs e) => _ = DoLoginAsync();
private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter) _ = DoLoginAsync();
}
private async Task DoLoginAsync()
{
if (_busy) return;
// 服务地址是内部实现(构建时注入的默认值 / 启动参数 --server 覆盖),不在界面上暴露
var server = AppSettings.Normalize(_settings.ServerBaseUrl);
var account = AccountBox.Text.Trim();
var password = PasswordBox.Password;
if (account.Length == 0)
{
ShowError("请填写账号");
AccountBox.Focus();
return;
}
if (password.Length == 0)
{
ShowError("请填写密码");
PasswordBox.Focus();
return;
}
ClearError();
SetBusy(true, "正在登录…");
try
{
var api = new ApiClient(server);
var result = await api.LoginAsync(account, password);
result.Session.DisplayName = result.User.DisplayName;
SessionStore.Save(result.Session);
_settings.ServerBaseUrl = server;
_settings.RememberAccount = RememberBox.IsChecked == true;
_settings.LastAccount = _settings.RememberAccount ? account : string.Empty;
_settings.Save();
Session = result.Session;
User = result.User;
Subjects = result.Subjects;
AppLog.Write($"登录成功:{result.User.DisplayName}({server},主体 {Subjects.Count} 个)");
DialogResult = true;
}
catch (ApiException ex)
{
ShowError(ex.Message);
}
catch (Exception ex)
{
ShowError($"登录失败:{ex.Message}");
}
finally
{
SetBusy(false);
}
}
// ---------------- 微信扫码登录 ----------------
private void Wechat_Click(object sender, RoutedEventArgs e) => _ = EnterWechatAsync();
private void WechatRefresh_Click(object sender, RoutedEventArgs e) => _ = StartWechatTicketAsync();
private void Back_Click(object sender, RoutedEventArgs e)
{
StopWechatPolling();
WechatPanel.Visibility = Visibility.Collapsed;
AccountPanel.Visibility = Visibility.Visible;
ClearError();
AccountBox.Focus();
}
private async Task EnterWechatAsync()
{
ClearError();
AccountPanel.Visibility = Visibility.Collapsed;
WechatPanel.Visibility = Visibility.Visible;
await StartWechatTicketAsync();
}
private async Task StartWechatTicketAsync()
{
StopWechatPolling();
var cts = new CancellationTokenSource();
_wechatCts = cts;
QrImage.Source = null;
QrPlaceholder.Visibility = Visibility.Visible;
QrPlaceholder.Text = "正在生成二维码…";
QrTip.Text = "请用手机扫码,确认后自动登录";
try
{
var api = new ApiClient(AppSettings.Normalize(_settings.ServerBaseUrl));
var ticket = await api.StartWechatLoginAsync(cts.Token);
// WPF 不能渲染 SVG,这里拿同一张二维码的 GIF
var bytes = await api.GetImageAsync(
$"/api/wechat/qrcode.gif?code={Uri.EscapeDataString(ticket.Code)}", cts.Token);
QrImage.Source = ToBitmap(bytes);
QrPlaceholder.Visibility = Visibility.Collapsed;
QrTip.Text = "请用手机微信扫码,确认后自动登录";
AppLog.Write($"[wechat] 已生成登录二维码:{ticket.Code}");
_ = PollWechatAsync(api, ticket.Code, cts.Token);
}
catch (OperationCanceledException)
{
// 切回账号登录,忽略
}
catch (Exception ex)
{
QrPlaceholder.Text = "二维码生成失败";
ShowError($"微信登录不可用:{ex.Message}");
AppLog.Write($"[wechat] 生成二维码失败:{ex.Message}");
}
}
/// <summary>长轮询:确认了就登录;码过期(refreshed)就换一张继续等</summary>
private async Task PollWechatAsync(ApiClient api, string code, CancellationToken ct)
{
var current = code;
while (!ct.IsCancellationRequested)
{
try
{
var result = await api.PollWechatLoginAsync(current, 25, ct);
if (result.Status == "confirmed" && result.Session is not null)
{
var session = result.Session;
session.DisplayName = result.User?.DisplayName ?? session.DisplayName;
SessionStore.Save(session);
_settings.ServerBaseUrl = api.BaseUrl;
_settings.Save();
Session = session;
User = result.User;
Subjects = await LoadSubjectsSafeAsync(api, session.Token);
AppLog.Write($"[wechat] 扫码登录成功:{session.DisplayName}(主体 {Subjects.Count} 个)");
if (!ct.IsCancellationRequested) DialogResult = true;
return;
}
if (result.Status == "refreshed" && !string.IsNullOrWhiteSpace(result.Code))
{
current = result.Code!;
try
{
var bytes = await api.GetImageAsync(
$"/api/wechat/qrcode.gif?code={Uri.EscapeDataString(current)}", ct);
QrImage.Source = ToBitmap(bytes);
QrTip.Text = "二维码已刷新,请重新扫码";
}
catch
{
QrTip.Text = "二维码刷新失败,可点「刷新二维码」重试";
}
}
}
catch (OperationCanceledException)
{
return;
}
catch (Exception ex)
{
QrTip.Text = $"连接中断,正在重试…({ex.Message})";
try
{
await Task.Delay(1200, ct);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
private void StopWechatPolling()
{
try
{
_wechatCts?.Cancel();
}
catch
{
// 忽略
}
_wechatCts = null;
}
/// <summary>拿主体列表;失败不阻塞登录(主界面里还能再拉)</summary>
private static async Task<IReadOnlyList<ApiSubject>> LoadSubjectsSafeAsync(ApiClient api, string token)
{
try
{
return await api.SubjectsAsync(token);
}
catch (Exception ex)
{
AppLog.Write($"读取主体列表失败:{ex.Message}");
return Array.Empty<ApiSubject>();
}
}
private static BitmapImage? ToBitmap(byte[] bytes)
{
if (bytes.Length == 0) return null;
using var stream = new MemoryStream(bytes);
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
image.Freeze();
return image;
}
// ---------------- 状态 ----------------
private void SetBusy(bool busy, string? text = null)
{
_busy = busy;
LoginButton.IsEnabled = !busy;
WechatButton.IsEnabled = !busy;
ExitButton.IsEnabled = !busy;
AccountBox.IsEnabled = !busy;
PasswordBox.IsEnabled = !busy;
RememberBox.IsEnabled = !busy;
LoginButton.Content = busy ? (text ?? "请稍候…") : "登录";
}
private void ShowError(string message)
{
ErrorText.Text = message;
ErrorText.Visibility = Visibility.Visible;
}
private void ClearError()
{
ErrorText.Text = string.Empty;
ErrorText.Visibility = Visibility.Collapsed;
}
private void Exit_Click(object sender, RoutedEventArgs e)
{
StopWechatPolling();
DialogResult = false;
}
}