MainWindow.xaml.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. using System.Collections.Generic;
  2. using System.Globalization;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using QuickIP.Client.Models;
  6. using QuickIP.Client.Services;
  7. namespace QuickIP.Client;
  8. public partial class MainWindow : Window
  9. {
  10. private readonly NetworkAdapterService _networkAdapterService = new();
  11. private readonly PasswordStoreService _passwordStoreService = new();
  12. private readonly NetworkConfigurationService _networkConfigurationService = new();
  13. private readonly DiscoveryService _discoveryService = new();
  14. private readonly AgentApiService _agentApiService = new();
  15. private readonly AdminPrivilegeService _adminPrivilegeService = new();
  16. private IReadOnlyList<AdapterInfo> _adapters = [];
  17. private string _connectedBaseAddress = string.Empty;
  18. private string _connectedLocalIPv4 = string.Empty;
  19. private bool _configValidated;
  20. private bool _suppressConfigChangeHandling;
  21. private bool _isShowingPassword;
  22. private bool _isBusy;
  23. private bool _suppressPasswordSync;
  24. public MainWindow()
  25. {
  26. InitializeComponent();
  27. Loaded += MainWindow_OnLoaded;
  28. }
  29. private async void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
  30. {
  31. await LoadInitialStateAsync();
  32. }
  33. private async Task LoadInitialStateAsync()
  34. {
  35. AdminStateTextBlock.Text = _adminPrivilegeService.IsAdministrator()
  36. ? "管理员状态:当前已以管理员身份运行,可执行本机网卡切换。"
  37. : "管理员状态:当前不是管理员运行,切换到维护网络会失败。";
  38. _adapters = _networkAdapterService.GetEthernetAdapters();
  39. await _networkAdapterService.ProbeMaintenanceReachabilityAsync(_adapters);
  40. _adapters = _adapters
  41. .OrderByDescending(adapter => adapter.RecommendationScore)
  42. .ThenBy(adapter => adapter.Name)
  43. .ToList();
  44. AdapterComboBox.ItemsSource = _adapters;
  45. var recommendedAdapter = _networkAdapterService.GetRecommendedAdapter(_adapters);
  46. var savedPassword = _passwordStoreService.LoadPassword();
  47. if (!string.IsNullOrWhiteSpace(savedPassword))
  48. {
  49. PasswordBox.Password = savedPassword;
  50. PasswordTextBox.Text = savedPassword;
  51. }
  52. if (recommendedAdapter is not null)
  53. {
  54. AdapterComboBox.SelectedItem = recommendedAdapter;
  55. UpdateAdapterDetails(recommendedAdapter);
  56. }
  57. else if (_adapters.Count > 0)
  58. {
  59. AdapterComboBox.SelectedIndex = 0;
  60. UpdateAdapterDetails(_adapters[0]);
  61. }
  62. AppendLog("客户端已加载连接页。", true);
  63. ClearRemoteDetails();
  64. UpdateButtonStates();
  65. }
  66. private void AdapterComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  67. {
  68. if (AdapterComboBox.SelectedItem is not AdapterInfo adapter)
  69. {
  70. UpdateAdapterDetails(null);
  71. ClearRemoteDetails();
  72. SetStatus("请选择一块有线网卡。", false);
  73. UpdateButtonStates();
  74. return;
  75. }
  76. UpdateAdapterDetails(adapter);
  77. ClearRemoteDetails();
  78. SetStatus(adapter.HasLink
  79. ? $"已选择 {adapter.RecommendationLabel} 网卡,可切换到维护网络。{adapter.RecommendationReason}"
  80. : "当前网卡未检测到链路,请检查网线连接。", true);
  81. UpdateButtonStates();
  82. }
  83. private async void SwitchMaintenanceButton_OnClick(object sender, RoutedEventArgs e)
  84. {
  85. if (!_adminPrivilegeService.IsAdministrator())
  86. {
  87. SetStatus("当前程序未以管理员身份运行,无法修改本机网卡。", true);
  88. MessageBox.Show(this, "请以管理员身份运行客户端后再切换到维护网络。", "需要管理员权限", MessageBoxButton.OK, MessageBoxImage.Warning);
  89. return;
  90. }
  91. if (AdapterComboBox.SelectedItem is not AdapterInfo adapter)
  92. {
  93. SetStatus("请先选择一块网卡。", true);
  94. return;
  95. }
  96. PersistPasswordIfNeeded();
  97. if (adapter.IsReachableToMaintenance)
  98. {
  99. SetStatus("当前网卡已经可以直接访问 169.254.100.2,无需切换到维护网络。", true);
  100. return;
  101. }
  102. SetBusyState(true);
  103. SetStatus("正在切换到维护网络,请稍候。", true);
  104. await Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.Render);
  105. try
  106. {
  107. await _networkConfigurationService.ConfigureMaintenanceNetworkAsync(adapter);
  108. SetStatus("已切换到维护网络。", true);
  109. await RefreshAdaptersAsync(adapter.Id);
  110. }
  111. catch (Exception ex)
  112. {
  113. SetStatus($"切换维护网络失败:{ex.Message}", true);
  114. MessageBox.Show(this, ex.Message, "切换维护网络失败", MessageBoxButton.OK, MessageBoxImage.Error);
  115. }
  116. finally
  117. {
  118. SetBusyState(false);
  119. }
  120. }
  121. private async void RefreshAdaptersButton_OnClick(object sender, RoutedEventArgs e)
  122. {
  123. SetBusyState(true);
  124. try
  125. {
  126. await RefreshAdaptersAsync();
  127. SetStatus("已刷新本机网卡和管理口探测结果。", true);
  128. }
  129. catch (Exception ex)
  130. {
  131. SetStatus($"刷新本机网卡失败:{ex.Message}", true);
  132. MessageBox.Show(this, ex.Message, "刷新失败", MessageBoxButton.OK, MessageBoxImage.Error);
  133. }
  134. finally
  135. {
  136. SetBusyState(false);
  137. }
  138. }
  139. private async void DiscoverConnectButton_OnClick(object sender, RoutedEventArgs e)
  140. {
  141. if (string.IsNullOrWhiteSpace(GetCurrentPassword()))
  142. {
  143. SetStatus("请输入管理密码。", true);
  144. MessageBox.Show(this, "请先在右侧“管理密码(必填)”区域输入密码。", "缺少管理密码", MessageBoxButton.OK, MessageBoxImage.Information);
  145. return;
  146. }
  147. PersistPasswordIfNeeded();
  148. SetBusyState(true);
  149. SetStatus("正在检查当前网卡是否可直接访问管理口。", true);
  150. await Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.Render);
  151. try
  152. {
  153. if (AdapterComboBox.SelectedItem is AdapterInfo adapter && adapter.IsReachableToMaintenance)
  154. {
  155. var directResult = await _agentApiService.CheckHealthAsync("http://169.254.100.2:48888", GetCurrentPassword(), adapter.IPv4Address);
  156. if (directResult.Success)
  157. {
  158. _connectedBaseAddress = "http://169.254.100.2:48888";
  159. _connectedLocalIPv4 = adapter.IPv4Address;
  160. SetStatus("连接成功,无需切换本机网卡。", true);
  161. OpenDeviceDetailsWindow(_connectedBaseAddress, _connectedLocalIPv4);
  162. return;
  163. }
  164. if (directResult.StatusCode == 401)
  165. {
  166. SetStatus("该网卡可以直连管理口,但管理密码错误。", true);
  167. MessageBox.Show(this, "当前网卡已经可以直连 Agent,但密码校验失败,请确认密码是否正确。", "密码错误", MessageBoxButton.OK, MessageBoxImage.Warning);
  168. return;
  169. }
  170. if (directResult.StatusCode == 403)
  171. {
  172. SetStatus("该网卡可以直连管理口,但 Agent 拒绝访问,请确认远端是否还是旧版本。", true);
  173. MessageBox.Show(this, "当前网卡已经可以直连 Agent,但请求被拒绝。请确认 Linux 端是否运行的是最新版本 Agent。", "访问被拒绝", MessageBoxButton.OK, MessageBoxImage.Warning);
  174. return;
  175. }
  176. SetStatus($"该网卡虽可建立连接,但直连 HTTP 校验失败:{directResult.Message}。正在尝试设备发现。", true);
  177. }
  178. SetStatus("当前网卡无法完成直连校验,正在发现设备,请稍候。", true);
  179. var selectedAdapter = AdapterComboBox.SelectedItem as AdapterInfo;
  180. var device = await _discoveryService.DiscoverAsync(selectedAdapter?.IPv4Address ?? string.Empty);
  181. if (device is null)
  182. {
  183. SetStatus("未发现设备。如果当前网卡不可达,请先切换到维护网络。", true);
  184. return;
  185. }
  186. SetStatus("已发现设备,正在验证连接。", true);
  187. var discoveredResult = await _agentApiService.CheckHealthAsync($"http://{device.Lan2Ip}:48888", GetCurrentPassword(), selectedAdapter?.IPv4Address ?? string.Empty);
  188. if (discoveredResult.Success)
  189. {
  190. _connectedBaseAddress = $"http://{device.Lan2Ip}:48888";
  191. _connectedLocalIPv4 = selectedAdapter?.IPv4Address ?? string.Empty;
  192. SetStatus("连接成功。", true);
  193. OpenDeviceDetailsWindow(_connectedBaseAddress, _connectedLocalIPv4);
  194. }
  195. else
  196. {
  197. SetStatus($"设备已发现,但 HTTP 验证失败:{discoveredResult.Message}", true);
  198. }
  199. }
  200. catch (Exception ex)
  201. {
  202. ClearRemoteDetails();
  203. SetStatus($"连接失败:{ex.Message}", true);
  204. MessageBox.Show(this, ex.Message, "连接失败", MessageBoxButton.OK, MessageBoxImage.Error);
  205. }
  206. finally
  207. {
  208. SetBusyState(false);
  209. }
  210. }
  211. private void PersistPasswordIfNeeded()
  212. {
  213. var password = GetCurrentPassword();
  214. if (!string.IsNullOrWhiteSpace(password))
  215. {
  216. _passwordStoreService.SavePassword(password);
  217. return;
  218. }
  219. }
  220. private string GetCurrentPassword()
  221. {
  222. return _isShowingPassword ? PasswordTextBox.Text : PasswordBox.Password;
  223. }
  224. private void UpdateButtonStates()
  225. {
  226. var adapter = AdapterComboBox.SelectedItem as AdapterInfo;
  227. var hasAdapter = adapter is not null;
  228. RefreshAdaptersButton.IsEnabled = !_isBusy;
  229. SwitchMaintenanceButton.IsEnabled = !_isBusy && hasAdapter;
  230. DiscoverConnectButton.IsEnabled = !_isBusy && hasAdapter && adapter!.HasLink;
  231. ReloadInterfaceConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  232. ValidateConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  233. ApplyConfigButton.IsEnabled = _configValidated && RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  234. }
  235. private async Task RefreshAdaptersAsync(string? selectedAdapterId = null)
  236. {
  237. _adapters = _networkAdapterService.GetEthernetAdapters();
  238. await _networkAdapterService.ProbeMaintenanceReachabilityAsync(_adapters);
  239. _adapters = _adapters
  240. .OrderByDescending(adapter => adapter.RecommendationScore)
  241. .ThenBy(adapter => adapter.Name)
  242. .ToList();
  243. AdapterComboBox.ItemsSource = _adapters;
  244. var selected = selectedAdapterId is null
  245. ? _networkAdapterService.GetRecommendedAdapter(_adapters)
  246. : _adapters.FirstOrDefault(adapter => adapter.Id == selectedAdapterId) ?? _networkAdapterService.GetRecommendedAdapter(_adapters);
  247. if (selected is not null)
  248. {
  249. AdapterComboBox.SelectedItem = selected;
  250. UpdateAdapterDetails(selected);
  251. }
  252. }
  253. private void UpdateAdapterDetails(AdapterInfo? adapter)
  254. {
  255. if (adapter is null)
  256. {
  257. AdapterProbeTextBlock.Text = "-";
  258. return;
  259. }
  260. AdapterProbeTextBlock.Text = $"{adapter.ProbeStatus} / {adapter.ProbeReason}";
  261. }
  262. private async Task LoadRemoteDetailsAsync(string baseAddress, string localIPv4)
  263. {
  264. ClearRemoteDetails();
  265. RemoteDetailsBorder.Visibility = Visibility.Visible;
  266. SetStatus("正在读取设备信息。", true);
  267. var device = await _agentApiService.GetDeviceInfoAsync(baseAddress, GetCurrentPassword(), localIPv4);
  268. if (device is not null)
  269. {
  270. RemoteDeviceIdTextBlock.Text = device.DeviceId;
  271. RemoteHostnameTextBlock.Text = device.Hostname;
  272. RemoteOsVersionTextBlock.Text = device.OSVersion;
  273. RemoteAgentVersionTextBlock.Text = device.AgentVersion;
  274. }
  275. SetStatus("正在读取 Linux 接口列表。", true);
  276. var interfaces = await _agentApiService.GetInterfacesAsync(baseAddress, GetCurrentPassword(), localIPv4);
  277. if (interfaces is not null)
  278. {
  279. RemoteSummaryTextBlock.Text = $"当前管理接口:{interfaces.ManagementInterface};建议目标接口:{interfaces.SuggestedTargetInterface};{(interfaces.RequiresTargetSelection ? "需要手动选择目标接口。" : "已自动识别建议目标接口。")}";
  280. var suggested = interfaces.Interfaces.FirstOrDefault(item => item.SystemName == interfaces.SuggestedTargetInterface)
  281. ?? interfaces.Interfaces.FirstOrDefault(item => item.IsSuggestedTarget)
  282. ?? interfaces.Interfaces.FirstOrDefault(item => !item.IsManagementInterface);
  283. RemoteTargetInterfaceComboBox.ItemsSource = interfaces.Interfaces;
  284. if (suggested is not null)
  285. {
  286. RemoteTargetInterfaceComboBox.SelectedItem = suggested;
  287. await LoadRemoteInterfaceConfigAsync(suggested.SystemName);
  288. }
  289. SetStatus("已加载设备信息和 Linux 接口列表。", true);
  290. return;
  291. }
  292. RemoteSummaryTextBlock.Text = "设备已连接,但暂时无法读取 Linux 接口列表。";
  293. }
  294. private void OpenDeviceDetailsWindow(string baseAddress, string localIPv4)
  295. {
  296. var window = new DeviceDetailsWindow(baseAddress, localIPv4, GetCurrentPassword())
  297. {
  298. Owner = this,
  299. };
  300. window.ShowDialog();
  301. }
  302. private void ClearRemoteDetails()
  303. {
  304. RemoteDetailsBorder.Visibility = Visibility.Collapsed;
  305. RemoteDeviceIdTextBlock.Text = "-";
  306. RemoteHostnameTextBlock.Text = "-";
  307. RemoteOsVersionTextBlock.Text = "-";
  308. RemoteAgentVersionTextBlock.Text = "-";
  309. RemoteTargetInterfaceComboBox.ItemsSource = null;
  310. RemoteConfigInterfaceTextBlock.Text = "-";
  311. RemoteConfigIpTextBlock.Text = "-";
  312. RemoteConfigGatewayTextBlock.Text = "-";
  313. RemoteConfigDnsTextBlock.Text = "-";
  314. NewIpTextBox.Text = string.Empty;
  315. NewMaskTextBox.Text = string.Empty;
  316. NewGatewayTextBox.Text = string.Empty;
  317. NewDnsTextBox.Text = string.Empty;
  318. ConfigValidationTextBlock.Text = "读取目标接口当前配置后,可在此修改并校验。";
  319. ApplyTaskStatusTextBlock.Text = "尚未提交配置任务。";
  320. _configValidated = false;
  321. RemoteSummaryTextBlock.Text = "连接成功后,这里会显示 Linux 管理接口和建议目标接口。";
  322. UpdateButtonStates();
  323. }
  324. private async void RemoteTargetInterfaceComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  325. {
  326. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected || string.IsNullOrWhiteSpace(_connectedBaseAddress))
  327. {
  328. return;
  329. }
  330. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  331. }
  332. private async Task LoadRemoteInterfaceConfigAsync(string interfaceName)
  333. {
  334. SetStatus($"正在读取目标接口 {interfaceName} 当前配置。", true);
  335. var result = await _agentApiService.GetInterfaceConfigAsync(_connectedBaseAddress, GetCurrentPassword(), _connectedLocalIPv4, interfaceName);
  336. if (!result.Success || result.Data is null)
  337. {
  338. RemoteConfigInterfaceTextBlock.Text = interfaceName;
  339. RemoteConfigIpTextBlock.Text = "读取失败";
  340. RemoteConfigGatewayTextBlock.Text = "读取失败";
  341. RemoteConfigDnsTextBlock.Text = "读取失败";
  342. SetStatus($"读取目标接口 {interfaceName} 配置失败:{result.Message}", true);
  343. return;
  344. }
  345. var config = result.Data;
  346. RemoteConfigInterfaceTextBlock.Text = config.Interface;
  347. RemoteConfigIpTextBlock.Text = string.IsNullOrWhiteSpace(config.IP) ? "无" : $"{config.IP}/{config.Prefix}";
  348. RemoteConfigGatewayTextBlock.Text = string.IsNullOrWhiteSpace(config.Gateway) ? "无" : config.Gateway;
  349. RemoteConfigDnsTextBlock.Text = config.DnsSummary;
  350. _suppressConfigChangeHandling = true;
  351. NewIpTextBox.Text = config.IP;
  352. NewMaskTextBox.Text = PrefixToMask(config.Prefix);
  353. NewGatewayTextBox.Text = config.Gateway;
  354. NewDnsTextBox.Text = config.Dns.FirstOrDefault() ?? string.Empty;
  355. _suppressConfigChangeHandling = false;
  356. _configValidated = false;
  357. ConfigValidationTextBlock.Text = "已回填目标接口当前配置,可直接修改后校验。";
  358. ApplyTaskStatusTextBlock.Text = "尚未提交配置任务。";
  359. UpdateButtonStates();
  360. SetStatus($"已读取目标接口 {interfaceName} 当前配置。", true);
  361. }
  362. private async void ReloadInterfaceConfigButton_OnClick(object sender, RoutedEventArgs e)
  363. {
  364. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  365. {
  366. return;
  367. }
  368. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  369. }
  370. private async void ValidateConfigButton_OnClick(object sender, RoutedEventArgs e)
  371. {
  372. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  373. {
  374. return;
  375. }
  376. var request = BuildConfigRequest(selected.SystemName);
  377. if (request is null)
  378. {
  379. return;
  380. }
  381. SetStatus($"正在校验目标接口 {selected.SystemName} 的新配置。", true);
  382. var result = await _agentApiService.ValidateInterfaceConfigAsync(_connectedBaseAddress, GetCurrentPassword(), _connectedLocalIPv4, request);
  383. _configValidated = result.Success && result.Data?.Valid == true;
  384. if (result.Data is not null)
  385. {
  386. var warnings = result.Data.Warnings.Count > 0 ? $" 警告:{string.Join(";", result.Data.Warnings)}" : string.Empty;
  387. var errors = result.Data.Errors.Count > 0 ? $" 错误:{string.Join(";", result.Data.Errors)}" : string.Empty;
  388. ConfigValidationTextBlock.Text = result.Success ? $"校验通过。{warnings}" : $"校验失败。{errors}{warnings}";
  389. }
  390. else
  391. {
  392. ConfigValidationTextBlock.Text = $"校验失败:{result.Message}";
  393. }
  394. ApplyTaskStatusTextBlock.Text = _configValidated ? "配置已通过校验,可提交应用。" : "当前配置尚未通过校验。";
  395. UpdateButtonStates();
  396. }
  397. private async void ApplyConfigButton_OnClick(object sender, RoutedEventArgs e)
  398. {
  399. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  400. {
  401. return;
  402. }
  403. var request = BuildConfigRequest(selected.SystemName);
  404. if (request is null)
  405. {
  406. return;
  407. }
  408. var confirmMessage = $"将要把以下配置应用到接口 {selected.SystemName}:\n\n" +
  409. $"IP:{request.IP}/{request.Prefix}\n" +
  410. $"网关:{(string.IsNullOrWhiteSpace(request.Gateway) ? "无" : request.Gateway)}\n" +
  411. $"DNS:{(request.Dns.Count == 0 ? "无" : string.Join(", ", request.Dns))}\n\n" +
  412. "请确认是否继续。";
  413. if (MessageBox.Show(this, confirmMessage, "确认应用配置", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK)
  414. {
  415. return;
  416. }
  417. SetStatus($"正在提交目标接口 {selected.SystemName} 的配置任务。", true);
  418. var applyResult = await _agentApiService.ApplyInterfaceConfigAsync(_connectedBaseAddress, GetCurrentPassword(), _connectedLocalIPv4, request);
  419. if (!applyResult.Success || applyResult.Data is null)
  420. {
  421. ApplyTaskStatusTextBlock.Text = $"提交配置任务失败:{applyResult.Message}";
  422. return;
  423. }
  424. ApplyTaskStatusTextBlock.Text = $"配置任务已提交:{applyResult.Data.TaskId},正在轮询状态。";
  425. await PollTaskAsync(applyResult.Data.TaskId);
  426. }
  427. private async Task PollTaskAsync(string taskId)
  428. {
  429. var transientFailureCount = 0;
  430. for (var i = 0; i < 20; i++)
  431. {
  432. await Task.Delay(1000);
  433. var result = await _agentApiService.GetTaskAsync(_connectedBaseAddress, GetCurrentPassword(), _connectedLocalIPv4, taskId);
  434. if (!result.Success || result.Data is null)
  435. {
  436. if (result.StatusCode is null)
  437. {
  438. transientFailureCount++;
  439. ApplyTaskStatusTextBlock.Text = $"任务 {taskId} 轮询中,检测到短暂断连,正在重试({transientFailureCount})。";
  440. continue;
  441. }
  442. ApplyTaskStatusTextBlock.Text = $"读取任务状态失败:{result.Message}";
  443. return;
  444. }
  445. transientFailureCount = 0;
  446. var task = result.Data;
  447. ApplyTaskStatusTextBlock.Text = $"任务 {task.TaskId} / {task.Status} / {task.Step} / {task.Detail}";
  448. if (task.Status is "success" or "failed" or "rolled_back")
  449. {
  450. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  451. {
  452. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  453. }
  454. return;
  455. }
  456. }
  457. ApplyTaskStatusTextBlock.Text = $"任务 {taskId} 轮询超时,请稍后手动刷新。";
  458. }
  459. private RemoteInterfaceConfig? BuildConfigRequest(string interfaceName)
  460. {
  461. if (string.IsNullOrWhiteSpace(NewIpTextBox.Text))
  462. {
  463. ConfigValidationTextBlock.Text = "IP 地址不能为空。";
  464. return null;
  465. }
  466. if (!TryMaskToPrefix(NewMaskTextBox.Text, out var prefix))
  467. {
  468. ConfigValidationTextBlock.Text = "子网掩码格式不正确。";
  469. return null;
  470. }
  471. var dns = string.IsNullOrWhiteSpace(NewDnsTextBox.Text)
  472. ? Array.Empty<string>()
  473. : new[] { NewDnsTextBox.Text.Trim() };
  474. return new RemoteInterfaceConfig
  475. {
  476. Interface = interfaceName,
  477. IP = NewIpTextBox.Text.Trim(),
  478. Prefix = prefix,
  479. Gateway = NewGatewayTextBox.Text.Trim(),
  480. Dns = dns,
  481. };
  482. }
  483. private static string PrefixToMask(int prefix)
  484. {
  485. if (prefix < 0 || prefix > 32)
  486. {
  487. return string.Empty;
  488. }
  489. var mask = prefix == 0 ? 0u : uint.MaxValue << (32 - prefix);
  490. return string.Join('.', new[]
  491. {
  492. (mask >> 24) & 255,
  493. (mask >> 16) & 255,
  494. (mask >> 8) & 255,
  495. mask & 255,
  496. });
  497. }
  498. private static bool TryMaskToPrefix(string maskText, out int prefix)
  499. {
  500. prefix = 0;
  501. if (string.IsNullOrWhiteSpace(maskText))
  502. {
  503. return false;
  504. }
  505. var parts = maskText.Trim().Split('.');
  506. if (parts.Length != 4)
  507. {
  508. return false;
  509. }
  510. uint mask = 0;
  511. foreach (var part in parts)
  512. {
  513. if (!byte.TryParse(part, out var octet))
  514. {
  515. return false;
  516. }
  517. mask = (mask << 8) | octet;
  518. }
  519. var seenZero = false;
  520. for (var i = 31; i >= 0; i--)
  521. {
  522. var bit = (mask & (1u << i)) != 0;
  523. if (bit && seenZero)
  524. {
  525. return false;
  526. }
  527. if (bit)
  528. {
  529. prefix++;
  530. }
  531. else
  532. {
  533. seenZero = true;
  534. }
  535. }
  536. return true;
  537. }
  538. private void ConfigInputChanged_OnChanged(object sender, TextChangedEventArgs e)
  539. {
  540. if (_suppressConfigChangeHandling)
  541. {
  542. return;
  543. }
  544. _configValidated = false;
  545. ConfigValidationTextBlock.Text = "配置内容已变更,请重新点击“校验配置”。";
  546. ApplyTaskStatusTextBlock.Text = "当前配置尚未通过校验。";
  547. UpdateButtonStates();
  548. }
  549. private void SetStatus(string message, bool addLog)
  550. {
  551. StatusTextBlock.Text = message;
  552. if (addLog)
  553. {
  554. AppendLog(message, false);
  555. }
  556. }
  557. private void AppendLog(string message, bool isInitial)
  558. {
  559. var prefix = DateTime.Now.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
  560. EventLogListBox.Items.Add($"[{prefix}] {message}");
  561. if (!isInitial)
  562. {
  563. EventLogListBox.ScrollIntoView(EventLogListBox.Items[^1]);
  564. }
  565. }
  566. private void SetBusyState(bool isBusy)
  567. {
  568. _isBusy = isBusy;
  569. AdapterComboBox.IsEnabled = !isBusy;
  570. RefreshAdaptersButton.IsEnabled = !isBusy;
  571. PasswordBox.IsEnabled = !isBusy;
  572. PasswordTextBox.IsEnabled = !isBusy;
  573. TogglePasswordVisibilityButton.IsEnabled = !isBusy;
  574. SwitchMaintenanceButton.IsEnabled = !isBusy && AdapterComboBox.SelectedItem is AdapterInfo;
  575. DiscoverConnectButton.IsEnabled = !isBusy && AdapterComboBox.SelectedItem is AdapterInfo adapter && adapter.HasLink;
  576. }
  577. private void TogglePasswordVisibilityButton_OnClick(object sender, RoutedEventArgs e)
  578. {
  579. _isShowingPassword = !_isShowingPassword;
  580. if (_isShowingPassword)
  581. {
  582. PasswordTextBox.Text = PasswordBox.Password;
  583. PasswordBox.Visibility = Visibility.Collapsed;
  584. PasswordTextBox.Visibility = Visibility.Visible;
  585. TogglePasswordVisibilityButton.Content = "🙈";
  586. PasswordTextBox.Focus();
  587. PasswordTextBox.CaretIndex = PasswordTextBox.Text.Length;
  588. return;
  589. }
  590. PasswordBox.Password = PasswordTextBox.Text;
  591. PasswordTextBox.Visibility = Visibility.Collapsed;
  592. PasswordBox.Visibility = Visibility.Visible;
  593. TogglePasswordVisibilityButton.Content = "👁";
  594. PasswordBox.Focus();
  595. }
  596. private void PasswordBox_OnPasswordChanged(object sender, RoutedEventArgs e)
  597. {
  598. if (_suppressPasswordSync)
  599. {
  600. return;
  601. }
  602. _suppressPasswordSync = true;
  603. PasswordTextBox.Text = PasswordBox.Password;
  604. _suppressPasswordSync = false;
  605. }
  606. private void PasswordTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
  607. {
  608. if (_suppressPasswordSync)
  609. {
  610. return;
  611. }
  612. _suppressPasswordSync = true;
  613. PasswordBox.Password = PasswordTextBox.Text;
  614. _suppressPasswordSync = false;
  615. }
  616. }