«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono subito i suggerimenti locali, poi i profili di Instagram con la foto, come chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima il fuoco, legge la risposta della pagina e non clicca mai un risultato. La ricerca ha una categoria propria nel Governatore, con tetti larghi che non consumano quelli della raccolta, e si dà il turno con il motore sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le foto passano dal CDN con un permesso ciascuna e restano solo in memoria. Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli search-open e search-box saranno raccolti dal vivo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
225 lines
11 KiB
C#
225 lines
11 KiB
C#
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;
|
|
|
|
/// <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.TryAddSingleton<Febe.Core.Collection.Search.IProfileSearch, OfflineProfileSearch>();
|
|
services.TryAddSingleton<IEngineSettingsControl>(sp => new StoredEngineSettingsControl(sp.GetRequiredService<IFebeStorage>()));
|
|
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
|
|
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
|
services.TryAddSingleton<IBrowserPreview, NoBrowserPreview>();
|
|
services.TryAddSingleton<IDiagnosticSource, NoDiagnosticSource>();
|
|
services.TryAddSingleton<IIncidentHistory>(sp => new StoredIncidentHistory(sp.GetRequiredService<IFebeStorage>()));
|
|
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
|
|
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
|
|
services.TryAddSingleton<FolderSizes>();
|
|
services.TryAddSingleton<RebuildJob>();
|
|
services.TryAddSingleton(sp => sp.GetService<ImportService>() is { } import
|
|
? new ImportHub(import, sp.GetRequiredService<IClock>(), sp.GetRequiredService<LibraryChanges>())
|
|
: new ImportHub(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<FebeLibrary>(), sp.GetRequiredService<IClock>(), options, sp.GetRequiredService<LibraryChanges>()));
|
|
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>();
|
|
app.UseMiddleware<ConfigurationGateMiddleware>();
|
|
|
|
// 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;
|
|
}
|
|
|
|
/// <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);
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
}
|