feat: add headless agent management to CLI and both desktop clients

This commit is contained in:
tongtong committed 2026-11-12 21:17:44 +08:00
1 parent e91fa0235c
commit 6916dd54fb
50 files changed
+4837 -148

No files matched your search

@@ -0,0 +1,75 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'agent_models.freezed.dart';
@freezed
abstract class ManagedPhone with _$ManagedPhone {
const ManagedPhone._();
const factory ManagedPhone({
required String id,
String? target,
String? adbSerial,
required bool enabled,
required bool connected,
String? lastError,
}) = _ManagedPhone;
factory ManagedPhone.fromMap(Map<String, Object?> map) => ManagedPhone(
id: map['id'] as String,
target: map['target'] as String?,
adbSerial: map['adb_serial'] as String?,
enabled: map['enabled'] == true,
connected: map['connected'] == true,
lastError: map['last_error'] as String?,
);
String get description =>
'$id · ${!enabled
? "已停用"
: connected
? lastError == null
? "已注册"
: "转发异常"
: "等待注册"} · ${target ?? adbSerial ?? ""}';
}
@freezed
abstract class ManagedAgent with _$ManagedAgent {
const ManagedAgent._();
const factory ManagedAgent({
required String id,
required String name,
required bool online,
required String hostname,
required String os,
required String arch,
required String version,
required int pid,
required int revision,
required bool supervised,
required List<ManagedPhone> devices,
}) = _ManagedAgent;
factory ManagedAgent.fromMap(Map<String, Object?> map) {
final status = Map<String, Object?>.from(
map['status']! as Map<String, Object?>,
);
return ManagedAgent(
id: map['id'] as String,
name: status['name'] as String? ?? '',
online: map['online'] == true,
hostname: status['hostname'] as String? ?? '',
os: status['os'] as String? ?? '',
arch: status['arch'] as String? ?? '',
version: status['version'] as String? ?? '',
pid: status['pid'] as int? ?? 0,
revision: status['revision'] as int? ?? 0,
supervised: status['supervised'] == true,
devices: (status['devices'] as List<Object?>? ?? [])
.map(
(v) => ManagedPhone.fromMap(
Map<String, Object?>.from(v! as Map<String, Object?>),
),
)
.toList(),
);
}
String get description =>
'${name.isEmpty ? id : name} · ${online ? "在线" : "离线"} · $os · ${devices.length} 台手机';
}
@@ -0,0 +1,594 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'agent_models.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$ManagedPhone {
String get id; String? get target; String? get adbSerial; bool get enabled; bool get connected; String? get lastError;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ManagedPhoneCopyWith<ManagedPhone> get copyWith => _$ManagedPhoneCopyWithImpl<ManagedPhone>(this as ManagedPhone, _$identity);
@override
bool operator ==(Object other) {
final _this = this as ManagedPhone;
return identical(this, other) || (other.runtimeType == runtimeType&&other is ManagedPhone&&(identical(other.id, _this.id) || other.id == _this.id)&&(identical(other.target, _this.target) || other.target == _this.target)&&(identical(other.adbSerial, _this.adbSerial) || other.adbSerial == _this.adbSerial)&&(identical(other.enabled, _this.enabled) || other.enabled == _this.enabled)&&(identical(other.connected, _this.connected) || other.connected == _this.connected)&&(identical(other.lastError, _this.lastError) || other.lastError == _this.lastError));
}
@override
int get hashCode {
final _this = this as ManagedPhone;
return Object.hash(runtimeType,_this.id,_this.target,_this.adbSerial,_this.enabled,_this.connected,_this.lastError);
}
@override
String toString() {
final _this = this as ManagedPhone;
return 'ManagedPhone(id: ${_this.id}, target: ${_this.target}, adbSerial: ${_this.adbSerial}, enabled: ${_this.enabled}, connected: ${_this.connected}, lastError: ${_this.lastError})';
}
}
/// @nodoc
abstract mixin class $ManagedPhoneCopyWith<$Res> {
factory $ManagedPhoneCopyWith(ManagedPhone value, $Res Function(ManagedPhone) _then) = _$ManagedPhoneCopyWithImpl;
@useResult
$Res call({
String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError
});
}
/// @nodoc
class _$ManagedPhoneCopyWithImpl<$Res>
implements $ManagedPhoneCopyWith<$Res> {
_$ManagedPhoneCopyWithImpl(this._self, this._then);
final ManagedPhone _self;
final $Res Function(ManagedPhone) _then;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? target = freezed,Object? adbSerial = freezed,Object? enabled = null,Object? connected = null,Object? lastError = freezed,}) {
return _then(ManagedPhone(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,target: freezed == target ? _self.target : target // ignore: cast_nullable_to_non_nullable
as String?,adbSerial: freezed == adbSerial ? _self.adbSerial : adbSerial // ignore: cast_nullable_to_non_nullable
as String?,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable
as bool,connected: null == connected ? _self.connected : connected // ignore: cast_nullable_to_non_nullable
as bool,lastError: freezed == lastError ? _self.lastError : lastError // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// Adds pattern-matching-related methods to [ManagedPhone].
extension ManagedPhonePatterns on ManagedPhone {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _ManagedPhone value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _ManagedPhone value) $default,){
final _that = this;
switch (_that) {
case _ManagedPhone():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _ManagedPhone value)? $default,){
final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that.id,_that.target,_that.adbSerial,_that.enabled,_that.connected,_that.lastError);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError) $default,) {final _that = this;
switch (_that) {
case _ManagedPhone():
return $default(_that.id,_that.target,_that.adbSerial,_that.enabled,_that.connected,_that.lastError);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError)? $default,) {final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that.id,_that.target,_that.adbSerial,_that.enabled,_that.connected,_that.lastError);case _:
return null;
}
}
}
/// @nodoc
class _ManagedPhone extends ManagedPhone {
const _ManagedPhone({required this.id, this.target, this.adbSerial, required this.enabled, required this.connected, this.lastError}): super._();
@override final String id;
@override final String? target;
@override final String? adbSerial;
@override final bool enabled;
@override final bool connected;
@override final String? lastError;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ManagedPhoneCopyWith<_ManagedPhone> get copyWith => __$ManagedPhoneCopyWithImpl<_ManagedPhone>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _ManagedPhone&&(identical(other.id, id) || other.id == id)&&(identical(other.target, target) || other.target == target)&&(identical(other.adbSerial, adbSerial) || other.adbSerial == adbSerial)&&(identical(other.enabled, enabled) || other.enabled == enabled)&&(identical(other.connected, connected) || other.connected == connected)&&(identical(other.lastError, lastError) || other.lastError == lastError));
}
@override
int get hashCode {
return Object.hash(runtimeType,id,target,adbSerial,enabled,connected,lastError);
}
@override
String toString() {
return 'ManagedPhone(id: $id, target: $target, adbSerial: $adbSerial, enabled: $enabled, connected: $connected, lastError: $lastError)';
}
}
/// @nodoc
abstract mixin class _$ManagedPhoneCopyWith<$Res> implements $ManagedPhoneCopyWith<$Res> {
factory _$ManagedPhoneCopyWith(_ManagedPhone value, $Res Function(_ManagedPhone) _then) = __$ManagedPhoneCopyWithImpl;
@override @useResult
$Res call({
String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError
});
}
/// @nodoc
class __$ManagedPhoneCopyWithImpl<$Res>
implements _$ManagedPhoneCopyWith<$Res> {
__$ManagedPhoneCopyWithImpl(this._self, this._then);
final _ManagedPhone _self;
final $Res Function(_ManagedPhone) _then;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? target = freezed,Object? adbSerial = freezed,Object? enabled = null,Object? connected = null,Object? lastError = freezed,}) {
return _then(_ManagedPhone(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,target: freezed == target ? _self.target : target // ignore: cast_nullable_to_non_nullable
as String?,adbSerial: freezed == adbSerial ? _self.adbSerial : adbSerial // ignore: cast_nullable_to_non_nullable
as String?,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable
as bool,connected: null == connected ? _self.connected : connected // ignore: cast_nullable_to_non_nullable
as bool,lastError: freezed == lastError ? _self.lastError : lastError // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// @nodoc
mixin _$ManagedAgent {
String get id; String get name; bool get online; String get hostname; String get os; String get arch; String get version; int get pid; int get revision; bool get supervised; List<ManagedPhone> get devices;
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ManagedAgentCopyWith<ManagedAgent> get copyWith => _$ManagedAgentCopyWithImpl<ManagedAgent>(this as ManagedAgent, _$identity);
@override
bool operator ==(Object other) {
final _this = this as ManagedAgent;
return identical(this, other) || (other.runtimeType == runtimeType&&other is ManagedAgent&&(identical(other.id, _this.id) || other.id == _this.id)&&(identical(other.name, _this.name) || other.name == _this.name)&&(identical(other.online, _this.online) || other.online == _this.online)&&(identical(other.hostname, _this.hostname) || other.hostname == _this.hostname)&&(identical(other.os, _this.os) || other.os == _this.os)&&(identical(other.arch, _this.arch) || other.arch == _this.arch)&&(identical(other.version, _this.version) || other.version == _this.version)&&(identical(other.pid, _this.pid) || other.pid == _this.pid)&&(identical(other.revision, _this.revision) || other.revision == _this.revision)&&(identical(other.supervised, _this.supervised) || other.supervised == _this.supervised)&&const DeepCollectionEquality().equals(other.devices, _this.devices));
}
@override
int get hashCode {
final _this = this as ManagedAgent;
return Object.hash(runtimeType,_this.id,_this.name,_this.online,_this.hostname,_this.os,_this.arch,_this.version,_this.pid,_this.revision,_this.supervised,const DeepCollectionEquality().hash(_this.devices));
}
@override
String toString() {
final _this = this as ManagedAgent;
return 'ManagedAgent(id: ${_this.id}, name: ${_this.name}, online: ${_this.online}, hostname: ${_this.hostname}, os: ${_this.os}, arch: ${_this.arch}, version: ${_this.version}, pid: ${_this.pid}, revision: ${_this.revision}, supervised: ${_this.supervised}, devices: ${_this.devices})';
}
}
/// @nodoc
abstract mixin class $ManagedAgentCopyWith<$Res> {
factory $ManagedAgentCopyWith(ManagedAgent value, $Res Function(ManagedAgent) _then) = _$ManagedAgentCopyWithImpl;
@useResult
$Res call({
String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices
});
}
/// @nodoc
class _$ManagedAgentCopyWithImpl<$Res>
implements $ManagedAgentCopyWith<$Res> {
_$ManagedAgentCopyWithImpl(this._self, this._then);
final ManagedAgent _self;
final $Res Function(ManagedAgent) _then;
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,Object? online = null,Object? hostname = null,Object? os = null,Object? arch = null,Object? version = null,Object? pid = null,Object? revision = null,Object? supervised = null,Object? devices = null,}) {
return _then(ManagedAgent(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,online: null == online ? _self.online : online // ignore: cast_nullable_to_non_nullable
as bool,hostname: null == hostname ? _self.hostname : hostname // ignore: cast_nullable_to_non_nullable
as String,os: null == os ? _self.os : os // ignore: cast_nullable_to_non_nullable
as String,arch: null == arch ? _self.arch : arch // ignore: cast_nullable_to_non_nullable
as String,version: null == version ? _self.version : version // ignore: cast_nullable_to_non_nullable
as String,pid: null == pid ? _self.pid : pid // ignore: cast_nullable_to_non_nullable
as int,revision: null == revision ? _self.revision : revision // ignore: cast_nullable_to_non_nullable
as int,supervised: null == supervised ? _self.supervised : supervised // ignore: cast_nullable_to_non_nullable
as bool,devices: null == devices ? _self.devices : devices // ignore: cast_nullable_to_non_nullable
as List<ManagedPhone>,
));
}
}
/// Adds pattern-matching-related methods to [ManagedAgent].
extension ManagedAgentPatterns on ManagedAgent {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _ManagedAgent value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _ManagedAgent value) $default,){
final _that = this;
switch (_that) {
case _ManagedAgent():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _ManagedAgent value)? $default,){
final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that.id,_that.name,_that.online,_that.hostname,_that.os,_that.arch,_that.version,_that.pid,_that.revision,_that.supervised,_that.devices);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices) $default,) {final _that = this;
switch (_that) {
case _ManagedAgent():
return $default(_that.id,_that.name,_that.online,_that.hostname,_that.os,_that.arch,_that.version,_that.pid,_that.revision,_that.supervised,_that.devices);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices)? $default,) {final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that.id,_that.name,_that.online,_that.hostname,_that.os,_that.arch,_that.version,_that.pid,_that.revision,_that.supervised,_that.devices);case _:
return null;
}
}
}
/// @nodoc
class _ManagedAgent extends ManagedAgent {
const _ManagedAgent({required this.id, required this.name, required this.online, required this.hostname, required this.os, required this.arch, required this.version, required this.pid, required this.revision, required this.supervised, required List<ManagedPhone> devices}): _devices = devices,super._();
@override final String id;
@override final String name;
@override final bool online;
@override final String hostname;
@override final String os;
@override final String arch;
@override final String version;
@override final int pid;
@override final int revision;
@override final bool supervised;
final List<ManagedPhone> _devices;
@override List<ManagedPhone> get devices {
if (_devices is EqualUnmodifiableListView) return _devices;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_devices);
}
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ManagedAgentCopyWith<_ManagedAgent> get copyWith => __$ManagedAgentCopyWithImpl<_ManagedAgent>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _ManagedAgent&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.online, online) || other.online == online)&&(identical(other.hostname, hostname) || other.hostname == hostname)&&(identical(other.os, os) || other.os == os)&&(identical(other.arch, arch) || other.arch == arch)&&(identical(other.version, version) || other.version == version)&&(identical(other.pid, pid) || other.pid == pid)&&(identical(other.revision, revision) || other.revision == revision)&&(identical(other.supervised, supervised) || other.supervised == supervised)&&const DeepCollectionEquality().equals(other.devices, _devices));
}
@override
int get hashCode {
return Object.hash(runtimeType,id,name,online,hostname,os,arch,version,pid,revision,supervised,const DeepCollectionEquality().hash(_devices));
}
@override
String toString() {
return 'ManagedAgent(id: $id, name: $name, online: $online, hostname: $hostname, os: $os, arch: $arch, version: $version, pid: $pid, revision: $revision, supervised: $supervised, devices: $devices)';
}
}
/// @nodoc
abstract mixin class _$ManagedAgentCopyWith<$Res> implements $ManagedAgentCopyWith<$Res> {
factory _$ManagedAgentCopyWith(_ManagedAgent value, $Res Function(_ManagedAgent) _then) = __$ManagedAgentCopyWithImpl;
@override @useResult
$Res call({
String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices
});
}
/// @nodoc
class __$ManagedAgentCopyWithImpl<$Res>
implements _$ManagedAgentCopyWith<$Res> {
__$ManagedAgentCopyWithImpl(this._self, this._then);
final _ManagedAgent _self;
final $Res Function(_ManagedAgent) _then;
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,Object? online = null,Object? hostname = null,Object? os = null,Object? arch = null,Object? version = null,Object? pid = null,Object? revision = null,Object? supervised = null,Object? devices = null,}) {
return _then(_ManagedAgent(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,online: null == online ? _self.online : online // ignore: cast_nullable_to_non_nullable
as bool,hostname: null == hostname ? _self.hostname : hostname // ignore: cast_nullable_to_non_nullable
as String,os: null == os ? _self.os : os // ignore: cast_nullable_to_non_nullable
as String,arch: null == arch ? _self.arch : arch // ignore: cast_nullable_to_non_nullable
as String,version: null == version ? _self.version : version // ignore: cast_nullable_to_non_nullable
as String,pid: null == pid ? _self.pid : pid // ignore: cast_nullable_to_non_nullable
as int,revision: null == revision ? _self.revision : revision // ignore: cast_nullable_to_non_nullable
as int,supervised: null == supervised ? _self.supervised : supervised // ignore: cast_nullable_to_non_nullable
as bool,devices: null == devices ? _self._devices : devices // ignore: cast_nullable_to_non_nullable
as List<ManagedPhone>,
));
}
}
// dart format on
@@ -0,0 +1,54 @@
import 'dart:io';
import 'agent_models.dart';
import 'agent_service.dart';
class AgentRepository {
const AgentRepository(this.api);
final AgentApi api;
String get connectionKey => api.connectionKey;
String redact(String text) => api.redact(text);
Future<List<ManagedAgent>> list({
required bool local,
required String config,
}) async {
final values = local
? [
<String, Object?>{
'id': '',
'online': true,
'status': await api.local(config, {'op': 'status'}),
},
]
: await api.list();
if (local) {
final status = Map<String, Object?>.from(
values[0]['status']! as Map<String, Object?>,
);
values[0]['id'] = status['id'];
}
return values.map(ManagedAgent.fromMap).toList(growable: false);
}
Future<Object?> call(
bool local,
String config,
String agent,
JsonMap operation,
) => local ? api.local(config, operation) : api.request(agent, operation);
Future<void> importAdmin(String path) => api.importAdmin(path);
Future<String> enrollment(String path) async {
final file = File(path);
if (await file.length() > 65536) {
throw const FormatException('凭据文件过大');
}
final line = (await file.readAsLines())
.where((v) => v.startsWith('ADS_AGENT_TOKEN='))
.firstOrNull;
final value = line?.substring(16).trim() ?? '';
if (value.length < 32) {
throw const FormatException('请选择包含 ADS_AGENT_TOKEN 的 agent.env');
}
return value;
}
}
+181
View File
@@ -0,0 +1,181 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'manager_repository.dart';
typedef JsonMap = Map<String, Object?>;
abstract interface class AgentApi {
String get connectionKey;
Future<List<JsonMap>> list();
Future<Object?> request(String agent, JsonMap operation);
Future<Object?> local(String config, JsonMap operation);
Future<void> importAdmin(String path);
Future<void> initialize(String path, JsonMap config, String token);
Future<void> start(String path);
Future<void> install(String path);
String redact(String message);
}
class AgentService implements AgentApi {
AgentService(this.manager);
final ManagerRepository manager;
@override
String get connectionKey =>
jsonEncode([manager.settings.server, manager.settings.origin]);
String _token = '';
final Set<String> _secrets = {};
@override
String redact(String message) {
for (final secret in _secrets) {
message = message.replaceAll(secret, '[REDACTED]');
}
return message;
}
@override
Future<void> importAdmin(String path) async {
final file = File(path);
if (await file.length() > 65536) {
throw const FormatException('凭据文件过大');
}
final line = (await file.readAsLines())
.where((v) => v.startsWith('ADS_ADMIN_TOKEN='))
.firstOrNull;
final token = line?.substring(16).trim() ?? '';
if (token.length < 32 || token.contains(RegExp(r'[\r\n]'))) {
throw const FormatException('请选择包含 ADS_ADMIN_TOKEN 的 admin.env');
}
_token = token;
_secrets.add(token);
}
@override
Future<List<JsonMap>> list() async {
final value =
await manager.requestJson('v3/agents', bearer: _token) as List<Object?>;
return value.map((v) => Map<String, Object?>.from(v! as Map)).toList();
}
@override
Future<Object?> request(String agent, JsonMap operation) async {
final value = await manager.requestJson(
'v3/rpc',
bearer: _token,
payload: operation,
query: {'agent': agent},
) as Map<String, dynamic>;
if (value['ok'] != true) {
throw StateError(redact(value['error'] as String? ?? 'Agent 管理请求失败'));
}
return value['data'];
}
Future<ProcessResult> _cli(
List<String> args, {
String? input,
Map<String, String>? extra,
}) async {
final child = await Process.start(
manager.findTool('adsctl'),
args,
environment: {...manager.environment(), ...?extra},
includeParentEnvironment: false,
);
final out = child.stdout.transform(utf8.decoder).join();
final error = child.stderr.transform(utf8.decoder).join();
if (input != null) {
child.stdin.write(input);
}
await child.stdin.close();
try {
final code = await child.exitCode.timeout(const Duration(seconds: 22));
final result = ProcessResult(child.pid, code, await out, await error);
if (code != 0) {
throw StateError(redact(result.stderr as String));
}
return result;
} on TimeoutException {
child.kill();
rethrow;
}
}
@override
Future<Object?> local(String config, JsonMap operation) async {
final result = await _cli([
'--json',
'--config',
config,
'request',
], input: jsonEncode(operation));
return jsonDecode(result.stdout as String);
}
@override
Future<void> initialize(String path, JsonMap config, String token) async {
if (token.length < 32) {
throw const FormatException('请导入有效设备端凭据');
}
_secrets.add(token);
final args = [
'--json',
'--config',
path,
'--server',
config['server']! as String,
if (config['connect_address'] case final String origin) ...[
'--connect-address',
origin,
],
'init',
'--id',
config['id']! as String,
'--name',
config['name']! as String,
];
await _cli(args, extra: {'ADS_AGENT_TOKEN': token});
}
@override
Future<void> start(String path) async {
try {
await local(path, {'op': 'status'});
return;
} on StateError {
/* The private IPC lock prevents a duplicate daemon. */
}
await Process.start(
manager.findTool('ads-agent'),
['--quiet', '--supervise', '--config', path],
mode: ProcessStartMode.detached,
environment: manager.environment(),
includeParentEnvironment: false,
);
await Future<void>.delayed(const Duration(milliseconds: 700));
}
@override
Future<void> install(String path) async {
if (!Platform.isWindows) {
throw UnsupportedError('请在终端运行 adsctl service install,系统级服务加 --system');
}
String quote(String text) => "'${text.replaceAll("'", "''")}'";
final exe = manager.findTool('adsctl');
final escaped = '"${p.absolute(path)}"';
final script =
'\$p=Start-Process -FilePath ${quote(exe)} -ArgumentList @(\'--config\',${quote(escaped)},\'service\',\'install\') -Verb RunAs -WindowStyle Hidden -PassThru -Wait;exit \$p.ExitCode';
final result = await Process.run(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-Command', script],
environment: manager.environment(),
includeParentEnvironment: false,
);
if (result.exitCode != 0) {
throw StateError('开机服务安装失败,请在管理员终端检查 adsctl service install');
}
}
}
@@ -159,9 +159,19 @@ class ManagerRepository {
}
}
Future<dynamic> get(String suffix) async {
if (token.length < 32) {
throw const FormatException('请先导入客户端凭据');
Future<dynamic> get(String suffix) => requestJson(suffix);
Future<dynamic> requestJson(
String suffix, {
String? bearer,
Map<String, Object?>? payload,
Map<String, String>? query,
}) async {
final authorization = bearer ?? token;
if (authorization.length < 32) {
throw FormatException(
bearer == null ? '请先导入客户端凭据' : '请先导入管理员凭据 admin.env',
);
}
final client = HttpClient()..connectionTimeout = const Duration(seconds: 8);
client.findProxy = (_) => 'DIRECT';
@@ -192,9 +202,16 @@ class ManagerRepository {
};
}
try {
final request = await client.getUrl(settings.uri(suffix));
final uri = settings.uri(suffix).replace(queryParameters: query);
final request = payload == null
? await client.getUrl(uri)
: await client.postUrl(uri);
request.followRedirects = false;
request.headers.set('Authorization', 'Bearer $token');
request.headers.set('Authorization', 'Bearer $authorization');
if (payload != null) {
request.headers.contentType = ContentType.json;
request.write(jsonEncode(payload));
}
final response = await request.close().timeout(
const Duration(seconds: 12),
);
@@ -234,6 +251,7 @@ class ManagerRepository {
'ANDROID_ADB_SERVER_PORT',
'ADS_CLIENT_TOKEN',
'ADS_AGENT_TOKEN',
'ADS_ADMIN_TOKEN',
'ADS_CONNECT_ADDRESS',
].contains(k),
)