================================================================================
ClassNotify Turn 117 Client UI Source Bundle
Commitment: Zero-Scroll, Strict Two-Page Lifecycle, Space-Separated Pairing Code
Generated: 2026-10-02 00:41:01
================================================================================
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/DeviceStatusWindow.xaml.cs
--------------------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using ClassNotify.Client.Services;
using ClassNotify.Client.ViewModels;
using ClassNotify.Client.Views;
using ClassNotify.Shared.Enums;
using ClassNotify.Shared.Models;
namespace ClassNotify.Client
{
public partial class DeviceStatusWindow : Window
{
private readonly DeviceStatusViewModel _viewModel;
private readonly IpcClient? _ipcClient;
private readonly FirstPairingView _firstPairingView;
private readonly RunningDeviceView _runningDeviceView;
private long _lastStateRevision = 0;
private bool _allowRealExit = false;
public DeviceStatusViewModel ViewModel => _viewModel;
public DeviceStatusWindow(ClientStateSnapshotDto state, Action onReactivateRequested, IpcClient? ipcClient = null)
{
InitializeComponent();
_ipcClient = ipcClient;
_viewModel = new DeviceStatusViewModel();
this.DataContext = _viewModel;
_firstPairingView = new FirstPairingView();
_firstPairingView.Initialize(_ipcClient);
_runningDeviceView = new RunningDeviceView();
_runningDeviceView.Initialize(_ipcClient);
// Connect view switching to ViewModel.Page
UpdateContentPage();
_viewModel.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(DeviceStatusViewModel.Page))
{
Dispatcher.InvokeAsync(UpdateContentPage);
}
};
ApplyState(state);
if (_ipcClient != null)
{
_ipcClient.OnEnterPairingMode += OnRemoteEnterPairingMode;
this.Closed += (s, e) =>
{
_ipcClient.OnEnterPairingMode -= OnRemoteEnterPairingMode;
_viewModel.StopCountdownTimer();
};
}
else
{
this.Closed += (s, e) =>
{
_viewModel.StopCountdownTimer();
};
}
this.Loaded += async (s, e) =>
{
await InitialFetchPairingCodeAsync();
};
}
private void UpdateContentPage()
{
MainContent.Content = _viewModel.Page == DevicePage.FirstPairing
? _firstPairingView
: _runningDeviceView;
}
public void ApplyState(ClientStateSnapshotDto state)
{
if (state == null) return;
// Monotonic state revision guard
if (state.StateRevision > 0 && state.StateRevision < _lastStateRevision)
{
return;
}
_lastStateRevision = Math.Max(_lastStateRevision, state.StateRevision);
_viewModel.ApplySnapshot(state);
}
private async Task InitialFetchPairingCodeAsync()
{
if (_ipcClient == null) return;
try
{
var purpose = _viewModel.Page == DevicePage.FirstPairing
? PairingPurpose.InitialDeviceBinding
: PairingPurpose.AddTeacher;
var session = await _ipcClient.RequestPairingSessionAsync(purpose);
if (session != null)
{
_viewModel.ApplyPairingSession(session);
}
}
catch (Exception ex)
{
App.LogClient($"InitialFetchPairingCode error: {ex.Message}");
}
}
private void OnRemoteEnterPairingMode(string code, int ttl)
{
Dispatcher.Invoke(() =>
{
_viewModel.UpdatePairingCode(code, ttl);
});
}
private void OnTitleBarMouseDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
try
{
this.DragMove();
}
catch { }
}
}
private void OnMinimizeClick(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void OnHideToBackgroundClick(object sender, RoutedEventArgs e)
{
this.Hide();
this.ShowInTaskbar = false;
}
public void ForceClose()
{
_allowRealExit = true;
this.Close();
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (!_allowRealExit)
{
e.Cancel = true;
this.Hide();
this.ShowInTaskbar = false;
return;
}
base.OnClosing(e);
}
}
}
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/Views/FirstPairingView.xaml
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/Views/FirstPairingView.xaml.cs
--------------------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using ClassNotify.Client.Services;
using ClassNotify.Client.ViewModels;
using ClassNotify.Shared.Enums;
using ClassNotify.Shared.Models;
namespace ClassNotify.Client.Views
{
public partial class FirstPairingView : UserControl
{
private IpcClient? _ipcClient;
public DeviceStatusViewModel? ViewModel => DataContext as DeviceStatusViewModel;
public FirstPairingView()
{
InitializeComponent();
}
public void Initialize(IpcClient? ipcClient)
{
_ipcClient = ipcClient;
}
private async void OnRefreshCodeClick(object sender, RoutedEventArgs e)
{
if (ViewModel == null || _ipcClient == null || ViewModel.IsRequestingCode) return;
ViewModel.IsRequestingCode = true;
try
{
var session = await _ipcClient.RequestPairingSessionAsync(PairingPurpose.InitialDeviceBinding);
if (session != null)
{
ViewModel.ApplyPairingSession(session);
}
}
catch (Exception ex)
{
App.LogClient($"FirstPairingView refresh code error: {ex.Message}");
}
finally
{
ViewModel.IsRequestingCode = false;
}
}
}
}
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/Views/RunningDeviceView.xaml
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/Views/RunningDeviceView.xaml.cs
--------------------------------------------------------------------------------
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using ClassNotify.Client.Services;
using ClassNotify.Client.ViewModels;
using ClassNotify.Shared.Enums;
using ClassNotify.Shared.Models;
namespace ClassNotify.Client.Views
{
public partial class RunningDeviceView : UserControl
{
private IpcClient? _ipcClient;
public DeviceStatusViewModel? ViewModel => DataContext as DeviceStatusViewModel;
public RunningDeviceView()
{
InitializeComponent();
}
public void Initialize(IpcClient? ipcClient)
{
_ipcClient = ipcClient;
}
private async void OnRefreshCodeClick(object sender, RoutedEventArgs e)
{
if (ViewModel == null || _ipcClient == null || ViewModel.IsRequestingCode) return;
ViewModel.IsRequestingCode = true;
try
{
var session = await _ipcClient.RequestPairingSessionAsync(PairingPurpose.AddTeacher);
if (session != null)
{
ViewModel.ApplyPairingSession(session);
}
}
catch (Exception ex)
{
App.LogClient($"RunningDeviceView refresh code error: {ex.Message}");
}
finally
{
ViewModel.IsRequestingCode = false;
}
}
}
}
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/ViewModels/DeviceStatusViewModel.cs
--------------------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using ClassNotify.Client.Services;
using ClassNotify.Shared.Enums;
using ClassNotify.Shared.Models;
using ClassNotify.Shared.Utils;
namespace ClassNotify.Client.ViewModels
{
public enum DevicePage
{
FirstPairing, // WAITING_FOR_FIRST_BIND (首次引导态)
Running // RUNNING (日常运行与维护态)
}
///
/// Turn 117 教室大屏终端最终权威 ViewModel
/// 严格遵循单向事实驱动:
/// HasAnyTeacherBinding == false => FirstPairing
/// HasAnyTeacherBinding == true => Running
///
public sealed class DeviceStatusViewModel : INotifyPropertyChanged
{
private DevicePage _page = DevicePage.FirstPairing;
private string _rawPairingCode = string.Empty;
private string _pairingCodeDisplay = "等待获取";
private string _countdownText = "有效时间:10 分钟";
private DateTimeOffset _pairingExpiresAt = DateTimeOffset.MinValue;
private DispatcherTimer? _countdownTimer;
private BitmapImage? _qrImage;
private ServerReachabilityState _reachabilityState = ServerReachabilityState.Checking;
private bool _isRequestingCode = false;
public event PropertyChangedEventHandler? PropertyChanged;
public DevicePage Page
{
get => _page;
private set
{
if (_page != value)
{
_page = value;
OnPropertyChanged();
OnPropertyChanged(nameof(IsFirstPairing));
OnPropertyChanged(nameof(IsRunning));
OnPropertyChanged(nameof(HeaderReachabilityText));
OnPropertyChanged(nameof(FooterTipText));
}
}
}
public bool IsFirstPairing => Page == DevicePage.FirstPairing;
public bool IsRunning => Page == DevicePage.Running;
public string PairingCodeDisplay
{
get => _pairingCodeDisplay;
private set
{
if (_pairingCodeDisplay != value)
{
_pairingCodeDisplay = value;
OnPropertyChanged();
}
}
}
public string CountdownText
{
get => _countdownText;
private set
{
if (_countdownText != value)
{
_countdownText = value;
OnPropertyChanged();
}
}
}
public BitmapImage? QrImage
{
get => _qrImage;
private set
{
if (_qrImage != value)
{
_qrImage = value;
OnPropertyChanged();
}
}
}
public ServerReachabilityState ReachabilityState
{
get => _reachabilityState;
set
{
if (_reachabilityState != value)
{
_reachabilityState = value;
OnPropertyChanged();
OnPropertyChanged(nameof(HeaderReachabilityText));
OnPropertyChanged(nameof(HeaderReachabilityBrush));
OnPropertyChanged(nameof(HeaderReachabilityBackground));
OnPropertyChanged(nameof(HeaderReachabilityBorder));
}
}
}
public string HeaderReachabilityText
{
get
{
switch (ReachabilityState)
{
case ServerReachabilityState.Reachable:
return Page == DevicePage.FirstPairing ? "● 已连接云服务" : "● 云服务连接正常";
case ServerReachabilityState.Checking:
return "◌ 正在检测云服务";
case ServerReachabilityState.Unreachable:
default:
return "● 暂时无法连接云服务";
}
}
}
public Brush HeaderReachabilityBrush
{
get
{
switch (ReachabilityState)
{
case ServerReachabilityState.Reachable:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#16A34A"));
case ServerReachabilityState.Checking:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#D97706"));
case ServerReachabilityState.Unreachable:
default:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626"));
}
}
}
public Brush HeaderReachabilityBackground
{
get
{
switch (ReachabilityState)
{
case ServerReachabilityState.Reachable:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DCFCE7"));
case ServerReachabilityState.Checking:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FEF3C7"));
case ServerReachabilityState.Unreachable:
default:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FEE2E2"));
}
}
}
public Brush HeaderReachabilityBorder
{
get
{
switch (ReachabilityState)
{
case ServerReachabilityState.Reachable:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#86EFAC"));
case ServerReachabilityState.Checking:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FDE68A"));
case ServerReachabilityState.Unreachable:
default:
return new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FCA5A5"));
}
}
}
public string FooterTipText
{
get
{
return Page == DevicePage.FirstPairing
? "这是教室公共大屏终端,等待教师绑定后接收课堂通知"
: "物理终端已就绪 · 任课教师可随时查看配对码,在电脑端后台完成绑定";
}
}
public bool IsRequestingCode
{
get => _isRequestingCode;
set
{
if (_isRequestingCode != value)
{
_isRequestingCode = value;
OnPropertyChanged();
OnPropertyChanged(nameof(CanRefreshCode));
}
}
}
public bool CanRefreshCode => !_isRequestingCode;
public DeviceStatusViewModel()
{
// Generate QR Code bitmap for teacher registration URL
QrImage = QrCodeImageService.GenerateQrBitmap("https://classnotify.paradise.eu.org/register", pixelsPerModule: 16);
// Connect to ServerReachabilityService
ReachabilityState = ServerReachabilityService.Instance.CurrentState;
ServerReachabilityService.Instance.ReachabilityChanged += state =>
{
App.Current.Dispatcher.InvokeAsync(() =>
{
ReachabilityState = state;
});
};
}
///
/// 权威状态快照映射:只按 HasAnyTeacherBinding 决定页面
///
public void ApplySnapshot(ClientStateSnapshotDto state)
{
if (state == null) return;
// Turn 117 Invariant: HasAnyTeacherBinding determines Page A vs Page B
bool hasTeacher = state.BoundTeacherCount > 0 || state.BindingState == DeviceBindingState.Bound;
Page = hasTeacher ? DevicePage.Running : DevicePage.FirstPairing;
}
public void ApplyPairingSession(PairingSessionDto session)
{
if (session == null) return;
if (session.State == PairingSessionState.Active && !string.IsNullOrWhiteSpace(session.Code))
{
_rawPairingCode = session.Code;
PairingCodeDisplay = PairingCodeFormatter.FormatPairingCode(session.Code);
_pairingExpiresAt = session.ExpiresAt;
StartCountdownTimer();
}
else
{
PairingCodeDisplay = "等待获取";
CountdownText = "获取配对码失败,请重试";
}
}
public void UpdatePairingCode(string rawCode, int ttlSeconds = 600)
{
_rawPairingCode = rawCode;
PairingCodeDisplay = PairingCodeFormatter.FormatPairingCode(rawCode);
_pairingExpiresAt = DateTimeOffset.UtcNow.AddSeconds(ttlSeconds > 0 ? ttlSeconds : 600);
StartCountdownTimer();
}
private void StartCountdownTimer()
{
StopCountdownTimer();
UpdateCountdown();
_countdownTimer = new DispatcherTimer
{
Interval = TimeSpan.FromSeconds(1)
};
_countdownTimer.Tick += (s, e) => UpdateCountdown();
_countdownTimer.Start();
}
private void UpdateCountdown()
{
var remaining = (int)(_pairingExpiresAt - DateTimeOffset.UtcNow).TotalSeconds;
if (remaining <= 0)
{
StopCountdownTimer();
CountdownText = "有效时间:已过期,请刷新";
}
else
{
int m = remaining / 60;
int s = remaining % 60;
CountdownText = $"有效时间:{m:D2}:{s:D2}";
}
}
public void StopCountdownTimer()
{
if (_countdownTimer != null)
{
_countdownTimer.Stop();
_countdownTimer = null;
}
}
private void OnPropertyChanged([CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
--------------------------------------------------------------------------------
FILE: src/Shared/ClassNotify.Shared/Utils/PairingCodeFormatter.cs
--------------------------------------------------------------------------------
using System;
using System.Text.RegularExpressions;
namespace ClassNotify.Shared.Utils;
///
/// 教室大屏配对码权威格式化工具
/// 核心红线约束:
/// 1. 任何时候配对码严禁包含横杠 '-'
/// 2. 配对码严禁分为明显的两组4个字符,必须严格等间距排列 (例如 '5 8 2 9 1 0 3 4')
/// 3. 占位状态严禁出现 '--------',应显示为空白或提示文本
///
public static class PairingCodeFormatter
{
public const string DefaultPlaceholder = "等待获取";
///
/// 标准化配对码(移除所有空格、横杠、换行符)
///
public static string Normalize(string? input)
{
if (string.IsNullOrWhiteSpace(input)) return string.Empty;
return input.Replace("-", "").Replace(" ", "").Trim();
}
///
/// 校验配对码是否为合规的 8 位纯数字
///
public static bool IsValid(string? input)
{
var clean = Normalize(input);
return clean.Length == 8 && Regex.IsMatch(clean, @"^\d{8}$");
}
///
/// 转换为大屏与终端 4+4 空格格式化的字符串(严格无横杠,例如 '5829 1034')
///
public static string FormatPairingCode(string? code, string placeholder = DefaultPlaceholder)
{
if (string.IsNullOrWhiteSpace(code)) return placeholder;
var digits = new string(System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Where(code, char.IsDigit)));
if (digits.Length == 8)
return $"{digits[..4]} {digits[4..]}";
return digits.Length > 0 ? digits : placeholder;
}
///
/// 转换为大屏与终端显示的字符串
///
public static string FormatEqualSpacing(string? code, string placeholder = DefaultPlaceholder)
{
return FormatPairingCode(code, placeholder);
}
}
--------------------------------------------------------------------------------
FILE: src/Windows/ClassNotify.Client/Services/ServerReachabilityService.cs
--------------------------------------------------------------------------------
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace ClassNotify.Client.Services
{
public enum ServerReachabilityState
{
Checking,
Reachable,
Unreachable
}
///
/// Turn 117 独立云服务 HTTPS 连通性探测服务
/// 遵循规范:仅探测服务端 HTTPS 可达性,绝不耦合 SignalR/授权状态/本地证书
///
public sealed class ServerReachabilityService : IDisposable
{
private static readonly Lazy _instance =
new Lazy(() => new ServerReachabilityService());
public static ServerReachabilityService Instance => _instance.Value;
private readonly HttpClient _httpClient;
private readonly Timer _timer;
private int _consecutiveFailures = 0;
private bool _isDisposed = false;
private string _targetHealthUrl = "https://classnotify.paradise.eu.org/api/health";
public ServerReachabilityState CurrentState { get; private set; } = ServerReachabilityState.Checking;
public event Action? ReachabilityChanged;
private ServerReachabilityService()
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(5)
};
// Start immediately, then every 20 seconds
_timer = new Timer(OnTimerTick, null, 0, 20000);
}
public void ConfigureServerUrl(string? baseUrl)
{
if (!string.IsNullOrWhiteSpace(baseUrl))
{
var uri = new Uri(baseUrl);
_targetHealthUrl = $"{uri.Scheme}://{uri.Authority}/api/health";
}
}
private async void OnTimerTick(object? state)
{
if (_isDisposed) return;
await CheckReachabilityAsync();
}
public async Task CheckReachabilityAsync()
{
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var response = await _httpClient.GetAsync(_targetHealthUrl, HttpCompletionOption.ResponseHeadersRead, cts.Token);
if (response.IsSuccessStatusCode)
{
_consecutiveFailures = 0;
SetState(ServerReachabilityState.Reachable);
return;
}
}
catch
{
// Network or HTTP error
}
_consecutiveFailures++;
if (_consecutiveFailures >= 3)
{
SetState(ServerReachabilityState.Unreachable);
}
else if (CurrentState == ServerReachabilityState.Checking)
{
// Still checking during startup retries
}
}
private void SetState(ServerReachabilityState newState)
{
if (CurrentState == newState) return;
CurrentState = newState;
ReachabilityChanged?.Invoke(newState);
}
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
_timer.Dispose();
_httpClient.Dispose();
}
}
}