This commit is contained in:
kislovdm
2026-03-10 17:19:11 +03:00
parent afafe09426
commit 5add09e264
7 changed files with 59 additions and 54 deletions
@@ -1,7 +1,7 @@
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using NLog;
using PepperBot.Application.Interfaces;
using PepperBot.Domain;
@@ -9,6 +9,8 @@ namespace PepperBot.Infrastructure.Pepper;
public class PepperClient : IPepperClient
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private const string Url =
"https://auth.pepper.ru/v4/home/new?per_page=10&page=1&type=new&fields=id%2Ctitle%2Ccurrent_price%2Cshipping_and_handling%2Cretail_price%2Cpercent_off%2Ctop_deal%2Cimage_medium%2Ccreated_at%2Ccreated_at_in_millis%2Ccomments_count%2Clife_time_hotness%2Cuser%7Bid%2Clogin%2Cimage_medium%2Ccurrent_title%2Cdisplay_title%2Cdisplay_title_icon%7D%2Cstore%7Bpermalink%2Cname%2Cimage%7D%2Cpermalink%2Cposts_count%2Cvote_value%2Cdeal_types%2Cview_count%2Cforum%7Bforum_type%2Cname%2Cpermalink%7D%2Ctag_color_code%2C+dark_theme_tag_color_code%2Cworkflow_state%2Cdisplay_hotness_icon%2Creferral_state%2Ccoupon_code%2Cdeal_url%2Ccomment_preview%2Cis_nsfw%2Cdescription";
@@ -17,7 +19,6 @@ public class PepperClient : IPepperClient
"6c266d5dc070c811e61f611ddd970a3defb493a23c50ee01f32eb9b0cfe46cd8";
private readonly HttpClient _httpClient;
private readonly ILogger<PepperClient> _logger;
private static readonly JsonSerializerOptions JsonOptions = new()
{
@@ -25,9 +26,8 @@ public class PepperClient : IPepperClient
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public PepperClient(ILogger<PepperClient> logger)
public PepperClient()
{
_logger = logger;
_httpClient = new HttpClient
{
BaseAddress = new Uri("https://auth.pepper.ru")
@@ -45,10 +45,10 @@ public class PepperClient : IPepperClient
public async Task<IReadOnlyList<Deal>> GetLatestDealsAsync(CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(HttpMethod.Get, Url);
_logger.LogDebug("Отправка запроса за последними скидками Pepper: {Url}", Url);
Logger.Debug("Отправка запроса за последними скидками Pepper: {Url}", Url);
using var response = await _httpClient.SendAsync(request, cancellationToken);
_logger.LogDebug("Получен ответ от Pepper: {StatusCode}", (int)response.StatusCode);
Logger.Debug("Получен ответ от Pepper: {StatusCode}", (int)response.StatusCode);
response.EnsureSuccessStatusCode();
@@ -57,14 +57,14 @@ public class PepperClient : IPepperClient
if (dto?.Deals is null)
{
_logger.LogWarning("Не удалось распарсить ответ Pepper");
Logger.Warn("Не удалось распарсить ответ Pepper");
return Array.Empty<Deal>();
}
_logger.LogInformation("Успешно распарсен ответ Pepper: всего сделок в ответе {DealCount}", dto.Deals.Count);
Logger.Info("Успешно распарсен ответ Pepper: всего сделок в ответе {DealCount}", dto.Deals.Count);
var mappedDeals = dto.Deals.Select(MapToDeal).ToArray();
_logger.LogDebug("После маппинга в доменную модель осталось сделок: {MappedCount}", mappedDeals.Length);
Logger.Debug("После маппинга в доменную модель осталось сделок: {MappedCount}", mappedDeals.Length);
return mappedDeals;
}
@@ -1,6 +1,6 @@
using System.Globalization;
using System.Text;
using Microsoft.Extensions.Logging;
using NLog;
using PepperBot.Application.Interfaces;
using PepperBot.Domain;
using Telegram.Bot;
@@ -14,9 +14,10 @@ namespace PepperBot.Infrastructure.Telegram;
public class TelegramNotifier : ITelegramNotifier
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly ITelegramBotClient _botClient;
private readonly ISubscriptionRepository _subscriptionRepository;
private readonly ILogger<TelegramNotifier> _logger;
private readonly string _broadcastChatId;
private bool _started;
@@ -30,17 +31,15 @@ public class TelegramNotifier : ITelegramNotifier
public TelegramNotifier(
ITelegramBotClient botClient,
ISubscriptionRepository subscriptionRepository,
ILogger<TelegramNotifier> logger)
ISubscriptionRepository subscriptionRepository)
{
_botClient = botClient;
_subscriptionRepository = subscriptionRepository;
_logger = logger;
_broadcastChatId = Environment.GetEnvironmentVariable("TELEGRAM_CHAT_ID") ?? string.Empty;
if (string.IsNullOrWhiteSpace(_broadcastChatId))
{
_logger.LogInformation("TELEGRAM_CHAT_ID не задан. Общая рассылка по скидкам будет отключена.");
Logger.Info("TELEGRAM_CHAT_ID не задан. Общая рассылка по скидкам будет отключена.");
}
}
@@ -83,7 +82,7 @@ public class TelegramNotifier : ITelegramNotifier
cancellationToken);
_started = true;
_logger.LogInformation("Запущена обработка входящих сообщений Telegram.");
Logger.Info("Запущена обработка входящих сообщений Telegram.");
return Task.CompletedTask;
}
@@ -198,7 +197,7 @@ public class TelegramNotifier : ITelegramNotifier
text: confirmation.ToString(),
cancellationToken: cancellationToken);
_logger.LogInformation(
Logger.Info(
"Для чата {ChatId} добавлены правила подписки по ключевым словам: {Keywords}",
chatId,
string.Join(", ", keywords));
@@ -253,7 +252,7 @@ public class TelegramNotifier : ITelegramNotifier
_ => exception.ToString()
};
_logger.LogError("Ошибка Telegram-бота: {Error}", errorMessage);
Logger.Error("Ошибка Telegram-бота: {Error}", errorMessage);
return Task.CompletedTask;
}
@@ -296,7 +295,7 @@ public class TelegramNotifier : ITelegramNotifier
}
catch (ApiRequestException ex)
{
_logger.LogWarning(
Logger.Warn(
ex,
"Не удалось отправить сообщение в Telegram (чат {ChatId}): [{Code}] {Message}",
chatId,