Sync desktop with public relay and add verified device connection management
This commit is contained in:
1 parent
87e888af69
commit
51c4f86918
17 files changed
+1289
-118
No files matched your search
@@ -1,61 +1,494 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace Ads.Desktop;
|
||||
public record Device(string Id,bool Busy) { public string Description=>Busy?"在线 · 已占用":"在线 · 可连接"; }
|
||||
public partial class MainViewModel:ObservableObject,IDisposable
|
||||
|
||||
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal)
|
||||
{
|
||||
[ObservableProperty] private string server="wss://ads.ttstd.com";
|
||||
[ObservableProperty] private string token=Environment.GetEnvironmentVariable("ADS_CLIENT_TOKEN")??"";
|
||||
[ObservableProperty] private string clientPath=FindClient();
|
||||
[ObservableProperty] private string adbPath="adb";
|
||||
[ObservableProperty] private string scrcpyPath="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 Device? selectedDevice;
|
||||
[ObservableProperty] private string status="尚未连接";
|
||||
[ObservableProperty] private string activeEndpoint="请选择在线设备";
|
||||
[ObservableProperty] private string notice="填写客户端令牌,然后刷新设备。";
|
||||
[ObservableProperty] private string deviceSummary="尚未刷新";
|
||||
public ObservableCollection<Device> Devices {get;}=new();
|
||||
public ObservableCollection<string> Logs {get;}=new();
|
||||
private Process? client,scrcpy;
|
||||
private string? endpoint,activeAdb,activeId;
|
||||
private bool probing,stopping;
|
||||
private readonly DispatcherTimer timer;
|
||||
private readonly HttpClient http=new(new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromSeconds(10)};
|
||||
private static readonly string Folder=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"TTSTD","ADS");
|
||||
private static string FindClient() { var name=OperatingSystem.IsWindows()?"ads-client.exe":"ads-client"; for(var d=new DirectoryInfo(AppContext.BaseDirectory);d!=null;d=d.Parent){var p=Path.Combine(d.FullName,"bin",name);if(File.Exists(p))return p;}return name; }
|
||||
public MainViewModel() {
|
||||
try {var p=Path.Combine(Folder,"settings.json"); if(File.Exists(p)){var s=JsonSerializer.Deserialize<Settings>(File.ReadAllText(p));if(s!=null){Server=s.Server;ClientPath=s.Client;AdbPath=s.Adb;ScrcpyPath=s.Scrcpy;Port=s.Port;MaxSize=s.Size;MaxFps=s.Fps;Audio=s.Audio;ViewOnly=s.ViewOnly;MinimizeToTray=s.Tray;}}}catch(Exception e){Log(e.Message);}
|
||||
timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(3)};timer.Tick+=async(_,_)=>await ProbeAsync();timer.Start();
|
||||
}
|
||||
private void Log(string s)=>Dispatcher.UIThread.Post(()=>{if(Token.Length>0)s=s.Replace(Token,"[REDACTED]");Logs.Add($"{DateTime.Now:HH:mm:ss} {s}");while(Logs.Count>1000)Logs.RemoveAt(0);});
|
||||
private async Task Guard(Func<Task> f){try{await f();}catch(Exception e){Notice=e.Message;Log(e.Message);}}
|
||||
private Uri Validate(){if(!Uri.TryCreate(Server,UriKind.Absolute,out var u)||u.Scheme!="wss"||string.IsNullOrEmpty(u.Host)||u.AbsolutePath!="/"||u.Query!=""||u.Fragment!=""||u.UserInfo!="")throw new InvalidOperationException("请输入根路径 WSS 中继地址。");if(Token.Length<32)throw new InvalidOperationException("客户端令牌至少需要 32 个字符。");return u;}
|
||||
[RelayCommand] private Task RefreshAsync()=>Guard(async()=>{var u=Validate();using var req=new HttpRequestMessage(HttpMethod.Get,new UriBuilder(u){Scheme="https",Path="/v1/devices"}.Uri);req.Headers.Authorization=new AuthenticationHeaderValue("Bearer",Token);using var res=await http.SendAsync(req);res.EnsureSuccessStatusCode();var rows=await res.Content.ReadFromJsonAsync<Device[]>()??[];var id=SelectedDevice?.Id;Devices.Clear();foreach(var d in rows.OrderBy(d=>d.Id))Devices.Add(d);SelectedDevice=Devices.FirstOrDefault(d=>d.Id==id)??Devices.FirstOrDefault();DeviceSummary=$"{Devices.Count} 台在线设备";Notice="设备列表已更新";});
|
||||
private ProcessStartInfo Info(string exe,IEnumerable<string> args){var i=new ProcessStartInfo(exe){UseShellExecute=false,CreateNoWindow=true,RedirectStandardOutput=true,RedirectStandardError=true};foreach(var a in args)i.ArgumentList.Add(a);foreach(var k in new[]{"ADB_SERVER_SOCKET","ANDROID_ADB_SERVER_ADDRESS","ANDROID_ADB_SERVER_PORT","ADS_CLIENT_TOKEN"})i.Environment.Remove(k);i.Environment["NO_COLOR"]="1";return i;}
|
||||
private Process Start(ProcessStartInfo i){var p=new Process{StartInfo=i};p.OutputDataReceived+=(_,e)=>{if(e.Data!=null)Log(e.Data);};p.ErrorDataReceived+=(_,e)=>{if(e.Data!=null)Log(e.Data);};try{p.Start();p.BeginOutputReadLine();p.BeginErrorReadLine();return p;}catch{p.Dispose();throw;}}
|
||||
[RelayCommand] private Task ConnectAsync()=>Guard(async()=>{Validate();var d=SelectedDevice??throw new InvalidOperationException("请选择设备。");if(client!=null)throw new InvalidOperationException("请先断开当前连接。");if(d.Busy)throw new InvalidOperationException("设备已被其他客户端占用。");if(Port is <1024 or >65535)throw new InvalidOperationException("端口范围 1024–65535。");var ep=$"127.0.0.1:{Port}";var i=Info(ClientPath,["--server",Server,"--device",d.Id,"--listen",ep,"--adb",AdbPath]);i.Environment["ADS_CLIENT_TOKEN"]=Token;client=Start(i);endpoint=ep;activeAdb=AdbPath;activeId=d.Id;ActiveEndpoint=$"{d.Id} → {ep}";Status="连接中 · 等待租约与调试授权";await Task.CompletedTask;});
|
||||
private async Task<string> AdbAsync(params string[] args){using var p=Process.Start(Info(activeAdb??AdbPath,args))??throw new InvalidOperationException("无法启动 ADB");var o=p.StandardOutput.ReadToEndAsync();var e=p.StandardError.ReadToEndAsync();using var c=new CancellationTokenSource(TimeSpan.FromSeconds(8));try{await p.WaitForExitAsync(c.Token);}catch{if(!p.HasExited)p.Kill(true);throw;}var text=await o;var err=await e;if(p.ExitCode!=0)throw new InvalidOperationException("ADB:"+err.Trim());return text;}
|
||||
private async Task ProbeAsync(){if(probing||stopping||client==null)return;probing=true;var current=client;try{if(current.HasExited){Notice=$"守护程序退出码:{current.ExitCode}";await DisconnectAsync();return;}var text=await AdbAsync("devices");if(client!=current||stopping)return;var row=text.Split('\n').Select(l=>l.Trim().Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries)).FirstOrDefault(a=>a.Length>=2&&a[0]==endpoint);Status=row?[1] switch{"device"=>"已连接 · 可调试 / 控制","unauthorized"=>"等待手机允许 USB 调试","offline"=>"ADB 离线 · 正在恢复",_=>"连接中 · 等待设备 / 租约 / 网络恢复"};}catch(Exception e){Notice=e.Message;}finally{probing=false;}}
|
||||
[RelayCommand] private Task StartScrcpyAsync()=>Guard(async()=>{if(client==null||client.HasExited||endpoint==null)throw new InvalidOperationException("请先连接设备。");if(scrcpy!=null&&!scrcpy.HasExited)throw new InvalidOperationException("控制窗口已打开。");if(MaxSize is <256 or >8192||MaxFps is <1 or >240)throw new InvalidOperationException("分辨率范围 256–8192,帧率范围 1–240。");var ep=endpoint;var state=await AdbAsync("-s",ep,"get-state");if(state.Trim()!="device"||endpoint!=ep)throw new InvalidOperationException("设备尚未就绪,请先完成手机调试授权。");var args=new List<string>{"--serial",ep,"--force-adb-forward","--window-title",$"ADS · {activeId}","--max-size",MaxSize.ToString(),"--max-fps",MaxFps.ToString()};if(!Audio)args.Add("--no-audio");if(ViewOnly)args.Add("--no-control");scrcpy?.Dispose();var i=Info(ScrcpyPath,args);i.Environment["ADB"]=activeAdb??AdbPath;scrcpy=Start(i);Notice="手机控制已启动,详情见日志。";});
|
||||
private static async Task StopAsync(Process? p){if(p==null)return;try{if(!p.HasExited){p.Kill(true);await p.WaitForExitAsync();}}finally{p.Dispose();}}
|
||||
[RelayCommand] private async Task StopScrcpyAsync(){var p=scrcpy;scrcpy=null;await StopAsync(p);}
|
||||
[RelayCommand] private async Task DisconnectAsync(){if(stopping)return;stopping=true;try{await StopScrcpyAsync();var p=client;client=null;await StopAsync(p);if(endpoint!=null){try{await AdbAsync("disconnect",endpoint);}catch(Exception e){Log(e.Message);}}endpoint=null;activeAdb=null;activeId=null;Status="已断开";ActiveEndpoint="本地 ADB 通道已释放";}finally{stopping=false;}}
|
||||
private record Settings(string Server,string Client,string Adb,string Scrcpy,int Port,int Size,int Fps,bool Audio,bool ViewOnly,bool Tray);
|
||||
[RelayCommand] private void Save(){try{Directory.CreateDirectory(Folder);File.WriteAllText(Path.Combine(Folder,"settings.json"),JsonSerializer.Serialize(new Settings(Server,ClientPath,AdbPath,ScrcpyPath,Port,MaxSize,MaxFps,Audio,ViewOnly,MinimizeToTray),new JsonSerializerOptions{WriteIndented=true}));Notice="配置已保存,不包含令牌";}catch(Exception e){Notice=e.Message;}}
|
||||
[RelayCommand] private void ClearLogs()=>Logs.Clear();
|
||||
[RelayCommand] private void ExportLogs(){try{Directory.CreateDirectory(Folder);var p=Path.Combine(Folder,$"ads-{DateTime.Now:yyyyMMdd-HHmmss}.log");File.WriteAllLines(p,Logs);Notice="日志已导出:"+p;}catch(Exception e){Notice=e.Message;}}
|
||||
public async Task ShutdownAsync(){timer.Stop();await DisconnectAsync();}
|
||||
public void Dispose(){timer.Stop();http.Dispose();foreach(var p in new[]{scrcpy,client}){try{if(p!=null&&!p.HasExited)p.Kill(true);}catch{}p?.Dispose();}}
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user