build: prepare Flutter management center for agent integration
This commit is contained in:
1 parent
05d4d5fea6
commit
e91fa0235c
34 files changed
+3481
No files matched your search
@@ -0,0 +1,453 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:tray_manager/tray_manager.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import 'ui/manager_model.dart';
|
||||
import 'ui/manager_view.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await windowManager.ensureInitialized();
|
||||
final model = ManagerModel();
|
||||
runApp(ManagerApp(model: model));
|
||||
await windowManager.waitUntilReadyToShow(
|
||||
const WindowOptions(
|
||||
size: Size(1280, 820),
|
||||
minimumSize: Size(920, 640),
|
||||
center: true,
|
||||
title: 'ADS · Flutter 设备管理中心',
|
||||
),
|
||||
() async {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
},
|
||||
);
|
||||
unawaited(model.init());
|
||||
}
|
||||
|
||||
class ManagerApp extends StatefulWidget {
|
||||
final ManagerModel model;
|
||||
const ManagerApp({super.key, required this.model});
|
||||
@override
|
||||
State<ManagerApp> createState() => _ManagerAppState();
|
||||
}
|
||||
|
||||
class _ManagerAppState extends State<ManagerApp>
|
||||
with WindowListener, TrayListener {
|
||||
bool trayReady = false, quitting = false;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
windowManager.addListener(this);
|
||||
trayManager.addListener(this);
|
||||
unawaited(initTray());
|
||||
}
|
||||
|
||||
Future<void> initTray() async {
|
||||
try {
|
||||
await trayManager.setIcon('assets/tray.ico');
|
||||
await trayManager.setToolTip('ADS Flutter 设备管理');
|
||||
await trayManager.setContextMenu(
|
||||
Menu(
|
||||
items: [
|
||||
MenuItem(key: 'show', label: '打开管理中心'),
|
||||
MenuItem(key: 'disconnect', label: '断开全部设备'),
|
||||
MenuItem.separator(),
|
||||
MenuItem(key: 'quit', label: '退出'),
|
||||
],
|
||||
),
|
||||
);
|
||||
await windowManager.setPreventClose(true);
|
||||
trayReady = true;
|
||||
} catch (e) {
|
||||
widget.model.log('托盘初始化失败:$e');
|
||||
await windowManager.setPreventClose(true);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> quit() async {
|
||||
if (quitting) {
|
||||
return;
|
||||
}
|
||||
quitting = true;
|
||||
await widget.model.shutdown();
|
||||
await trayManager.destroy();
|
||||
await windowManager.destroy();
|
||||
exit(0);
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowClose() {
|
||||
if (trayReady) {
|
||||
unawaited(windowManager.hide());
|
||||
} else {
|
||||
unawaited(quit());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconMouseDown() {
|
||||
unawaited(windowManager.show());
|
||||
unawaited(windowManager.focus());
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconRightMouseDown() {
|
||||
unawaited(trayManager.popUpContextMenu());
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayMenuItemClick(MenuItem item) {
|
||||
if (item.key == 'show') {
|
||||
onTrayIconMouseDown();
|
||||
}
|
||||
if (item.key == 'quit') {
|
||||
unawaited(quit());
|
||||
}
|
||||
if (item.key == 'disconnect') {
|
||||
unawaited(
|
||||
widget.model.action(() async {
|
||||
for (final id in widget.model.repository.sessions.keys.toList()) {
|
||||
await widget.model.disconnect(id);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
windowManager.removeListener(this);
|
||||
trayManager.removeListener(this);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: 'ADS 管理中心',
|
||||
theme: ThemeData(
|
||||
useMaterial3: true,
|
||||
fontFamily: 'Microsoft YaHei',
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF305DDB)),
|
||||
scaffoldBackgroundColor: const Color(0xFFF3F5FA),
|
||||
cardTheme: const CardThemeData(
|
||||
elevation: 0,
|
||||
color: Colors.white,
|
||||
margin: EdgeInsets.zero,
|
||||
),
|
||||
inputDecorationTheme: const InputDecorationTheme(
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
),
|
||||
home: ManagerView(model: widget.model, onQuit: quit),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../data/manager_repository.dart';
|
||||
|
||||
class ManagerModel extends ChangeNotifier {
|
||||
late final ManagerRepository repository;
|
||||
List<Device> devices = [];
|
||||
List<Map<String, dynamic>> nodes = [];
|
||||
final List<String> logs = [];
|
||||
final Set<String> pending = {};
|
||||
String notice = '正在初始化', adbListing = '';
|
||||
bool refreshing = false, closing = false, polling = false;
|
||||
Timer? timer;
|
||||
int ticks = 0;
|
||||
ManagerModel() {
|
||||
repository = ManagerRepository(log);
|
||||
}
|
||||
void log(String text) {
|
||||
logs.insert(0, '${DateTime.now().toString().substring(11, 19)} $text');
|
||||
if (logs.length > 500) {
|
||||
logs.removeLast();
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> action(Future<void> Function() operation) async {
|
||||
try {
|
||||
await operation();
|
||||
} catch (e) {
|
||||
notice = e.toString();
|
||||
log(notice);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
await action(() async {
|
||||
await repository.init();
|
||||
notice = '准备就绪';
|
||||
});
|
||||
await refresh();
|
||||
timer = Timer.periodic(const Duration(seconds: 3), (_) async {
|
||||
if (closing || refreshing || polling) {
|
||||
return;
|
||||
}
|
||||
polling = true;
|
||||
try {
|
||||
await action(repository.monitor);
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
if (++ticks % 4 == 0) {
|
||||
await refresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
if (refreshing || closing) {
|
||||
return;
|
||||
}
|
||||
refreshing = true;
|
||||
notifyListeners();
|
||||
await action(() async {
|
||||
devices = await repository.devices();
|
||||
final response = await repository.get('v2/nodes') as Map<String, dynamic>;
|
||||
nodes = (response['nodes'] as List<dynamic>).cast<Map<String, dynamic>>();
|
||||
notice =
|
||||
'已同步 ${devices.length} 台设备 · ${DateTime.now().toString().substring(11, 19)}';
|
||||
});
|
||||
refreshing = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> deviceAction(String id, Future<void> Function() fn) async {
|
||||
if (closing || !pending.add(id)) {
|
||||
return;
|
||||
}
|
||||
notifyListeners();
|
||||
try {
|
||||
await action(fn);
|
||||
} finally {
|
||||
pending.remove(id);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connect(Device d) => deviceAction(d.id, () async {
|
||||
await repository.connect(d.id);
|
||||
log('已启动 ${d.id} 的连接');
|
||||
});
|
||||
Future<void> disconnect(String id) =>
|
||||
deviceAction(id, () => repository.disconnect(id));
|
||||
Future<void> localAdb() => action(() async {
|
||||
adbListing = await repository.run(repository.settings.adb, [
|
||||
'devices',
|
||||
'-l',
|
||||
]);
|
||||
});
|
||||
Future<void> shutdown() async {
|
||||
closing = true;
|
||||
timer?.cancel();
|
||||
while (pending.isNotEmpty) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
}
|
||||
await repository.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../data/manager_repository.dart';
|
||||
import 'manager_model.dart';
|
||||
|
||||
class ManagerView extends StatefulWidget {
|
||||
final ManagerModel model;
|
||||
final Future<void> Function() onQuit;
|
||||
const ManagerView({super.key, required this.model, required this.onQuit});
|
||||
@override
|
||||
State<ManagerView> createState() => _ManagerViewState();
|
||||
}
|
||||
|
||||
class _ManagerViewState extends State<ManagerView> {
|
||||
int page = 0;
|
||||
String search = '';
|
||||
ManagerModel get m => widget.model;
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: m,
|
||||
builder: (context, _) {
|
||||
return Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 204,
|
||||
child: Material(
|
||||
color: const Color(0xFF14233F),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(24, 30, 24, 8),
|
||||
child: Text(
|
||||
'ADS',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(24, 0, 16, 36),
|
||||
child: Text(
|
||||
'设备管理中心 / Flutter',
|
||||
style: TextStyle(color: Colors.white60, fontSize: 12),
|
||||
),
|
||||
),
|
||||
for (final (i, title, icon) in [
|
||||
(0, '设备工作台', Icons.devices_rounded),
|
||||
(1, '中继节点', Icons.hub_outlined),
|
||||
(2, '本机 ADB', Icons.terminal_rounded),
|
||||
(3, '连接配置', Icons.tune_rounded),
|
||||
(4, '运行日志', Icons.receipt_long_outlined),
|
||||
])
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 4,
|
||||
),
|
||||
child: ListTile(
|
||||
selected: page == i,
|
||||
selectedTileColor: const Color(0xFF29446C),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
leading: Icon(icon, color: Colors.white70, size: 21),
|
||||
title: Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
onTap: () => setState(() => page = i),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(20),
|
||||
child: Text(
|
||||
'Windows · 网络 ADB\n关闭窗口后保留在托盘',
|
||||
style: TextStyle(
|
||||
color: Colors.white54,
|
||||
height: 1.8,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: widget.onQuit,
|
||||
icon: const Icon(Icons.logout, size: 16),
|
||||
label: const Text('退出管理中心'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Container(
|
||||
color: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 28,
|
||||
vertical: 20,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
[
|
||||
'设备工作台',
|
||||
'中继节点',
|
||||
'本机 ADB',
|
||||
'连接配置',
|
||||
'运行日志',
|
||||
][page],
|
||||
style: const TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 5),
|
||||
Text(
|
||||
m.notice,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF66758D),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: m.refreshing ? null : m.refresh,
|
||||
icon: const Icon(Icons.refresh, size: 18),
|
||||
label: Text(m.refreshing ? '同步中' : '刷新'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (m.refreshing) const LinearProgressIndicator(minHeight: 2),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: switch (page) {
|
||||
0 => devices(),
|
||||
1 => nodes(),
|
||||
2 => adb(),
|
||||
3 => SettingsView(model: m),
|
||||
_ => logs(),
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
Widget stat(String label, String value, IconData icon) => Expanded(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, color: const Color(0xFF305DDB), size: 26),
|
||||
const SizedBox(width: 16),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
value,
|
||||
style: const TextStyle(
|
||||
fontSize: 25,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
label,
|
||||
style: const TextStyle(color: Colors.blueGrey, fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget devices() {
|
||||
final all = <String, Device>{for (final d in m.devices) d.id: d};
|
||||
for (final id in m.repository.sessions.keys) {
|
||||
all.putIfAbsent(id, () => Device(id, false));
|
||||
}
|
||||
final rows = all.values
|
||||
.where((d) => d.id.toLowerCase().contains(search.toLowerCase()))
|
||||
.toList();
|
||||
return Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
stat('网关在线设备', '${m.devices.length}', Icons.phone_android),
|
||||
const SizedBox(width: 16),
|
||||
stat('本机连接', '${m.repository.sessions.length}', Icons.link),
|
||||
const SizedBox(width: 16),
|
||||
stat(
|
||||
'ADB 已就绪',
|
||||
'${m.repository.sessions.values.where((s) => s.ready).length}',
|
||||
Icons.check_circle_outline,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
onChanged: (v) => setState(() => search = v),
|
||||
decoration: const InputDecoration(
|
||||
hintText: '搜索设备 ID',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
OutlinedButton(
|
||||
onPressed: m.repository.sessions.isEmpty
|
||||
? null
|
||||
: () => m.action(() async {
|
||||
for (final id in m.repository.sessions.keys.toList()) {
|
||||
await m.disconnect(id);
|
||||
}
|
||||
}),
|
||||
child: const Text('断开全部'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Expanded(
|
||||
child: rows.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.devices_other,
|
||||
size: 52,
|
||||
color: Colors.blueGrey,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Text('暂无设备'),
|
||||
TextButton(
|
||||
onPressed: () => setState(() => page = 3),
|
||||
child: const Text('检查服务地址与客户端凭据'),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.separated(
|
||||
itemCount: rows.length,
|
||||
separatorBuilder: (_, index) => const SizedBox(height: 12),
|
||||
itemBuilder: (context, i) => deviceCard(rows[i]),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget deviceCard(Device d) {
|
||||
final s = m.repository.sessions[d.id];
|
||||
final pending = m.pending.contains(d.id);
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFEDF2FF),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.phone_android,
|
||||
color: Color(0xFF305DDB),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
d.id,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 17,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 5),
|
||||
Text(
|
||||
s?.state ?? (d.busy ? '其他客户端占用' : '空闲 · 可连接'),
|
||||
style: TextStyle(
|
||||
color: s?.ready == true
|
||||
? Colors.teal
|
||||
: Colors.blueGrey,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (pending)
|
||||
const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
if (s == null)
|
||||
FilledButton(
|
||||
onPressed: pending || d.busy ? null : () => m.connect(d),
|
||||
child: const Text('连接设备'),
|
||||
)
|
||||
else
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
FilledButton.icon(
|
||||
onPressed: pending || !s.ready || s.screen != null
|
||||
? null
|
||||
: () => m.deviceAction(
|
||||
d.id,
|
||||
() => m.repository.screen(s),
|
||||
),
|
||||
icon: const Icon(Icons.open_in_new, size: 16),
|
||||
label: Text(s.screen == null ? '打开 scrcpy' : '投屏运行中'),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: pending ? null : () => m.disconnect(d.id),
|
||||
child: const Text('断开'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
if (s != null) ...[
|
||||
const Divider(height: 28),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'网络 ADB ${s.endpoint} · ${s.route}',
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: '复制 ADB 地址',
|
||||
onPressed: () =>
|
||||
Clipboard.setData(ClipboardData(text: s.endpoint)),
|
||||
icon: const Icon(Icons.copy, size: 16),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget nodes() => m.nodes.isEmpty
|
||||
? const Center(child: Text('暂无中继节点,或服务尚未启用 v2 节点接口'))
|
||||
: ListView.separated(
|
||||
itemCount: m.nodes.length,
|
||||
separatorBuilder: (_, index) => const SizedBox(height: 12),
|
||||
itemBuilder: (_, i) {
|
||||
final n = m.nodes[i];
|
||||
return Card(
|
||||
child: ListTile(
|
||||
contentPadding: const EdgeInsets.all(20),
|
||||
leading: Icon(
|
||||
Icons.hub,
|
||||
color: n['healthy'] == true ? Colors.teal : Colors.grey,
|
||||
),
|
||||
title: Text('${n["id"]}'),
|
||||
subtitle: Text(n['healthy'] == true ? '在线' : '不可用'),
|
||||
trailing: Text('通道 ${n["sessions"]} / ${n["capacity"]}'),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
Widget adb() => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'使用本机 ADB Server,显示本地 USB 设备和网络设备。',
|
||||
style: TextStyle(color: Colors.blueGrey),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
children: [
|
||||
FilledButton.icon(
|
||||
onPressed: m.localAdb,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('读取设备列表'),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: () => m.action(() async {
|
||||
final result = await m.repository.run(m.repository.settings.adb, [
|
||||
'start-server',
|
||||
]);
|
||||
m.log(result.isEmpty ? 'ADB Server 已启动' : result);
|
||||
await m.localAdb();
|
||||
}),
|
||||
child: const Text('启动 ADB Server'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Expanded(
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF14233F),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
child: SelectableText(
|
||||
m.adbListing.isEmpty ? '点击“读取设备列表”检查本机设备。' : m.adbListing,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontFamily: 'Consolas',
|
||||
height: 1.8,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
Widget logs() => Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Text('最近 500 条 · 仅保存在内存'),
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
Clipboard.setData(ClipboardData(text: m.logs.join('\n'))),
|
||||
child: const Text('复制日志'),
|
||||
),
|
||||
],
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: m.logs.length,
|
||||
itemBuilder: (_, i) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 5),
|
||||
child: SelectableText(
|
||||
m.logs[i],
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class SettingsView extends StatefulWidget {
|
||||
final ManagerModel model;
|
||||
const SettingsView({super.key, required this.model});
|
||||
@override
|
||||
State<SettingsView> createState() => _SettingsViewState();
|
||||
}
|
||||
|
||||
class _SettingsViewState extends State<SettingsView> {
|
||||
late final Map<String, TextEditingController> fields;
|
||||
bool relayOnly = false;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final s = widget.model.repository.settings;
|
||||
fields = {
|
||||
for (final entry in {
|
||||
'server': s.server,
|
||||
'origin': s.origin,
|
||||
'credential': s.credential,
|
||||
'client': s.client,
|
||||
'adb': s.adb,
|
||||
'scrcpy': s.scrcpy,
|
||||
}.entries)
|
||||
entry.key: TextEditingController(text: entry.value),
|
||||
};
|
||||
relayOnly = s.relayOnly;
|
||||
}
|
||||
|
||||
void apply() {
|
||||
final s = widget.model.repository.settings;
|
||||
s.server = fields['server']!.text.trim();
|
||||
s.origin = fields['origin']!.text.trim();
|
||||
s.credential = fields['credential']!.text.trim();
|
||||
s.client = fields['client']!.text.trim();
|
||||
s.adb = fields['adb']!.text.trim();
|
||||
s.scrcpy = fields['scrcpy']!.text.trim();
|
||||
s.relayOnly = relayOnly;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final c in fields.values) {
|
||||
c.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListView(
|
||||
children: [
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'控制中心与工具',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'修改后点击保存;已连接设备继续使用连接时的配置。令牌仅保存在内存。',
|
||||
style: TextStyle(color: Colors.blueGrey, fontSize: 12),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
for (final (key, label) in [
|
||||
('server', '控制中心 WSS 地址'),
|
||||
('origin', '直连服务器(可留空)'),
|
||||
('credential', '客户端凭据文件 client.env'),
|
||||
('client', 'ads-client.exe 路径'),
|
||||
('adb', 'adb.exe 路径'),
|
||||
('scrcpy', 'scrcpy.exe 路径(需保留完整发行目录)'),
|
||||
])
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 18),
|
||||
child: TextField(
|
||||
controller: fields[key],
|
||||
decoration: InputDecoration(labelText: label),
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
value: relayOnly,
|
||||
title: const Text('仅使用中继'),
|
||||
subtitle: const Text('关闭时优先尝试 P2P 直连'),
|
||||
onChanged: (v) => setState(() => relayOnly = v),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
FilledButton(
|
||||
onPressed: () => widget.model.action(() async {
|
||||
apply();
|
||||
widget.model.repository.settings.uri('v1/devices');
|
||||
await widget.model.repository.save();
|
||||
widget.model.notice = '配置已保存';
|
||||
}),
|
||||
child: const Text('保存配置'),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: () => widget.model.action(() async {
|
||||
apply();
|
||||
await widget.model.repository.importCredential();
|
||||
fields['origin']!.text =
|
||||
widget.model.repository.settings.origin;
|
||||
widget.model.notice = '客户端凭据已导入';
|
||||
await widget.model.refresh();
|
||||
}),
|
||||
child: const Text('导入凭据并同步'),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: () => widget.model.action(() async {
|
||||
apply();
|
||||
for (final (exe, args) in [
|
||||
(fields['client']!.text, ['--version']),
|
||||
(fields['adb']!.text, ['version']),
|
||||
(fields['scrcpy']!.text, ['--version']),
|
||||
]) {
|
||||
widget.model.log(
|
||||
await widget.model.repository.run(exe, args),
|
||||
);
|
||||
}
|
||||
widget.model.notice = '工具检查完成';
|
||||
}),
|
||||
child: const Text('检查工具'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user