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.Connection; 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; /// The engine for the interface: snapshot, «Metti in pausa», «Riprendi», the browser, and the event stream. public static class EngineApi { /// Idle time after which a comment line keeps the event stream open through proxies. public static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(25); /// The snapshot is pushed again at least this often, so «8 min fa» and «verso le» stay current. 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, IConnectionService connection, CancellationToken ct) => ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, 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); }); // «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(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, on the start page when it was at rest // and on the login page with { openLogin: true } (the red strip of a disconnection; issue #52). endpoints.MapPost("/api/browser/show", async (HttpContext context, IBrowserWindow browser, IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) => { if (!browser.IsSeparateWindow) { throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser."); } var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false); await connection.ShowBrowserAsync(body.OpenLogin, 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); } /// /// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known: /// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with /// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run /// (or there is none in this process) the connection is asked. /// public static async Task SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) { ArgumentNullException.ThrowIfNull(monitor); ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(tracker); ArgumentNullException.ThrowIfNull(clock); ArgumentNullException.ThrowIfNull(connection); 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", EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected", _ => "connected", }; var link = 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, link, canResume); } /// /// /api/eventi: server-sent events. motore carries the engine (at once, at every change, at least every /// minute); libreria says the library changed (at most every second and a half); a comment line keeps the /// stream open. Never contains captions, bodies or addresses. /// public static async Task StreamAsync( HttpContext context, IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, LibraryChanges library, IClock clock, IConnectionService connection) { 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(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, connection, ct).ConfigureAwait(false); await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false); } } private static async Task WaitAsync(ChannelReader 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) { } } }