Rifiniture (M8): avvisi su striscia, notifiche di Windows e Telegram con controllo dello spazio su disco; «Esporta l'elenco» della libreria; avvisi e ricette sospese in Attività; guida per il wiki in docs/guida

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 21:22:52 +00:00
1 parent dc4d1fc738
commit 69dbc7acf9
50 files changed
+3980 -28

No files matched your search

+220
View File
@@ -0,0 +1,220 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Core.Alerts;
/// <summary>The alerts of spec §13.3, one per kind of event worth telling Alberto about outside the interface.</summary>
public enum AlertKind
{
/// <summary>«Verifica richiesta»: stopped, needs Alberto in the browser and «Riprendi».</summary>
Verification,
/// <summary>«Disconnessione»: the Instagram session is gone, needs a new login and «Riprendi».</summary>
Disconnection,
/// <summary>«Fermo per rallentamento»: timed stop after a throttle.</summary>
ThrottleStop,
/// <summary>«…e ripresa»: the timed stop is over and Febe works again.</summary>
ThrottleEnd,
/// <summary>«Storico di un account completato».</summary>
BackfillDone,
/// <summary>«Formato non riconosciuto»: a reader met an unknown shape.</summary>
UnknownFormat,
/// <summary>A recipe suspended after three problems in a row (same switch as <see cref="UnknownFormat"/>).</summary>
RecipeSuspended,
/// <summary>«Disco quasi pieno»: the library or the Data folder is running out of space.</summary>
DiskLow,
}
/// <summary>
/// One alert: what happened (<see cref="Title"/>), what Febe did and what Alberto should do (<see cref="Message"/>),
/// both short Italian sentences. Never contains captions, cookies, tokens or signed addresses.
/// </summary>
/// <param name="Kind">Which alert.</param>
/// <param name="At">When the event happened.</param>
/// <param name="Title">«Instagram chiede una verifica».</param>
/// <param name="Message">«Ho fermato tutto alle 14:32 e non riparto da solo. Che cosa fare: …».</param>
/// <param name="Key">De-duplication key inside the kind (an account, a set of folders); empty for one per kind.</param>
/// <param name="AccountId">Account concerned, if any.</param>
public sealed record Alert(AlertKind Kind, DateTimeOffset At, string Title, string Message, string Key = "", long? AccountId = null)
{
/// <summary>The text of a Telegram message: title on the first line, then the message.</summary>
public string TelegramText => "Febe · " + Title + "\n" + Message;
}
/// <summary>Outcome of one channel for one alert.</summary>
/// <param name="Sent">The channel accepted the alert.</param>
/// <param name="Problem">Italian reason when not sent; never contains addresses or tokens.</param>
public sealed record AlertDelivery(bool Sent, string? Problem = null)
{
public static AlertDelivery Ok { get; } = new(true);
}
/// <summary>
/// A way to reach Alberto outside the interface: Telegram, Windows notifications. The red strip of the interface is not
/// a channel: it is always there (the engine snapshot, spec §13.3).
/// </summary>
public interface IAlertChannel
{
/// <summary>Italian name for the log and the timeline: «Telegram», «notifica di Windows».</summary>
string Name { get; }
/// <summary>The channel is available here and switched on in the settings.</summary>
bool IsEnabled(AlertSettings settings);
/// <summary>Sends the alert. Never throws for delivery problems: they come back as <see cref="AlertDelivery.Problem"/>.</summary>
Task<AlertDelivery> SendAsync(Alert alert, AlertSettings settings, CancellationToken ct);
}
/// <summary>Levels of the alert service's own log lines.</summary>
public enum AlertLogLevel
{
Information,
Warning,
}
/// <summary>Event codes written by the alert service (the others come from the engine, <see cref="EngineEventCodes"/>).</summary>
public static class AlertEventCodes
{
/// <summary>The library or the Data folder is almost full (spec §13.3).</summary>
public const string DiskLow = "disco-quasi-pieno";
/// <summary>An alert could not be delivered on a channel (never an alert itself).</summary>
public const string DeliveryFailed = "avviso-non-inviato";
}
/// <summary>
/// Which timeline events are alerts, their titles, texts, switches and minimum intervals. The intervals keep a
/// flapping state from sending the same message again and again: the interface still shows every event.
/// </summary>
public static class AlertCatalog
{
/// <summary>Codes shown in the «Avvisi» list of Attività: the alerts and the failed deliveries.</summary>
public static IReadOnlyList<string> Codes { get; } =
[
EngineEventCodes.ChallengeStop,
EngineEventCodes.DisconnectStop,
EngineEventCodes.ThrottleStop,
EngineEventCodes.ThrottleEnd,
EngineEventCodes.BackfillCompleted,
EngineEventCodes.FormatUnrecognized,
EngineEventCodes.RecipeSuspended,
AlertEventCodes.DiskLow,
AlertEventCodes.DeliveryFailed,
];
/// <summary>The alert kind of a timeline event code, if it is one.</summary>
public static AlertKind? KindOf(string? code) => code switch
{
EngineEventCodes.ChallengeStop => AlertKind.Verification,
EngineEventCodes.DisconnectStop => AlertKind.Disconnection,
EngineEventCodes.ThrottleStop => AlertKind.ThrottleStop,
EngineEventCodes.ThrottleEnd => AlertKind.ThrottleEnd,
EngineEventCodes.BackfillCompleted => AlertKind.BackfillDone,
EngineEventCodes.FormatUnrecognized => AlertKind.UnknownFormat,
EngineEventCodes.RecipeSuspended => AlertKind.RecipeSuspended,
AlertEventCodes.DiskLow => AlertKind.DiskLow,
_ => null,
};
/// <summary>What happened, in a few words: the title of the notification.</summary>
public static string Title(AlertKind kind) => kind switch
{
AlertKind.Verification => "Instagram chiede una verifica",
AlertKind.Disconnection => "Instagram ha chiuso la sessione",
AlertKind.ThrottleStop => "Instagram ha chiesto di rallentare",
AlertKind.ThrottleEnd => "Fine del fermo per rallentamento",
AlertKind.BackfillDone => "Storico completato",
AlertKind.UnknownFormat => "Formato non riconosciuto",
AlertKind.RecipeSuspended => "Ricetta sospesa",
AlertKind.DiskLow => "Disco quasi pieno",
_ => "Avviso di Febe",
};
/// <summary>The switch of Impostazioni ▸ Notifiche that governs the kind.</summary>
public static bool IsWanted(AlertKind kind, AlertEvents events)
{
ArgumentNullException.ThrowIfNull(events);
return kind switch
{
AlertKind.Verification => events.Verification,
AlertKind.Disconnection => events.Disconnection,
AlertKind.ThrottleStop or AlertKind.ThrottleEnd => events.Throttle,
AlertKind.BackfillDone => events.BackfillDone,
AlertKind.UnknownFormat or AlertKind.RecipeSuspended => events.UnknownFormat,
AlertKind.DiskLow => events.DiskLow,
_ => true,
};
}
/// <summary>
/// Minimum time between two sends of the same alert (same kind and key). A verification right after a «Riprendi»
/// does not reach Alberto twice in half an hour: he is at the computer and the strip shows it.
/// </summary>
public static TimeSpan MinimumInterval(AlertKind kind) => kind switch
{
AlertKind.Verification or AlertKind.Disconnection => TimeSpan.FromMinutes(30),
AlertKind.ThrottleStop or AlertKind.ThrottleEnd => TimeSpan.FromMinutes(30),
AlertKind.BackfillDone => TimeSpan.FromHours(24),
AlertKind.UnknownFormat or AlertKind.RecipeSuspended => TimeSpan.FromHours(6),
AlertKind.DiskLow => TimeSpan.FromHours(20),
_ => TimeSpan.FromHours(1),
};
/// <summary>
/// The alert of a timeline event: the title of the kind and a message that says what Febe did and what to do.
/// The engine's own message is reused where it carries the facts (end of a stop, account, number of posts).
/// </summary>
public static Alert FromEvent(AlertKind kind, EventRecord record, TimeZoneInfo zone, string? key = null)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentNullException.ThrowIfNull(zone);
var at = ItalianText.At(record.At, zone);
var message = kind switch
{
AlertKind.Verification =>
$"Ho fermato tutto {at} e non riparto da solo. Che cosa fare: apri Febe, poi il browser di Febe («Apri il browser»), completa la verifica a mano e premi «Riprendi».",
AlertKind.Disconnection =>
$"La sessione di Instagram non c'è più: ho fermato tutto {at} e non provo a rientrare. Che cosa fare: apri Febe, poi il browser di Febe («Apri il browser»), accedi a mano e premi «Riprendi».",
AlertKind.ThrottleStop => WithoutTitle(record.Message, Title(kind)) + " Non devi fare nulla: riparto da solo. Se succede spesso, scegli un profilo più prudente o segui meno account.",
AlertKind.ThrottleEnd => WithoutTitle(record.Message, Title(kind)) + " Non devi fare nulla.",
AlertKind.BackfillDone => record.Message,
AlertKind.UnknownFormat => record.Message
+ " Se succede tre volte di fila, quella ricetta si sospende: allora serve un campione nuovo con la sonda (guida, «Problemi comuni»).",
_ => record.Message,
};
return new Alert(kind, record.At, Title(kind), message, key ?? DefaultKey(kind, record), record.AccountId);
}
/// <summary>
/// The engine's sentence without its first words when they repeat the title: «Instagram ha chiesto di rallentare
/// (segnale http-429). Ho chiuso…» becomes «Ho chiuso…» (the signal stays in the stops of Attività).
/// </summary>
private static string WithoutTitle(string message, string title)
{
if (!message.StartsWith(title, StringComparison.Ordinal))
{
return message;
}
var rest = message[title.Length..];
if (rest.StartsWith(" (segnale ", StringComparison.Ordinal) && rest.IndexOf(')', StringComparison.Ordinal) is > 0 and var close)
{
rest = rest[(close + 1)..];
}
rest = rest.TrimStart('.', ':', ' ');
return rest.Length == 0 ? message : char.ToUpperInvariant(rest[0]) + rest[1..];
}
private static string DefaultKey(AlertKind kind, EventRecord record) => kind switch
{
AlertKind.BackfillDone => record.AccountId?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty,
_ => string.Empty,
};
}
+431
View File
@@ -0,0 +1,431 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
namespace Febe.Core.Alerts;
/// <summary>Options of <see cref="AlertService"/>.</summary>
public sealed record AlertServiceOptions
{
/// <summary>Folders whose disk is watched (library and Data folder); empty for none.</summary>
public IReadOnlyList<WatchedFolder> Folders { get; init; } = [];
public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe();
public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default;
/// <summary>Time between two checks of the free space.</summary>
public TimeSpan DiskCheckInterval { get; init; } = TimeSpan.FromMinutes(15);
/// <summary>Time from <see cref="AlertService.WatchDiskSpaceAsync"/> to the first check.</summary>
public TimeSpan FirstDiskCheckDelay { get; init; } = TimeSpan.FromMinutes(1);
/// <summary>While a disk stays almost full, the timeline line (and the alert) comes back this often.</summary>
public TimeSpan DiskReminder { get; init; } = TimeSpan.FromHours(24);
/// <summary>At most one «avviso non inviato» line per channel in this time.</summary>
public TimeSpan FailureEventInterval { get; init; } = TimeSpan.FromHours(1);
/// <summary>The service's own log lines (never addresses, tokens or message bodies).</summary>
public Action<AlertLogLevel, string>? Log { get; init; }
}
/// <summary>
/// The alerts of spec §13.3. It listens to the engine's timeline (<see cref="EngineEvents"/>: the circuit breaker's
/// stops and resumes, backfills completed, unknown formats, suspended recipes) and checks the free space of the
/// library and the Data folder; each alert goes to the channels switched on in Impostazioni ▸ Notifiche (Windows
/// notification on the desktop, Telegram when token and chat are set). The red strip of the interface is not its
/// job: the engine snapshot always shows a stop, and every alert is a line of the «Avvisi» list in Attività.
/// <list type="bullet">
/// <item>Same kind and key within <see cref="AlertCatalog.MinimumInterval"/>: not sent again (the times are kept in the
/// settings, so a restart does not send it again either).</item>
/// <item>A channel that fails writes one «avviso non inviato» line (at most one per hour per channel), with the
/// Italian reason only: never the address, the token or the answer of the service.</item>
/// <item>Alerts go out one at a time, in order, off the engine's threads.</item>
/// </list>
/// </summary>
public sealed class AlertService : IDisposable
{
private const string LastSentPrefix = "avvisi.inviato.";
private readonly ISettingsStore _settings;
private readonly IClock _clock;
private readonly EngineEvents _events;
private readonly IReadOnlyList<IAlertChannel> _channels;
private readonly AlertServiceOptions _options;
private readonly CancellationTokenSource _stop = new();
private readonly Lock _gate = new();
private readonly Dictionary<string, DateTimeOffset> _lastSent = new(StringComparer.Ordinal);
private readonly Dictionary<string, DateTimeOffset> _lastFailureEvent = new(StringComparer.Ordinal);
private Task _tail = Task.CompletedTask;
private bool _attached;
private string _diskKey = string.Empty;
private DateTimeOffset? _diskWrittenAt;
private bool _disposed;
public AlertService(ISettingsStore settings, IClock clock, EngineEvents events, IEnumerable<IAlertChannel> channels, AlertServiceOptions? options = null)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_events = events ?? throw new ArgumentNullException(nameof(events));
ArgumentNullException.ThrowIfNull(channels);
_channels = [.. channels];
_options = options ?? new AlertServiceOptions();
}
/// <summary>Raised after an alert has been handled (sent, suppressed or not wanted), for tests and diagnostics.</summary>
public event EventHandler<AlertOutcome>? Handled;
/// <summary>Starts listening to the engine's timeline. Idempotent.</summary>
public AlertService Attach()
{
lock (_gate)
{
if (_attached || _disposed)
{
return this;
}
_attached = true;
}
_events.Notified += OnNotified;
return this;
}
/// <summary>Raises an alert directly (not from the timeline).</summary>
public Task RaiseAsync(Alert alert)
{
ArgumentNullException.ThrowIfNull(alert);
return Enqueue(alert);
}
/// <summary>Waits until every alert raised so far has been handled.</summary>
public async Task FlushAsync()
{
while (true)
{
Task tail;
lock (_gate)
{
tail = _tail;
}
await tail.ConfigureAwait(false);
lock (_gate)
{
if (ReferenceEquals(tail, _tail))
{
return;
}
}
}
}
/// <summary>
/// Checks the free space of the watched folders now. When a disk is almost full it writes a warning line in the
/// timeline (that line becomes the alert): when the set of full disks changes, and again every
/// <see cref="AlertServiceOptions.DiskReminder"/> while it stays so.
/// </summary>
public async Task<DiskCheck> CheckDiskSpaceAsync(CancellationToken ct = default)
{
var low = new List<(WatchedFolder, FreeSpace)>();
var unmeasured = new List<WatchedFolder>();
foreach (var folder in _options.Folders)
{
var space = _options.FreeSpace.Measure(folder.Path);
if (space is null)
{
unmeasured.Add(folder);
}
else if (_options.Thresholds.IsLow(space))
{
low.Add((folder, space));
}
}
var check = new DiskCheck(low, unmeasured);
var now = _clock.Now;
bool write;
lock (_gate)
{
if (low.Count == 0)
{
_diskKey = string.Empty;
_diskWrittenAt = null;
write = false;
}
else
{
write = check.Key != _diskKey || _diskWrittenAt is not { } written || now - written >= _options.DiskReminder;
if (write)
{
_diskKey = check.Key;
_diskWrittenAt = now;
}
}
}
if (write)
{
await _events.WriteAsync(EventSeverity.Warning, AlertEventCodes.DiskLow, check.Describe(), ct: ct).ConfigureAwait(false);
}
return check;
}
/// <summary>Checks the free space periodically until <paramref name="ct"/> is cancelled (nothing to do without folders).</summary>
public async Task WatchDiskSpaceAsync(CancellationToken ct)
{
if (_options.Folders.Count == 0)
{
return;
}
var unmeasuredLogged = false;
try
{
await _clock.Delay(_options.FirstDiskCheckDelay, ct).ConfigureAwait(false);
while (!ct.IsCancellationRequested)
{
try
{
var check = await CheckDiskSpaceAsync(ct).ConfigureAwait(false);
if (check.Unmeasured.Count > 0 && !unmeasuredLogged)
{
unmeasuredLogged = true;
Log(AlertLogLevel.Warning, $"Spazio libero non misurabile per: {string.Join(", ", check.Unmeasured.Select(f => f.Name))}. Per quei dischi l'avviso «Disco quasi pieno» non arriva.");
}
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
Log(AlertLogLevel.Warning, $"Controllo dello spazio libero non riuscito ({ex.GetType().Name}): riprovo al prossimo giro.");
}
await _clock.Delay(_options.DiskCheckInterval, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
}
public void Dispose()
{
lock (_gate)
{
if (_disposed)
{
return;
}
_disposed = true;
}
_events.Notified -= OnNotified;
_stop.Cancel();
Task tail;
lock (_gate)
{
tail = _tail;
}
// Alerts in flight still hold the token: the source goes away once they are done.
_ = tail.ContinueWith(_ => _stop.Dispose(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
private void OnNotified(object? sender, EngineNotification notification)
{
if (notification.Kind != EngineNotificationKind.Event || notification.Event is not { } record)
{
return;
}
if (AlertCatalog.KindOf(record.Code) is not { } kind)
{
return;
}
string? key = null;
if (kind == AlertKind.DiskLow)
{
lock (_gate)
{
key = _diskKey;
}
}
_ = Enqueue(AlertCatalog.FromEvent(kind, record, _clock.LocalZone, key));
}
private Task Enqueue(Alert alert)
{
lock (_gate)
{
if (_disposed)
{
return Task.CompletedTask;
}
var token = _stop.Token;
_tail = _tail.ContinueWith(_ => HandleAsync(alert, token), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap();
return _tail;
}
}
private async Task HandleAsync(Alert alert, CancellationToken ct)
{
try
{
var outcome = await DeliverAsync(alert, ct).ConfigureAwait(false);
Handled?.Invoke(this, outcome);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// An alert must never stop the next one; the type alone is logged (messages may carry addresses).
Log(AlertLogLevel.Warning, $"Avviso «{alert.Title}» non gestito ({ex.GetType().Name}).");
}
}
private async Task<AlertOutcome> DeliverAsync(Alert alert, CancellationToken ct)
{
var settings = await AlertSettingsStore.LoadAsync(_settings, ct).ConfigureAwait(false);
if (!AlertCatalog.IsWanted(alert.Kind, settings.Events))
{
return new AlertOutcome(alert, AlertOutcomeKind.NotWanted, []);
}
var channels = _channels.Where(c => c.IsEnabled(settings)).ToList();
if (channels.Count == 0)
{
return new AlertOutcome(alert, AlertOutcomeKind.NoChannel, []);
}
var dedupKey = LastSentPrefix + alert.Kind.ToString().ToLowerInvariant() + (alert.Key.Length == 0 ? string.Empty : "." + alert.Key);
var now = _clock.Now;
var last = await LastSentAsync(dedupKey, ct).ConfigureAwait(false);
if (last is { } previous && now - previous < AlertCatalog.MinimumInterval(alert.Kind) && now >= previous)
{
Log(AlertLogLevel.Information, $"Avviso «{alert.Title}» non ripetuto: lo stesso è partito {ItalianText.At(previous, _clock.LocalZone)}.");
return new AlertOutcome(alert, AlertOutcomeKind.Repeated, []);
}
await RememberSentAsync(dedupKey, now, ct).ConfigureAwait(false);
var deliveries = new List<(string Channel, AlertDelivery Delivery)>();
foreach (var channel in channels)
{
AlertDelivery delivery;
try
{
delivery = await channel.SendAsync(alert, settings, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
delivery = new AlertDelivery(false, $"invio non riuscito ({ex.GetType().Name})");
}
deliveries.Add((channel.Name, delivery));
if (!delivery.Sent)
{
await RecordFailureAsync(alert, channel.Name, delivery.Problem, ct).ConfigureAwait(false);
}
}
var sent = deliveries.Where(d => d.Delivery.Sent).Select(d => d.Channel).ToList();
if (sent.Count > 0)
{
Log(AlertLogLevel.Information, $"Avviso «{alert.Title}» inviato: {string.Join(", ", sent)}.");
}
return new AlertOutcome(alert, sent.Count > 0 ? AlertOutcomeKind.Sent : AlertOutcomeKind.Failed, deliveries);
}
private async Task RecordFailureAsync(Alert alert, string channel, string? problem, CancellationToken ct)
{
var reason = string.IsNullOrWhiteSpace(problem) ? "invio non riuscito" : problem.TrimEnd('.');
Log(AlertLogLevel.Warning, $"Avviso «{alert.Title}» non inviato ({channel}): {reason}.");
var now = _clock.Now;
lock (_gate)
{
if (_lastFailureEvent.TryGetValue(channel, out var last) && now - last < _options.FailureEventInterval && now >= last)
{
return;
}
_lastFailureEvent[channel] = now;
}
await _events.WriteAsync(
EventSeverity.Warning,
AlertEventCodes.DeliveryFailed,
$"L'avviso «{alert.Title}» non è arrivato ({channel}): {reason}. Lo trovi comunque qui in Febe; controlla Impostazioni ▸ Notifiche e usa «Invia una prova».",
alert.AccountId,
ct: ct).ConfigureAwait(false);
}
private async Task<DateTimeOffset?> LastSentAsync(string key, CancellationToken ct)
{
lock (_gate)
{
if (_lastSent.TryGetValue(key, out var cached))
{
return cached;
}
}
var stored = await _settings.GetInt64Async(key, ct).ConfigureAwait(false);
return stored is { } ms ? DateTimeOffset.FromUnixTimeMilliseconds(ms) : null;
}
private async Task RememberSentAsync(string key, DateTimeOffset at, CancellationToken ct)
{
lock (_gate)
{
_lastSent[key] = at;
}
await _settings.SetAsync(key, at.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
}
private void Log(AlertLogLevel level, string message)
{
try
{
_options.Log?.Invoke(level, message);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
}
}
}
/// <summary>What happened to an alert.</summary>
public enum AlertOutcomeKind
{
/// <summary>At least one channel accepted it.</summary>
Sent,
/// <summary>Every channel failed (each failure is a timeline line).</summary>
Failed,
/// <summary>The same alert left a short while ago (<see cref="AlertCatalog.MinimumInterval"/>).</summary>
Repeated,
/// <summary>Its switch in Impostazioni ▸ Notifiche is off.</summary>
NotWanted,
/// <summary>No channel is configured (no Telegram, no Windows notifications): only the interface shows it.</summary>
NoChannel,
}
/// <summary>An alert and what each channel did with it.</summary>
public sealed record AlertOutcome(Alert Alert, AlertOutcomeKind Kind, IReadOnlyList<(string Channel, AlertDelivery Delivery)> Deliveries);
+9 -6
View File
@@ -98,20 +98,23 @@ public static class AlertSettingsStore
public sealed record AlertTestResult(bool Sent, string Message);
/// <summary>
/// «Invia una prova» of the Telegram alerts (spec §13.3). The real sender (one HTTPS call with <c>HttpClient</c>, no
/// library, the address never logged because it contains the token) arrives with milestone M8 and replaces
/// <see cref="TelegramNotAvailableYet"/>.
/// «Invia una prova» of the Telegram alerts (spec §13.3). The real sender is <see cref="TelegramAlertChannel"/> (one
/// HTTPS call with <c>HttpClient</c>, no library, the address never logged because it contains the token); the web
/// layer falls back to <see cref="NoTelegramSender"/> where nothing may leave (demonstration, tests).
/// </summary>
public interface IAlertTestSender
{
Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct);
}
/// <summary>Until M8: no message leaves, and the page says so plainly.</summary>
public sealed class TelegramNotAvailableYet : IAlertTestSender
/// <summary>
/// No Telegram here: the demonstration and hosts without a composition (tests) never use the network. The page says
/// so plainly; the real compositions register <see cref="TelegramAlertChannel"/>.
/// </summary>
public sealed class NoTelegramSender : IAlertTestSender
{
public const string Text =
"Le impostazioni sono salvate, ma l'invio dei messaggi Telegram non c'è ancora in questa versione di Febe (arriva con la tappa M8): nessun messaggio è partito, nemmeno di prova.";
"Le impostazioni sono salvate, ma questa istanza di Febe non invia messaggi Telegram (dimostrazione o prova): nessun messaggio è partito.";
public Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct) => Task.FromResult(new AlertTestResult(false, Text));
}
+122
View File
@@ -0,0 +1,122 @@
using Febe.Core.Engine;
namespace Febe.Core.Alerts;
/// <summary>Free and total space of the disk that holds a folder.</summary>
/// <param name="AvailableBytes">Space Febe can still use.</param>
/// <param name="TotalBytes">Size of the disk.</param>
public sealed record FreeSpace(long AvailableBytes, long TotalBytes)
{
/// <summary>Free share between 0 and 1 (1 when the size is unknown).</summary>
public double Ratio => TotalBytes <= 0 ? 1 : Math.Clamp((double)AvailableBytes / TotalBytes, 0, 1);
}
/// <summary>Measures the free space of the disk of a folder (tests use a fake).</summary>
public interface IFreeSpaceProbe
{
/// <summary>The space of the disk that holds <paramref name="folder"/>; null when it cannot be measured.</summary>
FreeSpace? Measure(string folder);
}
/// <summary>
/// <see cref="DriveInfo"/> on the nearest existing folder: on Linux any path of the file system (statvfs, so an Unraid
/// user share reports its own free space), on Windows the drive of the path. Network paths that Windows cannot
/// measure this way (\\server\share) give null: no alert rather than a wrong one.
/// </summary>
public sealed class DriveFreeSpaceProbe : IFreeSpaceProbe
{
public FreeSpace? Measure(string folder)
{
if (string.IsNullOrWhiteSpace(folder))
{
return null;
}
try
{
var existing = Path.GetFullPath(folder);
while (!Directory.Exists(existing))
{
var parent = Path.GetDirectoryName(existing);
if (parent is null || parent == existing)
{
return null;
}
existing = parent;
}
var drive = new DriveInfo(existing);
return new FreeSpace(drive.AvailableFreeSpace, drive.TotalSize);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.Security.SecurityException)
{
return null;
}
}
}
/// <summary>
/// When a disk counts as «quasi pieno»: fewer than <see cref="MinimumFreeBytes"/> free, or less than
/// <see cref="MinimumFreeRatio"/> of the disk free, whichever comes first (10 GB or 5% by default).
/// </summary>
public sealed record DiskThresholds(long MinimumFreeBytes, double MinimumFreeRatio)
{
public static DiskThresholds Default { get; } = new(10L * 1024 * 1024 * 1024, 0.05);
public bool IsLow(FreeSpace space)
{
ArgumentNullException.ThrowIfNull(space);
return space.AvailableBytes < MinimumFreeBytes || (space.TotalBytes > 0 && space.Ratio < MinimumFreeRatio);
}
}
/// <summary>A folder whose disk is watched.</summary>
/// <param name="Key">Stable key: «libreria», «dati».</param>
/// <param name="Name">Italian name: «libreria», «cartella dei dati».</param>
/// <param name="Path">The folder.</param>
public sealed record WatchedFolder(string Key, string Name, string Path)
{
public static WatchedFolder Library(string path) => new("libreria", "libreria", path);
public static WatchedFolder Data(string path) => new("dati", "cartella dei dati", path);
}
/// <summary>The outcome of one check of the watched folders.</summary>
/// <param name="Low">Folders whose disk is almost full, with their space.</param>
/// <param name="Unmeasured">Folders that could not be measured.</param>
public sealed record DiskCheck(IReadOnlyList<(WatchedFolder Folder, FreeSpace Space)> Low, IReadOnlyList<WatchedFolder> Unmeasured)
{
/// <summary>The set of low folders as a key: «dati», «libreria+dati».</summary>
public string Key => string.Join('+', Low.Select(l => l.Folder.Key));
/// <summary>
/// The Italian text of the alert: how much space is left on which disk, what Febe does, what to do. Two folders on
/// the same disk (same size and free space) are named together.
/// </summary>
public string Describe()
{
var groups = Low.GroupBy(l => (l.Space.TotalBytes, l.Space.AvailableBytes / (1024 * 1024 * 1024))).ToList();
var parts = groups.Select(g =>
{
var space = g.First().Space;
var names = string.Join(" e ", g.Select(x => "della " + x.Folder.Name));
var percent = ItalianText.Decimal(space.Ratio * 100, 1);
return $"sul disco {names} restano {ItalianText.Bytes(space.AvailableBytes)} liberi su {ItalianText.Bytes(space.TotalBytes)} ({percent}%)";
});
var text = ItalianText.Capitalize(string.Join("; ", parts)) + ".";
var data = Low.Any(l => l.Folder.Key == "dati");
var library = Low.Any(l => l.Folder.Key == "libreria");
if (library)
{
text += " Continuo a lavorare, ma con il disco pieno gli scaricamenti non riusciranno.";
}
if (data)
{
text += " Con il disco dei dati pieno il database non può più salvare nulla.";
}
return text + " Che cosa fare: libera spazio su quel disco o sposta la cartella su un disco più capiente (guida, «Problemi comuni»).";
}
}
+283
View File
@@ -0,0 +1,283 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Febe.Core.Alerts;
/// <summary>How a call to Telegram went.</summary>
public enum TelegramOutcome
{
Sent,
/// <summary>Token or chat identifier missing.</summary>
NotConfigured,
/// <summary>The token does not have the shape of a bot token: nothing was sent.</summary>
MalformedToken,
/// <summary>Telegram does not know the token (401, 404).</summary>
InvalidToken,
/// <summary>Telegram does not know the chat (400 «chat not found»).</summary>
ChatNotFound,
/// <summary>Any other 400.</summary>
Rejected,
/// <summary>The bot may not write to that chat (403: blocked, never started, not in the group).</summary>
Forbidden,
/// <summary>Too many messages (429).</summary>
RateLimited,
/// <summary>Other answers (5xx, unexpected bodies).</summary>
ServerError,
/// <summary>No answer within the timeout.</summary>
Timeout,
/// <summary>No connection (DNS, network, TLS).</summary>
Unreachable,
}
/// <summary>Result of one call: the outcome and an Italian sentence that says what to do. Never contains the token.</summary>
public sealed record TelegramResult(TelegramOutcome Outcome, string Message)
{
public bool Sent => Outcome == TelegramOutcome.Sent;
}
/// <summary>
/// The Telegram Bot API, the only call Febe makes: one HTTPS POST to <c>https://api.telegram.org/bot&lt;token&gt;/sendMessage</c>
/// with <see cref="HttpClient"/> and no library (spec §13.3). The address contains the bot token, so it is never
/// logged, never put in a message and never part of an exception that leaves this class; response bodies are read
/// only to tell a missing chat from other refusals, and never stored.
/// </summary>
public sealed partial class TelegramClient : IDisposable
{
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(15);
/// <summary>Longest text sent (Telegram accepts 4096 characters).</summary>
public const int MaxTextLength = 3500;
private const int MaxBodyBytes = 64 * 1024;
// A string, not a base Uri: «bot123:ABC» relative to a base would read as an address with the scheme «bot123».
private const string Api = "https://api.telegram.org/";
private readonly HttpClient _http;
private readonly TimeSpan _timeout;
/// <param name="handler">Tests pass a fake handler; null uses a pooled handler of its own.</param>
/// <param name="timeout">How long a call may take (15 seconds by default).</param>
public TelegramClient(HttpMessageHandler? handler = null, TimeSpan? timeout = null)
{
_timeout = timeout ?? DefaultTimeout;
_http = handler is null
? new HttpClient(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(10), ConnectTimeout = _timeout }, disposeHandler: true)
: new HttpClient(handler, disposeHandler: false);
// The timeout is enforced with a token of our own, to tell it apart from a cancellation of the caller.
_http.Timeout = Timeout.InfiniteTimeSpan;
}
/// <summary>A bot token has the shape «digits:letters» (what BotFather gives); anything else is refused before any call.</summary>
public static bool IsValidToken(string? token) => token is not null && TokenShape().IsMatch(token);
/// <summary>
/// Sends <paramref name="text"/> (plain text, no formatting) to <paramref name="chatId"/>. Delivery problems come
/// back as a <see cref="TelegramResult"/>; only a cancellation of <paramref name="ct"/> throws.
/// </summary>
public async Task<TelegramResult> SendMessageAsync(string? token, string? chatId, string text, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(text);
if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(chatId))
{
return Result(TelegramOutcome.NotConfigured);
}
token = token.Trim();
if (!IsValidToken(token))
{
return Result(TelegramOutcome.MalformedToken);
}
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(_timeout);
try
{
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(Api + "bot" + token + "/sendMessage", UriKind.Absolute));
request.Content = new ByteArrayContent(Body(chatId.Trim(), text));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
var body = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false);
return Classify(response.StatusCode, body);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (OperationCanceledException)
{
return Result(TelegramOutcome.Timeout);
}
catch (HttpRequestException)
{
// The exception text may name the host: it is not passed on, only the outcome.
return Result(TelegramOutcome.Unreachable);
}
catch (IOException)
{
return Result(TelegramOutcome.Unreachable);
}
}
/// <summary>The Italian sentence for an outcome: what happened and what to do.</summary>
public string Describe(TelegramOutcome outcome) => outcome switch
{
TelegramOutcome.Sent => "Messaggio inviato su Telegram.",
TelegramOutcome.NotConfigured => "Scrivi il gettone del bot e l'identificativo della chat, salva, poi invia la prova.",
TelegramOutcome.MalformedToken => "Il gettone del bot non ha la forma giusta (cifre, due punti, poi una lunga serie di lettere): copialo per intero dal messaggio di BotFather.",
TelegramOutcome.InvalidToken => "Telegram non riconosce il gettone del bot: copialo di nuovo per intero dal messaggio di BotFather.",
TelegramOutcome.ChatNotFound => "Telegram non trova la chat: controlla l'identificativo e scrivi almeno un messaggio al bot prima di riprovare.",
TelegramOutcome.Rejected => "Telegram ha rifiutato il messaggio: controlla l'identificativo della chat.",
TelegramOutcome.Forbidden => "Il bot non può scriverti: apri la chat con il bot su Telegram e premi «Avvia» (o sbloccalo; in un gruppo, aggiungilo), poi riprova.",
TelegramOutcome.RateLimited => "Telegram chiede di aspettare prima di altri messaggi: riprova fra qualche minuto.",
TelegramOutcome.ServerError => "Telegram ha risposto con un errore: riprova più tardi.",
TelegramOutcome.Timeout => $"Telegram non ha risposto entro {Math.Max(1, Math.Ceiling(_timeout.TotalSeconds)).ToString("0", CultureInfo.InvariantCulture)} secondi: controlla la connessione a Internet di Febe e riprova.",
TelegramOutcome.Unreachable => "Telegram non è raggiungibile: controlla la connessione a Internet di Febe (in Docker, quella del contenitore) e riprova.",
_ => "Invio a Telegram non riuscito.",
};
public void Dispose() => _http.Dispose();
private TelegramResult Result(TelegramOutcome outcome) => new(outcome, Describe(outcome));
private TelegramResult Classify(HttpStatusCode status, string body)
{
var code = (int)status;
if (code is >= 200 and < 300)
{
return Result(OkField(body) == false ? TelegramOutcome.ServerError : TelegramOutcome.Sent);
}
return Result(code switch
{
401 or 404 => TelegramOutcome.InvalidToken,
400 when Description(body)?.Contains("chat not found", StringComparison.OrdinalIgnoreCase) == true => TelegramOutcome.ChatNotFound,
400 => TelegramOutcome.Rejected,
403 => TelegramOutcome.Forbidden,
429 => TelegramOutcome.RateLimited,
_ => TelegramOutcome.ServerError,
});
}
private static byte[] Body(string chatId, string text)
{
if (text.Length > MaxTextLength)
{
text = text[..MaxTextLength] + "…";
}
using var stream = new MemoryStream();
using (var json = new Utf8JsonWriter(stream))
{
json.WriteStartObject();
json.WriteString("chat_id", chatId);
json.WriteString("text", text);
json.WriteBoolean("disable_web_page_preview", true);
json.WriteEndObject();
}
return stream.ToArray();
}
private static async Task<string> ReadLimitedAsync(HttpContent content, CancellationToken ct)
{
var stream = await content.ReadAsStreamAsync(ct).ConfigureAwait(false);
await using (stream.ConfigureAwait(false))
{
var buffer = new byte[MaxBodyBytes];
var total = 0;
int read;
while (total < buffer.Length && (read = await stream.ReadAsync(buffer.AsMemory(total), ct).ConfigureAwait(false)) > 0)
{
total += read;
}
return Encoding.UTF8.GetString(buffer, 0, total);
}
}
private static bool? OkField(string body)
{
try
{
using var document = JsonDocument.Parse(body);
return document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty("ok", out var ok) && ok.ValueKind is JsonValueKind.True or JsonValueKind.False
? ok.GetBoolean()
: null;
}
catch (JsonException)
{
return null;
}
}
private static string? Description(string body)
{
try
{
using var document = JsonDocument.Parse(body);
return document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty("description", out var d) && d.ValueKind == JsonValueKind.String
? d.GetString()
: null;
}
catch (JsonException)
{
return null;
}
}
[GeneratedRegex(@"^[0-9]{1,20}:[A-Za-z0-9_-]{10,200}$", RegexOptions.CultureInvariant)]
private static partial Regex TokenShape();
}
/// <summary>
/// The Telegram channel of the alerts and the real «Invia una prova» of Impostazioni ▸ Notifiche (spec §13.3): on when
/// both the bot token and the chat identifier are set.
/// </summary>
public sealed class TelegramAlertChannel(TelegramClient client) : IAlertChannel, IAlertTestSender
{
/// <summary>Text of the test message.</summary>
public const string TestText = "Febe · Prova degli avvisi\nSe leggi questo messaggio, gli avvisi di Febe arriveranno qui.";
private readonly TelegramClient _client = client ?? throw new ArgumentNullException(nameof(client));
public string Name => "Telegram";
public bool IsEnabled(AlertSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
return settings.TelegramConfigured;
}
public async Task<AlertDelivery> SendAsync(Alert alert, AlertSettings settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(alert);
ArgumentNullException.ThrowIfNull(settings);
var result = await _client.SendMessageAsync(settings.TelegramToken, settings.TelegramChatId, alert.TelegramText, ct).ConfigureAwait(false);
return result.Sent ? AlertDelivery.Ok : new AlertDelivery(false, result.Message);
}
public async Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(settings);
var result = await _client.SendMessageAsync(settings.TelegramToken, settings.TelegramChatId, TestText, ct).ConfigureAwait(false);
return result.Sent
? new AlertTestResult(true, "Messaggio di prova inviato: controlla la chat del bot su Telegram.")
: new AlertTestResult(false, "Nessun messaggio è partito. " + result.Message);
}
}
+1 -1
View File
@@ -711,7 +711,7 @@ internal sealed class SessionComposer
}
await RecordRecipeFailureAsync(kind, account, EngineEventCodes.FormatUnrecognized,
$"Formato non riconosciuto in {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
$"Formato non riconosciuto durante {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
break;
case RecipeStatus.AccountUnreachable:
+3
View File
@@ -137,6 +137,9 @@ public sealed record EventQuery
public DateTimeOffset? From { get; init; }
public DateTimeOffset? To { get; init; }
/// <summary>Only these codes (null: every code).</summary>
public IReadOnlyCollection<string>? Codes { get; init; }
}
/// <summary>Local copy of the list of profiles Alberto follows (spec §4.2, §8.3 <c>following</c>).</summary>