495 lines
23 KiB
C#
495 lines
23 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.Diagnostics;
|
||
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)
|
||
{
|
||
public string Description => IsLocal ? "本机正在使用" : 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 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 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 ObservableCollection<DeviceItem> Devices { get; } = new();
|
||
public ObservableCollection<string> Logs { get; } = new();
|
||
public string? Endpoint => endpoint;
|
||
public string? ActiveDeviceId => activeId;
|
||
|
||
private Process? client, scrcpy;
|
||
private string? endpoint, activeAdb, activeId;
|
||
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;
|
||
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。";
|
||
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) => UpdateCommands();
|
||
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();
|
||
}
|
||
|
||
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 ?? activeId ?? preferredDevice;
|
||
Devices.Clear();
|
||
foreach (var row in rows) Devices.Add(new DeviceItem(row.Id, row.Busy, HasConnection && row.Id == activeId));
|
||
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selectedId) ?? Devices.FirstOrDefault(d => !d.Busy) ?? Devices.FirstOrDefault();
|
||
RelayOnline = true;
|
||
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 };
|
||
private bool CanDisconnect() => !IsWorking && HasConnection;
|
||
private bool CanReadDeviceInfo() => !IsWorking && Ready;
|
||
private bool CanStartScrcpy() => !IsWorking && Ready && !ScreenRunning;
|
||
private bool CanStopScrcpy() => ScreenRunning;
|
||
|
||
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 Task ConnectCoreAsync(DeviceItem device)
|
||
{
|
||
if (client != null) throw new InvalidOperationException("请先断开当前连接。");
|
||
if (device.Busy) throw new InvalidOperationException("设备已被其他客户端占用。");
|
||
if (Port is < 1024 or > 65535) throw new InvalidOperationException("本地端口范围为 1024–65535。");
|
||
var portCheck = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, Port);
|
||
try
|
||
{
|
||
portCheck.Server.ExclusiveAddressUse = true;
|
||
portCheck.Start();
|
||
}
|
||
catch (System.Net.Sockets.SocketException)
|
||
{
|
||
throw new InvalidOperationException($"本地端口 {Port} 已被占用,请修改端口或先停止另一个连接客户端。");
|
||
}
|
||
finally { portCheck.Stop(); }
|
||
var relay = RelayOptions.Parse(Server, Origin, Token);
|
||
var clientExecutable = DesktopPaths.ResolveTool(ClientPath, "ads-client");
|
||
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
|
||
var address = $"127.0.0.1:{Port}";
|
||
var info = ProcessTools.ClientStartInfo(clientExecutable, adb, relay, device.Id, address);
|
||
client = Start(info);
|
||
endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
|
||
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
|
||
HasConnection = true; Ready = false;
|
||
UpdateLocalOwnership();
|
||
ActiveEndpoint = $"{device.Id} → {address}";
|
||
Status = "正在连接 · 等待设备就绪";
|
||
Notice = "连接已启动;首次使用时请在手机上允许调试。";
|
||
Model = AndroidVersion = ApiLevel = "—";
|
||
Log($"连接 {device.Id},本地 ADB 地址 {address}。");
|
||
return Task.CompletedTask;
|
||
}
|
||
|
||
private void UpdateLocalOwnership()
|
||
{
|
||
var selected = SelectedDevice?.Id;
|
||
for (var index = 0; index < Devices.Count; index++)
|
||
{
|
||
var device = Devices[index];
|
||
if (HasConnection && device.Id == activeId) Devices[index] = device with { Busy = true, IsLocal = true };
|
||
else if (device.IsLocal) Devices[index] = device with { Busy = false, IsLocal = false };
|
||
}
|
||
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selected);
|
||
}
|
||
|
||
private Process Start(ProcessStartInfo info)
|
||
{
|
||
var process = new Process { StartInfo = info };
|
||
process.OutputDataReceived += (_, line) => { if (line.Data != null) Log(line.Data); };
|
||
process.ErrorDataReceived += (_, line) => { if (line.Data != null) Log(line.Data); };
|
||
try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); return process; }
|
||
catch { process.Dispose(); throw; }
|
||
}
|
||
|
||
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 || IsWorking) return;
|
||
monitoring = true;
|
||
try
|
||
{
|
||
if (scrcpy is { HasExited: true })
|
||
{
|
||
Log($"手机控制窗口已关闭,退出码 {scrcpy.ExitCode}。");
|
||
scrcpy.Dispose(); scrcpy = null; ScreenRunning = false;
|
||
}
|
||
var current = client;
|
||
if (current != null)
|
||
{
|
||
if (current.HasExited)
|
||
{
|
||
Notice = $"连接守护程序退出,代码 {current.ExitCode};可查看日志后重新连接。";
|
||
await Exclusive(DisconnectCoreAsync);
|
||
}
|
||
else if (endpoint is { } address && activeAdb is { } adb)
|
||
{
|
||
var text = await AdbAsync(adb, lifetime.Token, "devices");
|
||
if (client == current)
|
||
{
|
||
var row = text.Split('\n').Select(l => l.Trim().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries))
|
||
.FirstOrDefault(parts => parts.Length >= 2 && parts[0] == address);
|
||
var wasReady = Ready;
|
||
Ready = row?[1] == "device";
|
||
Status = row?[1] switch
|
||
{
|
||
"device" => "已连接 · 可调试和控制",
|
||
"unauthorized" => "等待手机允许此电脑调试",
|
||
"offline" => "设备离线 · 正在恢复连接",
|
||
_ => "正在恢复连接 · 等待设备或网络"
|
||
};
|
||
if (Ready && !wasReady) { Log("设备已就绪。"); await ReadDeviceInfoCoreAsync(); }
|
||
}
|
||
}
|
||
}
|
||
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) { Ready = false; Report(error); } }
|
||
finally { monitoring = false; }
|
||
}
|
||
|
||
[RelayCommand(CanExecute = nameof(CanReadDeviceInfo))]
|
||
private Task ReadDeviceInfoAsync() => Guard(ReadDeviceInfoCoreAsync);
|
||
|
||
private async Task ReadDeviceInfoCoreAsync()
|
||
{
|
||
if (!Ready || endpoint is not { } address || activeAdb is not { } adb) return;
|
||
var current = client;
|
||
var text = await AdbAsync(adb, lifetime.Token, "-s", address, "shell",
|
||
"getprop ro.product.model; getprop ro.build.version.release; getprop ro.build.version.sdk");
|
||
if (endpoint != address || client != current) return;
|
||
var lines = text.Replace("\r", "").Split('\n');
|
||
Model = lines.ElementAtOrDefault(0)?.Trim() ?? "未知";
|
||
AndroidVersion = lines.ElementAtOrDefault(1)?.Trim() ?? "未知";
|
||
ApiLevel = lines.ElementAtOrDefault(2)?.Trim() ?? "未知";
|
||
Notice = "设备信息已更新。";
|
||
}
|
||
|
||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||
private Task DisconnectAsync() => Guard(() => Exclusive(async () =>
|
||
{
|
||
await DisconnectCoreAsync(); Notice = "连接已释放,远程手机守护程序继续在线。";
|
||
await RefreshDevicesAsync(announce: false);
|
||
}));
|
||
|
||
[RelayCommand(CanExecute = nameof(CanDisconnect))]
|
||
private Task ReconnectAsync() => Guard(() => Exclusive(async () =>
|
||
{
|
||
var id = activeId ?? throw new InvalidOperationException("尚未连接设备。");
|
||
await DisconnectCoreAsync();
|
||
DeviceItem? candidate = null;
|
||
for (var attempt = 0; attempt < 4; attempt++)
|
||
{
|
||
await Task.Delay(300, lifetime.Token);
|
||
await RefreshDevicesAsync(announce: false);
|
||
candidate = Devices.FirstOrDefault(d => d.Id == id);
|
||
if (candidate is { Busy: false }) break;
|
||
}
|
||
if (candidate == null) throw new InvalidOperationException("设备暂时不在线,请等待守护程序恢复后重试。");
|
||
await ConnectCoreAsync(candidate);
|
||
}));
|
||
|
||
private async Task DisconnectCoreAsync()
|
||
{
|
||
await StopScrcpyAsync();
|
||
var current = client; client = null;
|
||
await ProcessTools.StopAsync(current);
|
||
if (endpoint != null && activeAdb != null)
|
||
try { await AdbAsync(activeAdb, CancellationToken.None, "disconnect", endpoint); }
|
||
catch (Exception error) { Log(error.Message); }
|
||
endpoint = activeAdb = activeId = null;
|
||
HasConnection = Ready = false;
|
||
UpdateLocalOwnership();
|
||
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
|
||
Status = "已断开"; ActiveEndpoint = "本地 ADB 通道已释放";
|
||
Model = AndroidVersion = ApiLevel = "—";
|
||
}
|
||
|
||
[RelayCommand(CanExecute = nameof(CanStartScrcpy))]
|
||
private Task StartScrcpyAsync() => Guard(async () =>
|
||
{
|
||
if (!Ready || endpoint is not { } address || activeAdb is not { } adb) return;
|
||
var current = client;
|
||
if (MaxSize is < 256 or > 8192 || MaxFps is < 1 or > 240)
|
||
throw new InvalidOperationException("分辨率范围 256–8192,帧率范围 1–240。");
|
||
var executable = DesktopPaths.ResolveTool(ScrcpyPath, "scrcpy");
|
||
var state = await AdbAsync(adb, lifetime.Token, "-s", address, "get-state");
|
||
if (state.Trim() != "device" || endpoint != address || client != current) throw new InvalidOperationException("设备尚未就绪。");
|
||
var arguments = new List<string> { "--serial", address, "--force-adb-forward", "--window-title", $"ADS · {activeId}",
|
||
"--max-size", MaxSize.ToString(), "--max-fps", MaxFps.ToString() };
|
||
if (!Audio) arguments.Add("--no-audio");
|
||
if (ViewOnly) arguments.Add("--no-control");
|
||
var info = ProcessTools.CreateStartInfo(executable, arguments);
|
||
info.Environment["ADB"] = adb;
|
||
scrcpy = Start(info); ScreenRunning = true;
|
||
Log("手机控制进程已启动:" + activeId);
|
||
Notice = "手机控制窗口已启动。";
|
||
});
|
||
|
||
[RelayCommand(CanExecute = nameof(CanStopScrcpy))]
|
||
private async Task StopScrcpyAsync()
|
||
{
|
||
var current = scrcpy; scrcpy = null;
|
||
await ProcessTools.StopAsync(current); ScreenRunning = false;
|
||
if (current != null) Log("手机控制进程已停止。");
|
||
}
|
||
|
||
[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,
|
||
Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
|
||
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = activeId ?? 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()
|
||
{
|
||
timer.Stop(); lifetime.Cancel();
|
||
await connectionGate.WaitAsync();
|
||
try { await DisconnectCoreAsync(); }
|
||
finally { connectionGate.Release(); }
|
||
}
|
||
|
||
public void Dispose()
|
||
{
|
||
if (disposed) return;
|
||
disposed = true; timer.Stop(); lifetime.Cancel();
|
||
foreach (var process in new[] { scrcpy, client })
|
||
{
|
||
try { if (process != null && !process.HasExited) process.Kill(entireProcessTree: true); } catch { }
|
||
process?.Dispose();
|
||
}
|
||
lifetime.Dispose();
|
||
}
|
||
}
|