MainWindow.xaml.cs 27 KB

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