A session alone could change the password, switch the second factor on or off, send the key of the language model to another address and remove the rules that stop purchases. Each now needs the password and the code, with one limit on wrong attempts that a restart of the services does not clear, and the other sessions end when the password or the factor changes. Requests to the brokers pass a list of allowed calls, never follow a redirect with a key and are signed by one client only. Pages are closed by default, nothing is cached, requests are limited to 1 MB, secrets are masked in logs and notifications, exported tables cannot run as formulas, archives carry no sessions and the container refuses to run as root. refs #68 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
7.4 KiB
C#
174 lines
7.4 KiB
C#
using Anubis.Core;
|
|
using Anubis.Db;
|
|
using Anubis.Notifications;
|
|
|
|
namespace Anubis.Server;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
internal sealed partial class TelegramServices : IDisposable
|
|
{
|
|
/// <summary>The secret that keeps the address of the checking service when the configuration does not give one.</summary>
|
|
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; }
|
|
|
|
/// <summary>The address from the startup configuration (ANUBIS_HEARTBEAT_URL): it wins over the one saved here.</summary>
|
|
public string? ConfiguredHeartbeat { get; }
|
|
|
|
/// <summary>How often the queue is looked at.</summary>
|
|
public TimeSpan SendEvery { get; init; } = TimeSpan.FromSeconds(10);
|
|
|
|
/// <summary>The client of Telegram and of the checking service.</summary>
|
|
public HttpClient Http => _http;
|
|
|
|
public TelegramClient Client(string token) => new(_http, token);
|
|
|
|
public Task<TelegramSettings?> ReadAsync(CancellationToken cancellationToken) => TelegramSettings.ReadAsync(_secrets, cancellationToken);
|
|
|
|
public async Task<Uri?> 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<ScheduledJob> 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)),
|
|
];
|
|
|
|
/// <summary>Sends the queue and reads the commands until the services stop.</summary>
|
|
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)
|
|
{
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
public async Task<string?> 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);
|
|
}
|