Files

266 lines
22 KiB
C#

using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.Json;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace Ads.Desktop;
public partial class AgentManagementViewModel : ObservableObject, IDisposable
{
[ObservableProperty] private bool localMode;
[ObservableProperty] private string adminToken = "";
[ObservableProperty] private string enrollmentToken = "";
[ObservableProperty] private string configPath = DefaultConfig();
[ObservableProperty] private ManagedAgent? selectedAgent;
[ObservableProperty] private ManagedDevice? selectedManagedDevice;
[ObservableProperty] private string deviceId = "";
[ObservableProperty] private string target = "";
[ObservableProperty] private string adbSerial = "";
[ObservableProperty] private string adbServer = "";
[ObservableProperty] private string configJson = "";
[ObservableProperty] private string remoteLogText = "";
[ObservableProperty] private string notice = "管理员凭据用于远程管理;也可切换为管理本机 Agent。";
[ObservableProperty] private bool isBusy;
[ObservableProperty] private bool autoRefresh = true;
[ObservableProperty] private bool followLogs;
public ObservableCollection<DiscoveredDevice> DiscoveredDevices { get; } = new();
[ObservableProperty] private DiscoveredDevice? selectedDiscoveredDevice;
partial void OnSelectedDiscoveredDeviceChanged(DiscoveredDevice? value) {
if(value is null)return;
if(value.Configured || value.State!="device"){Notice="该设备已添加或尚未授权/离线。";return;}
DeviceId="phone-"+Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes((SelectedAgent?.Id ?? "")+":"+value.Serial)))[..12].ToLowerInvariant();
var tcp=System.Net.IPEndPoint.TryParse(value.Serial,out _);
Target=tcp?value.Serial:"";AdbSerial=tcp?"":value.Serial;
Notice=value.Configured?"该设备已添加。":"已填入添加表单;确认设备 ID 后点击添加手机。";
}
[RelayCommand(CanExecute=nameof(CanManage))] private Task DiscoverDevicesAsync()=>Guard(async()=>{
var rows=await CallAsync(new{op="devices_discover"});
DiscoveredDevices.Clear();SelectedDiscoveredDevice=null;
foreach(var row in rows.Deserialize<DiscoveredDevice[]>(new JsonSerializerOptions(JsonSerializerDefaults.Web)) ?? [])DiscoveredDevices.Add(row);
Notice=$"发现 {DiscoveredDevices.Count} 台 ADB 设备;选择未添加且状态为 device 的设备。USB 接入仍须启用 TCP adbd。";
});
public string SelectedAgentDetails => SelectedAgent?.Details ?? "请选择 Agent。";
public ObservableCollection<ManagedAgent> Agents { get; } = new();
public ObservableCollection<ManagedDevice> AgentDevices { get; } = new();
private readonly Func<(string Server,string Origin)> server;
private readonly Action<string> log;
private readonly CancellationTokenSource lifetime = new();
private readonly DispatcherTimer timer;
private readonly HashSet<string> secrets = new(StringComparer.Ordinal);
private bool polling, disposed;
private long logCursor;
private string logInstance = "";
private string listedSource = "";
private string SourceKey()=>LocalMode ? "local:"+ConfigPath : "remote:"+JsonSerializer.Serialize(new[]{server().Server,server().Origin});
private string? lastError;
public AgentManagementViewModel(Func<(string,string)> server, Action<string>? logger=null, bool background=true, bool credentials=true)
{
this.server=server; log=logger ?? (_=>{});
try {
var paths=Path.Combine(DesktopPaths.SettingsFolder,"agent-ui-paths.json");
if(File.Exists(paths))foreach(var entry in JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllText(paths)) ?? new())chosenPaths[entry.Key]=entry.Value;
if(chosenPaths.TryGetValue("config",out var config))ConfigPath=config;
}catch(Exception e){Notice="读取文件位置失败:"+e.Message;}
var (initialServer,initialOrigin)=server();
ConfigJson=JsonSerializer.Serialize(new {version=1,id="local-pc",name=Environment.MachineName,server=initialServer,connect_address=string.IsNullOrWhiteSpace(initialOrigin)?null:initialOrigin,adb_server="127.0.0.1:5037",devices=Array.Empty<object>()}, new JsonSerializerOptions{WriteIndented=true});
if(credentials) {
var path=DesktopPaths.ProjectRoot() is {} root ? Path.Combine(root,"config","private","admin.env") : Path.Combine(AppContext.BaseDirectory,"admin.env");
if(File.Exists(path)) { try { ImportAdmin(path); } catch { } }
}
timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(5)};
timer.Tick+=async(_,_)=>await PollAsync(); if(background)timer.Start();
}
public static string DefaultConfig() => OperatingSystem.IsWindows()
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AndroidDeviceStreaming","agent","agent.json")
: Path.Combine(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".config"),"ads","agent.json");
private readonly Dictionary<string,string> chosenPaths = new();
public string AdminPath=>RememberedPath("admin");
public string EnrollmentPath=>RememberedPath("enrollment");
public string RememberedPath(string key) => chosenPaths.GetValueOrDefault(key,"");
public void RememberPath(string key,string path) {
chosenPaths[key]=path;OnPropertyChanged(nameof(AdminPath));OnPropertyChanged(nameof(EnrollmentPath));
Directory.CreateDirectory(DesktopPaths.SettingsFolder);
var file=Path.Combine(DesktopPaths.SettingsFolder,"agent-ui-paths.json");
File.WriteAllText(file,JsonSerializer.Serialize(chosenPaths));
}
public void StartMonitoring()=>timer.Start();
private string Redact(string value) { foreach(var secret in secrets) value=value.Replace(secret,"[REDACTED]",StringComparison.Ordinal);return value; }
partial void OnAdminTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
partial void OnEnrollmentTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
partial void OnSelectedAgentChanged(ManagedAgent? value)
{
OnPropertyChanged(nameof(SelectedAgentDetails));
var selected=SelectedManagedDevice?.Id; AgentDevices.Clear();
foreach(var device in value?.Status.Devices ?? [])AgentDevices.Add(device);
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selected) ?? AgentDevices.FirstOrDefault();
DiscoveredDevices.Clear();SelectedDiscoveredDevice=null;logCursor=0;logInstance="";RemoteLogText="";UpdateCommands();
}
partial void OnSelectedManagedDeviceChanged(ManagedDevice? value)=>UpdateCommands();
partial void OnIsBusyChanged(bool value)=>UpdateCommands();
partial void OnLocalModeChanged(bool value){Agents.Clear();SelectedAgent=null;Notice=value?"管理本机 Agent,不需要管理员令牌。":"管理控制中心中的 Agent,需要独立管理员凭据。";}
private bool CanManage()=>!IsBusy && SelectedAgent?.Online==true;
private bool CanDevice()=>CanManage() && SelectedManagedDevice!=null;
private bool CanRestart()=>CanManage() && SelectedAgent?.Status.Supervised==true;
private bool CanLocal()=>!IsBusy && LocalMode;
private void UpdateCommands()
{
DiscoverDevicesCommand.NotifyCanExecuteChanged();LoadConfigCommand.NotifyCanExecuteChanged();SaveConfigCommand.NotifyCanExecuteChanged();AddDeviceCommand.NotifyCanExecuteChanged();
RemoveDeviceCommand.NotifyCanExecuteChanged();EnableDeviceCommand.NotifyCanExecuteChanged();DisableDeviceCommand.NotifyCanExecuteChanged();
ReadLogsCommand.NotifyCanExecuteChanged();RestartAgentCommand.NotifyCanExecuteChanged();
InitializeLocalCommand.NotifyCanExecuteChanged();StartLocalCommand.NotifyCanExecuteChanged();InstallServiceCommand.NotifyCanExecuteChanged();
}
public void ImportAdmin(string path)
{
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
var token=File.ReadLines(path).Select(l=>l.Split('=',2)).FirstOrDefault(p=>p.Length==2&&p[0].Trim()=="ADS_ADMIN_TOKEN")?.ElementAt(1).Trim();
if(string.IsNullOrEmpty(token)||token.Length<32||token.Contains('\r')||token.Contains('\n'))throw new InvalidOperationException("文件中没有有效的 ADS_ADMIN_TOKEN。");
RememberPath("admin",path);AdminToken=token;Notice="管理员凭据已加载,内容仅保存在内存中。";
}
public void ImportEnrollment(string path)
{
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
var value=File.ReadLines(path).FirstOrDefault(l=>l.StartsWith("ADS_AGENT_TOKEN=",StringComparison.Ordinal))?[16..].Trim();
if(string.IsNullOrEmpty(value)||value.Length<32)throw new InvalidOperationException("文件中没有有效的 ADS_AGENT_TOKEN。");
RememberPath("enrollment",path);EnrollmentToken=value;Notice="设备端凭据已加载,仅供本机初始化使用。";
}
private RelayOptions Options(){var(s,o)=server();return RelayOptions.Parse(s,o,AdminToken);}
private async Task Guard(Func<Task> action)
{
if(IsBusy)return;IsBusy=true;
try { await action(); }
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
catch(Exception error){Notice=Redact(error.Message);log("[Agent管理] "+Notice);}
finally{IsBusy=false;}
}
private async Task<JsonElement> LocalRequestAsync(object request)
{
var executable=DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl");
var info=ProcessTools.CreateStartInfo(executable,["--json","--config",ConfigPath,"request"]);info.RedirectStandardInput=true;info.StandardInputEncoding=new System.Text.UTF8Encoding(false);
using var process=Process.Start(info) ?? throw new InvalidOperationException("adsctl 无法启动。");
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
await process.StandardInput.WriteAsync(JsonSerializer.Serialize(request));process.StandardInput.Close();
try { await process.WaitForExitAsync(lifetime.Token).WaitAsync(TimeSpan.FromSeconds(20),lifetime.Token); }
catch { if(!process.HasExited)process.Kill(entireProcessTree:true);throw; }
if(process.ExitCode!=0) {
var message=(await error).Trim();
if(message.Contains("unknown variant") && message.Contains("devices_discover"))
message="本机 adsctl 或 Agent 版本过旧,不支持设备发现。请同步更新两者后重启 Agent。";
throw new InvalidOperationException(message);
}
using var value=JsonDocument.Parse(await output);return value.RootElement.Clone();
}
private Task<JsonElement> CallAsync(object request,string? agent=null) {
if(listedSource!=SourceKey())throw new InvalidOperationException("管理地址或配置路径已改变,请先刷新 Agent 列表。");
return LocalMode ? LocalRequestAsync(request) : AgentManagementApi.CallAsync(Options(),agent ?? SelectedAgent?.Id ?? throw new InvalidOperationException("请选择 Agent。"),request,lifetime.Token);
}
private async Task RefreshCoreAsync()
{
var selected=SelectedAgent?.Id;var selectedDevice=SelectedManagedDevice?.Id;
var local=LocalMode;var path=ConfigPath;var source=server();
ManagedAgent[] rows;
if(LocalMode) {
var value=await LocalRequestAsync(new{op="status"});
var status=value.Deserialize<ManagedStatus>(new JsonSerializerOptions(JsonSerializerDefaults.Web)) ?? throw new InvalidOperationException("Agent 状态无效。");
rows=[new ManagedAgent(status.Id,true,DateTimeOffset.UtcNow.ToUnixTimeSeconds(),status)];
}else rows=await AgentManagementApi.ListAsync(Options(),lifetime.Token);
if(local!=LocalMode||path!=ConfigPath||source!=server())return;
listedSource=SourceKey();
var discovered=DiscoveredDevices.ToArray();var cursor=logCursor;var instance=logInstance;var text=RemoteLogText;
Agents.Clear();foreach(var row in rows)Agents.Add(row);
var chosen=Agents.FirstOrDefault(r=>r.Id==selected) ?? Agents.FirstOrDefault(r=>r.Online) ?? Agents.FirstOrDefault();
// Preserve log cursor and draft configuration during periodic metadata refreshes.
SelectedAgent=chosen;
if(selected==chosen?.Id){DiscoveredDevices.Clear();foreach(var item in discovered)DiscoveredDevices.Add(item);logCursor=cursor;logInstance=instance;RemoteLogText=text;}
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selectedDevice) ?? AgentDevices.FirstOrDefault();
Notice=$"{rows.Length} 个 Agent · {rows.Count(r=>r.Online)} 个在线";lastError=null;
}
[RelayCommand]private Task RefreshAgentsAsync()=>Guard(RefreshCoreAsync);
[RelayCommand(CanExecute=nameof(CanManage))]private Task LoadConfigAsync()=>Guard(async()=>{
var value=await CallAsync(new{op="config_get"});ConfigJson=JsonSerializer.Serialize(value,new JsonSerializerOptions{WriteIndented=true});Notice="已读取配置,凭据不在配置中。";
});
private Task UpdateUsbPolicy(bool? enabled)=>Guard(async()=>{
var value=await CallAsync(new{op="config_get"});
var config=System.Text.Json.Nodes.JsonNode.Parse(value.GetRawText())!.AsObject();
var expected_config=config.DeepClone();
if(enabled.HasValue)config["auto_register_usb"]=enabled.Value;
else {
var serial=SelectedDiscoveredDevice?.Serial ?? throw new InvalidOperationException("请先发现并选择需要取消忽略的设备。");
var ignored=config["ignored_usb_serials"]?.AsArray() ?? new System.Text.Json.Nodes.JsonArray();
config["ignored_usb_serials"]=new System.Text.Json.Nodes.JsonArray(ignored.Where(n=>n?.GetValue<string>()!=serial).Select(n=>n?.DeepClone()).ToArray());
}
await CallAsync(new{op="config_set",config,expected_config});ConfigJson=config.ToJsonString(new JsonSerializerOptions{WriteIndented=true});
await RefreshCoreAsync();Notice=enabled.HasValue?(enabled.Value?"已开启真实 USB 自动注册。":"已关闭自动注册,已有设备保留。 "):"已取消该设备的忽略记录;开启自动注册后将重新检查。";
});
[RelayCommand(CanExecute=nameof(CanManage))]private Task EnableAutoUsbAsync()=>UpdateUsbPolicy(true);
[RelayCommand(CanExecute=nameof(CanManage))]private Task DisableAutoUsbAsync()=>UpdateUsbPolicy(false);
[RelayCommand(CanExecute=nameof(CanManage))]private Task UnignoreUsbAsync()=>UpdateUsbPolicy(null);
[RelayCommand(CanExecute=nameof(CanManage))]private Task SaveConfigAsync()=>Guard(async()=>{
using var doc=JsonDocument.Parse(ConfigJson);await CallAsync(new{op="config_set",config=doc.RootElement});await RefreshCoreAsync();Notice="配置已持久化并应用。受影响设备将重建连接。";
});
[RelayCommand(CanExecute=nameof(CanManage))]private Task AddDeviceAsync()=>Guard(async()=>{
if(string.IsNullOrWhiteSpace(Target)==string.IsNullOrWhiteSpace(AdbSerial))throw new InvalidOperationException("手机地址与 ADB 序列号必须填写其中一项。");
await CallAsync(new{op="device_add",device=new{id=DeviceId.Trim(),target=string.IsNullOrWhiteSpace(Target)?null:Target.Trim(),adb_serial=string.IsNullOrWhiteSpace(AdbSerial)?null:AdbSerial.Trim(),adb_server=string.IsNullOrWhiteSpace(AdbServer)?null:AdbServer.Trim(),device_port=5555,enabled=true}});
await RefreshCoreAsync();Notice="手机已添加并启动连接。";
});
private Task DeviceOperation(string operation,bool? enabled=null)=>Guard(async()=>{
var id=SelectedManagedDevice?.Id ?? throw new InvalidOperationException("请选择手机。");
await CallAsync(enabled.HasValue?new{op=operation,id,enabled=enabled.Value}:(object)new{op=operation,id});await RefreshCoreAsync();
});
[RelayCommand(CanExecute=nameof(CanDevice))]private Task RemoveDeviceAsync()=>DeviceOperation("device_remove");
[RelayCommand(CanExecute=nameof(CanDevice))]private Task EnableDeviceAsync()=>DeviceOperation("device_enable",true);
[RelayCommand(CanExecute=nameof(CanDevice))]private Task DisableDeviceAsync()=>DeviceOperation("device_enable",false);
private async Task LogsCoreAsync()
{
var page=await CallAsync(new{op="logs",after=logCursor,limit=50});var instance=page.GetProperty("instance").GetString() ?? "";
if(logInstance.Length>0&&instance!=logInstance){logCursor=0;RemoteLogText="";logInstance=instance;return;}
logInstance=instance;logCursor=page.GetProperty("next").GetInt64();
foreach(var entry in page.GetProperty("entries").EnumerateArray())RemoteLogText+=Redact($"{entry.GetProperty("time")} {entry.GetProperty("level")} {entry.GetProperty("message").GetString()}\n");
if(RemoteLogText.Length>100000)RemoteLogText=RemoteLogText[^100000..];
}
[RelayCommand(CanExecute=nameof(CanManage))]private Task ReadLogsAsync()=>Guard(LogsCoreAsync);
[RelayCommand(CanExecute=nameof(CanRestart))]private Task RestartAgentAsync()=>Guard(async()=>{await CallAsync(new{op="restart"});Notice="监督进程将重启 Agent,手机连接会短暂中断。";});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InitializeLocalAsync()=>Guard(async()=>{
if(File.Exists(ConfigPath))throw new InvalidOperationException("本机配置已存在,请读取后修改。");
using var doc=JsonDocument.Parse(ConfigJson);var root=doc.RootElement;
var args=new List<string>{"--json","--config",ConfigPath,"--server",root.GetProperty("server").GetString()!,"init","--id",root.GetProperty("id").GetString()!,"--name",root.GetProperty("name").GetString()!};
// Origin is a global CLI option and must precede the subcommand.
if(root.TryGetProperty("connect_address",out var origin)&&origin.ValueKind==JsonValueKind.String)args.InsertRange(5,["--connect-address",origin.GetString()!]);
if(OperatingSystem.IsLinux())Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(ConfigPath))!,UnixFileMode.UserRead|UnixFileMode.UserWrite|UnixFileMode.UserExecute);
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl"),args);info.Environment["ADS_AGENT_TOKEN"]=EnrollmentToken;
var result=await ProcessTools.RunAsync(info,lifetime.Token);if(result.ExitCode!=0)throw new InvalidOperationException(result.Error);
EnrollmentToken="";Notice="本机配置已初始化,可启动后台 Agent 后应用设备配置。";
});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task StartLocalAsync()=>Guard(async()=>{
if(!File.Exists(ConfigPath))throw new InvalidOperationException("请先导入 agent.env 并初始化本机配置,再启动 Agent。");
try { await LocalRequestAsync(new{op="status"});Notice="本机 Agent 已在运行。";return; } catch(InvalidOperationException){}
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-agent"),"ads-agent"),["--quiet","--supervise","--config",ConfigPath]);
info.RedirectStandardOutput=false;info.RedirectStandardError=false;info.StandardOutputEncoding=null;info.StandardErrorEncoding=null;
using var process=Process.Start(info) ?? throw new InvalidOperationException("Agent 启动失败。");
await Task.Delay(700,lifetime.Token);await RefreshCoreAsync();Notice="后台 Agent 已启动,退出托盘不会停止它。";
});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InstallServiceAsync()=>Guard(async()=>{
if(OperatingSystem.IsLinux()) {
var start=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl"),new[]{"--config",ConfigPath,"service","install"});
var result=await ProcessTools.RunAsync(start,lifetime.Token);
if(result.ExitCode!=0)throw new InvalidOperationException(result.Error);
await RefreshCoreAsync();Notice="已安装用户级 systemd 服务;无登录开机运行需启用该用户的 linger。";return;
}
if(!OperatingSystem.IsWindows())throw new InvalidOperationException("此平台请手动运行 Agent。");
var info=new ProcessStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl")){UseShellExecute=true,Verb="runas",WindowStyle=ProcessWindowStyle.Hidden};
foreach(var value in new[]{"--config",ConfigPath,"service","install"})info.ArgumentList.Add(value);
using var process=Process.Start(info) ?? throw new InvalidOperationException("安装命令无法启动。");await process.WaitForExitAsync(lifetime.Token);
if(process.ExitCode!=0)throw new InvalidOperationException("服务安装失败,请在管理员终端使用 adsctl 检查错误。");
await RefreshCoreAsync();Notice="已配置无界面开机启动。";
});
private async Task PollAsync()
{
if(polling||disposed||IsBusy||!AutoRefresh||(!LocalMode&&AdminToken.Length<32))return;polling=true;IsBusy=true;
try { await RefreshCoreAsync();if(FollowLogs&&SelectedAgent?.Online==true)await LogsCoreAsync(); }
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
catch(Exception error){var message=Redact(error.Message);Notice=message;if(message!=lastError){log("[Agent管理] "+message);lastError=message;}}
finally{polling=false;IsBusy=false;}
}
public void Dispose(){if(disposed)return;disposed=true;timer.Stop();lifetime.Cancel();lifetime.Dispose();}
}