Files
AndroidDeviceStreaming/desktop/Ads.Desktop/MainViewModel.cs
T

62 lines
9.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
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
{
[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();}}
}