ServerApiService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 async Task<ApiCallResult<RemoteApplyTaskResponse>> ApplyInterfaceConfigAsync(string baseAddress, string password, string localIPv4, RemoteInterfaceConfig input, CancellationToken cancellationToken = default)
  157. {
  158. try
  159. {
  160. using var client = CreateClient(baseAddress, password, localIPv4);
  161. using var response = await client.PostAsJsonAsync("/api/network/apply", input, _jsonOptions, cancellationToken);
  162. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  163. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteApplyTaskResponse>>(stream, _jsonOptions, cancellationToken);
  164. return new ApiCallResult<RemoteApplyTaskResponse>
  165. {
  166. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  167. StatusCode = (int)response.StatusCode,
  168. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "配置任务已提交" : $"提交失败,HTTP 状态码 {(int)response.StatusCode}。"),
  169. Data = wrapper?.Data,
  170. };
  171. }
  172. catch (Exception ex)
  173. {
  174. return new ApiCallResult<RemoteApplyTaskResponse>
  175. {
  176. Success = false,
  177. Message = ex.Message,
  178. };
  179. }
  180. }
  181. public async Task<ApiCallResult<RemoteTaskResult>> GetTaskAsync(string baseAddress, string password, string localIPv4, string taskId, CancellationToken cancellationToken = default)
  182. {
  183. try
  184. {
  185. using var client = CreateClient(baseAddress, password, localIPv4);
  186. using var response = await client.GetAsync($"/api/tasks/{Uri.EscapeDataString(taskId)}", cancellationToken);
  187. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  188. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteTaskResult>>(stream, _jsonOptions, cancellationToken);
  189. return new ApiCallResult<RemoteTaskResult>
  190. {
  191. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  192. StatusCode = (int)response.StatusCode,
  193. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "成功" : $"任务查询失败,HTTP 状态码 {(int)response.StatusCode}。"),
  194. Data = wrapper?.Data,
  195. };
  196. }
  197. catch (Exception ex)
  198. {
  199. return new ApiCallResult<RemoteTaskResult>
  200. {
  201. Success = false,
  202. Message = ex.Message,
  203. };
  204. }
  205. }
  206. public async Task<ApiCallResult<RemoteApplyTaskResponse>> ConfirmApplyTaskAsync(string baseAddress, string password, string localIPv4, string taskId, CancellationToken cancellationToken = default)
  207. {
  208. try
  209. {
  210. using var client = CreateClient(baseAddress, password, localIPv4);
  211. using var response = await client.PostAsJsonAsync("/api/network/apply/confirm", new { task_id = taskId }, _jsonOptions, cancellationToken);
  212. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  213. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteApplyTaskResponse>>(stream, _jsonOptions, cancellationToken);
  214. return new ApiCallResult<RemoteApplyTaskResponse>
  215. {
  216. Success = response.IsSuccessStatusCode,
  217. StatusCode = (int)response.StatusCode,
  218. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "已确认保留配置" : $"确认失败,HTTP 状态码 {(int)response.StatusCode}。"),
  219. Data = wrapper?.Data,
  220. };
  221. }
  222. catch (Exception ex)
  223. {
  224. return new ApiCallResult<RemoteApplyTaskResponse>
  225. {
  226. Success = false,
  227. Message = ex.Message,
  228. };
  229. }
  230. }
  231. public async Task<ApiCallResult<RemoteApplyTaskResponse>> CancelApplyTaskAsync(string baseAddress, string password, string localIPv4, string taskId, CancellationToken cancellationToken = default)
  232. {
  233. try
  234. {
  235. using var client = CreateClient(baseAddress, password, localIPv4);
  236. using var response = await client.PostAsJsonAsync("/api/network/apply/cancel", new { task_id = taskId }, _jsonOptions, cancellationToken);
  237. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  238. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteApplyTaskResponse>>(stream, _jsonOptions, cancellationToken);
  239. return new ApiCallResult<RemoteApplyTaskResponse>
  240. {
  241. Success = response.IsSuccessStatusCode,
  242. StatusCode = (int)response.StatusCode,
  243. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "已取消保留配置" : $"取消失败,HTTP 状态码 {(int)response.StatusCode}。"),
  244. Data = wrapper?.Data,
  245. };
  246. }
  247. catch (Exception ex)
  248. {
  249. return new ApiCallResult<RemoteApplyTaskResponse>
  250. {
  251. Success = false,
  252. Message = ex.Message,
  253. };
  254. }
  255. }
  256. public Task<ApiCallResult<RemoteSystemActionResponse>> RebootAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  257. {
  258. return PostSystemActionAsync(baseAddress, password, localIPv4, "/api/system/reboot", cancellationToken);
  259. }
  260. public Task<ApiCallResult<RemoteSystemActionResponse>> ShutdownAsync(string baseAddress, string password, string localIPv4, CancellationToken cancellationToken = default)
  261. {
  262. return PostSystemActionAsync(baseAddress, password, localIPv4, "/api/system/shutdown", cancellationToken);
  263. }
  264. private HttpClient CreateClient(string baseAddress, string password, string localIPv4)
  265. {
  266. var handler = new SocketsHttpHandler();
  267. if (!string.IsNullOrWhiteSpace(localIPv4))
  268. {
  269. handler.ConnectCallback = async (context, token) =>
  270. {
  271. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  272. socket.Bind(new IPEndPoint(IPAddress.Parse(localIPv4), 0));
  273. await socket.ConnectAsync(context.DnsEndPoint, token);
  274. return new NetworkStream(socket, ownsSocket: true);
  275. };
  276. }
  277. var client = new HttpClient(handler) { BaseAddress = new Uri(baseAddress), Timeout = TimeSpan.FromSeconds(5) };
  278. client.DefaultRequestHeaders.Add("X-Admin-Password", password);
  279. return client;
  280. }
  281. private async Task<ApiCallResult<RemoteSystemActionResponse>> PostSystemActionAsync(string baseAddress, string password, string localIPv4, string path, CancellationToken cancellationToken)
  282. {
  283. try
  284. {
  285. using var client = CreateClient(baseAddress, password, localIPv4);
  286. using var response = await client.PostAsync(path, content: null, cancellationToken);
  287. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
  288. var wrapper = await JsonSerializer.DeserializeAsync<ApiEnvelope<RemoteSystemActionResponse>>(stream, _jsonOptions, cancellationToken);
  289. return new ApiCallResult<RemoteSystemActionResponse>
  290. {
  291. Success = response.IsSuccessStatusCode && wrapper?.Data is not null,
  292. StatusCode = (int)response.StatusCode,
  293. Message = wrapper?.Message ?? (response.IsSuccessStatusCode ? "系统任务已提交" : $"提交失败,HTTP 状态码 {(int)response.StatusCode}。"),
  294. Data = wrapper?.Data,
  295. };
  296. }
  297. catch (Exception ex)
  298. {
  299. return new ApiCallResult<RemoteSystemActionResponse>
  300. {
  301. Success = false,
  302. Message = ex.Message,
  303. };
  304. }
  305. }
  306. private sealed class ApiEnvelope<T>
  307. {
  308. public int Code { get; set; }
  309. public string Message { get; set; } = string.Empty;
  310. public T? Data { get; set; }
  311. }
  312. }