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; /// /// 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 /// (Network.getCookies, 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). /// /// /// /// The lease taken by «Accedi a Instagram» and «Usa il browser» ends with «Ho finito», «Annulla» or «Scollega», and also /// by itself when for 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. /// /// /// 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 — the site's home when connected, the login /// page when not connected or after a disconnection. /// /// /// 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». /// /// /// 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 () and the /// lease of «Accedi» / «Usa il browser» ending by itself. 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 /// («Serve «Ho finito»») and the engine waits. /// /// public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable { /// Setting written at the first connection ever (Unix ms): the gradual start begins only once. public const string FirstConnectionKey = "collegamento.primo"; /// Setting set by «Scollega» and removed by the next connection: until then a missing session is expected. public const string DisconnectedByUserKey = "collegamento.scollegato"; /// A cookie check younger than this is reused by the status (the sidebar asks often). public static readonly TimeSpan CookieCacheLifetime = TimeSpan.FromSeconds(3); /// How often the cookie is looked at in the background (outside sessions it is the only way to notice). 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 string _homeUrl; private readonly SessionCookieOptions _cookie; private readonly ISessionCopier? _copier; private readonly Func? _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; /// The browser of Febe. /// The database (first connection, «Scollega»). /// When Alberto last used the browser. /// The composition's clock. /// Febe's log. /// The page «Accedi a Instagram» opens. /// The site's home, the start page once connected. /// The session cookie looked for (its name only). /// /// 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. /// /// /// What «Scollega» does to the saved session (deletes it, memory and file); null when there is none to delete. /// public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie, ISessionCopier? copier = null, Func? 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; } /// /// Whether the browser holds the session, from the last check (null before the first one). The engine reads it /// on every turn (): it never waits for the browser. /// public bool? IsConnected { get { lock (_gate) { return _connected; } } } /// /// 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). /// public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present; /// /// Whether the engine may collect (): the session cookie is in the browser /// and, with a saved session, a readable copy of it is there too. /// public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing; /// /// 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. /// public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30); /// /// 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. /// public string StartPageUrl => IsConnected == true && _engine?.Services.Breaker.State.Status != BreakerStatus.Disconnected ? _homeUrl : _loginUrl; /// /// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition /// marks it as «Tu» (); the status shows that account. Raised after every change of the /// connection, so that whoever learns the account can look again. /// public event EventHandler? ConnectionChanged; /// /// 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. /// public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2); /// /// 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. /// public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15); /// The engine, once it exists (it is built after the browser). public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine)); public async Task 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)); } /// /// 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 /// . Never throws for the browser; logs counts only, and says which of the two happened. /// 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; } _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(); } } /// /// «Pagina iniziale» of the window's bar and of the remote view (issue #52): Alberto's own navigation (rule 7) to /// , 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. /// /// /// 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. /// /// /// The waits can last up to 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. /// 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(); } } public async Task 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(); } } /// /// 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 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). /// public async Task 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; } /// The background check of the cookie, every , until cancelled. 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 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; } /// Records the state of the cookie; returns the one before (null before the first check). 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; } /// /// 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. /// 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 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); } /// A session is in the browser again: from now on its loss is a disconnection. private async Task ForgetUserDisconnectAsync(CancellationToken ct) { if (await IsDisconnectedByUserAsync(ct).ConfigureAwait(false)) { _disconnectedByUser = false; await _storage.Settings.SetAsync(DisconnectedByUserKey, null, ct).ConfigureAwait(false); } } /// /// The «driving» lease of this service ends by itself once it has been the only lease of the browser for /// : 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). /// 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) { continue; } // Before the page goes back to the engine: the copy of the session (S4b, answer 5). if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, 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", $"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); } } /// /// 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 /// () 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. /// private async Task CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, 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. try { await _commands.WaitAsync(ct).ConfigureAwait(false); } 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("Fine della guida del browser", StillAlbertos, ct).ConfigureAwait(false); return true; } finally { ReleaseCommands(); } } /// /// 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). /// private async Task CopyOnLetGoAsync(string what, Func 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})."); } } /// What a copy without «Ho finito» did, for the log (counts only). 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", }; } /// The saved session for the interface, in counts and names; null without a saved session in this start. 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. } } /// The first connection ever starts the gradual start (spec §7.2). True when it was the first. private async Task 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; } /// /// 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. /// private async Task OpenForAlbertoAsync(bool openLogin, CancellationToken ct) { if (!openLogin && !IsRest(await FullUrlAsync(ct).ConfigureAwait(false))) { _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 (IsRest(await FullUrlAsync(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; } var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false); _log.Info("collegamento", result.Succeeded ? $"Alberto usa il browser: {what} aperta." : $"Alberto usa il browser: {what} non aperta (errore di rete del browser)."); } /// /// 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 /// (Earlier), as long as the saved session is still there. /// 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(); } } /// /// 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 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. /// 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}", }; } /// /// «mancano 3 valori che servono alle richieste», «manca 1 valore che serve alle richieste» (: /// «mancava», «mancavano»): the count with the Italian singular. /// 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"; } /// «Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any. private async Task 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; } } /// The empty rest page (or no document at all): never what Alberto should be shown. private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl; /// The address of the main frame, in full (never logged); null when the browser does not answer. private async Task 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; } } 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); } } /// /// The page turn for Alberto's own navigation, so that no step of the profile search runs under it; null after /// (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. /// private async Task 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 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; } } /// /// 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 — 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). /// 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); } } /// Forgets the copy made when this use of the browser was let go (S4b): it no longer answers a late «Ho finito». private void ForgetLetGoCopy() { lock (_gate) { _letGoCopy = null; } } /// /// «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. /// private void EndUseWithHoFinito() { if (ReleaseLease()) { ForgetLetGoCopy(); } } /// Ends the lease (only , when given). True when a lease ended. 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); } /// /// Ends 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 : another lease (the remote view, the /// window, a hold of the connection) is a sign now. True when the lease ended. /// 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; 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."); } } }