M6 Windows: composizione condivisa Febe.App per Server e Desktop; Febe per Windows (WPF) con l'interfaccia in WebView2, area di notifica, istanza unica, «Browser di Febe» su WebView2 con CDP filtrato (WebView2CdpSession) e ripieghi di S2 (composizione, Edge), guscio nativo, avvisi, spostamento verificato della cartella dei dati, icona del marchio; un solo Febe.exe, installatore NSIS e zip portabile; guida docs/windows.md e prove dal vivo S1–S3

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 21:50:25 +00:00
1 parent dc4d1fc738
commit b443adfa8b
73 files changed
+7914 -699

No files matched your search

+5 -13
View File
@@ -1,5 +1,6 @@
using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Gestures;
using Febe.Browser.RemoteView;
@@ -14,7 +15,7 @@ namespace Febe.Server;
/// view, which holds the «Alberto is driving» lease while it is open, so the engine is still. One view at a time: a
/// view opened in another tab replaces the older one. Keys go to the browser and nowhere else.
/// </summary>
internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock, ServerLog log) : IRemoteViewHost
internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost
{
private readonly Lock _gate = new();
private BrowserRemoteViewConnection? _current;
@@ -101,7 +102,7 @@ internal sealed class BrowserRemoteViewHost(BrowserSupervisor browser, BrowserUs
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
{
private readonly BrowserRemoteViewHost _owner;
private readonly BrowserSupervisor _browser;
private readonly ChromiumBrowser _browser;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly RemoteViewSession _session;
@@ -122,7 +123,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private int _disposed;
private bool _used;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, BrowserSupervisor browser, BrowserUseTracker tracker, IClock clock)
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock)
{
_owner = owner;
_browser = browser;
@@ -389,16 +390,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
}
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
internal static string WithoutQuery(string url)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
var cut = url.IndexOfAny(['?', '#']);
return cut < 0 ? url : url[..cut];
}
return uri.Scheme is "http" or "https" ? uri.GetLeftPart(UriPartial.Path) : uri.GetLeftPart(UriPartial.Scheme) + uri.AbsolutePath;
}
internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url);
}
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
-240
View File
@@ -1,240 +0,0 @@
using System.Globalization;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
namespace Febe.Server;
/// <summary>
/// Xvfb and Chromium of the Docker edition (spec §5, §6.1, §11): started by Febe.Server itself, never by a shell
/// script. A start that fails (Chromium missing, sandbox refused, port taken) is retried with a growing wait; once
/// running, the supervisors of <see cref="XvfbProcess"/> and <see cref="ChromiumProcessHost"/> restart what crashes.
/// </summary>
internal sealed class BrowserSupervisor : IAsyncDisposable
{
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
private readonly ServerOptions _options;
private readonly IClock _clock;
private readonly ServerLog _log;
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
private XvfbProcess? _xvfb;
private volatile bool _started;
private volatile string? _lastError;
public BrowserSupervisor(ServerOptions options, string profileDirectory, string homeDirectory, IClock clock, ServerLog log)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
ArgumentNullException.ThrowIfNull(clock);
_log = log ?? throw new ArgumentNullException(nameof(log));
// Processes start, time out and restart in wall-clock time, whatever clock the engine runs on.
_clock = new SystemClock(clock.LocalZone);
ProfileDirectory = Path.GetFullPath(profileDirectory);
HomeDirectory = Path.GetFullPath(homeDirectory);
Host = new ChromiumProcessHost(options.LaunchOptions(HomeDirectory), _clock, log.ForBrowser());
BrowserOptions = new BrowserOptions(
ProfileDirectory,
options.WindowWidth,
options.WindowHeight,
options.DebugPort,
options.ChromiumPath,
UsesXvfb ? options.Display : null);
}
/// <summary>The browser: stable for the whole life of the server (a «Scollega» restarts it in place).</summary>
public ChromiumProcessHost Host { get; }
public BrowserOptions BrowserOptions { get; }
/// <summary>Dati/browser: holds the Instagram session.</summary>
public string ProfileDirectory { get; }
/// <summary>HOME of the browser process (certificate database, font cache).</summary>
public string HomeDirectory { get; }
/// <summary>Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window.</summary>
public static bool UsesXvfb => OperatingSystem.IsLinux();
/// <summary>True when the browser runs and a page connection is attached.</summary>
public bool IsAvailable => _started && Host.IsAttached;
/// <summary>Completes when the browser started the first time.</summary>
public Task Ready => _ready.Task;
/// <summary>Why the last start failed, in Italian (for the log and the connection status); null when running.</summary>
public string? LastError => _lastError;
public bool UserIsDriving => Host.UserIsDriving;
/// <summary>Starts Xvfb and Chromium, retrying until it works or <paramref name="ct"/> is cancelled.</summary>
public async Task RunAsync(CancellationToken ct)
{
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
{
try
{
await StartOnceAsync(ct).ConfigureAwait(false);
_started = true;
_lastError = null;
_ready.TrySetResult();
_log.Info("browser", $"Browser pronto: finestra {_options.WindowWidth.ToString(CultureInfo.InvariantCulture)}×{_options.WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_options.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{(_options.NoSandbox ? ", senza sandbox (FEBE_SENZA_SANDBOX)" : string.Empty)}.");
return;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_lastError = Explain(ex);
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_log.Error("browser", $"Il browser non parte: {_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
// A failed start leaves nothing running in the host (it can be started again); Xvfb, if it started, stays.
try
{
await _clock.Delay(wait, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
/// <summary>
/// «Scollega» (spec §4.1): stops Chromium (SIGINT, so it closes cleanly), deletes the profile folder with the
/// Instagram session, and starts the browser again with an empty profile.
/// </summary>
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
if (!_started)
{
DeleteProfile();
return;
}
await Host.RestartAsync(DeleteProfile, ct).ConfigureAwait(false);
_log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
}
public async ValueTask DisposeAsync()
{
await StopProcessesAsync().ConfigureAwait(false);
}
private async Task StartOnceAsync(CancellationToken ct)
{
Directory.CreateDirectory(HomeDirectory);
if (UsesXvfb && _xvfb is null)
{
RemoveStaleDisplayLock(_options.Display);
var xvfb = new XvfbProcess(_options.Display, _options.WindowWidth, _options.WindowHeight, clock: _clock, log: _log.ForBrowser());
await xvfb.StartAsync(ct).ConfigureAwait(false);
_xvfb = xvfb;
}
RemoveStaleProfileLocks(ProfileDirectory);
await Host.StartAsync(BrowserOptions, ct).ConfigureAwait(false);
}
private async Task StopProcessesAsync()
{
try
{
await Host.StopAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or IOException)
{
}
if (_xvfb is { } xvfb)
{
_xvfb = null;
await xvfb.DisposeAsync().ConfigureAwait(false);
}
}
private void DeleteProfile()
{
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
}
/// <summary>
/// Chromium's «profile in use on another computer» lock: after the container is recreated the host name changes and
/// Chromium would refuse the profile with a dialog nobody sees. Only Febe starts this browser, and it is not running
/// now, so the lock files are stale by definition.
/// </summary>
internal static void RemoveStaleProfileLocks(string profileDirectory)
{
foreach (var name in new[] { "SingletonLock", "SingletonSocket", "SingletonCookie" })
{
var path = Path.Combine(profileDirectory, name);
try
{
if (File.Exists(path) || new FileInfo(path).LinkTarget is not null)
{
File.Delete(path);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}
/// <summary>
/// A display lock left by an Xvfb of an earlier run of the same container (restart after a crash): its process
/// number may now belong to another process, so a lock whose owner is not an Xvfb is removed.
/// </summary>
internal static void RemoveStaleDisplayLock(string display)
{
if (!OperatingSystem.IsLinux() || !int.TryParse(display.AsSpan(1), NumberStyles.None, CultureInfo.InvariantCulture, out var number))
{
return;
}
var id = number.ToString(CultureInfo.InvariantCulture);
var lockFile = $"/tmp/.X{id}-lock";
try
{
if (!File.Exists(lockFile))
{
return;
}
var owner = int.TryParse(File.ReadAllText(lockFile).Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var pid) ? pid : 0;
var comm = owner > 0 && File.Exists($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm")
? File.ReadAllText($"/proc/{owner.ToString(CultureInfo.InvariantCulture)}/comm").Trim()
: string.Empty;
if (comm.Equals("Xvfb", StringComparison.Ordinal))
{
return;
}
File.Delete(lockFile);
var socket = $"/tmp/.X11-unix/X{id}";
if (File.Exists(socket))
{
File.Delete(socket);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
private static string Explain(Exception ex) => ex switch
{
FileNotFoundException => ex.Message,
PlatformNotSupportedException => ex.Message,
TimeoutException => ex.Message,
InvalidOperationException when ex.Message.Contains("sandbox", StringComparison.OrdinalIgnoreCase) =>
ex.Message + " Se il registro parla della sandbox, vedi docs/docker.md: profilo seccomp oppure FEBE_SENZA_SANDBOX=1.",
_ => $"{ex.GetType().Name}: {ex.Message}",
};
}
-27
View File
@@ -1,27 +0,0 @@
using Febe.Core.Engine;
namespace Febe.Server;
/// <summary>
/// The recipe runner of the engine before the browser exists: the engine and its monitor are built at start-up (the
/// interface shows them at once), the collection pipeline only when Chromium is up. The engine loop is started after
/// <see cref="Target"/> is set, so a recipe never runs without it.
/// </summary>
internal sealed class DeferredRecipeRunner : IRecipeRunner
{
private volatile IRecipeRunner? _target;
/// <summary>The real runner (the collection pipeline's), once the browser is up.</summary>
public IRecipeRunner? Target
{
get => _target;
set => _target = value;
}
public Task<RecipeOutcome> RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct) =>
_target is { } target
? target.RunAsync(request, session, ct)
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
}
+65
View File
@@ -0,0 +1,65 @@
using Febe.App;
using Febe.Core.Library;
using Febe.Web;
using Febe.Web.Connection;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Server;
/// <summary>
/// The Docker edition's parts of the composition (spec §11): password-protected interface on every address, the
/// password and the Data folder checked at start-up, Chromium on Xvfb supervised by Febe itself, the remote view of the
/// browser in the Collegamento and Browser pages. No native shell: folders are read-only in the interface.
/// </summary>
internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
{
public ServerOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
public FebeWebOptions WebOptions => Options.WebOptions();
public FebeListen Listen => new(Options.ListenAddress, Options.Port);
/// <summary>The remote view of the browser, once the composition registered it.</summary>
public BrowserRemoteViewHost? RemoteView { get; private set; }
public IReadOnlyList<ConfigurationProblem> CheckConfiguration(FebeAppOptions appOptions, DataFolderCheck dataFolderCheck) =>
StartupChecks.Run(Options, dataFolderCheck);
public Task<IFebeBrowser> CreateBrowserAsync(FebePlatformContext context, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(context);
var home = Path.Combine(context.Data.Root, "home");
return Task.FromResult<IFebeBrowser>(new ChromiumBrowser(
new ChromiumBrowserSettings
{
ProfileDirectory = context.Data.BrowserProfile,
HomeDirectory = home,
WindowWidth = Options.WindowWidth,
WindowHeight = Options.WindowHeight,
DebugPort = Options.DebugPort,
ExecutablePath = Options.ChromiumPath,
// Linux needs the virtual display; elsewhere (development on Windows) the browser opens a normal window.
Display = OperatingSystem.IsLinux() ? Options.Display : null,
Launch = Options.LaunchOptions(Path.GetFullPath(home)),
ReadyRemark = Options.NoSandbox ? ", senza sandbox (FEBE_SENZA_SANDBOX)" : null,
SandboxAdvice = " Se il registro parla della sandbox, vedi docs/docker.md: profilo seccomp oppure FEBE_SENZA_SANDBOX=1.",
},
context.Clock,
context.Log));
}
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log);
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
public void RegisterProblemServices(IServiceCollection services, FebeApp app)
{
}
public Task StoppingAsync() => RemoteView?.ShutdownAsync() ?? Task.CompletedTask;
}
+1
View File
@@ -11,6 +11,7 @@
<ProjectReference Include="..\Febe.Data\Febe.Data.csproj" />
<ProjectReference Include="..\Febe.Browser\Febe.Browser.csproj" />
<ProjectReference Include="..\Febe.Web\Febe.Web.csproj" />
<ProjectReference Include="..\Febe.App\Febe.App.csproj" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" />
</ItemGroup>
<ItemGroup>
+43 -547
View File
@@ -1,20 +1,12 @@
using System.Globalization;
using Febe.App;
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Febe.Server;
@@ -32,577 +24,81 @@ internal sealed record ServerHooks
/// <summary>How long the web host waits for open requests (events, remote view) when stopping.</summary>
public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3);
public FebeAppHooks ForApp() => new()
{
Clock = Clock,
Random = Random,
DataFolderCheck = DataFolderCheck,
Console = Console ?? System.Console.Out,
ShutdownTimeout = ShutdownTimeout,
};
}
/// <summary>
/// The real composition of the Docker edition (spec §5, §11, milestone M5). Start-up checks first: with a problem
/// (password missing, Data folder not writable or on a network share) neither the engine nor the browser start, and
/// the interface shows only the page that explains it. Otherwise: database, library, thumbnails, perceptual hashes,
/// import, daily backup, Xvfb and Chromium, the collection pipeline, the download queue and the engine, behind the
/// password-protected interface. Disposing stops everything in order (engine, downloads, browser with SIGINT, Xvfb).
/// The real composition of the Docker edition (spec §5, §11, milestone M5): the shared <see cref="FebeApp"/> with the
/// <see cref="DockerPlatform"/> — password-protected interface, Xvfb and Chromium supervised by Febe, the remote view.
/// Start-up checks first: with a problem (password missing, Data folder not writable or on a network share) neither
/// the engine nor the browser start, and the interface shows only the page that explains it. Disposing stops
/// everything in order (remote view, engine, downloads, browser with SIGINT, Xvfb).
/// </summary>
internal sealed class FebeServer : IAsyncDisposable
{
private readonly ServerOptions _options;
private readonly ServerLog _log;
private readonly CancellationTokenSource _lifetime = new();
private readonly List<Task> _background = [];
private readonly List<IDisposable> _disposables = [];
private readonly List<Action> _unsubscribe = [];
private string? _temporaryFolder;
private int _disposed;
private readonly FebeApp _app;
private readonly DockerPlatform _platform;
private FebeServer(ServerOptions options, ServerLog log, IClock clock, IReadOnlyList<ConfigurationProblem> problems)
private FebeServer(FebeApp app, DockerPlatform platform)
{
_options = options;
_log = log;
Clock = clock;
Problems = problems;
_app = app;
_platform = platform;
}
public IClock Clock { get; }
public FebeApp App => _app;
public IReadOnlyList<ConfigurationProblem> Problems { get; }
public IClock Clock => _app.Clock;
public WebApplication Web { get; private set; } = null!;
public IReadOnlyList<ConfigurationProblem> Problems => _app.Problems;
public WebApplication Web => _app.Web;
/// <summary>Where the interface answers (with 127.0.0.1 in place of «any address»).</summary>
public Uri Address { get; private set; } = null!;
public Uri Address => _app.Address;
public FebeDatabase Database { get; private set; } = null!;
public FebeDatabase Database => _app.Database;
public DataFolderLayout? Data { get; private set; }
public DataFolderLayout? Data => _app.Data;
public LibraryLayout? Library { get; private set; }
public LibraryLayout? Library => _app.Library;
public BrowserSupervisor? Browser { get; private set; }
/// <summary>Xvfb and Chromium (null with a configuration problem).</summary>
public ChromiumBrowser? Browser => _app.Browser as ChromiumBrowser;
public ServerConnectionService? Connection { get; private set; }
public BrowserConnectionService? Connection => _app.Connection;
public BrowserRemoteViewHost? RemoteView { get; private set; }
public BrowserRemoteViewHost? RemoteView => _platform.RemoteView;
public EngineHost? Engine { get; private set; }
public EngineHost? Engine => _app.Engine;
public CollectionPipeline? Pipeline { get; private set; }
public CollectionPipeline? Pipeline => _app.Pipeline;
public ImportService? Import { get; private set; }
public ImportService? Import => _app.Import;
public PerceptualHashIndex? HashIndex { get; private set; }
public PerceptualHashIndex? HashIndex => _app.HashIndex;
/// <summary>Completes when browser, pipeline and engine are running (never, with a configuration problem).</summary>
public Task Running => _running.Task;
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Task Running => _app.Running;
public static async Task<FebeServer> StartAsync(ServerOptions options, ServerHooks? hooks = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(options);
hooks ??= new ServerHooks();
var clock = hooks.Clock ?? new SystemClock(options.Zone);
var problems = StartupChecks.Run(options, hooks.DataFolderCheck);
var logFolder = problems.Count == 0 ? new DataFolderLayout(options.DataFolder).Logs : null;
var log = new ServerLog(logFolder, hooks.Console ?? System.Console.Out, clock);
var server = new FebeServer(options, log, clock, problems);
try
{
foreach (var warning in options.Warnings)
{
log.Warn("avvio", warning);
}
if (problems.Count > 0)
{
await server.StartWithProblemsAsync(hooks, ct).ConfigureAwait(false);
}
else
{
await server.StartNormallyAsync(hooks, ct).ConfigureAwait(false);
}
return server;
}
catch
{
await server.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <summary>
/// A configuration problem: only the interface, on an empty temporary database, behind the configuration gate. No
/// engine, no browser, nothing written in the Data folder.
/// </summary>
private async Task StartWithProblemsAsync(ServerHooks hooks, CancellationToken ct)
{
foreach (var problem in Problems)
{
_log.Error("avvio", $"{problem.Title}. {problem.Remedy}");
}
_log.Error("avvio", "Il motore e il browser non partono finché il problema non è risolto: l'interfaccia mostra solo la pagina che lo spiega.");
_temporaryFolder = Path.Combine(Path.GetTempPath(), "febe-problema-" + Guid.NewGuid().ToString("N")[..10]);
Database = await FebeDatabase.OpenAsync(Path.Combine(_temporaryFolder, "dati"), ct).ConfigureAwait(false);
var data = new DataFolderLayout(Path.Combine(_temporaryFolder, "dati"));
var layout = new LibraryLayout(Path.Combine(_temporaryFolder, "libreria"));
var library = new FebeLibrary(Database, data, layout, Clock);
// The same services as a normal start, on the empty temporary database, so that every endpoint can be built;
// the configuration gate answers 503 before any of them runs.
Import = new ImportService(new ImportEnvironment
{
Storage = Database,
Layout = layout,
Journal = new AccountJournal(Clock),
Clock = Clock,
Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")),
DataFolder = data.Root,
});
await StartWebAsync(hooks, services =>
{
services.AddSingleton<IFebeStorage>(Database);
services.AddSingleton(library);
services.AddSingleton<IClock>(Clock);
services.AddSingleton(Import);
services.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
services.AddSingleton<IConfigurationProblems>(new StartupProblems(Problems));
services.AddSingleton<IConnectionService>(new UnavailableConnectionService(Problems));
}).ConfigureAwait(false);
}
private async Task StartNormallyAsync(ServerHooks hooks, CancellationToken ct)
{
var o = _options;
var random = hooks.Random ?? new SystemRandom();
var data = new DataFolderLayout(o.DataFolder);
Data = data;
_log.Info("avvio", $"Febe {typeof(FebeServer).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(o.LibraryFolder)}, importazioni da {Path.GetFullPath(o.ImportFolder)}, fuso {o.ZoneId}, lingua {o.Language}.");
if (o.TestSite is not null)
{
_log.Warn("avvio", $"Modalità di sviluppo: il browser lavora sul sito di prova {o.TestSite.Authority}, non su Instagram.");
}
// Database and library.
Database = await FebeDatabase.OpenAsync(data.Root, ct).ConfigureAwait(false);
var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false);
var layout = new LibraryLayout(o.LibraryFolder);
Library = layout;
TryCreateFolder(layout.Root, "libreria");
var thumbnails = new ThumbnailStore(data.Thumbnails);
var hashes = new PerceptualHashIndex();
hashes.Load(await Database.Media.LoadPerceptualHashesAsync(ct).ConfigureAwait(false));
HashIndex = hashes;
var journal = new AccountJournal(Clock);
var ingest = new LibraryIngest(Database, layout, settings.Naming, journal, Clock, thumbnails, hashes, settings.SetFileTimeToPublication);
var library = new FebeLibrary(Database, data, layout, Clock, hashes);
var staging = Path.Combine(data.Root, "temporanei");
// Import (spec §9): sources under /importa, read-only; what was running when Febe stopped becomes «interrotto».
Import = new ImportService(new ImportEnvironment
{
Storage = Database,
Layout = layout,
Naming = settings.Naming,
Journal = journal,
Clock = Clock,
Thumbnails = thumbnails,
HashIndex = hashes,
Frames = VideoFrameExtractor.TryCreate(),
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(),
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = ImportSourceOptions.Docker(Path.GetFullPath(o.ImportFolder)),
DataFolder = data.Root,
});
var recovered = await Import.RecoverAsync(ct).ConfigureAwait(false);
if (recovered > 0)
{
_log.Info("importazione", $"{recovered.ToString(CultureInfo.InvariantCulture)} importazioni interrotte dall'arresto precedente: si riprendono dalla pagina Importa.");
}
// Browser, connection, remote view, engine. The engine loop starts only once the browser is up.
var tracker = new BrowserUseTracker();
var browser = new BrowserSupervisor(o, data.BrowserProfile, Path.Combine(data.Root, "home"), Clock, _log);
Browser = browser;
var connection = new ServerConnectionService(browser, Database, tracker, Clock, _log, o.LoginUrl, o.Site.SessionCookie);
Connection = connection;
RemoteView = new BrowserRemoteViewHost(browser, tracker, Clock, _log);
var engineOptions = o.FirstSessionDelay is { } delay
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
: EngineOptions.Default;
var services = await EngineServices.CreateAsync(
Database,
Clock,
random,
engineOptions,
userIsDriving: () => browser.UserIsDriving,
isConnected: () => connection.IsConnected == true,
ct: ct).ConfigureAwait(false);
var runner = new DeferredRecipeRunner();
var engine = new EngineHost(services, runner);
Engine = engine;
connection.AttachEngine(engine);
browser.Host.UserDriving.Changed += (_, _) => engine.NotifyUserDrivingChanged();
await StartWebAsync(hooks, s =>
{
s.AddSingleton<IFebeStorage>(Database);
s.AddSingleton(library);
s.AddSingleton<IClock>(Clock);
s.AddSingleton(tracker);
s.AddSingleton(engine.Monitor);
s.AddSingleton<IEngineControl>(new EngineHostControl(engine));
s.AddSingleton<IConnectionService>(connection);
s.AddSingleton<IRemoteViewHost>(RemoteView);
s.AddSingleton<IEngineSettingsControl>(new EngineHostSettingsControl(engine));
s.AddSingleton(ingest);
s.AddSingleton<IBrowserPreview>(new ServerBrowserPreview(browser, Clock));
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
s.AddSingleton(Import);
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
}).ConfigureAwait(false);
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
var lifetime = _lifetime.Token;
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
}
private async Task StartWebAsync(ServerHooks hooks, Action<IServiceCollection> register)
{
var web = FebeWebHost.Build(
_options.WebOptions(),
new FebeListen(_options.ListenAddress, _options.Port),
services =>
{
register(services);
services.Configure<HostOptions>(h => h.ShutdownTimeout = hooks.ShutdownTimeout);
},
logging => logging.AddProvider(_log.ForAspNet()));
try
{
await web.StartAsync().ConfigureAwait(false);
}
catch
{
await web.DisposeAsync().ConfigureAwait(false);
throw;
}
Web = web;
Address = FebeWebHost.BoundAddress(web);
_log.Info("avvio", $"Interfaccia sulla porta {Address.Port.ToString(CultureInfo.InvariantCulture)}{(Problems.Count > 0 ? " (solo la pagina del problema)" : string.Empty)}.");
}
/// <summary>Xvfb and Chromium, then the pipeline, the downloads, the connection check and the engine.</summary>
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, CancellationToken ct)
{
var browser = Browser!;
await browser.RunAsync(ct).ConfigureAwait(false);
if (ct.IsCancellationRequested)
{
return;
}
try
{
var o = _options;
Pipeline = await CollectionPipeline.StartAsync(
new CollectionPipelineOptions
{
Cdp = browser.Host.Cdp,
Site = o.Site,
Storage = Database,
Ingest = ingest,
Governor = services.Governor,
Budget = services.Governor,
DataBudget = services.Governor,
Breaker = services.Breaker,
Clock = Clock,
Random = services.Random,
StagingFolder = staging,
ConfigFolder = Data!.Root,
Pace = services.Settings.Pace,
UserIsDriving = () => browser.UserIsDriving,
Log = _log.ForBrowser(),
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
var changes = Web.Services.GetRequiredService<LibraryChanges>();
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
// Every finished recipe may have queued files: the queue looks at once instead of at its next idle poll.
var downloads = Pipeline.Downloads;
void WakeDownloads(object? sender, EngineNotification n)
{
if (n.Event?.Code.StartsWith("ricetta.", StringComparison.Ordinal) == true)
{
downloads.Wake();
}
}
services.Events.Notified += WakeDownloads;
_unsubscribe.Add(() => services.Events.Notified -= WakeDownloads);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
{
await TestSiteLoginAsync(ct).ConfigureAwait(false);
}
_background.Add(Task.Run(() => Connection.RunAsync(ct), CancellationToken.None));
await engine.StartAsync(ct).ConfigureAwait(false);
_log.Info("motore", Connection.IsConnected == true
? "Motore avviato: il browser è collegato."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).");
_running.TrySetResult();
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Error("avvio", "La raccolta non è partita.", ex);
_running.TrySetException(ex);
}
}
/// <summary>
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
/// the site once, so that its session cookie exists — then back to the rest page.
/// </summary>
private async Task TestSiteLoginAsync(CancellationToken ct)
{
var host = Browser!.Host;
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(host.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(host.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
await host.RestAsync(ct).ConfigureAwait(false);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
_log.Info("collegamento", "Sito di prova: accesso automatico fatto.");
}
/// <summary>
/// The download queue runs all the time (spec §6.5): it talks only to the CDN, so it goes on during a stop of the
/// breaker. An error (browser restarting) ends a pass, never the loop.
/// </summary>
private async Task DownloadLoopAsync(DownloadQueue queue, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await queue.RunAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warn("scaricamenti", "Scaricamenti interrotti: riprendo fra 30 secondi.", ex);
try
{
await Clock.Delay(TimeSpan.FromSeconds(30), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
/// <summary>The daily copy of the database (spec §8.5): at start-up if today's is missing, then once a day.</summary>
private async Task BackupLoopAsync(DailyBackup backup, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var result = await backup.RunAsync(ct).ConfigureAwait(false);
if (result.Created is { } created)
{
_log.Info("copie", $"Copia del database del giorno fatta ({Febe.Core.Engine.ItalianText.Bytes(created.Bytes)}); copie tenute: {backup.List().Count.ToString(CultureInfo.InvariantCulture)}.");
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Error("copie", "Copia del database non riuscita: riprovo fra un'ora.", ex);
try
{
await Clock.Delay(TimeSpan.FromHours(1), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
continue;
}
try
{
await Clock.Delay(UntilNextBackup(Clock.Now, Clock.LocalZone), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
var platform = new DockerPlatform(options);
var app = await FebeApp.StartAsync(options.AppOptions(), platform, hooks.ForApp(), ct).ConfigureAwait(false);
return new FebeServer(app, platform);
}
/// <summary>The next copy: a few minutes after local midnight (03:20, outside the active window of every profile).</summary>
internal static TimeSpan UntilNextBackup(DateTimeOffset now, TimeZoneInfo zone)
{
var tomorrow = LocalCalendar.Today(now, zone).AddDays(1);
var target = LocalCalendar.StartOfDay(tomorrow, zone) + TimeSpan.FromMinutes(200);
var wait = target - now;
return wait < TimeSpan.FromMinutes(1) ? TimeSpan.FromMinutes(1) : wait;
}
internal static TimeSpan UntilNextBackup(DateTimeOffset now, TimeZoneInfo zone) => FebeApp.UntilNextBackup(now, zone);
/// <summary>Temporary files left by an interrupted run (only <c>.febe-*.part</c>: never a library file, rule 12).</summary>
private async Task CleanTemporaryFilesAsync(string staging, LibraryLayout layout, CancellationToken ct)
{
try
{
var removed = SafeFileWriter.CleanupTemporaryFiles(staging, recursive: false);
removed += SafeFileWriter.CleanupTemporaryFiles(layout.Root);
var root = Path.TrimEndingDirectorySeparator(layout.Root) + Path.DirectorySeparatorChar;
foreach (var account in await Database.Accounts.ListAsync(ct).ConfigureAwait(false))
{
var folder = layout.AccountFolder(account);
if (!(folder + Path.DirectorySeparatorChar).StartsWith(root, StringComparison.Ordinal))
{
removed += SafeFileWriter.CleanupTemporaryFiles(folder);
}
}
if (removed > 0)
{
_log.Info("libreria", $"Tolti {removed.ToString(CultureInfo.InvariantCulture)} file temporanei lasciati da un arresto precedente.");
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or OperationCanceledException)
{
_log.Warn("libreria", "Pulizia dei file temporanei non completata.", ex);
}
}
private void TryCreateFolder(string folder, string what)
{
try
{
Directory.CreateDirectory(folder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
_log.Error("avvio", $"La cartella della {what} ({folder}) non si può creare: i file scaricati non avranno dove andare.", ex);
}
}
/// <summary>Stops everything in order: remote view, interface, engine, downloads, import, pipeline, browser, database.</summary>
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
_log.Info("arresto", "Arresto in corso.");
if (RemoteView is { } view)
{
await Quietly(view.ShutdownAsync).ConfigureAwait(false);
}
if (Web is { } web)
{
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
}
if (Engine is { } engine)
{
await Quietly(() => engine.DisposeAsync().AsTask()).ConfigureAwait(false);
}
await _lifetime.CancelAsync().ConfigureAwait(false);
foreach (var task in _background.ToArray())
{
await Quietly(() => task).ConfigureAwait(false);
}
foreach (var disposable in _disposables)
{
disposable.Dispose();
}
foreach (var unsubscribe in _unsubscribe)
{
unsubscribe();
}
if (Import is { } import)
{
await Quietly(() => import.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Pipeline is { } pipeline)
{
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Connection is { } connection)
{
await connection.DisposeAsync().ConfigureAwait(false);
}
if (Browser is { } browser)
{
// Chromium with SIGINT, so that the session is written to the profile (decisions, S3); then Xvfb.
await Quietly(() => browser.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Web is { } app)
{
await Quietly(() => app.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Database is { } database)
{
await Quietly(() => database.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (_temporaryFolder is { } temporary)
{
try
{
Directory.Delete(temporary, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
_log.Info("arresto", "Febe è fermo.");
_log.Dispose();
_lifetime.Dispose();
}
private async Task Quietly(Func<Task> step)
{
try
{
await step().ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (ex is not OperationCanceledException)
{
_log.Warn("arresto", "Un passo dell'arresto non è riuscito.", ex);
}
}
}
public ValueTask DisposeAsync() => _app.DisposeAsync();
}
-56
View File
@@ -1,56 +0,0 @@
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Web.Engine;
namespace Febe.Server;
/// <summary>
/// Preview of the browser for the Attività page (mockup 06): one still frame taken with Page.captureScreenshot when the
/// page asks, at most every few seconds. Reading what the browser shows is not an action toward the site. On the empty
/// rest page there is nothing to show.
/// </summary>
internal sealed class ServerBrowserPreview(BrowserSupervisor browser, IClock clock) : IBrowserPreview
{
private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(4);
private readonly SemaphoreSlim _gate = new(1, 1);
private BrowserFrame? _last;
public async Task<BrowserFrame?> GetLatestAsync(CancellationToken ct)
{
if (!browser.IsAvailable)
{
return null;
}
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
var now = clock.Now;
if (_last is { } cached && now - cached.At < MinimumAge)
{
return cached;
}
var url = await browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
if (string.IsNullOrEmpty(url) || url.StartsWith("about:", StringComparison.OrdinalIgnoreCase))
{
_last = null;
return null;
}
var jpeg = await PagePreview.CaptureAsync(browser.Host.Cdp, ct: ct).ConfigureAwait(false);
_last = new BrowserFrame(jpeg, BrowserRemoteViewConnection.WithoutQuery(url), now);
return _last;
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
{
return null;
}
finally
{
_gate.Release();
}
}
}
-412
View File
@@ -1,412 +0,0 @@
using System.Globalization;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Engine;
namespace Febe.Server;
/// <summary>
/// The link to Instagram in the Docker edition (spec §4.1, PROTOCOLLO.md) over the real browser. «Collegato» means
/// that the session cookie exists in the browser profile: only its existence is checked (<c>Network.getCookies</c>,
/// names only), never its value. Opening the login page is Alberto's action, not the engine's (rule 7, last
/// sentence): it happens only while he holds the «driving» lease and the engine is still.
/// </summary>
internal sealed class ServerConnectionService : IConnectionService, IAsyncDisposable
{
/// <summary>Setting written at the first connection ever (Unix ms): the gradual start begins only once.</summary>
public const string FirstConnectionKey = "collegamento.primo";
/// <summary>A cookie check younger than this is reused by the status (the sidebar asks often).</summary>
public static readonly TimeSpan CookieCacheLifetime = TimeSpan.FromSeconds(3);
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
private readonly BrowserSupervisor _browser;
private readonly IFebeStorage _storage;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly ServerLog _log;
private readonly string _loginUrl;
private readonly SessionCookieOptions _cookie;
private readonly SemaphoreSlim _commands = new(1, 1);
private readonly Lock _gate = new();
private EngineHost? _engine;
private IDisposable? _lease;
private bool? _connected;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
public ServerConnectionService(BrowserSupervisor browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, ServerLog log, string loginUrl, SessionCookieOptions cookie)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
}
/// <summary>
/// Whether the browser holds the session, from the last check (null before the first one). The engine reads it
/// on every turn (<see cref="EngineRuntime.IsConnected"/>): it never waits for the browser.
/// </summary>
public bool? IsConnected
{
get
{
lock (_gate)
{
return _connected;
}
}
}
/// <summary>
/// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition
/// marks it as «Tu» (<see cref="Account.IsMine"/>); the status shows that account. Raised after every change of the
/// connection, so that whoever learns the account can look again.
/// </summary>
public event EventHandler<bool>? ConnectionChanged;
/// <summary>The engine, once it exists (it is built after the browser).</summary>
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
public async Task<ConnectionStatus> GetStatusAsync(CancellationToken ct)
{
var driving = _browser.UserIsDriving;
if (!_browser.IsAvailable)
{
return new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, driving, null);
}
var breaker = _engine?.Services.Breaker.State.Status;
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
? ConnectionState.VerificationRequired
: await CheckAsync(force: false, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
Account? mine = null;
if (state != ConnectionState.NotConnected)
{
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
}
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
}
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
{
EnsureBrowser();
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
lock (_gate)
{
_lease ??= _browser.Host.UserDriving.Begin();
}
_tracker.MarkUsed(_clock.Now);
if (openLogin)
{
// The engine ends its session when the lease starts; wait for it before taking the page.
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
var result = await _browser.Host.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
_log.Info("collegamento", result.Succeeded
? "Alberto usa il browser: pagina di accesso aperta."
: "Alberto usa il browser: la pagina di accesso non si è aperta (errore di rete del browser).");
}
else
{
_log.Info("collegamento", "Alberto usa il browser.");
}
}
finally
{
_commands.Release();
}
}
public async Task<FinishResult> FinishAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
if (!_browser.IsAvailable)
{
ReleaseLease();
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
}
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false) == true;
_tracker.MarkUsed(_clock.Now);
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
await RestQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
string message;
if (!connected)
{
message = "Febe non trova la sessione di Instagram nel browser: l'accesso non sembra completato. Riprova con «Accedi a Instagram» e premi «Ho finito» solo dopo aver visto la tua pagina iniziale.";
}
else if (stopped)
{
message = "Collegato. Febe è ancora fermo per la verifica o la disconnessione: premi «Riprendi» quando vuoi che ricominci.";
}
else if (first)
{
message = "Collegato a Instagram. Febe comincia fra qualche minuto, con calma: nei primi giorni i tetti sono ridotti (avvio graduale).";
}
else
{
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
}
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
return new FinishResult(connected, message);
}
finally
{
_commands.Release();
}
}
public async Task CancelAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_browser.IsAvailable)
{
await RestQuietlyAsync().ConfigureAwait(false);
}
ReleaseLease();
_log.Info("collegamento", "«Annulla»: il browser torna a riposo.");
}
finally
{
_commands.Release();
}
}
public async Task DisconnectAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
var hold = _browser.Host.UserDriving.Begin();
try
{
var engine = _engine;
if (engine is not null)
{
await engine.StopAsync().ConfigureAwait(false);
}
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
SetConnected(false);
if (engine is not null)
{
await engine.Services.Events.WriteAsync(
EventSeverity.Info,
"collegamento.scollegato",
"Scollegato da te: il profilo del browser con la sessione di Instagram è stato cancellato.",
ct: CancellationToken.None).ConfigureAwait(false);
await engine.StartAsync(CancellationToken.None).ConfigureAwait(false);
}
_log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto.");
}
finally
{
ReleaseLease();
hold.Dispose();
_commands.Release();
}
}
/// <summary>
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
/// and after the test site's automatic login.
/// </summary>
public async Task<bool?> RefreshAsync(CancellationToken ct)
{
if (!_browser.IsAvailable)
{
return IsConnected;
}
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false);
if (connected == true)
{
await MarkConnectedAsync(ct).ConfigureAwait(false);
}
return connected;
}
/// <summary>The background check of the cookie, every <see cref="BackgroundCheck"/>, until cancelled.</summary>
public async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await _clock.Delay(BackgroundCheck, ct).ConfigureAwait(false);
if (!_browser.UserIsDriving)
{
await RefreshAsync(ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or IOException)
{
// The browser is restarting: the next turn looks again.
}
}
}
public ValueTask DisposeAsync()
{
ReleaseLease();
_commands.Dispose();
return ValueTask.CompletedTask;
}
private async Task<bool?> CheckAsync(bool force, CancellationToken ct)
{
lock (_gate)
{
if (!force && _connected is not null && _clock.Now - _checkedAt < CookieCacheLifetime)
{
return _connected;
}
}
bool has;
try
{
has = await SessionCookieProbe.HasSessionCookieAsync(_browser.Host.Cdp, _cookie, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
return IsConnected;
}
SetConnected(has);
return has;
}
private void SetConnected(bool connected)
{
bool changed;
lock (_gate)
{
changed = _connected != connected;
_connected = connected;
_checkedAt = _clock.Now;
}
if (changed)
{
_log.Info("collegamento", connected ? "Sessione presente nel browser: collegato." : "Nessuna sessione nel browser: non collegato.");
// Wakes the engine: it looks again whether it can work (it only cancels a session if Alberto is driving).
_engine?.NotifyUserDrivingChanged();
ConnectionChanged?.Invoke(this, connected);
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
private async Task<bool> MarkConnectedAsync(CancellationToken ct)
{
if (await _storage.Settings.GetInt64Async(FirstConnectionKey, ct).ConfigureAwait(false) is not null)
{
return false;
}
var now = _clock.Now;
await _storage.Settings.SetAsync(FirstConnectionKey, now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
if (_engine is { } engine)
{
await engine.Services.NotifyFirstConnectionAsync(ct).ConfigureAwait(false);
await engine.Services.Events.WriteAsync(
EventSeverity.Info,
"collegamento.primo",
"Primo collegamento a Instagram: comincia l'avvio graduale.",
ct: ct).ConfigureAwait(false);
}
_log.Info("collegamento", "Primo collegamento: comincia l'avvio graduale.");
return true;
}
private async Task WaitForSessionEndAsync(CancellationToken ct)
{
if (_engine is not { } engine)
{
return;
}
var deadline = _clock.Now + TimeSpan.FromSeconds(15);
while (engine.Services.Runtime.CurrentSession is not null && _clock.Now < deadline)
{
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
}
private async Task<string?> CurrentUrlAsync(CancellationToken ct)
{
try
{
var url = await _browser.Host.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
return BrowserRemoteViewConnection.WithoutQuery(url);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
{
return null;
}
}
private async Task RestQuietlyAsync()
{
try
{
await _browser.Host.RestAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
// The browser is restarting: it starts on the rest page anyway.
}
}
private void ReleaseLease()
{
IDisposable? lease;
lock (_gate)
{
lease = _lease;
_lease = null;
}
lease?.Dispose();
}
private void EnsureBrowser()
{
if (!_browser.IsAvailable)
{
throw new BadRequestException(_browser.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
}
}
-261
View File
@@ -1,261 +0,0 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using Febe.Browser.Diagnostics;
using Febe.Core.Abstractions;
using Microsoft.Extensions.Logging;
namespace Febe.Server;
/// <summary>
/// The log of the server (spec §8.2, §13.2): one file per local day in <c>Dati/registro</c>
/// (<c>febe-AAAA-MM-GG.log</c>), kept fourteen days, at most 20 MB a day, and the same lines on the console
/// (<c>docker logs</c>). Only actions and outcomes: every message passes through <see cref="Scrub"/>, which removes
/// addresses (signed CDN addresses, tokens); exceptions are written as type and first line only. Passwords, cookies,
/// keys and response bodies never reach this class.
/// </summary>
internal sealed partial class ServerLog : IDisposable
{
public const int DefaultKeepDays = 14;
public const long DefaultMaxBytesPerDay = 20L * 1024 * 1024;
private const string Prefix = "febe-";
private const string Extension = ".log";
private readonly Lock _gate = new();
private readonly string? _folder;
private readonly TextWriter? _console;
private readonly IClock _clock;
private readonly int _keepDays;
private readonly long _maxBytesPerDay;
private StreamWriter? _file;
private DateOnly _day;
private long _written;
private bool _capped;
private bool _disposed;
/// <param name="folder">Dati/registro; null writes to the console only (configuration problems, tests).</param>
/// <param name="console">Console writer; null for none.</param>
/// <param name="clock">Time of the lines and of the daily file.</param>
/// <param name="keepDays">Days of files kept.</param>
/// <param name="maxBytesPerDay">Above this the day's file stops growing (the console still gets the lines).</param>
public ServerLog(string? folder, TextWriter? console, IClock clock, int keepDays = DefaultKeepDays, long maxBytesPerDay = DefaultMaxBytesPerDay)
{
_folder = folder is null ? null : Path.GetFullPath(folder);
_console = console;
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_keepDays = Math.Max(1, keepDays);
_maxBytesPerDay = maxBytesPerDay;
}
/// <summary>Lowest level written to the console; the file gets everything from Information up.</summary>
public LogLevel ConsoleLevel { get; init; } = LogLevel.Information;
/// <summary>The log folder, when there is one.</summary>
public string? Folder => _folder;
public void Info(string source, string message) => Write(LogLevel.Information, source, message);
public void Warn(string source, string message, Exception? exception = null) => Write(LogLevel.Warning, source, message, exception);
public void Error(string source, string message, Exception? exception = null) => Write(LogLevel.Error, source, message, exception);
/// <summary>Writes one line. Never throws: a log that cannot be written must not stop Febe.</summary>
public void Write(LogLevel level, string source, string message, Exception? exception = null)
{
if (level < LogLevel.Information)
{
return;
}
var now = _clock.Now;
var local = TimeZoneInfo.ConvertTime(now, _clock.LocalZone);
var text = Scrub(message);
if (exception is not null)
{
text += $" ({exception.GetType().Name}: {Scrub(FirstLine(exception.Message))})";
}
var line = string.Create(CultureInfo.InvariantCulture, $"{local:yyyy-MM-dd HH:mm:ss.fff zzz} {Label(level)} [{source}] {text}");
lock (_gate)
{
if (_disposed)
{
return;
}
if (_console is not null && level >= ConsoleLevel)
{
try
{
_console.WriteLine(line);
}
catch (IOException)
{
}
}
WriteFileLocked(DateOnly.FromDateTime(local.DateTime), line);
}
}
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write(
level switch
{
BrowserLogLevel.Error => LogLevel.Error,
BrowserLogLevel.Warning => LogLevel.Warning,
BrowserLogLevel.Information => LogLevel.Information,
_ => LogLevel.Debug,
},
"browser",
message,
exception));
/// <summary>The adapter for ASP.NET Core (warnings and errors only; messages scrubbed like every other line).</summary>
public ILoggerProvider ForAspNet() => new Provider(this);
public void Dispose()
{
lock (_gate)
{
_disposed = true;
_file?.Dispose();
_file = null;
}
}
/// <summary>Removes addresses (anything like <c>scheme://…</c>) and line breaks from a message.</summary>
public static string Scrub(string? message)
{
if (string.IsNullOrEmpty(message))
{
return string.Empty;
}
var clean = Addresses().Replace(message, "<indirizzo>");
return clean.Replace('\r', ' ').Replace('\n', ' ');
}
/// <summary>Log files older than <paramref name="keepDays"/> days (today included) are removed; only <c>febe-*.log</c>.</summary>
public static IReadOnlyList<string> ApplyRetention(string folder, DateOnly today, int keepDays)
{
var removed = new List<string>();
if (!Directory.Exists(folder))
{
return removed;
}
var oldestKept = today.AddDays(-(Math.Max(1, keepDays) - 1));
foreach (var file in Directory.EnumerateFiles(folder, Prefix + "*" + Extension))
{
var name = Path.GetFileNameWithoutExtension(file);
if (DateOnly.TryParseExact(name[Prefix.Length..], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var day) && day < oldestKept)
{
try
{
File.Delete(file);
removed.Add(file);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
}
return removed;
}
public static string FileNameFor(DateOnly day) => Prefix + day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + Extension;
private void WriteFileLocked(DateOnly day, string line)
{
if (_folder is null)
{
return;
}
try
{
if (_file is null || day != _day)
{
_file?.Dispose();
_file = null;
Directory.CreateDirectory(_folder);
ApplyRetention(_folder, day, _keepDays);
var path = Path.Combine(_folder, FileNameFor(day));
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
_written = stream.Length;
_file = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
_day = day;
_capped = false;
}
if (_capped)
{
return;
}
if (_written + line.Length + 1 > _maxBytesPerDay)
{
_file.WriteLine("Registro di oggi troppo lungo: le righe successive vanno solo sulla console.");
_capped = true;
return;
}
_file.WriteLine(line);
_written += Encoding.UTF8.GetByteCount(line) + 1;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// The disk is full or the folder went away: the console still has the line.
_file?.Dispose();
_file = null;
}
}
private static string Label(LogLevel level) => level switch
{
LogLevel.Critical or LogLevel.Error => "ERRORE ",
LogLevel.Warning => "AVVISO ",
_ => "INFO ",
};
private static string FirstLine(string text)
{
var line = text.Split('\n')[0].Trim();
return line.Length > 300 ? line[..300] : line;
}
[GeneratedRegex(@"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+", RegexOptions.CultureInvariant)]
private static partial Regex Addresses();
private sealed class Provider(ServerLog log) : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName);
public void Dispose()
{
}
}
private sealed class Logger(ServerLog log, string category) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Warning;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
var source = category.StartsWith("Febe.", StringComparison.Ordinal) ? "web" : "aspnet";
log.Write(logLevel, source, formatter(state, exception), exception);
}
}
}
+19
View File
@@ -1,5 +1,6 @@
using System.Globalization;
using System.Net;
using Febe.App;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Web;
@@ -99,6 +100,24 @@ internal sealed record ServerOptions
/// </summary>
public string LoginUrl => TestSite is { } site ? new Uri(site, "/benvenuto").AbsoluteUri : "https://www.instagram.com/accounts/login/";
/// <summary>The options of the shared composition for the Docker edition.</summary>
public FebeAppOptions AppOptions() => new()
{
DataFolder = DataFolder,
LibraryFolder = LibraryFolder,
LibraryFolderFromSettings = false,
ImportFolder = ImportFolder,
ZoneId = ZoneId,
Zone = Zone,
Language = Language,
Site = Site,
LoginUrl = LoginUrl,
TestSite = TestSite,
TestSiteAutoLogin = TestSiteAutoLogin,
FirstSessionDelay = FirstSessionDelay,
Warnings = Warnings,
};
/// <summary>The interface options of the Docker edition.</summary>
public FebeWebOptions WebOptions() => new()
{
+5 -35
View File
@@ -1,3 +1,4 @@
using Febe.App;
using Febe.Core.Library;
using Febe.Web.Connection;
@@ -11,9 +12,9 @@ internal static class StartupChecks
{
public const string PasswordMissing = "password-mancante";
public const string DataNotWritable = "dati-non-scrivibili";
public const string DataNotWritable = DataFolderProblems.DataNotWritable;
public const string DataOnNetwork = "dati-in-rete";
public const string DataOnNetwork = DataFolderProblems.DataOnNetwork;
/// <summary>Every problem found, in the order the error page shows them.</summary>
public static IReadOnlyList<ConfigurationProblem> Run(ServerOptions options, DataFolderCheck? check = null)
@@ -30,42 +31,11 @@ internal static class StartupChecks
"Imposta FEBE_PASSWORD (nel modello di Unraid o in compose.yml) con una frase lunga che usi solo qui, poi riavvia il contenitore."));
}
if ((check ?? new DataFolderCheck()).Check(options.DataFolder) is { } data)
if (DataFolderProblems.Check(options.DataFolder, check) is { } data)
{
problems.Add(new ConfigurationProblem(
data.Kind == DataFolderProblemKind.NetworkPath ? DataOnNetwork : DataNotWritable,
data.Title,
data.Explanation,
data.Remedy));
problems.Add(data);
}
return problems;
}
}
/// <summary>The problems found at start-up; fixed for the life of the process (fixing one needs a restart).</summary>
internal sealed class StartupProblems(IReadOnlyList<ConfigurationProblem> problems) : IConfigurationProblems
{
public IReadOnlyList<ConfigurationProblem> Current { get; } = problems;
}
/// <summary>
/// The link to Instagram while a configuration problem keeps the browser from starting: always «browser non
/// disponibile», and every command refused with the problem (the configuration gate refuses them earlier anyway).
/// </summary>
internal sealed class UnavailableConnectionService(IReadOnlyList<ConfigurationProblem> problems) : IConnectionService
{
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) =>
Task.FromResult(new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null));
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => throw Refused();
public Task<FinishResult> FinishAsync(CancellationToken ct) => throw Refused();
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
public Task DisconnectAsync(CancellationToken ct) => throw Refused();
private Febe.Web.Api.BadRequestException Refused() =>
new($"{(problems.Count > 0 ? problems[0].Title : "Configurazione da sistemare")}: il browser di Febe non è partito.");
}