Unione dell'ondata 4 (interfaccia parte 2, server reale e Docker): impostazioni del motore, anteprima del browser e schema dei nomi collegati al server reale; decisioni consolidate
verifica / prove (push) Successful in 18m40s
verifica / prove (push) Successful in 18m40s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
39 files changed
+6228
-12
No files matched your search
@@ -0,0 +1,69 @@
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET /salute</c> (PROTOCOLLO.md, spec §11): <c>200 {"stato":"ok"}</c> or <c>503 {"stato":"problema"}</c> and
|
||||
/// nothing else, without authentication, for the Docker health check. It says no more than that on purpose.
|
||||
/// </summary>
|
||||
public static class HealthEndpoint
|
||||
{
|
||||
public const string Path = "/salute";
|
||||
|
||||
public const string Ok = """{"stato":"ok"}""";
|
||||
|
||||
public const string Problem = """{"stato":"problema"}""";
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
endpoints.MapMethods(Path, [HttpMethods.Get, HttpMethods.Head], (HttpContext context, IConfigurationProblems problems) =>
|
||||
{
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
var healthy = problems.Current.Count == 0;
|
||||
return Results.Text(healthy ? Ok : Problem, "application/json; charset=utf-8", statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>True for the health check request, which needs neither a session nor an allowed Host.</summary>
|
||||
public static bool IsHealthRequest(HttpRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method))
|
||||
&& string.Equals(request.Path.Value, Path, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// While a configuration problem keeps the engine from starting (spec §8.2, §11), the interface shows only the page
|
||||
/// that explains it: the API answers only what that page and the frame around it need, everything else (library,
|
||||
/// accounts, connection, remote view) gets 503 with the problem in Italian.
|
||||
/// </summary>
|
||||
public sealed class ConfigurationGateMiddleware(RequestDelegate next, IConfigurationProblems problems)
|
||||
{
|
||||
/// <summary>API addresses still answered while there is a problem.</summary>
|
||||
public static readonly IReadOnlyList<string> AllowedApi =
|
||||
["/api/capabilities", "/api/preferences", "/api/accesso", "/api/uscita", "/api/engine", "/api/eventi"];
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var current = problems.Current;
|
||||
var path = context.Request.Path;
|
||||
if (current.Count == 0
|
||||
|| !path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)
|
||||
|| AllowedApi.Any(a => string.Equals(path.Value, a, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
await next(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsJsonAsync(
|
||||
new ProblemDto($"{current[0].Title}. Il motore non è partito: {current[0].Remedy}"),
|
||||
FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// The browser seen through the interface (Docker only, spec §4.1, §11, mockup 10). Implemented by the server
|
||||
/// composition over the real Chromium; the web layer only speaks the protocol of <c>PROTOCOLLO.md</c> over a WebSocket.
|
||||
/// </summary>
|
||||
public interface IRemoteViewHost
|
||||
{
|
||||
/// <summary>
|
||||
/// Opens a remote view: Alberto is now driving (the engine is still) and frames start. A view opened earlier
|
||||
/// (another tab) is closed with <see cref="RemoteViewEnd.Replaced"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="RemoteViewUnavailableException">The browser is not running: nothing to show.</exception>
|
||||
Task<IRemoteViewConnection> OpenAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>One open remote view. Disposing it stops the frames and ends «Alberto is driving».</summary>
|
||||
public interface IRemoteViewConnection : IAsyncDisposable
|
||||
{
|
||||
/// <summary>What goes to the page, in order: meta first, then frames (the oldest dropped when the page is slow).</summary>
|
||||
IAsyncEnumerable<RemoteViewOutput> ReadAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Why the view ended on the server side (null while it is open).</summary>
|
||||
RemoteViewEnd? Ended { get; }
|
||||
|
||||
Task MouseAsync(RemoteViewMouse input, CancellationToken ct);
|
||||
|
||||
Task KeyAsync(RemoteViewKey input, CancellationToken ct);
|
||||
|
||||
Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Why a remote view ended without Alberto closing it.</summary>
|
||||
public enum RemoteViewEnd
|
||||
{
|
||||
/// <summary>Opened again in another tab or window: the newest wins.</summary>
|
||||
Replaced,
|
||||
|
||||
/// <summary>The browser stopped or is restarting.</summary>
|
||||
BrowserStopped,
|
||||
|
||||
/// <summary>The server is shutting down.</summary>
|
||||
ShuttingDown,
|
||||
}
|
||||
|
||||
/// <summary>A message for the page: a JPEG frame, or a meta message (address and size).</summary>
|
||||
public abstract record RemoteViewOutput;
|
||||
|
||||
/// <summary>A frame of the screencast, sent as one binary WebSocket message.</summary>
|
||||
/// <param name="Jpeg">The JPEG bytes.</param>
|
||||
public sealed record RemoteViewFrame(ReadOnlyMemory<byte> Jpeg) : RemoteViewOutput;
|
||||
|
||||
/// <summary>Sent at the start and whenever the address or the size changes.</summary>
|
||||
/// <param name="Width">Page width in CSS pixels the frames represent.</param>
|
||||
/// <param name="Height">Page height in CSS pixels the frames represent.</param>
|
||||
/// <param name="Url">Address of the page without query string or fragment.</param>
|
||||
public sealed record RemoteViewMeta(int Width, int Height, string Url) : RemoteViewOutput;
|
||||
|
||||
public enum RemoteViewMouseAction
|
||||
{
|
||||
Move,
|
||||
Down,
|
||||
Up,
|
||||
Wheel,
|
||||
}
|
||||
|
||||
public enum RemoteViewButton
|
||||
{
|
||||
None,
|
||||
Left,
|
||||
Middle,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// <summary>A mouse event; <paramref name="X"/> and <paramref name="Y"/> are 0–1 of the frame.</summary>
|
||||
public sealed record RemoteViewMouse(
|
||||
RemoteViewMouseAction Action,
|
||||
double X,
|
||||
double Y,
|
||||
RemoteViewButton Button,
|
||||
int ClickCount,
|
||||
double DeltaX,
|
||||
double DeltaY);
|
||||
|
||||
public enum RemoteViewKeyAction
|
||||
{
|
||||
/// <summary>Key pressed; when it has <see cref="RemoteViewKey.Text"/> the text is inserted.</summary>
|
||||
Down,
|
||||
|
||||
Up,
|
||||
|
||||
/// <summary>Text only (composed characters): inserted without key codes.</summary>
|
||||
Char,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A key from the page. Contains what Alberto types, passwords included: never logged, never stored, never shown
|
||||
/// (spec §13.2). <see cref="ToString"/> hides everything on purpose.
|
||||
/// </summary>
|
||||
/// <param name="Action">Down, up or char.</param>
|
||||
/// <param name="Key">DOM <c>key</c>.</param>
|
||||
/// <param name="Code">DOM <c>code</c>.</param>
|
||||
/// <param name="Text">Text the key produces, if any.</param>
|
||||
/// <param name="Modifiers">Bit mask of <c>Input.dispatchKeyEvent</c>: Alt 1, Ctrl 2, Meta 4, Shift 8.</param>
|
||||
public sealed record RemoteViewKey(RemoteViewKeyAction Action, string Key, string Code, string? Text, int Modifiers)
|
||||
{
|
||||
public override string ToString() => "RemoteViewKey(…)";
|
||||
}
|
||||
|
||||
public enum RemoteViewNavigation
|
||||
{
|
||||
/// <summary>Back to the previous address of this view.</summary>
|
||||
Back,
|
||||
|
||||
/// <summary>Reload the current page.</summary>
|
||||
Reload,
|
||||
}
|
||||
|
||||
/// <summary>The browser is not available (starting, restarting, missing, or Febe stopped by a configuration problem).</summary>
|
||||
public sealed class RemoteViewUnavailableException : Exception
|
||||
{
|
||||
public RemoteViewUnavailableException()
|
||||
: base("Il browser di Febe non è disponibile in questo momento.")
|
||||
{
|
||||
}
|
||||
|
||||
public RemoteViewUnavailableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public RemoteViewUnavailableException(string message, Exception? inner)
|
||||
: base(message, inner)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
using System.Buffers;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using Febe.Web.Api;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Web.Connection;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/vista</c>: the remote view over a WebSocket (PROTOCOLLO.md, spec §4.1, §11). The security middleware has
|
||||
/// already checked the session and the <c>Origin</c> (spec §13.1) before this runs. Frames go out as binary messages,
|
||||
/// meta as text; mouse, keys and back/reload come in as small JSON text messages and go to the browser. Nothing that
|
||||
/// comes in is ever logged: it contains what Alberto types.
|
||||
/// </summary>
|
||||
public static class RemoteViewSocket
|
||||
{
|
||||
public const string Path = "/api/vista";
|
||||
|
||||
/// <summary>Largest message accepted from the page; larger ones close the view.</summary>
|
||||
public const int MaxMessageBytes = 4096;
|
||||
|
||||
/// <summary>Close code when the view was opened again elsewhere (the newest wins).</summary>
|
||||
public const int CloseReplaced = 4001;
|
||||
|
||||
/// <summary>Close code when the browser stopped or is restarting.</summary>
|
||||
public const int CloseBrowserStopped = 4002;
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
endpoints.Map(Path, HandleAsync);
|
||||
}
|
||||
|
||||
public static async Task HandleAsync(HttpContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var options = context.RequestServices.GetRequiredService<FebeWebOptions>();
|
||||
if (options.Edition == FebeEdition.Desktop && !options.Demo)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status404NotFound, "Sul desktop il browser di Febe ha la sua finestra: la vista remota c'è solo nel contenitore.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.WebSockets.IsWebSocketRequest)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status400BadRequest, "La vista remota si apre solo con una connessione WebSocket.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.RequestServices.GetService<IRemoteViewHost>() is not { } host)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "La vista remota non è disponibile: il browser di Febe non è in funzione.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
IRemoteViewConnection connection;
|
||||
try
|
||||
{
|
||||
connection = await host.OpenAsync(context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
catch (RemoteViewUnavailableException ex)
|
||||
{
|
||||
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, ex.Message).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await using (connection.ConfigureAwait(false))
|
||||
{
|
||||
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
|
||||
{
|
||||
KeepAliveInterval = TimeSpan.FromSeconds(20),
|
||||
DangerousEnableCompression = false,
|
||||
}).ConfigureAwait(false);
|
||||
await RunAsync(socket, connection, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pumps one view until either side closes it.</summary>
|
||||
internal static async Task RunAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken aborted)
|
||||
{
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(aborted);
|
||||
var sender = Task.Run(() => SendLoopAsync(socket, connection, stop.Token), CancellationToken.None);
|
||||
var closeStatus = WebSocketCloseStatus.NormalClosure;
|
||||
var closeText = "Vista chiusa";
|
||||
try
|
||||
{
|
||||
if (!await ReceiveLoopAsync(socket, connection, stop.Token).ConfigureAwait(false))
|
||||
{
|
||||
closeStatus = WebSocketCloseStatus.MessageTooBig;
|
||||
closeText = "Messaggio troppo lungo";
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException)
|
||||
{
|
||||
// The page went away.
|
||||
}
|
||||
finally
|
||||
{
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await sender.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
await socket.CloseOutputAsync(closeStatus, closeText, timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SendLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
await foreach (var output in connection.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
switch (output)
|
||||
{
|
||||
case RemoteViewMeta meta:
|
||||
await socket.SendAsync(MetaJson(meta), WebSocketMessageType.Text, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewFrame frame:
|
||||
await socket.SendAsync(frame.Jpeg, WebSocketMessageType.Binary, endOfMessage: true, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The server ended the view (another tab, browser stopped, shutdown): tell the page why.
|
||||
if (!ct.IsCancellationRequested && socket.State == WebSocketState.Open)
|
||||
{
|
||||
var (status, text) = connection.Ended switch
|
||||
{
|
||||
RemoteViewEnd.Replaced => ((WebSocketCloseStatus)CloseReplaced, "Vista aperta in un'altra finestra"),
|
||||
RemoteViewEnd.ShuttingDown => (WebSocketCloseStatus.EndpointUnavailable, "Febe si sta fermando"),
|
||||
_ => ((WebSocketCloseStatus)CloseBrowserStopped, "Il browser si è fermato"),
|
||||
};
|
||||
await socket.CloseOutputAsync(status, text, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the page's messages until it closes. Returns false when a message was too long: the caller closes the
|
||||
/// view (only one task may send at a time, and the frames are being sent by another).
|
||||
/// </summary>
|
||||
private static async Task<bool> ReceiveLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(MaxMessageBytes + 1);
|
||||
try
|
||||
{
|
||||
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
|
||||
{
|
||||
var length = 0;
|
||||
ValueWebSocketReceiveResult result;
|
||||
do
|
||||
{
|
||||
if (length >= MaxMessageBytes + 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result = await socket.ReceiveAsync(buffer.AsMemory(length, MaxMessageBytes + 1 - length), ct).ConfigureAwait(false);
|
||||
if (result.MessageType == WebSocketMessageType.Close)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
length += result.Count;
|
||||
}
|
||||
while (!result.EndOfMessage);
|
||||
|
||||
if (length > MaxMessageBytes)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (result.MessageType != WebSocketMessageType.Text)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await DispatchAsync(buffer.AsMemory(0, length), connection, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses one message of the page and forwards it. Unknown or malformed messages are dropped silently.</summary>
|
||||
internal static async Task DispatchAsync(ReadOnlyMemory<byte> message, IRemoteViewConnection connection, CancellationToken ct)
|
||||
{
|
||||
object? input;
|
||||
try
|
||||
{
|
||||
input = Parse(message);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
switch (input)
|
||||
{
|
||||
case RemoteViewMouse mouse:
|
||||
await connection.MouseAsync(mouse, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewKey key:
|
||||
await connection.KeyAsync(key, ct).ConfigureAwait(false);
|
||||
break;
|
||||
case RemoteViewNavigation navigation:
|
||||
await connection.NavigateAsync(navigation, ct).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException)
|
||||
{
|
||||
// A lost gesture (no frame yet, browser restarting): the page simply tries again. Never logged: it may
|
||||
// be a key of a password.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The input messages of PROTOCOLLO.md: <c>mouse</c>, <c>key</c>, <c>navigate</c>. Returns null for anything else
|
||||
/// (unknown type or action, missing fields, values out of range).
|
||||
/// </summary>
|
||||
internal static object? Parse(ReadOnlyMemory<byte> message)
|
||||
{
|
||||
using var document = JsonDocument.Parse(message, new JsonDocumentOptions { MaxDepth = 3 });
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object || Text(root, "type", 16) is not { } type)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var action = Text(root, "action", 16);
|
||||
switch (type)
|
||||
{
|
||||
case "mouse":
|
||||
{
|
||||
RemoteViewMouseAction? kind = action switch
|
||||
{
|
||||
"move" => RemoteViewMouseAction.Move,
|
||||
"down" => RemoteViewMouseAction.Down,
|
||||
"up" => RemoteViewMouseAction.Up,
|
||||
"wheel" => RemoteViewMouseAction.Wheel,
|
||||
_ => null,
|
||||
};
|
||||
if (kind is null || Number(root, "x") is not { } x || Number(root, "y") is not { } y || x is < 0 or > 1 || y is < 0 or > 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var button = Text(root, "button", 16) switch
|
||||
{
|
||||
"left" => RemoteViewButton.Left,
|
||||
"middle" => RemoteViewButton.Middle,
|
||||
"right" => RemoteViewButton.Right,
|
||||
_ => kind is RemoteViewMouseAction.Down or RemoteViewMouseAction.Up ? RemoteViewButton.Left : RemoteViewButton.None,
|
||||
};
|
||||
var clicks = (int)Math.Clamp(Number(root, "clickCount") ?? 1, 1, 3);
|
||||
var dx = Math.Clamp(Number(root, "deltaX") ?? 0, -5000, 5000);
|
||||
var dy = Math.Clamp(Number(root, "deltaY") ?? 0, -5000, 5000);
|
||||
return new RemoteViewMouse(kind.Value, x, y, button, clicks, dx, dy);
|
||||
}
|
||||
|
||||
case "key":
|
||||
{
|
||||
RemoteViewKeyAction? kind = action switch
|
||||
{
|
||||
"down" => RemoteViewKeyAction.Down,
|
||||
"up" => RemoteViewKeyAction.Up,
|
||||
"char" => RemoteViewKeyAction.Char,
|
||||
_ => null,
|
||||
};
|
||||
var key = Text(root, "key", 64) ?? string.Empty;
|
||||
var code = Text(root, "code", 64) ?? string.Empty;
|
||||
var text = Text(root, "text", 32);
|
||||
var modifiers = (int)Math.Clamp(Number(root, "modifiers") ?? 0, 0, 15);
|
||||
if (kind is null || (kind == RemoteViewKeyAction.Char ? string.IsNullOrEmpty(text) : key.Length == 0))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new RemoteViewKey(kind.Value, key, code, string.IsNullOrEmpty(text) ? null : text, modifiers);
|
||||
}
|
||||
|
||||
case "navigate":
|
||||
return action switch
|
||||
{
|
||||
"back" => RemoteViewNavigation.Back,
|
||||
"reload" => RemoteViewNavigation.Reload,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The meta message as UTF-8 JSON.</summary>
|
||||
internal static ReadOnlyMemory<byte> MetaJson(RemoteViewMeta meta)
|
||||
{
|
||||
var buffer = new ArrayBufferWriter<byte>(256);
|
||||
using (var writer = new Utf8JsonWriter(buffer))
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
writer.WriteString("type", "meta");
|
||||
writer.WriteNumber("width", meta.Width);
|
||||
writer.WriteNumber("height", meta.Height);
|
||||
writer.WriteString("url", meta.Url);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
return buffer.WrittenMemory;
|
||||
}
|
||||
|
||||
private static string? Text(JsonElement root, string name, int maxLength) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.GetString() is { } s && s.Length <= maxLength
|
||||
? s
|
||||
: null;
|
||||
|
||||
private static double? Number(JsonElement root, string name) =>
|
||||
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var d) && double.IsFinite(d)
|
||||
? d
|
||||
: null;
|
||||
|
||||
private static Task RefuseAsync(HttpContext context, int status, string message)
|
||||
{
|
||||
context.Response.StatusCode = status;
|
||||
return context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user