Interfaccia web, parte 1: ospite, sicurezza, API, modalità dimostrativa, libreria, visualizzatore e account
Febe.Web: AddFebeWeb/UseFebe/FebeWebHost per le due vesti, interfaccia incorporata con IFileProvider proprio, indirizzi italiani, API JSON con contesto generato, eventi SSE, controlli di Host/Origin, gettone del desktop e password con blocco (§13.1), INativeShell e capacità per veste. Modalità --demo con 38 account e circa 18.000 elementi finti e scene del motore. Pagine Libreria, Visualizzatore, Account, Aggiungi account e Scheda account (contenuti, impostazioni con piano, cronologia); schermate in docs/schermate con le differenze dai mockup; prove delle API, della sicurezza, dell'esportazione CSV e dei dati dimostrativi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
76 files changed
+12503
-17
No files matched your search
@@ -0,0 +1,257 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace Febe.Web.Api;
|
||||
|
||||
/// <summary>The engine for the interface: snapshot, «Metti in pausa», «Riprendi», the browser, and the event stream.</summary>
|
||||
public static class EngineApi
|
||||
{
|
||||
/// <summary>Idle time after which a comment line keeps the event stream open through proxies.</summary>
|
||||
public static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(25);
|
||||
|
||||
/// <summary>The snapshot is pushed again at least this often, so «8 min fa» and «verso le» stay current.</summary>
|
||||
public static readonly TimeSpan Refresh = TimeSpan.FromSeconds(60);
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
|
||||
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
await control.PauseAsync(ct).ConfigureAwait(false);
|
||||
return ApiHttp.Message("Febe è in pausa: non apre nulla finché non premi «Riprendi».");
|
||||
});
|
||||
|
||||
endpoints.MapPost("/api/engine/resume", async (IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
var result = await control.ResumeAsync(ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(new ResumeDto(result.Resumed, result.Message), 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) =>
|
||||
{
|
||||
if (!browser.IsSeparateWindow)
|
||||
{
|
||||
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
|
||||
}
|
||||
|
||||
await browser.ShowAsync(ct).ConfigureAwait(false);
|
||||
tracker.MarkUsed(clock.Now);
|
||||
return ApiHttp.Message("Il browser di Febe è in primo piano.");
|
||||
});
|
||||
|
||||
// The Browser page («Ho finito») and the desktop window report that Alberto used the browser: «Riprendi» activates.
|
||||
endpoints.MapPost("/api/browser/used", (BrowserUseTracker tracker, IClock clock) =>
|
||||
{
|
||||
tracker.MarkUsed(clock.Now);
|
||||
return ApiHttp.Message("Bene: ora puoi premere «Riprendi».");
|
||||
});
|
||||
|
||||
endpoints.MapGet("/api/eventi", StreamAsync);
|
||||
}
|
||||
|
||||
/// <summary>The engine as the interface needs it.</summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(monitor);
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(tracker);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
|
||||
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
var state = snapshot.Mode switch
|
||||
{
|
||||
EngineMode.NotConnected => "notConnected",
|
||||
EngineMode.StoppedForVerification => "verification",
|
||||
EngineMode.Disconnected => "disconnected",
|
||||
_ => mine is null ? "notConnected" : "connected",
|
||||
};
|
||||
var connection = state == "notConnected"
|
||||
? new ConnectionDto(state, null, null, null)
|
||||
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
|
||||
|
||||
bool canResume;
|
||||
if (snapshot.Banner is { NeedsResume: true })
|
||||
{
|
||||
var since = snapshot.Breaker.LastSignal?.At ?? DateTimeOffset.MinValue;
|
||||
canResume = tracker.LastUsedAt is { } used && used >= since;
|
||||
}
|
||||
else
|
||||
{
|
||||
canResume = snapshot.Mode == EngineMode.Paused;
|
||||
}
|
||||
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, connection, canResume);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/eventi</c>: server-sent events. <c>motore</c> carries the engine (at once, at every change, at least every
|
||||
/// minute); <c>libreria</c> says the library changed (at most every second and a half); a comment line keeps the
|
||||
/// stream open. Never contains captions, bodies or addresses.
|
||||
/// </summary>
|
||||
public static async Task StreamAsync(
|
||||
HttpContext context,
|
||||
IEngineMonitor monitor,
|
||||
IFebeStorage storage,
|
||||
BrowserUseTracker tracker,
|
||||
LibraryChanges library,
|
||||
IClock clock)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var response = context.Response;
|
||||
response.ContentType = "text/event-stream; charset=utf-8";
|
||||
response.Headers.CacheControl = "no-cache, no-transform";
|
||||
response.Headers["X-Accel-Buffering"] = "no";
|
||||
var ct = context.RequestAborted;
|
||||
|
||||
var signals = Channel.CreateBounded<string>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var engineTask = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await foreach (var _ in monitor.SubscribeAsync(stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
signals.Writer.TryWrite("motore");
|
||||
}
|
||||
},
|
||||
CancellationToken.None);
|
||||
var libraryTask = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
await foreach (var change in library.SubscribeAsync(stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
signals.Writer.TryWrite("libreria:" + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange));
|
||||
}
|
||||
},
|
||||
CancellationToken.None);
|
||||
|
||||
try
|
||||
{
|
||||
await WriteAsync(response, "retry: 3000\n\n", ct).ConfigureAwait(false);
|
||||
await SendEngineAsync().ConfigureAwait(false);
|
||||
var libraryGap = TimeSpan.FromMilliseconds(1500);
|
||||
var lastEngine = DateTimeOffset.UtcNow;
|
||||
var lastLibrary = DateTimeOffset.MinValue;
|
||||
string? pendingLibrary = null;
|
||||
var enginePending = false;
|
||||
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var wait = Heartbeat;
|
||||
if (lastEngine + Refresh - now < wait)
|
||||
{
|
||||
wait = lastEngine + Refresh - now;
|
||||
}
|
||||
|
||||
if (pendingLibrary is not null && lastLibrary + libraryGap - now < wait)
|
||||
{
|
||||
wait = lastLibrary + libraryGap - now;
|
||||
}
|
||||
|
||||
var got = await WaitAsync(signals.Reader, wait < TimeSpan.Zero ? TimeSpan.Zero : wait, ct).ConfigureAwait(false);
|
||||
if (got)
|
||||
{
|
||||
// Changes come in bursts: wait a moment and send one update for all of them.
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(300), ct).ConfigureAwait(false);
|
||||
while (signals.Reader.TryRead(out var signal))
|
||||
{
|
||||
if (signal == "motore")
|
||||
{
|
||||
enginePending = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
pendingLibrary = signal["libreria:".Length..];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
now = DateTimeOffset.UtcNow;
|
||||
var sent = false;
|
||||
if (enginePending || now - lastEngine >= Refresh)
|
||||
{
|
||||
await SendEngineAsync().ConfigureAwait(false);
|
||||
enginePending = false;
|
||||
lastEngine = now;
|
||||
sent = true;
|
||||
}
|
||||
|
||||
if (pendingLibrary is not null && now - lastLibrary >= libraryGap)
|
||||
{
|
||||
await WriteAsync(response, "event: libreria\ndata: " + pendingLibrary + "\n\n", ct).ConfigureAwait(false);
|
||||
pendingLibrary = null;
|
||||
lastLibrary = now;
|
||||
sent = true;
|
||||
}
|
||||
|
||||
if (!sent && !got)
|
||||
{
|
||||
await WriteAsync(response, ": ancora qui\n\n", ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
// The page closed the stream.
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// The connection dropped.
|
||||
}
|
||||
finally
|
||||
{
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
await Task.WhenAll(Quiet(engineTask), Quiet(libraryTask)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
async Task SendEngineAsync()
|
||||
{
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false);
|
||||
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> WaitAsync(ChannelReader<string> reader, TimeSpan wait, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(wait);
|
||||
try
|
||||
{
|
||||
return await reader.WaitToReadAsync(timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteAsync(HttpResponse response, string text, CancellationToken ct)
|
||||
{
|
||||
await response.Body.WriteAsync(Encoding.UTF8.GetBytes(text), ct).ConfigureAwait(false);
|
||||
await response.Body.FlushAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static async Task Quiet(Task task)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user