import 'dart:async'; import 'package:flutter/foundation.dart'; import '../data/manager_repository.dart'; import '../data/agent_repository.dart'; import '../data/daily_log.dart'; import '../data/agent_service.dart'; import 'agent_model.dart'; import 'dart:io'; import 'package:path/path.dart' as p; DailyLog defaultLog() => DailyLog( Directory( p.join( Platform.environment['LOCALAPPDATA'] ?? p.join( Platform.environment['HOME'] ?? Directory.systemTemp.path, '.local', 'share', ), 'TTSTD', 'ADS-Flutter', 'logs', ), ), ); class ManagerModel extends ChangeNotifier { late final ManagerRepository repository; late final AgentModel agents; List devices = []; List> nodes = []; final List logs = []; late final DailyLog diskLog; Future openLogDirectory() => action(() async { await diskLog.directory.create(recursive: true); final command = Platform.isWindows ? 'explorer.exe' : Platform.isMacOS ? 'open' : 'xdg-open'; await Process.start(command, [ logDirectory, ], mode: ProcessStartMode.detached); }); String get logDirectory => diskLog.directory.path; final Set pending = {}; String notice = '正在初始化', adbListing = ''; bool refreshing = false, closing = false, polling = false; Timer? timer; int ticks = 0; ManagerModel({DailyLog? logWriter}) { diskLog = logWriter ?? defaultLog(); repository = ManagerRepository(log); agents = AgentModel(AgentRepository(AgentService(repository))); agents.onLog = (text) => log("[Agent] $text"); } void log(String text) { var safe = agents.repository.redact(text); for (final secret in [repository.token, agents.enrollmentToken]) { if (secret.isNotEmpty) safe = safe.replaceAll(secret, '[REDACTED]'); } logs.insert(0, '${DateTime.now().toString().substring(11, 19)} $safe'); diskLog.add( safe.length > 16384 ? '${safe.substring(0, 16384)} [truncated]' : safe, ); if (logs.length > 500) { logs.removeLast(); } notifyListeners(); } Future action(Future Function() operation) async { try { await operation(); } catch (e) { notice = e.toString(); log(notice); } notifyListeners(); } Future init() async { await action(() async { await repository.init(); agents.savePath = (key, value) async { repository.settings.agentPaths[key] = value; await repository.save(); }; await agents.initialize( adminFile: repository.settings.agentPaths['admin'] ?? (repository.root == null ? p.join(p.dirname(Platform.resolvedExecutable), 'admin.env') : p.join( repository.root!.path, 'config', 'private', 'admin.env', )), server: repository.settings.server, origin: repository.settings.origin, ); agents.configPath = repository.settings.agentPaths['configPath'] ?? agents.configPath; agents.enrollmentPath = repository.settings.agentPaths['enroll'] ?? agents.enrollmentPath; notice = '准备就绪'; }); await refresh(); log('ADS Flutter / Cupertino 已启动,本地日志目录:$logDirectory'); 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 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; nodes = (response['nodes'] as List).cast>(); notice = '已同步 ${devices.length} 台设备 · ${DateTime.now().toString().substring(11, 19)}'; }); refreshing = false; notifyListeners(); } Future deviceAction(String id, Future Function() fn) async { if (closing || !pending.add(id)) { return; } notifyListeners(); try { await action(fn); } finally { pending.remove(id); notifyListeners(); } } Future connect(Device d) => deviceAction(d.id, () async { await repository.connect(d.id); log('已启动 ${d.id} 的连接'); }); Future disconnect(String id) => deviceAction(id, () => repository.disconnect(id)); Future localAdb() => action(() async { adbListing = await repository.run(repository.settings.adb, [ 'devices', '-l', ]); }); @override void dispose() { agents.dispose(); timer?.cancel(); super.dispose(); } Future shutdown() async { closing = true; agents.dispose(); timer?.cancel(); while (pending.isNotEmpty) { await Future.delayed(const Duration(milliseconds: 50)); } await repository.shutdown(); await diskLog.flush(); } }