using System.Globalization; using System.Text.Json; using Febe.Core.Abstractions; using Febe.Core.Alerts; using Febe.Core.Collection.Diagnostics; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; using Febe.Web.Demo; using Febe.Web.Engine; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; namespace Febe.Web.Api; /// /// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the /// stops, the still frame of the browser, the probable duplicates waiting for Alberto, the diagnostic report. /// public static class ActivityApi { /// Days of stops shown by the page. public const int HistoryDays = 14; /// /// «Esporta il rapporto di diagnostica» (issue #39, spec §7.9): the traces of the engine sessions of the last two /// weeks as a JSON file to send, with no data value in it. Also answered with a configuration problem, where the /// engine never started and the report is empty. /// public const string DiagnosticsPath = "/api/engine/diagnostica"; public static void Map(IEndpointRouteBuilder endpoints) { 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); var dto = frame is null ? new BrowserPreviewDto(false, null, null, null) : new BrowserPreviewDto(true, WithoutQuery(frame.Url), frame.At.ToUnixTimeMilliseconds(), "/api/browser/preview/frame?v=" + frame.At.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture)); return ApiHttp.Json(dto, FebeJsonContext.Default.BrowserPreviewDto); }); endpoints.MapGet("/api/browser/preview/frame", async (HttpContext context, IBrowserPreview preview, CancellationToken ct) => { var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false); if (frame is null) { throw new NotFoundException("Nessuna immagine del browser in questo momento."); } context.Response.Headers.CacheControl = "no-store"; return Results.Bytes(frame.Jpeg, "image/jpeg"); }); endpoints.MapGet("/api/duplicates/count", async (IFebeStorage storage, CancellationToken ct) => { var download = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Download, ct).ConfigureAwait(false); var import = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct).ConfigureAwait(false); return ApiHttp.Json(new DuplicateCountsDto(download, import), FebeJsonContext.Default.DuplicateCountsDto); }); endpoints.MapGet(DiagnosticsPath, async (HttpContext context, IDiagnosticSource source, FebeWebOptions options, IClock clock, CancellationToken ct) => { var gathered = await source.GatherAsync(ct).ConfigureAwait(false); var now = clock.Now; var zone = clock.LocalZone; var edition = options.Demo ? DemoRequest.Edition(context) ?? FebeEdition.Desktop : options.Edition; // Written whole before answering: a failure becomes an error message, never half a file. using var buffer = new MemoryStream(); DiagnosticReport.Write( buffer, gathered.Traces, new DiagnosticReportHeader( options.Version, EditionName(edition), now, zone, DamagedLines: gathered.DamagedLines, RecorderFaults: gathered.RecorderFaults, UnreadableFiles: gathered.UnreadableFiles, UnfinishedSessions: gathered.UnfinishedSessions)); context.Response.Headers.ContentDisposition = $"attachment; filename=\"{DiagnosticReport.FileName(now, zone)}\""; context.Response.Headers.CacheControl = "no-store"; return Results.Bytes(buffer.ToArray(), "application/json; charset=utf-8"); }); } /// The «edizione» of the diagnostic report. public static string EditionName(FebeEdition edition) => edition == FebeEdition.Desktop ? "windows" : "docker"; public static async Task IncidentsAsync(IIncidentHistory history, IClock clock, CancellationToken ct) { ArgumentNullException.ThrowIfNull(history); ArgumentNullException.ThrowIfNull(clock); var now = clock.Now; var zone = clock.LocalZone; var items = await history.ListAsync(now - TimeSpan.FromDays(HistoryDays), now + TimeSpan.FromMinutes(1), ct).ConfigureAwait(false); var dtos = items.Select(i => new IncidentDto( i.Id, ApiMapping.Local(i.At, now, zone), Level(i.Level), Title(i.Level), i.Signal, WithoutQuery(i.Url), i.StoppedUntil is { } until ? ApiMapping.Local(until, now, zone) : null, i.ResolvedAt is { } resolved ? ApiMapping.Local(resolved, now, zone) : null, i.IsOpen, i.Note)).ToList(); var throttles = items.Count(i => i.Level == SignalLevel.Throttle && i.At >= now - TimeSpan.FromDays(7)); var advice = throttles >= 3 ? $"{ItalianText.Count(throttles, "rallentamento", "rallentamenti")} negli ultimi sette giorni: conviene passare a un profilo più prudente o seguire meno account (Impostazioni, Limiti e comportamento)." : null; return new IncidentListDto(dtos, throttles, advice); } /// The alerts of the last days (at most 50), from the timeline. public static async Task 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", SignalLevel.Challenge => "challenge", _ => "disconnect", }; public static string Title(SignalLevel level) => level switch { SignalLevel.Throttle => "Rallentamento", SignalLevel.Challenge => "Verifica richiesta", _ => "Disconnessione", }; /// An address without its query string and fragment (signed addresses never reach the page). public static string? WithoutQuery(string? url) { if (string.IsNullOrWhiteSpace(url)) { return null; } var cut = url.IndexOfAny(['?', '#']); return cut < 0 ? url : url[..cut]; } }