| | | 1 | | using Newtonsoft.Json.Linq; |
| | | 2 | | using System; |
| | | 3 | | using System.Collections.Concurrent; |
| | | 4 | | using System.Globalization; |
| | | 5 | | using System.Net.Http; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using System.Xml.Linq; |
| | | 8 | | |
| | | 9 | | namespace Services.PriceСlculationServices |
| | | 10 | | { |
| | | 11 | | public class CurrencyRateFetcher : ICurrencyRateFetcher |
| | | 12 | | { |
| | | 13 | | // Используем статичный HttpClient (рекомендованная практика для долгоживущих объектов). |
| | | 14 | | // Таймаут намеренно короткий: CBR-API используется только для UI, сбой не критичен. |
| | 0 | 15 | | private static readonly HttpClient _httpClient = new HttpClient |
| | 0 | 16 | | { |
| | 0 | 17 | | Timeout = TimeSpan.FromSeconds(10) |
| | 0 | 18 | | }; |
| | | 19 | | |
| | 0 | 20 | | private static readonly ConcurrentDictionary<string, (decimal Rate, DateTime FetchedAt)> _cache = new(); |
| | 0 | 21 | | private static readonly TimeSpan _cacheTtl = TimeSpan.FromHours(1); |
| | | 22 | | |
| | 0 | 23 | | public async Task<decimal> GetUSDRateAsync() => await GetCurrencyRateAsync("USD"); |
| | 0 | 24 | | public async Task<decimal> GetEURRateAsync() => await GetCurrencyRateAsync("EUR"); |
| | 0 | 25 | | public async Task<decimal> GetBYNRateAsync() => await GetCurrencyRateAsync("BYN"); |
| | | 26 | | |
| | | 27 | | private async Task<decimal> GetCurrencyRateAsync(string currencyCode) |
| | | 28 | | { |
| | 0 | 29 | | if (_cache.TryGetValue(currencyCode, out var cached) |
| | 0 | 30 | | && DateTime.UtcNow - cached.FetchedAt < _cacheTtl) |
| | | 31 | | { |
| | 0 | 32 | | return cached.Rate; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | decimal rate; |
| | | 36 | | try |
| | | 37 | | { |
| | 0 | 38 | | rate = await GetRateFromOfficialCbrAsync(currencyCode); |
| | 0 | 39 | | } |
| | 0 | 40 | | catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException) |
| | | 41 | | { |
| | 0 | 42 | | rate = await GetRateFromLegacyCbrAsync(currencyCode); |
| | | 43 | | } |
| | 0 | 44 | | _cache[currencyCode] = (rate, DateTime.UtcNow); |
| | | 45 | | |
| | 0 | 46 | | return rate; |
| | 0 | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary>Основной endpoint ЦБ РФ; CDN cbr-xml-daily.ru периодически недоступен из локальной сети.</summary> |
| | | 50 | | private static async Task<decimal> GetRateFromOfficialCbrAsync(string currencyCode) |
| | | 51 | | { |
| | | 52 | | const string officialUrl = "https://www.cbr.ru/scripts/XML_daily.asp"; |
| | 0 | 53 | | var response = await _httpClient.GetStringAsync(officialUrl); |
| | 0 | 54 | | var document = XDocument.Parse(response); |
| | 0 | 55 | | var currency = document.Root? |
| | 0 | 56 | | .Elements("Valute") |
| | 0 | 57 | | .FirstOrDefault(item => string.Equals(item.Element("CharCode")?.Value, currencyCode, StringComparison.Or |
| | 0 | 58 | | var value = currency?.Element("Value")?.Value; |
| | 0 | 59 | | var nominal = currency?.Element("Nominal")?.Value; |
| | | 60 | | |
| | 0 | 61 | | if (!decimal.TryParse(value, NumberStyles.Number, CultureInfo.GetCultureInfo("ru-RU"), out var parsedValue) |
| | 0 | 62 | | !decimal.TryParse(nominal, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedNominal) || |
| | 0 | 63 | | parsedNominal <= 0) |
| | | 64 | | { |
| | 0 | 65 | | throw new InvalidOperationException($"ЦБ РФ не вернул курс {currencyCode}."); |
| | | 66 | | } |
| | | 67 | | |
| | 0 | 68 | | return parsedValue / parsedNominal; |
| | 0 | 69 | | } |
| | | 70 | | |
| | | 71 | | private static async Task<decimal> GetRateFromLegacyCbrAsync(string currencyCode) |
| | | 72 | | { |
| | | 73 | | const string legacyUrl = "https://www.cbr-xml-daily.ru/daily_json.js"; |
| | 0 | 74 | | var response = await _httpClient.GetStringAsync(legacyUrl); |
| | 0 | 75 | | var json = JObject.Parse(response); |
| | 0 | 76 | | return json["Valute"]![currencyCode]!["Value"]!.Value<decimal>(); |
| | 0 | 77 | | } |
| | | 78 | | |
| | 0 | 79 | | public void ClearCache() => _cache.Clear(); |
| | | 80 | | } |
| | | 81 | | } |