MainWindow.xaml.cs 13 KB

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