MainWindow.xaml.cs 17 KB

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