using System.Net.Http.Headers; using System.Text; using System.Text.Json; using Admin.NET.Plugin.AiDOP.Entity.DataPlatform; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Executors; /// /// 出站回写(HTTP):按 payload 调第三方写接口。批量扫描由 负责。 /// public sealed class MdpApiPushExecutor : IMdpTargetPushExecutor, ITransient { private readonly IHttpClientFactory _httpClientFactory; public MdpApiPushExecutor(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public string SupportedType => "API"; public async Task PushAsync(MdpSource source, MdpOutbox item, CancellationToken ct = default) { if (source == null || string.IsNullOrWhiteSpace(source.ApiBaseUrl)) return MdpPushResult.Fail($"目标源 {item.TargetSourceCode} 未配置 API"); using var payloadDoc = JsonDocument.Parse(string.IsNullOrWhiteSpace(item.PayloadJson) ? "{}" : item.PayloadJson!); var root = payloadDoc.RootElement; var path = root.TryGetProperty("path", out var p) ? p.GetString() : $"/outbox/{item.ActionCode}"; var method = root.TryGetProperty("method", out var m) ? (m.GetString() ?? "POST") : "POST"; var bodyEl = root.TryGetProperty("body", out var b) ? b : root; var client = _httpClientFactory.CreateClient("MdpApiPush"); client.Timeout = TimeSpan.FromSeconds(60); var url = source.ApiBaseUrl!.TrimEnd('/') + (path!.StartsWith('/') ? path : "/" + path); using var request = new HttpRequestMessage(new HttpMethod(method), url); ApplyAuth(request, source); request.Content = new StringContent(bodyEl.GetRawText(), Encoding.UTF8, "application/json"); using var response = await client.SendAsync(request, ct); var respBody = await response.Content.ReadAsStringAsync(ct); if (response.IsSuccessStatusCode) return MdpPushResult.Ok(1, Truncate(respBody, 4000)); return MdpPushResult.Fail($"HTTP {(int)response.StatusCode}", Truncate(respBody, 4000)); } private static void ApplyAuth(HttpRequestMessage request, MdpSource source) { var authType = (source.ApiAuthType ?? "NONE").Trim().ToUpperInvariant(); if (authType is "NONE" or "") return; Dictionary? cfg = null; if (!string.IsNullOrWhiteSpace(source.ApiAuthConfig)) { try { cfg = JsonSerializer.Deserialize>(source.ApiAuthConfig!); } catch { /* ignore */ } } cfg ??= new Dictionary(); if ((authType is "BEARER" or "TOKEN") && (cfg.TryGetValue("token", out var token) || cfg.TryGetValue("access_token", out token))) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); else if (authType == "BASIC" && cfg.TryGetValue("username", out var user) && cfg.TryGetValue("password", out var pwd)) request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{user}:{pwd}"))); else if (authType == "APIKEY") { var header = cfg.GetValueOrDefault("header") ?? "X-API-Key"; if (cfg.TryGetValue("apiKey", out var key) || cfg.TryGetValue("key", out key)) request.Headers.TryAddWithoutValidation(header, key); } } private static string? Truncate(string? s, int max) => string.IsNullOrEmpty(s) ? s : (s.Length <= max ? s : s[..max]); }