| | | 1 | | using System.Net; |
| | | 2 | | using System.Net.Http.Headers; |
| | | 3 | | using Newtonsoft.Json.Linq; |
| | | 4 | | using Services.ApiServices.ApiSupplierRequestLog; |
| | | 5 | | |
| | | 6 | | namespace Services.ApiServices.MotexApi; |
| | | 7 | | |
| | | 8 | | /// <summary>Bearer-клиент Motex (МоТехС). Токен существует только в памяти текущего процесса.</summary> |
| | | 9 | | public sealed class MotexHttpClient |
| | | 10 | | { |
| | | 11 | | private readonly IHttpClientFactory _factory; |
| | | 12 | | private readonly MotexConfig _config; |
| | 54 | 13 | | private readonly SemaphoreSlim _tokenLock = new(1, 1); |
| | | 14 | | private string? _accessToken; |
| | 54 | 15 | | private DateTimeOffset _expiresAt = DateTimeOffset.MinValue; |
| | | 16 | | private readonly ApiSupplierRequestLogStore? _logs; |
| | | 17 | | |
| | 54 | 18 | | public MotexHttpClient(IHttpClientFactory factory, MotexConfig config, ApiSupplierRequestLogStore? logs = null) |
| | | 19 | | { |
| | 54 | 20 | | _factory = factory; |
| | 54 | 21 | | _config = config; |
| | 54 | 22 | | _logs = logs; |
| | 54 | 23 | | } |
| | | 24 | | |
| | | 25 | | public Task<JToken> GetAsync(string path, IReadOnlyDictionary<string, string?>? query, CancellationToken ct = defaul |
| | 34 | 26 | | => SendAsync(HttpMethod.Get, path, query, null, ct); |
| | | 27 | | |
| | | 28 | | public Task<JToken> PostAsync(string path, JToken body, CancellationToken ct = default) |
| | 12 | 29 | | => SendAsync(HttpMethod.Post, path, null, body, ct); |
| | | 30 | | |
| | | 31 | | private async Task<JToken> SendAsync(HttpMethod method, string path, IReadOnlyDictionary<string, string?>? query, JT |
| | | 32 | | { |
| | 46 | 33 | | var timer = System.Diagnostics.Stopwatch.StartNew(); |
| | | 34 | | HttpResponseMessage response; |
| | | 35 | | try |
| | | 36 | | { |
| | 46 | 37 | | response = await SendAuthorizedAsync(method, path, query, body, false, ct); |
| | 43 | 38 | | if (response.StatusCode == HttpStatusCode.Unauthorized) |
| | | 39 | | { |
| | 1 | 40 | | _accessToken = null; |
| | 1 | 41 | | _expiresAt = DateTimeOffset.MinValue; |
| | 1 | 42 | | response.Dispose(); |
| | 1 | 43 | | response = await SendAuthorizedAsync(method, path, query, body, true, ct); |
| | | 44 | | } |
| | 43 | 45 | | } |
| | 3 | 46 | | catch (Exception ex) |
| | | 47 | | { |
| | 3 | 48 | | _logs?.Add("Motex", method.Method, path, null, timer, body?.ToString(), ex.Message); |
| | 3 | 49 | | throw; |
| | | 50 | | } |
| | | 51 | | |
| | 43 | 52 | | using (response) |
| | | 53 | | { |
| | 43 | 54 | | var text = await response.Content.ReadAsStringAsync(ct); |
| | 43 | 55 | | _logs?.Add("Motex", method.Method, path, (int)response.StatusCode, timer, body?.ToString(), text); |
| | 43 | 56 | | if (!response.IsSuccessStatusCode) |
| | 1 | 57 | | throw new MotexApiException($"МоТехС вернул HTTP {(int)response.StatusCode}.", (int)response.StatusCode, |
| | | 58 | | |
| | 42 | 59 | | return UnwrapEnvelope(text, path); |
| | | 60 | | } |
| | 35 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <summary>Motex оборачивает все ответы в {status, messages, response}; отдаёт наружу только response.</summary> |
| | | 64 | | private static JToken UnwrapEnvelope(string text, string path) |
| | | 65 | | { |
| | | 66 | | JObject envelope; |
| | 136 | 67 | | try { envelope = JObject.Parse(text); } |
| | 0 | 68 | | catch (Exception ex) { throw new MotexApiException("МоТехС вернул невалидный JSON.", requestPath: path, innerExc |
| | | 69 | | |
| | 68 | 70 | | var status = envelope.Value<int?>("status") ?? 200; |
| | 68 | 71 | | if (status != 200) |
| | | 72 | | { |
| | 7 | 73 | | var messages = envelope["messages"]; |
| | 7 | 74 | | var messageText = messages switch |
| | 7 | 75 | | { |
| | 2 | 76 | | JObject obj => obj.Value<string>("errorText") is { Length: > 0 } errorText ? errorText : obj.ToString(Ne |
| | 10 | 77 | | JArray array => string.Join("; ", array.Select(x => x.ToString())), |
| | 0 | 78 | | null => null, |
| | 0 | 79 | | _ => messages.ToString() |
| | 7 | 80 | | }; |
| | 7 | 81 | | throw new MotexApiException( |
| | 7 | 82 | | string.IsNullOrWhiteSpace(messageText) ? $"МоТехС вернул статус {status}." : messageText, |
| | 7 | 83 | | status, path); |
| | | 84 | | } |
| | | 85 | | |
| | 61 | 86 | | return envelope["response"] ?? new JObject(); |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | private async Task<HttpResponseMessage> SendAuthorizedAsync(HttpMethod method, string path, IReadOnlyDictionary<stri |
| | | 90 | | { |
| | 47 | 91 | | var token = await GetTokenAsync(forceRefresh, ct); |
| | 47 | 92 | | var request = new HttpRequestMessage(method, BuildUri(path, query)); |
| | 47 | 93 | | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); |
| | 59 | 94 | | if (body != null) request.Content = new StringContent(body.ToString(), System.Text.Encoding.UTF8, "application/j |
| | 47 | 95 | | return await _factory.CreateClient("MotexApi").SendAsync(request, ct); |
| | 44 | 96 | | } |
| | | 97 | | |
| | | 98 | | private async Task<string> GetTokenAsync(bool forceRefresh, CancellationToken ct) |
| | | 99 | | { |
| | 68 | 100 | | if (!forceRefresh && !string.IsNullOrWhiteSpace(_accessToken) && _expiresAt > DateTimeOffset.UtcNow.AddMinutes(1 |
| | 26 | 101 | | await _tokenLock.WaitAsync(ct); |
| | | 102 | | try |
| | | 103 | | { |
| | 26 | 104 | | if (!forceRefresh && !string.IsNullOrWhiteSpace(_accessToken) && _expiresAt > DateTimeOffset.UtcNow.AddMinut |
| | 26 | 105 | | if (string.IsNullOrWhiteSpace(_config.Login) || string.IsNullOrWhiteSpace(_config.Password)) |
| | 0 | 106 | | throw new MotexApiException("Не настроены Motex:Login и/или Motex:Password."); |
| | | 107 | | |
| | 26 | 108 | | var body = new JObject { ["login"] = _config.Login, ["password"] = _config.Password }; |
| | 26 | 109 | | using var content = new StringContent(body.ToString(), System.Text.Encoding.UTF8, "application/json"); |
| | 26 | 110 | | var timer = System.Diagnostics.Stopwatch.StartNew(); |
| | | 111 | | HttpResponseMessage response; |
| | | 112 | | string text; |
| | | 113 | | try |
| | | 114 | | { |
| | 26 | 115 | | response = await _factory.CreateClient("MotexApi").PostAsync(BuildUri("/api/v1/Auth/login", null), conte |
| | 26 | 116 | | text = await response.Content.ReadAsStringAsync(ct); |
| | 26 | 117 | | } |
| | 0 | 118 | | catch (Exception ex) |
| | | 119 | | { |
| | 0 | 120 | | _logs?.Add("Motex", HttpMethod.Post.Method, "/api/v1/Auth/login", null, timer, body.ToString(), ex.Messa |
| | 0 | 121 | | throw; |
| | | 122 | | } |
| | 26 | 123 | | using (response) |
| | 26 | 124 | | _logs?.Add("Motex", HttpMethod.Post.Method, "/api/v1/Auth/login", (int)response.StatusCode, timer, body. |
| | 26 | 125 | | if (!response.IsSuccessStatusCode) throw new MotexApiException($"Авторизация МоТехС завершилась HTTP {(int)r |
| | | 126 | | |
| | 26 | 127 | | var result = UnwrapEnvelope(text, "/api/v1/Auth/login"); |
| | 26 | 128 | | var token = result.Value<string>("token"); |
| | 26 | 129 | | var expiresIn = result.Value<int?>("expireIn") ?? 3600; |
| | 26 | 130 | | if (string.IsNullOrWhiteSpace(token)) throw new MotexApiException("Ответ авторизации МоТехС не содержит toke |
| | 26 | 131 | | _accessToken = token; |
| | 26 | 132 | | _expiresAt = DateTimeOffset.UtcNow.AddSeconds(Math.Max(60, expiresIn)); |
| | 26 | 133 | | return token; |
| | | 134 | | } |
| | 0 | 135 | | catch (MotexApiException) { throw; } |
| | 0 | 136 | | catch (Exception ex) { throw new MotexApiException("Не удалось авторизоваться в МоТехС.", requestPath: "/api/v1/ |
| | 26 | 137 | | finally { _tokenLock.Release(); } |
| | 47 | 138 | | } |
| | | 139 | | |
| | | 140 | | private Uri BuildUri(string path, IReadOnlyDictionary<string, string?>? query) |
| | | 141 | | { |
| | 73 | 142 | | var builder = new UriBuilder(_config.BaseUrl.TrimEnd('/') + "/" + path.TrimStart('/')); |
| | 73 | 143 | | if (query != null) |
| | 69 | 144 | | builder.Query = string.Join("&", query.Where(x => !string.IsNullOrWhiteSpace(x.Value)).Select(x => $"{Uri.Es |
| | 73 | 145 | | return builder.Uri; |
| | | 146 | | } |
| | | 147 | | } |