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

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

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

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Engine.Support;
using Febe.Web.Native;
namespace Febe.Tests.Alerts.Support;
/// <summary>
/// The engine's services on a temporary database and a virtual clock (<see cref="EngineTestBed"/>), with an
/// <see cref="AlertService"/> listening to them: a fake desktop shell, a fake Telegram, a fake free-space probe on two
/// folders. Telegram and Windows notifications are switched on unless asked otherwise.
/// </summary>
internal sealed class AlertBed : IAsyncDisposable
{
public const string Token = "4839574812:AAF-tokendiprova_SegretoDaNonMostrare";
public const string Chat = "-100123456";
public const string LibraryFolder = "/prova/libreria";
public const string DataFolder = "/prova/dati";
private AlertBed(EngineTestBed engine, AlertService alerts, FakeNativeShell shell, FakeTelegramHandler telegram, FakeFreeSpaceProbe disk, AlertLogRecorder log, TelegramClient client)
{
Engine = engine;
Alerts = alerts;
Shell = shell;
Telegram = telegram;
Disk = disk;
Log = log;
Client = client;
}
public EngineTestBed Engine { get; }
public AlertService Alerts { get; }
public FakeNativeShell Shell { get; }
public FakeTelegramHandler Telegram { get; }
public FakeFreeSpaceProbe Disk { get; }
public AlertLogRecorder Log { get; }
public TelegramClient Client { get; }
public List<AlertOutcome> Outcomes { get; } = [];
public static async Task<AlertBed> CreateAsync(bool telegram = true, bool windows = true, AlertEvents? events = null, TimeSpan? telegramTimeout = null, DateTimeOffset? start = null)
{
var engine = await EngineTestBed.CreateAsync(start);
await AlertSettingsStore.SaveAsync(engine.Db.Settings, new AlertSettings(events ?? AlertEvents.All, windows, telegram ? Chat : null, telegram ? Token : null));
var shell = new FakeNativeShell();
var handler = new FakeTelegramHandler();
var disk = new FakeFreeSpaceProbe();
var log = new AlertLogRecorder();
var client = new TelegramClient(handler, telegramTimeout);
var alerts = new AlertService(
engine.Db.Settings,
engine.Clock,
engine.Services.Events,
[new NativeShellAlertChannel(shell), new TelegramAlertChannel(client)],
new AlertServiceOptions
{
Folders = [WatchedFolder.Library(LibraryFolder), WatchedFolder.Data(DataFolder)],
FreeSpace = disk,
Log = log.Write,
}).Attach();
var bed = new AlertBed(engine, alerts, shell, handler, disk, log, client);
alerts.Handled += (_, outcome) =>
{
lock (bed.Outcomes)
{
bed.Outcomes.Add(outcome);
}
};
return bed;
}
/// <summary>Reports a signal through the circuit breaker and waits for its incident, its event and its alert.</summary>
public async Task ReportAsync(SignalLevel level, string code = "segnale-prova")
{
await Engine.Breaker.ReportAsync(new Signal(level, code, "https://sito.prova/x", Engine.Clock.Now));
await Engine.Breaker.FlushAsync();
await Alerts.FlushAsync();
}
/// <summary>Writes a timeline event as the engine does and waits for its alert.</summary>
public async Task WriteEventAsync(EventSeverity severity, string code, string message, long? accountId = null)
{
await Engine.Services.Events.WriteAsync(severity, code, message, accountId);
await Alerts.FlushAsync();
}
/// <summary>Everything the bed recorded that leaves Febe or stays on disk: log lines, events, alert texts.</summary>
public async Task<string> EverythingWrittenAsync()
{
var events = await Engine.Db.Events.ListAsync(new EventQuery { Limit = 1000 });
var settings = await Engine.Db.Settings.GetAllAsync();
return string.Join(
"\n",
new[] { Log.All }
.Concat(events.Select(e => e.Code + " " + e.Message))
.Concat(Shell.Notifications.Select(n => n.Title + " " + n.Message))
.Concat(Telegram.Requests.Select(r => r.Body))
.Concat(Outcomes.SelectMany(o => o.Deliveries.Select(d => d.Delivery.Problem ?? string.Empty)))
.Concat(settings.Where(s => s.Key != AlertSettingKeys.TelegramToken).Select(s => s.Key + "=" + s.Value)));
}
public async ValueTask DisposeAsync()
{
Alerts.Dispose();
Client.Dispose();
await Engine.DisposeAsync();
}
}
@@ -0,0 +1,117 @@
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.Core.Alerts;
using Febe.Web.Native;
namespace Febe.Tests.Alerts.Support;
/// <summary>A request that reached the fake Telegram.</summary>
/// <param name="Method">HTTP method.</param>
/// <param name="Uri">Full address (it contains the token: tests check it here, nowhere else).</param>
/// <param name="ContentType">Media type of the body.</param>
/// <param name="Body">The JSON body.</param>
internal sealed record TelegramRequest(HttpMethod Method, Uri Uri, string? ContentType, string Body)
{
public string ChatId => JsonDocument.Parse(Body).RootElement.GetProperty("chat_id").GetString()!;
public string Text => JsonDocument.Parse(Body).RootElement.GetProperty("text").GetString()!;
}
/// <summary>
/// Telegram's Bot API, faked: records every request and answers with <see cref="Respond"/> (by default
/// <c>200 {"ok":true}</c>). Never touches the network: the real api.telegram.org is never contacted from tests.
/// </summary>
internal sealed class FakeTelegramHandler : HttpMessageHandler
{
private readonly ConcurrentQueue<TelegramRequest> _requests = new();
public Func<TelegramRequest, CancellationToken, Task<HttpResponseMessage>>? Respond { get; set; }
public IReadOnlyList<TelegramRequest> Requests => [.. _requests];
public static HttpResponseMessage Answer(HttpStatusCode status, string json) =>
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
/// <summary>Answers with <paramref name="status"/> and the usual error body of the Bot API.</summary>
public void Fail(HttpStatusCode status, string description) =>
Respond = (_, _) => Task.FromResult(Answer(status, $$"""{"ok":false,"error_code":{{(int)status}},"description":"{{description}}"}"""));
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken);
var recorded = new TelegramRequest(request.Method, request.RequestUri!, request.Content?.Headers.ContentType?.MediaType, body);
_requests.Enqueue(recorded);
return Respond is { } respond
? await respond(recorded, cancellationToken)
: Answer(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
}
}
/// <summary>The desktop shell, faked: it can notify and records the notifications.</summary>
internal sealed class FakeNativeShell(bool canNotify = true) : INativeShell
{
private readonly ConcurrentQueue<(string Title, string Message)> _notifications = new();
public IReadOnlyList<(string Title, string Message)> Notifications => [.. _notifications];
public bool Throws { get; set; }
public bool CanPickFolder => false;
public bool CanShowInFolder => false;
public bool CanOpenUrl => false;
public bool CanNotify { get; } = canNotify;
public bool SupportsAutostart => false;
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult<string?>(null);
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false);
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
public Task NotifyAsync(string title, string message, CancellationToken ct)
{
if (Throws)
{
throw new InvalidOperationException("notifiche spente");
}
_notifications.Enqueue((title, message));
return Task.CompletedTask;
}
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
}
/// <summary>Free space by folder, as the test decides.</summary>
internal sealed class FakeFreeSpaceProbe : IFreeSpaceProbe
{
private readonly ConcurrentDictionary<string, FreeSpace?> _spaces = new(StringComparer.Ordinal);
public const long GB = 1024L * 1024 * 1024;
public void Set(string folder, long availableBytes, long totalBytes) => _spaces[folder] = new FreeSpace(availableBytes, totalBytes);
public void Unmeasurable(string folder) => _spaces[folder] = null;
public FreeSpace? Measure(string folder) => _spaces.TryGetValue(folder, out var space) ? space : new FreeSpace(500 * GB, 1000 * GB);
}
/// <summary>The log lines of the alert service.</summary>
internal sealed class AlertLogRecorder
{
private readonly ConcurrentQueue<(AlertLogLevel Level, string Message)> _lines = new();
public IReadOnlyList<(AlertLogLevel Level, string Message)> Lines => [.. _lines];
public string All => string.Join("\n", _lines.Select(l => l.Message));
public void Write(AlertLogLevel level, string message) => _lines.Enqueue((level, message));
}