| | | 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.ShateMApi; |
| | | 7 | | |
| | | 8 | | /// <summary>Bearer-клиент Shate-M. Токен существует только в памяти текущего процесса.</summary> |
| | | 9 | | public sealed class ShateMHttpClient |
| | | 10 | | { |
| | | 11 | | private readonly IHttpClientFactory _factory; |
| | | 12 | | private readonly ShateMConfig _config; |
| | 61 | 13 | | private readonly SemaphoreSlim _tokenLock = new(1, 1); |
| | | 14 | | private string? _accessToken; |
| | 61 | 15 | | private DateTimeOffset _expiresAt = DateTimeOffset.MinValue; |
| | | 16 | | private readonly ApiSupplierRequestLogStore? _logs; |
| | | 17 | | |
| | 61 | 18 | | public ShateMHttpClient(IHttpClientFactory factory, ShateMConfig config, ApiSupplierRequestLogStore? logs = null) |
| | | 19 | | { |
| | 61 | 20 | | _factory = factory; |
| | 61 | 21 | | _config = config; |
| | 61 | 22 | | _logs = logs; |
| | 61 | 23 | | } |
| | | 24 | | |
| | | 25 | | public Task<JToken> GetAsync(string path, IReadOnlyDictionary<string, string?>? query, CancellationToken ct = defaul |
| | 38 | 26 | | => SendAsync(HttpMethod.Get, path, query, null, ct); |
| | | 27 | | |
| | | 28 | | public Task<JToken> PostAsync(string path, JToken body, CancellationToken ct = default) |
| | 34 | 29 | | => SendAsync(HttpMethod.Post, path, null, body, ct); |
| | | 30 | | |
| | | 31 | | public Task<JToken> PatchAsync(string path, JToken body, CancellationToken ct = default) |
| | 0 | 32 | | => SendAsync(HttpMethod.Patch, path, null, body, ct); |
| | | 33 | | |
| | | 34 | | public Task<JToken> DeleteAsync(string path, CancellationToken ct = default) |
| | 6 | 35 | | => SendAsync(HttpMethod.Delete, path, null, null, ct); |
| | | 36 | | |
| | | 37 | | private async Task<JToken> SendAsync(HttpMethod method, string path, IReadOnlyDictionary<string, string?>? query, JT |
| | | 38 | | { |
| | 78 | 39 | | var timer = System.Diagnostics.Stopwatch.StartNew(); |
| | | 40 | | HttpResponseMessage response; |
| | | 41 | | try |
| | | 42 | | { |
| | 78 | 43 | | response = await SendAuthorizedAsync(method, path, query, body, false, ct); |
| | 74 | 44 | | if (response.StatusCode == HttpStatusCode.Unauthorized) |
| | | 45 | | { |
| | 1 | 46 | | _accessToken = null; |
| | 1 | 47 | | _expiresAt = DateTimeOffset.MinValue; |
| | 1 | 48 | | response.Dispose(); |
| | 1 | 49 | | response = await SendAuthorizedAsync(method, path, query, body, true, ct); |
| | | 50 | | } |
| | 74 | 51 | | } |
| | 4 | 52 | | catch (Exception ex) |
| | | 53 | | { |
| | 4 | 54 | | _logs?.Add("ShateM", method.Method, path, null, timer, body?.ToString(), ex.Message); |
| | 4 | 55 | | throw; |
| | | 56 | | } |
| | | 57 | | |
| | 74 | 58 | | using (response) |
| | | 59 | | { |
| | 74 | 60 | | var text = await response.Content.ReadAsStringAsync(ct); |
| | 74 | 61 | | _logs?.Add("ShateM", method.Method, path, (int)response.StatusCode, timer, body?.ToString(), text); |
| | 74 | 62 | | if (!response.IsSuccessStatusCode) |
| | 6 | 63 | | throw new ShateMApiException($"Шате-М вернул HTTP {(int)response.StatusCode}. {GetErrorDescription(text) |
| | | 64 | | |
| | 68 | 65 | | try { return JToken.Parse(text); } |
| | 0 | 66 | | catch (Exception ex) { throw new ShateMApiException("Шате-М вернул невалидный JSON.", requestPath: path, inn |
| | | 67 | | } |
| | 68 | 68 | | } |
| | | 69 | | |
| | | 70 | | private async Task<HttpResponseMessage> SendAuthorizedAsync(HttpMethod method, string path, IReadOnlyDictionary<stri |
| | | 71 | | { |
| | 79 | 72 | | var token = await GetTokenAsync(forceRefresh, ct); |
| | 75 | 73 | | var request = new HttpRequestMessage(method, BuildUri(path, query)); |
| | 75 | 74 | | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); |
| | 109 | 75 | | if (body != null) request.Content = new StringContent(body.ToString(), System.Text.Encoding.UTF8, "application/j |
| | 75 | 76 | | return await _factory.CreateClient("ShateMApi").SendAsync(request, ct); |
| | 75 | 77 | | } |
| | | 78 | | |
| | | 79 | | private async Task<string> GetTokenAsync(bool forceRefresh, CancellationToken ct) |
| | | 80 | | { |
| | 109 | 81 | | if (!forceRefresh && !string.IsNullOrWhiteSpace(_accessToken) && _expiresAt > DateTimeOffset.UtcNow.AddMinutes(1 |
| | 49 | 82 | | await _tokenLock.WaitAsync(ct); |
| | | 83 | | try |
| | | 84 | | { |
| | 49 | 85 | | if (!forceRefresh && !string.IsNullOrWhiteSpace(_accessToken) && _expiresAt > DateTimeOffset.UtcNow.AddMinut |
| | 49 | 86 | | if (string.IsNullOrWhiteSpace(_config.Login) || string.IsNullOrWhiteSpace(_config.Password)) |
| | 0 | 87 | | throw new ShateMApiException("Не настроены ShateM:Login и/или ShateM:Password."); |
| | | 88 | | |
| | 49 | 89 | | using var content = new FormUrlEncodedContent(new Dictionary<string, string> |
| | 49 | 90 | | { |
| | 49 | 91 | | ["login"] = _config.Login, |
| | 49 | 92 | | ["password"] = _config.Password |
| | 49 | 93 | | }); |
| | 49 | 94 | | var timer = System.Diagnostics.Stopwatch.StartNew(); |
| | | 95 | | HttpResponseMessage response; |
| | | 96 | | string text; |
| | | 97 | | try |
| | | 98 | | { |
| | 49 | 99 | | response = await _factory.CreateClient("ShateMApi").PostAsync(BuildUri("/api/v1/auth/login", null), cont |
| | 45 | 100 | | text = await response.Content.ReadAsStringAsync(ct); |
| | 45 | 101 | | } |
| | 4 | 102 | | catch (Exception ex) |
| | | 103 | | { |
| | 4 | 104 | | _logs?.Add("ShateM", HttpMethod.Post.Method, "/api/v1/auth/login", null, timer, await content.ReadAsStri |
| | 4 | 105 | | throw; |
| | 0 | 106 | | } |
| | 45 | 107 | | using (response) |
| | 45 | 108 | | _logs?.Add("ShateM", HttpMethod.Post.Method, "/api/v1/auth/login", (int)response.StatusCode, timer, awai |
| | 45 | 109 | | if (!response.IsSuccessStatusCode) throw new ShateMApiException($"Авторизация Шате-М завершилась HTTP {(int) |
| | 45 | 110 | | var json = JObject.Parse(text); |
| | 45 | 111 | | var token = json.Value<string>("access_token"); |
| | 45 | 112 | | var expiresIn = json.Value<int?>("expires_in") ?? 3600; |
| | 45 | 113 | | if (string.IsNullOrWhiteSpace(token)) throw new ShateMApiException("Ответ авторизации Шате-М не содержит acc |
| | 45 | 114 | | _accessToken = token; |
| | 45 | 115 | | _expiresAt = DateTimeOffset.UtcNow.AddSeconds(Math.Max(60, expiresIn)); |
| | 45 | 116 | | return token; |
| | | 117 | | } |
| | 0 | 118 | | catch (ShateMApiException) { throw; } |
| | 8 | 119 | | catch (Exception ex) { throw new ShateMApiException("Не удалось авторизоваться в Шате-М.", requestPath: "/api/v1 |
| | 49 | 120 | | finally { _tokenLock.Release(); } |
| | 75 | 121 | | } |
| | | 122 | | |
| | | 123 | | private Uri BuildUri(string path, IReadOnlyDictionary<string, string?>? query) |
| | | 124 | | { |
| | 124 | 125 | | var builder = new UriBuilder(_config.BaseUrl.TrimEnd('/') + "/" + path.TrimStart('/')); |
| | 124 | 126 | | if (query != null) |
| | 55 | 127 | | builder.Query = string.Join("&", query.Where(x => !string.IsNullOrWhiteSpace(x.Value)).Select(x => $"{Uri.Es |
| | 124 | 128 | | return builder.Uri; |
| | | 129 | | } |
| | | 130 | | |
| | | 131 | | private static string GetErrorDescription(string response) |
| | | 132 | | { |
| | | 133 | | try |
| | | 134 | | { |
| | 6 | 135 | | var json = JToken.Parse(response); |
| | 6 | 136 | | var description = json.Value<string>("description") ?? json.Value<string>("message"); |
| | 6 | 137 | | var messages = json["messages"]?.Values<string>().Where(x => !string.IsNullOrWhiteSpace(x)); |
| | 6 | 138 | | var errorDescriptions = json["errorDescriptions"] is JObject errors |
| | 2 | 139 | | ? errors.Properties().Select(x => x.Value.Value<string>()).Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 6 | 140 | | : []; |
| | | 141 | | // byCartItems возвращает cartItemErrors, byPriceItems — priceItemErrors. |
| | 6 | 142 | | var itemErrors = new[] { "cartItemErrors", "priceItemErrors" } |
| | 12 | 143 | | .SelectMany(name => json[name] as JArray ?? new JArray()) |
| | 6 | 144 | | .OfType<JObject>() |
| | 1 | 145 | | .SelectMany(x => x["errors"]?.Values<string>() ?? []) |
| | 6 | 146 | | .Select(TranslateOrderError); |
| | 14 | 147 | | var details = string.Join(" ", new[] { description }.Concat(messages ?? []).Concat(errorDescriptions).Concat |
| | 6 | 148 | | return string.IsNullOrWhiteSpace(details) ? "Подробности доступны в журнале API." : details; |
| | | 149 | | } |
| | 0 | 150 | | catch |
| | | 151 | | { |
| | 0 | 152 | | return "Подробности доступны в журнале API."; |
| | | 153 | | } |
| | 6 | 154 | | } |
| | | 155 | | |
| | 1 | 156 | | private static string TranslateOrderError(string? error) => error switch |
| | 1 | 157 | | { |
| | 1 | 158 | | "NeedFullPrepayment" => "Требуется полная предоплата по строке заказа.", |
| | 0 | 159 | | _ => error ?? string.Empty |
| | 1 | 160 | | }; |
| | | 161 | | } |