Unione dell'ondata 5 (desktop M6, rifiniture M8): avvisi collegati una sola volta nella composizione condivisa per le due vesti

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

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 22:04:54 +00:00
commit 5be0b1dee8
62 files changed
+4168 -327

No files matched your search

-203
View File
@@ -1,203 +0,0 @@
using System.Threading.Channels;
using Febe.Core.Alerts;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
namespace Febe.App;
/// <summary>The events of spec §13.3 that deserve an alert besides the red strip of the interface.</summary>
public enum AlertKind
{
/// <summary>«Verifica richiesta».</summary>
Verification,
/// <summary>«Disconnessione».</summary>
Disconnection,
/// <summary>«Fermo per rallentamento e ripresa».</summary>
Throttle,
/// <summary>«Storico di un account completato».</summary>
BackfillDone,
/// <summary>«Disco quasi pieno».</summary>
DiskLow,
/// <summary>«Formato non riconosciuto».</summary>
UnknownFormat,
}
/// <summary>One alert: Italian title and text, no captions, bodies, cookies or addresses (spec §13.2).</summary>
public sealed record FebeAlert(AlertKind Kind, string Title, string Message, DateTimeOffset At, long? AccountId);
/// <summary>
/// A channel alerts go to besides the red strip (spec §13.3): Windows notifications on the desktop; Telegram (M8)
/// registers its own. Registered by the shells in DI as <c>IAlertChannel</c>; <see cref="AlertDispatcher"/> calls them.
/// </summary>
public interface IAlertChannel
{
/// <summary>Whether this channel is on with the settings of Impostazioni, Notifiche.</summary>
bool IsEnabled(AlertSettings settings);
/// <summary>Sends one alert. Never logs the message or any address of the channel.</summary>
Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct);
}
/// <summary>Which engine events become alerts (spec §13.3), and whether Alberto wants them.</summary>
public static class AlertRules
{
/// <summary>Code of the «disco quasi pieno» event, for whoever measures the free space (M8).</summary>
public const string DiskLowCode = "disco-quasi-pieno";
private const int MaxMessage = 240;
/// <summary>The alert for a timeline event, or null when the event is not one of §13.3.</summary>
public static FebeAlert? FromEvent(EventRecord record)
{
ArgumentNullException.ThrowIfNull(record);
(AlertKind Kind, string Title)? match = record.Code switch
{
EngineEventCodes.ChallengeStop => (AlertKind.Verification, "Instagram chiede una verifica"),
EngineEventCodes.DisconnectStop => (AlertKind.Disconnection, "Febe è stato scollegato da Instagram"),
EngineEventCodes.ThrottleStop => (AlertKind.Throttle, "Febe si è fermato per un rallentamento"),
EngineEventCodes.ThrottleEnd => (AlertKind.Throttle, "Il fermo per rallentamento è finito"),
EngineEventCodes.Resumed => (AlertKind.Throttle, "Febe ha ripreso"),
EngineEventCodes.BackfillCompleted => (AlertKind.BackfillDone, "Storico completato"),
EngineEventCodes.FormatUnrecognized => (AlertKind.UnknownFormat, "Formato non riconosciuto"),
DiskLowCode => (AlertKind.DiskLow, "Disco quasi pieno"),
_ => null,
};
if (match is not { } m)
{
return null;
}
var text = record.Message.Length > MaxMessage ? record.Message[..(MaxMessage - 1)] + "…" : record.Message;
return new FebeAlert(m.Kind, m.Title, text, record.At, record.AccountId);
}
/// <summary>True when Alberto wants alerts of this kind (Impostazioni, Notifiche).</summary>
public static bool Wanted(AlertKind kind, AlertEvents events)
{
ArgumentNullException.ThrowIfNull(events);
return kind switch
{
AlertKind.Verification => events.Verification,
AlertKind.Disconnection => events.Disconnection,
AlertKind.Throttle => events.Throttle,
AlertKind.BackfillDone => events.BackfillDone,
AlertKind.DiskLow => events.DiskLow,
AlertKind.UnknownFormat => events.UnknownFormat,
_ => false,
};
}
}
/// <summary>
/// The alerts hook of the shared composition (spec §13.3): listens to the engine's timeline, turns the events of §13.3
/// into <see cref="FebeAlert"/>s and hands them, in order and off the engine's thread, to every enabled
/// <see cref="IAlertChannel"/>. A channel that fails is logged by type only and never stops the others.
/// </summary>
public sealed class AlertDispatcher : IAsyncDisposable
{
private readonly EngineEvents _events;
private readonly ISettingsStore _settings;
private readonly IReadOnlyList<IAlertChannel> _channels;
private readonly FebeLog _log;
private readonly Channel<FebeAlert> _queue = Channel.CreateBounded<FebeAlert>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
private readonly CancellationTokenSource _stop = new();
private readonly Task _loop;
public AlertDispatcher(EngineEvents events, ISettingsStore settings, IEnumerable<IAlertChannel> channels, FebeLog log)
{
_events = events ?? throw new ArgumentNullException(nameof(events));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_channels = [.. channels ?? throw new ArgumentNullException(nameof(channels))];
_log = log ?? throw new ArgumentNullException(nameof(log));
_events.Notified += OnNotified;
_loop = Task.Run(() => RunAsync(_stop.Token));
}
/// <summary>The channels alerts go to.</summary>
public IReadOnlyList<IAlertChannel> Channels => _channels;
/// <summary>Alerts sent since the start (tests).</summary>
public int Sent => Volatile.Read(ref _sent);
private int _sent;
public async ValueTask DisposeAsync()
{
_events.Notified -= OnNotified;
_queue.Writer.TryComplete();
await _stop.CancelAsync().ConfigureAwait(false);
try
{
await _loop.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
_stop.Dispose();
}
private void OnNotified(object? sender, EngineNotification notification)
{
if (_channels.Count == 0 || notification.Kind != EngineNotificationKind.Event || notification.Event is not { } record)
{
return;
}
if (AlertRules.FromEvent(record) is { } alert)
{
_queue.Writer.TryWrite(alert);
}
}
private async Task RunAsync(CancellationToken ct)
{
await foreach (var alert in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
AlertSettings settings;
try
{
settings = await AlertSettingsStore.LoadAsync(_settings, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
_log.Warn("avvisi", "Impostazioni degli avvisi non leggibili: avviso non inviato.", ex);
continue;
}
if (!AlertRules.Wanted(alert.Kind, settings.Events))
{
continue;
}
foreach (var channel in _channels)
{
if (!channel.IsEnabled(settings))
{
continue;
}
try
{
await channel.SendAsync(alert, settings, ct).ConfigureAwait(false);
Interlocked.Increment(ref _sent);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Type only: the message of a channel's exception could contain its address (Telegram's has the token).
_log.Warn("avvisi", $"Un avviso non è partito ({channel.GetType().Name}: {ex.GetType().Name}).");
}
}
}
}
}
+32 -9
View File
@@ -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,6 +13,7 @@ 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;
@@ -25,7 +27,8 @@ namespace Febe.App;
/// in Docker, Data folder not writable or on a network share, WebView2 missing on Windows) neither the engine nor the
/// browser start, and the interface shows only the page that explains it. Otherwise: database, library, thumbnails,
/// perceptual hashes, import, daily backup, the browser of the platform, the collection pipeline, the download queue,
/// the engine, the connection, the alerts hook and the interface. Disposing stops everything in order.
/// the engine, the connection, the alerts (Windows notifications through the shell, Telegram, free disk space) and the
/// interface. Disposing stops everything in order.
/// </summary>
public sealed class FebeApp : IAsyncDisposable
{
@@ -36,6 +39,7 @@ public sealed class FebeApp : IAsyncDisposable
private readonly List<IDisposable> _disposables = [];
private readonly List<Action> _unsubscribe = [];
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
private TelegramClient? _telegram;
private string? _temporaryFolder;
private int _disposed;
@@ -85,8 +89,11 @@ public sealed class FebeApp : IAsyncDisposable
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
public BrowserUseTracker Tracker { get; } = new();
/// <summary>The alerts hook (null with a configuration problem).</summary>
public AlertDispatcher? Alerts { get; private set; }
/// <summary>
/// The alerts of spec §13.3 (null with a configuration problem): Windows notifications through the shell's
/// <see cref="INativeShell"/> (silent in Docker), Telegram, and the free space of the library and the Data folder.
/// </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;
@@ -246,6 +253,8 @@ public sealed class FebeApp : IAsyncDisposable
EventHandler<bool> drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
browser.UserDriving.Changed += drivingChanged;
_unsubscribe.Add(() => browser.UserDriving.Changed -= drivingChanged);
_telegram = new TelegramClient(hooks.TelegramHandler);
var telegramChannel = new TelegramAlertChannel(_telegram);
await StartWebAsync(hooks, s =>
{
@@ -266,6 +275,7 @@ public sealed class FebeApp : IAsyncDisposable
}
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
s.AddSingleton<IAlertTestSender>(telegramChannel);
_platform.RegisterServices(s, this);
}).ConfigureAwait(false);
@@ -275,14 +285,28 @@ public sealed class FebeApp : IAsyncDisposable
await Web.Services.GetRequiredService<Febe.Web.Import.ImportHub>().GetAsync(ct).ConfigureAwait(false);
}
// The alerts hook: the channels the shell registered (Windows notifications; Telegram with M8).
Alerts = new AlertDispatcher(services.Events, Database.Settings, Web.Services.GetServices<IAlertChannel>(), Log);
// Alerts (spec §13.3): from the engine's timeline and the free space of the two folders, to the shell's
// notifications (the desktop's; in Docker the shell cannot notify and the channel stays silent) and Telegram.
// The strip of the interface is the engine snapshot's. The library folder is read at every check: on Windows
// it can change in Impostazioni while Febe runs.
Alerts = new AlertService(
Database.Settings,
Clock,
services.Events,
[new NativeShellAlertChannel(Web.Services.GetRequiredService<INativeShell>()), telegramChannel],
new AlertServiceOptions
{
FolderSource = () => [WatchedFolder.Library(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();
// 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(FebeAppHooks hooks, Action<IServiceCollection> register)
@@ -570,10 +594,9 @@ public sealed class FebeApp : IAsyncDisposable
unsubscribe();
}
if (Alerts is { } alerts)
{
await Quietly(() => alerts.DisposeAsync().AsTask()).ConfigureAwait(false);
}
// Alerts in flight are cancelled before the Telegram client goes away.
Alerts?.Dispose();
_telegram?.Dispose();
if (Import is { } import)
{
+9 -1
View File
@@ -1,5 +1,6 @@
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Web;
@@ -35,7 +36,8 @@ public interface IFebePlatform
/// <summary>
/// Services of this shell for a normal start, registered before the web layer (whose fallbacks use TryAdd):
/// native shell, browser window, remote view, change of the Data folder, alert channels.
/// native shell (its notifications are the Windows channel of the alerts), browser window, remote view, change of
/// the Data folder.
/// </summary>
void RegisterServices(IServiceCollection services, FebeApp app);
@@ -115,4 +117,10 @@ public sealed record FebeAppHooks
/// <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; }
}