using Anubis.Core;
using Anubis.Db;
using Anubis.Notifications;
namespace Anubis.Server;
///
/// Telegram and the sign of life (SPEC 14): the queue sent every few seconds, the commands read as they arrive, the
/// call to the checking service every minute, the morning summary and the optional periodic status.
///
internal sealed partial class TelegramServices : IDisposable
{
/// The secret that keeps the address of the checking service when the configuration does not give one.
public const string HeartbeatSecret = "HEARTBEAT_URL";
public static readonly TimeOnly MorningAt = new(8, 0);
public static readonly TimeOnly EveningAt = new(20, 0);
private readonly HttpClient _http;
private readonly Database _db;
private readonly IClock _clock;
private readonly SettingsStore _settings;
private readonly SecretStore _secrets;
private readonly TimeZoneInfo _zone;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
public TelegramServices(AnubisHost host, Database db, IClock clock, SettingsStore settings, SecretStore secrets, string? configuredHeartbeat, HttpMessageHandler? handler,
Microsoft.Extensions.Logging.ILogger logger)
{
ArgumentNullException.ThrowIfNull(host);
_db = db;
_clock = clock;
_settings = settings;
_secrets = secrets;
_zone = host.Config.TimeZone;
_logger = logger;
_http = Anubis.Brokers.Outgoing.KeyedClient(handler);
// Longer than the wait of the commands' long polling.
_http.Timeout = TimeSpan.FromSeconds(60);
Desk = new TelegramDesk(host);
Sender = new NotificationSender(db, clock, ReadAsync, Client);
Bot = new TelegramBot(clock, ReadAsync, Client, new TelegramCommands(Desk, clock), logger);
ConfiguredHeartbeat = configuredHeartbeat;
Heartbeat = new Heartbeat(_http, clock, HeartbeatAddressAsync, logger);
}
public TelegramDesk Desk { get; }
public NotificationSender Sender { get; }
public TelegramBot Bot { get; }
public Heartbeat Heartbeat { get; }
/// The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here.
public string? ConfiguredHeartbeat { get; }
/// How often the queue is looked at.
public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10);
/// The client of Telegram and of the checking service.
public HttpClient Http => _http;
public TelegramClient Client(string token) => new(_http, token);
public Task ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken);
public async Task HeartbeatAddressAsync(CancellationToken cancellationToken)
{
var text = ConfiguredHeartbeat ?? await _secrets.RevealAsync(HeartbeatSecret, cancellationToken).ConfigureAwait(false);
return string.IsNullOrWhiteSpace(text) || Heartbeat.Check(text) is not null ? null : new Uri(text.Trim());
}
public IReadOnlyList Jobs() =>
[
new("segnale-di-vita", "Segnale di vita al servizio di controllo", Schedule.Every(TimeSpan.FromMinutes(1)), async ct => await Heartbeat.BeatAsync(ct).ConfigureAwait(false))
{
MaxLateness = TimeSpan.FromMinutes(2),
},
// The summary is still useful a little late; after four hours the day has moved on (SPEC 5.6).
new("riepilogo-mattino", "Riepilogo del mattino su Telegram", Schedule.Daily(MorningAt, _zone), MorningAsync)
{
MaxLateness = TimeSpan.FromHours(4),
CatchUpWithin = TimeSpan.FromHours(4),
},
new("stato-ogni-ora", "Stato periodico su Telegram, se scelto ogni ora", Schedule.Every(TimeSpan.FromHours(1)), ct => PeriodicAsync("hourly", ct)),
new("stato-ogni-giorno", "Stato periodico su Telegram, se scelto ogni giorno", Schedule.Daily(EveningAt, _zone), ct => PeriodicAsync("daily", ct)),
];
/// Sends the queue and reads the commands until the services stop.
public async Task RunAsync(CancellationToken cancellationToken)
{
var commands = Bot.RunAsync(cancellationToken);
try
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await Sender.SendDueAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
// A busy or unreachable database, or anything else: the queue keeps its messages for the next pass.
LogSendFailed(_logger, ex);
}
await Task.Delay(SendEvery, cancellationToken).ConfigureAwait(false);
}
}
finally
{
try
{
await commands.ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
}
}
///
/// The test of Impostazioni: a message to the chat, sent at once and not through the queue, so the answer says
/// whether Telegram took it. Null when it went; otherwise the reason, in the user's words.
///
public async Task TestAsync(TelegramSettings telegram, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(telegram);
try
{
var client = Client(telegram.Token);
var name = await client.GetMeAsync(cancellationToken).ConfigureAwait(false);
await client.SendAsync(telegram.ChatId, $"Anubis: messaggio di prova. Da qui ti scrivo{(name.Length > 0 ? " come @" + name : "")}; scrivi /aiuto per i comandi.",
cancellationToken).ConfigureAwait(false);
return null;
}
catch (TelegramException ex)
{
return ex.Message;
}
}
public void Dispose() => _http.Dispose();
private async Task MorningAsync(CancellationToken cancellationToken)
{
if (await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
{
return;
}
var text = await Desk.MorningAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "morning_summary", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
private async Task PeriodicAsync(string every, CancellationToken cancellationToken)
{
if ((await _settings.GetAsync(SettingsStore.TelegramStatus.Key, cancellationToken).ConfigureAwait(false)).Value != every
|| await ReadAsync(cancellationToken).ConfigureAwait(false) is null)
{
return;
}
var text = await Desk.StatusAsync(cancellationToken).ConfigureAwait(false);
await _db.WriteAsync(s => NotificationSender.EnqueueAsync(s, _clock, "periodic_status", text, cancellationToken), cancellationToken).ConfigureAwait(false);
}
[Microsoft.Extensions.Logging.LoggerMessage(Level = Microsoft.Extensions.Logging.LogLevel.Error, Message = "Sending the Telegram queue failed")]
private static partial void LogSendFailed(Microsoft.Extensions.Logging.ILogger logger, Exception exception);
}