feat: add Flutter USB mirroring and single-instance desktop clients
This commit is contained in:
1 parent
3a7bb071f0
commit
a339465392
30 files changed
+1688
-104
No files matched your search
@@ -4,12 +4,15 @@ import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'windows_usb.dart';
|
||||
|
||||
class Settings {
|
||||
String server = 'wss://ttstd.com/ads';
|
||||
String origin = '175.178.213.60:443';
|
||||
String credential = '';
|
||||
String client = '', adb = '', scrcpy = '';
|
||||
bool relayOnly = false;
|
||||
bool relayOnly = false, usbMode = false;
|
||||
String usbip = UsbDriver.defaultUsbip();
|
||||
Map<String, dynamic> toJson() => {
|
||||
'server': server,
|
||||
'origin': origin,
|
||||
@@ -18,6 +21,8 @@ class Settings {
|
||||
'adb': adb,
|
||||
'scrcpy': scrcpy,
|
||||
'relayOnly': relayOnly,
|
||||
'usbMode': usbMode,
|
||||
'usbip': usbip,
|
||||
};
|
||||
void load(Map<String, dynamic> j) {
|
||||
server = j['server'] as String? ?? server;
|
||||
@@ -27,6 +32,8 @@ class Settings {
|
||||
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) {
|
||||
@@ -52,12 +59,17 @@ class Device {
|
||||
}
|
||||
|
||||
class Session {
|
||||
final String id, endpoint, adb, statusFile;
|
||||
final String id, tunnel, adb, statusFile;
|
||||
String? leaseFile;
|
||||
WindowsUsbSession? usb;
|
||||
String get endpoint => usb?.serial ?? tunnel;
|
||||
String get mode => usb == null ? "网络 ADB" : "虚拟 USB";
|
||||
final Process process;
|
||||
Process? screen;
|
||||
bool screenEmbedded = false;
|
||||
String state = '连接中', route = '协商中';
|
||||
bool ready = false, stopping = false, exited = false;
|
||||
Session(this.id, this.endpoint, this.adb, this.statusFile, this.process);
|
||||
Session(this.id, this.tunnel, this.adb, this.statusFile, this.process);
|
||||
}
|
||||
|
||||
class ManagerRepository {
|
||||
@@ -300,73 +312,141 @@ class ManagerRepository {
|
||||
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++;
|
||||
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(findTool('ads-usb'), ['--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 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 (lease != null) ...[
|
||||
'--no-auto-connect',
|
||||
'--lease-status-file',
|
||||
lease,
|
||||
],
|
||||
if (settings.origin.trim().isNotEmpty) ...[
|
||||
'--connect-address',
|
||||
settings.origin.trim(),
|
||||
],
|
||||
],
|
||||
environment: environment()..['ADS_CLIENT_TOKEN'] = token,
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
watch(proc, id);
|
||||
session = Session(id, endpoint, settings.adb, status, proc);
|
||||
final current = session;
|
||||
sessions[id] = current;
|
||||
current.leaseFile = lease;
|
||||
unawaited(
|
||||
proc.exitCode.then((code) {
|
||||
current.exited = true;
|
||||
current.ready = false;
|
||||
current.state = '连接程序已退出 ($code)';
|
||||
}),
|
||||
);
|
||||
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}');
|
||||
}
|
||||
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 socket = await ServerSocket.bind(
|
||||
final probe = await ServerSocket.bind(
|
||||
InternetAddress.loopbackIPv4,
|
||||
port,
|
||||
);
|
||||
reservedPorts.add(port);
|
||||
await socket.close();
|
||||
break;
|
||||
await probe.close();
|
||||
return port;
|
||||
} on SocketException {
|
||||
port++;
|
||||
reservedPorts.remove(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;
|
||||
throw const SocketException('没有空闲的本地端口');
|
||||
}
|
||||
|
||||
Future<void> monitor() async {
|
||||
final listings = <String, String>{};
|
||||
for (final s in sessions.values.toList()) {
|
||||
if (s.stopping || s.exited) {
|
||||
if (!s.stopping && (s.exited || s.usb?.exited == true)) {
|
||||
await disconnect(s.id);
|
||||
continue;
|
||||
}
|
||||
if (s.stopping) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
@@ -393,29 +473,25 @@ class ManagerRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> screen(Session s) async {
|
||||
if (!s.ready || s.screen != null) {
|
||||
Future<void> screen(Session s, {bool embedded = false}) async {
|
||||
if (!s.ready) {
|
||||
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,
|
||||
if (s.screen != null) {
|
||||
if (s.screenEmbedded == embedded) {
|
||||
return;
|
||||
}
|
||||
await stop(s.screen);
|
||||
s.screen = null;
|
||||
}
|
||||
final proc = await launchScreen(
|
||||
s.endpoint,
|
||||
s.adb,
|
||||
s.id,
|
||||
embedded: embedded,
|
||||
);
|
||||
s.screen = proc;
|
||||
s.screenEmbedded = embedded;
|
||||
watch(proc, 'scrcpy ${s.id}');
|
||||
unawaited(
|
||||
proc.exitCode.then((code) {
|
||||
@@ -427,6 +503,38 @@ class ManagerRepository {
|
||||
);
|
||||
}
|
||||
|
||||
Future<Process> launchScreen(
|
||||
String endpoint,
|
||||
String adb,
|
||||
String id, {
|
||||
bool embedded = false,
|
||||
}) {
|
||||
return Process.start(
|
||||
settings.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(p.absolute(settings.scrcpy)),
|
||||
environment: environment()..['ADB'] = adb,
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> stop(Process? proc) async {
|
||||
if (proc == null) {
|
||||
return;
|
||||
@@ -441,20 +549,51 @@ class ManagerRepository {
|
||||
return;
|
||||
}
|
||||
s.stopping = true;
|
||||
try {
|
||||
for (final proc in [s.screen, s.usb?.bridge, s.process]) {
|
||||
try {
|
||||
await stop(s.screen);
|
||||
await stop(proc);
|
||||
} catch (e) {
|
||||
log("停止投屏:$e");
|
||||
log('停止设备进程:$e');
|
||||
}
|
||||
await stop(s.process);
|
||||
await run(s.adb, ['disconnect', s.endpoint]);
|
||||
}
|
||||
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.endpoint.split(':').last));
|
||||
final file = File(s.statusFile);
|
||||
if (await file.exists()) {
|
||||
await file.delete();
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
typedef UsbRun = Future<String> Function(String exe, List<String> args);
|
||||
|
||||
class UsbDriver {
|
||||
static const filename = 'USBip-0.9.8.1-x64.exe';
|
||||
static const hash =
|
||||
'38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a';
|
||||
static String defaultUsbip() => p.join(
|
||||
Platform.environment['ProgramFiles'] ?? r'C:Program Files',
|
||||
'USBip',
|
||||
'usbip.exe',
|
||||
);
|
||||
static Future<bool> installed(UsbRun run) async {
|
||||
if (!Platform.isWindows) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await run('sc.exe', ['query', 'usbip2_ude']);
|
||||
return true;
|
||||
} on ProcessException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static String installer(String? root) {
|
||||
final adjacent = p.join(
|
||||
p.dirname(Platform.resolvedExecutable),
|
||||
'drivers',
|
||||
filename,
|
||||
);
|
||||
if (File(adjacent).existsSync()) {
|
||||
return adjacent;
|
||||
}
|
||||
return root == null ? adjacent : p.join(root, 'work', filename);
|
||||
}
|
||||
|
||||
static Future<bool> validHash(File file) async =>
|
||||
(await sha256.bind(file.openRead()).first).toString() == hash;
|
||||
|
||||
/// Only invoked after the user selects Install in the missing-driver dialog.
|
||||
static Future<int> install(String file) async {
|
||||
if (!Platform.isWindows) {
|
||||
throw UnsupportedError('USB 模拟目前仅支持 Windows');
|
||||
}
|
||||
if (!await File(file).exists() || !await validHash(File(file))) {
|
||||
throw StateError('USBip 安装包缺失或 SHA-256 校验失败,请重新获取完整 Windows 安装包');
|
||||
}
|
||||
const script = r"""
|
||||
$ErrorActionPreference='Stop'
|
||||
$f=$env:ADS_USB_INSTALLER
|
||||
$s=Get-AuthenticodeSignature -LiteralPath $f
|
||||
if ($s.Status -ne 'Valid' -or $s.SignerCertificate.Thumbprint -ne '9AC56B6C76141395D74FFF6652818376E80B9C95') { throw 'USBip signature verification failed' }
|
||||
$p=Start-Process -FilePath $f -ArgumentList '/NORESTART' -Verb RunAs -PassThru -Wait
|
||||
exit $p.ExitCode
|
||||
""";
|
||||
final result = await Process.run(
|
||||
'powershell.exe',
|
||||
['-NoProfile', '-NonInteractive', '-Command', script],
|
||||
environment: Map.of(Platform.environment)
|
||||
..removeWhere((key, value) => key.startsWith('ADS_'))
|
||||
..['ADS_USB_INSTALLER'] = p.absolute(file),
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
if (result.exitCode != 0 && result.exitCode != 3010) {
|
||||
throw StateError(
|
||||
'USBip 安装未完成(可能已取消 UAC),退出码 ${result.exitCode}:${result.stderr}',
|
||||
);
|
||||
}
|
||||
return result.exitCode;
|
||||
}
|
||||
}
|
||||
|
||||
class WindowsUsbSession {
|
||||
final String serial;
|
||||
final int port;
|
||||
Process? bridge;
|
||||
bool exited = false;
|
||||
WindowsUsbSession(String device, this.port) : serial = serialFor(device);
|
||||
static String serialFor(String device) =>
|
||||
'ADS-${device.length <= 116 ? device : sha256.convert(utf8.encode(device)).toString().substring(0, 24).toUpperCase()}';
|
||||
|
||||
Future<void> start({
|
||||
required String leaseFile,
|
||||
required String upstream,
|
||||
required String executable,
|
||||
required String usbip,
|
||||
required Map<String, String> environment,
|
||||
required UsbRun run,
|
||||
required void Function(Process, String) watch,
|
||||
required bool Function() cancelled,
|
||||
Duration leaseTimeout = const Duration(seconds: 40),
|
||||
}) async {
|
||||
final deadline = DateTime.now().add(leaseTimeout);
|
||||
while (true) {
|
||||
if (cancelled()) {
|
||||
throw StateError('USB 连接已取消或客户端已退出');
|
||||
}
|
||||
final file = File(leaseFile);
|
||||
try {
|
||||
if (await file.exists() &&
|
||||
(await file.readAsString()).trim() == 'true') {
|
||||
break;
|
||||
}
|
||||
} on FileSystemException {
|
||||
/* publisher is replacing its readiness file */
|
||||
}
|
||||
if (DateTime.now().isAfter(deadline)) {
|
||||
throw StateError('等待 USB 设备租约超时');
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 150));
|
||||
}
|
||||
bridge = await Process.start(
|
||||
executable,
|
||||
[
|
||||
'--listen',
|
||||
'127.0.0.1:$port',
|
||||
'--upstream',
|
||||
upstream,
|
||||
'--serial',
|
||||
serial,
|
||||
],
|
||||
environment: environment,
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
watch(bridge!, serial);
|
||||
unawaited(bridge!.exitCode.then((_) => exited = true));
|
||||
final readyDeadline = DateTime.now().add(const Duration(seconds: 5));
|
||||
while (true) {
|
||||
if (exited || cancelled()) {
|
||||
throw StateError('虚拟 USB 设备进程已退出');
|
||||
}
|
||||
try {
|
||||
final probe = await Socket.connect(
|
||||
InternetAddress.loopbackIPv4,
|
||||
port,
|
||||
timeout: const Duration(milliseconds: 250),
|
||||
);
|
||||
probe.destroy();
|
||||
break;
|
||||
} on SocketException {
|
||||
if (DateTime.now().isAfter(readyDeadline)) {
|
||||
rethrow;
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
}
|
||||
}
|
||||
final output = await run(usbip, [
|
||||
'--tcp-port',
|
||||
'$port',
|
||||
'attach',
|
||||
'--remote',
|
||||
'127.0.0.1',
|
||||
'--bus-id',
|
||||
'1-1',
|
||||
'--terse',
|
||||
'--once',
|
||||
]);
|
||||
final imported = int.tryParse(output.trim());
|
||||
if (imported == null || imported < 1 || imported > 127) {
|
||||
throw StateError('无法确认 USBip 挂载成功:$output');
|
||||
}
|
||||
// --once has no persistent retry. Closing only our bridge removes only our
|
||||
// device; do not detach by a hub number that might have been reused.
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user