using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Core.Alerts;
/// The alerts of spec §13.3, one per kind of event worth telling Alberto about outside the interface.
public enum AlertKind
{
/// «Verifica richiesta»: stopped, needs Alberto in the browser and «Riprendi».
Verification,
/// «Disconnessione»: the Instagram session is gone, needs a new login and «Riprendi».
Disconnection,
/// «Fermo per rallentamento»: timed stop after a throttle.
ThrottleStop,
/// «…e ripresa»: the timed stop is over and Febe works again.
ThrottleEnd,
/// «Storico di un account completato».
BackfillDone,
/// «Formato non riconosciuto»: a reader met an unknown shape.
UnknownFormat,
/// A recipe suspended after three problems in a row (same switch as ).
RecipeSuspended,
/// «Disco quasi pieno»: the library or the Data folder is running out of space.
DiskLow,
}
///
/// One alert: what happened (), what Febe did and what Alberto should do (),
/// both short Italian sentences. Never contains captions, cookies, tokens or signed addresses.
///
/// Which alert.
/// When the event happened.
/// «Instagram chiede una verifica».
/// «Ho fermato tutto alle 14:32 e non riparto da solo. Che cosa fare: …».
/// De-duplication key inside the kind (an account, a set of folders); empty for one per kind.
/// Account concerned, if any.
public sealed record Alert(AlertKind Kind, DateTimeOffset At, string Title, string Message, string Key = "", long? AccountId = null)
{
/// The text of a Telegram message: title on the first line, then the message.
public string TelegramText => "Febe · " + Title + "\n" + Message;
}
/// Outcome of one channel for one alert.
/// The channel accepted the alert.
/// Italian reason when not sent; never contains addresses or tokens.
public sealed record AlertDelivery(bool Sent, string? Problem = null)
{
public static AlertDelivery Ok { get; } = new(true);
}
///
/// 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).
///
public interface IAlertChannel
{
/// Italian name for the log and the timeline: «Telegram», «notifica di Windows».
string Name { get; }
/// The channel is available here and switched on in the settings.
bool IsEnabled(AlertSettings settings);
/// Sends the alert. Never throws for delivery problems: they come back as .
Task SendAsync(Alert alert, AlertSettings settings, CancellationToken ct);
}
/// Levels of the alert service's own log lines.
public enum AlertLogLevel
{
Information,
Warning,
}
/// Event codes written by the alert service (the others come from the engine, ).
public static class AlertEventCodes
{
/// The library or the Data folder is almost full (spec §13.3).
public const string DiskLow = "disco-quasi-pieno";
/// An alert could not be delivered on a channel (never an alert itself).
public const string DeliveryFailed = "avviso-non-inviato";
}
///
/// 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.
///
public static class AlertCatalog
{
/// Codes shown in the «Avvisi» list of the Dashboard: the alerts and the failed deliveries.
public static IReadOnlyList Codes { get; } =
[
EngineEventCodes.ChallengeStop,
EngineEventCodes.DisconnectStop,
EngineEventCodes.ThrottleStop,
EngineEventCodes.ThrottleEnd,
EngineEventCodes.BackfillCompleted,
EngineEventCodes.FormatUnrecognized,
EngineEventCodes.RecipeSuspended,
AlertEventCodes.DiskLow,
AlertEventCodes.DeliveryFailed,
];
/// The alert kind of a timeline event code, if it is one.
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,
};
/// What happened, in a few words: the title of the notification.
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",
};
/// The switch of Impostazioni ▸ Notifiche that governs the kind.
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,
};
}
///
/// 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.
///
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),
};
///
/// 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).
///
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);
}
///
/// 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 the Dashboard).
///
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,
};
}