DeviceDetailsWindow.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. using System.Globalization;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using QuickIP.Client.Models;
  5. using QuickIP.Client.Services;
  6. namespace QuickIP.Client;
  7. public partial class DeviceDetailsWindow : Window
  8. {
  9. private readonly AgentApiService _agentApiService = new();
  10. private readonly string _baseAddress;
  11. private readonly string _localIPv4;
  12. private readonly string _password;
  13. private bool _configValidated;
  14. private bool _suppressConfigChangeHandling;
  15. public DeviceDetailsWindow(string baseAddress, string localIPv4, string password)
  16. {
  17. InitializeComponent();
  18. _baseAddress = baseAddress;
  19. _localIPv4 = localIPv4;
  20. _password = password;
  21. Loaded += DeviceDetailsWindow_OnLoaded;
  22. }
  23. private async void DeviceDetailsWindow_OnLoaded(object sender, RoutedEventArgs e)
  24. {
  25. await LoadRemoteDetailsAsync();
  26. UpdateButtonStates();
  27. }
  28. private async Task LoadRemoteDetailsAsync()
  29. {
  30. ClearDetails();
  31. var device = await _agentApiService.GetDeviceInfoAsync(_baseAddress, _password, _localIPv4);
  32. if (device is not null)
  33. {
  34. RemoteDeviceIdTextBlock.Text = device.DeviceId;
  35. RemoteHostnameTextBlock.Text = device.Hostname;
  36. RemoteOsVersionTextBlock.Text = device.OSVersion;
  37. RemoteAgentVersionTextBlock.Text = device.AgentVersion;
  38. }
  39. var interfaces = await _agentApiService.GetInterfacesAsync(_baseAddress, _password, _localIPv4);
  40. if (interfaces is null)
  41. {
  42. RemoteSummaryTextBlock.Text = "设备已连接,但暂时无法读取 Linux 接口列表。";
  43. return;
  44. }
  45. RemoteSummaryTextBlock.Text = $"当前管理接口:{interfaces.ManagementInterface};建议目标接口:{interfaces.SuggestedTargetInterface};{(interfaces.RequiresTargetSelection ? "需要手动选择目标接口。" : "已自动识别建议目标接口。")}";
  46. var suggested = interfaces.Interfaces.FirstOrDefault(item => item.SystemName == interfaces.SuggestedTargetInterface)
  47. ?? interfaces.Interfaces.FirstOrDefault(item => item.IsSuggestedTarget)
  48. ?? interfaces.Interfaces.FirstOrDefault(item => !item.IsManagementInterface);
  49. RemoteTargetInterfaceComboBox.ItemsSource = interfaces.Interfaces;
  50. if (suggested is not null)
  51. {
  52. RemoteTargetInterfaceComboBox.SelectedItem = suggested;
  53. await LoadRemoteInterfaceConfigAsync(suggested.SystemName);
  54. }
  55. }
  56. private void ClearDetails()
  57. {
  58. RemoteDeviceIdTextBlock.Text = "-";
  59. RemoteHostnameTextBlock.Text = "-";
  60. RemoteOsVersionTextBlock.Text = "-";
  61. RemoteAgentVersionTextBlock.Text = "-";
  62. RemoteTargetInterfaceComboBox.ItemsSource = null;
  63. RemoteConfigInterfaceTextBlock.Text = "-";
  64. RemoteConfigIpTextBlock.Text = "-";
  65. RemoteConfigGatewayTextBlock.Text = "-";
  66. RemoteConfigDnsTextBlock.Text = "-";
  67. NewIpTextBox.Text = string.Empty;
  68. NewMaskTextBox.Text = string.Empty;
  69. NewGatewayTextBox.Text = string.Empty;
  70. NewDnsTextBox.Text = string.Empty;
  71. ConfigValidationTextBlock.Text = "点击 1/2/3 按顺序操作:先读取当前配置,再校验,最后应用。";
  72. _configValidated = false;
  73. }
  74. private async void RemoteTargetInterfaceComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  75. {
  76. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  77. {
  78. return;
  79. }
  80. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  81. }
  82. private async Task LoadRemoteInterfaceConfigAsync(string interfaceName)
  83. {
  84. var result = await _agentApiService.GetInterfaceConfigAsync(_baseAddress, _password, _localIPv4, interfaceName);
  85. if (!result.Success || result.Data is null)
  86. {
  87. RemoteConfigInterfaceTextBlock.Text = interfaceName;
  88. RemoteConfigIpTextBlock.Text = "读取失败";
  89. RemoteConfigGatewayTextBlock.Text = "读取失败";
  90. RemoteConfigDnsTextBlock.Text = "读取失败";
  91. ConfigValidationTextBlock.Text = $"读取目标接口 {interfaceName} 配置失败:{result.Message}";
  92. return;
  93. }
  94. var config = result.Data;
  95. RemoteConfigInterfaceTextBlock.Text = config.Interface;
  96. RemoteConfigIpTextBlock.Text = string.IsNullOrWhiteSpace(config.IP) ? "无" : $"{config.IP}/{config.Prefix}";
  97. RemoteConfigGatewayTextBlock.Text = string.IsNullOrWhiteSpace(config.Gateway) ? "无" : config.Gateway;
  98. RemoteConfigDnsTextBlock.Text = config.DnsSummary;
  99. _suppressConfigChangeHandling = true;
  100. NewIpTextBox.Text = config.IP;
  101. NewMaskTextBox.Text = PrefixToMask(config.Prefix);
  102. NewGatewayTextBox.Text = config.Gateway;
  103. NewDnsTextBox.Text = config.Dns.FirstOrDefault() ?? string.Empty;
  104. _suppressConfigChangeHandling = false;
  105. _configValidated = false;
  106. ConfigValidationTextBlock.Text = "已回填目标接口当前配置,可直接修改后校验。";
  107. UpdateButtonStates();
  108. }
  109. private async void ReloadInterfaceConfigButton_OnClick(object sender, RoutedEventArgs e)
  110. {
  111. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  112. {
  113. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  114. }
  115. }
  116. private async void ValidateConfigButton_OnClick(object sender, RoutedEventArgs e)
  117. {
  118. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  119. {
  120. return;
  121. }
  122. var request = BuildConfigRequest(selected.SystemName);
  123. if (request is null)
  124. {
  125. return;
  126. }
  127. var result = await _agentApiService.ValidateInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
  128. _configValidated = result.Success && result.Data?.Valid == true;
  129. if (result.Data is not null)
  130. {
  131. var warnings = result.Data.Warnings.Count > 0 ? $" 警告:{string.Join(";", result.Data.Warnings)}" : string.Empty;
  132. var errors = result.Data.Errors.Count > 0 ? $" 错误:{string.Join(";", result.Data.Errors)}" : string.Empty;
  133. ConfigValidationTextBlock.Text = result.Success ? $"校验通过。{warnings}" : $"校验失败。{errors}{warnings}";
  134. }
  135. else
  136. {
  137. ConfigValidationTextBlock.Text = $"校验失败:{result.Message}";
  138. }
  139. ConfigValidationTextBlock.Text = _configValidated ? "配置已通过校验,可提交应用。" : "当前配置尚未通过校验。";
  140. UpdateButtonStates();
  141. }
  142. private async void ApplyConfigButton_OnClick(object sender, RoutedEventArgs e)
  143. {
  144. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  145. {
  146. return;
  147. }
  148. var request = BuildConfigRequest(selected.SystemName);
  149. if (request is null)
  150. {
  151. return;
  152. }
  153. var confirmMessage = $"将要把以下配置应用到接口 {selected.SystemName}:\n\n" +
  154. $"IP:{request.IP}/{request.Prefix}\n" +
  155. $"网关:{(string.IsNullOrWhiteSpace(request.Gateway) ? "无" : request.Gateway)}\n" +
  156. $"DNS:{(request.Dns.Count == 0 ? "无" : string.Join(", ", request.Dns))}\n\n" +
  157. "请确认是否继续。";
  158. if (MessageBox.Show(this, confirmMessage, "确认应用配置", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK)
  159. {
  160. return;
  161. }
  162. var applyResult = await _agentApiService.ApplyInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
  163. if (!applyResult.Success || applyResult.Data is null)
  164. {
  165. ConfigValidationTextBlock.Text = $"提交配置任务失败:{applyResult.Message}";
  166. return;
  167. }
  168. ConfigValidationTextBlock.Text = $"配置任务已提交:{applyResult.Data.TaskId},正在轮询状态。";
  169. await PollTaskAsync(applyResult.Data.TaskId);
  170. }
  171. private async Task PollTaskAsync(string taskId)
  172. {
  173. var transientFailureCount = 0;
  174. for (var i = 0; i < 20; i++)
  175. {
  176. await Task.Delay(1000);
  177. var result = await _agentApiService.GetTaskAsync(_baseAddress, _password, _localIPv4, taskId);
  178. if (!result.Success || result.Data is null)
  179. {
  180. if (result.StatusCode is null)
  181. {
  182. transientFailureCount++;
  183. ConfigValidationTextBlock.Text = $"任务 {taskId} 轮询中,检测到短暂断连,正在重试({transientFailureCount})。";
  184. continue;
  185. }
  186. ConfigValidationTextBlock.Text = $"读取任务状态失败:{result.Message}";
  187. return;
  188. }
  189. transientFailureCount = 0;
  190. var task = result.Data;
  191. ConfigValidationTextBlock.Text = $"任务 {task.TaskId} / {task.Status} / {task.Step} / {task.Detail}";
  192. if (task.Status is "success" or "failed" or "rolled_back")
  193. {
  194. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  195. {
  196. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  197. }
  198. return;
  199. }
  200. }
  201. ConfigValidationTextBlock.Text = $"任务 {taskId} 轮询超时,请稍后手动刷新。";
  202. }
  203. private async void RebootButton_OnClick(object sender, RoutedEventArgs e)
  204. {
  205. await ExecuteSystemActionAsync(
  206. "重启设备",
  207. "设备将立即重启,当前窗口和连接可能马上中断。是否继续?",
  208. () => _agentApiService.RebootAsync(_baseAddress, _password, _localIPv4));
  209. }
  210. private async void ShutdownButton_OnClick(object sender, RoutedEventArgs e)
  211. {
  212. await ExecuteSystemActionAsync(
  213. "关闭设备",
  214. "设备将立即关机,当前窗口和连接可能马上中断。是否继续?",
  215. () => _agentApiService.ShutdownAsync(_baseAddress, _password, _localIPv4));
  216. }
  217. private async Task ExecuteSystemActionAsync(string title, string confirmMessage, Func<Task<ApiCallResult<RemoteSystemActionResponse>>> action)
  218. {
  219. if (MessageBox.Show(this, confirmMessage, title, MessageBoxButton.OKCancel, MessageBoxImage.Warning) != MessageBoxResult.OK)
  220. {
  221. return;
  222. }
  223. var result = await action();
  224. if (!result.Success || result.Data is null)
  225. {
  226. ConfigValidationTextBlock.Text = $"{title}失败:{result.Message}";
  227. return;
  228. }
  229. ConfigValidationTextBlock.Text = $"{title}任务已提交:{result.Data.TaskId}。命令已发出,设备可能立即断开。";
  230. }
  231. private RemoteInterfaceConfig? BuildConfigRequest(string interfaceName)
  232. {
  233. if (string.IsNullOrWhiteSpace(NewIpTextBox.Text))
  234. {
  235. ConfigValidationTextBlock.Text = "IP 地址不能为空。";
  236. return null;
  237. }
  238. if (!TryMaskToPrefix(NewMaskTextBox.Text, out var prefix))
  239. {
  240. ConfigValidationTextBlock.Text = "子网掩码格式不正确。";
  241. return null;
  242. }
  243. var dns = string.IsNullOrWhiteSpace(NewDnsTextBox.Text) ? Array.Empty<string>() : new[] { NewDnsTextBox.Text.Trim() };
  244. return new RemoteInterfaceConfig
  245. {
  246. Interface = interfaceName,
  247. IP = NewIpTextBox.Text.Trim(),
  248. Prefix = prefix,
  249. Gateway = NewGatewayTextBox.Text.Trim(),
  250. Dns = dns,
  251. };
  252. }
  253. private static string PrefixToMask(int prefix)
  254. {
  255. if (prefix < 0 || prefix > 32)
  256. {
  257. return string.Empty;
  258. }
  259. var mask = prefix == 0 ? 0u : uint.MaxValue << (32 - prefix);
  260. return string.Join('.', new[] { (mask >> 24) & 255, (mask >> 16) & 255, (mask >> 8) & 255, mask & 255 });
  261. }
  262. private static bool TryMaskToPrefix(string maskText, out int prefix)
  263. {
  264. prefix = 0;
  265. if (string.IsNullOrWhiteSpace(maskText))
  266. {
  267. return false;
  268. }
  269. var parts = maskText.Trim().Split('.');
  270. if (parts.Length != 4)
  271. {
  272. return false;
  273. }
  274. uint mask = 0;
  275. foreach (var part in parts)
  276. {
  277. if (!byte.TryParse(part, out var octet))
  278. {
  279. return false;
  280. }
  281. mask = (mask << 8) | octet;
  282. }
  283. var seenZero = false;
  284. for (var i = 31; i >= 0; i--)
  285. {
  286. var bit = (mask & (1u << i)) != 0;
  287. if (bit && seenZero)
  288. {
  289. return false;
  290. }
  291. if (bit)
  292. {
  293. prefix++;
  294. }
  295. else
  296. {
  297. seenZero = true;
  298. }
  299. }
  300. return true;
  301. }
  302. private void ConfigInputChanged_OnChanged(object sender, TextChangedEventArgs e)
  303. {
  304. if (_suppressConfigChangeHandling)
  305. {
  306. return;
  307. }
  308. _configValidated = false;
  309. ConfigValidationTextBlock.Text = "配置内容已变更,请重新点击“2. 校验配置”。";
  310. UpdateButtonStates();
  311. }
  312. private void UpdateButtonStates()
  313. {
  314. ReloadInterfaceConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  315. ValidateConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  316. ApplyConfigButton.IsEnabled = _configValidated && RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  317. }
  318. }