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,193 @@
|
||||
using System.Net;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Demo;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Hosting;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
using Febe.Web.Security;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.AspNetCore.StaticFiles;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The web application of Febe, the same for both shells (spec §5): API under <c>/api</c>, server-sent events at
|
||||
/// <c>/api/eventi</c>, the interface files embedded in this assembly, and the Italian page addresses
|
||||
/// (<c>/libreria</c>, <c>/account/12</c>, <c>/impostazioni/generali</c> …) answered with the application page.
|
||||
/// <code>
|
||||
/// var app = FebeWebHost.Build(options, FebeListen.Loopback(port), services =>
|
||||
/// {
|
||||
/// services.AddSingleton<IFebeStorage>(db);
|
||||
/// services.AddSingleton(library); // FebeLibrary
|
||||
/// services.AddSingleton<IClock>(clock);
|
||||
/// services.AddSingleton(engine.Monitor); // IEngineMonitor (optional)
|
||||
/// services.AddSingleton<IEngineControl>(new EngineHostControl(engine)); // optional
|
||||
/// services.AddSingleton<INativeShell>(shell); // desktop only
|
||||
/// });
|
||||
/// await app.StartAsync();
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static class FebeWeb
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers the web layer. Register <c>IFebeStorage</c>, <see cref="FebeLibrary"/> and <see cref="IClock"/> as
|
||||
/// well; everything else has a default (no engine, no native functions, files from the library layout) that a
|
||||
/// registration made before this call replaces.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddFebeWeb(this IServiceCollection services, FebeWebOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
services.AddSingleton(options);
|
||||
services.TryAddSingleton<INativeShell>(BrowserShell.Instance);
|
||||
services.TryAddSingleton<IBrowserWindow, NoBrowserWindow>();
|
||||
services.TryAddSingleton<IMediaFileResolver, LibraryFileResolver>();
|
||||
services.TryAddSingleton<LibraryChanges>();
|
||||
services.TryAddSingleton<BrowserUseTracker>();
|
||||
services.TryAddSingleton<OfflineEngine>();
|
||||
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
|
||||
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
|
||||
services.AddHttpContextAccessor();
|
||||
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
||||
{
|
||||
services.TryAddSingleton(sp => new PasswordAccess(options.Password, options.Lockout, () => sp.GetRequiredService<IClock>().Now));
|
||||
}
|
||||
|
||||
services.ConfigureHttpJsonOptions(json =>
|
||||
{
|
||||
json.SerializerOptions.TypeInfoResolverChain.Clear();
|
||||
json.SerializerOptions.TypeInfoResolverChain.Add(FebeJsonContext.Default);
|
||||
});
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>Middleware (security, errors, static files) and every endpoint.</summary>
|
||||
public static WebApplication UseFebe(this WebApplication app)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
var options = app.Services.GetRequiredService<FebeWebOptions>();
|
||||
var files = options.InterfaceFolder is { Length: > 0 } folder ? new EmbeddedWwwroot(folder) : new EmbeddedWwwroot();
|
||||
|
||||
app.UseMiddleware<SecurityMiddleware>();
|
||||
if (options.Demo)
|
||||
{
|
||||
app.UseMiddleware<DemoRequestMiddleware>();
|
||||
}
|
||||
|
||||
app.UseMiddleware<ApiErrorMiddleware>();
|
||||
var types = new FileExtensionContentTypeProvider();
|
||||
types.Mappings[".json"] = "application/json; charset=utf-8";
|
||||
types.Mappings[".js"] = "text/javascript; charset=utf-8";
|
||||
types.Mappings[".css"] = "text/css; charset=utf-8";
|
||||
app.UseStaticFiles(new StaticFileOptions
|
||||
{
|
||||
FileProvider = files,
|
||||
ContentTypeProvider = types,
|
||||
OnPrepareResponse = ctx => ctx.Context.Response.Headers.CacheControl = "no-cache",
|
||||
});
|
||||
|
||||
app.MapFebeApi(files);
|
||||
return app;
|
||||
}
|
||||
|
||||
/// <summary>The endpoints alone (API, events, icons, application page).</summary>
|
||||
public static IEndpointRouteBuilder MapFebeApi(this IEndpointRouteBuilder endpoints, EmbeddedWwwroot files)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(endpoints);
|
||||
ArgumentNullException.ThrowIfNull(files);
|
||||
SystemApi.Map(endpoints, files);
|
||||
EngineApi.Map(endpoints);
|
||||
LibraryApi.Map(endpoints);
|
||||
AccountsApi.Map(endpoints);
|
||||
AccessApi.Map(endpoints);
|
||||
|
||||
endpoints.Map("/api/{**rest}", static context =>
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return context.Response.WriteAsJsonAsync(new ProblemDto("Indirizzo dell'API sconosciuto."), FebeJsonContext.Default.ProblemDto);
|
||||
});
|
||||
|
||||
// Every page address without an extension answers with the application page; the router of the page
|
||||
// decides what to show (and says «Pagina non trovata» for unknown addresses).
|
||||
var embeddedIndex = files.ReadText("index.html") ?? throw new InvalidOperationException("index.html non è incorporato.");
|
||||
endpoints.MapFallback("{*path:nonfile}", context =>
|
||||
{
|
||||
if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
context.Response.ContentType = "text/html; charset=utf-8";
|
||||
context.Response.Headers.CacheControl = "no-cache";
|
||||
return context.Response.WriteAsync(files.FromDisk ? files.ReadText("index.html") ?? embeddedIndex : embeddedIndex);
|
||||
});
|
||||
return endpoints;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Builds and starts the web application for either shell.</summary>
|
||||
public static class FebeWebHost
|
||||
{
|
||||
/// <summary>
|
||||
/// A web application listening on <paramref name="listen"/> (Kestrel only, no other server), with the web layer
|
||||
/// registered and mapped. ASP.NET Core request logs are kept at warnings: the desktop token travels once in a
|
||||
/// query string and must never reach a log.
|
||||
/// </summary>
|
||||
public static WebApplication Build(FebeWebOptions options, FebeListen listen, Action<IServiceCollection> configureServices, Action<ILoggingBuilder>? configureLogging = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
ArgumentNullException.ThrowIfNull(listen);
|
||||
ArgumentNullException.ThrowIfNull(configureServices);
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions
|
||||
{
|
||||
ApplicationName = typeof(FebeWeb).Assembly.GetName().Name,
|
||||
ContentRootPath = AppContext.BaseDirectory,
|
||||
});
|
||||
builder.WebHost.ConfigureKestrel(kestrel =>
|
||||
{
|
||||
kestrel.AddServerHeader = false;
|
||||
kestrel.Listen(listen.Address, listen.Port);
|
||||
});
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting", LogLevel.Warning);
|
||||
if (configureLogging is not null)
|
||||
{
|
||||
configureLogging(builder.Logging);
|
||||
}
|
||||
|
||||
configureServices(builder.Services);
|
||||
builder.Services.AddFebeWeb(options);
|
||||
var app = builder.Build();
|
||||
app.UseFebe();
|
||||
return app;
|
||||
}
|
||||
|
||||
/// <summary>The address Kestrel actually listens on (after <c>StartAsync</c>; useful with port 0).</summary>
|
||||
public static Uri BoundAddress(WebApplication app)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()?.Addresses
|
||||
?? throw new InvalidOperationException("Il server non ha indirizzi.");
|
||||
var first = addresses.First();
|
||||
return new Uri(first.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>The port Kestrel listens on.</summary>
|
||||
public static int BoundPort(WebApplication app) => BoundAddress(app).Port;
|
||||
|
||||
/// <summary>True for an address that only this computer can reach.</summary>
|
||||
public static bool IsLoopback(IPAddress address) => IPAddress.IsLoopback(address);
|
||||
}
|
||||
Reference in new issue
Block a user