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:
50 files changed
+3980
-28
No files matched your search
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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»).";
|
||||
}
|
||||
}
|
||||
@@ -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<token>/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);
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -460,10 +460,11 @@ internal sealed class EventStore(FebeDatabase db) : IEventStore
|
||||
{
|
||||
var command = c.Command(string.Empty);
|
||||
var list = command.AddList("sv", severities);
|
||||
var codes = query.Codes is { } wanted ? $" AND code IN ({command.AddList("cd", wanted)})" : string.Empty;
|
||||
command.CommandText = $"""
|
||||
SELECT {Columns} FROM event
|
||||
WHERE (@before IS NULL OR id < @before) AND (@a IS NULL OR account_id = @a) AND severity IN ({list})
|
||||
AND (@f IS NULL OR at >= @f) AND (@t IS NULL OR at < @t)
|
||||
AND (@f IS NULL OR at >= @f) AND (@t IS NULL OR at < @t){codes}
|
||||
ORDER BY id DESC LIMIT @limit
|
||||
""";
|
||||
command.With("@before", Sql.Int(query.BeforeId)).With("@a", Sql.Int(query.AccountId))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -12,9 +13,11 @@ using Febe.Web;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
@@ -32,6 +35,12 @@ internal sealed record ServerHooks
|
||||
|
||||
/// <summary>How long the web host waits for open requests (events, remote view) when stopping.</summary>
|
||||
public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>Fake Telegram (tests never reach the real API).</summary>
|
||||
public HttpMessageHandler? TelegramHandler { get; init; }
|
||||
|
||||
/// <summary>Fake free-space probe for the «Disco quasi pieno» alert.</summary>
|
||||
public IFreeSpaceProbe? FreeSpace { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -89,6 +98,9 @@ internal sealed class FebeServer : IAsyncDisposable
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
|
||||
/// <summary>The alerts of spec §13.3 (Telegram; Windows notifications through the shell, on the desktop).</summary>
|
||||
public AlertService? Alerts { get; private set; }
|
||||
|
||||
/// <summary>Completes when browser, pipeline and engine are running (never, with a configuration problem).</summary>
|
||||
public Task Running => _running.Task;
|
||||
|
||||
@@ -241,6 +253,8 @@ internal sealed class FebeServer : IAsyncDisposable
|
||||
Engine = engine;
|
||||
connection.AttachEngine(engine);
|
||||
browser.Host.UserDriving.Changed += (_, _) => engine.NotifyUserDrivingChanged();
|
||||
var telegram = new TelegramClient(hooks.TelegramHandler);
|
||||
var telegramChannel = new TelegramAlertChannel(telegram);
|
||||
|
||||
await StartWebAsync(hooks, s =>
|
||||
{
|
||||
@@ -258,13 +272,31 @@ internal sealed class FebeServer : IAsyncDisposable
|
||||
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
|
||||
s.AddSingleton(Import);
|
||||
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
|
||||
s.AddSingleton<IAlertTestSender>(telegramChannel);
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
// Alerts (spec §13.3): from the engine's timeline and the free space of the two folders, to the shell's
|
||||
// notifications (none in Docker) and Telegram. The strip of the interface is the engine snapshot's.
|
||||
Alerts = new AlertService(
|
||||
Database.Settings,
|
||||
Clock,
|
||||
services.Events,
|
||||
[new NativeShellAlertChannel(Web.Services.GetRequiredService<INativeShell>()), telegramChannel],
|
||||
new AlertServiceOptions
|
||||
{
|
||||
Folders = [WatchedFolder.Library(layout.Root), WatchedFolder.Data(data.Root)],
|
||||
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
|
||||
Log = (level, message) => _log.Write(level == AlertLogLevel.Warning ? LogLevel.Warning : LogLevel.Information, "avvisi", message),
|
||||
}).Attach();
|
||||
_disposables.Add(Alerts);
|
||||
_disposables.Add(telegram);
|
||||
|
||||
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
|
||||
var lifetime = _lifetime.Token;
|
||||
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => Alerts.WatchDiskSpaceAsync(lifetime), CancellationToken.None));
|
||||
}
|
||||
|
||||
private async Task StartWebAsync(ServerHooks hooks, Action<IServiceCollection> register)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -24,6 +26,9 @@ public static class ActivityApi
|
||||
endpoints.MapGet("/api/engine/incidents", async (IIncidentHistory history, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await IncidentsAsync(history, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.IncidentListDto));
|
||||
|
||||
endpoints.MapGet("/api/alerts", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await AlertsAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AlertListDto));
|
||||
|
||||
endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) =>
|
||||
{
|
||||
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
|
||||
@@ -78,6 +83,37 @@ public static class ActivityApi
|
||||
return new IncidentListDto(dtos, throttles, advice);
|
||||
}
|
||||
|
||||
/// <summary>The alerts of the last <see cref="HistoryDays"/> days (at most 50), from the timeline.</summary>
|
||||
public static async Task<AlertListDto> AlertsAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var now = clock.Now;
|
||||
var zone = clock.LocalZone;
|
||||
var events = await storage.Events.ListAsync(
|
||||
new EventQuery { From = now - TimeSpan.FromDays(HistoryDays), Codes = AlertCatalog.Codes, Limit = 50 },
|
||||
ct).ConfigureAwait(false);
|
||||
var items = events.Select(e =>
|
||||
{
|
||||
var kind = AlertCatalog.KindOf(e.Code);
|
||||
return new AlertItemDto(
|
||||
e.Id,
|
||||
ApiMapping.Local(e.At, now, zone),
|
||||
kind is { } k ? JsonNamingPolicy.CamelCase.ConvertName(k.ToString()) : "deliveryFailed",
|
||||
e.Severity switch
|
||||
{
|
||||
EventSeverity.Error => "error",
|
||||
EventSeverity.Warning => "warning",
|
||||
EventSeverity.Success => "success",
|
||||
_ => "info",
|
||||
},
|
||||
kind is { } known ? AlertCatalog.Title(known) : "Avviso non inviato",
|
||||
kind is { } alert ? AlertCatalog.FromEvent(alert, e, zone).Message : e.Message,
|
||||
e.AccountId);
|
||||
}).ToList();
|
||||
return new AlertListDto(items, HistoryDays);
|
||||
}
|
||||
|
||||
public static string Level(SignalLevel level) => level switch
|
||||
{
|
||||
SignalLevel.Throttle => "throttle",
|
||||
|
||||
@@ -39,6 +39,22 @@ public static class EngineApi
|
||||
return ApiHttp.Json(new ResumeDto(result.Resumed, result.Message), FebeJsonContext.Default.ResumeDto);
|
||||
});
|
||||
|
||||
// «Riattiva» a recipe suspended after three unknown formats (or targets not found) in a row.
|
||||
endpoints.MapPost("/api/engine/recipes/{recipe}/resume", async (string recipe, IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
if (!Enum.TryParse<RecipeKind>(recipe, ignoreCase: true, out var kind) || !Enum.IsDefined(kind))
|
||||
{
|
||||
throw new BadRequestException("Ricetta sconosciuta.");
|
||||
}
|
||||
|
||||
var resumed = await control.ResumeRecipeAsync(kind, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(
|
||||
new ResumeDto(resumed, resumed
|
||||
? "Ricetta riattivata: riprende alla prossima sessione. Se il formato è ancora sconosciuto, si sospende di nuovo dopo tre volte."
|
||||
: "Questa ricetta non era sospesa."),
|
||||
FebeJsonContext.Default.ResumeDto);
|
||||
});
|
||||
|
||||
// «Apri il browser» on Windows: the window of the browser comes to the front.
|
||||
endpoints.MapPost("/api/browser/show", async (IBrowserWindow browser, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
|
||||
@@ -48,6 +48,7 @@ namespace Febe.Web.Api;
|
||||
[JsonSerializable(typeof(BeginDrivingRequest))]
|
||||
[JsonSerializable(typeof(FinishDto))]
|
||||
[JsonSerializable(typeof(IncidentListDto))]
|
||||
[JsonSerializable(typeof(AlertListDto))]
|
||||
[JsonSerializable(typeof(BrowserPreviewDto))]
|
||||
[JsonSerializable(typeof(DuplicateCountsDto))]
|
||||
[JsonSerializable(typeof(GeneralSettingsDto))]
|
||||
|
||||
@@ -32,6 +32,16 @@ public sealed record IncidentDto(
|
||||
/// <param name="Advice">«Tre rallentamenti in sette giorni»: the proposal of spec §7.6, or null.</param>
|
||||
public sealed record IncidentListDto(IReadOnlyList<IncidentDto> Items, int ThrottlesLastWeek, string? Advice);
|
||||
|
||||
/// <summary>
|
||||
/// A line of the «Avvisi» list of Attività (spec §13.3): an alert or a failed delivery. <see cref="Kind"/>:
|
||||
/// verification, disconnection, throttleStop, throttleEnd, backfillDone, unknownFormat, recipeSuspended, diskLow,
|
||||
/// deliveryFailed. <see cref="Level"/>: error, warning, success, info.
|
||||
/// </summary>
|
||||
public sealed record AlertItemDto(long Id, LocalTimeDto At, string Kind, string Level, string Title, string Message, long? AccountId);
|
||||
|
||||
/// <summary><c>GET /api/alerts</c>: the alerts of the last <see cref="Days"/> days, newest first.</summary>
|
||||
public sealed record AlertListDto(IReadOnlyList<AlertItemDto> Items, int Days);
|
||||
|
||||
/// <summary>The preview of Febe's browser: <see cref="Frame"/> is the address of the JPEG (with a version), or null.</summary>
|
||||
public sealed record BrowserPreviewDto(bool HasFrame, string? Url, long? At, string? Frame);
|
||||
|
||||
|
||||
@@ -152,9 +152,9 @@ public static class SettingsApi
|
||||
}
|
||||
|
||||
var token = body.RemoveTelegramToken ? null : string.IsNullOrWhiteSpace(body.TelegramToken) ? stored.TelegramToken : body.TelegramToken.Trim();
|
||||
if (token is not null && (token.Length > 200 || token.Any(char.IsWhiteSpace)))
|
||||
if (token is not null && !TelegramClient.IsValidToken(token))
|
||||
{
|
||||
throw new BadRequestException("Il gettone del bot non è valido: copialo per intero dal messaggio di BotFather, senza spazi.");
|
||||
throw new BadRequestException("Il gettone del bot non è valido: copialo per intero dal messaggio di BotFather (cifre, due punti, poi una lunga serie di lettere), senza spazi.");
|
||||
}
|
||||
|
||||
var e = body.Events;
|
||||
@@ -186,7 +186,7 @@ public static class SettingsApi
|
||||
throw new BadRequestException("Scrivi il gettone del bot e l'identificativo della chat, salva, poi invia la prova.");
|
||||
}
|
||||
|
||||
var sender = d.Services.GetService(typeof(IAlertTestSender)) as IAlertTestSender ?? new TelegramNotAvailableYet();
|
||||
var sender = d.Services.GetService(typeof(IAlertTestSender)) as IAlertTestSender ?? new NoTelegramSender();
|
||||
var result = await sender.SendTelegramTestAsync(settings, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(new AlertTestDto(result.Sent, result.Message), FebeJsonContext.Default.AlertTestDto);
|
||||
});
|
||||
@@ -522,7 +522,7 @@ public static class SettingsApi
|
||||
SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock).Notifications,
|
||||
settings.TelegramChatId,
|
||||
!string.IsNullOrWhiteSpace(settings.TelegramToken),
|
||||
sender is not null and not TelegramNotAvailableYet);
|
||||
sender is not null and not NoTelegramSender);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- Dati
|
||||
|
||||
@@ -492,6 +492,20 @@ public static class DemoSeeder
|
||||
withNews == 0 ? "Giro dei profili che segui: nessuna novità" : $"Giro dei profili che segui: {withNews} contenuti nuovi", null));
|
||||
}
|
||||
|
||||
// The alerts of the last days (Attività, «Avvisi»): the throttle of three days ago (as DemoIncidentHistory) and
|
||||
// its end, and the backfills completed in the last two weeks.
|
||||
var throttle = LocalCalendar.StartOfDay(today.AddDays(-3), zone) + TimeSpan.FromHours(18.4);
|
||||
var throttleEnd = throttle + TimeSpan.FromHours(1);
|
||||
events.Add(Event(throttle, EventSeverity.Warning, Core.Engine.EngineEventCodes.ThrottleStop,
|
||||
$"Instagram ha chiesto di rallentare (segnale http-429). Ho chiuso la sessione e mi fermo per 1 ora, fino {Core.Engine.ItalianText.AtDay(throttleEnd, throttle, zone)}. Poi i tetti restano dimezzati per 48 ore.", null));
|
||||
events.Add(Event(throttleEnd, EventSeverity.Info, Core.Engine.EngineEventCodes.ThrottleEnd,
|
||||
$"Fine del fermo per rallentamento. Riprendo con i tetti dimezzati fino {Core.Engine.ItalianText.AtDay(throttleEnd + TimeSpan.FromHours(48), throttleEnd, zone)}.", null));
|
||||
foreach (var (spec, account) in accounts.Where(a => a.Account.BackfillCompletedAt is { } done && done > now - TimeSpan.FromDays(14) && done < now))
|
||||
{
|
||||
events.Add(Event(account.BackfillCompletedAt!.Value, EventSeverity.Success, Core.Engine.EngineEventCodes.BackfillCompleted,
|
||||
$"Storico di @{account.Username} completato: {Core.Engine.ItalianText.Count(spec.Posts, "post", "post")} in libreria. Da ora lo tengo aggiornato.", account.Id));
|
||||
}
|
||||
|
||||
foreach (var e in events.OrderBy(e => e.At))
|
||||
{
|
||||
await storage.Events.AppendAsync(e, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -26,6 +26,12 @@ public interface IEngineControl
|
||||
|
||||
/// <summary>Accounts were added, removed or changed: the engine brings its queue in step.</summary>
|
||||
Task NotifyAccountsChangedAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// «Riattiva» a recipe suspended after three problems in a row (unknown formats, targets not found). False when it
|
||||
/// was not suspended or there is no engine.
|
||||
/// </summary>
|
||||
Task<bool> ResumeRecipeAsync(RecipeKind recipe, CancellationToken ct) => Task.FromResult(false);
|
||||
}
|
||||
|
||||
/// <summary>The commands of the interface on the real engine.</summary>
|
||||
@@ -41,6 +47,8 @@ public sealed class EngineHostControl(EngineHost host) : IEngineControl
|
||||
public Task RequestFollowingListAsync(CancellationToken ct) => host.RequestFollowingListAsync(ct);
|
||||
|
||||
public Task NotifyAccountsChangedAsync(CancellationToken ct) => host.NotifyAccountsChangedAsync(ct);
|
||||
|
||||
public Task<bool> ResumeRecipeAsync(RecipeKind recipe, CancellationToken ct) => host.ResumeRecipeAsync(recipe, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -68,7 +68,7 @@ public static class FebeWeb
|
||||
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
||||
services.TryAddSingleton<IBrowserPreview, NoBrowserPreview>();
|
||||
services.TryAddSingleton<IIncidentHistory>(sp => new StoredIncidentHistory(sp.GetRequiredService<IFebeStorage>()));
|
||||
services.TryAddSingleton<IAlertTestSender, TelegramNotAvailableYet>();
|
||||
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
|
||||
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
|
||||
services.TryAddSingleton<FolderSizes>();
|
||||
services.TryAddSingleton<RebuildJob>();
|
||||
|
||||
@@ -17,7 +17,7 @@ Qui sotto le convenzioni per chi continua il lavoro (composizione di Server e De
|
||||
| `Library/` | `FebeLibrary` (archivio + disposizione, `HashIndex`, `DownloadDuplicates`), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente, `IDataFolderChange`, `FolderSizes`, `RebuildJob` |
|
||||
| `Connection/` | Contratto condiviso con il lato server del collegamento: `IConnectionService`, `IConfigurationProblems`, `PROTOCOLLO.md` (vista remota `/api/vista`); `UnavailableConnectionService` è il ripiego |
|
||||
| `Import/` | `ImportHub`: l'`ImportService` registrato dalla composizione, oppure uno costruito sulla libreria |
|
||||
| `Native/` | `INativeShell` (funzioni del sistema) e `IBrowserWindow` (finestra del browser), con le versioni «niente» |
|
||||
| `Native/` | `INativeShell` (funzioni del sistema) e `IBrowserWindow` (finestra del browser), con le versioni «niente»; `NativeShellAlertChannel`: le notifiche di Windows come canale degli avvisi |
|
||||
| `Demo/` | Modalità dimostrativa: dati finti coerenti, motore finto con scene, guscio finto |
|
||||
| `wwwroot/` | Interfaccia: HTML, CSS, moduli ES senza framework né build |
|
||||
|
||||
@@ -60,7 +60,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
|
||||
| `IEngineSettingsControl` | `StoredEngineSettingsControl`: salva le impostazioni del motore nell'archivio | `new EngineHostSettingsControl(engineHost)`: le applica anche al motore che gira |
|
||||
| `IBrowserPreview` | `NoBrowserPreview` (nessuna anteprima) | Chi ha il browser: `GetLatestAsync` restituisce l'ultima schermata JPEG (`BrowserFrame`) con l'indirizzo |
|
||||
| `IIncidentHistory` | `StoredIncidentHistory` (dall'archivio) | Di solito nessuno |
|
||||
| `IAlertTestSender` (Core) | `TelegramNotAvailableYet`: nessun messaggio parte, la risposta lo dice | M8, l'invio vero dei messaggi Telegram |
|
||||
| `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione: `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` |
|
||||
| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop (M6): sposta la cartella al riavvio |
|
||||
| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) |
|
||||
|
||||
@@ -102,13 +102,15 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
| `GET /api/library?cursor=&direction=older\|newer&limit=` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q` |
|
||||
| `GET /api/library/tiles?ids=` | Tessere per chiave |
|
||||
| `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) |
|
||||
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV |
|
||||
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) |
|
||||
| `GET /api/accounts`, `GET /api/accounts/{id}`, `GET /{id}/history` | Elenco con conteggi, scheda, cronologia |
|
||||
| `POST /api/accounts/{id}/plan`, `PUT /{id}/settings`, `POST /{id}/keep-updated`, `/pause`, `/resume`, `/check-now`, `/remove`, `/pick-folder`, `/open-on-instagram` | Impostazioni dell'account e comandi |
|
||||
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account» |
|
||||
| `GET /accesso`, `POST /api/accesso`, `POST /api/uscita` | Accesso con password |
|
||||
| `GET /api/connection`, `POST /api/connection/begin` (`{ openLogin }`), `/finish`, `/cancel`, `/disconnect` | Collegamento a Instagram (`IConnectionService`, §6.4): stato `notConnected`, `connected`, `verificationRequired`, `browserUnavailable` |
|
||||
| `GET /api/engine/incidents` | Incidenti degli ultimi 14 giorni (rallentamenti, verifiche, arresti), con un consiglio dopo 3 rallentamenti in 7 giorni |
|
||||
| `POST /api/engine/recipes/{ricetta}/resume` | «Riattiva» una ricetta sospesa dopo tre problemi di fila (`IEngineControl.ResumeRecipeAsync`: metodo con un'implementazione predefinita che risponde «non era sospesa», così le altre implementazioni non cambiano). Attività mostra le ricette sospese da `snapshot.suspendedRecipes` |
|
||||
| `GET /api/alerts` | Avvisi degli ultimi 14 giorni (§13.3, sezione «Avvisi» di Attività): righe della cronologia con i codici di `AlertCatalog.Codes`, compresi gli avvisi non arrivati |
|
||||
| `GET /api/browser/preview`, `GET /api/browser/preview/frame` | Anteprima del browser in Attività: indirizzo e immagine JPEG (`no-store`, 404 se non c'è) |
|
||||
| `GET /api/duplicates/count`, `GET /api/duplicates?after=`, `POST /api/duplicates/{pairId}` (`{ decision, applyToAll }`) | Doppioni dopo uno scaricamento (§9.5): `keepLarger`, `keepExisting`, `keepBoth`; niente si decide da solo |
|
||||
| `GET/PUT /api/settings/general`, `POST /api/settings/naming-preview`, `/pick-folder`, `/data-folder` | Cartelle (cambio della libreria solo desktop), schema dei nomi con anteprima, tema, avvio, area di notifica |
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using Febe.Core.Alerts;
|
||||
|
||||
namespace Febe.Web.Native;
|
||||
|
||||
/// <summary>
|
||||
/// Windows notifications as an alert channel (spec §12, §13.3): <see cref="INativeShell.NotifyAsync"/> with the title
|
||||
/// and the message of the alert. On when the shell can notify (the desktop) and «Notifiche di Windows» is on; in
|
||||
/// Docker <see cref="BrowserShell"/> cannot notify and the channel stays silent.
|
||||
/// </summary>
|
||||
public sealed class NativeShellAlertChannel(INativeShell shell) : IAlertChannel
|
||||
{
|
||||
private readonly INativeShell _shell = shell ?? throw new ArgumentNullException(nameof(shell));
|
||||
|
||||
public string Name => "notifica di Windows";
|
||||
|
||||
public bool IsEnabled(AlertSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return _shell.CanNotify && settings.WindowsNotifications;
|
||||
}
|
||||
|
||||
public async Task<AlertDelivery> SendAsync(Alert alert, AlertSettings settings, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(alert);
|
||||
try
|
||||
{
|
||||
await _shell.NotifyAsync(alert.Title, alert.Message, ct).ConfigureAwait(false);
|
||||
return AlertDelivery.Ok;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
return new AlertDelivery(false, $"Windows non ha mostrato la notifica ({ex.GetType().Name})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -339,6 +339,13 @@ input[type=range].cursore::-webkit-slider-thumb{-webkit-appearance:none;width:16
|
||||
input[type=range].cursore::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--superficie);border:1.5px solid var(--testo-2)}
|
||||
input[type=range].cursore:focus-visible{outline:2px solid var(--accento);outline-offset:3px}
|
||||
.grandezza{display:flex;align-items:center;gap:8px;color:var(--testo-2)}
|
||||
.btn.solo-icona{padding:0 8px}
|
||||
/* Libreria: when the tools do not fit in one row (a duplicates link, a narrow screen above 1000 px) the group on
|
||||
the right goes to a second row instead of squeezing the kind chips into a column. */
|
||||
@media (min-width:1001px){
|
||||
.strumenti:has(> div > .filtri){flex-wrap:wrap;row-gap:10px}
|
||||
.strumenti .filtri{flex-wrap:nowrap;flex-shrink:0}
|
||||
}
|
||||
|
||||
/* menu a comparsa */
|
||||
.menu{position:fixed;z-index:60;min-width:200px;max-width:340px;max-height:min(420px,70vh);overflow:auto;background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello);box-shadow:var(--ombra-menu);padding:6px}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Attività (mockups 06 and 11, spec §7.9): what the engine is doing now with a still frame of the browser every few
|
||||
// seconds, the strip of the day, «Limiti di oggi» with the four main budgets and «Tutti i tetti», the queue with
|
||||
// «verso le» times, «Appena fatto» with the outcomes, and the stops of the last days. It updates by itself from the
|
||||
// event stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
|
||||
// «verso le» times, «Appena fatto» with the outcomes, the stops of the last days and the alerts (spec §13.3: also the
|
||||
// ones that are not stops, like a backfill completed or a disk almost full). It updates by itself from the event
|
||||
// stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
|
||||
|
||||
import { api, withCarried } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
@@ -22,10 +23,12 @@ export default {
|
||||
const today = h('section.blocco');
|
||||
const budgets = h('section.blocco');
|
||||
const lists = h('div.due-colonne');
|
||||
const suspended = h('div');
|
||||
const incidents = h('section.blocco');
|
||||
const alerts = h('section.blocco', { hidden: true });
|
||||
// On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11).
|
||||
page.root.dataset.pagina = 'attivita';
|
||||
fill(page.body, h('div.attivita', now, today, budgets, lists, notice, incidents));
|
||||
fill(page.body, h('div.attivita', now, suspended, today, budgets, lists, notice, incidents, alerts));
|
||||
|
||||
let latest = null;
|
||||
page.onEngine((state) => {
|
||||
@@ -35,17 +38,20 @@ export default {
|
||||
drawToday(today, state);
|
||||
drawBudgets(budgets, state);
|
||||
drawLists(lists, state);
|
||||
drawSuspended(suspended, state);
|
||||
preview.update(state);
|
||||
});
|
||||
|
||||
async function loadSide() {
|
||||
try {
|
||||
const [counts, history] = await Promise.all([
|
||||
const [counts, history, recent] = await Promise.all([
|
||||
api('/api/duplicates/count', { signal: page.signal }),
|
||||
api('/api/engine/incidents', { signal: page.signal }),
|
||||
api('/api/alerts', { signal: page.signal }),
|
||||
]);
|
||||
drawNotice(notice, counts);
|
||||
drawIncidents(incidents, history);
|
||||
drawAlerts(alerts, recent);
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') showError(error);
|
||||
}
|
||||
@@ -287,6 +293,56 @@ function drawNotice(box, counts) {
|
||||
h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi'))));
|
||||
}
|
||||
|
||||
/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */
|
||||
function drawSuspended(box, state) {
|
||||
const items = state.snapshot.suspendedRecipes || [];
|
||||
if (!items.length) {
|
||||
box.replaceChildren();
|
||||
return;
|
||||
}
|
||||
fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } },
|
||||
icon('octagon-alert', 's'),
|
||||
h('span', t('attivita.sospesa', { nome: r.name })),
|
||||
h('button.btn.piccolo', {
|
||||
type: 'button',
|
||||
onclick: async () => {
|
||||
try {
|
||||
const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' });
|
||||
toast(result.message, result.resumed ? '' : 'errore');
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
},
|
||||
}, t('attivita.riattiva')))));
|
||||
}
|
||||
|
||||
const ALERT_LOOK = {
|
||||
error: { icon: 'octagon-alert', label: 'rosso' },
|
||||
warning: { icon: 'triangle-alert', label: 'ambra' },
|
||||
success: { icon: 'circle-check', label: 'verde' },
|
||||
info: { icon: 'bell', label: '' },
|
||||
};
|
||||
|
||||
/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */
|
||||
function drawAlerts(box, recent) {
|
||||
const items = (recent && recent.items) || [];
|
||||
box.hidden = !items.length;
|
||||
if (!items.length) {
|
||||
box.replaceChildren();
|
||||
return;
|
||||
}
|
||||
fill(box,
|
||||
h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))),
|
||||
h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => {
|
||||
const look = ALERT_LOOK[i.level] || ALERT_LOOK.info;
|
||||
return h('li',
|
||||
h('span.quando.dati', capitalize(at(i.at))),
|
||||
h('div.chi-cosa', h('b', i.title), h('span', i.message)),
|
||||
label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon));
|
||||
}))));
|
||||
}
|
||||
|
||||
function drawIncidents(box, history) {
|
||||
const items = history.items || [];
|
||||
fill(box,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Libreria (mockup 01, spec §4.6): every entry by publication day, filters by kind, account, period and provenance,
|
||||
// search by account name and caption, tile size, multiple selection to export or delete, viewer on click.
|
||||
// «Esporta l'elenco» in the tools row exports what the filter shows (spec §4.8: CSV with «;», UTF-8 with BOM).
|
||||
|
||||
import { api, download, withCarried } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
@@ -91,6 +92,8 @@ export default {
|
||||
const size = local.get('libreria.tessere', 160);
|
||||
const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') });
|
||||
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
|
||||
// Icon only, like the tile size: the row of the mockup has no room for one more label.
|
||||
const exportButton = h('button.btn.nudo.piccolo.solo-icona.solo-largo', { type: 'button', title: t('libreria.esportaAiuto'), 'aria-label': t('libreria.esporta') }, icon('file-down'));
|
||||
// Probable duplicates after a download wait for Alberto (spec §9.5): a short link to their review.
|
||||
const duplicates = h('a.btn.nudo.piccolo.doppioni-link', { href: withCarried('/doppioni'), hidden: true });
|
||||
api('/api/duplicates/count', { signal: page.signal }).then((counts) => {
|
||||
@@ -104,6 +107,7 @@ export default {
|
||||
filtersButton,
|
||||
h('div.destra',
|
||||
duplicates,
|
||||
exportButton,
|
||||
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
|
||||
selectButton)));
|
||||
|
||||
@@ -287,6 +291,7 @@ export default {
|
||||
}
|
||||
|
||||
selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting));
|
||||
exportButton.addEventListener('click', () => exportFiltered());
|
||||
|
||||
async function exportSelected() {
|
||||
try {
|
||||
@@ -297,6 +302,18 @@ export default {
|
||||
}
|
||||
}
|
||||
|
||||
async function exportFiltered() {
|
||||
exportButton.disabled = true;
|
||||
try {
|
||||
await download('/api/entries/export', { query: apiQuery(state, today()) }, 'febe-elementi.csv');
|
||||
toast(t(filtersActive() ? 'libreria.esportatoFiltro' : 'libreria.esportato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
exportButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelected() {
|
||||
const ids = [...mosaic.selected];
|
||||
const removed = await confirmDelete(ids);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Impostazioni, Notifiche (spec §13.3): which events notify, Windows notifications (desktop only), Telegram with the
|
||||
// bot token (masked, never shown again once saved, never logged) and the chat identifier, and «Invia una prova».
|
||||
// The Telegram sender arrives with milestone M8: until then the server answers plainly that nothing was sent.
|
||||
// Telegram: one HTTPS call from the server (TelegramAlertChannel); where no sender is registered (demonstration) the
|
||||
// page says that no message leaves.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
|
||||
@@ -131,6 +131,10 @@
|
||||
"nessunoTesto": "Cambia o togli un filtro per vedere altro.",
|
||||
"togliFiltri": "Togli i filtri",
|
||||
"doppioni": "1 doppione da decidere|{n} doppioni da decidere",
|
||||
"esporta": "Esporta l'elenco",
|
||||
"esportaAiuto": "Esporta l'elenco: un file CSV con gli elementi mostrati dai filtri di adesso, che si apre in Excel",
|
||||
"esportato": "Elenco esportato: il file CSV è nei download del browser.",
|
||||
"esportatoFiltro": "Elenco degli elementi filtrati esportato: il file CSV è nei download del browser.",
|
||||
"tessera": "{tipo} di @{account}, {quando}",
|
||||
"tesseraFile": "{n} file",
|
||||
"tesseraDurata": "video di {durata}",
|
||||
@@ -530,6 +534,11 @@
|
||||
"aperto": "In corso",
|
||||
"risolto": "Risolto {quando}",
|
||||
"fermoFino": "Fermo fino {quando}",
|
||||
"avvisi": "Avvisi",
|
||||
"sospesa": "«{nome}» è sospeso: tre risposte di fila in un formato non riconosciuto, o un comando non trovato nella pagina. Instagram potrebbe essere cambiato: serve un campione nuovo con la sonda (guida, «Problemi comuni»), poi riattivalo.",
|
||||
"riattiva": "Riattiva",
|
||||
"avvisiAiuto": "Gli ultimi {giorni} giorni: gli stessi che arrivano su Telegram e nelle notifiche, se li hai attivati in Impostazioni, Notifiche.",
|
||||
"livelliAvviso": { "error": "Fermo", "warning": "Attenzione", "success": "Fatto", "info": "Informazione" },
|
||||
"doppioni": "1 doppione probabile dopo gli ultimi scaricamenti aspetta la tua scelta.|{n} doppioni probabili dopo gli ultimi scaricamenti aspettano la tua scelta.",
|
||||
"decidi": "Decidi",
|
||||
"chiesto": "Chiesto da te"
|
||||
@@ -721,7 +730,7 @@
|
||||
"soloWindows": "Solo versione Windows",
|
||||
"prova": "Invia una prova",
|
||||
"telegram": "Telegram",
|
||||
"telegramAiuto": "Facoltativo. Crea un bot con BotFather, scrivigli un messaggio, poi copia qui il suo gettone e l'identificativo della chat.",
|
||||
"telegramAiuto": "Facoltativo. Crea un bot con BotFather, scrivigli un messaggio, poi copia qui il suo gettone e l'identificativo della chat: la guida, alla pagina «Avvisi e Telegram», spiega come.",
|
||||
"gettone": "Gettone del bot",
|
||||
"gettoneSalvato": "Gettone salvato: per cambiarlo scrivine uno nuovo",
|
||||
"gettoneVuoto": "Incolla il gettone di BotFather",
|
||||
@@ -730,7 +739,7 @@
|
||||
"chat": "Identificativo della chat",
|
||||
"chatEsempio": "Per esempio 123456789",
|
||||
"gettoneNota": "Il gettone resta nella cartella dei dati di Febe: non finisce nei registri e non viene più mostrato.",
|
||||
"nonAncora": "L'invio dei messaggi Telegram arriva con una prossima versione di Febe: per ora le impostazioni si salvano soltanto."
|
||||
"nonAncora": "Questa istanza di Febe non invia messaggi Telegram (dimostrazione o prova): le impostazioni si salvano soltanto."
|
||||
},
|
||||
"dati": {
|
||||
"cartella": "Cartella dei dati",
|
||||
|
||||
Reference in new issue
Block a user