M6 Windows: composizione condivisa Febe.App per Server e Desktop; Febe per Windows (WPF) con l'interfaccia in WebView2, area di notifica, istanza unica, «Browser di Febe» su WebView2 con CDP filtrato (WebView2CdpSession) e ripieghi di S2 (composizione, Edge), guscio nativo, avvisi, spostamento verificato della cartella dei dati, icona del marchio; un solo Febe.exe, installatore NSIS e zip portabile; guida docs/windows.md e prove dal vivo S1–S3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
73 files changed
+7914
-699
No files matched your search
@@ -0,0 +1,468 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Api;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.App;
|
||||
|
||||
/// <summary>
|
||||
/// The link to Instagram over the real browser, the same in both shells (spec §4.1, §10.3, PROTOCOLLO.md). «Collegato»
|
||||
/// means that the session cookie exists in the browser profile: only its existence is checked
|
||||
/// (<c>Network.getCookies</c>, names only), never its value. Opening the login page is Alberto's action, not the
|
||||
/// engine's (rule 7, last sentence): it happens only while he holds the «driving» lease and the engine is still.
|
||||
/// On Windows the browser is the window «Browser di Febe»: «Accedi» and «Portalo in primo piano» bring it to the front,
|
||||
/// «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the profile. In Docker
|
||||
/// showing and hiding do nothing (the remote view shows the browser).
|
||||
/// </summary>
|
||||
public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Setting written at the first connection ever (Unix ms): the gradual start begins only once.</summary>
|
||||
public const string FirstConnectionKey = "collegamento.primo";
|
||||
|
||||
/// <summary>A cookie check younger than this is reused by the status (the sidebar asks often).</summary>
|
||||
public static readonly TimeSpan CookieCacheLifetime = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
|
||||
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly IFebeBrowser _browser;
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly string _loginUrl;
|
||||
private readonly SessionCookieOptions _cookie;
|
||||
private readonly SemaphoreSlim _commands = new(1, 1);
|
||||
private readonly Lock _gate = new();
|
||||
private EngineHost? _engine;
|
||||
private IDisposable? _lease;
|
||||
private bool? _connected;
|
||||
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
|
||||
|
||||
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, SessionCookieOptions cookie)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
||||
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
|
||||
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the browser holds the session, from the last check (null before the first one). The engine reads it
|
||||
/// on every turn (<see cref="EngineRuntime.IsConnected"/>): it never waits for the browser.
|
||||
/// </summary>
|
||||
public bool? IsConnected
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _connected;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition
|
||||
/// marks it as «Tu» (<see cref="Account.IsMine"/>); the status shows that account. Raised after every change of the
|
||||
/// connection, so that whoever learns the account can look again.
|
||||
/// </summary>
|
||||
public event EventHandler<bool>? ConnectionChanged;
|
||||
|
||||
/// <summary>The engine, once it exists (it is built after the browser).</summary>
|
||||
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
|
||||
|
||||
public async Task<ConnectionStatus> GetStatusAsync(CancellationToken ct)
|
||||
{
|
||||
var driving = _browser.UserIsDriving;
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
return new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, driving, null);
|
||||
}
|
||||
|
||||
var breaker = _engine?.Services.Breaker.State.Status;
|
||||
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
|
||||
? ConnectionState.VerificationRequired
|
||||
: await CheckAsync(force: false, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
|
||||
|
||||
Account? mine = null;
|
||||
if (state != ConnectionState.NotConnected)
|
||||
{
|
||||
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
|
||||
{
|
||||
EnsureBrowser();
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lease ??= _browser.UserDriving.Begin();
|
||||
}
|
||||
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
if (openLogin)
|
||||
{
|
||||
// The engine ends its session when the lease starts; wait for it before taking the page.
|
||||
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
||||
var result = await _browser.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", result.Succeeded
|
||||
? "Alberto usa il browser: pagina di accesso aperta."
|
||||
: "Alberto usa il browser: la pagina di accesso non si è aperta (errore di rete del browser).");
|
||||
}
|
||||
else
|
||||
{
|
||||
_log.Info("collegamento", "Alberto usa il browser.");
|
||||
}
|
||||
|
||||
// Windows: the window «Browser di Febe» comes to the front (Docker: nothing, the remote view shows it).
|
||||
await ShowQuietlyAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<FinishResult> FinishAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
ReleaseLease();
|
||||
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
|
||||
}
|
||||
|
||||
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false) == true;
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
|
||||
await RestQuietlyAsync().ConfigureAwait(false);
|
||||
await HideQuietlyAsync().ConfigureAwait(false);
|
||||
ReleaseLease();
|
||||
|
||||
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
|
||||
string message;
|
||||
if (!connected)
|
||||
{
|
||||
message = "Febe non trova la sessione di Instagram nel browser: l'accesso non sembra completato. Riprova con «Accedi a Instagram» e premi «Ho finito» solo dopo aver visto la tua pagina iniziale.";
|
||||
}
|
||||
else if (stopped)
|
||||
{
|
||||
message = "Collegato. Febe è ancora fermo per la verifica o la disconnessione: premi «Riprendi» quando vuoi che ricominci.";
|
||||
}
|
||||
else if (first)
|
||||
{
|
||||
message = "Collegato a Instagram. Febe comincia fra qualche minuto, con calma: nei primi giorni i tetti sono ridotti (avvio graduale).";
|
||||
}
|
||||
else
|
||||
{
|
||||
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
|
||||
}
|
||||
|
||||
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
|
||||
return new FinishResult(connected, message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CancelAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_browser.IsAvailable)
|
||||
{
|
||||
await RestQuietlyAsync().ConfigureAwait(false);
|
||||
await HideQuietlyAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
ReleaseLease();
|
||||
_log.Info("collegamento", "«Annulla»: il browser torna a riposo.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
var hold = _browser.UserDriving.Begin();
|
||||
try
|
||||
{
|
||||
var engine = _engine;
|
||||
if (engine is not null)
|
||||
{
|
||||
await engine.StopAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Windows: the browser window goes out of view and WebView2 closes before its folder is deleted.
|
||||
await HideQuietlyAsync().ConfigureAwait(false);
|
||||
Exception? failure = null;
|
||||
try
|
||||
{
|
||||
await _browser.RestartWithEmptyProfileAsync(ct).ConfigureAwait(false);
|
||||
SetConnected(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A file of the profile stayed (Windows: a process of the browser held it). The engine starts again
|
||||
// anyway; whether the session is still there is checked again, never assumed.
|
||||
failure = ex;
|
||||
await RefreshAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (engine is not null)
|
||||
{
|
||||
if (failure is null)
|
||||
{
|
||||
await engine.Services.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
"collegamento.scollegato",
|
||||
"Scollegato da te: il profilo del browser con la sessione di Instagram è stato cancellato.",
|
||||
ct: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await engine.StartAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (failure is not null)
|
||||
{
|
||||
_log.Warn("collegamento", "«Scollega»: il profilo del browser non si è potuto cancellare del tutto.", failure);
|
||||
throw new BadRequestException("«Scollega» non è riuscito del tutto: " + failure.Message);
|
||||
}
|
||||
|
||||
_log.Info("collegamento", "«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
ReleaseLease();
|
||||
hold.Dispose();
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
|
||||
/// and after the test site's automatic login.
|
||||
/// </summary>
|
||||
public async Task<bool?> RefreshAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
return IsConnected;
|
||||
}
|
||||
|
||||
var connected = await CheckAsync(force: true, ct).ConfigureAwait(false);
|
||||
if (connected == true)
|
||||
{
|
||||
await MarkConnectedAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return connected;
|
||||
}
|
||||
|
||||
/// <summary>The background check of the cookie, every <see cref="BackgroundCheck"/>, until cancelled.</summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _clock.Delay(BackgroundCheck, ct).ConfigureAwait(false);
|
||||
if (!_browser.UserIsDriving)
|
||||
{
|
||||
await RefreshAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or IOException)
|
||||
{
|
||||
// The browser is restarting: the next turn looks again.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
ReleaseLease();
|
||||
_commands.Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task<bool?> CheckAsync(bool force, CancellationToken ct)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!force && _connected is not null && _clock.Now - _checkedAt < CookieCacheLifetime)
|
||||
{
|
||||
return _connected;
|
||||
}
|
||||
}
|
||||
|
||||
bool has;
|
||||
try
|
||||
{
|
||||
has = await SessionCookieProbe.HasSessionCookieAsync(_browser.Cdp, _cookie, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
return IsConnected;
|
||||
}
|
||||
|
||||
SetConnected(has);
|
||||
return has;
|
||||
}
|
||||
|
||||
private void SetConnected(bool connected)
|
||||
{
|
||||
bool changed;
|
||||
lock (_gate)
|
||||
{
|
||||
changed = _connected != connected;
|
||||
_connected = connected;
|
||||
_checkedAt = _clock.Now;
|
||||
}
|
||||
|
||||
if (changed)
|
||||
{
|
||||
_log.Info("collegamento", connected ? "Sessione presente nel browser: collegato." : "Nessuna sessione nel browser: non collegato.");
|
||||
|
||||
// Wakes the engine: it looks again whether it can work (it only cancels a session if Alberto is driving).
|
||||
_engine?.NotifyUserDrivingChanged();
|
||||
ConnectionChanged?.Invoke(this, connected);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
|
||||
private async Task<bool> MarkConnectedAsync(CancellationToken ct)
|
||||
{
|
||||
if (await _storage.Settings.GetInt64Async(FirstConnectionKey, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var now = _clock.Now;
|
||||
await _storage.Settings.SetAsync(FirstConnectionKey, now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
|
||||
if (_engine is { } engine)
|
||||
{
|
||||
await engine.Services.NotifyFirstConnectionAsync(ct).ConfigureAwait(false);
|
||||
await engine.Services.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
"collegamento.primo",
|
||||
"Primo collegamento a Instagram: comincia l'avvio graduale.",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_log.Info("collegamento", "Primo collegamento: comincia l'avvio graduale.");
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task WaitForSessionEndAsync(CancellationToken ct)
|
||||
{
|
||||
if (_engine is not { } engine)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var deadline = _clock.Now + TimeSpan.FromSeconds(15);
|
||||
while (engine.Services.Runtime.CurrentSession is not null && _clock.Now < deadline)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> CurrentUrlAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = await _browser.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
||||
return Addresses.WithoutQuery(url);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RestQuietlyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _browser.RestAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
// The browser is restarting: it starts on the rest page anyway.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ShowQuietlyAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _browser.ShowToUserAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or IOException)
|
||||
{
|
||||
_log.Warn("collegamento", "La finestra del browser non è venuta in primo piano.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HideQuietlyAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _browser.HideFromUserAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or TimeoutException or IOException)
|
||||
{
|
||||
_log.Warn("collegamento", "La finestra del browser non si è nascosta.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseLease()
|
||||
{
|
||||
IDisposable? lease;
|
||||
lock (_gate)
|
||||
{
|
||||
lease = _lease;
|
||||
_lease = null;
|
||||
}
|
||||
|
||||
lease?.Dispose();
|
||||
}
|
||||
|
||||
private void EnsureBrowser()
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
throw new BadRequestException(_browser.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user