Files
Febe/src/Febe.App/BrowserConnectionService.cs
T
Alby96andClaude Opus 5.5 9941a2fa1f
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
Ricerca dei profili con suggerimenti e foto (#37)
«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono
subito i suggerimenti locali, poi i profili di Instagram con la foto, come
chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram
con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima
il fuoco, legge la risposta della pagina e non clicca mai un risultato.

La ricerca ha una categoria propria nel Governatore, con tetti larghi che
non consumano quelli della raccolta, e si dà il turno con il motore
sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le
foto passano dal CDN con un permesso ciascuna e restano solo in memoria.

Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento
requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in
docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli
search-open e search-box saranno raccolti dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:30:03 +01:00

662 lines
26 KiB
C#

using System.Globalization;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
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>
/// <remarks>
/// <para>
/// The lease taken by «Accedi a Instagram» and «Usa il browser» ends with «Ho finito», «Annulla» or «Scollega», and also
/// by itself when for <see cref="DrivingGrace"/> it is the only sign that Alberto uses the browser — no remote view open
/// in Docker, the window «Browser di Febe» out of view on Windows: he went away without either button, and the engine
/// must not stay still for ever.
/// </para>
/// <para>
/// A session cookie that disappears outside a session (or is missing at start-up after a connection) is a disconnection
/// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only
/// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega».
/// </para>
/// </remarks>
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>Setting set by «Scollega» and removed by the next connection: until then a missing session is expected.</summary>
public const string DisconnectedByUserKey = "collegamento.scollegato";
/// <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 CancellationTokenSource? _leaseWatch;
private DateTimeOffset _lastDrivingSign;
private bool? _connected;
private bool? _disconnectedByUser;
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>
/// How long the lease of «Accedi a Instagram» / «Usa il browser» outlives every other lease of the browser (remote
/// view, window in front) before it ends by itself. Read at every look; tests shorten it.
/// </summary>
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
/// <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, mayReport: true, 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)
{
if (_lease is null)
{
_lease = _browser.UserDriving.Begin();
var watch = new CancellationTokenSource();
_leaseWatch = watch;
var lease = _lease;
_ = Task.Run(() => WatchLeaseAsync(lease, watch.Token), CancellationToken.None);
}
_lastDrivingSign = _clock.Now;
}
_tracker.MarkUsed(_clock.Now);
if (openLogin)
{
// The engine ends its session when the lease starts; wait for it before taking the page. A search step
// in progress (issue #37) stops at its next check of the lease: the login page waits for its turn.
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
using var turn = await TakePageAsync(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.");
}
// Alberto has just been at the browser: a session he did not complete is said here, not reported as a stop.
var connected = await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) == true;
_tracker.MarkUsed(_clock.Now);
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
await RestIfAlbertosAsync().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 RestIfAlbertosAsync().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
{
// From now on a missing session is Alberto's choice, not a disconnection to report (until he connects again).
await RememberUserDisconnectAsync().ConfigureAwait(false);
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. A session that went away (or is missing at start-up after a
/// connection) while Alberto is not at the browser is reported to the breaker as a disconnection (spec §7.6).
/// </summary>
public async Task<bool?> RefreshAsync(CancellationToken ct)
{
if (!_browser.IsAvailable)
{
return IsConnected;
}
var connected = await CheckAsync(force: true, mayReport: 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, bool mayReport, 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;
}
var previous = SetConnected(has);
if (has)
{
await ForgetUserDisconnectAsync(ct).ConfigureAwait(false);
}
else if (mayReport && previous != false && !_browser.UserIsDriving)
{
await ReportLostSessionAsync(previous, ct).ConfigureAwait(false);
}
return has;
}
/// <summary>Records the state of the cookie; returns the one before (null before the first check).</summary>
private bool? SetConnected(bool connected)
{
bool? previous;
lock (_gate)
{
previous = _connected;
_connected = connected;
_checkedAt = _clock.Now;
}
if (previous != connected)
{
_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);
}
return previous;
}
/// <summary>
/// The session cookie is gone while Alberto is not at the browser (spec §7.6 «il cookie di sessione non c'è più»):
/// the same disconnection the recipes report, so the breaker writes the incident, the alert goes out and only
/// «Riprendi» (with the gradual start) restarts the engine. Not after «Scollega», and at start-up only when the
/// profile had been connected.
/// </summary>
private async Task ReportLostSessionAsync(bool? previous, CancellationToken ct)
{
if (_engine is not { } engine || await IsDisconnectedByUserAsync(ct).ConfigureAwait(false))
{
return;
}
if (previous is null && await _storage.Settings.GetInt64Async(FirstConnectionKey, ct).ConfigureAwait(false) is null)
{
return; // never connected: nothing was lost
}
engine.Services.Breaker.Report(new Signal(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null, _clock.Now));
_log.Warn("collegamento", "La sessione di Instagram non c'è più nel browser: Febe si ferma finché non accedi di nuovo e premi «Riprendi».");
}
private async Task<bool> IsDisconnectedByUserAsync(CancellationToken ct)
{
if (_disconnectedByUser is { } known)
{
return known;
}
var stored = await _storage.Settings.GetBoolAsync(DisconnectedByUserKey, false, ct).ConfigureAwait(false);
_disconnectedByUser = stored;
return stored;
}
private async Task RememberUserDisconnectAsync()
{
_disconnectedByUser = true;
await _storage.Settings.SetBoolAsync(DisconnectedByUserKey, true, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>A session is in the browser again: from now on its loss is a disconnection.</summary>
private async Task ForgetUserDisconnectAsync(CancellationToken ct)
{
if (await IsDisconnectedByUserAsync(ct).ConfigureAwait(false))
{
_disconnectedByUser = false;
await _storage.Settings.SetAsync(DisconnectedByUserKey, null, ct).ConfigureAwait(false);
}
}
/// <summary>
/// The «driving» lease of this service ends by itself once it has been the only lease of the browser for
/// <see cref="DrivingGrace"/>: the remote view closed (Docker) or the window went out of view (Windows), and
/// neither «Ho finito» nor «Annulla» came. The page is not touched here (the engine puts it to rest).
/// </summary>
private async Task WatchLeaseAsync(IDisposable lease, CancellationToken ct)
{
try
{
while (true)
{
var grace = DrivingGrace;
var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
await _clock.Delay(poll, ct).ConfigureAwait(false);
DateTimeOffset lastSign;
lock (_gate)
{
if (!ReferenceEquals(_lease, lease))
{
return;
}
// Besides this lease: the remote view, the browser window in front, «Scollega» in progress.
if (_browser.UserDriving.Leases > 1)
{
_lastDrivingSign = _clock.Now;
}
lastSign = _lastDrivingSign;
}
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
{
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
return;
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The lease ended with a command of Alberto.
}
}
/// <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);
}
}
/// <summary>
/// The page turn for Alberto's login page, so that no step of the profile search runs under it; after 15 seconds
/// the page is taken anyway (Alberto asked for it), and null comes back.
/// </summary>
private async Task<PageTurn?> TakePageAsync(CancellationToken ct)
{
if (_engine is not { } engine)
{
return null;
}
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(TimeSpan.FromSeconds(15));
try
{
return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return null;
}
}
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;
}
}
/// <summary>
/// Puts the page to rest while it is Alberto's (a lease holds the engine still). Once every lease ended — this
/// service's ended by itself after <see cref="DrivingGrace"/> — the page is the engine's again: a late «Ho finito» or
/// «Annulla» must not navigate under a session (the engine rested the page when the driving ended).
/// </summary>
private Task RestIfAlbertosAsync() => _browser.UserIsDriving ? RestQuietlyAsync() : Task.CompletedTask;
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);
}
}
/// <summary>Ends the lease (only <paramref name="expected"/>, when given). True when a lease ended.</summary>
private bool ReleaseLease(IDisposable? expected = null)
{
IDisposable? lease;
CancellationTokenSource? watch;
lock (_gate)
{
if (expected is not null && !ReferenceEquals(_lease, expected))
{
return false;
}
lease = _lease;
watch = _leaseWatch;
_lease = null;
_leaseWatch = null;
}
if (watch is not null)
{
watch.Cancel();
watch.Dispose();
}
lease?.Dispose();
return lease is not null;
}
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.");
}
}
}