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 _agents = []; List 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 Function(String, String)? savePath; String adminPath = '', enrollmentPath = '', enrollmentToken = '', configPath = '', configText = '', logText = ''; List discoveredDevices = []; Future discoverDevices() => run(() async { final rows = await _call({'op': 'devices_discover'}); discoveredDevices = (rows! as List) .map((v) => Map.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 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': [], }); 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 run(Future 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) { 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 importAdmin() => run(() async { await repository.importAdmin(adminPath); _hasAdmin = true; notice = '管理员凭据已导入,仅保存在内存中。'; await _refresh(); }); Future importEnrollment() => run(() async { enrollmentToken = await repository.enrollment(enrollmentPath); notice = '设备端凭据已导入,仅用于本机初始化。'; }); Future refresh() => run(_refresh); Future _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 _call(JsonMap operation) { if (_listedSource != _sourceKey) { throw StateError('管理地址或配置路径已改变,请先刷新 Agent 列表'); } return repository.call(localMode, configPath, selectedId ?? '', operation); } Future loadConfig() => run(() async { configText = const JsonEncoder.withIndent(' ') .convert(await _call({'op': 'config_get'})); notice = '已读取配置,凭据不在配置中。'; }); Future saveConfig() => run(() async { final data = jsonDecode(configText) as Map; await _call({'op': 'config_set', 'config': data}); await _refresh(); notice = '配置已保存并应用,受影响的设备会重建连接。'; }); Future 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 deviceOperation(String op, {bool? enabled}) => run(() async { if (selectedPhone == null) { return; } await _call({'op': op, 'id': selectedPhone, 'enabled': ?enabled}); await _refresh(); }); Future restart() => run(() async { await _call({'op': 'restart'}); notice = '监督进程将重启 Agent,手机连接会短暂中断。'; }); Future readLogs() => run(_logs); Future _logs() async { final page = Map.from( (await _call({'op': 'logs', 'after': _cursor, 'limit': 50}))! as Map, ); 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) { final line = value! as Map; logText += repository.redact( '${line['time']} ${line['level']} ${line['message']}\n', ); } if (logText.length > 100000) { logText = logText.substring(logText.length - 100000); } } Future initializeLocal() => run(() async { if (await File(configPath).exists()) { throw StateError('配置已经存在,请读取后修改'); } await repository.api.initialize( configPath, jsonDecode(configText) as Map, enrollmentToken, ); enrollmentToken = ''; notice = '本机配置已初始化,可启动后台 Agent 后应用设备配置。'; }); Future startLocal() => run(() async { await repository.api.start(configPath); await _refresh(); notice = '后台 Agent 已启动,退出客户端不会停止它。'; }); Future installLocal() => run(() async { await repository.api.install(configPath); await _refresh(); notice = '已安装无界面开机服务。'; }); @override void dispose() { if (_disposed) { return; } _disposed = true; _timer?.cancel(); super.dispose(); } }