454 lines
13 KiB
Dart
454 lines
13 KiB
Dart
import 'dart:async';
|
||
import 'dart:convert';
|
||
import 'dart:io';
|
||
|
||
import 'package:path/path.dart' as p;
|
||
|
||
class Settings {
|
||
String server = 'wss://ttstd.com/ads';
|
||
String origin = '175.178.213.60:443';
|
||
String credential = '';
|
||
String client = '', adb = '', scrcpy = '';
|
||
bool relayOnly = false;
|
||
Map<String, dynamic> toJson() => {
|
||
'server': server,
|
||
'origin': origin,
|
||
'credential': credential,
|
||
'client': client,
|
||
'adb': adb,
|
||
'scrcpy': scrcpy,
|
||
'relayOnly': relayOnly,
|
||
};
|
||
void load(Map<String, dynamic> j) {
|
||
server = j['server'] as String? ?? server;
|
||
origin = j['origin'] as String? ?? origin;
|
||
credential = j['credential'] as String? ?? credential;
|
||
client = j['client'] as String? ?? client;
|
||
adb = j['adb'] as String? ?? adb;
|
||
scrcpy = j['scrcpy'] as String? ?? scrcpy;
|
||
relayOnly = j['relayOnly'] == true;
|
||
}
|
||
|
||
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;
|
||
const Device(this.id, this.busy);
|
||
}
|
||
|
||
class Session {
|
||
final String id, endpoint, adb, statusFile;
|
||
final Process process;
|
||
Process? screen;
|
||
String state = '连接中', route = '协商中';
|
||
bool ready = false, stopping = false, exited = false;
|
||
Session(this.id, this.endpoint, 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;
|
||
String token = '';
|
||
Directory? root;
|
||
late Directory storage;
|
||
ManagerRepository(this.log);
|
||
|
||
Future<void> init() async {
|
||
storage = Directory(
|
||
p.join(
|
||
Platform.environment['LOCALAPPDATA'] ?? Directory.systemTemp.path,
|
||
'TTSTD',
|
||
'ADS-Flutter',
|
||
),
|
||
);
|
||
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>,
|
||
);
|
||
}
|
||
token = Platform.environment['ADS_CLIENT_TOKEN'] ?? '';
|
||
if (token.isEmpty && await File(settings.credential).exists()) {
|
||
await importCredential();
|
||
}
|
||
}
|
||
|
||
String findTool(String name) {
|
||
final exe = '$name.exe';
|
||
final base = p.dirname(Platform.resolvedExecutable);
|
||
final candidates = [
|
||
p.join(base, exe),
|
||
p.join(base, 'tools', 'scrcpy', exe),
|
||
if (root != null) p.join(root!.path, 'bin', exe),
|
||
if (root != null) p.join(root!.path, 'bin', 'tools', 'scrcpy', exe),
|
||
for (final dir in (Platform.environment['PATH'] ?? '').split(';'))
|
||
p.join(dir, exe),
|
||
];
|
||
return candidates.firstWhere(
|
||
(v) => File(v).existsSync(),
|
||
orElse: () => exe,
|
||
);
|
||
}
|
||
|
||
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) async {
|
||
if (token.length < 32) {
|
||
throw const FormatException('请先导入客户端凭据');
|
||
}
|
||
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 request = await client.getUrl(settings.uri(suffix));
|
||
request.followRedirects = false;
|
||
request.headers.set('Authorization', 'Bearer $token');
|
||
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) {
|
||
throw HttpException('控制中心 HTTP ${response.statusCode}');
|
||
}
|
||
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);
|
||
}).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_CONNECT_ADDRESS',
|
||
].contains(k),
|
||
)
|
||
..['NO_COLOR'] = '1';
|
||
|
||
Future<String> run(String exe, List<String> args) async {
|
||
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('请先导入凭据');
|
||
}
|
||
var port = 15555;
|
||
while (port < 18000) {
|
||
if (reservedPorts.contains(port) ||
|
||
sessions.values.any((s) => s.endpoint.endsWith(':$port'))) {
|
||
port++;
|
||
continue;
|
||
}
|
||
try {
|
||
final socket = await ServerSocket.bind(
|
||
InternetAddress.loopbackIPv4,
|
||
port,
|
||
);
|
||
reservedPorts.add(port);
|
||
await socket.close();
|
||
break;
|
||
} on SocketException {
|
||
port++;
|
||
}
|
||
}
|
||
if (port == 18000) {
|
||
throw const SocketException('没有空闲本地端口');
|
||
}
|
||
final endpoint = '127.0.0.1:$port';
|
||
final status = p.join(
|
||
storage.path,
|
||
'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json',
|
||
);
|
||
final proc = await Process.start(
|
||
settings.client,
|
||
[
|
||
'--server',
|
||
settings.server.trim(),
|
||
'--device',
|
||
id,
|
||
'--listen',
|
||
endpoint,
|
||
'--adb',
|
||
settings.adb,
|
||
'--transport',
|
||
settings.relayOnly ? 'relay' : 'auto',
|
||
'--status-file',
|
||
status,
|
||
if (settings.origin.trim().isNotEmpty) ...[
|
||
'--connect-address',
|
||
settings.origin.trim(),
|
||
],
|
||
],
|
||
environment: environment()..['ADS_CLIENT_TOKEN'] = token,
|
||
includeParentEnvironment: false,
|
||
);
|
||
watch(proc, id);
|
||
final session = Session(id, endpoint, settings.adb, status, proc);
|
||
sessions[id] = session;
|
||
unawaited(
|
||
proc.exitCode.then((code) {
|
||
session.exited = true;
|
||
session.ready = false;
|
||
session.state = '连接程序已退出 ($code)';
|
||
}),
|
||
);
|
||
return session;
|
||
}
|
||
|
||
Future<void> monitor() async {
|
||
final listings = <String, String>{};
|
||
for (final s in sessions.values.toList()) {
|
||
if (s.stopping || s.exited) {
|
||
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';
|
||
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';
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> screen(Session s) async {
|
||
if (!s.ready || s.screen != null) {
|
||
return;
|
||
}
|
||
final proc = await Process.start(
|
||
settings.scrcpy,
|
||
[
|
||
'--serial',
|
||
s.endpoint,
|
||
'--force-adb-forward',
|
||
'--window-title',
|
||
'ADS Flutter · ${s.id}',
|
||
'--max-size',
|
||
'1920',
|
||
'--max-fps',
|
||
'60',
|
||
'--no-audio',
|
||
],
|
||
workingDirectory: p.dirname(p.absolute(settings.scrcpy)),
|
||
environment: environment()..['ADB'] = s.adb,
|
||
includeParentEnvironment: false,
|
||
);
|
||
s.screen = proc;
|
||
watch(proc, 'scrcpy ${s.id}');
|
||
unawaited(
|
||
proc.exitCode.then((code) {
|
||
if (s.screen == proc) {
|
||
s.screen = null;
|
||
}
|
||
log('投屏窗口关闭 ($code)');
|
||
}),
|
||
);
|
||
}
|
||
|
||
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;
|
||
try {
|
||
try {
|
||
await stop(s.screen);
|
||
} catch (e) {
|
||
log("停止投屏:$e");
|
||
}
|
||
await stop(s.process);
|
||
await run(s.adb, ['disconnect', s.endpoint]);
|
||
} finally {
|
||
sessions.remove(id);
|
||
reservedPorts.remove(int.parse(s.endpoint.split(':').last));
|
||
final file = File(s.statusFile);
|
||
if (await file.exists()) {
|
||
await file.delete();
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> shutdown() async {
|
||
for (final id in sessions.keys.toList()) {
|
||
try {
|
||
await disconnect(id);
|
||
} catch (e) {
|
||
log('释放 $id:$e');
|
||
}
|
||
}
|
||
}
|
||
}
|