Files
tongtong 0a04d5990f Add relay node management and pin manager header layout
- server: add, delete and set-default node endpoints writing cluster.json with validation

- deploy: grant ads-server write access to /etc/ads

- flutter: relay node page with admin token plumbing, stop reconnecting devices removed from device list

- flutter: fixed header heights and strut so tab switching never shifts refresh/notice
2026-11-16 16:44:58 +08:00

823 lines
24 KiB
Dart
Raw Permalink 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.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'windows_usb.dart';
import 'usb_recovery.dart';
import 'tool_paths.dart';
import 'app_paths.dart';
class Settings {
String server = 'wss://ttstd.com/ads';
String origin = '175.178.213.60:443';
String credential = '';
Map<String, String> agentPaths = {};
String client = '', adb = '', scrcpy = '';
bool relayOnly = false, usbMode = false;
String usbip = UsbDriver.defaultUsbip();
Map<String, dynamic> toJson() => {
'server': server,
'origin': origin,
'credential': credential,
'agentPaths': agentPaths,
'client': client,
'adb': adb,
'scrcpy': scrcpy,
'relayOnly': relayOnly,
'usbMode': usbMode,
'usbip': usbip,
};
void load(Map<String, dynamic> j) {
server = j['server'] as String? ?? server;
origin = j['origin'] as String? ?? origin;
credential = j['credential'] as String? ?? credential;
agentPaths = Map<String, String>.from(j['agentPaths'] as Map? ?? {});
client = j['client'] as String? ?? client;
adb = j['adb'] as String? ?? adb;
scrcpy = j['scrcpy'] as String? ?? scrcpy;
relayOnly = j['relayOnly'] == true;
usbMode = j['usbMode'] == true;
usbip = j['usbip'] as String? ?? usbip;
}
Uri uri(String suffix) {
final u = Uri.parse(server.trim());
if (u.scheme != 'wss' ||
u.host.isEmpty ||
u.hasQuery ||
u.hasFragment ||
u.userInfo.isNotEmpty) {
throw const FormatException('服务地址必须是有效的 wss:// 地址');
}
return u.replace(
scheme: 'https',
path: '${u.path.replaceFirst(RegExp(r"/+$"), "")}/$suffix',
);
}
}
class Device {
final String id;
final bool busy;
final String agentId, computerName;
const Device(this.id, this.busy, {this.agentId = "", this.computerName = ""});
}
class Session {
final String id, tunnel, adb, statusFile;
String? leaseFile;
WindowsUsbSession? usb;
String get endpoint => usb?.serial ?? tunnel;
String get mode => usb == null ? "网络 ADB" : "虚拟 USB";
Process process;
Future<Process> Function()? restartClient;
final recovery = UsbRecoveryPolicy();
String usbip = '', usbExecutable = '';
bool recovering = false,
initialized = false,
screenWanted = false,
usbBroken = false;
Future<void>? recoveryTask;
bool screenPageVisible = false;
Process? screen;
bool screenEmbedded = false;
String state = '连接中', route = '协商中';
bool ready = false, stopping = false, exited = false;
int missingPasses = 0;
Session(this.id, this.tunnel, this.adb, this.statusFile, this.process);
}
class ManagerRepository {
final Settings settings = Settings();
final Map<String, Session> sessions = {};
final Set<int> reservedPorts = {};
final void Function(String) log;
bool allowEmbeddedResume = true;
String token = '';
Directory? root;
late Directory storage;
final ToolPaths? paths;
ManagerRepository(this.log, {this.paths});
Future<void> init() async {
storage = Directory(AppPaths.configuration());
await storage.create(recursive: true);
for (final start in [
Directory.current.path,
p.dirname(Platform.resolvedExecutable),
]) {
var d = Directory(start);
while (true) {
if (File(p.join(d.path, 'Cargo.toml')).existsSync()) {
root = d;
break;
}
final parent = d.parent;
if (parent.path == d.path) {
break;
}
d = parent;
}
if (root != null) {
break;
}
}
settings.client = findTool('ads-client');
settings.adb = findTool('adb');
settings.scrcpy = findTool('scrcpy');
settings.credential = root == null
? ''
: p.join(root!.path, 'config', 'private', 'client.env');
final saved = File(p.join(storage.path, 'settings.json'));
if (await saved.exists()) {
settings.load(
jsonDecode(await saved.readAsString()) as Map<String, dynamic>,
);
}
if (!Platform.isWindows) settings.usbMode = false;
await repairToolPaths();
token = Platform.environment['ADS_CLIENT_TOKEN'] ?? '';
if (token.isEmpty && await File(settings.credential).exists()) {
await importCredential();
}
}
ToolPaths get toolPaths => paths ?? ToolPaths(projectRoot: root?.path);
String findTool(String name) => toolPaths.resolve(name);
Future<void> repairToolPaths() async {
var changed = false;
void repair(String name, String value, void Function(String) assign) {
final resolved = toolPaths.resolve(name, configured: value);
if (resolved != value) {
assign(resolved);
changed = true;
log('已更新 $name 工具位置:$resolved');
}
}
repair('ads-client', settings.client, (v) => settings.client = v);
repair('adb', settings.adb, (v) => settings.adb = v);
repair('scrcpy', settings.scrcpy, (v) => settings.scrcpy = v);
if (changed) await save();
}
Future<void> save() =>
File(p.join(storage.path, 'settings.json'))
.writeAsString(jsonEncode(settings.toJson()));
Future<void> importCredential() async {
final file = File(settings.credential);
if (await file.length() > 65536) {
throw const FormatException('凭据文件过大');
}
final values = <String, String>{};
for (final line in await file.readAsLines()) {
final i = line.indexOf('=');
if (i > 0) {
values[line.substring(0, i).trim()] = line.substring(i + 1).trim();
}
}
final value = values['ADS_CLIENT_TOKEN'] ?? '';
if (value.length < 32 || value.contains(RegExp(r'[\r\n]'))) {
throw const FormatException('请选择包含 ADS_CLIENT_TOKEN 的 client.env');
}
token = value;
if (values['ADS_CONNECT_ADDRESS'] case final String address) {
settings.origin = address;
}
}
Future<dynamic> get(String suffix) => requestJson(suffix);
Future<dynamic> requestJson(
String suffix, {
String? bearer,
Map<String, Object?>? payload,
Map<String, String>? query,
String? method,
}) async {
final authorization = bearer ?? token;
if (authorization.length < 32) {
throw FormatException(
bearer == null ? '请先导入客户端凭据' : '请先导入管理员凭据 admin.env',
);
}
final client = HttpClient()..connectionTimeout = const Duration(seconds: 8);
client.findProxy = (_) => 'DIRECT';
if (settings.origin.trim().isNotEmpty) {
final origin = Uri.parse('tcp://${settings.origin.trim()}');
if (origin.host.isEmpty ||
!origin.hasPort ||
origin.port < 1 ||
origin.port > 65535) {
throw const FormatException('直连地址应为 IP或主机名:端口');
}
client.connectionFactory = (uri, proxyHost, proxyPort) async {
final task = await Socket.startConnect(origin.host, origin.port);
Socket? connected;
final secured = task.socket
.then((socket) async {
connected = socket;
return SecureSocket.secure(socket, host: uri.host);
})
.then((socket) {
connected = socket;
return socket;
});
return ConnectionTask.fromSocket(secured, () {
task.cancel();
connected?.destroy();
});
};
}
try {
final uri = settings.uri(suffix).replace(queryParameters: query);
final request = await client.openUrl(
method ?? (payload == null ? 'GET' : 'POST'),
uri,
);
request.followRedirects = false;
request.headers.set('Authorization', 'Bearer $authorization');
if (payload != null) {
request.headers.contentType = ContentType.json;
request.write(jsonEncode(payload));
}
final response = await request.close().timeout(
const Duration(seconds: 12),
);
final body = await utf8.decoder
.bind(response)
.join()
.timeout(const Duration(seconds: 12));
if (suffix == 'v2/nodes' && response.statusCode == 404) {
return {'nodes': <dynamic>[]};
}
if (response.statusCode < 200 || response.statusCode >= 300) {
final detail = body.trim();
throw HttpException(
'控制中心 HTTP ${response.statusCode}${detail.isEmpty ? '' : ':${detail.length > 200 ? detail.substring(0, 200) : detail}'}',
);
}
if (body.trim().isEmpty) {
return null;
}
return jsonDecode(body);
} finally {
client.close(force: true);
}
}
Future<List<Device>> devices() async {
final raw = await get('v1/devices') as List<dynamic>;
return raw.map((v) {
final j = v as Map<String, dynamic>;
final id = j['id'] as String;
if (!RegExp(r'^[a-zA-Z0-9_.-]{1,128}$').hasMatch(id)) {
throw const FormatException('无效设备 ID');
}
return Device(
id,
j['busy'] == true,
agentId: j['agent_id'] as String? ?? '',
computerName: j['computer_name'] as String? ?? '',
);
}).toList()..sort((a, b) => a.id.compareTo(b.id));
}
Map<String, String> environment() => Map.of(Platform.environment)
..removeWhere(
(k, v) => [
'ADB_SERVER_SOCKET',
'ANDROID_ADB_SERVER_ADDRESS',
'ANDROID_ADB_SERVER_PORT',
'ADS_CLIENT_TOKEN',
'ADS_AGENT_TOKEN',
'ADS_ADMIN_TOKEN',
'ADS_CONNECT_ADDRESS',
].contains(k),
)
..['NO_COLOR'] = '1';
Future<String> run(String exe, List<String> args) async {
final name = p
.basename(exe)
.replaceFirst(RegExp(r'\.exe$', caseSensitive: false), '');
if (['ads-client', 'ads-usb', 'adsctl', 'adb', 'scrcpy'].contains(name)) {
exe = toolPaths.resolve(name, configured: exe, required: true);
}
final proc = await Process.start(
exe,
args,
environment: environment(),
includeParentEnvironment: false,
);
final out = utf8.decoder.bind(proc.stdout).join();
final err = utf8.decoder.bind(proc.stderr).join();
try {
final code = await proc.exitCode.timeout(const Duration(seconds: 12));
final output = await out, error = await err;
if (code != 0) {
throw ProcessException(p.basename(exe), [], error, code);
}
return output;
} on TimeoutException {
proc.kill();
rethrow;
}
}
void watch(Process proc, String label) {
for (final stream in [proc.stdout, proc.stderr]) {
stream
.transform(const Utf8Decoder(allowMalformed: true))
.transform(const LineSplitter())
.listen(
(line) => log(
'[$label] ${token.isEmpty ? line : line.replaceAll(token, "[REDACTED]")}',
),
);
}
}
Future<Session> connect(String id) async {
if (sessions.containsKey(id)) {
return sessions[id]!;
}
settings.uri('v1/devices');
if (token.length < 32) {
throw const FormatException('请先导入凭据');
}
await repairToolPaths();
settings.client = toolPaths.resolve(
'ads-client',
configured: settings.client,
required: true,
);
settings.adb = toolPaths.resolve(
'adb',
configured: settings.adb,
required: true,
);
if (settings.usbMode && !Platform.isWindows) {
throw UnsupportedError("Linux 桌面端请使用网络 ADB;USB 模拟可使用 ads-usb CLI。");
}
final usbMode = settings.usbMode;
final usbip = settings.usbip;
if (usbMode) {
if (!await UsbDriver.installed(run)) {
throw StateError('未安装 USBip 虚拟控制器,请在连接配置中安装驱动');
}
if (!await File(usbip).exists()) {
throw StateError('找不到 usbip.exe,请检查配置路径');
}
await run(toolPaths.resolve('ads-usb', required: true), ['--version']);
}
final port = await allocatePort(15555, 18000);
int? usbPort;
Session? session;
try {
if (usbMode) {
usbPort = await allocateUsbPort();
}
final endpoint = '127.0.0.1:$port';
final status = p.join(
storage.path,
'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json',
);
final lease = usbMode ? "$status.lease" : null;
final clientExecutable = settings.client, adbExecutable = settings.adb;
final serverAddress = settings.server.trim(),
originAddress = settings.origin.trim();
final transportMode = settings.relayOnly ? 'relay' : 'auto';
final clientEnvironment = environment()..['ADS_CLIENT_TOKEN'] = token;
Future<Process> startClient() => Process.start(
clientExecutable,
[
'--server',
serverAddress,
'--device',
id,
'--listen',
endpoint,
'--adb',
adbExecutable,
'--transport',
transportMode,
'--status-file',
status,
if (lease != null) ...[
'--no-auto-connect',
'--lease-status-file',
lease,
],
if (originAddress.isNotEmpty) ...['--connect-address', originAddress],
],
environment: clientEnvironment,
includeParentEnvironment: false,
);
final proc = await startClient();
watch(proc, id);
session = Session(id, endpoint, settings.adb, status, proc);
final current = session;
sessions[id] = current;
current.leaseFile = lease;
current.restartClient = startClient;
current.usbip = usbip;
current.usbExecutable = findTool('ads-usb');
observeClient(current, proc);
if (usbMode) {
final usb = WindowsUsbSession(id, usbPort!);
current.usb = usb;
current.state = '等待设备租约并挂载 USB';
await usb.start(
leaseFile: lease!,
upstream: current.tunnel,
executable: findTool('ads-usb'),
usbip: usbip,
environment: environment(),
run: run,
watch: watch,
cancelled: () => current.exited || current.stopping,
);
log('USB 已挂载:${usb.serial}');
}
current.initialized = true;
return current;
} catch (_) {
if (session != null) {
await disconnect(id);
} else {
reservedPorts.remove(port);
if (usbPort != null) {
reservedPorts.remove(usbPort);
}
}
rethrow;
}
}
Future<int> allocateUsbPort() async {
// A new OS-selected endpoint also avoids a previous controller's delayed
// teardown reconnecting to the next export at a reused fixed port.
while (true) {
final probe = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = probe.port;
final reserved = reservedPorts.add(port);
await probe.close();
if (reserved) {
return port;
}
}
}
Future<int> allocatePort(int start, int end) async {
for (var port = start; port < end; port++) {
if (!reservedPorts.add(port)) {
continue;
}
try {
final probe = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await probe.close();
return port;
} on SocketException {
reservedPorts.remove(port);
}
}
throw const SocketException('没有空闲的本地端口');
}
Future<void> monitor() async {
final listings = <String, String>{};
Set<String>? online;
if (sessions.values.any((s) => s.usb != null)) {
try {
online = (await devices()).map((d) => d.id).toSet();
} catch (_) {
// Inventory unavailable; keep the current connection states.
}
}
for (final s in sessions.values.toList()) {
if (s.stopping) {
continue;
}
if (online != null && s.usb != null) {
if (online.contains(s.id)) {
s.missingPasses = 0;
} else {
s.missingPasses++;
if (s.missingPasses >= 3) {
log('[${s.id}] 设备已不在设备列表,停止自动重连');
await disconnect(s.id);
continue;
}
s.state = '设备已下线 · 等待恢复';
continue;
}
}
if (s.usb == null && !s.stopping && s.exited) {
await disconnect(s.id);
continue;
}
if (s.stopping || s.recovering || !s.initialized) {
continue;
}
try {
final listing = listings[s.adb] ??= await run(s.adb, ['devices', '-l']);
final rows = listing
.split('\n')
.map((r) => r.trim().split(RegExp(r'\s+')));
final row = rows
.where((r) => r.length >= 2 && r[0] == s.endpoint)
.firstOrNull;
s.ready = row?[1] == 'device';
if (s.usb != null &&
s.recovery.due(
DateTime.now(),
ready: s.ready,
unauthorized: row?[1] == 'unauthorized',
broken: s.exited || s.usb!.exited || s.usbBroken,
)) {
scheduleUsbRecovery(s);
continue;
}
if (s.ready &&
s.screenWanted &&
(!s.screenEmbedded ||
(s.screenPageVisible && allowEmbeddedResume)) &&
s.screen == null &&
!DateTime.now().isBefore(s.recovery.retryAt)) {
s.recovery.attempted(DateTime.now());
try {
await screen(s, embedded: s.screenEmbedded);
} catch (e) {
log('[${s.id}] 恢复投屏失败:$e');
}
}
s.state = row == null ? '等待设备 / 自动重连' : row[1];
final file = File(s.statusFile);
if (await file.exists()) {
final j =
jsonDecode(await file.readAsString()) as Map<String, dynamic>;
s.route =
'${j["transport"]} · ${(j["nodes"] as List<dynamic>? ?? []).join(", ")}';
}
} catch (e) {
s.ready = false;
s.state = '检测失败:$e';
}
}
}
void observeClient(Session s, Process process) {
unawaited(
process.exitCode.then((code) {
if (s.process != process) {
return;
}
s.exited = true;
s.ready = false;
s.state = '连接程序已退出 ($code)';
}),
);
}
Future<void> stopScreen(Session s) async {
s.screenWanted = false;
final process = s.screen;
s.screen = null;
await stop(process);
log('[${s.id}] 用户停止投屏,取消自动恢复');
}
void scheduleUsbRecovery(Session s) {
if (s.stopping || s.recovering) {
return;
}
s.recovering = true;
s.ready = false;
s.recovery.attempted(DateTime.now());
s.state = 'USB 会话中断 · 正在重新挂载';
log('[${s.id}] USB 自动恢复,第 ${s.recovery.attempts} 次');
s.recoveryTask = recoverUsb(s).whenComplete(() => s.recovering = false);
}
Future<void> recoverUsb(Session s) async {
try {
final screen = s.screen;
s.screen = null;
await stop(screen);
final old = s.usb!;
await stop(old.bridge);
reservedPorts.remove(old.port);
if (s.stopping) {
return;
}
if (s.exited) {
final lease = File(s.leaseFile!);
if (await lease.exists()) {
await lease.delete();
}
s.process = await s.restartClient!();
s.exited = false;
watch(s.process, s.id);
observeClient(s, s.process);
}
if (s.stopping) {
return;
}
final port = await allocateUsbPort();
final usb = WindowsUsbSession(s.id, port);
s.usb = usb;
await usb.start(
leaseFile: s.leaseFile!,
upstream: s.tunnel,
executable: s.usbExecutable,
usbip: s.usbip,
environment: environment(),
run: run,
watch: watch,
cancelled: () => s.stopping || s.exited,
);
s.usbBroken = false;
s.recovery.missing = 0;
s.state = 'USB 已重新挂载 · 等待 ADB 就绪';
log('[${s.id}] USB 已重新挂载;设备就绪后恢复投屏');
} catch (e) {
// No unhandled async exception; monitor retries with bounded backoff.
try {
await stop(s.usb?.bridge);
} catch (_) {}
if (!s.stopping) {
s.state = 'USB 恢复失败 · 稍后重试';
log('[${s.id}] USB 恢复失败:$e');
}
}
}
Future<void> screen(Session s, {bool embedded = false}) async {
embedded = embedded && Platform.isWindows;
if (s.stopping) {
return;
}
s.screenWanted = true;
if (!s.ready || s.recovering || s.stopping) {
return;
}
if (s.screen != null) {
if (s.screenEmbedded == embedded) {
return;
}
final previous = s.screen;
s.screen = null;
await stop(previous);
}
final proc = await launchScreen(
s.endpoint,
s.adb,
s.id,
embedded: embedded,
);
if (s.stopping || !s.screenWanted) {
await stop(proc);
return;
}
s.screen = proc;
s.screenEmbedded = embedded;
watch(proc, 'scrcpy ${s.id}');
unawaited(
proc.exitCode.then((code) {
if (s.screen == proc) {
s.screen = null;
if (code == 0) {
s.screenWanted = false;
} else if (!s.stopping && code == 2 && s.usb != null) {
s.usbBroken = true;
}
}
log('投屏窗口关闭 ($code)');
}),
);
}
Future<Process> launchScreen(
String endpoint,
String adb,
String id, {
bool embedded = false,
}) {
final scrcpy = toolPaths.resolve(
'scrcpy',
configured: settings.scrcpy,
required: true,
);
final selectedAdb = toolPaths.resolve(
'adb',
configured: adb,
required: true,
);
return Process.start(
scrcpy,
[
'--serial',
endpoint,
'--force-adb-forward',
'--window-title',
'ADS Flutter · $id',
if (embedded) ...[
'--window-borderless',
'--hwdec=disabled',
'--render-driver=software',
'--no-window-aspect-ratio-lock',
],
'--max-size',
'1920',
'--max-fps',
'60',
'--no-audio',
],
workingDirectory: p.dirname(scrcpy),
environment: environment()..['ADB'] = selectedAdb,
includeParentEnvironment: false,
);
}
Future<void> stop(Process? proc) async {
if (proc == null) {
return;
}
proc.kill();
await proc.exitCode.timeout(const Duration(seconds: 5));
}
Future<void> disconnect(String id) async {
final s = sessions[id];
if (s == null || s.stopping) {
return;
}
s.stopping = true;
s.screenWanted = false;
await s.recoveryTask;
for (final proc in [s.screen, s.usb?.bridge, s.process]) {
try {
await stop(proc);
} catch (e) {
log('停止设备进程:$e');
}
}
try {
if (s.usb == null) {
await run(s.adb, ['disconnect', s.tunnel]);
} else {
final deadline = DateTime.now().add(const Duration(seconds: 8));
while (true) {
final listing = await run(s.adb, ['devices']);
if (!listing
.split('\n')
.any((line) => line.startsWith('${s.endpoint}\t'))) {
break;
}
if (DateTime.now().isAfter(deadline)) {
throw StateError('虚拟 USB 正在由 Windows 回收,请稍后重连');
}
await Future<void>.delayed(const Duration(milliseconds: 200));
}
}
} catch (e) {
log('断开 ADB:$e');
} finally {
sessions.remove(id);
reservedPorts.remove(int.parse(s.tunnel.split(':').last));
if (s.usb != null) {
reservedPorts.remove(s.usb!.port);
}
for (final path in [s.statusFile, s.leaseFile]) {
if (path == null) {
continue;
}
final file = File(path);
try {
if (await file.exists()) {
await file.delete();
}
} on FileSystemException catch (e) {
log('$e');
}
}
}
}
Future<void> shutdown() async {
for (final id in sessions.keys.toList()) {
try {
await disconnect(id);
} catch (e) {
log('释放 $id:$e');
}
}
}
}