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:
73 files changed
+7914
-699
No files matched your search
@@ -0,0 +1,203 @@
|
||||
using System.Threading.Channels;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>The events of spec §13.3 that deserve an alert besides the red strip of the interface.</summary>
|
||||
public enum AlertKind
|
||||
{
|
||||
/// <summary>«Verifica richiesta».</summary>
|
||||
Verification,
|
||||
|
||||
/// <summary>«Disconnessione».</summary>
|
||||
Disconnection,
|
||||
|
||||
/// <summary>«Fermo per rallentamento e ripresa».</summary>
|
||||
Throttle,
|
||||
|
||||
/// <summary>«Storico di un account completato».</summary>
|
||||
BackfillDone,
|
||||
|
||||
/// <summary>«Disco quasi pieno».</summary>
|
||||
DiskLow,
|
||||
|
||||
/// <summary>«Formato non riconosciuto».</summary>
|
||||
UnknownFormat,
|
||||
}
|
||||
|
||||
/// <summary>One alert: Italian title and text, no captions, bodies, cookies or addresses (spec §13.2).</summary>
|
||||
public sealed record FebeAlert(AlertKind Kind, string Title, string Message, DateTimeOffset At, long? AccountId);
|
||||
|
||||
/// <summary>
|
||||
/// A channel alerts go to besides the red strip (spec §13.3): Windows notifications on the desktop; Telegram (M8)
|
||||
/// registers its own. Registered by the shells in DI as <c>IAlertChannel</c>; <see cref="AlertDispatcher"/> calls them.
|
||||
/// </summary>
|
||||
public interface IAlertChannel
|
||||
{
|
||||
/// <summary>Whether this channel is on with the settings of Impostazioni, Notifiche.</summary>
|
||||
bool IsEnabled(AlertSettings settings);
|
||||
|
||||
/// <summary>Sends one alert. Never logs the message or any address of the channel.</summary>
|
||||
Task SendAsync(FebeAlert alert, AlertSettings settings, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Which engine events become alerts (spec §13.3), and whether Alberto wants them.</summary>
|
||||
public static class AlertRules
|
||||
{
|
||||
/// <summary>Code of the «disco quasi pieno» event, for whoever measures the free space (M8).</summary>
|
||||
public const string DiskLowCode = "disco-quasi-pieno";
|
||||
|
||||
private const int MaxMessage = 240;
|
||||
|
||||
/// <summary>The alert for a timeline event, or null when the event is not one of §13.3.</summary>
|
||||
public static FebeAlert? FromEvent(EventRecord record)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
(AlertKind Kind, string Title)? match = record.Code switch
|
||||
{
|
||||
EngineEventCodes.ChallengeStop => (AlertKind.Verification, "Instagram chiede una verifica"),
|
||||
EngineEventCodes.DisconnectStop => (AlertKind.Disconnection, "Febe è stato scollegato da Instagram"),
|
||||
EngineEventCodes.ThrottleStop => (AlertKind.Throttle, "Febe si è fermato per un rallentamento"),
|
||||
EngineEventCodes.ThrottleEnd => (AlertKind.Throttle, "Il fermo per rallentamento è finito"),
|
||||
EngineEventCodes.Resumed => (AlertKind.Throttle, "Febe ha ripreso"),
|
||||
EngineEventCodes.BackfillCompleted => (AlertKind.BackfillDone, "Storico completato"),
|
||||
EngineEventCodes.FormatUnrecognized => (AlertKind.UnknownFormat, "Formato non riconosciuto"),
|
||||
DiskLowCode => (AlertKind.DiskLow, "Disco quasi pieno"),
|
||||
_ => null,
|
||||
};
|
||||
if (match is not { } m)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var text = record.Message.Length > MaxMessage ? record.Message[..(MaxMessage - 1)] + "…" : record.Message;
|
||||
return new FebeAlert(m.Kind, m.Title, text, record.At, record.AccountId);
|
||||
}
|
||||
|
||||
/// <summary>True when Alberto wants alerts of this kind (Impostazioni, Notifiche).</summary>
|
||||
public static bool Wanted(AlertKind kind, AlertEvents events)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(events);
|
||||
return kind switch
|
||||
{
|
||||
AlertKind.Verification => events.Verification,
|
||||
AlertKind.Disconnection => events.Disconnection,
|
||||
AlertKind.Throttle => events.Throttle,
|
||||
AlertKind.BackfillDone => events.BackfillDone,
|
||||
AlertKind.DiskLow => events.DiskLow,
|
||||
AlertKind.UnknownFormat => events.UnknownFormat,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The alerts hook of the shared composition (spec §13.3): listens to the engine's timeline, turns the events of §13.3
|
||||
/// into <see cref="FebeAlert"/>s and hands them, in order and off the engine's thread, to every enabled
|
||||
/// <see cref="IAlertChannel"/>. A channel that fails is logged by type only and never stops the others.
|
||||
/// </summary>
|
||||
public sealed class AlertDispatcher : IAsyncDisposable
|
||||
{
|
||||
private readonly EngineEvents _events;
|
||||
private readonly ISettingsStore _settings;
|
||||
private readonly IReadOnlyList<IAlertChannel> _channels;
|
||||
private readonly FebeLog _log;
|
||||
private readonly Channel<FebeAlert> _queue = Channel.CreateBounded<FebeAlert>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly Task _loop;
|
||||
|
||||
public AlertDispatcher(EngineEvents events, ISettingsStore settings, IEnumerable<IAlertChannel> channels, FebeLog log)
|
||||
{
|
||||
_events = events ?? throw new ArgumentNullException(nameof(events));
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_channels = [.. channels ?? throw new ArgumentNullException(nameof(channels))];
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_events.Notified += OnNotified;
|
||||
_loop = Task.Run(() => RunAsync(_stop.Token));
|
||||
}
|
||||
|
||||
/// <summary>The channels alerts go to.</summary>
|
||||
public IReadOnlyList<IAlertChannel> Channels => _channels;
|
||||
|
||||
/// <summary>Alerts sent since the start (tests).</summary>
|
||||
public int Sent => Volatile.Read(ref _sent);
|
||||
|
||||
private int _sent;
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
_events.Notified -= OnNotified;
|
||||
_queue.Writer.TryComplete();
|
||||
await _stop.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await _loop.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private void OnNotified(object? sender, EngineNotification notification)
|
||||
{
|
||||
if (_channels.Count == 0 || notification.Kind != EngineNotificationKind.Event || notification.Event is not { } record)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (AlertRules.FromEvent(record) is { } alert)
|
||||
{
|
||||
_queue.Writer.TryWrite(alert);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
await foreach (var alert in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
AlertSettings settings;
|
||||
try
|
||||
{
|
||||
settings = await AlertSettingsStore.LoadAsync(_settings, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("avvisi", "Impostazioni degli avvisi non leggibili: avviso non inviato.", ex);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!AlertRules.Wanted(alert.Kind, settings.Events))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var channel in _channels)
|
||||
{
|
||||
if (!channel.IsEnabled(settings))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await channel.SendAsync(alert, settings, ct).ConfigureAwait(false);
|
||||
Interlocked.Increment(ref _sent);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Type only: the message of a channel's exception could contain its address (Telegram's has the token).
|
||||
_log.Warn("avvisi", $"Un avviso non è partito ({channel.GetType().Name}: {ex.GetType().Name}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
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.App;
|
||||
|
||||
/// <summary>
|
||||
/// The link to Instagram over the real browser, the same in both shells (spec §4.1, §10.3, PROTOCOLLO.md). «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.
|
||||
/// On Windows the browser is the window «Browser di Febe»: «Accedi» and «Portalo in primo piano» bring it to the front,
|
||||
/// «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the profile. In Docker
|
||||
/// showing and hiding do nothing (the remote view shows the browser).
|
||||
/// </summary>
|
||||
public sealed class BrowserConnectionService : 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 IFebeBrowser _browser;
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly FebeLog _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 BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog 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.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.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.");
|
||||
}
|
||||
|
||||
// Windows: the window «Browser di Febe» comes to the front (Docker: nothing, the remote view shows it).
|
||||
await ShowQuietlyAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
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);
|
||||
await HideQuietlyAsync().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);
|
||||
await HideQuietlyAsync().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.UserDriving.Begin();
|
||||
try
|
||||
{
|
||||
var engine = _engine;
|
||||
if (engine is not null)
|
||||
{
|
||||
await engine.StopAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Windows: the browser window goes out of view and WebView2 closes before its folder is deleted.
|
||||
await HideQuietlyAsync().ConfigureAwait(false);
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
|
||||
SetConnected(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file of the profile stayed (Windows: a process of the browser held it). The engine starts again
|
||||
// anyway; whether the session is still there is checked again, never assumed.
|
||||
failure = ex;
|
||||
await RefreshAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (engine is not null)
|
||||
{
|
||||
if (failure is 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);
|
||||
}
|
||||
|
||||
if (failure is not null)
|
||||
{
|
||||
_log.Warn("collegamento", "«Scollega»: il profilo del browser non si è potuto cancellare del tutto.", failure);
|
||||
throw new BadRequestException("«Scollega» non è riuscito del tutto: " + failure.Message);
|
||||
}
|
||||
|
||||
_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.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.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
||||
return Addresses.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.RestAsync(CancellationToken.None).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 async Task ShowQuietlyAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _browser.ShowToUserAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or IOException)
|
||||
{
|
||||
_log.Warn("collegamento", "La finestra del browser non è venuta in primo piano.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HideQuietlyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _browser.HideFromUserAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or IOException)
|
||||
{
|
||||
_log.Warn("collegamento", "La finestra del browser non si è nascosta.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>How a Chromium-family browser is started and looked after (spec §6.1, §11; S2 fallback on Windows).</summary>
|
||||
public sealed record ChromiumBrowserSettings
|
||||
{
|
||||
/// <summary>The profile folder given to the browser (<c>--user-data-dir</c>): it holds the Instagram session.</summary>
|
||||
public required string ProfileDirectory { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The folder «Scollega» deletes while the browser is stopped. Null: <see cref="ProfileDirectory"/>. On Windows the
|
||||
/// Edge profile is a subfolder of <c>Dati\browser</c>, and «Scollega» deletes the whole <c>Dati\browser</c>.
|
||||
/// </summary>
|
||||
public string? ProfileFolderToDelete { get; init; }
|
||||
|
||||
/// <summary>Folder created before the start (Docker: the HOME of the browser process). Null: none.</summary>
|
||||
public string? HomeDirectory { get; init; }
|
||||
|
||||
/// <summary>Size of the browser window, always the same (spec §6.1).</summary>
|
||||
public int WindowWidth { get; init; } = 1280;
|
||||
|
||||
public int WindowHeight { get; init; } = 900;
|
||||
|
||||
/// <summary>The fixed DevTools port, on 127.0.0.1 only (spec §6.1).</summary>
|
||||
public int DebugPort { get; init; } = 9222;
|
||||
|
||||
/// <summary>The executable; null: <see cref="ChromiumCommandLine.FindExecutable"/>.</summary>
|
||||
public string? ExecutablePath { get; init; }
|
||||
|
||||
/// <summary>The Xvfb display (Docker, «:99»). Null: no virtual display, the browser opens a normal window.</summary>
|
||||
public string? Display { get; init; }
|
||||
|
||||
/// <summary>Arguments, environment, cookie of the session, restart policy.</summary>
|
||||
public ChromiumLaunchOptions Launch { get; init; } = new();
|
||||
|
||||
/// <summary>Added to the «browser ready» log line (Docker: «, senza sandbox (FEBE_SENZA_SANDBOX)»).</summary>
|
||||
public string? ReadyRemark { get; init; }
|
||||
|
||||
/// <summary>Added to a start error that mentions the sandbox (Docker: where the seccomp profile is explained).</summary>
|
||||
public string? SandboxAdvice { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A Chromium-family browser started and supervised by Febe itself, never by a shell script (spec §5, §6.1, §11): the
|
||||
/// distribution's Chromium on Xvfb in Docker, or Edge on Windows as the last fallback of S2. A start that fails
|
||||
/// (browser 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>
|
||||
public sealed class ChromiumBrowser : IFebeBrowser
|
||||
{
|
||||
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
|
||||
|
||||
private readonly ChromiumBrowserSettings _settings;
|
||||
private readonly IClock _clock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private XvfbProcess? _xvfb;
|
||||
private volatile bool _started;
|
||||
private volatile string? _lastError;
|
||||
|
||||
public ChromiumBrowser(ChromiumBrowserSettings settings, IClock clock, FebeLog log)
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
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(settings.ProfileDirectory);
|
||||
HomeDirectory = settings.HomeDirectory is { } home ? Path.GetFullPath(home) : null;
|
||||
Host = new ChromiumProcessHost(settings.Launch, _clock, log.ForBrowser());
|
||||
BrowserOptions = new BrowserOptions(
|
||||
ProfileDirectory,
|
||||
settings.WindowWidth,
|
||||
settings.WindowHeight,
|
||||
settings.DebugPort,
|
||||
settings.ExecutablePath,
|
||||
settings.Display);
|
||||
}
|
||||
|
||||
/// <summary>The browser: stable for the whole life of the composition (a «Scollega» restarts it in place).</summary>
|
||||
public ChromiumProcessHost Host { get; }
|
||||
|
||||
public BrowserOptions BrowserOptions { get; }
|
||||
|
||||
public ICdpSession Cdp => Host.Cdp;
|
||||
|
||||
public UserDrivingGate UserDriving => Host.UserDriving;
|
||||
|
||||
public string ProfileDirectory { get; }
|
||||
|
||||
/// <summary>HOME of the browser process (certificate database, font cache); null when not set.</summary>
|
||||
public string? HomeDirectory { get; }
|
||||
|
||||
public int WindowWidth => BrowserOptions.WindowWidth;
|
||||
|
||||
public int WindowHeight => BrowserOptions.WindowHeight;
|
||||
|
||||
/// <summary>True when the browser runs on a virtual display (Docker).</summary>
|
||||
public bool UsesXvfb => _settings.Display is not null;
|
||||
|
||||
/// <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;
|
||||
|
||||
public string? LastError => _lastError;
|
||||
|
||||
public bool UserIsDriving => Host.UserIsDriving;
|
||||
|
||||
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 {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, porta di debug {_settings.DebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1{_settings.ReadyRemark}.");
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task<NavigationResult> RestAsync(CancellationToken ct) => Host.RestAsync(ct);
|
||||
|
||||
/// <summary>Nothing: in Docker the remote view shows the browser (on Windows, <c>EdgeBrowser</c> moves the window).</summary>
|
||||
public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
/// <summary>Nothing: on Xvfb the window is never in anyone's view.</summary>
|
||||
public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// «Scollega» (spec §4.1): stops the browser (SIGINT on Linux, 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)
|
||||
{
|
||||
if (HomeDirectory is { } home)
|
||||
{
|
||||
Directory.CreateDirectory(home);
|
||||
}
|
||||
|
||||
if (_settings.Display is { } display && _xvfb is null)
|
||||
{
|
||||
RemoveStaleDisplayLock(display);
|
||||
var xvfb = new XvfbProcess(display, WindowWidth, 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()
|
||||
{
|
||||
var folder = _settings.ProfileFolderToDelete is { } root ? Path.GetFullPath(root) : ProfileDirectory;
|
||||
if (Directory.Exists(folder))
|
||||
{
|
||||
Directory.Delete(folder, 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 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 + _settings.SandboxAdvice,
|
||||
_ => $"{ex.GetType().Name}: {ex.Message}",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <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>
|
||||
public 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;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- La composizione condivisa delle due vesti (specifica §5, «I due involucri»): database, libreria, importazione,
|
||||
copie, browser, raccolta, scaricamenti, motore, collegamento, avvisi e interfaccia web. Le parti che cambiano fra
|
||||
Docker e Windows (browser, guscio nativo, cartelle, accesso) arrivano da IFebePlatform. -->
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
<ProjectReference Include="..\Febe.Core\Febe.Core.csproj" />
|
||||
<ProjectReference Include="..\Febe.Data\Febe.Data.csproj" />
|
||||
<ProjectReference Include="..\Febe.Browser\Febe.Browser.csproj" />
|
||||
<ProjectReference Include="..\Febe.Web\Febe.Web.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Febe.Tests" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,639 @@
|
||||
using System.Globalization;
|
||||
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;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="IFebePlatform"/>. 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 hook and the interface. Disposing stops everything in order.
|
||||
/// </summary>
|
||||
public sealed class FebeApp : IAsyncDisposable
|
||||
{
|
||||
private readonly FebeAppOptions _options;
|
||||
private readonly IFebePlatform _platform;
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<Task> _background = [];
|
||||
private readonly List<IDisposable> _disposables = [];
|
||||
private readonly List<Action> _unsubscribe = [];
|
||||
private readonly TaskCompletionSource _running = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private string? _temporaryFolder;
|
||||
private int _disposed;
|
||||
|
||||
private FebeApp(FebeAppOptions options, IFebePlatform platform, FebeLog log, IClock clock, IReadOnlyList<ConfigurationProblem> 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<ConfigurationProblem> Problems { get; }
|
||||
|
||||
public WebApplication Web { get; private set; } = null!;
|
||||
|
||||
/// <summary>Where the interface answers (with 127.0.0.1 in place of «any address»).</summary>
|
||||
public Uri Address { get; private set; } = null!;
|
||||
|
||||
public FebeDatabase Database { get; private set; } = null!;
|
||||
|
||||
public DataFolderLayout? Data { get; private set; }
|
||||
|
||||
/// <summary>The library layout at start-up (the desktop may change the folder later: <see cref="FebeLibrary.Layout"/>).</summary>
|
||||
public LibraryLayout? Library { get; private set; }
|
||||
|
||||
public IFebeBrowser? Browser { get; private set; }
|
||||
|
||||
public BrowserConnectionService? Connection { get; private set; }
|
||||
|
||||
public EngineHost? Engine { get; private set; }
|
||||
|
||||
public CollectionPipeline? Pipeline { get; private set; }
|
||||
|
||||
public ImportService? Import { get; private set; }
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
|
||||
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
|
||||
public BrowserUseTracker Tracker { get; } = new();
|
||||
|
||||
/// <summary>The alerts hook (null with a configuration problem).</summary>
|
||||
public AlertDispatcher? Alerts { get; private set; }
|
||||
|
||||
/// <summary>Completes when browser, pipeline and engine are running (never, with a configuration problem).</summary>
|
||||
public Task Running => _running.Task;
|
||||
|
||||
public static async Task<FebeApp> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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(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.
|
||||
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(Tracker);
|
||||
services.AddSingleton(Import);
|
||||
services.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
|
||||
services.AddSingleton<IConfigurationProblems>(new StartupProblems(Problems));
|
||||
services.AddSingleton<IConnectionService>(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;
|
||||
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)}, 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.");
|
||||
}
|
||||
|
||||
// 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");
|
||||
|
||||
// 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 = VideoFrameExtractor.TryCreate(),
|
||||
VideoProbe = FfprobeVideoMetadataProbe.TryCreate(),
|
||||
SetFileTimeToPublication = settings.SetFileTimeToPublication,
|
||||
Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot),
|
||||
DataFolder = data.Root,
|
||||
});
|
||||
LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
// Browser, connection, engine. The engine loop starts only once the browser is up.
|
||||
var browser = await _platform.CreateBrowserAsync(new FebePlatformContext(o, data, Database, Clock, Log, Tracker), ct).ConfigureAwait(false);
|
||||
Browser = browser;
|
||||
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, o.Site.SessionCookie);
|
||||
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.IsConnected == true,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
var runner = new DeferredRecipeRunner();
|
||||
var engine = new EngineHost(services, runner);
|
||||
Engine = engine;
|
||||
connection.AttachEngine(engine);
|
||||
EventHandler<bool> drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
|
||||
browser.UserDriving.Changed += drivingChanged;
|
||||
_unsubscribe.Add(() => browser.UserDriving.Changed -= drivingChanged);
|
||||
|
||||
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<IEngineSettingsControl>(new EngineHostSettingsControl(engine));
|
||||
s.AddSingleton(ingest);
|
||||
s.AddSingleton<IBrowserPreview>(new LiveBrowserPreview(browser, Clock));
|
||||
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
|
||||
if (Import is not null)
|
||||
{
|
||||
s.AddSingleton(Import);
|
||||
}
|
||||
|
||||
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
|
||||
_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<Febe.Web.Import.ImportHub>().GetAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The alerts hook: the channels the shell registered (Windows notifications; Telegram with M8).
|
||||
Alerts = new AlertDispatcher(services.Events, Database.Settings, Web.Services.GetServices<IAlertChannel>(), Log);
|
||||
|
||||
// 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(FebeAppHooks hooks, Action<IServiceCollection> register)
|
||||
{
|
||||
var web = FebeWebHost.Build(
|
||||
_platform.WebOptions,
|
||||
_platform.Listen,
|
||||
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>The browser, 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.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(EngineEventCodes.RecipePrefix, 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 browser = Browser!;
|
||||
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);
|
||||
await browser.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 ({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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The next copy: a few minutes after local midnight (03:20, outside the active window of every profile).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops everything in order: the shell's own first (remote view), interface, engine, downloads, alerts, import,
|
||||
/// pipeline, browser, database.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
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 (Alerts is { } alerts)
|
||||
{
|
||||
await Quietly(() => alerts.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
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, 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<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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Core.Abstractions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>
|
||||
/// The log of Febe, the same in both shells (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, if any
|
||||
/// (<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>
|
||||
public sealed partial class FebeLog : 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 FebeLog(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(FebeLog log) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new Logger(log, categoryName);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Logger(FebeLog 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>
|
||||
/// The browser of Febe as the shared composition sees it (spec §5, §6.1): Chromium on Xvfb in Docker, WebView2 in the
|
||||
/// window «Browser di Febe» on Windows, or Edge started as a process (the last fallback of S2). It owns the
|
||||
/// <see cref="IBrowserHost"/>, starts it with retries, and does the few things the composition needs around it: rest
|
||||
/// page, «Alberto is driving», showing and hiding the window, «Scollega».
|
||||
/// </summary>
|
||||
public interface IFebeBrowser : IAsyncDisposable
|
||||
{
|
||||
/// <summary>The page session: stable for the whole life of the composition (a restart keeps the same object).</summary>
|
||||
ICdpSession Cdp { get; }
|
||||
|
||||
/// <summary>Leases taken while Alberto uses the browser (connection page, remote view, the window in front).</summary>
|
||||
UserDrivingGate UserDriving { get; }
|
||||
|
||||
/// <summary>True while at least one lease is open: the engine does not act.</summary>
|
||||
bool UserIsDriving { get; }
|
||||
|
||||
/// <summary>True when the browser runs and commands can be sent.</summary>
|
||||
bool IsAvailable { get; }
|
||||
|
||||
/// <summary>Why the last start failed, in Italian; null when running.</summary>
|
||||
string? LastError { get; }
|
||||
|
||||
/// <summary>Dati/browser: holds the Instagram session.</summary>
|
||||
string ProfileDirectory { get; }
|
||||
|
||||
/// <summary>Width of the page, always the same (spec §6.1).</summary>
|
||||
int WindowWidth { get; }
|
||||
|
||||
/// <summary>Height of the page, always the same (spec §6.1).</summary>
|
||||
int WindowHeight { get; }
|
||||
|
||||
/// <summary>Starts the browser, retrying with a growing wait until it works or <paramref name="ct"/> is cancelled.</summary>
|
||||
Task RunAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Puts the browser at rest on the blank page (spec §6.1).</summary>
|
||||
Task<NavigationResult> RestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Windows: brings the browser window to the front. Docker: nothing (the remote view shows it).</summary>
|
||||
Task ShowToUserAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Windows: puts the window out of view, still open and painting (S2). Docker: nothing.</summary>
|
||||
Task HideFromUserAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>«Scollega» (spec §4.1): closes the browser, deletes the profile folder and starts it again empty.</summary>
|
||||
Task RestartWithEmptyProfileAsync(CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>
|
||||
/// The parts of a shell that differ between Docker and Windows (spec §5 «I due involucri»): how the interface is
|
||||
/// protected and where it listens, which checks stop the engine at start-up, which browser visits the site and how it
|
||||
/// is supervised, and the native services (folder picker, notifications, remote view…). Everything else — database,
|
||||
/// library, import, backups, collection pipeline, downloads, engine, connection, alerts, web host — is
|
||||
/// <see cref="FebeApp"/>, the same for both.
|
||||
/// </summary>
|
||||
public interface IFebePlatform
|
||||
{
|
||||
/// <summary>Interface options: edition, access (password in Docker, per-start token on Windows), allowed hosts.</summary>
|
||||
FebeWebOptions WebOptions { get; }
|
||||
|
||||
/// <summary>Where Kestrel listens (Docker: every address on 8480; Windows: 127.0.0.1 on a port chosen at start-up).</summary>
|
||||
FebeListen Listen { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Problems that keep the engine and the browser from starting (spec §8.2, §11, §12). With any, only the interface
|
||||
/// starts, on a temporary database, and shows the page that explains them.
|
||||
/// </summary>
|
||||
IReadOnlyList<ConfigurationProblem> CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck);
|
||||
|
||||
/// <summary>The browser of this shell. Called once, after the database is open and before the engine exists.</summary>
|
||||
Task<IFebeBrowser> CreateBrowserAsync(FebePlatformContext context, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Services of this shell for a normal start, registered before the web layer (whose fallbacks use TryAdd):
|
||||
/// native shell, browser window, remote view, change of the Data folder, alert channels.
|
||||
/// </summary>
|
||||
void RegisterServices(IServiceCollection services, FebeApp app);
|
||||
|
||||
/// <summary>Services of this shell while a configuration problem keeps everything else still.</summary>
|
||||
void RegisterProblemServices(IServiceCollection services, FebeApp app);
|
||||
|
||||
/// <summary>Called first when the composition stops (Docker: the open remote view is closed with its reason).</summary>
|
||||
Task StoppingAsync();
|
||||
}
|
||||
|
||||
/// <summary>What a platform gets to build its browser.</summary>
|
||||
/// <param name="Options">The options of the composition.</param>
|
||||
/// <param name="Data">The Data folder (profile in <see cref="DataFolderLayout.BrowserProfile"/>).</param>
|
||||
/// <param name="Storage">The database (settings of the shell, e.g. the S2 hosting mode on Windows).</param>
|
||||
/// <param name="Clock">The clock of the engine.</param>
|
||||
/// <param name="Log">The log.</param>
|
||||
/// <param name="Tracker">When Alberto last used the browser: the desktop window marks it when he uses and closes it.</param>
|
||||
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker);
|
||||
|
||||
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
|
||||
public sealed record FebeAppOptions
|
||||
{
|
||||
/// <summary>Data folder: database, browser profile, thumbnails, backups, log (Docker /dati; Windows %LOCALAPPDATA%\Febe).</summary>
|
||||
public required string DataFolder { get; init; }
|
||||
|
||||
/// <summary>Library folder (Docker /libreria, fixed; Windows Immagini\Febe, the default of the setting).</summary>
|
||||
public required string LibraryFolder { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Windows: the library folder chosen in Impostazioni (stored in the database) wins over <see cref="LibraryFolder"/>,
|
||||
/// which is only its default. Docker: false, the volume decides.
|
||||
/// </summary>
|
||||
public bool LibraryFolderFromSettings { get; init; }
|
||||
|
||||
/// <summary>Docker: the read-only root of the import sources (/importa). Null: any folder, chosen with the picker.</summary>
|
||||
public string? ImportFolder { get; init; }
|
||||
|
||||
/// <summary>Time zone of the engine, of file names and (Docker) of the browser.</summary>
|
||||
public string ZoneId { get; init; } = "Europe/Rome";
|
||||
|
||||
public TimeZoneInfo Zone { get; init; } = TimeZoneInfo.Local;
|
||||
|
||||
/// <summary>Language of the browser, for the log (Docker: LANG; Windows: the language of the system).</summary>
|
||||
public string Language { get; init; } = "it_IT.UTF-8";
|
||||
|
||||
/// <summary>The site the browser works on: Instagram, or the local test site in development.</summary>
|
||||
public CollectionSite Site { get; init; } = CollectionSite.Instagram;
|
||||
|
||||
/// <summary>The page «Accedi a Instagram» opens.</summary>
|
||||
public string LoginUrl { get; init; } = "https://www.instagram.com/accounts/login/";
|
||||
|
||||
/// <summary>Development: the local test site (only for the warning in the log).</summary>
|
||||
public Uri? TestSite { get; init; }
|
||||
|
||||
/// <summary>Development, test site only: opens the site once at start-up so its session cookie exists.</summary>
|
||||
public bool TestSiteAutoLogin { get; init; }
|
||||
|
||||
/// <summary>Development: the first session comes after this delay instead of 2–10 minutes.</summary>
|
||||
public TimeSpan? FirstSessionDelay { get; init; }
|
||||
|
||||
/// <summary>Warnings found while reading the configuration, for the log.</summary>
|
||||
public IReadOnlyList<string> Warnings { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Things tests (and only tests) replace in the composition.</summary>
|
||||
public sealed record FebeAppHooks
|
||||
{
|
||||
public IClock? Clock { get; init; }
|
||||
|
||||
public IRandomSource? Random { get; init; }
|
||||
|
||||
/// <summary>The Data folder check (tests inject a mount table with a network share).</summary>
|
||||
public DataFolderCheck? DataFolderCheck { get; init; }
|
||||
|
||||
/// <summary>Console writer for the log; null: none (the desktop has no console).</summary>
|
||||
public TextWriter? Console { get; init; }
|
||||
|
||||
/// <summary>How long the web host waits for open requests (events, remote view) when stopping.</summary>
|
||||
public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <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. The same in both shells.
|
||||
/// </summary>
|
||||
public sealed class LiveBrowserPreview(IFebeBrowser 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.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(url) || url.StartsWith("about:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_last = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
var jpeg = await PagePreview.CaptureAsync(browser.Cdp, ct: ct).ConfigureAwait(false);
|
||||
_last = new BrowserFrame(jpeg, Addresses.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Addresses as Febe may show them.</summary>
|
||||
public static class Addresses
|
||||
{
|
||||
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
|
||||
public static string WithoutQuery(string url)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Febe.Core.Library;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>The problems found at start-up; fixed for the life of the process (fixing one needs a restart).</summary>
|
||||
public sealed class StartupProblems(IReadOnlyList<ConfigurationProblem> problems) : IConfigurationProblems
|
||||
{
|
||||
public IReadOnlyList<ConfigurationProblem> Current { get; } = problems;
|
||||
}
|
||||
|
||||
/// <summary>Checks shared by both shells (spec §8.2): the Data folder is local and writable.</summary>
|
||||
public static class DataFolderProblems
|
||||
{
|
||||
public const string DataNotWritable = "dati-non-scrivibili";
|
||||
|
||||
public const string DataOnNetwork = "dati-in-rete";
|
||||
|
||||
/// <summary>The problem with the Data folder, or null when it is fine.</summary>
|
||||
public static ConfigurationProblem? Check(string dataFolder, DataFolderCheck? check = null)
|
||||
{
|
||||
if ((check ?? new DataFolderCheck()).Check(dataFolder) is not { } data)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new ConfigurationProblem(
|
||||
data.Kind == DataFolderProblemKind.NetworkPath ? DataOnNetwork : DataNotWritable,
|
||||
data.Title,
|
||||
data.Explanation,
|
||||
data.Remedy);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public sealed class ProblemConnectionService(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.");
|
||||
}
|
||||
Reference in new issue
Block a user