| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365 |
- using System.Globalization;
- using System.Windows;
- using System.Windows.Controls;
- using QuickIP.Client.Models;
- using QuickIP.Client.Services;
- namespace QuickIP.Client;
- public partial class DeviceDetailsWindow : Window
- {
- private readonly AgentApiService _agentApiService = new();
- private readonly string _baseAddress;
- private readonly string _localIPv4;
- private readonly string _password;
- private bool _configValidated;
- private bool _suppressConfigChangeHandling;
- public DeviceDetailsWindow(string baseAddress, string localIPv4, string password)
- {
- InitializeComponent();
- _baseAddress = baseAddress;
- _localIPv4 = localIPv4;
- _password = password;
- Loaded += DeviceDetailsWindow_OnLoaded;
- }
- private async void DeviceDetailsWindow_OnLoaded(object sender, RoutedEventArgs e)
- {
- await LoadRemoteDetailsAsync();
- UpdateButtonStates();
- }
- private async Task LoadRemoteDetailsAsync()
- {
- ClearDetails();
- var device = await _agentApiService.GetDeviceInfoAsync(_baseAddress, _password, _localIPv4);
- if (device is not null)
- {
- RemoteDeviceIdTextBlock.Text = device.DeviceId;
- RemoteHostnameTextBlock.Text = device.Hostname;
- RemoteOsVersionTextBlock.Text = device.OSVersion;
- RemoteAgentVersionTextBlock.Text = device.AgentVersion;
- }
- var interfaces = await _agentApiService.GetInterfacesAsync(_baseAddress, _password, _localIPv4);
- if (interfaces is null)
- {
- RemoteSummaryTextBlock.Text = "设备已连接,但暂时无法读取 Linux 接口列表。";
- return;
- }
- RemoteSummaryTextBlock.Text = $"当前管理接口:{interfaces.ManagementInterface};建议目标接口:{interfaces.SuggestedTargetInterface};{(interfaces.RequiresTargetSelection ? "需要手动选择目标接口。" : "已自动识别建议目标接口。")}";
- var suggested = interfaces.Interfaces.FirstOrDefault(item => item.SystemName == interfaces.SuggestedTargetInterface)
- ?? interfaces.Interfaces.FirstOrDefault(item => item.IsSuggestedTarget)
- ?? interfaces.Interfaces.FirstOrDefault(item => !item.IsManagementInterface);
- RemoteTargetInterfaceComboBox.ItemsSource = interfaces.Interfaces;
- if (suggested is not null)
- {
- RemoteTargetInterfaceComboBox.SelectedItem = suggested;
- await LoadRemoteInterfaceConfigAsync(suggested.SystemName);
- }
- }
- private void ClearDetails()
- {
- RemoteDeviceIdTextBlock.Text = "-";
- RemoteHostnameTextBlock.Text = "-";
- RemoteOsVersionTextBlock.Text = "-";
- RemoteAgentVersionTextBlock.Text = "-";
- RemoteTargetInterfaceComboBox.ItemsSource = null;
- RemoteConfigInterfaceTextBlock.Text = "-";
- RemoteConfigIpTextBlock.Text = "-";
- RemoteConfigGatewayTextBlock.Text = "-";
- RemoteConfigDnsTextBlock.Text = "-";
- NewIpTextBox.Text = string.Empty;
- NewMaskTextBox.Text = string.Empty;
- NewGatewayTextBox.Text = string.Empty;
- NewDnsTextBox.Text = string.Empty;
- ConfigValidationTextBlock.Text = "点击 1/2/3 按顺序操作:先读取当前配置,再校验,最后应用。";
- _configValidated = false;
- }
- private async void RemoteTargetInterfaceComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
- {
- return;
- }
- await LoadRemoteInterfaceConfigAsync(selected.SystemName);
- }
- private async Task LoadRemoteInterfaceConfigAsync(string interfaceName)
- {
- var result = await _agentApiService.GetInterfaceConfigAsync(_baseAddress, _password, _localIPv4, interfaceName);
- if (!result.Success || result.Data is null)
- {
- RemoteConfigInterfaceTextBlock.Text = interfaceName;
- RemoteConfigIpTextBlock.Text = "读取失败";
- RemoteConfigGatewayTextBlock.Text = "读取失败";
- RemoteConfigDnsTextBlock.Text = "读取失败";
- ConfigValidationTextBlock.Text = $"读取目标接口 {interfaceName} 配置失败:{result.Message}";
- return;
- }
- var config = result.Data;
- RemoteConfigInterfaceTextBlock.Text = config.Interface;
- RemoteConfigIpTextBlock.Text = string.IsNullOrWhiteSpace(config.IP) ? "无" : $"{config.IP}/{config.Prefix}";
- RemoteConfigGatewayTextBlock.Text = string.IsNullOrWhiteSpace(config.Gateway) ? "无" : config.Gateway;
- RemoteConfigDnsTextBlock.Text = config.DnsSummary;
- _suppressConfigChangeHandling = true;
- NewIpTextBox.Text = config.IP;
- NewMaskTextBox.Text = PrefixToMask(config.Prefix);
- NewGatewayTextBox.Text = config.Gateway;
- NewDnsTextBox.Text = config.Dns.FirstOrDefault() ?? string.Empty;
- _suppressConfigChangeHandling = false;
- _configValidated = false;
- ConfigValidationTextBlock.Text = "已回填目标接口当前配置,可直接修改后校验。";
- UpdateButtonStates();
- }
- private async void ReloadInterfaceConfigButton_OnClick(object sender, RoutedEventArgs e)
- {
- if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
- {
- await LoadRemoteInterfaceConfigAsync(selected.SystemName);
- }
- }
- private async void ValidateConfigButton_OnClick(object sender, RoutedEventArgs e)
- {
- if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
- {
- return;
- }
- var request = BuildConfigRequest(selected.SystemName);
- if (request is null)
- {
- return;
- }
- var result = await _agentApiService.ValidateInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
- _configValidated = result.Success && result.Data?.Valid == true;
- if (result.Data is not null)
- {
- var warnings = result.Data.Warnings.Count > 0 ? $" 警告:{string.Join(";", result.Data.Warnings)}" : string.Empty;
- var errors = result.Data.Errors.Count > 0 ? $" 错误:{string.Join(";", result.Data.Errors)}" : string.Empty;
- ConfigValidationTextBlock.Text = result.Success ? $"校验通过。{warnings}" : $"校验失败。{errors}{warnings}";
- }
- else
- {
- ConfigValidationTextBlock.Text = $"校验失败:{result.Message}";
- }
- ConfigValidationTextBlock.Text = _configValidated ? "配置已通过校验,可提交应用。" : "当前配置尚未通过校验。";
- UpdateButtonStates();
- }
- private async void ApplyConfigButton_OnClick(object sender, RoutedEventArgs e)
- {
- if (RemoteTargetInterfaceComboBox.SelectedItem is not RemoteInterfaceInfo selected)
- {
- return;
- }
- var request = BuildConfigRequest(selected.SystemName);
- if (request is null)
- {
- return;
- }
- var confirmMessage = $"将要把以下配置应用到接口 {selected.SystemName}:\n\n" +
- $"IP:{request.IP}/{request.Prefix}\n" +
- $"网关:{(string.IsNullOrWhiteSpace(request.Gateway) ? "无" : request.Gateway)}\n" +
- $"DNS:{(request.Dns.Count == 0 ? "无" : string.Join(", ", request.Dns))}\n\n" +
- "请确认是否继续。";
- if (MessageBox.Show(this, confirmMessage, "确认应用配置", MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK)
- {
- return;
- }
- var applyResult = await _agentApiService.ApplyInterfaceConfigAsync(_baseAddress, _password, _localIPv4, request);
- if (!applyResult.Success || applyResult.Data is null)
- {
- ConfigValidationTextBlock.Text = $"提交配置任务失败:{applyResult.Message}";
- return;
- }
- ConfigValidationTextBlock.Text = $"配置任务已提交:{applyResult.Data.TaskId},正在轮询状态。";
- await PollTaskAsync(applyResult.Data.TaskId);
- }
- private async Task PollTaskAsync(string taskId)
- {
- var transientFailureCount = 0;
- for (var i = 0; i < 20; i++)
- {
- await Task.Delay(1000);
- var result = await _agentApiService.GetTaskAsync(_baseAddress, _password, _localIPv4, taskId);
- if (!result.Success || result.Data is null)
- {
- if (result.StatusCode is null)
- {
- transientFailureCount++;
- ConfigValidationTextBlock.Text = $"任务 {taskId} 轮询中,检测到短暂断连,正在重试({transientFailureCount})。";
- continue;
- }
- ConfigValidationTextBlock.Text = $"读取任务状态失败:{result.Message}";
- return;
- }
- transientFailureCount = 0;
- var task = result.Data;
- ConfigValidationTextBlock.Text = $"任务 {task.TaskId} / {task.Status} / {task.Step} / {task.Detail}";
- if (task.Status is "success" or "failed" or "rolled_back")
- {
- if (RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo selected)
- {
- await LoadRemoteInterfaceConfigAsync(selected.SystemName);
- }
- return;
- }
- }
- ConfigValidationTextBlock.Text = $"任务 {taskId} 轮询超时,请稍后手动刷新。";
- }
- private async void RebootButton_OnClick(object sender, RoutedEventArgs e)
- {
- await ExecuteSystemActionAsync(
- "重启设备",
- "设备将立即重启,当前窗口和连接可能马上中断。是否继续?",
- () => _agentApiService.RebootAsync(_baseAddress, _password, _localIPv4));
- }
- private async void ShutdownButton_OnClick(object sender, RoutedEventArgs e)
- {
- await ExecuteSystemActionAsync(
- "关闭设备",
- "设备将立即关机,当前窗口和连接可能马上中断。是否继续?",
- () => _agentApiService.ShutdownAsync(_baseAddress, _password, _localIPv4));
- }
- private async Task ExecuteSystemActionAsync(string title, string confirmMessage, Func<Task<ApiCallResult<RemoteSystemActionResponse>>> action)
- {
- if (MessageBox.Show(this, confirmMessage, title, MessageBoxButton.OKCancel, MessageBoxImage.Warning) != MessageBoxResult.OK)
- {
- return;
- }
- var result = await action();
- if (!result.Success || result.Data is null)
- {
- ConfigValidationTextBlock.Text = $"{title}失败:{result.Message}";
- return;
- }
- ConfigValidationTextBlock.Text = $"{title}任务已提交:{result.Data.TaskId}。命令已发出,设备可能立即断开。";
- }
- private RemoteInterfaceConfig? BuildConfigRequest(string interfaceName)
- {
- if (string.IsNullOrWhiteSpace(NewIpTextBox.Text))
- {
- ConfigValidationTextBlock.Text = "IP 地址不能为空。";
- return null;
- }
- if (!TryMaskToPrefix(NewMaskTextBox.Text, out var prefix))
- {
- ConfigValidationTextBlock.Text = "子网掩码格式不正确。";
- return null;
- }
- var dns = string.IsNullOrWhiteSpace(NewDnsTextBox.Text) ? Array.Empty<string>() : new[] { NewDnsTextBox.Text.Trim() };
- return new RemoteInterfaceConfig
- {
- Interface = interfaceName,
- IP = NewIpTextBox.Text.Trim(),
- Prefix = prefix,
- Gateway = NewGatewayTextBox.Text.Trim(),
- Dns = dns,
- };
- }
- private static string PrefixToMask(int prefix)
- {
- if (prefix < 0 || prefix > 32)
- {
- return string.Empty;
- }
- var mask = prefix == 0 ? 0u : uint.MaxValue << (32 - prefix);
- return string.Join('.', new[] { (mask >> 24) & 255, (mask >> 16) & 255, (mask >> 8) & 255, mask & 255 });
- }
- private static bool TryMaskToPrefix(string maskText, out int prefix)
- {
- prefix = 0;
- if (string.IsNullOrWhiteSpace(maskText))
- {
- return false;
- }
- var parts = maskText.Trim().Split('.');
- if (parts.Length != 4)
- {
- return false;
- }
- uint mask = 0;
- foreach (var part in parts)
- {
- if (!byte.TryParse(part, out var octet))
- {
- return false;
- }
- mask = (mask << 8) | octet;
- }
- var seenZero = false;
- for (var i = 31; i >= 0; i--)
- {
- var bit = (mask & (1u << i)) != 0;
- if (bit && seenZero)
- {
- return false;
- }
- if (bit)
- {
- prefix++;
- }
- else
- {
- seenZero = true;
- }
- }
- return true;
- }
- private void ConfigInputChanged_OnChanged(object sender, TextChangedEventArgs e)
- {
- if (_suppressConfigChangeHandling)
- {
- return;
- }
- _configValidated = false;
- ConfigValidationTextBlock.Text = "配置内容已变更,请重新点击“2. 校验配置”。";
- UpdateButtonStates();
- }
- private void UpdateButtonStates()
- {
- ReloadInterfaceConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
- ValidateConfigButton.IsEnabled = RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
- ApplyConfigButton.IsEnabled = _configValidated && RemoteTargetInterfaceComboBox.SelectedItem is RemoteInterfaceInfo;
- }
- }
|