Con la correzione #67 un browser che resta muto per tutta l'attesa conta come a riposo, e Febe prova ad aprire la pagina iniziale. Un browser che si sta ancora riavviando dopo «Scollega» rifiuta però anche Page.navigate: l'errore risaliva fino all'API e Alberto vedeva, dopo dieci secondi, un errore interno al posto della finestra. Ora quella navigazione mancata si annota nel registro («non aperta (il browser non risponde)») e la finestra viene in primo piano come prima. Nuova prova con un browser che non risponde a nulla, per «Usa il browser» e «Apri il browser». Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1537 lines
67 KiB
C#
1537 lines
67 KiB
C#
using System.Globalization;
|
|
using Febe.Browser.Cdp;
|
|
using Febe.Browser.Hosting;
|
|
using Febe.Browser.Session;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Collection;
|
|
using Febe.Core.Collection.Requests;
|
|
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», «Apri il browser» 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; leaving a page of Febe leaves it as it is. 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>
|
|
/// Alberto never meets the empty rest page (issue #52): when he takes the browser while it rests there, his own first
|
|
/// navigation (rule 7, like the login page) opens <see cref="StartPageUrl"/> — the site's home when connected, the login
|
|
/// page when not connected or after a disconnection.
|
|
/// </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>
|
|
/// <para>
|
|
/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the
|
|
/// browser without it: the window «Browser di Febe» closed on Windows (<see cref="CopyOnWindowClosedAsync"/>), the page
|
|
/// of the browser left in Docker (<see cref="LeavePageAsync"/>, <see cref="RemoteViewClosed"/>: after
|
|
/// <see cref="PageLeaveGrace"/> without a view open again, answer of 25 November 2026) and the lease of «Accedi» /
|
|
/// «Usa il browser» ending by itself. «Annulla» never copies. Always before the page goes back to the engine, with the
|
|
/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is
|
|
/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is
|
|
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
|
|
/// </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);
|
|
|
|
/// <summary>How the log names leaving the page of the browser in Docker (answer of 25 November 2026).</summary>
|
|
private const string PageLeftText = "Pagina del browser lasciata";
|
|
|
|
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 string _homeUrl;
|
|
private readonly SessionCookieOptions _cookie;
|
|
private readonly ISessionCopier? _copier;
|
|
private readonly Func<CancellationToken, Task>? _forgetSavedSession;
|
|
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;
|
|
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
|
|
private SessionCopyOutcome? _letGoCopy;
|
|
private DateTimeOffset? _leftAt;
|
|
|
|
/// <param name="browser">The browser of Febe.</param>
|
|
/// <param name="storage">The database (first connection, «Scollega»).</param>
|
|
/// <param name="tracker">When Alberto last used the browser.</param>
|
|
/// <param name="clock">The composition's clock.</param>
|
|
/// <param name="log">Febe's log.</param>
|
|
/// <param name="loginUrl">The page «Accedi a Instagram» opens.</param>
|
|
/// <param name="homeUrl">The site's home, the start page once connected.</param>
|
|
/// <param name="cookie">The session cookie looked for (its name only).</param>
|
|
/// <param name="copier">
|
|
/// The copy of the session into the saved session at «Ho finito» (issue #36, S4); null when the composition keeps no
|
|
/// saved session (option «raccolta» on «pagine», or no configured operation): «Ho finito» then reads names only.
|
|
/// </param>
|
|
/// <param name="forgetSavedSession">
|
|
/// What «Scollega» does to the saved session (deletes it, memory and file); null when there is none to delete.
|
|
/// </param>
|
|
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie, ISessionCopier? copier = null, Func<CancellationToken, Task>? forgetSavedSession = null)
|
|
{
|
|
_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));
|
|
_homeUrl = homeUrl ?? throw new ArgumentNullException(nameof(homeUrl));
|
|
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
|
|
_copier = copier;
|
|
_forgetSavedSession = forgetSavedSession;
|
|
}
|
|
|
|
/// <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>
|
|
/// True when the composition keeps a saved session (raccolta «richieste») and there is no readable one: the cookie
|
|
/// alone is not «Collegato», the copy of «Ho finito» is missing (issue #36, S4b, answer 6).
|
|
/// </summary>
|
|
public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present;
|
|
|
|
/// <summary>
|
|
/// Whether the engine may collect (<see cref="EngineRuntime.IsConnected"/>): the session cookie is in the browser
|
|
/// and, with a saved session, a readable copy of it is there too.
|
|
/// </summary>
|
|
public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing;
|
|
|
|
/// <summary>
|
|
/// How long a copy when Alberto closes the browser window waits, at most, for the commands of the connection and for
|
|
/// the copy itself (real time); then it gives up and the window gives the page back. Tests shorten it.
|
|
/// </summary>
|
|
public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30);
|
|
|
|
/// <summary>
|
|
/// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the
|
|
/// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection
|
|
/// (spec §7.6), when Instagram's home would only send him there.
|
|
/// </summary>
|
|
public string StartPageUrl =>
|
|
IsConnected == true && _engine?.Services.Breaker.State.Status != BreakerStatus.Disconnected ? _homeUrl : _loginUrl;
|
|
|
|
/// <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>
|
|
/// How long after Alberto left the page of the browser in Docker (<see cref="LeavePageAsync"/>, or its remote view
|
|
/// closed by the page: <see cref="RemoteViewClosed"/>) no view may open again before Febe takes it as letting go of
|
|
/// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well
|
|
/// before. Read at every look; tests shorten it.
|
|
/// </summary>
|
|
public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5);
|
|
|
|
/// <summary>
|
|
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
|
|
/// wait; tests shorten it.
|
|
/// </summary>
|
|
public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15);
|
|
|
|
/// <summary>
|
|
/// How long Alberto's first navigation waits, at most, for the browser to say which page it shows when it does not
|
|
/// answer (real time): right after «Scollega» it has just restarted with an empty profile and may not answer yet.
|
|
/// After it the page counts as the rest page, and the start page opens (issue #67, decision of 29 November 2026):
|
|
/// never a white window (issue #52). Read at every wait; tests shorten it.
|
|
/// </summary>
|
|
public TimeSpan AddressWait { get; set; } = TimeSpan.FromSeconds(10);
|
|
|
|
/// <summary>How often the wait of <see cref="AddressWait"/> asks the browser again.</summary>
|
|
private static readonly TimeSpan AddressPoll = TimeSpan.FromMilliseconds(200);
|
|
|
|
/// <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;
|
|
var saved = _copier?.Report();
|
|
if (state == ConnectionState.Connected && saved is not null && saved.State != SavedSessionState.Present)
|
|
{
|
|
state = ConnectionState.SessionCopyMissing;
|
|
}
|
|
|
|
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), ToStatus(saved));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The window «Browser di Febe» was closed by Alberto without «Ho finito», or left minimised too long (Windows, issue
|
|
/// #36, S4b, answer 5): the session is copied while the page is still his. The caller (the window) holds the driving
|
|
/// gate until this returns, so the page goes back to the engine only afterwards. Gives up after
|
|
/// <see cref="LetGoWait"/>. Never throws for the browser; logs counts only, and says which of the two happened.
|
|
/// </summary>
|
|
public async Task CopyOnWindowClosedAsync(BrowserWindowLetGo how, CancellationToken ct)
|
|
{
|
|
var what = how == BrowserWindowLetGo.MinimizedTooLong ? "Finestra del browser ridotta a icona troppo a lungo" : "Finestra del browser chiusa";
|
|
if (_copier is null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (!_browser.IsAvailable)
|
|
{
|
|
// A letting go that copies nothing: a late «Ho finito» must not report a copy of an earlier one.
|
|
ForgetLetGoCopy();
|
|
return;
|
|
}
|
|
|
|
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
limit.CancelAfter(LetGoWait);
|
|
try
|
|
{
|
|
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (limit.IsCancellationRequested)
|
|
{
|
|
ForgetLetGoCopy();
|
|
_log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
|
|
return;
|
|
}
|
|
catch (ObjectDisposedException)
|
|
{
|
|
return; // Febe is stopping
|
|
}
|
|
|
|
try
|
|
{
|
|
await CopyOnLetGoAsync(what, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
ReleaseCommands();
|
|
}
|
|
}
|
|
|
|
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
|
|
{
|
|
EnsureBrowser();
|
|
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_lease is null)
|
|
{
|
|
// A new use of the browser: what an earlier one copied when it let go is no longer this one's.
|
|
_letGoCopy = 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;
|
|
|
|
// Alberto is back (a reload of the page left a moment ago): not a letting go.
|
|
_leftAt = null;
|
|
}
|
|
|
|
_tracker.MarkUsed(_clock.Now);
|
|
await OpenForAlbertoAsync(openLogin, ct).ConfigureAwait(false);
|
|
|
|
// 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 ShowBrowserAsync(bool openLogin, CancellationToken ct)
|
|
{
|
|
EnsureBrowser();
|
|
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
|
|
|
// Alberto's hold while his page opens: the window takes its own lease when it comes on screen, and holds the
|
|
// engine still for as long as it stays there (closing it ends it, as before).
|
|
var hold = _browser.UserDriving.Begin();
|
|
try
|
|
{
|
|
_tracker.MarkUsed(_clock.Now);
|
|
await OpenForAlbertoAsync(openLogin, ct).ConfigureAwait(false);
|
|
await _browser.ShowToUserAsync(ct).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
hold.Dispose();
|
|
_commands.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Pagina iniziale» of the window's bar and of the remote view (issue #52): Alberto's own navigation (rule 7) to
|
|
/// <see cref="StartPageUrl"/>, as when he takes the browser from the rest page — after the engine's session ended and
|
|
/// with the page's turn, so that no step of a session or of the profile search has its page swapped under it. Only
|
|
/// while he is at the browser: otherwise the page is the engine's and nothing happens.
|
|
/// </summary>
|
|
/// <param name="ct">
|
|
/// Cancelled when the lease of whoever pressed the button ends (the window closed, the remote view closed): the press
|
|
/// is then forgotten, whatever it was waiting for.
|
|
/// </param>
|
|
/// <remarks>
|
|
/// The waits can last up to <see cref="PageTurnWait"/> and more: Alberto may have let go of the browser meanwhile, and
|
|
/// then the page is the engine's again (rules 7 and 8: no navigation without his lease, outside the Governor). So
|
|
/// right before navigating, with the page's turn in hand, it looks again: he still drives and the caller's lease still
|
|
/// holds. Without the page's turn (a step of the search kept it) nothing happens either: the page is not taken from
|
|
/// under the step.
|
|
/// </remarks>
|
|
public async Task OpenStartPageAsync(CancellationToken ct)
|
|
{
|
|
if (!_browser.IsAvailable)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
if (!_browser.UserIsDriving)
|
|
{
|
|
return;
|
|
}
|
|
|
|
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
|
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
|
if (_engine is not null && turn is null)
|
|
{
|
|
_log.Info("collegamento", "«Pagina iniziale» non aperta: la pagina è ancora occupata dalla ricerca dei profili. Riprova fra poco.");
|
|
return;
|
|
}
|
|
|
|
// The last look, with the page's turn in hand (no recipe and no search step can open a page until it is given
|
|
// back): Alberto still drives and the caller's lease still holds.
|
|
if (ct.IsCancellationRequested || !_browser.UserIsDriving)
|
|
{
|
|
_log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser.");
|
|
return;
|
|
}
|
|
|
|
var target = StartPageUrl;
|
|
var what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito";
|
|
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
|
|
_log.Info("collegamento", result.Succeeded
|
|
? $"«Pagina iniziale»: {what} aperta."
|
|
: $"«Pagina iniziale»: {what} non aperta (errore di rete del browser).");
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
{
|
|
_log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser.");
|
|
}
|
|
finally
|
|
{
|
|
_commands.Release();
|
|
}
|
|
}
|
|
|
|
public async Task ReleaseAsync(CancellationToken ct)
|
|
{
|
|
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (ReleaseLease())
|
|
{
|
|
_log.Info("collegamento", "Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi.");
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
_commands.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Docker (answer of 25 November 2026): the page of the browser was left without «Ho finito» or «Annulla». Nothing
|
|
/// happens at once — a reload opens the page, «Usa il browser» and the view again within a moment. The watch of the
|
|
/// lease lets go of the browser once, for <see cref="PageLeaveGrace"/> after this and after the last view closed, no
|
|
/// view is open and no «Accedi» / «Usa il browser» came: the copy of the session as when the window is closed on
|
|
/// Windows, then the lease ends and the page goes back to the engine (which puts it to rest).
|
|
/// </summary>
|
|
public Task LeavePageAsync(CancellationToken ct)
|
|
{
|
|
if (NoteLeft())
|
|
{
|
|
_log.Info("collegamento", $"Pagina del browser lasciata senza «Ho finito» né «Annulla»: se entro {ItalianText.Duration(PageLeaveGrace)} non torni al browser, Febe copia la sessione e il motore può riprendere.");
|
|
}
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Docker: a remote view was closed by its page (the page left, the tab closed, the link lost; not another view taking
|
|
/// its place, nor Febe stopping). While the lease of «Accedi» / «Usa il browser» holds it counts as leaving the page
|
|
/// (<see cref="LeavePageAsync"/>): the last view closed, the moment starts again from now.
|
|
/// </summary>
|
|
public void RemoteViewClosed()
|
|
{
|
|
// The browser gone: its view closed with it, Alberto did not leave (the page opens it again once it is back).
|
|
if (_browser.IsAvailable)
|
|
{
|
|
NoteLeft();
|
|
}
|
|
}
|
|
|
|
/// <summary>Notes that Alberto may have left the browser; false without the lease of «Accedi» / «Usa il browser».</summary>
|
|
private bool NoteLeft()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_lease is null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_leftAt = _clock.Now;
|
|
return true;
|
|
}
|
|
}
|
|
|
|
public async Task<FinishResult> FinishAsync(CancellationToken ct)
|
|
{
|
|
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
|
try
|
|
{
|
|
if (!_browser.IsAvailable)
|
|
{
|
|
EndUseWithHoFinito();
|
|
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);
|
|
|
|
// The copy for the site client (S4): while the page still holds the session and is still Alberto's.
|
|
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : default;
|
|
await RestIfAlbertosAsync().ConfigureAwait(false);
|
|
await HideQuietlyAsync().ConfigureAwait(false);
|
|
EndUseWithHoFinito();
|
|
|
|
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.";
|
|
}
|
|
|
|
if (copy.Outcome is { } outcome)
|
|
{
|
|
message += " " + CopyMessage(outcome, copy.Earlier);
|
|
}
|
|
|
|
_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;
|
|
|
|
// The saved session first (S4): no request of the site client may use it any more, whatever the profile does.
|
|
var savedSessionFailure = await ForgetSavedSessionAsync().ConfigureAwait(false);
|
|
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 (savedSessionFailure is not null)
|
|
{
|
|
// Never the path or the message of the file system: the kind of error only.
|
|
_log.Warn("collegamento", $"«Scollega»: la sessione salvata non si è potuta cancellare dal disco ({savedSessionFailure.GetType().Name}): Febe non la usa più finché resta acceso, ma il file resta e al prossimo avvio con «richieste» la rileggerebbe.");
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
if (savedSessionFailure is not null)
|
|
{
|
|
throw new BadRequestException("«Scollega» non è riuscito del tutto: la sessione salvata per le richieste non si è potuta cancellare dal disco. Febe non la usa più finché resta acceso, ma al prossimo avvio con la raccolta «richieste» la rileggerebbe: riprova «Scollega» e, se resta, cancella a mano la cartella «sessione» nella cartella dei dati prima di riavviare Febe.");
|
|
}
|
|
|
|
_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) —
|
|
/// unless <paramref name="mayReport"/> is false: the first look of a start with the test site's automatic login,
|
|
/// which is about to open the session itself (issue #52: a false disconnection at every development start).
|
|
/// </summary>
|
|
public async Task<bool?> RefreshAsync(CancellationToken ct, bool mayReport = true)
|
|
{
|
|
if (!_browser.IsAvailable)
|
|
{
|
|
return IsConnected;
|
|
}
|
|
|
|
var connected = await CheckAsync(force: true, mayReport, 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 leaveGrace = PageLeaveGrace;
|
|
var shortest = leaveGrace < grace ? leaveGrace : grace;
|
|
var poll = TimeSpan.FromTicks(Math.Clamp(shortest.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
|
|
await _clock.Delay(poll, ct).ConfigureAwait(false);
|
|
DateTimeOffset lastSign;
|
|
DateTimeOffset? leftAt;
|
|
lock (_gate)
|
|
{
|
|
if (!ReferenceEquals(_lease, lease))
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Besides this lease: the remote view, the browser window in front, «Scollega» in progress. A view open
|
|
// again also cancels an earlier leave (a late «pageLeft» of a reloaded page, the old view that
|
|
// «Riprova» closed): only a view closing after this counts as leaving, so that a view ended later by
|
|
// the server (the browser stopped) waits for DrivingGrace, as a browser that is down is not leaving.
|
|
if (_browser.UserDriving.Leases > 1)
|
|
{
|
|
_lastDrivingSign = _clock.Now;
|
|
_leftAt = null;
|
|
}
|
|
|
|
lastSign = _lastDrivingSign;
|
|
leftAt = _leftAt;
|
|
}
|
|
|
|
// Docker: the page of the browser left, or its last view closed by the page, and for a moment nothing came
|
|
// back (answer of 25 November 2026). Otherwise the long wait of a lease nobody uses.
|
|
var now = _clock.Now;
|
|
var left = leftAt is { } at && now - (at > lastSign ? at : lastSign) >= leaveGrace;
|
|
if (!left && now - lastSign < grace)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
// Before the page goes back to the engine: the copy of the session (S4b, answer 5; leaving the page in
|
|
// Docker, answer of 25 November 2026).
|
|
var what = left ? PageLeftText : "Fine della guida del browser";
|
|
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, what, ct).ConfigureAwait(false))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
// The copy may have lasted long (the page's turn, the browser, the database): the remote view, the window
|
|
// or «Accedi» / «Usa il browser» may have come back meanwhile. Looked at again in the same step that ends
|
|
// the lease, so that nothing slips in between.
|
|
if (ReleaseIdleLease(lease, lastSign))
|
|
{
|
|
_log.Info("collegamento", left
|
|
? $"{PageLeftText}: nessuna vista del browser riaperta, il motore può riprendere."
|
|
: $"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.
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
// Whatever failed, the lease must not hold the engine still for ever (rule 10: the kind of error only).
|
|
_log.Warn("collegamento", $"Controllo della fine della guida del browser interrotto da un errore ({ex.GetType().Name}): il motore può riprendere.");
|
|
ReleaseLease(lease);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The copy when the lease of «Accedi» / «Usa il browser» is about to end by itself (S4b, answer 5), while it still
|
|
/// holds. Not when a copy was already made since the last sign that Alberto used the browser (the window closed a
|
|
/// moment before): the window's own hold lasts a moment after its copy, so a sign within one look
|
|
/// (<paramref name="poll"/>) of the copy is that hold, not Alberto. False when the lease must not end now: a sign of
|
|
/// driving came while the copy waited for its turn.
|
|
/// </summary>
|
|
private async Task<bool> CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, string what, CancellationToken ct)
|
|
{
|
|
if (_copier is null)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
lock (_gate)
|
|
{
|
|
if (_lastCopyAt != DateTimeOffset.MinValue && _lastCopyAt >= lastSign - poll)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide. Leaving the page
|
|
// in Docker waits at most LetGoWait for another command of the connection, as closing the window does (§6.0), so
|
|
// that the engine is not held still: then the lease ends without the copy.
|
|
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
if (what == PageLeftText)
|
|
{
|
|
limit.CancelAfter(LetGoWait);
|
|
}
|
|
|
|
try
|
|
{
|
|
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested && limit.IsCancellationRequested)
|
|
{
|
|
ForgetLetGoCopy();
|
|
_log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
|
|
return true;
|
|
}
|
|
catch (ObjectDisposedException)
|
|
{
|
|
return true; // Febe is stopping
|
|
}
|
|
|
|
try
|
|
{
|
|
bool StillAlbertos()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return ReferenceEquals(_lease, lease);
|
|
}
|
|
}
|
|
|
|
if (!StillAlbertos())
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (_browser.UserDriving.Leases > 1)
|
|
{
|
|
// The remote view or the window came back while this waited: the lease goes on.
|
|
lock (_gate)
|
|
{
|
|
_lastDrivingSign = _clock.Now;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
await CopyOnLetGoAsync(what, StillAlbertos, ct).ConfigureAwait(false);
|
|
return true;
|
|
}
|
|
finally
|
|
{
|
|
ReleaseCommands();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The copy when Alberto lets go of the browser without «Ho finito»: only while the page is still his, only when the
|
|
/// browser holds the session, with the driving gate held and the page's turn, like «Ho finito». The copier refuses a
|
|
/// page off the site or a login or verification page. One log line with the outcome (counts only).
|
|
/// </summary>
|
|
private async Task CopyOnLetGoAsync(string what, Func<bool> stillAlbertos, CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
if (!_browser.UserIsDriving)
|
|
{
|
|
_log.Info("collegamento", $"{what}: sessione non copiata, il browser era già tornato al motore.");
|
|
return;
|
|
}
|
|
|
|
// The last time this use of the browser let go decides what a late «Ho finito» says: a copy that does not
|
|
// happen now (no session, the page busy, refused, an error) forgets one made at an earlier letting go.
|
|
ForgetLetGoCopy();
|
|
|
|
if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true)
|
|
{
|
|
_log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare.");
|
|
return;
|
|
}
|
|
|
|
var hold = _browser.UserDriving.Begin();
|
|
try
|
|
{
|
|
const string PageBusy = "sessione non copiata, la pagina era occupata dalla ricerca dei profili";
|
|
PageTurn? taken;
|
|
try
|
|
{
|
|
taken = await TakePageAsync(ct).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
{
|
|
// The time of the letting go ran out while a step of the search held the page: not the browser's fault.
|
|
_log.Info("collegamento", $"{what}: {PageBusy}.");
|
|
return;
|
|
}
|
|
|
|
using var turn = taken;
|
|
if (_engine is not null && turn is null)
|
|
{
|
|
_log.Info("collegamento", $"{what}: {PageBusy}.");
|
|
return;
|
|
}
|
|
|
|
var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false);
|
|
lock (_gate)
|
|
{
|
|
_lastCopyAt = _clock.Now;
|
|
if (outcome.Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly or SessionCopyStatus.KeptComplete)
|
|
{
|
|
// A late «Ho finito» of this use says that the session was already copied (S4b).
|
|
_letGoCopy = outcome;
|
|
}
|
|
}
|
|
|
|
_log.Info("collegamento", $"{what}: {LetGoSummary(outcome)}.");
|
|
}
|
|
finally
|
|
{
|
|
hold.Dispose();
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
{
|
|
_log.Info("collegamento", $"{what}: sessione non copiata, il browser non ha risposto in tempo.");
|
|
}
|
|
catch (Exception ex) when (ex is not OutOfMemoryException)
|
|
{
|
|
// The database, the disk, Febe stopping: never the lease held for ever because of it. The kind of error only
|
|
// (rule 10): the page and the saved session hold what the session holds.
|
|
_log.Warn("collegamento", $"{what}: copia della sessione non riuscita per un errore ({ex.GetType().Name}).");
|
|
}
|
|
}
|
|
|
|
/// <summary>What a copy without «Ho finito» did, for the log (counts only).</summary>
|
|
internal static string LetGoSummary(SessionCopyOutcome copy)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(copy);
|
|
var missing = copy.MissingValues + copy.MissingDocIds;
|
|
var clause = missing == 0 ? string.Empty : ", ma " + MissingNeeded(missing, past: false);
|
|
return copy.Status switch
|
|
{
|
|
SessionCopyStatus.Saved => "sessione copiata" + clause,
|
|
SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause,
|
|
SessionCopyStatus.KeptComplete => $"copia incompleta ({ItalianText.Count(missing, "valore mancante", "valori mancanti")}), resta quella completa salvata prima",
|
|
SessionCopyStatus.Discarded => "sessione letta ma non salvata, il browser era tornato al motore",
|
|
_ => $"sessione non copiata, {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}; la sessione salvata resta com'era",
|
|
};
|
|
}
|
|
|
|
/// <summary>The saved session for the interface, in counts and names; null without a saved session in this start.</summary>
|
|
private static SavedSessionStatus? ToStatus(SavedSessionReport? report) => report is null
|
|
? null
|
|
: new SavedSessionStatus(
|
|
report.State switch
|
|
{
|
|
SavedSessionState.Present => SavedSessionStatus.Present,
|
|
SavedSessionState.Unreadable => SavedSessionStatus.Unreadable,
|
|
_ => SavedSessionStatus.None,
|
|
},
|
|
report.CopiedAt,
|
|
report.Cookies,
|
|
report.ValuesPresent,
|
|
report.ValuesExpected,
|
|
report.MissingValues,
|
|
report.DocIdsPresent,
|
|
report.DocIdsExpected,
|
|
report.MissingDocIds,
|
|
report.NeededMissing);
|
|
|
|
private void ReleaseCommands()
|
|
{
|
|
try
|
|
{
|
|
_commands.Release();
|
|
}
|
|
catch (ObjectDisposedException)
|
|
{
|
|
// Febe stopped while the copy ran.
|
|
}
|
|
}
|
|
|
|
/// <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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Alberto's own first navigation (rule 7: not an engine action, no Governor), under his lease: the login page when
|
|
/// asked for, and the start page when the browser rests on the empty page (issue #52). Any other page stays as it is
|
|
/// — the one he was using, or the verification page of a stop. A browser that does not say its page is waited for,
|
|
/// up to <see cref="AddressWait"/>; still silent, its page counts as the rest page (issue #67).
|
|
/// </summary>
|
|
private async Task OpenForAlbertoAsync(bool openLogin, CancellationToken ct)
|
|
{
|
|
// A known address that is not the rest page is a page Alberto uses: never touched. An unknown one (the browser
|
|
// still silent after the wait) is the rest page.
|
|
var answered = true;
|
|
if (!openLogin)
|
|
{
|
|
var first = await AwaitFullUrlAsync(ct).ConfigureAwait(false);
|
|
answered = first is not null;
|
|
if (answered && !IsRest(first))
|
|
{
|
|
_log.Info("collegamento", "Alberto usa il browser.");
|
|
return;
|
|
}
|
|
}
|
|
|
|
// 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: Alberto's page waits for its turn.
|
|
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
|
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
|
string target;
|
|
string what;
|
|
if (openLogin)
|
|
{
|
|
target = _loginUrl;
|
|
what = "pagina di accesso";
|
|
}
|
|
else if (await IsAtRestAsync(wait: answered, ct).ConfigureAwait(false))
|
|
{
|
|
target = StartPageUrl;
|
|
what = target == _loginUrl ? "era a riposo, pagina di accesso" : "era a riposo, pagina iniziale del sito";
|
|
}
|
|
else
|
|
{
|
|
// The session that just ended left its page: his to look at.
|
|
_log.Info("collegamento", "Alberto usa il browser.");
|
|
return;
|
|
}
|
|
|
|
// A browser still silent (restarting after «Scollega», issue #67) usually refuses the navigation too: the window
|
|
// comes to the front all the same, as when its page was unknown before, never an internal error.
|
|
NavigationResult result;
|
|
try
|
|
{
|
|
result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
|
{
|
|
_log.Info("collegamento", $"Alberto usa il browser: {what} non aperta (il browser non risponde).");
|
|
return;
|
|
}
|
|
|
|
_log.Info("collegamento", result.Succeeded
|
|
? $"Alberto usa il browser: {what} aperta."
|
|
: $"Alberto usa il browser: {what} non aperta (errore di rete del browser).");
|
|
}
|
|
|
|
/// <summary>
|
|
/// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still
|
|
/// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate
|
|
/// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the
|
|
/// page; a lease that ended all the same before the copy is saved throws the copy away. A late «Ho finito», after
|
|
/// this use of the browser already copied when it let go (S4b), reads nothing and reports that earlier copy
|
|
/// (<c>Earlier</c>), as long as the saved session is still there.
|
|
/// </summary>
|
|
private async Task<(SessionCopyOutcome? Outcome, bool Earlier)> CopySessionAsync(CancellationToken ct)
|
|
{
|
|
IDisposable? lease;
|
|
SessionCopyOutcome? earlier;
|
|
lock (_gate)
|
|
{
|
|
lease = _lease;
|
|
earlier = _letGoCopy;
|
|
}
|
|
|
|
if (lease is null || !_browser.UserIsDriving)
|
|
{
|
|
if (earlier is not null && _copier!.SavedState == SavedSessionState.Present)
|
|
{
|
|
_log.Info("collegamento", "«Ho finito»: sessione non copiata di nuovo, era già stata copiata quando il browser è tornato al motore.");
|
|
return (earlier, true);
|
|
}
|
|
|
|
_log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore.");
|
|
return (new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0), false);
|
|
}
|
|
|
|
// «Ho finito» copies again: from now on its own outcome is what a later «Ho finito» refers to, not an earlier copy
|
|
// made when the browser was let go (that copy may be of another login).
|
|
ForgetLetGoCopy();
|
|
var hold = _browser.UserDriving.Begin();
|
|
try
|
|
{
|
|
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
|
if (_engine is not null && turn is null)
|
|
{
|
|
_log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
|
|
return (new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0), false);
|
|
}
|
|
|
|
bool StillAlbertos()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return ReferenceEquals(_lease, lease);
|
|
}
|
|
}
|
|
|
|
return (await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false), false);
|
|
}
|
|
finally
|
|
{
|
|
hold.Dispose();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a
|
|
/// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never
|
|
/// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because
|
|
/// «Ho finito» always ends the lease. With <paramref name="earlier"/> the copy is the one made a moment before, when
|
|
/// the browser went back to the engine without «Ho finito» (S4b): the message says so, and never asks for a new login
|
|
/// when that copy is complete.
|
|
/// </summary>
|
|
internal static string CopyMessage(SessionCopyOutcome copy, bool earlier = false)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(copy);
|
|
const string Before = "La sessione per le richieste era già stata copiata quando il browser è tornato al motore";
|
|
const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale.";
|
|
var missing = copy.MissingValues + copy.MissingDocIds;
|
|
var needed = MissingNeeded(missing, past: true);
|
|
var missingClause = missing == 0
|
|
? string.Empty
|
|
: $" Alla pagina però {needed}: la copia ha comunque sostituito quella salvata prima, e le richieste che {(missing == 1 ? "lo" : "li")} usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}";
|
|
return copy.Status switch
|
|
{
|
|
SessionCopyStatus.Saved when earlier => Before + "." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
|
|
SessionCopyStatus.SavedInMemoryOnly when earlier =>
|
|
Before + ", ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
|
|
SessionCopyStatus.KeptComplete when earlier =>
|
|
$"Quando il browser è tornato al motore alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
|
|
SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause,
|
|
SessionCopyStatus.SavedInMemoryOnly =>
|
|
"Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause,
|
|
SessionCopyStatus.Discarded =>
|
|
"La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.",
|
|
SessionCopyStatus.KeptComplete =>
|
|
$"Alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima e non usa quella nuova. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
|
|
_ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage =>
|
|
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}",
|
|
_ =>
|
|
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}. La sessione salvata resta com'era. {Again}",
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// «mancano 3 valori che servono alle richieste», «manca 1 valore che serve alle richieste» (<paramref name="past"/>:
|
|
/// «mancava», «mancavano»): the count with the Italian singular.
|
|
/// </summary>
|
|
internal static string MissingNeeded(int missing, bool past)
|
|
{
|
|
var one = missing == 1;
|
|
var verb = past ? (one ? "mancava" : "mancavano") : (one ? "manca" : "mancano");
|
|
return $"{verb} {ItalianText.Count(missing, "valore", "valori")} che {(one ? "serve" : "servono")} alle richieste";
|
|
}
|
|
|
|
/// <summary>«Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any.</summary>
|
|
private async Task<Exception?> ForgetSavedSessionAsync()
|
|
{
|
|
if (_forgetSavedSession is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
// Not cancellable: «Scollega» must not stop halfway because the page that asked it went away.
|
|
await _forgetSavedSession(CancellationToken.None).ConfigureAwait(false);
|
|
return null;
|
|
}
|
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
|
{
|
|
return ex;
|
|
}
|
|
}
|
|
|
|
/// <summary>The empty rest page (or no document at all): never what Alberto should be shown.</summary>
|
|
private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl;
|
|
|
|
/// <summary>The address of the main frame, in full (never logged); null when the browser does not answer.</summary>
|
|
private async Task<string?> FullUrlAsync(CancellationToken ct)
|
|
{
|
|
try
|
|
{
|
|
return await _browser.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The address of the main frame as <see cref="FullUrlAsync"/> gives it, but a browser that does not answer is asked
|
|
/// again every <see cref="AddressPoll"/> until it does, for at most <see cref="AddressWait"/> (real time, issue #67);
|
|
/// null when it stayed silent. Cancelled with <paramref name="ct"/>.
|
|
/// </summary>
|
|
private async Task<string?> AwaitFullUrlAsync(CancellationToken ct)
|
|
{
|
|
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
limit.CancelAfter(AddressWait);
|
|
try
|
|
{
|
|
while (true)
|
|
{
|
|
if (await FullUrlAsync(limit.Token).ConfigureAwait(false) is { } url)
|
|
{
|
|
return url;
|
|
}
|
|
|
|
await _clock.Delay(AddressPoll, limit.Token).ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
|
{
|
|
_log.Info("collegamento", "Il browser non ha indicato la pagina in tempo: la pagina conta come quella di riposo.");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// After the engine's session ended: whether the page is the rest page (or still unknown). A browser that already let
|
|
/// <see cref="AddressWait"/> pass is asked once more (<paramref name="wait"/> false), not waited for again.
|
|
/// </summary>
|
|
private async Task<bool> IsAtRestAsync(bool wait, CancellationToken ct)
|
|
{
|
|
var url = wait ? await AwaitFullUrlAsync(ct).ConfigureAwait(false) : await FullUrlAsync(ct).ConfigureAwait(false);
|
|
return url is null || IsRest(url);
|
|
}
|
|
|
|
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 own navigation, so that no step of the profile search runs under it; null after
|
|
/// <see cref="PageTurnWait"/> (and always without an engine). The login and the start page from the rest page then
|
|
/// take the page anyway (Alberto asked for it, under his lease); «Pagina iniziale» gives up.
|
|
/// </summary>
|
|
private async Task<PageTurn?> TakePageAsync(CancellationToken ct)
|
|
{
|
|
if (_engine is not { } engine)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
limit.CancelAfter(PageTurnWait);
|
|
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>Forgets the copy made when this use of the browser was let go (S4b): it no longer answers a late «Ho finito».</summary>
|
|
private void ForgetLetGoCopy()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_letGoCopy = null;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// «Ho finito» ends the lease. When it ends one, that use of the browser is over: a further «Ho finito» (a double
|
|
/// click, a second tab) must not report a copy made when that use was let go earlier.
|
|
/// </summary>
|
|
private void EndUseWithHoFinito()
|
|
{
|
|
if (ReleaseLease())
|
|
{
|
|
ForgetLetGoCopy();
|
|
}
|
|
}
|
|
|
|
/// <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, watch) = TakeLeaseLocked();
|
|
}
|
|
|
|
return EndLease(lease, watch);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ends <paramref name="expected"/> by itself only if, in the same look, it is still the only lease of the browser and
|
|
/// no sign that Alberto uses the browser came after <paramref name="lastSign"/>: another lease (the remote view, the
|
|
/// window, a hold of the connection) is a sign now. True when the lease ended.
|
|
/// </summary>
|
|
private bool ReleaseIdleLease(IDisposable expected, DateTimeOffset lastSign)
|
|
{
|
|
IDisposable? lease;
|
|
CancellationTokenSource? watch;
|
|
lock (_gate)
|
|
{
|
|
if (!ReferenceEquals(_lease, expected))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
if (_browser.UserDriving.Leases > 1)
|
|
{
|
|
_lastDrivingSign = _clock.Now;
|
|
return false;
|
|
}
|
|
|
|
if (_lastDrivingSign > lastSign)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
(lease, watch) = TakeLeaseLocked();
|
|
}
|
|
|
|
return EndLease(lease, watch);
|
|
}
|
|
|
|
private (IDisposable? Lease, CancellationTokenSource? Watch) TakeLeaseLocked()
|
|
{
|
|
var taken = (_lease, _leaseWatch);
|
|
_lease = null;
|
|
_leaseWatch = null;
|
|
_leftAt = null;
|
|
return taken;
|
|
}
|
|
|
|
private static bool EndLease(IDisposable? lease, CancellationTokenSource? watch)
|
|
{
|
|
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.");
|
|
}
|
|
}
|
|
}
|