MainWindow.xaml.cs 16 KB

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