using System.Threading.Channels;
using Mimante.Logging;
using Mimante.Settings;
namespace Mimante.Telegram;
///
/// Le notifiche Telegram (specifica §6.7): una coda con tre ritentativi e attesa crescente,
/// così un Telegram lento non rallenta mai il motore. Facoltativi i comandi in ingresso
/// (/stato, /halt, /riprendi, /osserva), letti con
/// getUpdates a polling lungo e accettati solo dalla chat configurata.
///
public sealed class TelegramNotifier : IAsyncDisposable
{
/// Quanto aspetta Telegram con getUpdates prima di rispondere senza messaggi nuovi.
private const int LongPollSeconds = 25;
private readonly Func _settings;
private readonly AppLog _log;
private readonly HttpClient _http;
private readonly Func _delay;
private readonly Channel _queue = Channel.CreateBounded(new BoundedChannelOptions(200) { FullMode = BoundedChannelFullMode.DropOldest });
private readonly CancellationTokenSource _cts = new();
private readonly Task _sender;
private readonly Task _commands;
private long _offset;
private bool _failureSaid;
/// Risponde a un comando ricevuto: il testo della risposta.
public Func>? CommandHandler { get; set; }
/// Il client verso Telegram; i test ne passano uno con un gestore finto.
/// Le attese fra i tentativi e dei cicli (di serie ); i test le accorciano.
public TelegramNotifier(Func settings, AppLog log, HttpClient? http = null, Func? delay = null)
{
_settings = settings;
_log = log;
// Nessun tempo massimo sul client: ogni richiesta ha il suo (TelegramTimeoutSeconds),
// che vale dal vivo e dà un errore leggibile invece della scadenza generica del client.
_http = http ?? new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
_delay = delay ?? Task.Delay;
_sender = Task.Run(() => SendLoopAsync(_cts.Token));
_commands = Task.Run(() => CommandLoopAsync(_cts.Token));
}
public bool Configured
{
get
{
var s = _settings();
return !string.IsNullOrWhiteSpace(s.TelegramBotToken) && !string.IsNullOrWhiteSpace(s.TelegramChatId);
}
}
/// Accoda un messaggio già formattato (). Senza token o chat non fa nulla.
public void Enqueue(string text)
{
if (Configured) _queue.Writer.TryWrite(text);
}
/// «Invia messaggio di prova» delle impostazioni: subito, senza coda, con l'esito.
public async Task<(bool Ok, string Message)> SendTestAsync(CancellationToken ct)
{
var s = _settings();
if (string.IsNullOrWhiteSpace(s.TelegramBotToken) || string.IsNullOrWhiteSpace(s.TelegramChatId))
return (false, "Scrivi token del bot e chat id, salva, poi riprova");
try
{
var ok = await SendOnceAsync(s, TelegramFormat.Message("Messaggio di prova da Mimante", "Se lo leggi, le notifiche arrivano."), ct).ConfigureAwait(false);
return ok ? (true, "Messaggio inviato") : (false, "Telegram ha rifiutato il messaggio: controlla token e chat id (scrivi prima un messaggio al bot)");
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return (false, $"Telegram non raggiungibile: {NoAnswer(s)}");
}
catch (Exception ex)
{
return (false, $"Telegram non raggiungibile: {ex.Message}");
}
}
/// Un solo invio, con il tempo massimo delle impostazioni sopra quello di chi chiama.
private async Task SendOnceAsync(AppSettings s, string text, CancellationToken ct)
{
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(TimeSpan.FromSeconds(s.TelegramTimeoutSeconds));
return await TelegramApi.SendAsync(_http, s.TelegramBotToken, s.TelegramChatId, text, limit.Token).ConfigureAwait(false);
}
private static string NoAnswer(AppSettings s) => $"nessuna risposta in {s.TelegramTimeoutSeconds} s";
private async Task SendLoopAsync(CancellationToken ct)
{
try
{
await foreach (var text in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
var s = _settings();
if (string.IsNullOrWhiteSpace(s.TelegramBotToken) || string.IsNullOrWhiteSpace(s.TelegramChatId)) continue;
var sent = false;
string? error = null;
for (var attempt = 0; attempt < 3 && !sent; attempt++)
{
if (attempt > 0) await _delay(TimeSpan.FromSeconds(2 << attempt), ct).ConfigureAwait(false);
try { sent = await SendOnceAsync(s, text, ct).ConfigureAwait(false); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (OperationCanceledException) { error = NoAnswer(s); }
catch (Exception ex) { error = ex.Message; }
}
if (!sent && !_failureSaid)
{
_failureSaid = true;
_log.Warn("TELEGRAM", $"Messaggio non inviato dopo tre tentativi{(error != null ? $": {error}" : "")}");
}
else if (sent) _failureSaid = false;
}
}
catch (OperationCanceledException) { }
}
private async Task CommandLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var s = _settings();
if (!s.TelegramCommandsEnabled || !Configured || CommandHandler == null)
{
try { await _delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; }
continue;
}
try
{
IReadOnlyList updates;
using (var limit = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
limit.CancelAfter(TimeSpan.FromSeconds(LongPollSeconds + s.TelegramTimeoutSeconds));
updates = await TelegramApi.GetUpdatesAsync(_http, s.TelegramBotToken, _offset, LongPollSeconds, limit.Token).ConfigureAwait(false);
}
foreach (var u in updates)
{
_offset = Math.Max(_offset, u.UpdateId + 1);
if (u.ChatId != s.TelegramChatId.Trim() || string.IsNullOrWhiteSpace(u.Text)) continue;
var command = u.Text.Trim().Split(' ', '@')[0].ToLowerInvariant();
_log.Info("TELEGRAM", $"Comando ricevuto: {command}");
var reply = await CommandHandler(command).ConfigureAwait(false);
Enqueue(reply);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (Exception)
{
try { await _delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false); } catch (OperationCanceledException) { return; }
}
}
}
public async ValueTask DisposeAsync()
{
_queue.Writer.TryComplete();
await _cts.CancelAsync().ConfigureAwait(false);
try { await Task.WhenAll(_sender, _commands).WaitAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); } catch { }
_http.Dispose();
_cts.Dispose();
}
}