feat: add headless agent management to CLI and both desktop clients
This commit is contained in:
1 parent
e91fa0235c
commit
6916dd54fb
50 files changed
+4837
-148
No files matched your search
@@ -0,0 +1,263 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../data/agent_models.dart';
|
||||
import '../data/agent_repository.dart';
|
||||
import '../data/agent_service.dart';
|
||||
|
||||
class AgentModel extends ChangeNotifier {
|
||||
AgentModel(this.repository);
|
||||
final AgentRepository repository;
|
||||
List<ManagedAgent> _agents = [];
|
||||
List<ManagedAgent> get agents => List.unmodifiable(_agents);
|
||||
String? selectedId, selectedPhone;
|
||||
ManagedAgent? get selected =>
|
||||
_agents.where((a) => a.id == selectedId).firstOrNull;
|
||||
bool localMode = false, busy = false, autoRefresh = true, followLogs = false;
|
||||
String adminPath = '',
|
||||
enrollmentPath = '',
|
||||
enrollmentToken = '',
|
||||
configPath = '',
|
||||
configText = '',
|
||||
logText = '';
|
||||
String deviceId = '', target = '', adbSerial = '', adbServer = '';
|
||||
String notice = '远程管理需要独立管理员凭据;也可选择管理本机 Agent。';
|
||||
Timer? _timer;
|
||||
bool _disposed = false, _hasAdmin = false;
|
||||
int _cursor = 0;
|
||||
String _instance = '', _listedSource = '';
|
||||
String get _sourceKey =>
|
||||
localMode ? 'local:$configPath' : 'remote:${repository.connectionKey}';
|
||||
bool get canManage =>
|
||||
!busy && selected?.online == true && _listedSource == _sourceKey;
|
||||
bool get canDevice => canManage && selectedPhone != null;
|
||||
Future<void> initialize({
|
||||
required String adminFile,
|
||||
required String server,
|
||||
required String origin,
|
||||
}) async {
|
||||
adminPath = adminFile;
|
||||
configPath = Platform.isWindows
|
||||
? p.join(
|
||||
Platform.environment['LOCALAPPDATA'] ?? Directory.current.path,
|
||||
'AndroidDeviceStreaming',
|
||||
'agent',
|
||||
'agent.json',
|
||||
)
|
||||
: p.join(
|
||||
Platform.environment['XDG_CONFIG_HOME'] ??
|
||||
p.join(Platform.environment['HOME'] ?? '.', '.config'),
|
||||
'ads',
|
||||
'agent.json',
|
||||
);
|
||||
configText = const JsonEncoder.withIndent(' ').convert({
|
||||
'version': 1,
|
||||
'id': 'local-pc',
|
||||
'name': Platform.localHostname,
|
||||
'server': server,
|
||||
'connect_address': origin.trim().isEmpty ? null : origin,
|
||||
'adb_server': '127.0.0.1:5037',
|
||||
'devices': <Object?>[],
|
||||
});
|
||||
if (await File(adminPath).exists()) {
|
||||
await importAdmin();
|
||||
}
|
||||
_timer = Timer.periodic(const Duration(seconds: 5), (_) {
|
||||
if (!busy && autoRefresh && (localMode || _hasAdmin)) {
|
||||
unawaited(
|
||||
run(() async {
|
||||
await _refresh();
|
||||
if (followLogs && selected?.online == true) {
|
||||
await _logs();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) {
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> run(Future<void> Function() operation) async {
|
||||
if (busy || _disposed) {
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
_notify();
|
||||
try {
|
||||
await operation();
|
||||
} catch (error) {
|
||||
notice = repository.redact(error.toString());
|
||||
} finally {
|
||||
busy = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
void select(String? id) {
|
||||
if (id != selectedId) {
|
||||
selectedId = id;
|
||||
_cursor = 0;
|
||||
_instance = '';
|
||||
logText = '';
|
||||
selectedPhone = selected?.devices.firstOrNull?.id;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
void setLocal(bool value) {
|
||||
localMode = value;
|
||||
_agents = [];
|
||||
select(null);
|
||||
notice = value ? '管理本机 Agent,无需管理员令牌。' : '远程管理使用连接配置中的控制中心地址。';
|
||||
_notify();
|
||||
}
|
||||
|
||||
Future<void> importAdmin() => run(() async {
|
||||
await repository.importAdmin(adminPath);
|
||||
_hasAdmin = true;
|
||||
notice = '管理员凭据已导入,仅保存在内存中。';
|
||||
await _refresh();
|
||||
});
|
||||
Future<void> importEnrollment() => run(() async {
|
||||
enrollmentToken = await repository.enrollment(enrollmentPath);
|
||||
notice = '设备端凭据已导入,仅用于本机初始化。';
|
||||
});
|
||||
Future<void> refresh() => run(_refresh);
|
||||
Future<void> _refresh() async {
|
||||
final source = _sourceKey;
|
||||
final mode = localMode;
|
||||
final config = configPath;
|
||||
final rows = await repository.list(local: mode, config: config);
|
||||
if (_disposed || source != _sourceKey) {
|
||||
return;
|
||||
}
|
||||
_listedSource = source;
|
||||
_agents = List.unmodifiable(rows);
|
||||
if (!_agents.any((a) => a.id == selectedId)) {
|
||||
select(
|
||||
_agents.where((a) => a.online).firstOrNull?.id ??
|
||||
_agents.firstOrNull?.id,
|
||||
);
|
||||
}
|
||||
if (selected?.devices.any((d) => d.id == selectedPhone) != true) {
|
||||
selectedPhone = selected?.devices.firstOrNull?.id;
|
||||
}
|
||||
notice =
|
||||
'${rows.length} 个 Agent · ${rows.where((a) => a.online).length} 个在线';
|
||||
}
|
||||
|
||||
Future<Object?> _call(JsonMap operation) {
|
||||
if (_listedSource != _sourceKey) {
|
||||
throw StateError('管理地址或配置路径已改变,请先刷新 Agent 列表');
|
||||
}
|
||||
return repository.call(localMode, configPath, selectedId ?? '', operation);
|
||||
}
|
||||
|
||||
Future<void> loadConfig() => run(() async {
|
||||
configText = const JsonEncoder.withIndent(' ')
|
||||
.convert(await _call({'op': 'config_get'}));
|
||||
notice = '已读取配置,凭据不在配置中。';
|
||||
});
|
||||
Future<void> saveConfig() => run(() async {
|
||||
final data = jsonDecode(configText) as Map<String, Object?>;
|
||||
await _call({'op': 'config_set', 'config': data});
|
||||
await _refresh();
|
||||
notice = '配置已保存并应用,受影响的设备会重建连接。';
|
||||
});
|
||||
Future<void> addDevice() => run(() async {
|
||||
if (target.trim().isEmpty == adbSerial.trim().isEmpty) {
|
||||
throw const FormatException('手机地址与 ADB 序列号必须填写其中一项');
|
||||
}
|
||||
await _call({
|
||||
'op': 'device_add',
|
||||
'device': {
|
||||
'id': deviceId.trim(),
|
||||
'target': target.trim().isEmpty ? null : target.trim(),
|
||||
'adb_serial': adbSerial.trim().isEmpty ? null : adbSerial.trim(),
|
||||
'adb_server': adbServer.trim().isEmpty ? null : adbServer.trim(),
|
||||
'device_port': 5555,
|
||||
'enabled': true,
|
||||
},
|
||||
});
|
||||
await _refresh();
|
||||
notice = '手机已添加。';
|
||||
});
|
||||
Future<void> deviceOperation(String op, {bool? enabled}) => run(() async {
|
||||
if (selectedPhone == null) {
|
||||
return;
|
||||
}
|
||||
await _call({'op': op, 'id': selectedPhone, 'enabled': ?enabled});
|
||||
await _refresh();
|
||||
});
|
||||
Future<void> restart() => run(() async {
|
||||
await _call({'op': 'restart'});
|
||||
notice = '监督进程将重启 Agent,手机连接会短暂中断。';
|
||||
});
|
||||
Future<void> readLogs() => run(_logs);
|
||||
Future<void> _logs() async {
|
||||
final page = Map<String, Object?>.from(
|
||||
(await _call({'op': 'logs', 'after': _cursor, 'limit': 50}))!
|
||||
as Map<String, Object?>,
|
||||
);
|
||||
final instance = page['instance'] as String;
|
||||
if (_instance.isNotEmpty && _instance != instance) {
|
||||
_cursor = 0;
|
||||
logText = '';
|
||||
_instance = instance;
|
||||
return;
|
||||
}
|
||||
_instance = instance;
|
||||
_cursor = page['next'] as int;
|
||||
for (final value in page['entries']! as List<Object?>) {
|
||||
final line = value! as Map<String, Object?>;
|
||||
logText += repository.redact(
|
||||
'${line['time']} ${line['level']} ${line['message']}\n',
|
||||
);
|
||||
}
|
||||
if (logText.length > 100000) {
|
||||
logText = logText.substring(logText.length - 100000);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> initializeLocal() => run(() async {
|
||||
if (await File(configPath).exists()) {
|
||||
throw StateError('配置已经存在,请读取后修改');
|
||||
}
|
||||
await repository.api.initialize(
|
||||
configPath,
|
||||
jsonDecode(configText) as Map<String, Object?>,
|
||||
enrollmentToken,
|
||||
);
|
||||
enrollmentToken = '';
|
||||
notice = '本机配置已初始化,可启动后台 Agent 后应用设备配置。';
|
||||
});
|
||||
Future<void> startLocal() => run(() async {
|
||||
await repository.api.start(configPath);
|
||||
await _refresh();
|
||||
notice = '后台 Agent 已启动,退出客户端不会停止它。';
|
||||
});
|
||||
Future<void> installLocal() => run(() async {
|
||||
await repository.api.install(configPath);
|
||||
await _refresh();
|
||||
notice = '已安装无界面开机服务。';
|
||||
});
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) {
|
||||
return;
|
||||
}
|
||||
_disposed = true;
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user