using System.Globalization;
using System.Security.Cryptography;
using Febe.Browser.Recipes;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Requests;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Library.StillVideos;
using Febe.Core.Security;
using Febe.Core.Storage;
using Febe.Data;
using Febe.Web;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Febe.App;
///
/// The engine of Febe composed once for both shells (spec §5 «I due involucri»): Febe.Server (Docker) and Febe.Desktop
/// (Windows) differ only in their . Start-up checks first: with a problem (password missing
/// in Docker, Data folder not writable or on a network share, WebView2 missing on Windows) 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, the browser of the platform, the collection pipeline, the download queue,
/// the engine, the connection, the alerts (Windows notifications through the shell, Telegram, free disk space) and the
/// interface. Disposing stops everything in order.
///
public sealed class FebeApp : IAsyncDisposable
{
/// How long a stop waits for «Cerca i video fermi» to give up the video it analyses.
private static readonly TimeSpan StillVideosWait = TimeSpan.FromSeconds(5);
private readonly FebeAppOptions _options;
private readonly IFebePlatform _platform;
private readonly CancellationTokenSource _lifetime = new();
// The start adds to these lists from its background tasks while a stop may already be running (#46): one lock.
private readonly Lock _gate = new();
private readonly List _background = [];
private readonly List _disposables = [];
private readonly List _unsubscribe = [];
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
private TelegramClient? _telegram;
private string? _temporaryFolder;
private RequestCatalog? _requestCatalog;
private ISessionCopier? _copier;
private int _disposed;
private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList problems)
{
_options = options;
_platform = platform;
Log = log;
Clock = clock;
Problems = problems;
}
public IClock Clock { get; }
public FebeLog Log { get; }
public FebeAppOptions Options => _options;
public IFebePlatform Platform => _platform;
public IReadOnlyList Problems { get; }
public WebApplication Web { get; private set; } = null!;
/// Where the interface answers (with 127.0.0.1 in place of «any address»).
public Uri Address { get; private set; } = null!;
public FebeDatabase Database { get; private set; } = null!;
public DataFolderLayout? Data { get; private set; }
/// The library layout at start-up (the desktop may change the folder later: ).
public LibraryLayout? Library { get; private set; }
public IFebeBrowser? Browser { get; private set; }
public BrowserConnectionService? Connection { get; private set; }
///
/// The saved session of the site client (issue #36, S4, §6.0, §13.2): built only with the option «raccolta» on
/// «richieste» and a catalog with configured operations; null otherwise (always with Instagram in S4).
///
public ISavedSiteSession? SavedSession { get; private set; }
/// The site client the recipes use (same conditions as ); null when every recipe goes by the browser.
public HttpSiteRequester? SiteRequester { get; private set; }
public EngineHost? Engine { get; private set; }
public CollectionPipeline? Pipeline { get; private set; }
/// The profile search (issue #37): local suggestions at once, the site's own search box between engine actions.
public ProfileSearchService? Search { get; private set; }
public ImportService? Import { get; private set; }
public PerceptualHashIndex? HashIndex { get; private set; }
///
/// The recorder of the diagnostic report (issue #39), with its log in Dati/diagnostica (null with a
/// configuration problem). Flushed when Febe stops.
///
public CollectionDiagnostics? Diagnostics { get; private set; }
/// When Alberto last used the browser («Riprendi» after a verification).
public BrowserUseTracker Tracker { get; } = new();
///
/// The alerts of spec §13.3 (null with a configuration problem): Windows notifications through the shell's
/// (silent in Docker), Telegram, and the free space of the library and the Data folder.
///
public AlertService? Alerts { get; private set; }
/// Completes when browser, pipeline and engine are running (never, with a configuration problem).
public Task Running => _running.Task;
public static async Task StartAsync(FebeAppOptions options, IFebePlatform platform, FebeAppHooks? hooks = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(platform);
hooks ??= new FebeAppHooks();
var clock = hooks.Clock ?? new SystemClock(options.Zone);
var problems = platform.CheckConfiguration(options, hooks.DataFolderCheck ?? new DataFolderCheck());
var logFolder = problems.Count == 0 ? new DataFolderLayout(options.DataFolder).Logs : null;
var log = new FebeLog(logFolder, hooks.Console, clock);
var app = new FebeApp(options, platform, log, clock, problems);
try
{
foreach (var warning in options.Warnings)
{
log.Warn("avvio", warning);
}
if (problems.Count > 0)
{
await app.StartWithProblemsAsync(hooks, ct).ConfigureAwait(false);
}
else
{
await app.StartNormallyAsync(hooks, ct).ConfigureAwait(false);
}
return app;
}
catch
{
await app.DisposeAsync().ConfigureAwait(false);
throw;
}
}
///
/// 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.
///
private async Task StartWithProblemsAsync(FebeAppHooks 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.
var longWork = new LongWorkGate();
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,
Gate = longWork,
});
var idleConversion = new LibraryConversionWorker(new LibraryConversionEnvironment { Storage = Database, Layout = () => library.Layout, Clock = Clock, Gate = longWork });
await StartWebAsync(hooks, services =>
{
services.AddSingleton(longWork);
services.AddSingleton(idleConversion);
services.AddSingleton(new LibraryConversionQueue(Database, Clock));
services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false));
services.AddSingleton(Database);
services.AddSingleton(library);
services.AddSingleton(Clock);
services.AddSingleton(Tracker);
services.AddSingleton(Import);
services.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
services.AddSingleton(new StartupProblems(Problems));
services.AddSingleton(new ProblemConnectionService(Problems));
_platform.RegisterProblemServices(services, this);
}).ConfigureAwait(false);
}
private async Task StartNormallyAsync(FebeAppHooks hooks, CancellationToken ct)
{
var o = _options;
var random = hooks.Random ?? new SystemRandom();
var data = new DataFolderLayout(o.DataFolder);
Data = data;
// Database first: on Windows the library folder is a setting stored in it.
Database = await FebeDatabase.OpenAsync(data.Root, ct).ConfigureAwait(false);
var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false);
var libraryRoot = o.LibraryFolderFromSettings ? settings.LibraryRoot : o.LibraryFolder;
var importRoot = o.ImportFolder is { } import ? Path.GetFullPath(import) : null;
var exportRoot = hooks.ExportMounts is { } mounts ? o.ExportRoot with { Mounts = mounts } : o.ExportRoot;
var exportState = ExportRoots.Evaluate(exportRoot);
Log.Info("avvio", $"Febe {typeof(FebeApp).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(libraryRoot)}{(importRoot is null ? string.Empty : ", importazioni da " + importRoot)}{ExportLogText(exportRoot, exportState)}, fuso {o.ZoneId}, lingua {o.Language}.");
if (exportRoot is { Root: not null, Declared: true } && !exportState.Active)
{
// Not a configuration problem: the engine starts, the copies stay off until the folder is mounted.
Log.Warn("avvio", exportState.Problem ?? ExportRoots.NotDeclaredText);
}
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.");
}
// Library.
var layout = new LibraryLayout(libraryRoot);
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");
// One gate for import, copies to external folders and rebuild: they never run together (spec §4.10).
var longWork = new LongWorkGate();
// Import (spec §9). Docker: sources under /importa, read-only, over the fixed library; what was running when
// Febe stopped becomes «interrotto». Windows: the web layer's ImportHub builds the service over the library
// and builds it again when the library folder changes in Impostazioni (any source folder, native picker).
if (!o.LibraryFolderFromSettings)
{
Import = new ImportService(new ImportEnvironment
{
Storage = Database,
Layout = layout,
Naming = settings.Naming,
Journal = journal,
Clock = Clock,
Thumbnails = thumbnails,
HashIndex = hashes,
Frames = VideoFrameDecoder.Instance,
VideoProbe = new ContainerVideoMetadataProbe(Clock),
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot),
DataFolder = data.Root,
Gate = longWork,
});
LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false));
}
// Browser, connection, engine. The engine loop starts only once the browser is up.
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
// The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens.
var context = new FebePlatformContext(
o,
data,
Database,
Clock,
Log,
Tracker,
ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
(how, ct) => Connection?.CopyOnWindowClosedAsync(how, ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
PrepareSavedSession(context, browser);
var savedSession = SavedSession;
var sessionFile = data.SessionFile;
Func forget = savedSession is not null
? savedSession.DeleteAsync
: _ =>
{
// Without a saved session in this start («pagine»): a file an earlier start with «richieste» left goes too.
OwnerOnlyFiles.DeleteWithLeftovers(sessionFile);
return Task.CompletedTask;
};
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie, _copier, forget);
Connection = connection;
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.IsReadyToCollect,
ct: ct,
sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false);
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
// capture sees goes to the session in progress, if any.
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
Diagnostics = diagnostics;
services.Diagnostics = diagnostics;
EventHandler permitDenied = (_, permit) => diagnostics.PermitDenied(null, permit.Kind, permit.Reason);
services.Governor.Denied += permitDenied;
OnStop(() => services.Governor.Denied -= permitDenied);
var runner = new DeferredRecipeRunner();
var engine = new EngineHost(services, runner);
Engine = engine;
var search = new ProfileSearchService(services);
Search = search;
search.Start();
connection.AttachEngine(engine);
EventHandler drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
browser.UserDriving.Changed += drivingChanged;
OnStop(() => browser.UserDriving.Changed -= drivingChanged);
_telegram = new TelegramClient(hooks.TelegramHandler);
var telegramChannel = new TelegramAlertChannel(_telegram);
// The conversion for the library (tappa E3, spec §4.10): one worker, started below in the background; it yields
// to import, copies and rebuild through the gate and never runs during an engine session. Never in the demo.
var sessionState = new RuntimeSessionState(services.Runtime);
var conversion = new LibraryConversionWorker(new LibraryConversionEnvironment
{
Storage = Database,
Layout = () => library.Layout,
Clock = Clock,
Gate = longWork,
Session = sessionState,
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
Log = message => Log.Write(LogLevel.Warning, "conversione", message),
});
await StartWebAsync(hooks, s =>
{
s.AddSingleton(longWork);
s.AddSingleton(conversion);
s.AddSingleton(new LibraryConversionQueue(Database, Clock));
s.AddSingleton(exportRoot);
s.AddSingleton(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
if (hooks.StillVideoAnalyser is { } analyser)
{
s.AddSingleton(analyser);
}
s.AddSingleton(sessionState);
s.AddSingleton(Database);
s.AddSingleton(library);
s.AddSingleton(Clock);
s.AddSingleton(Tracker);
s.AddSingleton(engine.Monitor);
s.AddSingleton(new EngineHostControl(engine));
s.AddSingleton(search);
s.AddSingleton(connection);
s.AddSingleton(new EngineHostSettingsControl(engine));
s.AddSingleton(ingest);
s.AddSingleton(new LiveBrowserPreview(browser, Clock));
s.AddSingleton(new RecordedDiagnosticSource(diagnostics));
s.AddSingleton(new StartupProblems([]));
if (Import is not null)
{
s.AddSingleton(Import);
}
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
s.AddSingleton(telegramChannel);
_platform.RegisterServices(s, this);
}).ConfigureAwait(false);
if (Import is null)
{
// The hub's own service: built now, so that an import interrupted by the last stop is marked at once.
await Web.Services.GetRequiredService().GetAsync(ct).ConfigureAwait(false);
}
// Copies to external folders (spec §4.10): built now, so that a copy interrupted by the last stop is marked at once.
var exports = Web.Services.GetRequiredService();
await exports.GetAsync(ct).ConfigureAwait(false);
LogRecoveredExports(exports.Recovered);
// Alerts (spec §13.3): from the engine's timeline and the free space of the two folders, to the shell's
// notifications (the desktop's; in Docker the shell cannot notify and the channel stays silent) and Telegram.
// The strip of the interface is the engine snapshot's. The library folder is read at every check: on Windows
// it can change in Impostazioni while Febe runs.
Alerts = new AlertService(
Database.Settings,
Clock,
services.Events,
[new NativeShellAlertChannel(Web.Services.GetRequiredService()), telegramChannel],
new AlertServiceOptions
{
FolderSource = () => [WatchedFolder.Library(library.Layout.Root), WatchedFolder.Data(data.Root)],
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
Log = (level, message) => Log.Write(level == AlertLogLevel.Warning ? LogLevel.Warning : LogLevel.Information, "avvisi", message),
}).Attach();
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
var lifetime = _lifetime.Token;
InBackground(() => CleanTemporaryFilesAsync(staging, layout, lifetime));
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
InBackground(() => conversion.RunAsync(lifetime));
}
/// Runs in the background; the stop waits for it.
private void InBackground(Func work)
{
lock (_gate)
{
_background.Add(Task.Run(work, CancellationToken.None));
}
}
/// Keeps for the stop; disposes it at once when the stop already took its list.
private void DisposeOnStop(IDisposable disposable)
{
lock (_gate)
{
if (Volatile.Read(ref _disposed) == 0)
{
_disposables.Add(disposable);
return;
}
}
disposable.Dispose();
}
/// Keeps for the stop.
private void OnStop(Action unsubscribe)
{
lock (_gate)
{
_unsubscribe.Add(unsubscribe);
}
}
private async Task StartWebAsync(FebeAppHooks hooks, Action register)
{
var web = FebeWebHost.Build(
_platform.WebOptions,
_platform.Listen,
services =>
{
register(services);
services.Configure(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)}.");
}
/// The browser, then the pipeline, the downloads, the connection check and the engine.
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, ProfileSearchService search, 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.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,
// Rule 7: the pages Alberto opens (login, verification) are his, not the engine's, while no session runs.
UserOwnsPage = () => browser.UserIsDriving && services.Runtime.CurrentSession is null,
Log = Log.ForBrowser(),
Diagnostics = Diagnostics,
PageTurns = services.PageTurns,
SearchOptions = search.Options,
SearchPhotos = search.Photos,
// Requests (#36, S4): only with «raccolta» on «richieste» and configured operations; otherwise every
// recipe goes by the browser, as before.
Requests = CreateSiteRequests(),
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
if (Pipeline.Search is { } searchRunner)
{
search.Attach(searchRunner, Pipeline.SearchPhotos);
}
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
var changes = Web.Services.GetRequiredService();
DisposeOnStop(changes.Attach(Pipeline.Downloads, Clock));
InBackground(() => DownloadLoopAsync(Pipeline.Downloads, ct));
// 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(EngineEventCodes.RecipePrefix, StringComparison.Ordinal) == true)
{
downloads.Wake();
}
}
services.Events.Notified += WakeDownloads;
OnStop(() => services.Events.Notified -= WakeDownloads);
// With the test site's automatic login the first look reports nothing: the session it may not find yet is
// the one the login below opens (issue #52), not a disconnection.
await Connection!.RefreshAsync(ct, mayReport: !o.TestSiteAutoLogin).ConfigureAwait(false);
if (o.TestSiteAutoLogin && (Connection.IsConnected != true || (SavedSession is not null && SavedSession.Read() is null)))
{
await TestSiteLoginAsync(ct).ConfigureAwait(false);
}
InBackground(() => Connection.RunAsync(ct));
await engine.StartAsync(ct).ConfigureAwait(false);
Log.Info("motore", StartedMessage(Connection));
_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);
}
}
///
/// Which reader vocabulary and target map the collection uses, in the log: where each came from (embedded in Febe or
/// the copy in the Data folder) and in what state, never what is in them; a warning when a copy in the Data folder
/// hides a better embedded file. Then the engine clears, once, the suspensions and failures of the recipes counted
/// against other files (). Before the engine loop starts.
///
private async Task CheckCollectionConfigurationAsync(CollectionPipeline pipeline, EngineHost engine, CancellationToken ct)
{
try
{
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap, SiteRequester is not null ? _requestCatalog : null);
foreach (var line in configuration.Lines)
{
Log.Info("raccolta", line);
}
foreach (var warning in configuration.Warnings)
{
Log.Warn("raccolta", warning);
}
if (await engine.ApplyCollectionConfigurationAsync(configuration.Fingerprint, ct).ConfigureAwait(false))
{
Log.Info("raccolta", $"Configurazione della raccolta diversa dall'ultimo avvio (impronta {configuration.Fingerprint[..12]}): sospensioni ed errori contati delle ricette azzerati.");
}
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
// Never a reason not to collect: the suspensions stay as they are, «Riattiva» still clears them.
Log.Warn("raccolta", "Non riesco a confrontare la configurazione della raccolta con quella dell'ultimo avvio: le ricette sospese restano come sono.", ex);
}
}
///
/// The gate of S4 (issue #36, decision of 17 November 2026): the saved session, its copy at «Ho finito» and the site
/// client exist only with the option «raccolta» on «richieste» AND a catalog of the site with at least one
/// configured operation. With «pagine» (the default) nothing is built, and one line of the log says so (§6.0: the
/// log says which route Febe took); with Instagram (no operation configured in S4) nothing is built either: no cookie
/// value is read, no module of the page.
///
private void PrepareSavedSession(FebePlatformContext context, IFebeBrowser browser)
{
var o = _options;
if (o.Collection != CollectionRoute.Requests)
{
Log.Info("raccolta", "Raccolta «pagine»: tutte le ricette con il browser (nessuna sessione salvata, nessun client del sito).");
return;
}
var catalog = LoadRequestCatalog(context.Data);
if (catalog is null || !catalog.Configured.Any())
{
Log.Info("raccolta", $"Raccolta «richieste»: nessuna operazione configurata in richieste.{o.Site.Name}.json, tutte le ricette restano al browser (nessuna sessione salvata, nessun client del sito).");
return;
}
try
{
var protector = _platform.CreateSessionProtector(context);
var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
var rules = LoadSignalRules(context.Data);
var settings = context.Storage.Settings;
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message))
{
// What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once.
IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy,
};
_requestCatalog = catalog;
SavedSession = saved;
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito», alla chiusura della finestra del browser e alla fine della guida.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
{
// Never a reason not to collect: the browser does every recipe, as with «pagine». The kind of error only.
Log.Error("raccolta", $"Raccolta «richieste» non attivata: la cifratura della sessione salvata non è pronta ({ex.GetType().Name}). Tutte le ricette restano al browser.");
}
}
/// The catalog of the site: the copy in the Data folder, or the embedded file when there is none or it is not valid.
private RequestCatalog? LoadRequestCatalog(DataFolderLayout data)
{
var name = $"richieste.{_options.Site.Name}.json";
try
{
return RequestCatalog.LoadOrEmbedded(Path.Combine(data.Root, name), name);
}
catch (InvalidDataException ex)
{
Log.Warn("raccolta", $"{name} nella cartella dei dati non è valido: uso quello di Febe. {ex.Message}");
}
try
{
return RequestCatalog.LoadEmbedded(name);
}
catch (Exception ex) when (ex is InvalidDataException or FileNotFoundException)
{
Log.Warn("raccolta", $"Nessun catalogo delle richieste per il sito «{_options.Site.Name}».");
return null;
}
}
/// The stop rules of the site as the pipeline loads them: their login and verification paths are pages where no copy is made.
private SignalRules? LoadSignalRules(DataFolderLayout data)
{
var file = Path.Combine(data.Root, _options.Site.SignalsFile);
try
{
return File.Exists(file) ? SignalRules.Load(file) : SignalRules.LoadEmbedded(_options.Site.SignalsFile);
}
catch (InvalidDataException)
{
return SignalRules.LoadEmbedded(_options.Site.SignalsFile);
}
}
///
/// The site client of the recipes, over the saved session (issue #36, S4): only when
/// built one. Instagram's options for Instagram, the test site's for the test site; any other site gets none.
///
private SiteRequestOptions? CreateSiteRequests()
{
if (SavedSession is not { } session || _requestCatalog is not { } catalog)
{
return null;
}
var o = _options;
HttpSiteRequesterOptions? options = catalog.Site switch
{
"instagram" => HttpSiteRequesterOptions.Instagram(),
"prova" => HttpSiteRequesterOptions.TestSite(new Uri(o.Site.BaseUrl.TrimEnd('/') + "/"), o.Site.SessionCookie.CookieName),
_ => null,
};
if (options is null)
{
Log.Warn("raccolta", $"Client del sito non costruito: il sito «{catalog.Site}» non ha opzioni del client. Tutte le ricette restano al browser.");
return null;
}
try
{
var requester = new HttpSiteRequester(catalog, session, options, Clock, line => Log.Info("client", line));
DisposeOnStop(requester);
SiteRequester = requester;
return new SiteRequestOptions(requester, catalog);
}
catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
{
// The messages of the client name a variable or an option, never a value of the session.
Log.Warn("raccolta", "Client del sito non costruito: " + ex.Message + " Tutte le ricette restano al browser.");
return null;
}
}
///
/// The start-up line of the engine, with what it waits for: the same state as the engine's own gate
/// (), so that the log never says «collegato» while the monitor
/// says «Serve «Ho finito»».
///
internal static string StartedMessage(BrowserConnectionService connection)
{
ArgumentNullException.ThrowIfNull(connection);
if (connection.IsReadyToCollect)
{
return "Motore avviato: il browser è collegato.";
}
return connection.IsConnected == true && connection.SessionCopyMissing
? "Motore avviato: il browser è collegato, ma aspetta la copia della sessione per le richieste (pagina Collegamento, «Ho finito»)."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).";
}
/// The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».
private static string HomeUrl(string baseUrl) =>
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
///
/// Development with the test site only (--accesso-di-prova): what Alberto does by hand on Instagram — open
/// the site once, so that its session cookie exists, and with a saved session copy it as «Ho finito» would (S4) —
/// then back to the rest page. Before the engine starts, under a hold of the driving gate as Alberto's own login.
///
private async Task TestSiteLoginAsync(CancellationToken ct)
{
var browser = Browser!;
var hold = _copier is null ? null : browser.UserDriving.Begin();
try
{
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, _options.LoginUrl, ct).ConfigureAwait(false);
await Febe.Browser.Cdp.CdpPageExtensions.WaitForLoadAsync(browser.Cdp, Clock, TimeSpan.FromSeconds(15), ct).ConfigureAwait(false);
if (_copier is not null)
{
await _copier.CopyAsync(() => true, ct).ConfigureAwait(false);
}
}
finally
{
hold?.Dispose();
}
await browser.RestAsync(ct).ConfigureAwait(false);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
Log.Info("collegamento", "Sito di prova: accesso automatico fatto.");
}
///
/// 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.
///
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;
}
}
}
}
/// The daily copy of the database (spec §8.5): at start-up if today's is missing, then once a day.
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 ({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;
}
}
}
/// The next copy: a few minutes after local midnight (03:20, outside the active window of every profile).
public 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;
}
/// Temporary files left by an interrupted run (only .febe-*.part: never a library file, rule 12).
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 LogRecoveredExports(int recovered)
{
if (recovered > 0)
{
Log.Info("esportazione", recovered == 1
? "Una copia interrotta dall'arresto precedente: si riprende dalla Dashboard, scheda Esportazione."
: $"{recovered.ToString(CultureInfo.InvariantCulture)} copie interrotte dall'arresto precedente: si riprendono dalla Dashboard, scheda Esportazione.");
}
}
/// The part of the start-up line about the copies to external folders (Docker only).
private static string ExportLogText(ExportRootOptions root, ExportRootState state) => root.Root switch
{
null => string.Empty,
var folder when state.Active => ", copie esterne in " + folder,
var folder when !root.Declared => $", copie esterne spente ({folder} non dichiarata)",
var folder => $", copie esterne spente ({folder} non montata)",
};
private void LogRecovered(int recovered)
{
if (recovered > 0)
{
Log.Info("importazione", $"{recovered.ToString(CultureInfo.InvariantCulture)} importazioni interrotte dall'arresto precedente: si riprendono dalla pagina Importa.");
}
}
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);
}
}
///
/// Stops everything in order: the shell's own first (remote view), interface, engine, downloads, alerts, import,
/// pipeline, browser, database.
///
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 1)
{
return;
}
Log.Info("arresto", "Arresto in corso.");
await Quietly(_platform.StoppingAsync).ConfigureAwait(false);
if (Web is { } web)
{
await Quietly(() => web.StopAsync()).ConfigureAwait(false);
// «Cerca i video fermi» (tappa E4): the job gives up the video it analyses (nothing stored for it) and ends
// before the database closes; it does not resume at the next start (answer 41). Not waited for without an end:
// a read stuck on a library that does not answer (a network folder) must not keep the engine and the browser
// from closing in time, and its result would not be stored anyway.
await Quietly(async () =>
{
var stills = web.Services.GetRequiredService();
stills.Dispose();
await stills.Job.WaitAsync(StillVideosWait).ConfigureAwait(false);
}).ConfigureAwait(false);
}
if (Engine is { } engine)
{
await Quietly(() => engine.DisposeAsync().AsTask()).ConfigureAwait(false);
}
await _lifetime.CancelAsync().ConfigureAwait(false);
// A start still in progress adds tasks while the first ones are awaited: look again until nothing new appears,
// so nothing still reads the database once it is closed (#46).
var awaited = 0;
while (true)
{
Task[] pending;
lock (_gate)
{
pending = _background.Skip(awaited).ToArray();
}
if (pending.Length == 0)
{
break;
}
foreach (var task in pending)
{
await Quietly(() => task).ConfigureAwait(false);
}
awaited += pending.Length;
}
IDisposable[] disposables;
Action[] unsubscribes;
lock (_gate)
{
disposables = [.. _disposables];
unsubscribes = [.. _unsubscribe];
_disposables.Clear();
}
foreach (var disposable in disposables)
{
disposable.Dispose();
}
foreach (var unsubscribe in unsubscribes)
{
unsubscribe();
}
// Alerts in flight are cancelled before the Telegram client goes away.
Alerts?.Dispose();
_telegram?.Dispose();
if (Import is { } import)
{
await Quietly(() => import.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Search is { } profileSearch)
{
profileSearch.Detach();
await Quietly(() => profileSearch.DisposeAsync().AsTask()).ConfigureAwait(false);
}
if (Pipeline is { } pipeline)
{
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
}
// What is still open of the diagnostic report: sessions as in progress, the day outside sessions as it is.
Diagnostics?.Dispose();
if (Connection is { } connection)
{
await connection.DisposeAsync().ConfigureAwait(false);
}
if (Browser is { } browser)
{
// Chromium with SIGINT, WebView2 closed and waited for, so that the session is written to the profile (S3).
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 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);
}
}
}
}