MainWindow.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. using System.Collections.Generic;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Input;
  5. using System.Windows.Media;
  6. using System.Windows.Media.Animation;
  7. using System.Windows.Threading;
  8. using NetworkTool.Client.Models;
  9. using NetworkTool.Client.Services;
  10. namespace NetworkTool.Client;
  11. public partial class MainWindow : Window
  12. {
  13. private readonly NetworkAdapterService _networkAdapterService = new();
  14. private readonly PasswordStoreService _passwordStoreService = new();
  15. private readonly DiscoveryService _discoveryService = new();
  16. private readonly ServerApiService _serverApiService = new();
  17. private IReadOnlyList<AdapterInfo> _allAdapters = [];
  18. private IReadOnlyList<AdapterInfo> _adapters = [];
  19. private IReadOnlyList<DiscoveredDevice> _discoveredDevices = [];
  20. private bool _isBusy;
  21. private CancellationTokenSource? _statusMessageCts;
  22. public MainWindow()
  23. {
  24. InitializeComponent();
  25. Loaded += MainWindow_OnLoaded;
  26. }
  27. private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
  28. {
  29. LoadInitialState();
  30. }
  31. private void LoadInitialState()
  32. {
  33. _allAdapters = _networkAdapterService.GetAdapters();
  34. ApplyAdapterFilter();
  35. UpdateButtonStates();
  36. }
  37. private void ApplyAdapterFilter(string? selectedAdapterId = null)
  38. {
  39. _adapters = _allAdapters
  40. .Where(adapter => ShowUsableAdaptersOnlyCheckBox.IsChecked != true || IsUsableAdapter(adapter))
  41. .OrderByDescending(adapter => adapter.RecommendationScore)
  42. .ThenBy(adapter => adapter.Name)
  43. .ToList();
  44. AdapterComboBox.ItemsSource = _adapters;
  45. var selected = selectedAdapterId is null
  46. ? _networkAdapterService.GetRecommendedAdapter(_adapters)
  47. : _adapters.FirstOrDefault(adapter => adapter.Id == selectedAdapterId) ?? _networkAdapterService.GetRecommendedAdapter(_adapters);
  48. if (selected is not null)
  49. {
  50. AdapterComboBox.SelectedItem = selected;
  51. }
  52. else if (_adapters.Count > 0)
  53. {
  54. AdapterComboBox.SelectedIndex = 0;
  55. }
  56. }
  57. private static bool IsUsableAdapter(AdapterInfo adapter)
  58. {
  59. return adapter.HasLink && !string.IsNullOrWhiteSpace(adapter.IPv4Address);
  60. }
  61. private void AdapterComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  62. {
  63. if (AdapterComboBox.SelectedItem is not AdapterInfo adapter)
  64. {
  65. ClearDiscoveredDevices();
  66. SetStatus("请选择一块网卡。", StatusMessageType.Warning, false);
  67. UpdateButtonStates();
  68. return;
  69. }
  70. if (!adapter.HasLink)
  71. {
  72. ClearDiscoveredDevices();
  73. SetStatus("当前网卡未检测到链路,请检查网线连接。", StatusMessageType.Warning, true);
  74. UpdateButtonStates();
  75. return;
  76. }
  77. UpdateButtonStates();
  78. _ = SearchDevicesAsync(adapter);
  79. }
  80. private async void RefreshAdaptersButton_OnClick(object sender, RoutedEventArgs e)
  81. {
  82. SetBusyState(true, "正在刷新本机网卡...");
  83. try
  84. {
  85. RefreshAdapters();
  86. SetStatus("已刷新本机网卡。", StatusMessageType.Success, true);
  87. }
  88. catch (Exception ex)
  89. {
  90. SetStatus($"刷新本机网卡失败:{ex.Message}", StatusMessageType.Error, true);
  91. MessageBox.Show(this, ex.Message, "刷新失败", MessageBoxButton.OK, MessageBoxImage.Error);
  92. }
  93. finally
  94. {
  95. SetBusyState(false);
  96. }
  97. if (AdapterComboBox.SelectedItem is AdapterInfo adapter)
  98. {
  99. await SearchDevicesAsync(adapter);
  100. }
  101. }
  102. private async void SearchDevicesButton_OnClick(object sender, RoutedEventArgs e)
  103. {
  104. if (AdapterComboBox.SelectedItem is AdapterInfo adapter)
  105. {
  106. await SearchDevicesAsync(adapter);
  107. }
  108. else
  109. {
  110. SetStatus("请先选择一块网卡。", StatusMessageType.Warning, true);
  111. }
  112. }
  113. private void ShowUsableAdaptersOnlyCheckBox_OnChanged(object sender, RoutedEventArgs e)
  114. {
  115. if (AdapterComboBox is null || ShowUsableAdaptersOnlyCheckBox is null)
  116. {
  117. return;
  118. }
  119. var selectedAdapterId = (AdapterComboBox.SelectedItem as AdapterInfo)?.Id;
  120. ApplyAdapterFilter(selectedAdapterId);
  121. UpdateButtonStates();
  122. }
  123. private async Task SearchDevicesAsync(AdapterInfo adapter)
  124. {
  125. if (_isBusy)
  126. {
  127. return;
  128. }
  129. if (string.IsNullOrWhiteSpace(adapter.IPv4Address))
  130. {
  131. ClearDiscoveredDevices();
  132. SetStatus("当前网卡没有可用 IPv4,无法搜索设备。", StatusMessageType.Error, true);
  133. return;
  134. }
  135. if (!adapter.HasLink)
  136. {
  137. ClearDiscoveredDevices();
  138. SetStatus("当前网卡未检测到链路,请检查网线连接。", StatusMessageType.Warning, true);
  139. return;
  140. }
  141. SetBusyState(true, "正在搜索设备...");
  142. ClearDiscoveredDevices();
  143. await Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.Render);
  144. try
  145. {
  146. _discoveredDevices = await _discoveryService.DiscoverManyAsync(adapter.IPv4Address);
  147. DiscoveredDevicesListView.ItemsSource = _discoveredDevices;
  148. if (_discoveredDevices.Count == 0)
  149. {
  150. SetStatus("未发现 169.254 开头的设备 IP,请确认网卡、网线、远端服务和维护网段配置。", StatusMessageType.Warning, true);
  151. return;
  152. }
  153. SetStatus($"已发现 {_discoveredDevices.Count} 台设备,请双击 IP 连接。", StatusMessageType.Success, true);
  154. }
  155. catch (Exception ex)
  156. {
  157. SetStatus($"搜索设备失败:{ex.Message}", StatusMessageType.Error, true);
  158. MessageBox.Show(this, ex.Message, "搜索设备失败", MessageBoxButton.OK, MessageBoxImage.Error);
  159. }
  160. finally
  161. {
  162. SetBusyState(false);
  163. }
  164. }
  165. private void SavePasswordForDevice(DiscoveredDevice device, string password)
  166. {
  167. var deviceKey = GetDevicePasswordKey(device);
  168. if (!string.IsNullOrWhiteSpace(deviceKey) && !string.IsNullOrWhiteSpace(password))
  169. {
  170. _passwordStoreService.SavePassword(deviceKey, password);
  171. }
  172. }
  173. private void UpdateButtonStates()
  174. {
  175. var adapter = AdapterComboBox.SelectedItem as AdapterInfo;
  176. var hasAdapter = adapter is not null;
  177. RefreshAdaptersButton.IsEnabled = !_isBusy;
  178. SearchDevicesButton.IsEnabled = !_isBusy && hasAdapter && adapter!.HasLink;
  179. }
  180. private void RefreshAdapters(string? selectedAdapterId = null)
  181. {
  182. _allAdapters = _networkAdapterService.GetAdapters();
  183. ApplyAdapterFilter(selectedAdapterId);
  184. }
  185. private void ClearDiscoveredDevices()
  186. {
  187. _discoveredDevices = [];
  188. DiscoveredDevicesListView.ItemsSource = _discoveredDevices;
  189. }
  190. private async void DiscoveredDevicesListView_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
  191. {
  192. if (!_isBusy && DiscoveredDevicesListView.SelectedItem is DiscoveredDevice device)
  193. {
  194. await ConnectToDeviceAsync(device);
  195. }
  196. }
  197. private void DiscoveredDevicesListView_OnSizeChanged(object sender, SizeChangedEventArgs e)
  198. {
  199. var availableWidth = DiscoveredDevicesListView.ActualWidth - 36;
  200. if (availableWidth <= 0)
  201. {
  202. return;
  203. }
  204. DeviceIpColumn.Width = Math.Max(130, availableWidth * 0.26);
  205. DeviceHostnameColumn.Width = Math.Max(150, availableWidth * 0.30);
  206. DeviceMacColumn.Width = Math.Max(180, availableWidth - DeviceIpColumn.Width - DeviceHostnameColumn.Width);
  207. }
  208. private async Task ConnectToDeviceAsync(DiscoveredDevice device)
  209. {
  210. var deviceKey = GetDevicePasswordKey(device);
  211. var savedPassword = _passwordStoreService.LoadPassword(deviceKey);
  212. var password = string.Empty;
  213. if (!string.IsNullOrWhiteSpace(savedPassword))
  214. {
  215. password = savedPassword;
  216. }
  217. else if (!TryPromptForPassword(device, out savedPassword))
  218. {
  219. return;
  220. }
  221. else
  222. {
  223. password = savedPassword;
  224. }
  225. if (string.IsNullOrWhiteSpace(password))
  226. {
  227. SetStatus("请输入管理密码。", StatusMessageType.Warning, true);
  228. return;
  229. }
  230. var selectedAdapter = AdapterComboBox.SelectedItem as AdapterInfo;
  231. SetBusyState(true, $"正在连接 {device.Lan2Ip}...");
  232. try
  233. {
  234. var baseAddress = $"http://{device.Lan2Ip}:48888";
  235. var result = await _serverApiService.CheckHealthAsync(baseAddress, password, selectedAdapter?.IPv4Address ?? string.Empty);
  236. if (result.Success)
  237. {
  238. SavePasswordForDevice(device, password);
  239. SetStatus("连接成功。", StatusMessageType.Success, true);
  240. OpenDeviceDetailsWindow(baseAddress, selectedAdapter?.IPv4Address ?? string.Empty, password);
  241. return;
  242. }
  243. if (result.StatusCode == 401)
  244. {
  245. SetStatus("管理密码错误,请确认密码是否正确。", StatusMessageType.Error, true);
  246. MessageBox.Show(this, "管理密码校验失败,请确认密码是否正确。", "密码错误", MessageBoxButton.OK, MessageBoxImage.Warning);
  247. return;
  248. }
  249. SetStatus($"设备已发现,但 HTTP 验证失败:{result.Message}", StatusMessageType.Error, true);
  250. }
  251. catch (Exception ex)
  252. {
  253. SetStatus($"连接失败:{ex.Message}", StatusMessageType.Error, true);
  254. MessageBox.Show(this, ex.Message, "连接失败", MessageBoxButton.OK, MessageBoxImage.Error);
  255. }
  256. finally
  257. {
  258. SetBusyState(false);
  259. }
  260. }
  261. private void OpenDeviceDetailsWindow(string baseAddress, string localIPv4, string password)
  262. {
  263. var window = new DeviceDetailsWindow(baseAddress, localIPv4, password)
  264. {
  265. Owner = this,
  266. };
  267. window.ShowDialog();
  268. }
  269. private bool TryPromptForPassword(DiscoveredDevice device, out string password)
  270. {
  271. var label = string.IsNullOrWhiteSpace(device.Mac) ? device.Lan2Ip : device.Mac;
  272. var window = new PasswordPromptWindow(label)
  273. {
  274. Owner = this,
  275. };
  276. if (window.ShowDialog() == true)
  277. {
  278. password = window.Password;
  279. return true;
  280. }
  281. password = string.Empty;
  282. return false;
  283. }
  284. private static string GetDevicePasswordKey(DiscoveredDevice device)
  285. {
  286. if (!string.IsNullOrWhiteSpace(device.Mac))
  287. {
  288. return device.Mac;
  289. }
  290. return device.DeviceId;
  291. }
  292. private void SetStatus(string message, StatusMessageType type, bool addLog)
  293. {
  294. ApplyStatusMessageStyle(type);
  295. StatusTextBlock.Text = message;
  296. StatusMessageBorder.Opacity = 0;
  297. StatusMessageBorder.Visibility = Visibility.Visible;
  298. StatusMessageBorder.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(160)));
  299. _statusMessageCts?.Cancel();
  300. _statusMessageCts = new CancellationTokenSource();
  301. _ = HideStatusMessageAsync(_statusMessageCts.Token);
  302. _ = addLog;
  303. }
  304. private async Task HideStatusMessageAsync(CancellationToken cancellationToken)
  305. {
  306. try
  307. {
  308. await Task.Delay(3000, cancellationToken);
  309. await Dispatcher.InvokeAsync(() =>
  310. {
  311. var animation = new DoubleAnimation(0, TimeSpan.FromMilliseconds(200));
  312. animation.Completed += (_, _) =>
  313. {
  314. if (!cancellationToken.IsCancellationRequested)
  315. {
  316. StatusMessageBorder.Visibility = Visibility.Collapsed;
  317. }
  318. };
  319. StatusMessageBorder.BeginAnimation(OpacityProperty, animation);
  320. });
  321. }
  322. catch (TaskCanceledException)
  323. {
  324. }
  325. }
  326. private void ApplyStatusMessageStyle(StatusMessageType type)
  327. {
  328. var (background, icon) = GetStatusMessageVisuals(type);
  329. StatusIconBorder.Background = background;
  330. StatusIconTextBlock.Text = icon;
  331. StatusTextBlock.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1F2937"));
  332. }
  333. private static (Brush Background, string Icon) GetStatusMessageVisuals(StatusMessageType type)
  334. {
  335. return type switch
  336. {
  337. StatusMessageType.Success => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#27C346")), "✓"),
  338. StatusMessageType.Error => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F76965")), "×"),
  339. StatusMessageType.Warning => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF9626")), "!"),
  340. _ => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#508DF8")), "i"),
  341. };
  342. }
  343. private void SetBusyState(bool isBusy, string? message = null)
  344. {
  345. _isBusy = isBusy;
  346. BusyOverlay.Visibility = isBusy ? Visibility.Visible : Visibility.Collapsed;
  347. BusyMessageTextBlock.Text = string.IsNullOrWhiteSpace(message) ? "正在处理,请稍候..." : message;
  348. AdapterComboBox.IsEnabled = !isBusy;
  349. RefreshAdaptersButton.IsEnabled = !isBusy;
  350. SearchDevicesButton.IsEnabled = !isBusy && AdapterComboBox.SelectedItem is AdapterInfo adapter && adapter.HasLink;
  351. }
  352. }