using System.Net.Http.Headers; using System.Net.Http.Json; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; namespace Ads.Desktop; public partial class MainViewModel { [ObservableProperty] private RelayNode? selectedRelayNode; [ObservableProperty] private string newRelayId=""; [ObservableProperty] private string newRelayUrl=""; [ObservableProperty] private string newRelayOrigin=""; [ObservableProperty] private int newRelayPriority=100; [ObservableProperty] private bool confirmRelayDelete; private readonly Dictionary missingRelayDevices=new(); [RelayCommand] private Task AddRelayAsync()=>Guard(()=>Exclusive(async()=>{ var id=NewRelayId.Trim(); if(id.Length is <1 or >128 || id.Any(c=>!char.IsAsciiLetterOrDigit(c)&&c!='-'&&c!='_'&&c!='.'))throw new InvalidOperationException("节点 ID 格式无效。"); RelayOptions.ParseBaseUri(NewRelayUrl); if(!string.IsNullOrWhiteSpace(NewRelayOrigin))RelayOptions.ParseOrigin(NewRelayOrigin.Trim()); await MutateRelayAsync(HttpMethod.Post,"/v2/nodes",new{id,url=NewRelayUrl.Trim(),connect_address=NewRelayOrigin.Trim(),priority=NewRelayPriority}); })); [RelayCommand] private Task SetDefaultRelayAsync()=>Guard(()=>Exclusive(()=>MutateRelayAsync(HttpMethod.Post,"/v2/nodes/default",new{id=(SelectedRelayNode??throw new InvalidOperationException("请选择节点。")).Id}))); [RelayCommand] private Task DeleteRelayAsync()=>Guard(()=>Exclusive(async()=>{ if(!ConfirmRelayDelete)throw new InvalidOperationException("请先勾选删除确认。"); var node=SelectedRelayNode??throw new InvalidOperationException("请选择节点。"); await MutateRelayAsync(HttpMethod.Delete,"/v2/nodes/"+Uri.EscapeDataString(node.Id),null);ConfirmRelayDelete=false; })); private async Task MutateRelayAsync(HttpMethod method,string path,object? body) { var options=RelayOptions.Parse(Server,Origin,AgentManager.AdminToken); using var http=RelayApi.CreateClient(options); using var req=new HttpRequestMessage(method,new UriBuilder(options.DevicesUri){Path=options.BaseUri.AbsolutePath.TrimEnd('/')+path}.Uri); req.Headers.Authorization=new AuthenticationHeaderValue("Bearer",options.Token); if(body!=null)req.Content=JsonContent.Create(body); using var res=await http.SendAsync(req,lifetime.Token); if(!res.IsSuccessStatusCode)throw new InvalidOperationException($"节点操作失败 HTTP {(int)res.StatusCode};请检查管理员凭据、节点参数及服务器配置写入权限。"); await RefreshDevicesAsync(false);Notice="中继节点配置已更新。"; } }