DeviceDetailsWindow.xaml.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System.Globalization;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Media;
  5. using System.Windows.Media.Animation;
  6. using QuickIP.Client.Models;
  7. using QuickIP.Client.Services;
  8. namespace QuickIP.Client;
  9. public partial class DeviceDetailsWindow : Window
  10. {
  11. private readonly AgentApiService _agentApiService = new();
  12. private readonly string _baseAddress;
  13. private readonly string _localIPv4;
  14. private readonly string _password;
  15. private bool _configValidated;
  16. private bool _isBusy;
  17. private bool _suppressConfigChangeHandling;
  18. private CancellationTokenSource? _statusMessageCts;
  19. public DeviceDetailsWindow(string baseAddress, string localIPv4, string password)
  20. {
  21. InitializeComponent();
  22. _baseAddress = baseAddress;
  23. _localIPv4 = localIPv4;
  24. _password = password;
  25. Loaded += DeviceDetailsWindow_OnLoaded;
  26. }
  27. private async void DeviceDetailsWindow_OnLoaded(object sender, RoutedEventArgs e)
  28. {
  29. await LoadRemoteDetailsAsync();
  30. UpdateButtonStates();
  31. }
  32. private async Task LoadRemoteDetailsAsync()
  33. {
  34. ClearDetails();
  35. var device = await _agentApiService.GetDeviceInfoAsync(_baseAddress, _password, _localIPv4);
  36. if (device is not null)
  37. {
  38. RemoteDeviceIdTextBlock.Text = device.DeviceId;
  39. RemoteHostnameTextBlock.Text = device.Hostname;
  40. RemoteOsVersionTextBlock.Text = device.OSVersion;
  41. RemoteAgentVersionTextBlock.Text = device.AgentVersion;
  42. }
  43. var interfaces = await _agentApiService.GetInterfacesAsync(_baseAddress, _password, _localIPv4);
  44. if (interfaces is null)
  45. {
  46. ShowStatusMessage("设备已连接,但暂时无法读取 Linux 接口列表。");
  47. return;
  48. }
  49. ShowStatusMessage($"当前管理接口:{interfaces.ManagementInterface};建议目标接口:{interfaces.SuggestedTargetInterface};{(interfaces.RequiresTargetSelection ? "需要手动选择目标接口。" : "已自动识别建议目标接口。")}");
  50. var suggested = interfaces.Interfaces.FirstOrDefault(item => item.SystemName == interfaces.SuggestedTargetInterface)
  51. ?? interfaces.Interfaces.FirstOrDefault(item => item.IsSuggestedTarget)
  52. ?? interfaces.Interfaces.FirstOrDefault(item => !item.IsManagementInterface);
  53. RemoteTargetInterfaceComboBox.ItemsSource = interfaces.Interfaces;
  54. if (suggested is not null)
  55. {
  56. RemoteTargetInterfaceComboBox.SelectedItem = suggested;
  57. await LoadRemoteInterfaceConfigAsync(suggested.SystemName);
  58. }
  59. }
  60. private void ClearDetails()
  61. {
  62. RemoteDeviceIdTextBlock.Text = "-";
  63. RemoteHostnameTextBlock.Text = "-";
  64. RemoteOsVersionTextBlock.Text = "-";
  65. RemoteAgentVersionTextBlock.Text = "-";
  66. RemoteTargetInterfaceComboBox.ItemsSource = null;
  67. RemoteConfigInterfaceTextBlock.Text = "-";
  68. RemoteConfigIpTextBlock.Text = "-";
  69. RemoteConfigGatewayTextBlock.Text = "-";
  70. RemoteConfigDnsTextBlock.Text = "-";
  71. NewIpTextBox.Text = string.Empty;
  72. NewMaskTextBox.Text = string.Empty;
  73. NewGatewayTextBox.Text = string.Empty;
  74. NewDnsTextBox.Text = string.Empty;
  75. _configValidated = false;
  76. }
  77. private async void RemoteTargetInterfaceComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  78. {
  79. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  80. {
  81. UpdateButtonStates();
  82. return;
  83. }
  84. await LoadRemoteInterfaceConfigAsync(selected.SystemName, useBusyState: true);
  85. }
  86. private async Task LoadRemoteInterfaceConfigAsync(string interfaceName, bool useBusyState = false)
  87. {
  88. if (useBusyState)
  89. {
  90. SetBusyState(true, "正在读取 Linux 端 IP 配置...");
  91. }
  92. try
  93. {
  94. var result = await _agentApiService.GetInterfaceConfigAsync(_baseAddress, _password, _localIPv4, interfaceName);
  95. if (!result.Success || result.Data is null)
  96. {
  97. RemoteConfigInterfaceTextBlock.Text = interfaceName;
  98. RemoteConfigIpTextBlock.Text = "读取失败";
  99. RemoteConfigGatewayTextBlock.Text = "读取失败";
  100. RemoteConfigDnsTextBlock.Text = "读取失败";
  101. ShowStatusMessage($"读取目标接口 {interfaceName} 配置失败:{result.Message}");
  102. return;
  103. }
  104. var config = result.Data;
  105. RemoteConfigInterfaceTextBlock.Text = config.Interface;
  106. RemoteConfigIpTextBlock.Text = string.IsNullOrWhiteSpace(config.IP) ? "无" : $"{config.IP}/{config.Prefix}";
  107. RemoteConfigGatewayTextBlock.Text = string.IsNullOrWhiteSpace(config.Gateway) ? "无" : config.Gateway;
  108. RemoteConfigDnsTextBlock.Text = config.DnsSummary;
  109. _suppressConfigChangeHandling = true;
  110. NewIpTextBox.Text = config.IP;
  111. NewMaskTextBox.Text = PrefixToMask(config.Prefix);
  112. NewGatewayTextBox.Text = config.Gateway;
  113. NewDnsTextBox.Text = config.Dns.FirstOrDefault() ?? string.Empty;
  114. _suppressConfigChangeHandling = false;
  115. _configValidated = false;
  116. ShowStatusMessage("已读取Linux端IP配置。");
  117. UpdateButtonStates();
  118. }
  119. finally
  120. {
  121. if (useBusyState)
  122. {
  123. SetBusyState(false);
  124. }
  125. }
  126. }
  127. private async void ReloadInterfaceConfigButton_OnClick(object sender, RoutedEventArgs e)
  128. {
  129. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  130. {
  131. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  132. }
  133. }
  134. private async void ValidateConfigButton_OnClick(object sender, RoutedEventArgs e)
  135. {
  136. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  137. {
  138. return;
  139. }
  140. var request = BuildConfigRequest(selected.SystemName);
  141. if (request is null)
  142. {
  143. return;
  144. }
  145. SetBusyState(true, "正在校验配置,请稍候...");
  146. try
  147. {
  148. var result = await _agentApiService.ValidateInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
  149. _configValidated = result.Success && result.Data?.Valid == true;
  150. if (result.Data is not null)
  151. {
  152. var warnings = result.Data.Warnings.Count > 0 ? $" 警告:{string.Join(";", result.Data.Warnings)}" : string.Empty;
  153. var errors = result.Data.Errors.Count > 0 ? $" 错误:{string.Join(";", result.Data.Errors)}" : string.Empty;
  154. ShowStatusMessage(_configValidated ? $"校验通过,可应用配置。{warnings}" : $"校验失败。{errors}{warnings}");
  155. }
  156. else
  157. {
  158. ShowStatusMessage($"校验失败:{result.Message}");
  159. }
  160. UpdateButtonStates();
  161. }
  162. finally
  163. {
  164. SetBusyState(false);
  165. }
  166. }
  167. private async void ApplyConfigButton_OnClick(object sender, RoutedEventArgs e)
  168. {
  169. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  170. {
  171. return;
  172. }
  173. var request = BuildConfigRequest(selected.SystemName);
  174. if (request is null)
  175. {
  176. return;
  177. }
  178. var confirmMessage = $"将要把以下配置应用到接口 {selected.SystemName}:\n\n" +
  179. $"IP:{request.IP}/{request.Prefix}\n" +
  180. $"网关:{(string.IsNullOrWhiteSpace(request.Gateway) ? "无" : request.Gateway)}\n" +
  181. $"DNS:{(request.Dns.Count == 0 ? "无" : string.Join(", ", request.Dns))}\n\n" +
  182. "请确认是否继续。";
  183. if (MessageBox.Show(this, confirmMessage, "确认应用配置", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK)
  184. {
  185. return;
  186. }
  187. SetBusyState(true, "正在提交并应用配置,请稍候...");
  188. try
  189. {
  190. var applyResult = await _agentApiService.ApplyInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
  191. if (!applyResult.Success || applyResult.Data is null)
  192. {
  193. ShowStatusMessage($"提交配置任务失败:{applyResult.Message}");
  194. return;
  195. }
  196. ShowStatusMessage($"配置任务已提交:{applyResult.Data.TaskId},正在轮询状态。");
  197. await PollTaskAsync(applyResult.Data.TaskId);
  198. }
  199. finally
  200. {
  201. SetBusyState(false);
  202. }
  203. }
  204. private async Task PollTaskAsync(string taskId)
  205. {
  206. var transientFailureCount = 0;
  207. for (var i = 0; i < 20; i++)
  208. {
  209. await Task.Delay(1000);
  210. var result = await _agentApiService.GetTaskAsync(_baseAddress, _password, _localIPv4, taskId);
  211. if (!result.Success || result.Data is null)
  212. {
  213. if (result.StatusCode is null)
  214. {
  215. transientFailureCount++;
  216. ShowStatusMessage($"任务 {taskId} 轮询中,检测到短暂断连,正在重试({transientFailureCount})。");
  217. continue;
  218. }
  219. ShowStatusMessage($"读取任务状态失败:{result.Message}");
  220. return;
  221. }
  222. transientFailureCount = 0;
  223. var task = result.Data;
  224. ShowStatusMessage($"任务 {task.TaskId} / {task.Status} / {task.Step} / {task.Detail}");
  225. if (task.Status is "success" or "failed" or "rolled_back")
  226. {
  227. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  228. {
  229. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  230. }
  231. return;
  232. }
  233. }
  234. ShowStatusMessage($"任务 {taskId} 轮询超时,请稍后手动刷新。");
  235. }
  236. private async void RebootButton_OnClick(object sender, RoutedEventArgs e)
  237. {
  238. await ExecuteSystemActionAsync(
  239. "重启设备",
  240. "设备将立即重启,当前窗口和连接可能马上中断。是否继续?",
  241. () => _agentApiService.RebootAsync(_baseAddress, _password, _localIPv4));
  242. }
  243. private async void ShutdownButton_OnClick(object sender, RoutedEventArgs e)
  244. {
  245. await ExecuteSystemActionAsync(
  246. "关闭设备",
  247. "设备将立即关机,当前窗口和连接可能马上中断。是否继续?",
  248. () => _agentApiService.ShutdownAsync(_baseAddress, _password, _localIPv4));
  249. }
  250. private async Task ExecuteSystemActionAsync(string title, string confirmMessage, Func<Task<ApiCallResult<RemoteSystemActionResponse>>> action)
  251. {
  252. if (MessageBox.Show(this, confirmMessage, title, MessageBoxButton.OKCancel, MessageBoxImage.Warning) != MessageBoxResult.OK)
  253. {
  254. return;
  255. }
  256. var result = await action();
  257. if (!result.Success || result.Data is null)
  258. {
  259. ShowStatusMessage($"{title}失败:{result.Message}");
  260. return;
  261. }
  262. ShowStatusMessage($"{title}任务已提交:{result.Data.TaskId}。命令已发出,设备可能立即断开。");
  263. }
  264. private RemoteInterfaceConfig? BuildConfigRequest(string interfaceName)
  265. {
  266. if (string.IsNullOrWhiteSpace(NewIpTextBox.Text))
  267. {
  268. ShowStatusMessage("IP 地址不能为空。");
  269. return null;
  270. }
  271. if (!TryMaskToPrefix(NewMaskTextBox.Text, out var prefix))
  272. {
  273. ShowStatusMessage("子网掩码格式不正确。");
  274. return null;
  275. }
  276. var dns = string.IsNullOrWhiteSpace(NewDnsTextBox.Text) ? Array.Empty<string>() : new[] { NewDnsTextBox.Text.Trim() };
  277. return new RemoteInterfaceConfig
  278. {
  279. Interface = interfaceName,
  280. IP = NewIpTextBox.Text.Trim(),
  281. Prefix = prefix,
  282. Gateway = NewGatewayTextBox.Text.Trim(),
  283. Dns = dns,
  284. };
  285. }
  286. private static string PrefixToMask(int prefix)
  287. {
  288. if (prefix < 0 || prefix > 32)
  289. {
  290. return string.Empty;
  291. }
  292. var mask = prefix == 0 ? 0u : uint.MaxValue << (32 - prefix);
  293. return string.Join('.', new[] { (mask >> 24) & 255, (mask >> 16) & 255, (mask >> 8) & 255, mask & 255 });
  294. }
  295. private static bool TryMaskToPrefix(string maskText, out int prefix)
  296. {
  297. prefix = 0;
  298. if (string.IsNullOrWhiteSpace(maskText))
  299. {
  300. return false;
  301. }
  302. var parts = maskText.Trim().Split('.');
  303. if (parts.Length != 4)
  304. {
  305. return false;
  306. }
  307. uint mask = 0;
  308. foreach (var part in parts)
  309. {
  310. if (!byte.TryParse(part, out var octet))
  311. {
  312. return false;
  313. }
  314. mask = (mask << 8) | octet;
  315. }
  316. var seenZero = false;
  317. for (var i = 31; i >= 0; i--)
  318. {
  319. var bit = (mask & (1u << i)) != 0;
  320. if (bit && seenZero)
  321. {
  322. return false;
  323. }
  324. if (bit)
  325. {
  326. prefix++;
  327. }
  328. else
  329. {
  330. seenZero = true;
  331. }
  332. }
  333. return true;
  334. }
  335. private void ConfigInputChanged_OnChanged(object sender, TextChangedEventArgs e)
  336. {
  337. if (_suppressConfigChangeHandling)
  338. {
  339. return;
  340. }
  341. _configValidated = false;
  342. ShowStatusMessage("配置内容已变更,请重新点击“2. 校验配置”。");
  343. UpdateButtonStates();
  344. }
  345. private void ShowStatusMessage(string message)
  346. {
  347. ApplyStatusMessageStyle(message);
  348. StatusMessageTextBlock.Text = message;
  349. StatusMessageBorder.Opacity = 0;
  350. StatusMessageBorder.Visibility = Visibility.Visible;
  351. StatusMessageBorder.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(160)));
  352. _statusMessageCts?.Cancel();
  353. _statusMessageCts = new CancellationTokenSource();
  354. _ = HideStatusMessageAsync(_statusMessageCts.Token);
  355. }
  356. private async Task HideStatusMessageAsync(CancellationToken cancellationToken)
  357. {
  358. try
  359. {
  360. await Task.Delay(3000, cancellationToken);
  361. await Dispatcher.InvokeAsync(() =>
  362. {
  363. var animation = new DoubleAnimation(0, TimeSpan.FromMilliseconds(200));
  364. animation.Completed += (_, _) =>
  365. {
  366. if (!cancellationToken.IsCancellationRequested)
  367. {
  368. StatusMessageBorder.Visibility = Visibility.Collapsed;
  369. }
  370. };
  371. StatusMessageBorder.BeginAnimation(OpacityProperty, animation);
  372. });
  373. }
  374. catch (TaskCanceledException)
  375. {
  376. }
  377. }
  378. private void ApplyStatusMessageStyle(string message)
  379. {
  380. var (background, foreground) = GetStatusMessageBrushes(message);
  381. StatusMessageBorder.Background = background;
  382. StatusMessageTextBlock.Foreground = foreground;
  383. }
  384. private static (Brush Background, Brush Foreground) GetStatusMessageBrushes(string message)
  385. {
  386. if (ContainsAny(message, "失败", "错误", "拒绝", "超时", "不能为空", "不正确", "无法"))
  387. {
  388. return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#B91C1C")), Brushes.White);
  389. }
  390. if (ContainsAny(message, "未发现", "请", "重试", "警告", "需要"))
  391. {
  392. return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#C2410C")), Brushes.White);
  393. }
  394. if (ContainsAny(message, "成功", "已切换", "已刷新", "已读取", "已加载", "已发现", "已提交", "已回填"))
  395. {
  396. return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#047857")), Brushes.White);
  397. }
  398. return (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#111827")), Brushes.White);
  399. }
  400. private static bool ContainsAny(string message, params string[] markers)
  401. {
  402. return markers.Any(marker => message.Contains(marker, StringComparison.Ordinal));
  403. }
  404. private void UpdateButtonStates()
  405. {
  406. var hasSelectedInterface = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  407. var canEdit = !_isBusy && hasSelectedInterface;
  408. RemoteTargetInterfaceComboBox.IsEnabled = !_isBusy && RemoteTargetInterfaceComboBox.Items.Count > 0;
  409. ReloadInterfaceConfigButton.IsEnabled = canEdit;
  410. ValidateConfigButton.IsEnabled = canEdit;
  411. ApplyConfigButton.IsEnabled = !_isBusy && _configValidated && hasSelectedInterface;
  412. NewIpTextBox.IsEnabled = canEdit;
  413. NewMaskTextBox.IsEnabled = canEdit;
  414. NewGatewayTextBox.IsEnabled = canEdit;
  415. NewDnsTextBox.IsEnabled = canEdit;
  416. RebootButton.IsEnabled = !_isBusy;
  417. ShutdownButton.IsEnabled = !_isBusy;
  418. }
  419. private void SetBusyState(bool isBusy, string? message = null)
  420. {
  421. _isBusy = isBusy;
  422. BusyOverlay.Visibility = isBusy ? Visibility.Visible : Visibility.Collapsed;
  423. BusyMessageTextBlock.Text = string.IsNullOrWhiteSpace(message) ? "正在处理,请稍候..." : message;
  424. UpdateButtonStates();
  425. }
  426. }