504 lines
28 KiB
C#
504 lines
28 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.Diagnostics;
|
||
using System.Text.Json;
|
||
using System.Text.RegularExpressions;
|
||
using Avalonia.Threading;
|
||
using CommunityToolkit.Mvvm.ComponentModel;
|
||
using CommunityToolkit.Mvvm.Input;
|
||
|
||
namespace Ads.Desktop;
|
||
|
||
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal, bool Online = true, string LocalSummary = "")
|
||
{
|
||
public string Description => IsLocal ? "本机 · " + LocalSummary : !Online ? "远程暂时离线" : Busy ? "在线 · 其他客户端使用中" : "在线 · 可连接";
|
||
}
|
||
|
||
public partial class MainViewModel : ObservableObject, IDisposable
|
||
{
|
||
[ObservableProperty] private string server = RelayOptions.DefaultServer;
|
||
[ObservableProperty] private string origin = RelayOptions.DefaultOrigin;
|
||
[ObservableProperty] private string token = "";
|
||
[ObservableProperty] private string clientPath = DesktopPaths.FindTool("ads-client");
|
||
[ObservableProperty] private string adbPath = DesktopPaths.FindTool("adb");
|
||
[ObservableProperty] private string scrcpyPath = DesktopPaths.FindTool("scrcpy");
|
||
[ObservableProperty] private int port = 15555;
|
||
[ObservableProperty] private int maxSize = 1920;
|
||
[ObservableProperty] private int maxFps = 60;
|
||
[ObservableProperty] private bool usbMode;
|
||
[ObservableProperty] private string usbipPath = WindowsUsbSession.DefaultUsbipPath();
|
||
[ObservableProperty] private int usbPort = 3240;
|
||
[ObservableProperty] private bool relayOnly;
|
||
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
|
||
[ObservableProperty] private bool audio;
|
||
[ObservableProperty] private bool viewOnly;
|
||
[ObservableProperty] private bool minimizeToTray = true;
|
||
[ObservableProperty] private bool autoRefresh = true;
|
||
[ObservableProperty] private DeviceItem? selectedDevice;
|
||
[ObservableProperty] private string status = "尚未连接";
|
||
[ObservableProperty] private string activeEndpoint = "选择设备后建立本地 ADB 通道";
|
||
[ObservableProperty] private string notice = "正在准备连接配置。";
|
||
[ObservableProperty] private string deviceSummary = "尚未刷新";
|
||
[ObservableProperty] private string relayStatus = "中继尚未检测";
|
||
[ObservableProperty] private string credentialSource = "未加载客户端凭据";
|
||
[ObservableProperty] private string toolsStatus = "请检查工具路径";
|
||
[ObservableProperty] private string portCleanupStatus = "清理会结束所选本地端口的监听进程。";
|
||
[ObservableProperty] private string model = "—";
|
||
[ObservableProperty] private string androidVersion = "—";
|
||
[ObservableProperty] private string apiLevel = "—";
|
||
[ObservableProperty] private bool relayOnline;
|
||
[ObservableProperty] private bool hasConnection;
|
||
[ObservableProperty] private bool ready;
|
||
[ObservableProperty] private bool screenRunning;
|
||
[ObservableProperty] private bool isWorking;
|
||
[ObservableProperty] private bool isRefreshing;
|
||
|
||
public AgentManagementViewModel AgentManager { get; }
|
||
public ObservableCollection<RelayNode> RelayNodes { get; } = new();
|
||
public ObservableCollection<DeviceItem> Devices { get; } = new();
|
||
public ObservableCollection<string> Logs { get; } = new();
|
||
public ObservableCollection<DeviceConnection> Connections { get; } = new();
|
||
public string ConnectionSummary => $"{Connections.Count} 台连接 · {Connections.Count(c => c.Ready)} 台就绪 · {Connections.Count(c => c.ScreenRunning)} 台投屏";
|
||
public bool HasConnections => Connections.Count > 0;
|
||
public string? Endpoint => Current?.Endpoint;
|
||
public string? ActiveDeviceId => Current?.HasConnection == true ? Current.DeviceId : null;
|
||
public DeviceConnection? Current => SelectedDevice != null ? sessions.GetValueOrDefault(SelectedDevice.Id) : null;
|
||
|
||
private readonly Dictionary<string, DeviceConnection> sessions = new(StringComparer.Ordinal);
|
||
private string credentialFile = "", preferredDevice = "home-phone";
|
||
private bool monitoring, disposed, initialized;
|
||
private DateTime lastRefresh;
|
||
private string? lastRefreshError;
|
||
private readonly DispatcherTimer timer;
|
||
private readonly CancellationTokenSource lifetime = new();
|
||
private readonly SemaphoreSlim connectionGate = new(1, 1);
|
||
private readonly HashSet<string> secrets = new(StringComparer.Ordinal);
|
||
private readonly string folder, settingsFile;
|
||
private static readonly Regex Ansi = new(@"\x1B\[[0-?]*[ -/]*[@-~]", RegexOptions.Compiled);
|
||
|
||
public MainViewModel(string? settingsFolder = null, bool backgroundMonitoring = true, bool loadLocalCredentials = true)
|
||
{
|
||
folder = settingsFolder ?? DesktopPaths.SettingsFolder;
|
||
settingsFile = Path.Combine(folder, "settings.json");
|
||
try
|
||
{
|
||
var settings = DesktopPaths.LoadSettings(settingsFile);
|
||
Server = settings.Server;
|
||
Origin = Environment.GetEnvironmentVariable("ADS_CONNECT_ADDRESS") ?? settings.Origin ?? RelayOptions.DefaultOrigin;
|
||
if (settings.Client.Length > 0) ClientPath = settings.Client;
|
||
if (settings.Adb.Length > 0) AdbPath = settings.Adb;
|
||
if (settings.Scrcpy.Length > 0) ScrcpyPath = settings.Scrcpy;
|
||
Port = settings.Port; MaxSize = settings.Size; MaxFps = settings.Fps;
|
||
UsbMode = settings.UsbMode; UsbPort = settings.UsbPort;
|
||
if (settings.UsbipPath.Length > 0) UsbipPath = settings.UsbipPath;
|
||
RelayOnly = settings.RelayOnly; Audio = settings.Audio; ViewOnly = settings.ViewOnly;
|
||
MinimizeToTray = settings.Tray; AutoRefresh = settings.AutoRefresh;
|
||
credentialFile = settings.CredentialFile;
|
||
preferredDevice = settings.PreferredDevice;
|
||
}
|
||
catch (Exception error) { Log("读取配置失败,使用默认值:" + error.Message); }
|
||
var environmentToken = loadLocalCredentials ? Environment.GetEnvironmentVariable("ADS_CLIENT_TOKEN") : null;
|
||
if (!string.IsNullOrWhiteSpace(environmentToken))
|
||
{
|
||
Token = environmentToken.Trim(); CredentialSource = "来自 ADS_CLIENT_TOKEN 环境变量";
|
||
}
|
||
else if (loadLocalCredentials)
|
||
{
|
||
if (credentialFile.Length == 0) credentialFile = DesktopPaths.DefaultCredentialFile();
|
||
if (File.Exists(credentialFile)) LoadCredentials(credentialFile, useOrigin: false);
|
||
}
|
||
Notice = Token.Length >= 32 ? "配置已就绪,正在等待刷新设备。" : "请在连接配置中导入 client.env。";
|
||
AgentManager = new AgentManagementViewModel(() => (Server, Origin), Log, backgroundMonitoring, loadLocalCredentials);
|
||
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
|
||
timer.Tick += async (_, _) => await MonitorAsync();
|
||
if (backgroundMonitoring) timer.Start();
|
||
}
|
||
|
||
partial void OnTokenChanged(string value)
|
||
{
|
||
if (value.Length > 0) lock (secrets) secrets.Add(value);
|
||
CredentialSource = value.Length > 0 ? "当前输入的客户端令牌(仅内存)" : "未加载客户端凭据";
|
||
}
|
||
partial void OnSelectedDeviceChanged(DeviceItem? value) => SyncSelected();
|
||
partial void OnHasConnectionChanged(bool value) => UpdateCommands();
|
||
partial void OnReadyChanged(bool value) => UpdateCommands();
|
||
partial void OnScreenRunningChanged(bool value) => UpdateCommands();
|
||
partial void OnIsWorkingChanged(bool value) => UpdateCommands();
|
||
partial void OnRelayOnlineChanged(bool value) => UpdateCommands();
|
||
|
||
private void UpdateCommands()
|
||
{
|
||
ConnectCommand.NotifyCanExecuteChanged(); DisconnectCommand.NotifyCanExecuteChanged();
|
||
ReconnectCommand.NotifyCanExecuteChanged(); ReadDeviceInfoCommand.NotifyCanExecuteChanged();
|
||
StartScrcpyCommand.NotifyCanExecuteChanged(); StopScrcpyCommand.NotifyCanExecuteChanged();
|
||
ClearPortCommand.NotifyCanExecuteChanged(); ConnectAllCommand.NotifyCanExecuteChanged();
|
||
DisconnectAllCommand.NotifyCanExecuteChanged(); StartAllScreensCommand.NotifyCanExecuteChanged();
|
||
DisconnectDeviceCommand.NotifyCanExecuteChanged(); ReconnectDeviceCommand.NotifyCanExecuteChanged();
|
||
StartScreenDeviceCommand.NotifyCanExecuteChanged(); StopScreenDeviceCommand.NotifyCanExecuteChanged();
|
||
}
|
||
|
||
private string Redact(string text)
|
||
{
|
||
text = Ansi.Replace(text, "");
|
||
lock (secrets) foreach (var secret in secrets) text = text.Replace(secret, "[REDACTED]", StringComparison.Ordinal);
|
||
return text;
|
||
}
|
||
|
||
private void Log(string message)
|
||
{
|
||
var line = $"{DateTime.Now:HH:mm:ss} {Redact(message)}";
|
||
void Append() { if (disposed) return; Logs.Add(line); while (Logs.Count > 1000) Logs.RemoveAt(0); }
|
||
if (Dispatcher.UIThread.CheckAccess()) Append(); else Dispatcher.UIThread.Post(Append);
|
||
}
|
||
|
||
private void Report(Exception error)
|
||
{
|
||
Notice = Redact(error is OperationCanceledException ? "操作超时,请检查网络或工具状态。" : error.Message);
|
||
Log(Notice);
|
||
}
|
||
|
||
private async Task Guard(Func<Task> action)
|
||
{
|
||
try { await action(); }
|
||
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
|
||
catch (Exception error) { if (!disposed) Report(error); }
|
||
}
|
||
|
||
public async Task InitializeAsync()
|
||
{
|
||
if (initialized) return;
|
||
initialized = true;
|
||
if (Token.Length >= 32) await RefreshAsync();
|
||
else Notice = "请导入客户端凭据,再刷新设备。";
|
||
}
|
||
|
||
public void LoadCredentials(string path, bool useOrigin = true)
|
||
{
|
||
try
|
||
{
|
||
var credential = ClientCredential.Read(path);
|
||
Token = credential.Token;
|
||
if (useOrigin && credential.Origin != null) Origin = credential.Origin;
|
||
credentialFile = Path.GetFullPath(path);
|
||
CredentialSource = "已加载 " + Path.GetFileName(path) + "(令牌仅在内存中使用)";
|
||
Notice = "客户端凭据已加载,可刷新设备。";
|
||
Log("已读取客户端凭据,未记录令牌内容。");
|
||
}
|
||
catch (Exception error) { Report(error); }
|
||
}
|
||
|
||
[RelayCommand]
|
||
private Task RefreshAsync() => Guard(() => RefreshDevicesAsync(announce: true));
|
||
|
||
private async Task RefreshDevicesAsync(bool announce)
|
||
{
|
||
if (IsRefreshing) return;
|
||
IsRefreshing = true; lastRefresh = DateTime.UtcNow;
|
||
try
|
||
{
|
||
var options = RelayOptions.Parse(Server, Origin, Token);
|
||
var rows = await RelayApi.GetDevicesAsync(options, lifetime.Token);
|
||
if (Server.Trim() != options.BaseUri.OriginalString || Origin.Trim() != options.Origin || Token != options.Token) return;
|
||
var selectedId = SelectedDevice?.Id ?? preferredDevice;
|
||
Devices.Clear();
|
||
foreach (var row in rows) {
|
||
var connection = sessions.GetValueOrDefault(row.Id);
|
||
Devices.Add(new DeviceItem(row.Id, row.Busy || connection?.HasConnection == true, connection?.HasConnection == true, true, connection?.Status ?? ""));
|
||
}
|
||
foreach (var local in Connections.Where(c => rows.All(r => r.Id != c.DeviceId)))
|
||
Devices.Add(new DeviceItem(local.DeviceId, true, true, false, local.Status));
|
||
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selectedId) ?? Devices.FirstOrDefault(d => !d.Busy) ?? Devices.FirstOrDefault();
|
||
RelayOnline = true;
|
||
RelayStatus = "控制中心在线";
|
||
try {
|
||
var nodes = await RelayApi.GetNodesAsync(options, lifetime.Token);
|
||
if (Server.Trim() != options.BaseUri.OriginalString || Origin.Trim() != options.Origin || Token != options.Token) return;
|
||
RelayNodes.Clear(); foreach (var node in nodes) RelayNodes.Add(node);
|
||
if (nodes.Length > 0) RelayStatus += $" · 中继 {nodes.Count(n => n.Healthy)}/{nodes.Length} 在线";
|
||
} catch (Exception error) when (error is HttpRequestException or TaskCanceledException) {
|
||
RelayNodes.Clear(); RelayStatus += " · 节点状态暂不可用";
|
||
}
|
||
DeviceSummary = $"{rows.Length} 台在线 · {DateTime.Now:HH:mm:ss} 更新";
|
||
lastRefreshError = null;
|
||
if (announce) { Notice = "设备列表已更新。"; Log($"中继在线,发现 {rows.Length} 台设备。"); }
|
||
}
|
||
catch
|
||
{
|
||
RelayOnline = false; RelayStatus = "中继暂不可达";
|
||
DeviceSummary = Devices.Count > 0 ? "保留上次列表,等待恢复" : "未取得设备列表";
|
||
throw;
|
||
}
|
||
finally { IsRefreshing = false; }
|
||
}
|
||
|
||
private bool CanConnect() => !IsWorking && !HasConnection && RelayOnline && SelectedDevice is { Busy: false, Online: true };
|
||
private bool CanDisconnect() => !IsWorking && HasConnection;
|
||
private bool CanReadDeviceInfo() => !IsWorking && Ready;
|
||
private bool CanStartScrcpy() => !IsWorking && Ready && !ScreenRunning;
|
||
private bool CanStopScrcpy() => !IsWorking && ScreenRunning;
|
||
private bool CanConnectAll() => !IsWorking && RelayOnline && Devices.Any(d => d.Online && !d.Busy && !d.IsLocal);
|
||
private bool CanDisconnectAll() => !IsWorking && HasConnections;
|
||
private bool CanStartAllScreens() => !IsWorking && Connections.Any(c => c.Ready && !c.ScreenRunning);
|
||
private bool CanClearPort() => !IsWorking;
|
||
|
||
[RelayCommand(CanExecute = nameof(CanClearPort))]
|
||
private Task ClearPortAsync() => Guard(() => Exclusive(async () =>
|
||
{
|
||
var selectedPort = Current?.HasConnection == true ? Current.Options.Port : Port;
|
||
if (selectedPort == 5037) throw new InvalidOperationException("不能清理 ADB 主服务端口 5037,请选择隧道端口。");
|
||
var owned = Connections.FirstOrDefault(c => c.Options.Port == selectedPort);
|
||
var releasedOwnConnection = owned != null;
|
||
var releasedUsb = owned?.Options.UsbMode == true;
|
||
if (releasedOwnConnection)
|
||
{
|
||
Log($"清理端口 {selectedPort}:先断开当前工作台管理的连接。");
|
||
await owned!.DisconnectAsync();
|
||
}
|
||
var owners = await Task.Run(() => LocalPortProcesses.Inspect(selectedPort), lifetime.Token);
|
||
PortCleanupStatus = owners.Count == 0 ? $"端口 {selectedPort} 没有监听进程。" :
|
||
string.Join(";", owners.Select(owner => $"{owner.Name} · PID {owner.Id} · 端口 {selectedPort}"));
|
||
foreach (var owner in owners) Log($"清理端口 {selectedPort}:{owner.Name}(PID {owner.Id})。");
|
||
var ended = await LocalPortProcesses.TerminateAsync(selectedPort, owners, lifetime.Token);
|
||
try
|
||
{
|
||
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
|
||
if (!releasedUsb) await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
|
||
}
|
||
catch (Exception error) { Log("清除 ADB 端点:" + error.Message); }
|
||
PortCleanupStatus = releasedOwnConnection && ended == 0
|
||
? $"本机连接已断开,端口 {selectedPort} 已释放。"
|
||
: $"端口 {selectedPort} 已释放,结束了 {ended} 个占用进程。";
|
||
Notice = PortCleanupStatus + " 现在可以重新连接设备。";
|
||
Log(PortCleanupStatus);
|
||
if (Token.Length >= 32)
|
||
try { await RefreshDevicesAsync(announce: false); } catch (Exception error) { Log(error.Message); }
|
||
}));
|
||
|
||
private async Task Exclusive(Func<Task> action)
|
||
{
|
||
await connectionGate.WaitAsync(lifetime.Token);
|
||
IsWorking = true;
|
||
try { await action(); }
|
||
finally { IsWorking = false; connectionGate.Release(); }
|
||
}
|
||
|
||
[RelayCommand(CanExecute = nameof(CanConnect))]
|
||
private Task ConnectAsync() => Guard(() => Exclusive(async () =>
|
||
{
|
||
var selected = SelectedDevice ?? throw new InvalidOperationException("请选择设备。");
|
||
await ConnectCoreAsync(selected);
|
||
}));
|
||
|
||
private async Task ConnectCoreAsync(DeviceItem device)
|
||
{
|
||
if (sessions.GetValueOrDefault(device.Id)?.HasConnection == true) throw new InvalidOperationException("该设备已经连接。");
|
||
if (device.Busy) throw new InvalidOperationException("设备已被其他客户端占用。");
|
||
var relay = RelayOptions.Parse(Server, Origin, Token);
|
||
var client = DesktopPaths.ResolveTool(ClientPath, "ads-client");
|
||
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
|
||
var reserved = ReservedPorts().ToHashSet();
|
||
var rawPort = ConnectionPorts.Allocate(Port, reserved); reserved.Add(rawPort);
|
||
int? usbPort = null;
|
||
if (UsbMode) {
|
||
usbPort = ConnectionPorts.Allocate(UsbPort, reserved);
|
||
WindowsUsbSession.Validate(UsbipPath, usbPort.Value);
|
||
}
|
||
if (sessions.Remove(device.Id, out var old)) { old.PropertyChanged -= ConnectionChanged; old.Dispose(); }
|
||
var session = new DeviceConnection(device.Id,
|
||
new ConnectionOptions(relay, client, adb, UsbMode, UsbipPath, RelayOnly, rawPort, usbPort, folder), Log, lifetime.Token);
|
||
sessions.Add(device.Id, session); session.PropertyChanged += ConnectionChanged;
|
||
preferredDevice = device.Id;
|
||
try { await session.ConnectAsync(); }
|
||
finally { UpdateLocalOwnership(); SyncSelected(); }
|
||
Notice = $"{device.Id} 已启动,其他设备连接保持运行。";
|
||
}
|
||
|
||
private void ConnectionChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||
{
|
||
if (sender is not DeviceConnection session) return;
|
||
if (session.HasConnection && !Connections.Contains(session)) Connections.Add(session);
|
||
else if (!session.HasConnection) Connections.Remove(session);
|
||
if (e.PropertyName is nameof(DeviceConnection.HasConnection) or nameof(DeviceConnection.Status)) UpdateLocalOwnership();
|
||
if (Current == session) SyncSelected();
|
||
OnPropertyChanged(nameof(ConnectionSummary)); OnPropertyChanged(nameof(HasConnections)); UpdateCommands();
|
||
}
|
||
private void SyncSelected()
|
||
{
|
||
var current = Current;
|
||
HasConnection = current?.HasConnection == true; Ready = current?.Ready == true; ScreenRunning = current?.ScreenRunning == true;
|
||
Status = current?.Status ?? "尚未连接";
|
||
TransportStatus = current?.TransportStatus ?? "尚未建立数据通道";
|
||
Model = current?.Model ?? "—"; AndroidVersion = current?.AndroidVersion ?? "—"; ApiLevel = current?.ApiLevel ?? "—";
|
||
ActiveEndpoint = HasConnection ? $"{current!.DeviceId} → {current.Mode} · {current.Endpoint}" : "选择设备后建立本地 ADB 通道";
|
||
if (!string.IsNullOrEmpty(current?.Notice)) Notice = Redact(current.Notice);
|
||
OnPropertyChanged(nameof(Current)); OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId)); UpdateCommands();
|
||
}
|
||
private void UpdateLocalOwnership()
|
||
{
|
||
var selected = SelectedDevice?.Id;
|
||
for (var i = 0; i < Devices.Count; i++) {
|
||
var row = Devices[i]; var session = sessions.GetValueOrDefault(row.Id);
|
||
var local = session?.HasConnection == true;
|
||
var replacement = row with { Busy = local || (!row.IsLocal && row.Busy), IsLocal = local, LocalSummary = local ? session!.Status : "" };
|
||
if (replacement != row) Devices[i] = replacement;
|
||
}
|
||
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selected);
|
||
}
|
||
private async Task<string> AdbAsync(string adb, CancellationToken cancellation, params string[] arguments)
|
||
{
|
||
var result = await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(adb, arguments), cancellation);
|
||
if (result.ExitCode != 0) throw new InvalidOperationException("ADB:" + result.Error.Trim());
|
||
return result.Output;
|
||
}
|
||
private async Task MonitorAsync()
|
||
{
|
||
if (monitoring || disposed) return;
|
||
monitoring = true;
|
||
try {
|
||
// One ADB listing per executable for the whole fleet, including unselected phones.
|
||
foreach (var group in Connections.ToArray().GroupBy(c => c.Options.Adb)) {
|
||
try {
|
||
var listing = await AdbAsync(group.Key, lifetime.Token, "devices");
|
||
await Task.WhenAll(group.Select(c => c.MonitorAsync(listing)));
|
||
} catch (Exception error) when (!lifetime.IsCancellationRequested) {
|
||
foreach (var connection in group) connection.MonitoringFailed(error.Message);
|
||
}
|
||
}
|
||
if (AutoRefresh && Token.Length >= 32 && DateTime.UtcNow - lastRefresh >= TimeSpan.FromSeconds(10)) {
|
||
try { await RefreshDevicesAsync(announce: false); }
|
||
catch (Exception error) {
|
||
var message = Redact(error.Message);
|
||
if (message != lastRefreshError) { Log("刷新设备:" + message); lastRefreshError = message; }
|
||
}
|
||
}
|
||
} catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
|
||
catch (Exception error) { if (!disposed) Report(error); }
|
||
finally { monitoring = false; }
|
||
}
|
||
[RelayCommand(CanExecute = nameof(CanReadDeviceInfo))]
|
||
private Task ReadDeviceInfoAsync() => Guard(async () => { if (Current is { } c) await c.ReadInfoAsync(); });
|
||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||
private Task DisconnectAsync() => Guard(() => Exclusive(async () => {
|
||
var current = Current;
|
||
if (current != null) await current.DisconnectAsync();
|
||
await RefreshDevicesAsync(announce: false);
|
||
}));
|
||
private async Task ReconnectConnectionAsync(DeviceConnection connection)
|
||
{
|
||
var id = connection.DeviceId;
|
||
await connection.DisconnectAsync();
|
||
await Task.Delay(300, lifetime.Token);
|
||
await ConnectCoreAsync(new DeviceItem(id, false, false));
|
||
}
|
||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||
private Task ReconnectAsync() => Guard(() => Exclusive(async () => { if (Current is { } c) await ReconnectConnectionAsync(c); }));
|
||
[RelayCommand(CanExecute = nameof(CanStartScrcpy))]
|
||
private Task StartScrcpyAsync() => Guard(() => Exclusive(async () => { if (Current is { } c) await StartScreenAsync(c); }));
|
||
private IEnumerable<int> ReservedPorts() => Connections.SelectMany(c => new int?[] { c.Options.Port, c.Options.UsbPort, c.ScreenPort }).Where(p => p.HasValue).Select(p => p!.Value);
|
||
private Task StartScreenAsync(DeviceConnection connection)
|
||
{
|
||
var port = ConnectionPorts.Allocate(27183, ReservedPorts());
|
||
return connection.StartScreenAsync(ScrcpyPath, MaxSize, MaxFps, Audio, ViewOnly, port);
|
||
}
|
||
[RelayCommand(CanExecute = nameof(CanStopScrcpy))]
|
||
private Task StopScrcpyAsync() => Guard(() => Exclusive(async () => { if (Current is { } c) await c.StopScreenAsync(); }));
|
||
[RelayCommand(CanExecute = nameof(CanConnectAll))]
|
||
private Task ConnectAllAsync() => Guard(() => Exclusive(async () => {
|
||
var available = Devices.Where(d => d.Online && !d.Busy && !d.IsLocal).ToArray(); var failed = 0;
|
||
foreach (var device in available) {
|
||
try { await ConnectCoreAsync(device); } catch (Exception error) { failed++; Log($"[{device.Id}] {error.Message}"); }
|
||
}
|
||
Notice = $"已处理 {available.Length} 台设备,失败 {failed} 台。";
|
||
}));
|
||
[RelayCommand(CanExecute = nameof(CanDisconnectAll))]
|
||
private Task DisconnectAllAsync() => Guard(() => Exclusive(DisconnectAllCoreAsync));
|
||
private async Task DisconnectAllCoreAsync()
|
||
{
|
||
foreach (var connection in Connections.ToArray()) {
|
||
try { await connection.ShutdownAsync(); } catch (Exception error) { Log($"[{connection.DeviceId}] {error.Message}"); }
|
||
}
|
||
SyncSelected();
|
||
}
|
||
[RelayCommand(CanExecute = nameof(CanStartAllScreens))]
|
||
private Task StartAllScreensAsync() => Guard(() => Exclusive(async () => {
|
||
foreach (var connection in Connections.Where(c => c.Ready && !c.ScreenRunning).ToArray()) {
|
||
try { await StartScreenAsync(connection); } catch (Exception error) { Log($"[{connection.DeviceId}] {error.Message}"); }
|
||
}
|
||
}));
|
||
[RelayCommand] private void SelectConnection(DeviceConnection connection) => SelectedDevice = Devices.FirstOrDefault(d => d.Id == connection.DeviceId);
|
||
private bool CanManage(DeviceConnection? connection) => !IsWorking && connection?.HasConnection == true && Connections.Contains(connection);
|
||
[RelayCommand(CanExecute = nameof(CanManage))] private Task DisconnectDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => connection.DisconnectAsync()));
|
||
[RelayCommand(CanExecute = nameof(CanManage))] private Task ReconnectDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => ReconnectConnectionAsync(connection)));
|
||
private bool CanStartDeviceScreen(DeviceConnection? connection) => CanManage(connection) && connection!.Ready && !connection.ScreenRunning;
|
||
private bool CanStopDeviceScreen(DeviceConnection? connection) => CanManage(connection) && connection!.ScreenRunning;
|
||
[RelayCommand(CanExecute = nameof(CanStartDeviceScreen))] private Task StartScreenDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => StartScreenAsync(connection)));
|
||
[RelayCommand(CanExecute = nameof(CanStopDeviceScreen))] private Task StopScreenDeviceAsync(DeviceConnection connection) => Guard(() => Exclusive(() => connection.StopScreenAsync()));
|
||
|
||
[RelayCommand]
|
||
private Task CheckToolsAsync() => Guard(async () =>
|
||
{
|
||
var results = new List<string>();
|
||
foreach (var tool in new[] { ("ads-client", ClientPath), ("adb", AdbPath), ("scrcpy", ScrcpyPath) })
|
||
{
|
||
lifetime.Token.ThrowIfCancellationRequested();
|
||
try
|
||
{
|
||
var executable = DesktopPaths.ResolveTool(tool.Item2, tool.Item1);
|
||
var result = await ProcessTools.RunAsync(ProcessTools.CreateStartInfo(executable,
|
||
[tool.Item1 == "adb" ? "version" : "--version"]), lifetime.Token);
|
||
if (result.ExitCode != 0) throw new InvalidOperationException("工具无法启动。");
|
||
results.Add(tool.Item1 + " 就绪");
|
||
Log(tool.Item1 + ":" + (result.Output + result.Error).Split('\n')[0].Trim());
|
||
}
|
||
catch (Exception error) { results.Add(tool.Item1 + " 未就绪"); Log(tool.Item1 + ":" + error.Message); }
|
||
}
|
||
ToolsStatus = string.Join(" · ", results); Notice = ToolsStatus;
|
||
});
|
||
|
||
[RelayCommand]
|
||
private void Save()
|
||
{
|
||
try
|
||
{
|
||
RelayOptions.ParseBaseUri(Server);
|
||
if (!string.IsNullOrWhiteSpace(Origin)) RelayOptions.ParseOrigin(Origin);
|
||
DesktopPaths.SaveSettings(settingsFile, new DesktopSettings
|
||
{
|
||
Server = Server.Trim(), Origin = Origin.Trim(), Client = ClientPath, Adb = AdbPath, Scrcpy = ScrcpyPath,
|
||
UsbMode = UsbMode, UsbipPath = UsbipPath, UsbPort = UsbPort, RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
|
||
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = SelectedDevice?.Id ?? preferredDevice
|
||
});
|
||
Notice = "配置已保存;令牌内容未写入配置。";
|
||
}
|
||
catch (Exception error) { Report(error); }
|
||
}
|
||
|
||
[RelayCommand] private void ClearLogs() => Logs.Clear();
|
||
[RelayCommand] private void ExportLogs()
|
||
{
|
||
try
|
||
{
|
||
Directory.CreateDirectory(folder);
|
||
var path = Path.Combine(folder, $"ads-{DateTime.Now:yyyyMMdd-HHmmss}.log");
|
||
File.WriteAllLines(path, Logs.Select(Redact)); Notice = "日志已导出:" + path;
|
||
}
|
||
catch (Exception error) { Report(error); }
|
||
}
|
||
|
||
public async Task ShutdownAsync()
|
||
{
|
||
AgentManager.Dispose(); timer.Stop(); lifetime.Cancel();
|
||
await connectionGate.WaitAsync();
|
||
try { await DisconnectAllCoreAsync(); }
|
||
finally { connectionGate.Release(); }
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
if (disposed) return;
|
||
disposed = true; AgentManager.Dispose(); timer.Stop(); lifetime.Cancel();
|
||
foreach (var session in sessions.Values) { session.PropertyChanged -= ConnectionChanged; session.Dispose(); }
|
||
sessions.Clear(); Connections.Clear();
|
||
lifetime.Dispose();
|
||
}
|
||
}
|