Sync desktop with public relay and add verified device connection management

This commit is contained in:
tongtong committed 2026-11-12 15:30:05 +08:00
1 parent 87e888af69
commit 51c4f86918
17 files changed
+1262 -91

No files matched your search

@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="11.3.8"/>
<ProjectReference Include="../Ads.Desktop/Ads.Desktop.csproj"/>
</ItemGroup>
</Project>
+133
View File
@@ -0,0 +1,133 @@
using Ads.Desktop;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
AppBuilder.Configure<App>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
using var finished = new CancellationTokenSource();
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { await RunAsync(args.Contains("--live"), args.Contains("--screen")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
Dispatcher.UIThread.MainLoop(finished.Token);
if (failure != null) { Console.Error.WriteLine(failure); return 1; }
return 0;
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static async Task UntilAsync(Func<bool> condition, string message)
{
var deadline = DateTime.UtcNow.AddSeconds(35);
while (!condition())
{
if (DateTime.UtcNow > deadline) throw new InvalidOperationException(message);
await Task.Delay(150);
}
}
private static async Task RunAsync(bool live, bool screen)
{
var root = DesktopPaths.ProjectRoot() ?? throw new InvalidOperationException("Project root not found");
var folder = Path.Combine(root, "work", "desktop-smoke", Guid.NewGuid().ToString("N"));
using var vm = new MainViewModel(folder, backgroundMonitoring: true, loadLocalCredentials: live);
// Avoid collisions with the interactive application or another local ADB device.
var temporary = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
temporary.Start(); vm.Port = ((System.Net.IPEndPoint)temporary.LocalEndpoint).Port; temporary.Stop();
var window = new MainWindow { DataContext = vm };
window.Show();
await Task.Delay(60);
try
{
Require(window.FindControl<TextBox>("ServerBox")?.Text == RelayOptions.DefaultServer, "Server binding is wrong");
Require(window.FindControl<TextBox>("OriginBox")?.Text == RelayOptions.DefaultOrigin, "Origin binding is wrong");
if (!live)
{
Require(window.FindControl<Button>("ConnectButton")?.IsEffectivelyEnabled == false, "Connect should be disabled before device selection");
vm.Devices.Add(new DeviceItem("busy-phone", true, false));
vm.SelectedDevice = vm.Devices[0];
vm.RelayOnline = true;
Require(!vm.ConnectCommand.CanExecute(null), "Busy device was connectable");
vm.Devices.Add(new DeviceItem("free-phone", false, false));
vm.SelectedDevice = vm.Devices[1];
Require(vm.ConnectCommand.CanExecute(null), "Available device was not connectable");
var occupied = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
occupied.Start();
try
{
vm.Port = ((System.Net.IPEndPoint)occupied.LocalEndpoint).Port;
await vm.ConnectCommand.ExecuteAsync(null);
Require(!vm.HasConnection && vm.Notice.Contains("已被占用"), "Occupied port was not rejected safely");
}
finally { occupied.Stop(); }
Console.WriteLine("PASS: Avalonia bindings and device action availability");
return;
}
await vm.InitializeAsync();
await UntilAsync(() => vm.RelayOnline && vm.Devices.Any(d => d.Id == "home-phone"), "Public gateway was not discovered: " + vm.Notice);
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
Require(!vm.SelectedDevice.Busy, "The gateway is in use; smoke test will not steal its lease");
await vm.ConnectCommand.ExecuteAsync(null);
await UntilAsync(() => vm.Ready && vm.Model != "—", "Device did not become ready: " + vm.Notice);
Require(window.FindControl<TextBlock>("ModelText")?.Text == vm.Model, "Model UI binding failed");
Require(window.FindControl<Button>("ReconnectButton")?.IsEffectivelyEnabled == true, "Reconnect button not enabled");
Console.WriteLine("PASS: public device list, GUI connect, local ADB ready and model information: " + vm.Model);
Require(vm.Devices.Single(d => d.Id == "home-phone").IsLocal, "Current device ownership label is wrong");
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", "desktop-live.png"));
window.Width = 980; window.Height = 700;
await Task.Delay(60);
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", "desktop-minimum.png"));
window.Width = 1240; window.Height = 880;
if (screen)
{
await vm.CheckToolsCommand.ExecuteAsync(null);
Require(!vm.ToolsStatus.Contains("未就绪"), "Missing tool: " + vm.ToolsStatus);
await vm.StartScrcpyCommand.ExecuteAsync(null);
Require(vm.ScreenRunning, "scrcpy did not start: " + vm.Notice);
try
{
await UntilAsync(() => vm.Logs.Any(line => line.Contains("INFO: Texture")),
"scrcpy did not report a video texture");
}
catch (Exception error)
{
throw new InvalidOperationException(error.Message + "; state=" + vm.ScreenRunning + "; notice=" + vm.Notice + "; logs=" + string.Join(" | ", vm.Logs.TakeLast(25)));
}
Require(vm.ScreenRunning, "scrcpy process exited unexpectedly");
await vm.StopScrcpyCommand.ExecuteAsync(null);
Require(!vm.ScreenRunning, "scrcpy did not stop");
Console.WriteLine("PASS: GUI starts real scrcpy video stream and stops its process");
}
await vm.ReconnectCommand.ExecuteAsync(null);
await UntilAsync(() => vm.Ready && vm.Model != "—", "Reconnect did not recover device: " + vm.Notice);
Console.WriteLine("PASS: GUI reconnect and information recovery");
await vm.DisconnectCommand.ExecuteAsync(null);
Require(!vm.HasConnection && !vm.Ready && vm.Endpoint == null, "Disconnect did not clean up local connection");
await vm.RefreshCommand.ExecuteAsync(null);
Require(vm.Devices.Single(d => d.Id == "home-phone").Busy == false, "Device lease was not released");
Console.WriteLine("PASS: GUI disconnect releases lease; remote gateway remains online");
vm.SaveCommand.Execute(null);
Require(!File.ReadAllText(Path.Combine(folder, "settings.json")).Contains(vm.Token), "Saved settings leaked the token");
Require(!vm.Logs.Any(line => line.Contains(vm.Token)), "UI log leaked token");
Console.WriteLine("PASS: settings and UI logs do not contain client token");
}
finally
{
await vm.ShutdownAsync();
File.WriteAllLines(Path.Combine(root, "work", "desktop-smoke.log"), vm.Logs);
window.Close();
}
}
}
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable><IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1"/>
<PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"><PrivateAssets>all</PrivateAssets></PackageReference>
<ProjectReference Include="../Ads.Desktop/Ads.Desktop.csproj"/>
</ItemGroup>
</Project>
@@ -0,0 +1,115 @@
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Ads.Desktop;
using Xunit;
namespace Ads.Desktop.Tests;
public class ConnectionTests
{
private const string Token = "client-test-token-that-is-at-least-32-characters";
[Theory]
[InlineData("wss://ttstd.com/ads", "https://ttstd.com/ads/v1/devices")]
[InlineData("wss://ttstd.com/ads/", "https://ttstd.com/ads/v1/devices")]
[InlineData("wss://example.test:8443/prefix", "https://example.test:8443/prefix/v1/devices")]
public void ApiPreservesPrefixAndPort(string server, string expected)
{
Assert.Equal(expected, RelayOptions.Parse(server, "", Token).DevicesUri.ToString());
}
[Theory]
[InlineData("ws://ttstd.com/ads", "")]
[InlineData("wss://user:password@ttstd.com", "")]
[InlineData("wss://ttstd.com/ads?ticket=secret", "")]
[InlineData("wss://ttstd.com/ads", "175.178.213.60")]
[InlineData("wss://ttstd.com/ads", "example.test:443/extra")]
public void UnsafeOrAmbiguousConfigurationIsRejected(string server, string origin)
{
Assert.Throws<InvalidOperationException>(() => RelayOptions.Parse(server, origin, Token));
}
[Fact]
public void MigrateOldDefaultButPreserveCustomRelay()
{
var original = new DesktopSettings { Server = "wss://ads.ttstd.com" };
original.Migrate();
Assert.Equal(RelayOptions.DefaultServer, original.Server);
Assert.Equal(RelayOptions.DefaultOrigin, original.Origin);
var custom = new DesktopSettings { Server = "wss://private.example.test/path" };
custom.Migrate();
Assert.Equal("wss://private.example.test/path", custom.Server);
Assert.Equal("", custom.Origin);
}
[Fact]
public void TokenIsAnEnvironmentValueNotACommandArgument()
{
var options = RelayOptions.Parse(RelayOptions.DefaultServer, RelayOptions.DefaultOrigin, Token);
Assert.DoesNotContain(Token, options.ToString());
Assert.DoesNotContain(Token, new ClientCredential(Token, null).ToString());
var info = ProcessTools.ClientStartInfo("ads-client", "adb", options, "home-phone", "127.0.0.1:15555");
Assert.Equal(Token, info.Environment["ADS_CLIENT_TOKEN"]);
Assert.DoesNotContain(Token, info.ArgumentList);
Assert.Contains("--connect-address", info.ArgumentList);
Assert.Contains(RelayOptions.DefaultOrigin, info.ArgumentList);
Assert.DoesNotContain("ADS_AGENT_TOKEN", info.Environment.Keys);
Assert.DoesNotContain("ADB_SERVER_SOCKET", info.Environment.Keys);
}
[Fact]
public void ClientImportRejectsAgentRoleAndSettingsDoNotContainToken()
{
var folder = Path.Combine(DesktopPaths.ProjectRoot()!, "work", "desktop-tests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
var agentFile = Path.Combine(folder, "agent.env");
File.WriteAllText(agentFile, "ADS_AGENT_TOKEN=" + Token);
Assert.Throws<InvalidOperationException>(() => ClientCredential.Read(agentFile));
var clientFile = Path.Combine(folder, "client.env");
File.WriteAllText(clientFile, "ADS_CLIENT_TOKEN=" + Token + "\nADS_CONNECT_ADDRESS=" + RelayOptions.DefaultOrigin);
Assert.Equal(Token, ClientCredential.Read(clientFile).Token);
var settingsFile = Path.Combine(folder, "settings.json");
DesktopPaths.SaveSettings(settingsFile, new DesktopSettings { CredentialFile = clientFile });
Assert.DoesNotContain(Token, File.ReadAllText(settingsFile));
}
[Fact]
public async Task OriginOverrideStillRejectsAnUntrustedTlsCertificate()
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=relay.example.test", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
var names = new SubjectAlternativeNameBuilder(); names.AddDnsName("relay.example.test");
request.CertificateExtensions.Add(names.Build());
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1));
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(8));
var peer = Task.Run(async () =>
{
using var socket = await listener.AcceptTcpClientAsync(cancellation.Token);
using var tls = new SslStream(socket.GetStream());
try
{
await tls.AuthenticateAsServerAsync(new SslServerAuthenticationOptions
{
ServerCertificate = certificate, EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13
}, cancellation.Token);
var buffer = new byte[1024];
await tls.ReadAsync(buffer, cancellation.Token);
}
catch (Exception error) when (error is AuthenticationException or IOException or OperationCanceledException) { }
});
var options = RelayOptions.Parse("wss://relay.example.test/ads", $"127.0.0.1:{port}", Token);
await Assert.ThrowsAsync<HttpRequestException>(() => RelayApi.GetDevicesAsync(options, cancellation.Token));
await peer;
}
finally { listener.Stop(); }
}
}
-1
View File
@@ -2,4 +2,3 @@
<PropertyGroup><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup> <PropertyGroup><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.8"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup> <ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Avalonia.Themes.Fluent" Version="11.3.8"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup>
<ItemGroup><AvaloniaResource Include="Assets/**"/></ItemGroup></Project> <ItemGroup><AvaloniaResource Include="Assets/**"/></ItemGroup></Project>
+15 -2
View File
@@ -18,19 +18,32 @@ public partial class App : Application
desktop.MainWindow = window; desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
void Show() { window.Show(); window.WindowState = WindowState.Normal; window.Activate(); } void Show() { window.Show(); window.WindowState = WindowState.Normal; window.Activate(); }
async Task QuitAsync()
{
if (quitting) return;
quitting = true;
try { await vm.ShutdownAsync(); }
finally { desktop.Shutdown(); }
}
var menu = new NativeMenu(); var menu = new NativeMenu();
var show = new NativeMenuItem("打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show); var show = new NativeMenuItem("打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show);
menu.Items.Add(new NativeMenuItem("断开当前连接") { Command = vm.DisconnectCommand });
menu.Items.Add(new NativeMenuItemSeparator());
var quit = new NativeMenuItem("退出并断开连接"); var quit = new NativeMenuItem("退出并断开连接");
quit.Click += async (_, _) => { quitting = true; await vm.ShutdownAsync(); desktop.Shutdown(); }; quit.Click += async (_, _) => await QuitAsync();
menu.Items.Add(quit); menu.Items.Add(quit);
using var stream = Avalonia.Platform.AssetLoader.Open(new Uri("avares://Ads.Desktop/Assets/app.png")); using var stream = Avalonia.Platform.AssetLoader.Open(new Uri("avares://Ads.Desktop/Assets/app.png"));
var tray = new TrayIcon { ToolTipText = "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) }; var tray = new TrayIcon { ToolTipText = "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) };
TrayIcon.SetIcons(this, new TrayIcons { tray }); TrayIcon.SetIcons(this, new TrayIcons { tray });
vm.PropertyChanged += (_, change) => {
if (change.PropertyName is nameof(vm.Status) or nameof(vm.ActiveDeviceId))
tray.ToolTipText = "ADS · " + vm.Status;
};
window.Closing += async (_, e) => { window.Closing += async (_, e) => {
if (quitting) return; if (quitting) return;
e.Cancel = true; e.Cancel = true;
if (vm.MinimizeToTray) window.Hide(); if (vm.MinimizeToTray) window.Hide();
else { quitting = true; await vm.ShutdownAsync(); desktop.Shutdown(); } else await QuitAsync();
}; };
desktop.Exit += (_, _) => { tray.Dispose(); vm.Dispose(); }; desktop.Exit += (_, _) => { tray.Dispose(); vm.Dispose(); };
} }
+128
View File
@@ -0,0 +1,128 @@
using System.Text.Json;
namespace Ads.Desktop;
public sealed class DesktopSettings
{
public int Version { get; set; } = 2;
public string Server { get; set; } = RelayOptions.DefaultServer;
public string? Origin { get; set; }
public string Client { get; set; } = "";
public string Adb { get; set; } = "";
public string Scrcpy { get; set; } = "";
public int Port { get; set; } = 15555;
public int Size { get; set; } = 1920;
public int Fps { get; set; } = 60;
public bool Audio { get; set; }
public bool ViewOnly { get; set; }
public bool Tray { get; set; } = true;
public bool AutoRefresh { get; set; } = true;
public string CredentialFile { get; set; } = "";
public string PreferredDevice { get; set; } = "home-phone";
public void Migrate()
{
var oldDefault = Server.TrimEnd('/') is "wss://ads.ttstd.com" or "wss://devices.example.com";
if (oldDefault) Server = RelayOptions.DefaultServer;
Origin ??= oldDefault || Server.TrimEnd('/') == RelayOptions.DefaultServer ? RelayOptions.DefaultOrigin : "";
Version = 2;
}
}
public sealed record ClientCredential(string Token, string? Origin)
{
public override string ToString() => "ClientCredential { Token = [REDACTED] }";
public static ClientCredential Read(string path)
{
if (!File.Exists(path)) throw new InvalidOperationException("凭据文件不存在。");
if (new FileInfo(path).Length > 64 * 1024) throw new InvalidOperationException("凭据文件过大。");
string? token = null, origin = null;
foreach (var line in File.ReadLines(path))
{
var separator = line.IndexOf('=');
if (separator < 0) continue;
var name = line[..separator].Trim();
var value = line[(separator + 1)..].Trim();
if (name == "ADS_CLIENT_TOKEN") token = value;
if (name == "ADS_CONNECT_ADDRESS") origin = value;
}
if (token is null || token.Length < 32 || token.Contains('\r') || token.Contains('\n'))
throw new InvalidOperationException("文件中没有有效的 ADS_CLIENT_TOKEN,请选择 client.env。");
if (!string.IsNullOrWhiteSpace(origin)) RelayOptions.ParseOrigin(origin);
return new ClientCredential(token, origin);
}
}
public static class DesktopPaths
{
public static string SettingsFolder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TTSTD", "ADS");
public static string? ProjectRoot()
{
foreach (var start in new[] { AppContext.BaseDirectory, Environment.CurrentDirectory })
for (var directory = new DirectoryInfo(start); directory != null; directory = directory.Parent)
if (File.Exists(Path.Combine(directory.FullName, "Cargo.toml")) && Directory.Exists(Path.Combine(directory.FullName, "server")))
return directory.FullName;
return null;
}
public static string DefaultCredentialFile()
{
var adjacent = Path.Combine(AppContext.BaseDirectory, "client.env");
if (File.Exists(adjacent)) return adjacent;
var root = ProjectRoot();
return root is null ? "" : Path.Combine(root, "config", "private", "client.env");
}
public static string FindTool(string name)
{
var executable = OperatingSystem.IsWindows() ? name + ".exe" : name;
var candidates = new List<string>
{
Path.Combine(AppContext.BaseDirectory, executable),
Path.Combine(AppContext.BaseDirectory, "tools", executable),
Path.Combine(AppContext.BaseDirectory, "tools", "scrcpy", executable)
};
if (ProjectRoot() is { } root)
{
candidates.Add(Path.Combine(root, "bin", executable));
candidates.Add(Path.Combine(root, "bin", "tools", "scrcpy", executable));
}
if (name == "adb")
foreach (var variable in new[] { "ANDROID_HOME", "ANDROID_SDK_ROOT" })
if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } sdk)
candidates.Add(Path.Combine(sdk, "platform-tools", executable));
candidates.AddRange((Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)
.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => Path.Combine(p.Trim('"'), executable)));
return candidates.FirstOrDefault(File.Exists) ?? name;
}
public static string ResolveTool(string value, string name)
{
value = Environment.ExpandEnvironmentVariables(value.Trim().Trim('"'));
if (File.Exists(value)) return Path.GetFullPath(value);
if (value == name || value == name + ".exe")
{
var found = FindTool(name);
if (File.Exists(found)) return Path.GetFullPath(found);
}
throw new InvalidOperationException($"找不到 {name},请在连接配置中选择可执行文件。");
}
public static DesktopSettings LoadSettings(string file)
{
var settings = File.Exists(file)
? JsonSerializer.Deserialize<DesktopSettings>(File.ReadAllText(file)) ?? new DesktopSettings()
: new DesktopSettings();
settings.Migrate();
return settings;
}
public static void SaveSettings(string file, DesktopSettings settings)
{
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
var temporary = file + ".tmp";
File.WriteAllText(temporary, JsonSerializer.Serialize(settings, new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, file, overwrite: true);
}
}
+471 -38
View File
@@ -1,61 +1,494 @@
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Http.Headers; using System.Text.RegularExpressions;
using System.Net.Http.Json;
using System.Text.Json;
using Avalonia.Threading; using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
namespace Ads.Desktop; namespace Ads.Desktop;
public record Device(string Id,bool Busy) { public string Description=>Busy?"在线 · 已占用":"在线 · 可连接"; }
public sealed record DeviceItem(string Id, bool Busy, bool IsLocal)
{
public string Description => IsLocal ? "本机正在使用" : Busy ? "在线 · 其他客户端使用中" : "在线 · 可连接";
}
public partial class MainViewModel : ObservableObject, IDisposable public partial class MainViewModel : ObservableObject, IDisposable
{ {
[ObservableProperty] private string server="wss://ads.ttstd.com"; [ObservableProperty] private string server = RelayOptions.DefaultServer;
[ObservableProperty] private string token=Environment.GetEnvironmentVariable("ADS_CLIENT_TOKEN")??""; [ObservableProperty] private string origin = RelayOptions.DefaultOrigin;
[ObservableProperty] private string clientPath=FindClient(); [ObservableProperty] private string token = "";
[ObservableProperty] private string adbPath="adb"; [ObservableProperty] private string clientPath = DesktopPaths.FindTool("ads-client");
[ObservableProperty] private string scrcpyPath="scrcpy"; [ObservableProperty] private string adbPath = DesktopPaths.FindTool("adb");
[ObservableProperty] private string scrcpyPath = DesktopPaths.FindTool("scrcpy");
[ObservableProperty] private int port = 15555; [ObservableProperty] private int port = 15555;
[ObservableProperty] private int maxSize = 1920; [ObservableProperty] private int maxSize = 1920;
[ObservableProperty] private int maxFps = 60; [ObservableProperty] private int maxFps = 60;
[ObservableProperty] private bool audio; [ObservableProperty] private bool audio;
[ObservableProperty] private bool viewOnly; [ObservableProperty] private bool viewOnly;
[ObservableProperty] private bool minimizeToTray = true; [ObservableProperty] private bool minimizeToTray = true;
[ObservableProperty] private Device? selectedDevice; [ObservableProperty] private bool autoRefresh = true;
[ObservableProperty] private DeviceItem? selectedDevice;
[ObservableProperty] private string status = "尚未连接"; [ObservableProperty] private string status = "尚未连接";
[ObservableProperty] private string activeEndpoint="请选择在线设备"; [ObservableProperty] private string activeEndpoint = "选择设备后建立本地 ADB 通道";
[ObservableProperty] private string notice="填写客户端令牌,然后刷新设备。"; [ObservableProperty] private string notice = "正在准备连接配置。";
[ObservableProperty] private string deviceSummary = "尚未刷新"; [ObservableProperty] private string deviceSummary = "尚未刷新";
public ObservableCollection<Device> Devices {get;}=new(); [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 ObservableCollection<string> Logs { get; } = new();
public string? Endpoint => endpoint;
public string? ActiveDeviceId => activeId;
private Process? client, scrcpy; private Process? client, scrcpy;
private string? endpoint, activeAdb, activeId; private string? endpoint, activeAdb, activeId;
private bool probing,stopping; private string credentialFile = "", preferredDevice = "home-phone";
private bool monitoring, disposed, initialized;
private DateTime lastRefresh;
private string? lastRefreshError;
private readonly DispatcherTimer timer; private readonly DispatcherTimer timer;
private readonly HttpClient http=new(new HttpClientHandler{AllowAutoRedirect=false}){Timeout=TimeSpan.FromSeconds(10)}; private readonly CancellationTokenSource lifetime = new();
private static readonly string Folder=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"TTSTD","ADS"); private readonly SemaphoreSlim connectionGate = new(1, 1);
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; } private readonly HashSet<string> secrets = new(StringComparer.Ordinal);
public MainViewModel() { private readonly string folder, settingsFile;
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);} private static readonly Regex Ansi = new(@"\x1B\[[0-?]*[ -/]*[@-~]", RegexOptions.Compiled);
timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(3)};timer.Tick+=async(_,_)=>await ProbeAsync();timer.Start();
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;
} }
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);}); catch (Exception error) { Log("读取配置失败,使用默认值:" + error.Message); }
private async Task Guard(Func<Task> f){try{await f();}catch(Exception e){Notice=e.Message;Log(e.Message);}} var environmentToken = loadLocalCredentials ? Environment.GetEnvironmentVariable("ADS_CLIENT_TOKEN") : null;
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;} if (!string.IsNullOrWhiteSpace(environmentToken))
[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;} Token = environmentToken.Trim(); CredentialSource = "来自 ADS_CLIENT_TOKEN 环境变量";
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;}); else if (loadLocalCredentials)
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;}} if (credentialFile.Length == 0) credentialFile = DesktopPaths.DefaultCredentialFile();
[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="手机控制已启动,详情见日志。";}); if (File.Exists(credentialFile)) LoadCredentials(credentialFile, useOrigin: false);
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);} Notice = Token.Length >= 32 ? "配置已就绪,正在等待刷新设备。" : "请在连接配置中导入 client.env。";
[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;}} timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
private record Settings(string Server,string Client,string Adb,string Scrcpy,int Port,int Size,int Fps,bool Audio,bool ViewOnly,bool Tray); timer.Tick += async (_, _) => await MonitorAsync();
[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;}} 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 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;}} [RelayCommand] private void ExportLogs()
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();}} 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();
}
} }
+101 -40
View File
@@ -1,54 +1,115 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Ads.Desktop.MainWindow" Title="ADS · Android 设备工作台" Width="1180" Height="820" MinWidth="900" MinHeight="640" Background="#10151F"> <Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Ads.Desktop.MainWindow" Title="ADS · 公网设备工作台"
Width="1240" Height="880" MinWidth="980" MinHeight="700" Background="#10151F">
<Window.Styles> <Window.Styles>
<Style Selector="TextBox"><Setter Property="Margin" Value="0,4,0,10"/></Style> <Style Selector="TextBox"><Setter Property="Margin" Value="0,5,0,12"/></Style>
<Style Selector="Button"><Setter Property="Padding" Value="16,10"/><Setter Property="Margin" Value="0,0,8,0"/></Style> <Style Selector="Button"><Setter Property="Padding" Value="15,10"/><Setter Property="Margin" Value="0,0,8,8"/></Style>
<Style Selector="TextBlock.label"><Setter Property="Foreground" Value="#9CAFC7"/></Style> <Style Selector="TextBlock.label"><Setter Property="Foreground" Value="#9CAFC7"/></Style>
<Style Selector="TextBlock.section"><Setter Property="FontSize" Value="18"/><Setter Property="FontWeight" Value="SemiBold"/></Style>
<Style Selector="Border.card"><Setter Property="Background" Value="#192230"/><Setter Property="CornerRadius" Value="12"/><Setter Property="Padding" Value="20"/></Style>
</Window.Styles> </Window.Styles>
<Grid RowDefinitions="Auto,*,Auto" Margin="28"> <Grid RowDefinitions="Auto,*,Auto" Margin="26">
<Grid ColumnDefinitions="*,Auto" Margin="0,0,0,22"> <Grid ColumnDefinitions="*,Auto" Margin="0,0,0,20">
<StackPanel><TextBlock Text="ANDROID DEVICE STREAMING" Foreground="#66D9C0" FontSize="12" LetterSpacing="3"/><TextBlock Text="设备工作台" FontSize="30" FontWeight="Bold" Margin="0,8,0,4"/><TextBlock Text="远程连接 · 本地调试 · 手机控制" Classes="label"/></StackPanel> <StackPanel Spacing="5">
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center"><Button Content="刷新设备" Command="{Binding RefreshCommand}"/><Button Content="保存配置" Command="{Binding SaveCommand}"/></StackPanel> <TextBlock Text="ANDROID DEVICE STREAMING" Foreground="#66D9C0" FontSize="11" LetterSpacing="3"/>
<TextBlock Text="公网设备工作台" FontSize="29" FontWeight="Bold"/>
<TextBlock Text="连接远程手机,在本机调试与控制" Classes="label"/>
</StackPanel>
<StackPanel Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" Spacing="8">
<TextBlock x:Name="RelayStatusText" Text="{Binding RelayStatus}" HorizontalAlignment="Right" Foreground="#66D9C0"/>
<StackPanel Orientation="Horizontal"><Button x:Name="RefreshButton" Content="刷新设备" Command="{Binding RefreshCommand}"/><Button Content="保存配置" Command="{Binding SaveCommand}"/></StackPanel>
</StackPanel>
</Grid> </Grid>
<TabControl Grid.Row="1"> <TabControl x:Name="MainTabs" Grid.Row="1">
<TabItem Header="设备与连接"> <TabItem Header="设备与连接">
<Grid ColumnDefinitions="2*,3*" Margin="0,16,0,0"> <Grid ColumnDefinitions="320,*" Margin="0,16,0,0">
<Border Background="#192230" CornerRadius="12" Padding="18" Margin="0,0,16,0"> <Border Classes="card" Margin="0,0,16,0">
<Grid RowDefinitions="Auto,*,Auto"><TextBlock Text="在线设备" FontSize="18" FontWeight="SemiBold"/> <Grid RowDefinitions="Auto,*,Auto,Auto">
<ListBox Grid.Row="1" ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice}" Margin="0,16,0,12" Background="Transparent"> <TextBlock Text="在线设备" Classes="section"/>
<ListBox.ItemTemplate><DataTemplate><StackPanel Margin="6,10"><TextBlock Text="{Binding Id}" FontSize="17"/><TextBlock Text="{Binding Description}" Foreground="#9CAFC7" Margin="0,6,0,0"/></StackPanel></DataTemplate></ListBox.ItemTemplate> <ListBox x:Name="DeviceList" Grid.Row="1" ItemsSource="{Binding Devices}" SelectedItem="{Binding SelectedDevice}" Margin="0,14,0,12" Background="Transparent">
<ListBox.ItemTemplate><DataTemplate><StackPanel Margin="5,10" Spacing="6"><TextBlock Text="{Binding Id}" FontSize="17" TextWrapping="Wrap"/><TextBlock Text="{Binding Description}" Classes="label" TextWrapping="Wrap"/></StackPanel></DataTemplate></ListBox.ItemTemplate>
</ListBox> </ListBox>
<TextBlock Grid.Row="2" Text="{Binding DeviceSummary}" Classes="label" TextWrapping="Wrap"/> <TextBlock Grid.Row="2" Text="{Binding DeviceSummary}" Classes="label" TextWrapping="Wrap"/>
<CheckBox Grid.Row="3" Content="自动刷新设备列表" IsChecked="{Binding AutoRefresh}" Margin="0,12,0,0"/>
</Grid> </Grid>
</Border> </Border>
<ScrollViewer Grid.Column="1"><StackPanel Spacing="12"> <ScrollViewer Grid.Column="1">
<TextBlock Text="连接管理" FontSize="22" FontWeight="SemiBold"/> <StackPanel Spacing="14">
<TextBlock Text="{Binding Status}" Foreground="#66D9C0" FontSize="16" TextWrapping="Wrap"/> <Border Classes="card">
<TextBlock Text="{Binding ActiveEndpoint}" Classes="label"/> <StackPanel Spacing="12">
<StackPanel Orientation="Horizontal"><Button Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button Content="断开连接" Command="{Binding DisconnectCommand}"/></StackPanel> <TextBlock Text="连接管理" Classes="section"/>
<Border Background="#192230" CornerRadius="12" Padding="20" Margin="0,12,0,0"><StackPanel Spacing="12"> <TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
<TextBlock Text="scrcpy 手机控制" FontSize="19" FontWeight="SemiBold"/> <TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
<TextBlock Text="连接成功并完成手机 USB 调试授权后,在独立窗口中显示与操作手机。" TextWrapping="Wrap" Classes="label"/> <WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/></WrapPanel>
<Grid ColumnDefinitions="*,*"><StackPanel><TextBlock Text="最大分辨率"/><TextBox Text="{Binding MaxSize}"/></StackPanel><StackPanel Grid.Column="1" Margin="12,0,0,0"><TextBlock Text="最大帧率"/><TextBox Text="{Binding MaxFps}"/></StackPanel></Grid> <TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
<CheckBox Content="传输手机音频" IsChecked="{Binding Audio}"/> </StackPanel>
<CheckBox Content="只看画面(禁止控制输入)" IsChecked="{Binding ViewOnly}"/> </Border>
<StackPanel Orientation="Horizontal"><Button Content="打开手机控制" Command="{Binding StartScrcpyCommand}"/><Button Content="停止投屏" Command="{Binding StopScrcpyCommand}"/></StackPanel> <Border Classes="card">
</StackPanel></Border> <StackPanel Spacing="12">
<TextBlock Text="提示:unauthorized 表示需要在手机上允许调试;设备被占用时需要先释放其他客户端的连接。" TextWrapping="Wrap" Classes="label"/> <Grid ColumnDefinitions="*,Auto"><TextBlock Text="设备信息" Classes="section"/><Button Grid.Column="1" Content="更新信息" Command="{Binding ReadDeviceInfoCommand}" Padding="12,6" Margin="0"/></Grid>
</StackPanel></ScrollViewer> <Grid ColumnDefinitions="2*,*,*">
<StackPanel Spacing="5"><TextBlock Text="型号" Classes="label"/><TextBlock x:Name="ModelText" Text="{Binding Model}" FontSize="16" TextWrapping="Wrap"/></StackPanel>
<StackPanel Grid.Column="1" Spacing="5" Margin="12,0"><TextBlock Text="Android" Classes="label"/><TextBlock Text="{Binding AndroidVersion}" FontSize="16"/></StackPanel>
<StackPanel Grid.Column="2" Spacing="5"><TextBlock Text="API 等级" Classes="label"/><TextBlock Text="{Binding ApiLevel}" FontSize="16"/></StackPanel>
</Grid>
</StackPanel>
</Border>
<Border Classes="card">
<StackPanel Spacing="10">
<TextBlock Text="手机画面与控制" Classes="section"/>
<TextBlock Text="设备就绪后打开独立控制窗口,可使用鼠标和键盘。" TextWrapping="Wrap" Classes="label"/>
<Grid ColumnDefinitions="*,*">
<StackPanel><TextBlock Text="最大分辨率" Classes="label"/><NumericUpDown Value="{Binding MaxSize}" Minimum="256" Maximum="8192" Increment="128" Margin="0,6,8,4"/></StackPanel>
<StackPanel Grid.Column="1"><TextBlock Text="最大帧率" Classes="label"/><NumericUpDown Value="{Binding MaxFps}" Minimum="1" Maximum="240" Increment="10" Margin="8,6,0,4"/></StackPanel>
</Grid>
<WrapPanel><CheckBox Content="传输音频" IsChecked="{Binding Audio}" Margin="0,0,24,0"/><CheckBox Content="只看画面" IsChecked="{Binding ViewOnly}"/></WrapPanel>
<WrapPanel><Button x:Name="StartScreenButton" Content="打开手机控制" Command="{Binding StartScrcpyCommand}"/><Button Content="停止投屏" Command="{Binding StopScrcpyCommand}"/></WrapPanel>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="连接配置">
<ScrollViewer>
<StackPanel Margin="4,18" MaxWidth="880" Spacing="16">
<Border Classes="card"><StackPanel>
<TextBlock Text="公网中继" Classes="section" Margin="0,0,0,12"/>
<TextBlock Text="中继地址(WSS,可包含路径)"/><TextBox x:Name="ServerBox" Text="{Binding Server}" Watermark="wss://ttstd.com/ads"/>
<TextBlock Text="直连服务器(可选)"/><TextBox x:Name="OriginBox" Text="{Binding Origin}" Watermark="175.178.213.60:443"/>
<TextBlock Text="留空则按域名解析;指定公网 IP 时仍验证域名证书。当前部署使用此设置避开 Cloudflare 连接超时。" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
<Border Classes="card"><StackPanel Spacing="6">
<TextBlock Text="客户端凭据" Classes="section" Margin="0,0,0,6"/>
<TextBlock x:Name="CredentialSourceText" Text="{Binding CredentialSource}" Classes="label" TextWrapping="Wrap"/>
<TextBox Text="{Binding Token}" PasswordChar="●" Watermark="ADS_CLIENT_TOKEN"/>
<WrapPanel><Button Content="导入 client.env" Click="ImportCredentialsClick"/><Button Content="刷新设备" Command="{Binding RefreshCommand}"/></WrapPanel>
<TextBlock Text="凭据自动从项目的 config/private/client.env 或环境变量读取。保存配置不保存令牌内容;不要使用 agent.env。" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
<Border Classes="card"><StackPanel>
<Grid ColumnDefinitions="*,Auto"><TextBlock Text="本机工具" Classes="section"/><Button Grid.Column="1" Content="检查工具" Command="{Binding CheckToolsCommand}" Padding="12,6" Margin="0,0,0,10"/></Grid>
<TextBlock Text="ads-client 可执行文件"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding ClientPath}"/><Button Grid.Column="1" Content="选择" Tag="client" Click="ChooseToolClick" Margin="10,5,0,12"/></Grid>
<TextBlock Text="ADB 可执行文件"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding AdbPath}"/><Button Grid.Column="1" Content="选择" Tag="adb" Click="ChooseToolClick" Margin="10,5,0,12"/></Grid>
<TextBlock Text="scrcpy 可执行文件"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding ScrcpyPath}"/><Button Grid.Column="1" Content="选择" Tag="scrcpy" Click="ChooseToolClick" Margin="10,5,0,12"/></Grid>
<TextBlock Text="{Binding ToolsStatus}" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
<Border Classes="card"><StackPanel Spacing="12">
<TextBlock Text="本地连接" Classes="section"/>
<Grid ColumnDefinitions="*,180"><TextBlock Text="本地 ADB 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}"/>
<TextBlock Text="配置修改在下一次连接生效。完全退出工作台会停止本机连接;远程守护程序继续运行。" TextWrapping="Wrap" Classes="label"/>
<Button Content="保存配置" Command="{Binding SaveCommand}" HorizontalAlignment="Left"/>
</StackPanel></Border>
</StackPanel>
</ScrollViewer>
</TabItem>
<TabItem Header="运行日志">
<Grid RowDefinitions="Auto,*" Margin="0,16,0,0">
<StackPanel Orientation="Horizontal"><Button Content="清空日志" Command="{Binding ClearLogsCommand}"/><Button Content="导出日志" Command="{Binding ExportLogsCommand}"/></StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Logs}" Margin="0,8,0,0" FontFamily="Cascadia Mono,Consolas" FontSize="12"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding}" TextWrapping="Wrap"/></DataTemplate></ListBox.ItemTemplate></ListBox>
</Grid> </Grid>
</TabItem> </TabItem>
<TabItem Header="连接配置"><ScrollViewer><StackPanel Margin="4,18" MaxWidth="780" HorizontalAlignment="Stretch">
<TextBlock Text="中继服务器(WSS)"/><TextBox Text="{Binding Server}" Watermark="wss://ads.ttstd.com"/>
<TextBlock Text="客户端令牌(仅当前进程使用,不写入配置)"/><TextBox Text="{Binding Token}" PasswordChar="●"/>
<TextBlock Text="ads-client 可执行文件"/><TextBox Text="{Binding ClientPath}"/>
<TextBlock Text="ADB 可执行文件"/><TextBox Text="{Binding AdbPath}"/>
<TextBlock Text="scrcpy 可执行文件(选择官方发行包中的程序)"/><TextBox Text="{Binding ScrcpyPath}"/>
<TextBlock Text="本地 ADB 隧道端口"/><TextBox Text="{Binding Port}"/>
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}" Margin="0,12"/>
<TextBlock Text="配置修改在下一次连接时生效。令牌也可通过 ADS_CLIENT_TOKEN 环境变量提供。" TextWrapping="Wrap" Classes="label"/>
</StackPanel></ScrollViewer></TabItem>
<TabItem Header="运行日志"><Grid RowDefinitions="Auto,*" Margin="0,16,0,0"><StackPanel Orientation="Horizontal"><Button Content="清空日志" Command="{Binding ClearLogsCommand}"/><Button Content="导出日志" Command="{Binding ExportLogsCommand}"/></StackPanel><ListBox Grid.Row="1" ItemsSource="{Binding Logs}" Margin="0,12,0,0" FontFamily="Cascadia Mono,Consolas" FontSize="12"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding}" TextWrapping="Wrap"/></DataTemplate></ListBox.ItemTemplate></ListBox></Grid></TabItem>
</TabControl> </TabControl>
<TextBlock Grid.Row="2" Text="{Binding Notice}" Foreground="#A8B7CC" Margin="0,18,0,0" TextWrapping="Wrap"/> <TextBlock Grid.Row="2" x:Name="NoticeText" Text="{Binding Notice}" Foreground="#A8B7CC" Margin="0,18,0,0" TextWrapping="Wrap" MaxHeight="70"/>
</Grid> </Grid>
</Window> </Window>
+48 -1
View File
@@ -1,6 +1,53 @@
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
namespace Ads.Desktop; namespace Ads.Desktop;
public partial class MainWindow : Window public partial class MainWindow : Window
{ {
public MainWindow() { InitializeComponent(); } public MainWindow()
{
InitializeComponent();
Opened += async (_, _) => { if (DataContext is MainViewModel vm) await vm.InitializeAsync(); };
}
private async void ImportCredentialsClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not MainViewModel vm) return;
try
{
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
Title = "选择客户端凭据 client.env", AllowMultiple = false,
FileTypeFilter = [new FilePickerFileType("环境配置文件") { Patterns = ["*.env"] }, FilePickerFileTypes.All]
});
if (files.FirstOrDefault()?.TryGetLocalPath() is { } path) vm.LoadCredentials(path);
}
catch { vm.Notice = "无法打开凭据文件,请检查文件访问权限。"; }
}
private async void ChooseToolClick(object? sender, RoutedEventArgs e)
{
if (DataContext is not MainViewModel vm || sender is not Button button) return;
try
{
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "选择可执行文件", AllowMultiple = false });
if (files.FirstOrDefault()?.TryGetLocalPath() is not { } path) return;
switch (button.Tag as string)
{
case "client": vm.ClientPath = path; break;
case "adb": vm.AdbPath = path; break;
case "scrcpy": vm.ScrcpyPath = path; break;
}
}
catch { vm.Notice = "无法选择工具,请检查文件访问权限。"; }
}
private async void CopyEndpointClick(object? sender, RoutedEventArgs e)
{
if (DataContext is MainViewModel { Endpoint: { } endpoint } vm && Clipboard != null)
{
try { await Clipboard.SetTextAsync(endpoint); vm.Notice = "已复制本地 ADB 地址:" + endpoint; }
catch { vm.Notice = "无法访问系统剪贴板。"; }
}
}
} }
+63
View File
@@ -0,0 +1,63 @@
using System.Diagnostics;
namespace Ads.Desktop;
public sealed record ProcessResult(int ExitCode, string Output, string Error);
public static class ProcessTools
{
public static ProcessStartInfo CreateStartInfo(string executable, IEnumerable<string> arguments)
{
var info = new ProcessStartInfo(executable)
{
UseShellExecute = false, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardError = true
};
foreach (var argument in arguments) info.ArgumentList.Add(argument);
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_CONNECT_ADDRESS" })
info.Environment.Remove(key);
info.Environment["NO_COLOR"] = "1";
return info;
}
public static ProcessStartInfo ClientStartInfo(string executable, string adb, RelayOptions relay, string device, string endpoint)
{
var arguments = new List<string> { "--server", relay.BaseUri.ToString().TrimEnd('/'), "--device", device, "--listen", endpoint, "--adb", adb };
if (relay.Origin.Length > 0) arguments.AddRange(["--connect-address", relay.Origin]);
var info = CreateStartInfo(executable, arguments);
info.Environment["ADS_CLIENT_TOKEN"] = relay.Token;
return info;
}
public static async Task<ProcessResult> RunAsync(ProcessStartInfo info, CancellationToken cancellation = default)
{
using var process = Process.Start(info) ?? throw new InvalidOperationException("程序无法启动。");
var output = process.StandardOutput.ReadToEndAsync();
var error = process.StandardError.ReadToEndAsync();
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
try { await process.WaitForExitAsync(timeout.Token); }
catch
{
if (!process.HasExited) process.Kill(entireProcessTree: true);
throw;
}
return new ProcessResult(process.ExitCode, await output, await error);
}
public static async Task StopAsync(Process? process)
{
if (process == null) return;
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await process.WaitForExitAsync(timeout.Token);
}
}
catch (InvalidOperationException) when (process.HasExited) { }
finally { process.Dispose(); }
}
}
+98
View File
@@ -0,0 +1,98 @@
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Net.Sockets;
namespace Ads.Desktop;
public sealed record RelayOptions(Uri BaseUri, string Origin, string Token)
{
public const string DefaultServer = "wss://ttstd.com/ads";
public const string DefaultOrigin = "175.178.213.60:443";
public override string ToString() => $"RelayOptions {{ BaseUri = {BaseUri}, Origin = {Origin}, Token = [REDACTED] }}";
public static Uri ParseBaseUri(string server)
{
if (!Uri.TryCreate(server.Trim(), UriKind.Absolute, out var uri) ||
uri.Scheme != "wss" || string.IsNullOrEmpty(uri.Host) ||
uri.Query.Length != 0 || uri.Fragment.Length != 0 || uri.UserInfo.Length != 0)
throw new InvalidOperationException("请输入有效的 WSS 中继地址,可以包含 /ads 路径。");
return uri;
}
public static RelayOptions Parse(string server, string origin, string token)
{
var uri = ParseBaseUri(server);
if (token.Length < 32 || token.Contains('\r') || token.Contains('\n'))
throw new InvalidOperationException("请导入有效的客户端令牌(至少 32 个字符)。");
origin = origin.Trim();
if (origin.Length > 0) ParseOrigin(origin);
return new RelayOptions(uri, origin, token);
}
public static DnsEndPoint ParseOrigin(string origin)
{
if (!Uri.TryCreate("tcp://" + origin, UriKind.Absolute, out var uri) ||
uri.Port is < 1 or > 65535 || string.IsNullOrEmpty(uri.Host) ||
uri.UserInfo.Length != 0 || uri.AbsolutePath != "/" ||
uri.Query.Length != 0 || uri.Fragment.Length != 0)
throw new InvalidOperationException("直连服务器请填写 IP或主机名:端口,例如 175.178.213.60:443;也可以留空。");
return new DnsEndPoint(uri.IdnHost.Trim('[', ']'), uri.Port);
}
public Uri DevicesUri => new UriBuilder(BaseUri)
{
Scheme = "https",
Port = BaseUri.Port > 0 ? BaseUri.Port : 443,
Path = BaseUri.AbsolutePath.TrimEnd('/') + "/v1/devices"
}.Uri;
}
public sealed record RelayDevice(string Id, bool Busy);
public static class RelayApi
{
public static HttpClient CreateClient(RelayOptions options)
{
var handler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
UseProxy = false,
ConnectTimeout = TimeSpan.FromSeconds(8)
};
if (!string.IsNullOrWhiteSpace(options.Origin))
{
var origin = RelayOptions.ParseOrigin(options.Origin);
handler.ConnectCallback = async (_, cancellation) =>
{
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
{
await socket.ConnectAsync(origin, cancellation);
return new NetworkStream(socket, ownsSocket: true);
}
catch { socket.Dispose(); throw; }
};
}
// Only TCP resolution is overridden. HttpClient still supplies the URL's
// hostname for TLS SNI and normal certificate/hostname validation.
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(12) };
}
public static async Task<RelayDevice[]> GetDevicesAsync(RelayOptions options, CancellationToken cancellation = default)
{
using var http = CreateClient(options);
using var request = new HttpRequestMessage(HttpMethod.Get, options.DevicesUri);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.Token);
using var response = await http.SendAsync(request, cancellation);
if (response.StatusCode == HttpStatusCode.Unauthorized)
throw new InvalidOperationException("客户端令牌无效,请导入 client.env,而不是 agent.env。");
if (!response.IsSuccessStatusCode)
throw new InvalidOperationException($"中继返回 HTTP {(int)response.StatusCode},请检查地址与服务状态。");
var devices = await response.Content.ReadFromJsonAsync<RelayDevice[]>(cancellationToken: cancellation) ?? [];
if (devices.Any(d => string.IsNullOrWhiteSpace(d.Id) || d.Id.Length > 128 ||
d.Id.Any(c => !char.IsAsciiLetterOrDigit(c) && c != '-' && c != '_' && c != '.')))
throw new InvalidOperationException("中继返回了无效的设备 ID。");
return devices.OrderBy(d => d.Id, StringComparer.Ordinal).ToArray();
}
}
+27 -9
View File
@@ -12,11 +12,12 @@ dotnet run --project Ads.Desktop -c Release
或运行 `desktop/Ads.Desktop/bin/Release/net8.0/Ads.Desktop.exe`。 或运行 `desktop/Ads.Desktop/bin/Release/net8.0/Ads.Desktop.exe`。
1. 在“连接配置”填写中继 WSS 根地址和 **客户端令牌**(不是 agent 令牌)。默认 `wss://ads.ttstd.com`;服务器域名与 TLS 必须已部署完成。 1. 默认公网中继已同步为 `wss://ttstd.com/ads`,直连服务器为 `175.178.213.60:443`。设备 API 和 Rust 子进程都使用同一套地址、路径前缀和直连设置;TLS 仍按 `ttstd.com` 验证。直连留空时使用正常域名解析,不使用系统 HTTP 代理。
2. 设置 ads-client、ADB、scrcpy 的可执行文件路径。开发目录自动查找根目录 `bin/ads-client.exe`;ADB 和 scrcpy 默认使用 PATH。仓库 `adb/`、`scrcpy/` 是源码目录,不能作为可执行文件使用。 2. 自动读取 `ADS_CLIENT_TOKEN` 环境变量,或项目 `config/private/client.env`,也支持应用旁的 `client.env`。也可在“连接配置”导入文件;拒绝仅有 agent 角色令牌的文件。发布包不包含令牌。
3. 刷新设备,选择空闲设备并连接。状态每 3 秒从本机 ADB 检查;未取得租约时显示等待状态,详细错误见日志。 3. 自动查找 ads-client、ADB 和 scrcpy。Windows 分发包附带 ads-client 和完整 scrcpy 官方运行目录(包含 ADB);也可选择自己的工具路径,并使用“检查工具”。仓库 `adb/`、`scrcpy/` 是源码,不能作为可执行文件使用。
4. 手机允许调试后,点击“打开手机控制”。scrcpy 使用独立窗口,支持鼠标、键盘操作;可设置分辨率、帧率、音频与只读模式。强制 `--force-adb-forward`,避免反向连接无法穿过中继。 4. 自动每 10 秒刷新在线设备,状态每 3 秒从本机 ADB 检查。支持连接、断开、重新连接、读取型号/Android/API 等级、复制本地 ADB 地址。当前占用标记区分“本机正在使用”和其他客户端占用。
5. 关闭窗口默认进入托盘,右键托盘可重新打开或退出。取消托盘选项后关闭窗口会退出。退出会停止本应用启动的 scrcpy、ads-client,并只断开所用 ADB 端点。 5. 手机允许调试后,点击“打开手机控制”。scrcpy 使用独立窗口,支持鼠标、键盘操作;可设置分辨率、帧率、音频与只读模式。强制 `--force-adb-forward`,避免反向连接无法穿过中继。
6. 关闭窗口默认进入托盘,右键托盘可重新打开、断开连接或退出。取消托盘选项后关闭窗口会退出。退出会停止本应用启动的 scrcpy、ads-client,并只断开所用 ADB 端点;远程守护程序继续运行。
请从 scrcpy 官方发行包安装程序及配套 server、DLL 等文件,不要只复制 scrcpy.exe。首次调试必须在手机端授权。 请从 scrcpy 官方发行包安装程序及配套 server、DLL 等文件,不要只复制 scrcpy.exe。首次调试必须在手机端授权。
@@ -24,14 +25,31 @@ dotnet run --project Ads.Desktop -c Release
UI 使用 `/v1/devices` 的 Bearer 认证接口并管理现有 Rust ads-client 子进程,不承担 ADB 数据转发,也未新增本机 HTTP 管理 API。一次管理一个远程连接;断线重连由 ads-client 负责。完全退出 UI 后不保留后台守护进程。连接配置修改在下次连接生效。 UI 使用 `/v1/devices` 的 Bearer 认证接口并管理现有 Rust ads-client 子进程,不承担 ADB 数据转发,也未新增本机 HTTP 管理 API。一次管理一个远程连接;断线重连由 ads-client 负责。完全退出 UI 后不保留后台守护进程。连接配置修改在下次连接生效。
令牌仅保存在内存,通过 `ADS_CLIENT_TOKEN` 子进程环境变量传递,可在启动 UI 前设置该环境变量。配置保存在系统 LocalApplicationData 下 `TTSTD/ADS/settings.json`,不包含令牌。日志最多保留 1000 条,可导出到同目录;不自动落盘。 令牌仅保存在内存,通过 `ADS_CLIENT_TOKEN` 子进程环境变量传递,不出现在命令参数、配置或日志中。配置保存在系统 LocalApplicationData 下 `TTSTD/ADS/settings.json`,只记住非敏感连接配置和凭据文件路径。旧的默认子域名配置会自动迁移到当前公网地址,自定义中继地址保持不变。日志最多保留 1000 条,可导出到同目录;不自动落盘。子进程不继承远程 ADB Server 或 agent 角色凭据环境变量。
托盘需要桌面环境支持;Linux 桌面可能需要 AppIndicator。未在 Linux/macOS 或真实手机上验收此 UI。真实投屏仍需远程 agent 在线、手机 TCP ADB 已开启且本机密钥获得手机授权。 托盘需要桌面环境支持;Linux 桌面可能需要 AppIndicator。当前在 Windows 完成构建、Avalonia 离屏布局和真实公网手机连接测试;Linux/macOS 尚未运行验收。设备列表表示网关在线,实际手机就绪状态以本地 ADB 检测为准。一次管理一个远程连接,不提供远程守护重启、SSH 或服务器管理。USB 模拟仍仅为 AGENTS.md 中的后续方案,没有在本次加入。
## 发布 ## 发布
```powershell ```powershell
dotnet publish Ads.Desktop -c Release -r win-x64 --self-contained true -o ../bin/desktop-win-x64 # 在项目根目录运行
.\scripts\build-desktop.ps1
.\scripts\start-desktop.ps1
``` ```
将对应平台的 ads-client 放到 PATH,或在设置指定绝对路径,同时安装 ADB 与 scrcpy。 产物:`bin/desktop-win-x64/Ads.Desktop.exe`,Windows 自包含包无需另装 .NET。构建脚本会复制已准备好的 `bin/ads-client.exe` 和 `bin/tools/scrcpy/`,不会复制凭据。将整个目录分发,不要只复制 exe。离开项目目录使用时,导入用户自己的 client.env。
当前随项目准备的 scrcpy 为官方 5.0.1 Windows x64 包,下载 ZIP 的 SHA-256 已对照官方说明验证:`b12a2c4ee8be317422451fc7dcf8ee20a71b5ea7ef9ad73ddd825a25316227a5`。来源:[scrcpy 官方 Windows 说明](https://github.com/Genymobile/scrcpy/blob/master/doc/windows.md)。
## 验证
在 `desktop/` 运行:
```powershell
dotnet test Ads.Desktop.Tests -c Debug
dotnet run --project Ads.Desktop.Smoke -c Debug
# 会连接真实 home-phone,仅在设备空闲且本地具有 client.env 时运行:
dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen
```
单元测试覆盖路径前缀、源站配置、旧默认地址迁移、角色凭据隔离、不可信证书拒绝、环境变量与保存配置。离屏测试加载真实 XAML,覆盖按钮可用状态、实际设备发现/连接/型号显示/重连/释放、scrcpy 视频纹理启动与停止。示例布局图片写入 `work/`。原生 Windows 自动化运行时本次初始化失败,因此未自动点击真实原生窗口或验证托盘菜单;不是把无头测试当作原生点击验收。
+2
View File
@@ -59,6 +59,8 @@ TLS 沿用现有主站证书,核验到的有效期截止 `2026-11-28 06:59:59
## 本地 Windows 电脑 ## 本地 Windows 电脑
桌面客户端已同步当前公网配置,可运行 `scripts/start-desktop.ps1`,或打开 `bin/desktop-win-x64/Ads.Desktop.exe`。它会读取项目的客户端凭据,显示远程 `home-phone` 并管理本地连接、重连、断开、设备信息和独立手机控制窗口。桌面模式已管理 ads-client 子进程,使用时无需再单独启动下面的命令行客户端。
本地配置位于 `config/private/client.env`,已配置目录 ACL 并被 Git 忽略。该文件只包含客户端角色凭据和非敏感连接地址,不包含服务器 root 密码。 本地配置位于 `config/private/client.env`,已配置目录 ACL 并被 Git 忽略。该文件只包含客户端角色凭据和非敏感连接地址,不包含服务器 root 密码。
```powershell ```powershell
+9
View File
@@ -37,3 +37,12 @@ Remote Windows gateway follow-up:
- Ran `tests/real_device.py --existing-device home-phone`: only a local client was started; no local gateway and no remote ADB Server transport were used. Ordinary local ADB showed the phone as `device`, and model query plus shell marker passed. - Ran `tests/real_device.py --existing-device home-phone`: only a local client was started; no local gateway and no remote ADB Server transport were used. Ordinary local ADB showed the phone as `device`, and model query plus shell marker passed.
- Restarted the remote task and repeated that test: passed again, with local endpoint `127.0.0.1:49832` and model `AOSP on crosshatch`. - Restarted the remote task and repeated that test: passed again, with local endpoint `127.0.0.1:49832` and model `AOSP on crosshatch`.
- Remote gateway remains running. Temporary local smoke-test endpoints/processes were cleaned up. Startup trigger configuration was inspected without rebooting the PC. System VPN was not disabled; it was only needed for remote SSH management, not the tested ADB data path. - Remote gateway remains running. Temporary local smoke-test endpoints/processes were cleaned up. Startup trigger configuration was inspected without rebooting the PC. System VPN was not disabled; it was only needed for remote SSH management, not the tested ADB data path.
Desktop follow-up:
- Avalonia now defaults to `wss://ttstd.com/ads`, with explicit origin `175.178.213.60:443`. HTTPS catalog requests and the Rust child share the same prefix/origin configuration; neither disables TLS validation.
- Twelve .NET tests passed: URI prefix/port handling, invalid configuration, migration, role-token import, environment isolation and non-persistence, and rejection of an untrusted local TLS certificate even with an origin override.
- Official Avalonia headless tests loaded the real XAML and checked bindings/button state. Real live-device tests passed public catalog discovery, GUI command connect, ADB readiness, model/Android/API display, reconnect, disconnect and lease release.
- Official scrcpy 5.0.1 archive matched its published SHA-256. The desktop command started real public video streaming; scrcpy reported `Texture (D3D11VA): 944x1920`. Stop, reconnect and disconnect checks passed after that.
- Rendered normal and minimum-size layouts were inspected. No token was present in saved settings or UI logs. Windows self-contained publishing succeeded, excluding credentials.
- Native Windows UI automation could not initialize because its runtime reported a sandbox setup error. Tests were Avalonia headless plus real network/process/video operations; native mouse/keyboard, clipboard/file picker and tray behavior have not been automatically exercised in this run.
+25
View File
@@ -0,0 +1,25 @@
param(
[string]$Runtime = 'win-x64',
[switch]$FrameworkDependent
)
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$outputDirectory = Join-Path $projectRoot "bin/desktop-$Runtime"
$selfContained = if ($FrameworkDependent) { 'false' } else { 'true' }
Push-Location (Join-Path $projectRoot 'desktop')
try {
dotnet publish Ads.Desktop -c Release -r $Runtime --self-contained $selfContained -o $outputDirectory --nologo
if ($LASTEXITCODE -ne 0) { throw 'Desktop publish failed' }
} finally { Pop-Location }
$suffix = if ($Runtime.StartsWith('win-')) { '.exe' } else { '' }
$client = Join-Path $projectRoot ('bin/ads-client' + $suffix)
if (Test-Path -LiteralPath $client) {
Copy-Item -LiteralPath $client -Destination (Join-Path $outputDirectory ('ads-client' + $suffix)) -Force
}
if ($Runtime.StartsWith('win-') -and (Test-Path -LiteralPath (Join-Path $projectRoot 'bin/tools/scrcpy/scrcpy.exe'))) {
$tools = Join-Path $outputDirectory 'tools/scrcpy'
New-Item -ItemType Directory -Force -Path $tools | Out-Null
Copy-Item -Path (Join-Path $projectRoot 'bin/tools/scrcpy/*') -Destination $tools -Recurse -Force
}
# Do not copy client.env or any other credential into a distributable directory.
Write-Host "Desktop published to $outputDirectory (credentials excluded)"
+7
View File
@@ -0,0 +1,7 @@
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$application = Join-Path $projectRoot 'bin/desktop-win-x64/Ads.Desktop.exe'
if (-not (Test-Path -LiteralPath $application)) {
throw 'Build the desktop package first with scripts/build-desktop.ps1'
}
Start-Process -FilePath $application -WorkingDirectory $projectRoot