DeviceDetailsWindow.xaml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. ApplyTaskStatusTextBlock.Text = "尚未提交配置任务。";
  73. _configValidated = false;
  74. }
  75. private async void RemoteTargetInterfaceComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  76. {
  77. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  78. {
  79. return;
  80. }
  81. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  82. }
  83. private async Task LoadRemoteInterfaceConfigAsync(string interfaceName)
  84. {
  85. var result = await _agentApiService.GetInterfaceConfigAsync(_baseAddress, _password, _localIPv4, interfaceName);
  86. if (!result.Success || result.Data is null)
  87. {
  88. RemoteConfigInterfaceTextBlock.Text = interfaceName;
  89. RemoteConfigIpTextBlock.Text = "读取失败";
  90. RemoteConfigGatewayTextBlock.Text = "读取失败";
  91. RemoteConfigDnsTextBlock.Text = "读取失败";
  92. ConfigValidationTextBlock.Text = $"读取目标接口 {interfaceName} 配置失败:{result.Message}";
  93. return;
  94. }
  95. var config = result.Data;
  96. RemoteConfigInterfaceTextBlock.Text = config.Interface;
  97. RemoteConfigIpTextBlock.Text = string.IsNullOrWhiteSpace(config.IP) ? "无" : $"{config.IP}/{config.Prefix}";
  98. RemoteConfigGatewayTextBlock.Text = string.IsNullOrWhiteSpace(config.Gateway) ? "无" : config.Gateway;
  99. RemoteConfigDnsTextBlock.Text = config.DnsSummary;
  100. _suppressConfigChangeHandling = true;
  101. NewIpTextBox.Text = config.IP;
  102. NewMaskTextBox.Text = PrefixToMask(config.Prefix);
  103. NewGatewayTextBox.Text = config.Gateway;
  104. NewDnsTextBox.Text = config.Dns.FirstOrDefault() ?? string.Empty;
  105. _suppressConfigChangeHandling = false;
  106. _configValidated = false;
  107. ConfigValidationTextBlock.Text = "已回填目标接口当前配置,可直接修改后校验。";
  108. ApplyTaskStatusTextBlock.Text = "尚未提交配置任务。";
  109. UpdateButtonStates();
  110. }
  111. private async void ReloadInterfaceConfigButton_OnClick(object sender, RoutedEventArgs e)
  112. {
  113. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  114. {
  115. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  116. }
  117. }
  118. private async void ValidateConfigButton_OnClick(object sender, RoutedEventArgs e)
  119. {
  120. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  121. {
  122. return;
  123. }
  124. var request = BuildConfigRequest(selected.SystemName);
  125. if (request is null)
  126. {
  127. return;
  128. }
  129. var result = await _agentApiService.ValidateInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
  130. _configValidated = result.Success && result.Data?.Valid == true;
  131. if (result.Data is not null)
  132. {
  133. var warnings = result.Data.Warnings.Count > 0 ? $" 警告:{string.Join(";", result.Data.Warnings)}" : string.Empty;
  134. var errors = result.Data.Errors.Count > 0 ? $" 错误:{string.Join(";", result.Data.Errors)}" : string.Empty;
  135. ConfigValidationTextBlock.Text = result.Success ? $"校验通过。{warnings}" : $"校验失败。{errors}{warnings}";
  136. }
  137. else
  138. {
  139. ConfigValidationTextBlock.Text = $"校验失败:{result.Message}";
  140. }
  141. ApplyTaskStatusTextBlock.Text = _configValidated ? "配置已通过校验,可提交应用。" : "当前配置尚未通过校验。";
  142. UpdateButtonStates();
  143. }
  144. private async void ApplyConfigButton_OnClick(object sender, RoutedEventArgs e)
  145. {
  146. if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
  147. {
  148. return;
  149. }
  150. var request = BuildConfigRequest(selected.SystemName);
  151. if (request is null)
  152. {
  153. return;
  154. }
  155. var confirmMessage = $"将要把以下配置应用到接口 {selected.SystemName}:\n\n" +
  156. $"IP:{request.IP}/{request.Prefix}\n" +
  157. $"网关:{(string.IsNullOrWhiteSpace(request.Gateway) ? "无" : request.Gateway)}\n" +
  158. $"DNS:{(request.Dns.Count == 0 ? "无" : string.Join(", ", request.Dns))}\n\n" +
  159. "请确认是否继续。";
  160. if (MessageBox.Show(this, confirmMessage, "确认应用配置", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK)
  161. {
  162. return;
  163. }
  164. var applyResult = await _agentApiService.ApplyInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
  165. if (!applyResult.Success || applyResult.Data is null)
  166. {
  167. ApplyTaskStatusTextBlock.Text = $"提交配置任务失败:{applyResult.Message}";
  168. return;
  169. }
  170. ApplyTaskStatusTextBlock.Text = $"配置任务已提交:{applyResult.Data.TaskId},正在轮询状态。";
  171. await PollTaskAsync(applyResult.Data.TaskId);
  172. }
  173. private async Task PollTaskAsync(string taskId)
  174. {
  175. var transientFailureCount = 0;
  176. for (var i = 0; i < 20; i++)
  177. {
  178. await Task.Delay(1000);
  179. var result = await _agentApiService.GetTaskAsync(_baseAddress, _password, _localIPv4, taskId);
  180. if (!result.Success || result.Data is null)
  181. {
  182. if (result.StatusCode is null)
  183. {
  184. transientFailureCount++;
  185. ApplyTaskStatusTextBlock.Text = $"任务 {taskId} 轮询中,检测到短暂断连,正在重试({transientFailureCount})。";
  186. continue;
  187. }
  188. ApplyTaskStatusTextBlock.Text = $"读取任务状态失败:{result.Message}";
  189. return;
  190. }
  191. transientFailureCount = 0;
  192. var task = result.Data;
  193. ApplyTaskStatusTextBlock.Text = $"任务 {task.TaskId} / {task.Status} / {task.Step} / {task.Detail}";
  194. if (task.Status is "success" or "failed" or "rolled_back")
  195. {
  196. if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
  197. {
  198. await LoadRemoteInterfaceConfigAsync(selected.SystemName);
  199. }
  200. return;
  201. }
  202. }
  203. ApplyTaskStatusTextBlock.Text = $"任务 {taskId} 轮询超时,请稍后手动刷新。";
  204. }
  205. private async void RebootButton_OnClick(object sender, RoutedEventArgs e)
  206. {
  207. await ExecuteSystemActionAsync(
  208. "重启设备",
  209. "设备将立即重启,当前窗口和连接可能马上中断。是否继续?",
  210. () => _agentApiService.RebootAsync(_baseAddress, _password, _localIPv4));
  211. }
  212. private async void ShutdownButton_OnClick(object sender, RoutedEventArgs e)
  213. {
  214. await ExecuteSystemActionAsync(
  215. "关闭设备",
  216. "设备将立即关机,当前窗口和连接可能马上中断。是否继续?",
  217. () => _agentApiService.ShutdownAsync(_baseAddress, _password, _localIPv4));
  218. }
  219. private async Task ExecuteSystemActionAsync(string title, string confirmMessage, Func<Task<ApiCallResult<RemoteSystemActionResponse>>> action)
  220. {
  221. if (MessageBox.Show(this, confirmMessage, title, MessageBoxButton.OKCancel, MessageBoxImage.Warning) != MessageBoxResult.OK)
  222. {
  223. return;
  224. }
  225. var result = await action();
  226. if (!result.Success || result.Data is null)
  227. {
  228. ApplyTaskStatusTextBlock.Text = $"{title}失败:{result.Message}";
  229. return;
  230. }
  231. ApplyTaskStatusTextBlock.Text = $"{title}任务已提交:{result.Data.TaskId}。命令已发出,设备可能立即断开。";
  232. }
  233. private RemoteInterfaceConfig? BuildConfigRequest(string interfaceName)
  234. {
  235. if (string.IsNullOrWhiteSpace(NewIpTextBox.Text))
  236. {
  237. ConfigValidationTextBlock.Text = "IP 地址不能为空。";
  238. return null;
  239. }
  240. if (!TryMaskToPrefix(NewMaskTextBox.Text, out var prefix))
  241. {
  242. ConfigValidationTextBlock.Text = "子网掩码格式不正确。";
  243. return null;
  244. }
  245. var dns = string.IsNullOrWhiteSpace(NewDnsTextBox.Text) ? Array.Empty<string>() : new[] { NewDnsTextBox.Text.Trim() };
  246. return new RemoteInterfaceConfig
  247. {
  248. Interface = interfaceName,
  249. IP = NewIpTextBox.Text.Trim(),
  250. Prefix = prefix,
  251. Gateway = NewGatewayTextBox.Text.Trim(),
  252. Dns = dns,
  253. };
  254. }
  255. private static string PrefixToMask(int prefix)
  256. {
  257. if (prefix < 0 || prefix > 32)
  258. {
  259. return string.Empty;
  260. }
  261. var mask = prefix == 0 ? 0u : uint.MaxValue << (32 - prefix);
  262. return string.Join('.', new[] { (mask >> 24) & 255, (mask >> 16) & 255, (mask >> 8) & 255, mask & 255 });
  263. }
  264. private static bool TryMaskToPrefix(string maskText, out int prefix)
  265. {
  266. prefix = 0;
  267. if (string.IsNullOrWhiteSpace(maskText))
  268. {
  269. return false;
  270. }
  271. var parts = maskText.Trim().Split('.');
  272. if (parts.Length != 4)
  273. {
  274. return false;
  275. }
  276. uint mask = 0;
  277. foreach (var part in parts)
  278. {
  279. if (!byte.TryParse(part, out var octet))
  280. {
  281. return false;
  282. }
  283. mask = (mask << 8) | octet;
  284. }
  285. var seenZero = false;
  286. for (var i = 31; i >= 0; i--)
  287. {
  288. var bit = (mask & (1u << i)) != 0;
  289. if (bit && seenZero)
  290. {
  291. return false;
  292. }
  293. if (bit)
  294. {
  295. prefix++;
  296. }
  297. else
  298. {
  299. seenZero = true;
  300. }
  301. }
  302. return true;
  303. }
  304. private void ConfigInputChanged_OnChanged(object sender, TextChangedEventArgs e)
  305. {
  306. if (_suppressConfigChangeHandling)
  307. {
  308. return;
  309. }
  310. _configValidated = false;
  311. ConfigValidationTextBlock.Text = "配置内容已变更,请重新点击“2. 校验配置”。";
  312. ApplyTaskStatusTextBlock.Text = "当前配置尚未通过校验。";
  313. UpdateButtonStates();
  314. }
  315. private void UpdateButtonStates()
  316. {
  317. ReloadInterfaceConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  318. ValidateConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  319. ApplyConfigButton.IsEnabled = _configValidated && RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
  320. }
  321. }