MdpApiPushExecutor.cs 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Net.Http.Headers;
  2. using System.Text;
  3. using System.Text.Json;
  4. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
  6. /// <summary>
  7. /// 出站回写(HTTP):按 payload 调第三方写接口。批量扫描由 <see cref="MdpTargetPushDispatcher"/> 负责。
  8. /// </summary>
  9. public sealed class MdpApiPushExecutor : IMdpTargetPushExecutor, ITransient
  10. {
  11. private readonly IHttpClientFactory _httpClientFactory;
  12. public MdpApiPushExecutor(IHttpClientFactory httpClientFactory)
  13. {
  14. _httpClientFactory = httpClientFactory;
  15. }
  16. public string SupportedType => "API";
  17. public async Task<MdpPushResult> PushAsync(MdpSource source, MdpOutbox item, CancellationToken ct = default)
  18. {
  19. if (source == null || string.IsNullOrWhiteSpace(source.ApiBaseUrl))
  20. return MdpPushResult.Fail($"目标源 {item.TargetSourceCode} 未配置 API");
  21. using var payloadDoc = JsonDocument.Parse(string.IsNullOrWhiteSpace(item.PayloadJson) ? "{}" : item.PayloadJson!);
  22. var root = payloadDoc.RootElement;
  23. var path = root.TryGetProperty("path", out var p) ? p.GetString() : $"/outbox/{item.ActionCode}";
  24. var method = root.TryGetProperty("method", out var m) ? (m.GetString() ?? "POST") : "POST";
  25. var bodyEl = root.TryGetProperty("body", out var b) ? b : root;
  26. var client = _httpClientFactory.CreateClient("MdpApiPush");
  27. client.Timeout = TimeSpan.FromSeconds(60);
  28. var url = source.ApiBaseUrl!.TrimEnd('/') + (path!.StartsWith('/') ? path : "/" + path);
  29. using var request = new HttpRequestMessage(new HttpMethod(method), url);
  30. ApplyAuth(request, source);
  31. request.Content = new StringContent(bodyEl.GetRawText(), Encoding.UTF8, "application/json");
  32. using var response = await client.SendAsync(request, ct);
  33. var respBody = await response.Content.ReadAsStringAsync(ct);
  34. if (response.IsSuccessStatusCode)
  35. return MdpPushResult.Ok(1, Truncate(respBody, 4000));
  36. return MdpPushResult.Fail($"HTTP {(int)response.StatusCode}", Truncate(respBody, 4000));
  37. }
  38. private static void ApplyAuth(HttpRequestMessage request, MdpSource source)
  39. {
  40. var authType = (source.ApiAuthType ?? "NONE").Trim().ToUpperInvariant();
  41. if (authType is "NONE" or "") return;
  42. Dictionary<string, string>? cfg = null;
  43. if (!string.IsNullOrWhiteSpace(source.ApiAuthConfig))
  44. {
  45. try { cfg = JsonSerializer.Deserialize<Dictionary<string, string>>(source.ApiAuthConfig!); }
  46. catch { /* ignore */ }
  47. }
  48. cfg ??= new Dictionary<string, string>();
  49. if ((authType is "BEARER" or "TOKEN") && (cfg.TryGetValue("token", out var token) || cfg.TryGetValue("access_token", out token)))
  50. request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  51. else if (authType == "BASIC" && cfg.TryGetValue("username", out var user) && cfg.TryGetValue("password", out var pwd))
  52. request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{pwd}")));
  53. else if (authType == "APIKEY")
  54. {
  55. var header = cfg.GetValueOrDefault("header") ?? "X-API-Key";
  56. if (cfg.TryGetValue("apiKey", out var key) || cfg.TryGetValue("key", out key))
  57. request.Headers.TryAddWithoutValidation(header, key);
  58. }
  59. }
  60. private static string? Truncate(string? s, int max) =>
  61. string.IsNullOrEmpty(s) ? s : (s.Length <= max ? s : s[..max]);
  62. }