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; /// /// 登录窗 /// /// - 账号密码登录:`POST /api/web/auth/login` 拿 user JWT(顺带下发主体列表); /// - **微信扫码登录**:`GET /api/wechat/login` 发码 → 显示二维码(GIF,WPF 可直接显示)→ 长轮询 /// `GET /api/wechat/login?code=&wait=25`,手机确认后直接拿到令牌; /// - 本地已有令牌时,先调 `GET /api/web/me` 验证,还有效就直接跳过登录(窗口一闪而过); /// - 成功后把令牌存到 `%LOCALAPPDATA%\YuncangTrace\session.json`。 /// public partial class LoginWindow : Window { private readonly AppSettings _settings; private readonly Session? _saved; private bool _busy; /// 微信扫码的长轮询取消源(离开扫码面板 / 关窗口时取消) private CancellationTokenSource? _wechatCts; /// 登录成功后的会话(ShowDialog 返回 true 时可用) public Session? Session { get; private set; } /// 登录用户 public ApiUser? User { get; private set; } /// 登录时后端下发的主体列表 public IReadOnlyList Subjects { get; private set; } = Array.Empty(); public LoginWindow(AppSettings settings, Session? saved) { InitializeComponent(); _settings = settings; _saved = saved; ServerBox.Text = settings.ServerBaseUrl; AccountBox.Text = settings.LastAccount; RememberBox.IsChecked = settings.RememberAccount; // 环境由构建决定(Debug = 开发环境,Release = 生产环境),默认地址也来自构建 EnvText.Text = BuildInfo.EnvironmentLabel; ServerBox.ToolTip = $"留空即使用{BuildInfo.EnvironmentLabel}默认地址:{BuildInfo.DefaultServer}\n启动时可用 --server=http://x.x.x.x:7300 临时指定"; Loaded += OnLoaded; Closed += (_, _) => StopWechatPolling(); } private async void OnLoaded(object sender, RoutedEventArgs e) { if (_saved is null) { AccountBox.Focus(); return; } await ResumeAsync(); } /// 本地有令牌:问一下服务端还在不在,有效就直接进主界面 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; var server = AppSettings.Normalize(ServerBox.Text); 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(ServerBox.Text)); 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}"); } } /// 长轮询:确认了就登录;码过期(refreshed)就换一张继续等 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; } /// 拿主体列表;失败不阻塞登录(主界面里还能再拉) private static async Task> LoadSubjectsSafeAsync(ApiClient api, string token) { try { return await api.SubjectsAsync(token); } catch (Exception ex) { AppLog.Write($"读取主体列表失败:{ex.Message}"); return Array.Empty(); } } 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; ServerBox.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; } }