using System.Net; using Febe.Core.Abstractions; using Febe.Core.Alerts; using Febe.Core.Engine; using Febe.Core.Import; using Febe.Core.Storage; using Febe.Web.Api; using Febe.Web.Connection; using Febe.Web.Demo; using Febe.Web.Engine; using Febe.Web.Hosting; using Febe.Web.Import; 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; /// /// The web application of Febe, the same for both shells (spec §5): API under /api, server-sent events at /// /api/eventi, the interface files embedded in this assembly, and the Italian page addresses /// (/libreria, /account/12, /impostazioni/generali …) answered with the application page. /// /// 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(); /// /// public static class FebeWeb { /// /// Registers the web layer. Register IFebeStorage, and 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. /// public static IServiceCollection AddFebeWeb(this IServiceCollection services, FebeWebOptions options) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(options); services.AddSingleton(options); services.TryAddSingleton(BrowserShell.Instance); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(sp => sp.GetRequiredService()); services.TryAddSingleton(sp => sp.GetRequiredService()); services.TryAddSingleton(); services.TryAddSingleton(sp => new StoredEngineSettingsControl(sp.GetRequiredService())); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(sp => new StoredIncidentHistory(sp.GetRequiredService())); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(sp => sp.GetService() is { } import ? new ImportHub(import, sp.GetRequiredService(), sp.GetRequiredService()) : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService())); services.AddHttpContextAccessor(); if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password)) { services.TryAddSingleton(sp => new PasswordAccess(options.Password, options.Lockout, () => sp.GetRequiredService().Now)); } services.ConfigureHttpJsonOptions(json => { json.SerializerOptions.TypeInfoResolverChain.Clear(); json.SerializerOptions.TypeInfoResolverChain.Add(FebeJsonContext.Default); }); return services; } /// Middleware (security, errors, static files) and every endpoint. public static WebApplication UseFebe(this WebApplication app) { ArgumentNullException.ThrowIfNull(app); var options = app.Services.GetRequiredService(); var files = options.InterfaceFolder is { Length: > 0 } folder ? new EmbeddedWwwroot(folder) : new EmbeddedWwwroot(); app.UseMiddleware(); if (options.Demo) { app.UseMiddleware(); } app.UseMiddleware(); app.UseMiddleware(); // The remote view (/api/vista). Origin and session are checked by the security middleware above. app.UseWebSockets(); 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; } /// The endpoints alone (API, events, icons, application page). 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); ConnectionApi.Map(endpoints); ActivityApi.Map(endpoints); SettingsApi.Map(endpoints); ImportApi.Map(endpoints); DuplicatesApi.Map(endpoints); SearchApi.Map(endpoints); RemoteViewSocket.Map(endpoints); HealthEndpoint.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; } } /// Builds and starts the web application for either shell. public static class FebeWebHost { /// /// A web application listening on (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. /// public static WebApplication Build(FebeWebOptions options, FebeListen listen, Action configureServices, Action? 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; } /// The address Kestrel actually listens on (after StartAsync; useful with port 0). public static Uri BoundAddress(WebApplication app) { ArgumentNullException.ThrowIfNull(app); var addresses = app.Services.GetRequiredService().Features.Get()?.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)); } /// The port Kestrel listens on. public static int BoundPort(WebApplication app) => BoundAddress(app).Port; /// True for an address that only this computer can reach. public static bool IsLoopback(IPAddress address) => IPAddress.IsLoopback(address); }