| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Services.ApiServices.TelegramBotApi; |
| | | 3 | | |
| | | 4 | | namespace OzonOrdersWeb.WebServices.SystemAlerts; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Держит в чатах одно закреплённое сообщение «активные алерты» и обновляет его на месте (editMessageText). |
| | | 8 | | /// Когда алертов не осталось, текст меняется на «активных алертов нет» и сообщение откреплается. |
| | | 9 | | /// Состояние хранится в памяти; после перезапуска сообщение находится по закрепу чата (getChat), так что |
| | | 10 | | /// дубли не появляются и БД не нужна. |
| | | 11 | | /// </summary> |
| | 5 | 12 | | public sealed class SystemAlertPinnedMessageService(ITelegramNotifier telegram, TelegramBotConfig config, |
| | 5 | 13 | | ILogger<SystemAlertPinnedMessageService> logger) |
| | | 14 | | { |
| | 18 | 15 | | private sealed record ChatState(long MessageId, string LastHtml); |
| | | 16 | | |
| | 1 | 17 | | private static readonly ConcurrentDictionary<(long ChatId, int Thread), ChatState> States = new(); |
| | 1 | 18 | | private static readonly ConcurrentDictionary<(long ChatId, int Thread), bool> Restored = new(); |
| | | 19 | | |
| | | 20 | | public async Task SyncAsync(IReadOnlyList<TelegramAlertItem> active, CancellationToken ct = default) |
| | | 21 | | { |
| | 10 | 22 | | if (!telegram.IsConfigured) return; |
| | | 23 | | |
| | 10 | 24 | | var message = TelegramMessageFactory.ActiveAlerts(active, config.SiteBaseUrl); |
| | 40 | 25 | | foreach (var route in telegram.RoutesFor(TelegramChannel.Alerts)) |
| | | 26 | | { |
| | | 27 | | try |
| | | 28 | | { |
| | 10 | 29 | | await SyncChatAsync(route, message, active.Count == 0, ct); |
| | 10 | 30 | | } |
| | 0 | 31 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 32 | | { |
| | 0 | 33 | | throw; |
| | | 34 | | } |
| | 0 | 35 | | catch (Exception ex) |
| | | 36 | | { |
| | 0 | 37 | | logger.LogWarning(ex, "Не удалось обновить закреплённое сообщение алертов в чате {ChatId}", route.ChatId |
| | 0 | 38 | | } |
| | 10 | 39 | | } |
| | 10 | 40 | | } |
| | | 41 | | |
| | | 42 | | private async Task SyncChatAsync(TelegramRoute route, TelegramMessage message, bool nothingActive, CancellationToken |
| | | 43 | | { |
| | 10 | 44 | | var chatId = route.ChatId; |
| | 10 | 45 | | var key = (chatId, route.ThreadId ?? 0); |
| | 10 | 46 | | if (!States.TryGetValue(key, out var state) && Restored.TryAdd(key, true)) |
| | | 47 | | { |
| | | 48 | | // Первый проход после старта: ищем своё закреплённое сообщение, чтобы не плодить новые. |
| | 5 | 49 | | var pinned = await telegram.GetPinnedAsync(chatId, ct); |
| | 5 | 50 | | if (pinned is { FromBot: true } && IsOurs(pinned.Text)) |
| | | 51 | | { |
| | 1 | 52 | | state = new ChatState(pinned.MessageId, string.Empty); |
| | 1 | 53 | | States[key] = state; |
| | | 54 | | } |
| | | 55 | | } |
| | | 56 | | |
| | 10 | 57 | | if (nothingActive) |
| | | 58 | | { |
| | 3 | 59 | | if (state == null) return; |
| | 1 | 60 | | if (state.LastHtml != message.Html && await telegram.EditAsync(chatId, state.MessageId, message.Html, ct)) |
| | 1 | 61 | | await telegram.UnpinAsync(chatId, state.MessageId, ct); |
| | 1 | 62 | | States.TryRemove(key, out _); |
| | 1 | 63 | | return; |
| | | 64 | | } |
| | | 65 | | |
| | 8 | 66 | | if (state != null) |
| | | 67 | | { |
| | 5 | 68 | | if (state.LastHtml == message.Html) return; |
| | 3 | 69 | | if (await telegram.EditAsync(chatId, state.MessageId, message.Html, ct)) |
| | | 70 | | { |
| | 2 | 71 | | States[key] = state with { LastHtml = message.Html }; |
| | 2 | 72 | | return; |
| | | 73 | | } |
| | | 74 | | // Сообщение удалили вручную или оно недоступно — создадим новое. |
| | | 75 | | } |
| | | 76 | | |
| | 5 | 77 | | var id = await telegram.SendToRouteAsync(message with { Silent = true }, route, ct); |
| | 5 | 78 | | if (id is not { } messageId) return; |
| | 5 | 79 | | States[key] = new ChatState(messageId, message.Html); |
| | 5 | 80 | | await telegram.PinAsync(chatId, messageId, silent: true, ct); |
| | 10 | 81 | | } |
| | | 82 | | |
| | | 83 | | private static bool IsOurs(string? text) => |
| | 1 | 84 | | text != null && text.Contains(TelegramMessageFactory.ActiveAlertsMarker, StringComparison.OrdinalIgnoreCase); |
| | | 85 | | } |