feat: add control center, multiple relay nodes and P2P-first transport
This commit is contained in:
1 parent
0988e9c363
commit
2abfb63da9
44 files changed
+3477
-67
No files matched your search
@@ -13,6 +13,7 @@ public sealed class DesktopSettings
|
||||
public int Port { get; set; } = 15555;
|
||||
public int Size { get; set; } = 1920;
|
||||
public int Fps { get; set; } = 60;
|
||||
public bool RelayOnly { get; set; }
|
||||
public bool Audio { get; set; }
|
||||
public bool ViewOnly { get; set; }
|
||||
public bool Tray { get; set; } = true;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Avalonia.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
@@ -23,6 +24,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
[ObservableProperty] private int port = 15555;
|
||||
[ObservableProperty] private int maxSize = 1920;
|
||||
[ObservableProperty] private int maxFps = 60;
|
||||
[ObservableProperty] private bool relayOnly;
|
||||
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
|
||||
[ObservableProperty] private bool audio;
|
||||
[ObservableProperty] private bool viewOnly;
|
||||
[ObservableProperty] private bool minimizeToTray = true;
|
||||
@@ -46,13 +49,14 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
[ObservableProperty] private bool isWorking;
|
||||
[ObservableProperty] private bool isRefreshing;
|
||||
|
||||
public ObservableCollection<RelayNode> RelayNodes { get; } = new();
|
||||
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? endpoint, activeAdb, activeId, transportFile;
|
||||
private string credentialFile = "", preferredDevice = "home-phone";
|
||||
private bool monitoring, disposed, initialized;
|
||||
private DateTime lastRefresh;
|
||||
@@ -77,7 +81,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
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;
|
||||
RelayOnly = settings.RelayOnly; Audio = settings.Audio; ViewOnly = settings.ViewOnly;
|
||||
MinimizeToTray = settings.Tray; AutoRefresh = settings.AutoRefresh;
|
||||
credentialFile = settings.CredentialFile;
|
||||
preferredDevice = settings.PreferredDevice;
|
||||
@@ -186,7 +190,15 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
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 = "中继在线";
|
||||
RelayStatus = "控制中心在线";
|
||||
try {
|
||||
var nodes = await RelayApi.GetNodesAsync(options, lifetime.Token);
|
||||
if (Server.Trim() != options.BaseUri.OriginalString || Origin.Trim() != options.Origin || Token != options.Token) return;
|
||||
RelayNodes.Clear(); foreach (var node in nodes) RelayNodes.Add(node);
|
||||
if (nodes.Length > 0) RelayStatus += $" · 中继 {nodes.Count(n => n.Healthy)}/{nodes.Length} 在线";
|
||||
} catch (Exception error) when (error is HttpRequestException or TaskCanceledException) {
|
||||
RelayNodes.Clear(); RelayStatus += " · 节点状态暂不可用";
|
||||
}
|
||||
DeviceSummary = $"{rows.Length} 台在线 · {DateTime.Now:HH:mm:ss} 更新";
|
||||
lastRefreshError = null;
|
||||
if (announce) { Notice = "设备列表已更新。"; Log($"中继在线,发现 {rows.Length} 台设备。"); }
|
||||
@@ -274,6 +286,11 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
|
||||
var address = $"127.0.0.1:{Port}";
|
||||
var info = ProcessTools.ClientStartInfo(clientExecutable, adb, relay, device.Id, address);
|
||||
Directory.CreateDirectory(folder);
|
||||
transportFile = Path.Combine(folder, "transport-" + Guid.NewGuid().ToString("N") + ".json");
|
||||
info.ArgumentList.Add("--transport"); info.ArgumentList.Add(RelayOnly ? "relay" : "auto");
|
||||
info.ArgumentList.Add("--status-file"); info.ArgumentList.Add(transportFile);
|
||||
TransportStatus = "正在协商连接路线";
|
||||
client = Start(info);
|
||||
endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
|
||||
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
|
||||
@@ -326,6 +343,21 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
Log($"手机控制窗口已关闭,退出码 {scrcpy.ExitCode}。");
|
||||
scrcpy.Dispose(); scrcpy = null; ScreenRunning = false;
|
||||
}
|
||||
if (transportFile != null && File.Exists(transportFile))
|
||||
{
|
||||
try {
|
||||
using var state = JsonDocument.Parse(await File.ReadAllTextAsync(transportFile, lifetime.Token));
|
||||
var root = state.RootElement;
|
||||
var nodes = string.Join("、", root.GetProperty("nodes").EnumerateArray().Select(n => n.GetString()));
|
||||
TransportStatus = root.GetProperty("transport").GetString() switch {
|
||||
"p2p" => "P2P 直连 · 数据不经过中继",
|
||||
"relay" => "中继连接 · " + nodes,
|
||||
"mixed" => "P2P 与中继并用 · " + nodes,
|
||||
"negotiating" => "正在协商连接路线",
|
||||
_ => "等待 ADB 数据通道"
|
||||
};
|
||||
} catch (IOException) { } catch (JsonException) { }
|
||||
}
|
||||
var current = client;
|
||||
if (current != null)
|
||||
{
|
||||
@@ -418,6 +450,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
if (endpoint != null && activeAdb != null)
|
||||
try { await AdbAsync(activeAdb, CancellationToken.None, "disconnect", endpoint); }
|
||||
catch (Exception error) { Log(error.Message); }
|
||||
if (transportFile != null) { try { File.Delete(transportFile); } catch (IOException) { } }
|
||||
transportFile = null; TransportStatus = "尚未建立数据通道";
|
||||
endpoint = activeAdb = activeId = null;
|
||||
HasConnection = Ready = false;
|
||||
UpdateLocalOwnership();
|
||||
@@ -486,7 +520,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
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,
|
||||
RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
|
||||
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = activeId ?? SelectedDevice?.Id ?? preferredDevice
|
||||
});
|
||||
Notice = "配置已保存;令牌内容未写入配置。";
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Text="连接管理" Classes="section"/>
|
||||
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
|
||||
<TextBlock x:Name="TransportStatusText" Text="{Binding TransportStatus}" Foreground="#A8B7CC" TextWrapping="Wrap"/>
|
||||
<TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
|
||||
<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"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
|
||||
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
|
||||
@@ -74,8 +75,9 @@
|
||||
<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="控制中心" Classes="section" Margin="0,0,0,12"/>
|
||||
<ItemsControl ItemsSource="{Binding RelayNodes}" Margin="0,0,0,12"><ItemsControl.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" Foreground="#66D9C0" Margin="0,3"/></DataTemplate></ItemsControl.ItemTemplate></ItemsControl>
|
||||
<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>
|
||||
@@ -95,6 +97,7 @@
|
||||
</StackPanel></Border>
|
||||
<Border Classes="card"><StackPanel Spacing="12">
|
||||
<TextBlock Text="本地连接" Classes="section"/>
|
||||
<CheckBox x:Name="RelayOnlyCheck" Content="仅使用中继(关闭时 P2P 优先,失败自动选择中继节点)" IsChecked="{Binding RelayOnly}"/>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="本地 ADB 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<WrapPanel><Button Content="清理占用端口" Command="{Binding ClearPortCommand}" ToolTip.Tip="结束当前所选端口的监听进程"/><TextBlock Text="{Binding PortCleanupStatus}" Classes="label" TextWrapping="Wrap" MaxWidth="580" VerticalAlignment="Center"/></WrapPanel>
|
||||
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}"/>
|
||||
|
||||
@@ -50,6 +50,12 @@ public sealed record RelayOptions(Uri BaseUri, string Origin, string Token)
|
||||
|
||||
public sealed record RelayDevice(string Id, bool Busy);
|
||||
|
||||
public sealed record RelayNode(string Id, bool Healthy, int Sessions, int Capacity)
|
||||
{
|
||||
public string Description => $"{Id} · {(Healthy ? "在线" : "不可用")} · 通道 {Sessions}/{Capacity}";
|
||||
}
|
||||
public sealed record RelayCluster(RelayNode[] Nodes);
|
||||
|
||||
public static class RelayApi
|
||||
{
|
||||
public static HttpClient CreateClient(RelayOptions options)
|
||||
@@ -79,6 +85,18 @@ public static class RelayApi
|
||||
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(12) };
|
||||
}
|
||||
|
||||
public static async Task<RelayNode[]> GetNodesAsync(RelayOptions options, CancellationToken cancellation = default)
|
||||
{
|
||||
using var http = CreateClient(options);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get,
|
||||
new UriBuilder(options.DevicesUri) { Path = options.BaseUri.AbsolutePath.TrimEnd('/') + "/v2/nodes" }.Uri);
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.Token);
|
||||
using var response = await http.SendAsync(request, cancellation);
|
||||
if (response.StatusCode == HttpStatusCode.NotFound) return [];
|
||||
response.EnsureSuccessStatusCode();
|
||||
return (await response.Content.ReadFromJsonAsync<RelayCluster>(cancellationToken: cancellation))?.Nodes ?? [];
|
||||
}
|
||||
|
||||
public static async Task<RelayDevice[]> GetDevicesAsync(RelayOptions options, CancellationToken cancellation = default)
|
||||
{
|
||||
using var http = CreateClient(options);
|
||||
|
||||
Reference in new issue
Block a user