ServerApiService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. using System.Net;
  2. using System.Net.Http;
  3. using System.Net.Http.Json;
  4. using System.Net.Sockets;
  5. using System.Text.Json;
  6. using NetworkTool.Client.Models;
  7. namespace NetworkTool.Client.Services;
  8. public sealed class ServerApiService
  9. {
  10. private readonly JsonSerializerOptions _jsonOptions = new()
  11. {
  12. PropertyNameCaseInsensitive = true,
  13. };
  14. public async Task<HealthCheckResult> CheckHealthAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  15. {
  16. try
  17. {
  18. using var handler = new SocketsHttpHandler();
  19. if (!string.IsNullOrWhiteSpace(localIPv4))
  20. {
  21. handler.ConnectCallback = async (context, token) =>
  22. {
  23. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  24. socket.Bind(new IPEndPoint(IPAddress.Parse(localIPv4), 0));
  25. await socket.ConnectAsync(context.DnsEndPoint, token);
  26. return new NetworkStream(socket, ownsSocket: true);
  27. };
  28. }
  29. using var client = new HttpClient(handler) { BaseAddress = new Uri(baseAddress), Timeout = TimeSpan.FromSeconds(5) };
  30. client.DefaultRequestHeaders.Add("X-Admin-Password", password);
  31. using var response = await client.GetAsync("/api/health", cancellationToken);
  32. return new HealthCheckResult
  33. {
  34. Success = response.IsSuccessStatusCode,
  35. StatusCode = (int)response.StatusCode,
  36. Message = response.IsSuccessStatusCode
  37. ? "HTTP 健康检查通过。"
  38. : $"HTTP 健康检查返回状态码 {(int)response.StatusCode}。",
  39. };
  40. }
  41. catch (Exception ex)
  42. {
  43. return new HealthCheckResult
  44. {
  45. Success = false,
  46. StatusCode = null,
  47. Message = ex.Message,
  48. };
  49. }
  50. }
  51. public async Task<RemoteDeviceInfo?> GetDeviceInfoAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  52. {
  53. try
  54. {
  55. using var client = CreateClient(baseAddress, password, localIPv4);
  56. using var response = await client.GetAsync("/api/device/info", cancellationToken);
  57. if (!response.IsSuccessStatusCode)
  58. {
  59. return null;
  60. }
  61. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  62. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteDeviceInfo>>(stream, _jsonOptions, cancellationToken);
  63. return wrapper?.Data;
  64. }
  65. catch
  66. {
  67. return null;
  68. }
  69. }
  70. public async Task<RemoteInterfacesInfo?> GetInterfacesAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  71. {
  72. try
  73. {
  74. using var client = CreateClient(baseAddress, password, localIPv4);
  75. using var response = await client.GetAsync("/api/network/interfaces", cancellationToken);
  76. if (!response.IsSuccessStatusCode)
  77. {
  78. return null;
  79. }
  80. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  81. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteInterfacesInfo>>(stream, _jsonOptions, cancellationToken);
  82. return wrapper?.Data;
  83. }
  84. catch
  85. {
  86. return null;
  87. }
  88. }
  89. public async Task<ApiCallResult<RemoteInterfaceConfig>> GetInterfaceConfigAsync(string baseAddress, string password, string localIPv4, string interfaceName, CancellationToken cancellationToken = default)
  90. {
  91. try
  92. {
  93. using var client = CreateClient(baseAddress, password, localIPv4);
  94. using var response = await client.GetAsync($"/api/network/config?interface={Uri.EscapeDataString(interfaceName)}", cancellationToken);
  95. if (!response.IsSuccessStatusCode)
  96. {
  97. return new ApiCallResult<RemoteInterfaceConfig>
  98. {
  99. Success = false,
  100. StatusCode = (int)response.StatusCode,
  101. Message = $"读取接口配置失败,HTTP 状态码 {(int)response.StatusCode}。",
  102. };
  103. }
  104. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  105. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteInterfaceConfig>>(stream, _jsonOptions, cancellationToken);
  106. if (wrapper?.Data is null)
  107. {
  108. return new ApiCallResult<RemoteInterfaceConfig>
  109. {
  110. Success = false,
  111. Message = "接口配置返回内容为空。",
  112. };
  113. }
  114. return new ApiCallResult<RemoteInterfaceConfig>
  115. {
  116. Success = true,
  117. StatusCode = (int)response.StatusCode,
  118. Message = "成功",
  119. Data = wrapper.Data,
  120. };
  121. }
  122. catch (Exception ex)
  123. {
  124. return new ApiCallResult<RemoteInterfaceConfig>
  125. {
  126. Success = false,
  127. Message = ex.Message,
  128. };
  129. }
  130. }
  131. public async Task<ApiCallResult<RemoteValidateResult>> ValidateInterfaceConfigAsync(string baseAddress, string password, string localIPv4, RemoteInterfaceConfig input, CancellationToken cancellationToken = default)
  132. {
  133. try
  134. {
  135. using var client = CreateClient(baseAddress, password, localIPv4);
  136. using var response = await client.PostAsJsonAsync("/api/network/validate", input, _jsonOptions, cancellationToken);
  137. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  138. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteValidateResult>>(stream, _jsonOptions, cancellationToken);
  139. return new ApiCallResult<RemoteValidateResult>
  140. {
  141. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  142. StatusCode = (int)response.StatusCode,
  143. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "校验通过" : $"校验失败,HTTP 状态码 {(int)response.StatusCode}。"),
  144. Data = wrapper?.Data,
  145. };
  146. }
  147. catch (Exception ex)
  148. {
  149. return new ApiCallResult<RemoteValidateResult>
  150. {
  151. Success = false,
  152. Message = ex.Message,
  153. };
  154. }
  155. }
  156. public Task<ApiCallResult<RemoteValidateResult>> ValidateInterfaceConfigsAsync(string baseAddress, string password, string localIPv4, IReadOnlyList<RemoteInterfaceConfig> inputs, CancellationToken cancellationToken = default)
  157. {
  158. return ValidateInterfaceConfigsAsync(baseAddress, password, localIPv4, new RemoteInterfaceConfigsRequest { Configs = inputs }, cancellationToken);
  159. }
  160. private async Task<ApiCallResult<RemoteValidateResult>> ValidateInterfaceConfigsAsync(string baseAddress, string password, string localIPv4, RemoteInterfaceConfigsRequest input, CancellationToken cancellationToken = default)
  161. {
  162. try
  163. {
  164. using var client = CreateClient(baseAddress, password, localIPv4);
  165. using var response = await client.PostAsJsonAsync("/api/network/validate-all", input, _jsonOptions, cancellationToken);
  166. var content = await response.Content.ReadAsStringAsync(cancellationToken);
  167. var wrapper = DeserializeEnvelope<RemoteValidateResult>(content);
  168. if (wrapper is null)
  169. {
  170. return CreateInvalidJsonResult<RemoteValidateResult>(response.StatusCode, content, "批量校验");
  171. }
  172. return new ApiCallResult<RemoteValidateResult>
  173. {
  174. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  175. StatusCode = (int)response.StatusCode,
  176. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "校验通过" : $"校验失败,HTTP 状态码 {(int)response.StatusCode}。"),
  177. Data = wrapper?.Data,
  178. };
  179. }
  180. catch (Exception ex)
  181. {
  182. return new ApiCallResult<RemoteValidateResult>
  183. {
  184. Success = false,
  185. Message = ex.Message,
  186. };
  187. }
  188. }
  189. public async Task<ApiCallResult<RemoteApplyTaskResponse>> ApplyInterfaceConfigAsync(string baseAddress, string password, string localIPv4, RemoteInterfaceConfig input, CancellationToken cancellationToken = default)
  190. {
  191. try
  192. {
  193. using var client = CreateClient(baseAddress, password, localIPv4);
  194. using var response = await client.PostAsJsonAsync("/api/network/apply", input, _jsonOptions, cancellationToken);
  195. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  196. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteApplyTaskResponse>>(stream, _jsonOptions, cancellationToken);
  197. return new ApiCallResult<RemoteApplyTaskResponse>
  198. {
  199. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  200. StatusCode = (int)response.StatusCode,
  201. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "配置任务已提交" : $"提交失败,HTTP 状态码 {(int)response.StatusCode}。"),
  202. Data = wrapper?.Data,
  203. };
  204. }
  205. catch (Exception ex)
  206. {
  207. return new ApiCallResult<RemoteApplyTaskResponse>
  208. {
  209. Success = false,
  210. Message = ex.Message,
  211. };
  212. }
  213. }
  214. public Task<ApiCallResult<RemoteApplyTaskResponse>> ApplyInterfaceConfigsAsync(string baseAddress, string password, string localIPv4, IReadOnlyList<RemoteInterfaceConfig> inputs, CancellationToken cancellationToken = default)
  215. {
  216. return ApplyInterfaceConfigsAsync(baseAddress, password, localIPv4, new RemoteInterfaceConfigsRequest { Configs = inputs }, cancellationToken);
  217. }
  218. private async Task<ApiCallResult<RemoteApplyTaskResponse>> ApplyInterfaceConfigsAsync(string baseAddress, string password, string localIPv4, RemoteInterfaceConfigsRequest input, CancellationToken cancellationToken = default)
  219. {
  220. try
  221. {
  222. using var client = CreateClient(baseAddress, password, localIPv4);
  223. using var response = await client.PostAsJsonAsync("/api/network/apply-all", input, _jsonOptions, cancellationToken);
  224. var content = await response.Content.ReadAsStringAsync(cancellationToken);
  225. var wrapper = DeserializeEnvelope<RemoteApplyTaskResponse>(content);
  226. if (wrapper is null)
  227. {
  228. return CreateInvalidJsonResult<RemoteApplyTaskResponse>(response.StatusCode, content, "批量应用");
  229. }
  230. return new ApiCallResult<RemoteApplyTaskResponse>
  231. {
  232. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  233. StatusCode = (int)response.StatusCode,
  234. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "配置任务已提交" : $"提交失败,HTTP 状态码 {(int)response.StatusCode}。"),
  235. Data = wrapper?.Data,
  236. };
  237. }
  238. catch (Exception ex)
  239. {
  240. return new ApiCallResult<RemoteApplyTaskResponse>
  241. {
  242. Success = false,
  243. Message = ex.Message,
  244. };
  245. }
  246. }
  247. public async Task<ApiCallResult<RemoteTaskResult>> GetTaskAsync(string baseAddress, string password, string localIPv4, string taskId, CancellationToken cancellationToken = default)
  248. {
  249. try
  250. {
  251. using var client = CreateClient(baseAddress, password, localIPv4);
  252. using var response = await client.GetAsync($"/api/tasks/{Uri.EscapeDataString(taskId)}", cancellationToken);
  253. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  254. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteTaskResult>>(stream, _jsonOptions, cancellationToken);
  255. return new ApiCallResult<RemoteTaskResult>
  256. {
  257. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  258. StatusCode = (int)response.StatusCode,
  259. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "成功" : $"任务查询失败,HTTP 状态码 {(int)response.StatusCode}。"),
  260. Data = wrapper?.Data,
  261. };
  262. }
  263. catch (Exception ex)
  264. {
  265. return new ApiCallResult<RemoteTaskResult>
  266. {
  267. Success = false,
  268. Message = ex.Message,
  269. };
  270. }
  271. }
  272. public async Task<ApiCallResult<RemoteApplyTaskResponse>> ConfirmApplyTaskAsync(string baseAddress, string password, string localIPv4, string taskId, CancellationToken cancellationToken = default)
  273. {
  274. try
  275. {
  276. using var client = CreateClient(baseAddress, password, localIPv4);
  277. using var response = await client.PostAsJsonAsync("/api/network/apply/confirm", new { task_id = taskId }, _jsonOptions, cancellationToken);
  278. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  279. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteApplyTaskResponse>>(stream, _jsonOptions, cancellationToken);
  280. return new ApiCallResult<RemoteApplyTaskResponse>
  281. {
  282. Success = response.IsSuccessStatusCode,
  283. StatusCode = (int)response.StatusCode,
  284. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "已确认保留配置" : $"确认失败,HTTP 状态码 {(int)response.StatusCode}。"),
  285. Data = wrapper?.Data,
  286. };
  287. }
  288. catch (Exception ex)
  289. {
  290. return new ApiCallResult<RemoteApplyTaskResponse>
  291. {
  292. Success = false,
  293. Message = ex.Message,
  294. };
  295. }
  296. }
  297. public async Task<ApiCallResult<RemoteApplyTaskResponse>> CancelApplyTaskAsync(string baseAddress, string password, string localIPv4, string taskId, CancellationToken cancellationToken = default)
  298. {
  299. try
  300. {
  301. using var client = CreateClient(baseAddress, password, localIPv4);
  302. using var response = await client.PostAsJsonAsync("/api/network/apply/cancel", new { task_id = taskId }, _jsonOptions, cancellationToken);
  303. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  304. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteApplyTaskResponse>>(stream, _jsonOptions, cancellationToken);
  305. return new ApiCallResult<RemoteApplyTaskResponse>
  306. {
  307. Success = response.IsSuccessStatusCode,
  308. StatusCode = (int)response.StatusCode,
  309. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "已取消保留配置" : $"取消失败,HTTP 状态码 {(int)response.StatusCode}。"),
  310. Data = wrapper?.Data,
  311. };
  312. }
  313. catch (Exception ex)
  314. {
  315. return new ApiCallResult<RemoteApplyTaskResponse>
  316. {
  317. Success = false,
  318. Message = ex.Message,
  319. };
  320. }
  321. }
  322. public Task<ApiCallResult<RemoteSystemActionResponse>> RebootAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  323. {
  324. return PostSystemActionAsync(baseAddress, password, localIPv4, "/api/system/reboot", cancellationToken);
  325. }
  326. public Task<ApiCallResult<RemoteSystemActionResponse>> ShutdownAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  327. {
  328. return PostSystemActionAsync(baseAddress, password, localIPv4, "/api/system/shutdown", cancellationToken);
  329. }
  330. private HttpClient CreateClient(string baseAddress, string password, string localIPv4)
  331. {
  332. var handler = new SocketsHttpHandler();
  333. if (!string.IsNullOrWhiteSpace(localIPv4))
  334. {
  335. handler.ConnectCallback = async (context, token) =>
  336. {
  337. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  338. socket.Bind(new IPEndPoint(IPAddress.Parse(localIPv4), 0));
  339. await socket.ConnectAsync(context.DnsEndPoint, token);
  340. return new NetworkStream(socket, ownsSocket: true);
  341. };
  342. }
  343. var client = new HttpClient(handler) { BaseAddress = new Uri(baseAddress), Timeout = TimeSpan.FromSeconds(5) };
  344. client.DefaultRequestHeaders.Add("X-Admin-Password", password);
  345. return client;
  346. }
  347. private async Task<ApiCallResult<RemoteSystemActionResponse>> PostSystemActionAsync(string baseAddress, string password, string localIPv4, string path, CancellationToken cancellationToken)
  348. {
  349. try
  350. {
  351. using var client = CreateClient(baseAddress, password, localIPv4);
  352. using var response = await client.PostAsync(path, content: null, cancellationToken);
  353. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  354. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteSystemActionResponse>>(stream, _jsonOptions, cancellationToken);
  355. return new ApiCallResult<RemoteSystemActionResponse>
  356. {
  357. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  358. StatusCode = (int)response.StatusCode,
  359. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "系统任务已提交" : $"提交失败,HTTP 状态码 {(int)response.StatusCode}。"),
  360. Data = wrapper?.Data,
  361. };
  362. }
  363. catch (Exception ex)
  364. {
  365. return new ApiCallResult<RemoteSystemActionResponse>
  366. {
  367. Success = false,
  368. Message = ex.Message,
  369. };
  370. }
  371. }
  372. private sealed class ApiEnvelope<T>
  373. {
  374. public int Code { get; set; }
  375. public string Message { get; set; } = string.Empty;
  376. public T? Data { get; set; }
  377. }
  378. private ApiEnvelope<T>? DeserializeEnvelope<T>(string content)
  379. {
  380. try
  381. {
  382. return JsonSerializer.Deserialize<ApiEnvelope<T>>(content, _jsonOptions);
  383. }
  384. catch (JsonException)
  385. {
  386. return null;
  387. }
  388. }
  389. private static ApiCallResult<T> CreateInvalidJsonResult<T>(HttpStatusCode statusCode, string content, string actionName)
  390. {
  391. var body = string.IsNullOrWhiteSpace(content) ? "响应为空" : content.Trim();
  392. if (body.Length > 160)
  393. {
  394. body = body[..160] + "...";
  395. }
  396. var status = (int)statusCode;
  397. var hint = status == 404
  398. ? $"Linux 端 Server 可能还未更新,不支持{actionName}接口。请重新发布并启动最新 Server。"
  399. : $"Linux 端 Server 返回了无法解析的{actionName}响应。";
  400. return new ApiCallResult<T>
  401. {
  402. Success = false,
  403. StatusCode = status,
  404. Message = $"{hint}HTTP {status}:{body}",
  405. };
  406. }
  407. }