MainWindow.xaml.cs 14 KB

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