Files
AndroidDeviceStreaming/flutter_manager/lib/ui/agent_model.dart
T

324 lines
10 KiB
Dart

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;
void Function(String)? onLog;
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;
Future<void> Function(String, String)? savePath;
String adminPath = '',
enrollmentPath = '',
enrollmentToken = '',
configPath = '',
configText = '',
logText = '';
List<JsonMap> discoveredDevices = [];
Future<void> discoverDevices() => run(() async {
final rows = await _call({'op': 'devices_discover'});
discoveredDevices = (rows! as List<Object?>)
.map((v) => Map<String, Object?>.from(v! as Map))
.toList();
notice =
'发现 ${discoveredDevices.length} 台 ADB 设备;选择后确认添加。USB 接入仍须启用 TCP adbd。';
});
void chooseDiscovered(JsonMap row) {
final serial = row['serial']! as String;
final tcp = RegExp(r'^.+:\d+$').hasMatch(serial);
target = tcp ? serial : '';
adbSerial = tcp ? '' : serial;
deviceId = 'phone-${DateTime.now().microsecondsSinceEpoch}';
notice = '已填入添加表单,请确认设备 ID 后添加手机。';
_notify();
}
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;
}
final previousNotice = notice;
busy = true;
_notify();
try {
await operation();
} catch (error) {
notice = repository.redact(error.toString());
} finally {
if (notice != previousNotice) onLog?.call(notice);
busy = false;
_notify();
}
}
void select(String? id) {
if (id != selectedId) {
discoveredDevices = [];
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> setAutoUsb(bool enabled) => run(() async {
final config = Map<String, Object?>.from(
await _call({'op': 'config_get'}) as Map,
);
final expected = Map<String, Object?>.from(config);
config['auto_register_usb'] = enabled;
await _call({
'op': 'config_set',
'config': config,
'expected_config': expected,
});
configText = const JsonEncoder.withIndent(' ').convert(config);
await _refresh();
notice = enabled ? '已开启真实 USB 自动注册。' : '已关闭自动注册,已有设备保留。';
});
Future<void> unignoreUsb() => run(() async {
final serial = adbSerial.trim();
if (serial.isEmpty) throw StateError('请先发现并选择需要取消忽略的 USB 设备');
final config = Map<String, Object?>.from(
await _call({'op': 'config_get'}) as Map,
);
final expected = Map<String, Object?>.from(config);
config['ignored_usb_serials'] =
(config['ignored_usb_serials'] as List? ?? [])
.where((s) => s != serial)
.toList();
await _call({
'op': 'config_set',
'config': config,
'expected_config': expected,
});
configText = const JsonEncoder.withIndent(' ').convert(config);
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?>;
final text = repository.redact(
'${line['time']} ${line['level']} ${line['message']}',
);
logText += '$text\n';
onLog?.call('[${selectedId ?? "local"}] $text');
}
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();
}
}