| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400 |
- using System.Collections.Generic;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Threading;
- using NetworkTool.Client.Models;
- using NetworkTool.Client.Services;
- namespace NetworkTool.Client;
- public partial class MainWindow : Window
- {
- private readonly NetworkAdapterService _networkAdapterService = new();
- private readonly PasswordStoreService _passwordStoreService = new();
- private readonly DiscoveryService _discoveryService = new();
- private readonly ServerApiService _serverApiService = new();
- private IReadOnlyList<AdapterInfo> _allAdapters = [];
- private IReadOnlyList<AdapterInfo> _adapters = [];
- private IReadOnlyList<DiscoveredDevice> _discoveredDevices = [];
- private bool _isBusy;
- private CancellationTokenSource? _statusMessageCts;
- public MainWindow()
- {
- InitializeComponent();
- Loaded += MainWindow_OnLoaded;
- }
- private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
- {
- LoadInitialState();
- }
- private void LoadInitialState()
- {
- _allAdapters = _networkAdapterService.GetAdapters();
- ApplyAdapterFilter();
- UpdateButtonStates();
- }
- private void ApplyAdapterFilter(string? selectedAdapterId = null)
- {
- _adapters = _allAdapters
- .Where(adapter => ShowUsableAdaptersOnlyCheckBox.IsChecked != true || IsUsableAdapter(adapter))
- .OrderByDescending(adapter => adapter.RecommendationScore)
- .ThenBy(adapter => adapter.Name)
- .ToList();
- AdapterComboBox.ItemsSource = _adapters;
- var selected = selectedAdapterId is null
- ? _networkAdapterService.GetRecommendedAdapter(_adapters)
- : _adapters.FirstOrDefault(adapter => adapter.Id == selectedAdapterId) ?? _networkAdapterService.GetRecommendedAdapter(_adapters);
- if (selected is not null)
- {
- AdapterComboBox.SelectedItem = selected;
- }
- else if (_adapters.Count > 0)
- {
- AdapterComboBox.SelectedIndex = 0;
- }
- }
- private static bool IsUsableAdapter(AdapterInfo adapter)
- {
- return adapter.HasLink && !string.IsNullOrWhiteSpace(adapter.IPv4Address);
- }
- private void AdapterComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- if (AdapterComboBox.SelectedItem is not AdapterInfo adapter)
- {
- ClearDiscoveredDevices();
- SetStatus("请选择一块网卡。", StatusMessageType.Warning, false);
- UpdateButtonStates();
- return;
- }
- if (!adapter.HasLink)
- {
- ClearDiscoveredDevices();
- SetStatus("当前网卡未检测到链路,请检查网线连接。", StatusMessageType.Warning, true);
- UpdateButtonStates();
- return;
- }
- UpdateButtonStates();
- _ = SearchDevicesAsync(adapter);
- }
- private async void RefreshAdaptersButton_OnClick(object sender, RoutedEventArgs e)
- {
- SetBusyState(true, "正在刷新本机网卡...");
- try
- {
- RefreshAdapters();
- SetStatus("已刷新本机网卡。", StatusMessageType.Success, true);
- }
- catch (Exception ex)
- {
- SetStatus($"刷新本机网卡失败:{ex.Message}", StatusMessageType.Error, true);
- MessageBox.Show(this, ex.Message, "刷新失败", MessageBoxButton.OK, MessageBoxImage.Error);
- }
- finally
- {
- SetBusyState(false);
- }
- if (AdapterComboBox.SelectedItem is AdapterInfo adapter)
- {
- await SearchDevicesAsync(adapter);
- }
- }
- private async void SearchDevicesButton_OnClick(object sender, RoutedEventArgs e)
- {
- if (AdapterComboBox.SelectedItem is AdapterInfo adapter)
- {
- await SearchDevicesAsync(adapter);
- }
- else
- {
- SetStatus("请先选择一块网卡。", StatusMessageType.Warning, true);
- }
- }
- private void ShowUsableAdaptersOnlyCheckBox_OnChanged(object sender, RoutedEventArgs e)
- {
- if (AdapterComboBox is null || ShowUsableAdaptersOnlyCheckBox is null)
- {
- return;
- }
- var selectedAdapterId = (AdapterComboBox.SelectedItem as AdapterInfo)?.Id;
- ApplyAdapterFilter(selectedAdapterId);
- UpdateButtonStates();
- }
- private async Task SearchDevicesAsync(AdapterInfo adapter)
- {
- if (_isBusy)
- {
- return;
- }
- if (string.IsNullOrWhiteSpace(adapter.IPv4Address))
- {
- ClearDiscoveredDevices();
- SetStatus("当前网卡没有可用 IPv4,无法搜索设备。", StatusMessageType.Error, true);
- return;
- }
- if (!adapter.HasLink)
- {
- ClearDiscoveredDevices();
- SetStatus("当前网卡未检测到链路,请检查网线连接。", StatusMessageType.Warning, true);
- return;
- }
- SetBusyState(true, "正在搜索设备...");
- ClearDiscoveredDevices();
- await Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.Render);
- try
- {
- _discoveredDevices = await _discoveryService.DiscoverManyAsync(adapter.IPv4Address);
- DiscoveredDevicesListView.ItemsSource = _discoveredDevices;
- if (_discoveredDevices.Count == 0)
- {
- SetStatus("未发现 169.254 开头的设备 IP,请确认网卡、网线、远端服务和维护网段配置。", StatusMessageType.Warning, true);
- return;
- }
- SetStatus($"已发现 {_discoveredDevices.Count} 台设备,请双击 IP 连接。", StatusMessageType.Success, true);
- }
- catch (Exception ex)
- {
- SetStatus($"搜索设备失败:{ex.Message}", StatusMessageType.Error, true);
- MessageBox.Show(this, ex.Message, "搜索设备失败", MessageBoxButton.OK, MessageBoxImage.Error);
- }
- finally
- {
- SetBusyState(false);
- }
- }
- private void SavePasswordForDevice(DiscoveredDevice device, string password)
- {
- var deviceKey = GetDevicePasswordKey(device);
- if (!string.IsNullOrWhiteSpace(deviceKey) && !string.IsNullOrWhiteSpace(password))
- {
- _passwordStoreService.SavePassword(deviceKey, password);
- }
- }
- private void UpdateButtonStates()
- {
- var adapter = AdapterComboBox.SelectedItem as AdapterInfo;
- var hasAdapter = adapter is not null;
- RefreshAdaptersButton.IsEnabled = !_isBusy;
- SearchDevicesButton.IsEnabled = !_isBusy && hasAdapter && adapter!.HasLink;
- }
- private void RefreshAdapters(string? selectedAdapterId = null)
- {
- _allAdapters = _networkAdapterService.GetAdapters();
- ApplyAdapterFilter(selectedAdapterId);
- }
- private void ClearDiscoveredDevices()
- {
- _discoveredDevices = [];
- DiscoveredDevicesListView.ItemsSource = _discoveredDevices;
- }
- private async void DiscoveredDevicesListView_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
- {
- if (!_isBusy && DiscoveredDevicesListView.SelectedItem is DiscoveredDevice device)
- {
- await ConnectToDeviceAsync(device);
- }
- }
- private void DiscoveredDevicesListView_OnSizeChanged(object sender, SizeChangedEventArgs e)
- {
- var availableWidth = DiscoveredDevicesListView.ActualWidth - 36;
- if (availableWidth <= 0)
- {
- return;
- }
- DeviceIpColumn.Width = Math.Max(130, availableWidth * 0.26);
- DeviceHostnameColumn.Width = Math.Max(150, availableWidth * 0.30);
- DeviceMacColumn.Width = Math.Max(180, availableWidth - DeviceIpColumn.Width - DeviceHostnameColumn.Width);
- }
- private async Task ConnectToDeviceAsync(DiscoveredDevice device)
- {
- var deviceKey = GetDevicePasswordKey(device);
- var savedPassword = _passwordStoreService.LoadPassword(deviceKey);
- var password = string.Empty;
- if (!string.IsNullOrWhiteSpace(savedPassword))
- {
- password = savedPassword;
- }
- else if (!TryPromptForPassword(device, out savedPassword))
- {
- return;
- }
- else
- {
- password = savedPassword;
- }
- if (string.IsNullOrWhiteSpace(password))
- {
- SetStatus("请输入管理密码。", StatusMessageType.Warning, true);
- return;
- }
- var selectedAdapter = AdapterComboBox.SelectedItem as AdapterInfo;
- SetBusyState(true, $"正在连接 {device.Lan2Ip}...");
- try
- {
- var baseAddress = $"http://{device.Lan2Ip}:48888";
- var result = await _serverApiService.CheckHealthAsync(baseAddress, password, selectedAdapter?.IPv4Address ?? string.Empty);
- if (result.Success)
- {
- SavePasswordForDevice(device, password);
- SetStatus("连接成功。", StatusMessageType.Success, true);
- OpenDeviceDetailsWindow(baseAddress, selectedAdapter?.IPv4Address ?? string.Empty, password);
- return;
- }
- if (result.StatusCode == 401)
- {
- SetStatus("管理密码错误,请确认密码是否正确。", StatusMessageType.Error, true);
- MessageBox.Show(this, "管理密码校验失败,请确认密码是否正确。", "密码错误", MessageBoxButton.OK, MessageBoxImage.Warning);
- return;
- }
- SetStatus($"设备已发现,但 HTTP 验证失败:{result.Message}", StatusMessageType.Error, true);
- }
- catch (Exception ex)
- {
- SetStatus($"连接失败:{ex.Message}", StatusMessageType.Error, true);
- MessageBox.Show(this, ex.Message, "连接失败", MessageBoxButton.OK, MessageBoxImage.Error);
- }
- finally
- {
- SetBusyState(false);
- }
- }
- private void OpenDeviceDetailsWindow(string baseAddress, string localIPv4, string password)
- {
- var window = new DeviceDetailsWindow(baseAddress, localIPv4, password)
- {
- Owner = this,
- };
- window.ShowDialog();
- }
- private bool TryPromptForPassword(DiscoveredDevice device, out string password)
- {
- var label = string.IsNullOrWhiteSpace(device.Mac) ? device.Lan2Ip : device.Mac;
- var window = new PasswordPromptWindow(label)
- {
- Owner = this,
- };
- if (window.ShowDialog() == true)
- {
- password = window.Password;
- return true;
- }
- password = string.Empty;
- return false;
- }
- private static string GetDevicePasswordKey(DiscoveredDevice device)
- {
- if (!string.IsNullOrWhiteSpace(device.Mac))
- {
- return device.Mac;
- }
- return device.DeviceId;
- }
- private void SetStatus(string message, StatusMessageType type, bool addLog)
- {
- ApplyStatusMessageStyle(type);
- StatusTextBlock.Text = message;
- StatusMessageBorder.Opacity = 0;
- StatusMessageBorder.Visibility = Visibility.Visible;
- StatusMessageBorder.BeginAnimation(OpacityProperty, new DoubleAnimation(1, TimeSpan.FromMilliseconds(160)));
- _statusMessageCts?.Cancel();
- _statusMessageCts = new CancellationTokenSource();
- _ = HideStatusMessageAsync(_statusMessageCts.Token);
- _ = addLog;
- }
- private async Task HideStatusMessageAsync(CancellationToken cancellationToken)
- {
- try
- {
- await Task.Delay(3000, cancellationToken);
- await Dispatcher.InvokeAsync(() =>
- {
- var animation = new DoubleAnimation(0, TimeSpan.FromMilliseconds(200));
- animation.Completed += (_, _) =>
- {
- if (!cancellationToken.IsCancellationRequested)
- {
- StatusMessageBorder.Visibility = Visibility.Collapsed;
- }
- };
- StatusMessageBorder.BeginAnimation(OpacityProperty, animation);
- });
- }
- catch (TaskCanceledException)
- {
- }
- }
- private void ApplyStatusMessageStyle(StatusMessageType type)
- {
- var (background, icon) = GetStatusMessageVisuals(type);
- StatusIconBorder.Background = background;
- StatusIconTextBlock.Text = icon;
- StatusTextBlock.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1F2937"));
- }
- private static (Brush Background, string Icon) GetStatusMessageVisuals(StatusMessageType type)
- {
- return type switch
- {
- StatusMessageType.Success => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#27C346")), "✓"),
- StatusMessageType.Error => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#F76965")), "×"),
- StatusMessageType.Warning => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF9626")), "!"),
- _ => (new SolidColorBrush((Color)ColorConverter.ConvertFromString("#508DF8")), "i"),
- };
- }
- private void SetBusyState(bool isBusy, string? message = null)
- {
- _isBusy = isBusy;
- BusyOverlay.Visibility = isBusy ? Visibility.Visible : Visibility.Collapsed;
- BusyMessageTextBlock.Text = string.IsNullOrWhiteSpace(message) ? "正在处理,请稍候..." : message;
- AdapterComboBox.IsEnabled = !isBusy;
- RefreshAdaptersButton.IsEnabled = !isBusy;
- SearchDevicesButton.IsEnabled = !isBusy && AdapterComboBox.SelectedItem is AdapterInfo adapter && adapter.HasLink;
- }
- }
|