Files
AndroidDeviceStreaming/desktop/Ads.Desktop/AgentManagement.cs
T

58 lines
4.0 KiB
C#

using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Ads.Desktop;
public sealed record DiscoveredDevice(string Serial,string State,string Details,bool Configured) {
public string Description=>$"{Serial} · {State} · {(Configured ? "已添加" : "未添加")} · {Details}";
}
public sealed record ManagedDevice(
string Id, string? Target, [property:JsonPropertyName("adb_serial")] string? AdbSerial,
[property:JsonPropertyName("adb_server")] string? AdbServer,
[property:JsonPropertyName("device_port")] int DevicePort, bool Enabled, bool Connected,
[property:JsonPropertyName("last_error")] string? LastError)
{
public string Description => $"{Id} · {(Enabled ? Connected ? LastError==null ? "已注册" : "转发异常:"+LastError : LastError==null ? "等待注册" : "未就绪:"+LastError : "已停用")} · {Target ?? AdbSerial}";
}
public sealed record ManagedStatus(string Id, string Name, string Hostname, string Os, string Arch, string Version, int Pid,
[property:JsonPropertyName("uptime_seconds")] long UptimeSeconds, bool Supervised, long Revision, string Instance, ManagedDevice[] Devices);
public sealed record ManagedAgent(string Id, bool Online, [property:JsonPropertyName("last_seen")] long LastSeen, ManagedStatus Status)
{
public string Description => $"{(string.IsNullOrWhiteSpace(Status.Name) ? Id : Status.Name)} · {(Online ? "在线" : "离线")} · {Status.Os} · {Status.Devices.Length} 台手机";
public string Details => $"{Id} · {Status.Hostname} · {Status.Os}/{Status.Arch} · v{Status.Version} · PID {Status.Pid} · 配置版本 {Status.Revision}";
}
public sealed record ManagementResponse(bool Ok, JsonElement? Data, string? Error)
{
public JsonElement Value() => Ok && Data.HasValue ? Data.Value : throw new InvalidOperationException(Error ?? "Agent 管理请求失败。");
}
public static class AgentManagementApi
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private static Uri UriFor(RelayOptions options, string endpoint) => new UriBuilder(options.DevicesUri) {
Path = options.BaseUri.AbsolutePath.TrimEnd('/') + endpoint
}.Uri;
public static async Task<ManagedAgent[]> ListAsync(RelayOptions options, CancellationToken cancellation)
{
using var http = RelayApi.CreateClient(options);
using var request = new HttpRequestMessage(HttpMethod.Get, UriFor(options,"/v3/agents"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",options.Token);
using var response = await http.SendAsync(request,cancellation); Check(response);
return await response.Content.ReadFromJsonAsync<ManagedAgent[]>(Json,cancellation) ?? [];
}
public static async Task<JsonElement> CallAsync(RelayOptions options, string agent, object operation, CancellationToken cancellation)
{
using var http = RelayApi.CreateClient(options); http.Timeout=TimeSpan.FromSeconds(20);
var uri = new UriBuilder(UriFor(options,"/v3/rpc")) { Query="agent="+Uri.EscapeDataString(agent) }.Uri;
using var request = new HttpRequestMessage(HttpMethod.Post,uri) { Content=JsonContent.Create(operation) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",options.Token);
using var response = await http.SendAsync(request,cancellation); Check(response);
return (await response.Content.ReadFromJsonAsync<ManagementResponse>(Json,cancellation) ?? throw new InvalidOperationException("管理响应为空。")).Value();
}
private static void Check(HttpResponseMessage response)
{
if (response.StatusCode==System.Net.HttpStatusCode.Unauthorized) throw new InvalidOperationException("管理员凭据无效,需要 admin.env;手机连接令牌不具有管理权限。");
if (response.StatusCode==System.Net.HttpStatusCode.ServiceUnavailable) throw new InvalidOperationException("控制中心尚未配置 ADS_ADMIN_TOKEN。");
response.EnsureSuccessStatusCode();
}
}