Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)
Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9958745e53
commit
883ea4683c
41 files changed
+1349
-101
No files matched your search
@@ -4,6 +4,7 @@ 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;
|
||||
@@ -40,6 +41,14 @@ namespace Febe.App;
|
||||
/// (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"/>) 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
|
||||
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable
|
||||
{
|
||||
@@ -74,6 +83,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
private bool? _connected;
|
||||
private bool? _disconnectedByUser;
|
||||
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
|
||||
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
|
||||
|
||||
/// <param name="browser">The browser of Febe.</param>
|
||||
/// <param name="storage">The database (first connection, «Scollega»).</param>
|
||||
@@ -119,6 +129,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
/// <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
|
||||
@@ -161,6 +189,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
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)
|
||||
@@ -168,7 +201,47 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(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» (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.
|
||||
/// </summary>
|
||||
public async Task CopyOnWindowClosedAsync(CancellationToken ct)
|
||||
{
|
||||
const string What = "Finestra del browser chiusa";
|
||||
if (_copier is null || !_browser.IsAvailable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
limit.CancelAfter(LetGoWait);
|
||||
try
|
||||
{
|
||||
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (limit.IsCancellationRequested)
|
||||
{
|
||||
_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)
|
||||
@@ -653,7 +726,18 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
lastSign = _lastDrivingSign;
|
||||
}
|
||||
|
||||
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
|
||||
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;
|
||||
}
|
||||
|
||||
if (ReleaseLease(lease))
|
||||
{
|
||||
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
|
||||
return;
|
||||
@@ -666,6 +750,163 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
/// <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, 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.
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
||||
if (_engine is not null && turn is null)
|
||||
{
|
||||
_log.Info("collegamento", $"{what}: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
|
||||
return;
|
||||
}
|
||||
|
||||
var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
_lastCopyAt = _clock.Now;
|
||||
}
|
||||
|
||||
_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.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 : string.Create(CultureInfo.InvariantCulture, $", ma mancano {missing} valori che servono alle richieste");
|
||||
return copy.Status switch
|
||||
{
|
||||
SessionCopyStatus.Saved => "sessione copiata" + clause,
|
||||
SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause,
|
||||
SessionCopyStatus.KeptComplete => string.Create(CultureInfo.InvariantCulture, $"copia incompleta ({missing} 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)
|
||||
{
|
||||
@@ -801,6 +1042,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
"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 => string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"Alla pagina mancavano {missing} valori che servono alle richieste: 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}",
|
||||
_ =>
|
||||
|
||||
+20
-5
@@ -261,7 +261,16 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
// Browser, connection, engine. The engine loop starts only once the browser is up.
|
||||
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
|
||||
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
|
||||
// The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens.
|
||||
var context = new FebePlatformContext(
|
||||
o,
|
||||
data,
|
||||
Database,
|
||||
Clock,
|
||||
Log,
|
||||
Tracker,
|
||||
ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
|
||||
ct => Connection?.CopyOnWindowClosedAsync(ct) ?? Task.CompletedTask);
|
||||
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
|
||||
Browser = browser;
|
||||
PrepareSavedSession(context, browser);
|
||||
@@ -286,8 +295,9 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
random,
|
||||
engineOptions,
|
||||
userIsDriving: () => browser.UserIsDriving,
|
||||
isConnected: () => connection.IsConnected == true,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
isConnected: () => connection.IsReadyToCollect,
|
||||
ct: ct,
|
||||
sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false);
|
||||
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
|
||||
// capture sees goes to the session in progress, if any.
|
||||
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
|
||||
@@ -576,10 +586,15 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
var protector = _platform.CreateSessionProtector(context);
|
||||
var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
|
||||
var rules = LoadSignalRules(context.Data);
|
||||
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message));
|
||||
var settings = context.Storage.Settings;
|
||||
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message))
|
||||
{
|
||||
// What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once.
|
||||
IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy,
|
||||
};
|
||||
_requestCatalog = catalog;
|
||||
SavedSession = saved;
|
||||
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito».");
|
||||
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito», alla chiusura della finestra del browser e alla fine della guida.");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
|
||||
{
|
||||
|
||||
@@ -72,7 +72,12 @@ public interface IFebePlatform
|
||||
/// the login page otherwise, once the engine's session ended and with the page's turn
|
||||
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
|
||||
/// </param>
|
||||
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
|
||||
/// <param name="CopyOnWindowClosed">
|
||||
/// What closing the browser window does before the page goes back to the engine (issue #36, S4b): the connection copies
|
||||
/// the session into the saved session, when there is one (<c>BrowserConnectionService.CopyOnWindowClosedAsync</c>). The
|
||||
/// window holds the driving gate until the task ends. Null: nothing.
|
||||
/// </param>
|
||||
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null, Func<CancellationToken, Task>? CopyOnWindowClosed = null);
|
||||
|
||||
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
|
||||
public sealed record FebeAppOptions
|
||||
|
||||
@@ -19,6 +19,12 @@ public enum SessionCopyStatus
|
||||
|
||||
/// <summary>Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).</summary>
|
||||
Discarded,
|
||||
|
||||
/// <summary>
|
||||
/// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose
|
||||
/// «Tieni la copia completa» (<see cref="IncompleteCopyChoice.KeepComplete"/>). The saved session stays as it was.
|
||||
/// </summary>
|
||||
KeptComplete,
|
||||
}
|
||||
|
||||
/// <summary>What a copy did, for the message of «Ho finito» and the tests. Never a value.</summary>
|
||||
@@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the
|
||||
/// automatic login of the test site. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e
|
||||
/// sostituisce»), also when some value of the page is missing: the requests that send it then do not leave and stop
|
||||
/// the engine as a disconnection until a new copy has it (never a way back to the pages). A refused copy leaves the
|
||||
/// saved session as it is.
|
||||
/// The saved session as the Collegamento page shows it (issue #36, S4b, answer 10): its state, when it was copied, how
|
||||
/// many values of the page and doc_id it holds and the names of those it lacks. Counts and names only, never a value.
|
||||
/// </summary>
|
||||
/// <param name="State">Whether a saved session is there and can be read.</param>
|
||||
/// <param name="CopiedAt">When the browser's session was copied; null without a session or when not known.</param>
|
||||
/// <param name="Cookies">How many cookies it holds.</param>
|
||||
/// <param name="ValuesPresent">Values of the page it holds, of <paramref name="ValuesExpected"/>.</param>
|
||||
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
|
||||
/// <param name="MissingValues">Names of the values of the page it lacks.</param>
|
||||
/// <param name="DocIdsPresent">doc_id it holds, of <paramref name="DocIdsExpected"/>.</param>
|
||||
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
|
||||
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
|
||||
/// <param name="NeededMissing">How many of the missing values and doc_id a configured operation sends.</param>
|
||||
public sealed record SavedSessionReport(
|
||||
SavedSessionState State,
|
||||
DateTimeOffset? CopiedAt,
|
||||
int Cookies,
|
||||
int ValuesPresent,
|
||||
int ValuesExpected,
|
||||
IReadOnlyList<string> MissingValues,
|
||||
int DocIdsPresent,
|
||||
int DocIdsExpected,
|
||||
IReadOnlyList<string> MissingDocIds,
|
||||
int NeededMissing)
|
||||
{
|
||||
/// <summary>True when a readable session is there and nothing a configured operation sends is missing.</summary>
|
||||
public bool Complete => State == SavedSessionState.Present && NeededMissing == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», after the
|
||||
/// automatic login of the test site, and (S4b) when Alberto closes the browser window on Windows or his driving lease
|
||||
/// ends by itself. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e sostituisce»), also when
|
||||
/// some value of the page is missing — unless Alberto chose «Tieni la copia completa» and the saved one is complete.
|
||||
/// The requests that send a missing value do not leave and stop the engine as a disconnection until a new copy has it
|
||||
/// (never a way back to the pages). A refused copy leaves the saved session as it is.
|
||||
/// </summary>
|
||||
public interface ISessionCopier
|
||||
{
|
||||
@@ -48,6 +85,12 @@ public interface ISessionCopier
|
||||
/// <param name="mayKeep">Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).</param>
|
||||
/// <param name="ct">Cancels the copy; nothing is saved then.</param>
|
||||
Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct);
|
||||
|
||||
/// <summary>Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often).</summary>
|
||||
SavedSessionState SavedState { get; }
|
||||
|
||||
/// <summary>The saved session now, in counts and names (the Collegamento page, «Collegato»).</summary>
|
||||
SavedSessionReport Report();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What an incomplete copy does, asked at every copy (the setting of the Collegamento page,
|
||||
/// <see cref="SessionCopySettings"/>); by default it replaces the saved session, as before.
|
||||
/// </summary>
|
||||
public Func<CancellationToken, Task<IncompleteCopyChoice>> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace);
|
||||
|
||||
/// <summary>
|
||||
/// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the
|
||||
/// connection meanwhile, so a browser that hangs must not hold them for ever (real time).
|
||||
@@ -116,15 +165,24 @@ public sealed class BrowserSessionCopier : ISessionCopier
|
||||
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
|
||||
}
|
||||
|
||||
// Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the
|
||||
// saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies.
|
||||
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
|
||||
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
|
||||
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
|
||||
var needed = neededValues.Concat(neededDocIds).ToList();
|
||||
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
|
||||
|
||||
// An incomplete copy replaces the saved one (§6.0: an older copy could keep another login's cookies), unless
|
||||
// Alberto chose to keep a complete one (answer 9 of 18 November 2026) and the saved one is complete.
|
||||
if (needed.Count > 0
|
||||
&& IsComplete(_store.Read())
|
||||
&& await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete)
|
||||
{
|
||||
_log($"Sessione letta ma non salvata: mancano {string.Join(", ", needed)}, che servono alle operazioni configurate; come scelto, resta la copia completa salvata prima ({counts}).");
|
||||
return new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, result.Cookies, neededValues.Count, neededDocIds.Count);
|
||||
}
|
||||
|
||||
// Not cancelled from here: the copy was made, and a half-written replacement is never left.
|
||||
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
|
||||
_log($"Sessione copiata: {counts}"
|
||||
+ (needed.Count == 0 ? string.Empty : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate")
|
||||
+ (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa")
|
||||
@@ -138,6 +196,52 @@ public sealed class BrowserSessionCopier : ISessionCopier
|
||||
neededDocIds.Count);
|
||||
}
|
||||
|
||||
public SavedSessionState SavedState => _store.State;
|
||||
|
||||
public SavedSessionReport Report()
|
||||
{
|
||||
var state = _store.State;
|
||||
var values = state == SavedSessionState.Present ? _store.Read() : null;
|
||||
if (values is null)
|
||||
{
|
||||
var none = state == SavedSessionState.Present ? SavedSessionState.None : state;
|
||||
return new SavedSessionReport(none, null, 0, 0, _plan.Values.Count, [], 0, _plan.DocIds.Count, [], 0);
|
||||
}
|
||||
|
||||
var missingValues = new List<string>();
|
||||
var needed = 0;
|
||||
foreach (var read in _plan.Values)
|
||||
{
|
||||
if (!values.Fields.ContainsKey(read.Field))
|
||||
{
|
||||
missingValues.Add(read.Field);
|
||||
needed += _plan.NeededValues.Contains(read.Field) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
var missingDocIds = new List<string>();
|
||||
foreach (var read in _plan.DocIds)
|
||||
{
|
||||
if (!values.DocIds.ContainsKey(read.Field))
|
||||
{
|
||||
missingDocIds.Add(read.Field);
|
||||
needed += _plan.NeededDocIds.Contains(read.Field) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
return new SavedSessionReport(
|
||||
SavedSessionState.Present,
|
||||
values.CopiedAt,
|
||||
values.Cookies.Count,
|
||||
_plan.Values.Count - missingValues.Count,
|
||||
_plan.Values.Count,
|
||||
missingValues,
|
||||
_plan.DocIds.Count - missingDocIds.Count,
|
||||
_plan.DocIds.Count,
|
||||
missingDocIds,
|
||||
needed);
|
||||
}
|
||||
|
||||
/// <summary>Why a copy was refused, in Italian.</summary>
|
||||
public static string Reason(CaptureRefusal refusal) => refusal switch
|
||||
{
|
||||
@@ -146,4 +250,31 @@ public sealed class BrowserSessionCopier : ISessionCopier
|
||||
CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
|
||||
_ => "il browser non ha risposto",
|
||||
};
|
||||
|
||||
/// <summary>True when <paramref name="saved"/> holds every value and doc_id a configured operation sends.</summary>
|
||||
private bool IsComplete(SiteSessionValues? saved)
|
||||
{
|
||||
if (saved is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var field in _plan.NeededValues)
|
||||
{
|
||||
if (!saved.Fields.ContainsKey(field))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var operation in _plan.NeededDocIds)
|
||||
{
|
||||
if (!saved.DocIds.ContainsKey(operation))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -57,12 +57,14 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
|
||||
/// <c>page</c> section of the catalog says where to read (<see cref="PageSources"/>): <c>lsd</c>, <c>fb_dtsg</c>,
|
||||
/// <c>app_id</c>, <c>account_id</c>, and since S4 <c>rev</c> (<c>__rev</c>), <c>hs</c> (<c>__hs</c>), <c>hsi</c>
|
||||
/// (<c>__hsi</c>), <c>dpr</c>, <c>ccg</c> (<c>__ccg</c>), <c>comet_req</c> (<c>__comet_req</c>) and
|
||||
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>).
|
||||
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>), and since S4b <c>spin_r</c>, <c>spin_b</c> and <c>spin_t</c>
|
||||
/// (<c>__spin_r</c>, <c>__spin_b</c>, <c>__spin_t</c>: a snapshot of the page at «Ho finito», decision of 18 November
|
||||
/// 2026).
|
||||
/// </summary>
|
||||
public static IReadOnlySet<string> SessionFields { get; } = new[]
|
||||
{
|
||||
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
|
||||
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce",
|
||||
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t",
|
||||
}.ToFrozenSet(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The session fields that need no <c>page</c> entry: the browser's user agent and the claim the site sets (H13).</summary>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>What a copy of the browser's session does when some value the requests need is missing (issue #36, S4b).</summary>
|
||||
public enum IncompleteCopyChoice
|
||||
{
|
||||
/// <summary>
|
||||
/// «Sostituisci comunque» (the default): the new copy replaces the saved one all the same, because keeping an older
|
||||
/// copy could keep the cookies of another login (§6.0).
|
||||
/// </summary>
|
||||
Replace,
|
||||
|
||||
/// <summary>
|
||||
/// «Tieni la copia completa»: when the saved copy has every value the configured operations need and the new one
|
||||
/// does not, the saved one stays and the message says so.
|
||||
/// </summary>
|
||||
KeepComplete,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings of the copy of the session (issue #36, S4b; decision of Alberto of 18 November 2026, answer 9), in the
|
||||
/// <c>setting</c> table like the other settings. Read at every copy: a change holds from the next copy, no restart.
|
||||
/// </summary>
|
||||
/// <param name="IncompleteCopy">What an incomplete copy does.</param>
|
||||
public sealed record SessionCopySettings(IncompleteCopyChoice IncompleteCopy)
|
||||
{
|
||||
/// <summary>The key of <see cref="IncompleteCopy"/>: <c>sostituisci</c> or <c>tieni-completa</c>.</summary>
|
||||
public const string IncompleteCopyKey = "sessione.copia-incompleta";
|
||||
|
||||
/// <summary>The text of <see cref="IncompleteCopyChoice.Replace"/> in the table and in the API.</summary>
|
||||
public const string ReplaceText = "sostituisci";
|
||||
|
||||
/// <summary>The text of <see cref="IncompleteCopyChoice.KeepComplete"/> in the table and in the API.</summary>
|
||||
public const string KeepCompleteText = "tieni-completa";
|
||||
|
||||
/// <summary>The settings of a database that never stored them: an incomplete copy replaces the saved one.</summary>
|
||||
public static SessionCopySettings Default { get; } = new(IncompleteCopyChoice.Replace);
|
||||
|
||||
/// <summary>The text of <paramref name="choice"/>.</summary>
|
||||
public static string ToText(IncompleteCopyChoice choice) => choice == IncompleteCopyChoice.KeepComplete ? KeepCompleteText : ReplaceText;
|
||||
|
||||
/// <summary>The choice of <paramref name="text"/>; null for any other text.</summary>
|
||||
public static IncompleteCopyChoice? Parse(string? text) => text switch
|
||||
{
|
||||
ReplaceText => IncompleteCopyChoice.Replace,
|
||||
KeepCompleteText => IncompleteCopyChoice.KeepComplete,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>The stored settings; an unknown or missing value is the default.</summary>
|
||||
public static async Task<SessionCopySettings> LoadAsync(ISettingsStore settings, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var text = await settings.GetAsync(IncompleteCopyKey, ct).ConfigureAwait(false);
|
||||
return Parse(text) is { } choice ? new SessionCopySettings(choice) : Default;
|
||||
}
|
||||
|
||||
/// <summary>Stores these settings.</summary>
|
||||
public Task SaveAsync(ISettingsStore settings, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return settings.SetAsync(IncompleteCopyKey, ToText(IncompleteCopy), ct);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
|
||||
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, __spin_r, __spin_b e __spin_t dalle chiavi omonime di SiteData (decisione di Alberto del 18 novembre 2026: si copiano dalla pagina a «Ho finito», come gli altri; chi le aggiunge alla richiesta resta da vedere, H23), i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce, spin_r, spin_b, spin_t), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn e __d, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
|
||||
"page": {
|
||||
"note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.",
|
||||
"docIdModule": "{operation}_instagramRelayOperation",
|
||||
@@ -15,7 +15,10 @@
|
||||
"dpr": "SiteData.pr",
|
||||
"comet_req": "SiteData.comet_env",
|
||||
"ccg": "WebConnectionClassServerGuess.connectionClass",
|
||||
"entry_nonce": "BootloaderConfig.nonce"
|
||||
"entry_nonce": "BootloaderConfig.nonce",
|
||||
"spin_r": "SiteData.__spin_r",
|
||||
"spin_b": "SiteData.__spin_b",
|
||||
"spin_t": "SiteData.__spin_t"
|
||||
}
|
||||
},
|
||||
"operations": [
|
||||
@@ -66,9 +69,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -148,9 +151,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -226,9 +229,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -310,9 +313,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -389,9 +392,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -465,9 +468,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -538,9 +541,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -618,9 +621,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
@@ -699,9 +702,9 @@
|
||||
"__rev": "session:rev",
|
||||
"__s": "pending",
|
||||
"__sjsp": "pending",
|
||||
"__spin_b": "pending",
|
||||
"__spin_r": "pending",
|
||||
"__spin_t": "pending",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_t": "session:spin_t",
|
||||
"__user": "session:account_id",
|
||||
"av": "session:account_id",
|
||||
"doc_id": "session:doc_id",
|
||||
|
||||
@@ -15,7 +15,10 @@
|
||||
"dpr": "VersioneProva.dpr",
|
||||
"comet_req": "VersioneProva.comet",
|
||||
"ccg": "ConnessioneProva.classe",
|
||||
"entry_nonce": "AvvioProva.nonce"
|
||||
"entry_nonce": "AvvioProva.nonce",
|
||||
"spin_r": "GiroProva.revisione",
|
||||
"spin_b": "GiroProva.ramo",
|
||||
"spin_t": "GiroProva.tempo"
|
||||
}
|
||||
},
|
||||
"operations": [
|
||||
@@ -104,6 +107,9 @@
|
||||
"__hs": "session:hs",
|
||||
"__hsi": "session:hsi",
|
||||
"__rev": "session:rev",
|
||||
"__spin_r": "session:spin_r",
|
||||
"__spin_b": "session:spin_b",
|
||||
"__spin_t": "session:spin_t",
|
||||
"dpr": "session:dpr",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"lsd": "session:lsd",
|
||||
@@ -121,7 +127,7 @@
|
||||
"profilo"
|
||||
],
|
||||
"sample": "000002-profilo-pubblico",
|
||||
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
|
||||
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req, __spin_r, __spin_b, __spin_t) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
|
||||
},
|
||||
{
|
||||
"name": "profilo-altri",
|
||||
|
||||
@@ -12,6 +12,7 @@ public sealed class EngineRuntime
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Func<bool> _userIsDriving;
|
||||
private readonly Func<bool>? _isConnected;
|
||||
private readonly Func<bool>? _sessionCopyMissing;
|
||||
private CautionProfile _profile = CautionProfile.Prudent;
|
||||
private DateTimeOffset? _rampStart;
|
||||
private SessionContext? _session;
|
||||
@@ -23,10 +24,15 @@ public sealed class EngineRuntime
|
||||
|
||||
/// <param name="userIsDriving">True while Alberto uses the browser (<see cref="IBrowserHost.UserIsDriving"/>).</param>
|
||||
/// <param name="isConnected">Whether the Instagram session exists in the browser; null when unknown.</param>
|
||||
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null)
|
||||
/// <param name="sessionCopyMissing">
|
||||
/// True when the browser holds the session but the saved session of the raccolta «richieste» is missing (issue #36,
|
||||
/// S4b): <paramref name="isConnected"/> is then false and the monitor says «Serve «Ho finito»». Null: never.
|
||||
/// </param>
|
||||
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null, Func<bool>? sessionCopyMissing = null)
|
||||
{
|
||||
_userIsDriving = userIsDriving ?? (() => false);
|
||||
_isConnected = isConnected;
|
||||
_sessionCopyMissing = sessionCopyMissing;
|
||||
}
|
||||
|
||||
/// <summary>The effective caution profile (settings applied).</summary>
|
||||
@@ -56,6 +62,9 @@ public sealed class EngineRuntime
|
||||
/// <summary>Whether the browser holds an Instagram session; null when the host does not say.</summary>
|
||||
public bool? IsConnected => _isConnected?.Invoke();
|
||||
|
||||
/// <summary>True when the browser holds the session but the copy for the requests is missing (S4b).</summary>
|
||||
public bool SessionCopyMissing => _sessionCopyMissing?.Invoke() == true;
|
||||
|
||||
/// <summary>The session in progress, if any. The Governor refuses every site action without one.</summary>
|
||||
public SessionContext? CurrentSession
|
||||
{
|
||||
|
||||
@@ -85,6 +85,7 @@ public sealed class EngineServices
|
||||
/// <param name="userIsDriving">True while Alberto uses the browser.</param>
|
||||
/// <param name="isConnected">Whether the browser holds an Instagram session; null when unknown.</param>
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
/// <param name="sessionCopyMissing">True when the session is in the browser but its saved copy is missing (S4b).</param>
|
||||
public static async Task<EngineServices> CreateAsync(
|
||||
IFebeStorage storage,
|
||||
IClock clock,
|
||||
@@ -92,14 +93,15 @@ public sealed class EngineServices
|
||||
EngineOptions? options = null,
|
||||
Func<bool>? userIsDriving = null,
|
||||
Func<bool>? isConnected = null,
|
||||
CancellationToken ct = default)
|
||||
CancellationToken ct = default,
|
||||
Func<bool>? sessionCopyMissing = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(random);
|
||||
options ??= EngineOptions.Default;
|
||||
|
||||
var runtime = new EngineRuntime(userIsDriving, isConnected);
|
||||
var runtime = new EngineRuntime(userIsDriving, isConnected, sessionCopyMissing);
|
||||
var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||
runtime.Profile = settings.EffectiveProfile;
|
||||
runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -184,6 +184,8 @@ public sealed class EngineMonitor : IEngineMonitor
|
||||
|
||||
case EngineMode.Disconnected:
|
||||
return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo");
|
||||
case EngineMode.NotConnected when runtime.SessionCopyMissing:
|
||||
return ("Serve «Ho finito»", ["Il browser è collegato, ma manca la copia della sessione per le richieste.", "Dalla pagina Collegamento apri il browser e premi «Ho finito» sulla tua pagina iniziale."], "Serve «Ho finito»");
|
||||
case EngineMode.NotConnected:
|
||||
return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato");
|
||||
case EngineMode.UserDriving:
|
||||
|
||||
@@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
|
||||
Host = new WebView2Host(
|
||||
ui,
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage),
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage, context.CopyOnWindowClosed),
|
||||
context.Log);
|
||||
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,11 @@ namespace Febe.Desktop.Browser;
|
||||
/// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise,
|
||||
/// once the engine's session ended and with the page's turn. Null: the button does nothing.
|
||||
/// </param>
|
||||
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
|
||||
/// <param name="CopyOnClose">
|
||||
/// What closing the window does before the page goes back to the engine (issue #36, S4b): the connection copies the
|
||||
/// session, when it keeps a saved one. The window keeps the engine still until the task ends. Null: nothing.
|
||||
/// </param>
|
||||
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null, Func<CancellationToken, Task>? CopyOnClose = null);
|
||||
|
||||
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
|
||||
internal enum ProcessFailureResponse
|
||||
@@ -554,12 +558,42 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
TakeLease();
|
||||
}
|
||||
|
||||
/// <summary>Alberto closed the window (or left it minimised too long): done, out of view.</summary>
|
||||
/// <summary>
|
||||
/// Alberto closed the window (or left it minimised too long): done, out of view at once. With a saved session
|
||||
/// (S4b) the session is copied first: a hold of the driving gate keeps the page his until the copy is over, and only
|
||||
/// then does it go back to the engine (rule 7).
|
||||
/// </summary>
|
||||
private void Done()
|
||||
{
|
||||
_window?.MoveOffScreen();
|
||||
ReleaseLease();
|
||||
NotifyPositionChanged();
|
||||
if (_lease is null || _closing || _settings.CopyOnClose is not { } copy)
|
||||
{
|
||||
ReleaseLease();
|
||||
return;
|
||||
}
|
||||
|
||||
var hold = UserDriving.Begin();
|
||||
ReleaseLease();
|
||||
_ = CopyThenLetGoAsync(copy, hold);
|
||||
}
|
||||
|
||||
private async Task CopyThenLetGoAsync(Func<CancellationToken, Task> copy, IDisposable hold)
|
||||
{
|
||||
try
|
||||
{
|
||||
await copy(CancellationToken.None).ConfigureAwait(true);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// The kind of error only: the page and the browser may hold what the session holds.
|
||||
_log.Warn("browser", $"Copia della sessione alla chiusura della finestra non riuscita ({ex.GetType().Name}).");
|
||||
}
|
||||
finally
|
||||
{
|
||||
hold.Dispose();
|
||||
_settings.MarkUsed();
|
||||
}
|
||||
}
|
||||
|
||||
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Native;
|
||||
@@ -57,19 +59,54 @@ public static class ConnectionApi
|
||||
await connection.DisconnectAsync(ct).ConfigureAwait(false);
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
// What an incomplete copy of the session does (issue #36, S4b, answer 9): read at every copy, no restart.
|
||||
endpoints.MapGet("/api/connection/settings", async (IFebeStorage storage, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto));
|
||||
|
||||
endpoints.MapPut("/api/connection/settings", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
|
||||
{
|
||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConnectionSettingsDto).ConfigureAwait(false);
|
||||
var choice = SessionCopySettings.Parse(body.IncompleteCopy)
|
||||
?? throw new BadRequestException($"Scelta sconosciuta per la copia incompleta: ammesse «{SessionCopySettings.ReplaceText}» e «{SessionCopySettings.KeepCompleteText}».");
|
||||
await new SessionCopySettings(choice).SaveAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto);
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<ConnectionSettingsDto> SettingsAsync(IFebeStorage storage, CancellationToken ct)
|
||||
{
|
||||
var settings = await SessionCopySettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||
return new ConnectionSettingsDto(SessionCopySettings.ToText(settings.IncompleteCopy));
|
||||
}
|
||||
|
||||
public static ConnectionStatusDto ToDto(ConnectionStatus status)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(status);
|
||||
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl);
|
||||
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl, ToDto(status.SavedSession));
|
||||
}
|
||||
|
||||
/// <summary>The saved session in counts and names; null without one.</summary>
|
||||
public static SavedSessionDto? ToDto(SavedSessionStatus? saved) => saved is null
|
||||
? null
|
||||
: new SavedSessionDto(
|
||||
saved.State,
|
||||
saved.CopiedAt?.ToUnixTimeMilliseconds(),
|
||||
saved.Cookies,
|
||||
saved.ValuesPresent,
|
||||
saved.ValuesExpected,
|
||||
saved.MissingValues,
|
||||
saved.DocIdsPresent,
|
||||
saved.DocIdsExpected,
|
||||
saved.MissingDocIds,
|
||||
saved.NeededMissing);
|
||||
|
||||
public static string State(ConnectionState state) => state switch
|
||||
{
|
||||
ConnectionState.NotConnected => "notConnected",
|
||||
ConnectionState.Connected => "connected",
|
||||
ConnectionState.VerificationRequired => "verificationRequired",
|
||||
ConnectionState.SessionCopyMissing => "copyMissing",
|
||||
_ => "browserUnavailable",
|
||||
};
|
||||
}
|
||||
@@ -98,10 +98,16 @@ public static class EngineApi
|
||||
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
var state = snapshot.Mode switch
|
||||
{
|
||||
EngineMode.NotConnected => "notConnected",
|
||||
// The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account.
|
||||
EngineMode.NotConnected => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.SessionCopyMissing ? "copyMissing" : "notConnected",
|
||||
EngineMode.StoppedForVerification => "verification",
|
||||
EngineMode.Disconnected => "disconnected",
|
||||
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
|
||||
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch
|
||||
{
|
||||
ConnectionState.Connected => "connected",
|
||||
ConnectionState.SessionCopyMissing => "copyMissing",
|
||||
_ => "notConnected",
|
||||
},
|
||||
_ => "connected",
|
||||
};
|
||||
var link = state == "notConnected"
|
||||
|
||||
@@ -48,6 +48,7 @@ namespace Febe.Web.Api;
|
||||
[JsonSerializable(typeof(LoginDto))]
|
||||
[JsonSerializable(typeof(Library.LibraryChange))]
|
||||
[JsonSerializable(typeof(ConnectionStatusDto))]
|
||||
[JsonSerializable(typeof(ConnectionSettingsDto))]
|
||||
[JsonSerializable(typeof(BeginDrivingRequest))]
|
||||
[JsonSerializable(typeof(CancelDrivingRequest))]
|
||||
[JsonSerializable(typeof(FinishDto))]
|
||||
|
||||
@@ -5,8 +5,33 @@ namespace Febe.Web.Api;
|
||||
|
||||
// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
|
||||
|
||||
/// <summary><c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, verificationRequired, browserUnavailable.</summary>
|
||||
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl);
|
||||
/// <summary>
|
||||
/// <c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, copyMissing, verificationRequired,
|
||||
/// browserUnavailable. <see cref="SavedSession"/> only with the raccolta «richieste».
|
||||
/// </summary>
|
||||
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl, SavedSessionDto? SavedSession = null);
|
||||
|
||||
/// <summary>
|
||||
/// The saved session in counts and names (issue #36, S4b): <see cref="State"/> present, none or unreadable;
|
||||
/// <see cref="CopiedAt"/> Unix milliseconds. Never a value.
|
||||
/// </summary>
|
||||
public sealed record SavedSessionDto(
|
||||
string State,
|
||||
long? CopiedAt,
|
||||
int Cookies,
|
||||
int ValuesPresent,
|
||||
int ValuesExpected,
|
||||
IReadOnlyList<string> MissingValues,
|
||||
int DocIdsPresent,
|
||||
int DocIdsExpected,
|
||||
IReadOnlyList<string> MissingDocIds,
|
||||
int NeededMissing);
|
||||
|
||||
/// <summary>
|
||||
/// <c>GET/PUT /api/connection/settings</c>: what an incomplete copy of the session does, <c>sostituisci</c> (the
|
||||
/// default) or <c>tieni-completa</c>.
|
||||
/// </summary>
|
||||
public sealed record ConnectionSettingsDto(string IncompleteCopy);
|
||||
|
||||
/// <summary><c>POST /api/connection/begin</c>.</summary>
|
||||
public sealed record BeginDrivingRequest(bool OpenLogin);
|
||||
|
||||
@@ -14,6 +14,48 @@ public enum ConnectionState
|
||||
|
||||
/// <summary>The browser is not available (starting, crashed, demo without browser).</summary>
|
||||
BrowserUnavailable,
|
||||
|
||||
/// <summary>
|
||||
/// The session cookie is in the browser, but the raccolta «richieste» has no readable saved session to send it with
|
||||
/// (issue #36, S4b): «Serve «Ho finito»». The engine waits until a copy is made.
|
||||
/// </summary>
|
||||
SessionCopyMissing,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The saved session of the raccolta «richieste» as the Collegamento page shows it (issue #36, S4b): counts and names
|
||||
/// only, never a value (rule 10).
|
||||
/// </summary>
|
||||
/// <param name="State"><see cref="Present"/>, <see cref="None"/> or <see cref="Unreadable"/>.</param>
|
||||
/// <param name="CopiedAt">When the copy was made; null when there is none or it is not known.</param>
|
||||
/// <param name="Cookies">How many cookies it holds.</param>
|
||||
/// <param name="ValuesPresent">Values of the page it holds.</param>
|
||||
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
|
||||
/// <param name="MissingValues">Names of the values it lacks.</param>
|
||||
/// <param name="DocIdsPresent">doc_id it holds.</param>
|
||||
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
|
||||
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
|
||||
/// <param name="NeededMissing">How many of those a configured operation sends (its requests do not leave).</param>
|
||||
public sealed record SavedSessionStatus(
|
||||
string State,
|
||||
DateTimeOffset? CopiedAt,
|
||||
int Cookies,
|
||||
int ValuesPresent,
|
||||
int ValuesExpected,
|
||||
IReadOnlyList<string> MissingValues,
|
||||
int DocIdsPresent,
|
||||
int DocIdsExpected,
|
||||
IReadOnlyList<string> MissingDocIds,
|
||||
int NeededMissing)
|
||||
{
|
||||
/// <summary>A readable saved session.</summary>
|
||||
public const string Present = "present";
|
||||
|
||||
/// <summary>No saved session.</summary>
|
||||
public const string None = "none";
|
||||
|
||||
/// <summary>A file that cannot be read: counts as none.</summary>
|
||||
public const string Unreadable = "unreadable";
|
||||
}
|
||||
|
||||
/// <summary>What the interface knows about the link to Instagram.</summary>
|
||||
@@ -22,12 +64,14 @@ public enum ConnectionState
|
||||
/// <param name="DisplayName">Display name, when known.</param>
|
||||
/// <param name="UserIsDriving">True while Alberto is using the browser (login page, remote view, browser window): the engine is still.</param>
|
||||
/// <param name="CurrentUrl">Address shown in the remote view's address bar, without query string.</param>
|
||||
/// <param name="SavedSession">The saved session (raccolta «richieste»); null when this start keeps none.</param>
|
||||
public sealed record ConnectionStatus(
|
||||
ConnectionState State,
|
||||
string? Username,
|
||||
string? DisplayName,
|
||||
bool UserIsDriving,
|
||||
string? CurrentUrl);
|
||||
string? CurrentUrl,
|
||||
SavedSessionStatus? SavedSession = null);
|
||||
|
||||
/// <summary>Result of «Ho finito» on the Collegamento page.</summary>
|
||||
/// <param name="Connected">True when the session cookie now exists.</param>
|
||||
|
||||
@@ -7,11 +7,12 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
|
||||
|
||||
| Endpoint | Corpo e risposta |
|
||||
|---|---|
|
||||
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` |
|
||||
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"copyMissing"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl, savedSession }` |
|
||||
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) |
|
||||
| `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») |
|
||||
| `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) |
|
||||
| `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) |
|
||||
| `GET /api/connection/settings`, `PUT /api/connection/settings` | `{ incompleteCopy: "sostituisci"\|"tieni-completa" }`: che cosa fa una copia della sessione incompleta (raccolta «richieste»); un altro valore → 400 |
|
||||
| `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale |
|
||||
|
||||
**Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la
|
||||
@@ -27,6 +28,14 @@ di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina
|
||||
|
||||
In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`.
|
||||
|
||||
**Raccolta «richieste»** (issue #36, S4b): `savedSession` è `null` senza sessione salvata in questo avvio («pagine», o
|
||||
nessuna operazione configurata); altrimenti `{ state: "present"|"none"|"unreadable", copiedAt (ms Unix o null), cookies,
|
||||
valuesPresent, valuesExpected, missingValues: [nomi], docIdsPresent, docIdsExpected, missingDocIds: [operazioni],
|
||||
neededMissing }`: solo conteggi e nomi, mai valori. Con il cookie di sessione nel browser ma senza una sessione salvata
|
||||
leggibile lo stato è `copyMissing` («Serve «Ho finito»»): il motore aspetta, e `/api/engine` dice `copyMissing` nel
|
||||
collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows e quando il
|
||||
permesso di guida finisce da solo, sempre prima che la pagina torni al motore.
|
||||
|
||||
L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina
|
||||
Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch`
|
||||
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo).
|
||||
|
||||
@@ -802,6 +802,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento
|
||||
.collega-destra h2.sez{margin-bottom:12px}
|
||||
.collega-destra .avviso{font-size:13.5px;line-height:1.5;padding:13px 16px}
|
||||
.nota-password{background:var(--accento-tinta)}
|
||||
.sessione-salvata{padding:14px 16px;font-size:13.5px;line-height:1.5}
|
||||
.sessione-salvata p{margin:0 0 6px}
|
||||
.sessione-salvata h2.sez{margin-bottom:8px}
|
||||
.sessione-salvata h3.sez{font-size:13.5px;font-weight:650;margin:12px 0 8px}
|
||||
.sessione-salvata .avviso{margin:4px 0 8px}
|
||||
.sessione-salvata .scelte{display:flex;flex-direction:column;gap:10px}
|
||||
.sessione-salvata .scelte .voce{align-items:flex-start}
|
||||
.sessione-salvata .scelte .voce .tondo{margin-top:2px}
|
||||
.sessione-salvata .scelte small{display:block;color:var(--testo-2);font-size:12.5px}
|
||||
.passi-collegamento{list-style:none;margin:0 0 8px;padding:0;display:flex;flex-direction:column;gap:18px}
|
||||
.passi-collegamento li{display:flex;gap:14px}
|
||||
.passi-collegamento .numero{width:24px;height:24px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--accento-tinta);color:var(--accento-scuro);font-weight:650;font-size:12.5px;margin-top:1px}
|
||||
|
||||
@@ -63,7 +63,7 @@ function renderStatus(state) {
|
||||
const s = state.snapshot;
|
||||
const meter = s.profilesOpenedToday;
|
||||
const connection = state.connection;
|
||||
const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato');
|
||||
const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : connection.state === 'copyMissing' ? 'stato.copiaMancante' : 'stato.collegato');
|
||||
// The own account is known only after the first sweep (a verification can come before it): no «@null».
|
||||
const who = connection.state === 'notConnected'
|
||||
? h('div.chi', h('span.av.segnaposto', icon('user', 's')),
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
// the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without
|
||||
// being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di
|
||||
// Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and
|
||||
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still.
|
||||
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. With the raccolta «richieste»
|
||||
// (issue #36, S4b) the page also shows the saved session in counts and names (never values), the choice for an
|
||||
// incomplete copy, and «Serve «Ho finito»» when the browser is connected but the copy is missing.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
@@ -10,10 +12,10 @@ import { h, icon, fill } from '../core/dom.js';
|
||||
import { engineState, refreshEngine } from '../core/engine.js';
|
||||
import { navigate } from '../core/shell.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js';
|
||||
import { avatar, confirmDialog, label, radio, showError, toast } from '../core/ui.js';
|
||||
import { remoteView } from './remote-view.js';
|
||||
|
||||
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' };
|
||||
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', copyMissing: 'ambra', verificationRequired: 'rosso', browserUnavailable: '' };
|
||||
|
||||
/** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */
|
||||
function waitsForResume(state) {
|
||||
@@ -120,6 +122,7 @@ export async function mountConnection(page) {
|
||||
fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || ''));
|
||||
if (status.state === 'connected') drawConnected();
|
||||
else if (status.state === 'browserUnavailable') drawUnavailable();
|
||||
else if (status.state === 'copyMissing') drawLogin({ copyMissing: true });
|
||||
else drawLogin();
|
||||
}
|
||||
|
||||
@@ -145,15 +148,17 @@ export async function mountConnection(page) {
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------- login or verification
|
||||
function drawLogin() {
|
||||
function drawLogin({ copyMissing = false } = {}) {
|
||||
const verification = status.state === 'verificationRequired';
|
||||
// Connected but without the copy for the requests: the start page (the site's home), never the login page.
|
||||
const login = !verification && !copyMissing;
|
||||
waitingResume = false;
|
||||
closeView();
|
||||
lease.begin(!verification);
|
||||
lease.begin(login);
|
||||
if (windows) {
|
||||
fill(left, windowPanel());
|
||||
} else {
|
||||
view = remoteView(page, { url: status.currentUrl, login: !verification });
|
||||
view = remoteView(page, { url: status.currentUrl, login });
|
||||
fill(left, view.element);
|
||||
}
|
||||
const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi');
|
||||
@@ -161,6 +166,8 @@ export async function mountConnection(page) {
|
||||
fill(right,
|
||||
verification
|
||||
? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto')))
|
||||
: copyMissing
|
||||
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', h('b', t('impostazioni.collegamento.copiaMancanteTitolo')), ' ', t('impostazioni.collegamento.copiaMancanteTesto')))
|
||||
: h('div',
|
||||
h('h2.sez', t('impostazioni.collegamento.come')),
|
||||
h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))),
|
||||
@@ -168,6 +175,7 @@ export async function mountConnection(page) {
|
||||
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
|
||||
// Windows: one engine per account (spec §5) said before the login too; Docker keeps mockup 10 as it is.
|
||||
windows ? h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))) : null,
|
||||
copyMissing ? savedSessionBox(status.savedSession, page) : null,
|
||||
message,
|
||||
h('div.molla'),
|
||||
h('div.bottoni-collegamento',
|
||||
@@ -235,7 +243,8 @@ export async function mountConnection(page) {
|
||||
fill(right,
|
||||
passwordNote(windows),
|
||||
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
|
||||
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))));
|
||||
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))),
|
||||
savedSessionBox(status.savedSession, page));
|
||||
}
|
||||
|
||||
async function useBrowser() {
|
||||
@@ -287,6 +296,57 @@ export async function mountConnection(page) {
|
||||
await draw();
|
||||
}
|
||||
|
||||
/**
|
||||
* The saved session of the raccolta «richieste» (issue #36, S4b): when it was copied, the values and doc_id present
|
||||
* and the names of the missing ones — counts and names only, the server never sends a value — and the choice for an
|
||||
* incomplete copy. Nothing without a saved session in this start («pagine»).
|
||||
*/
|
||||
export function savedSessionBox(saved, page) {
|
||||
if (!saved) return null;
|
||||
const k = (key, vars) => t(`impostazioni.collegamento.salvata.${key}`, vars);
|
||||
const lines = [];
|
||||
if (saved.state === 'present') {
|
||||
if (saved.copiedAt) {
|
||||
const when = new Date(saved.copiedAt).toLocaleString('it-IT', { dateStyle: 'medium', timeStyle: 'short' });
|
||||
lines.push(h('p', k('copiata', { quando: when })));
|
||||
}
|
||||
lines.push(h('p.muto', [
|
||||
k('valori', { presenti: String(saved.valuesPresent), attesi: String(saved.valuesExpected) }),
|
||||
k('docId', { presenti: String(saved.docIdsPresent), attesi: String(saved.docIdsExpected) }),
|
||||
k('cookie', { n: String(saved.cookies) }),
|
||||
].join(' ')));
|
||||
const missing = [...(saved.missingValues || []), ...(saved.missingDocIds || [])];
|
||||
if (missing.length) lines.push(h('p', k('mancano', { nomi: missing.join(', ') })));
|
||||
lines.push(saved.neededMissing
|
||||
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', k('servono', { n: String(saved.neededMissing) })))
|
||||
: h('p', k('completa')));
|
||||
} else {
|
||||
lines.push(h('p', k(saved.state === 'unreadable' ? 'illeggibile' : 'nessuna')));
|
||||
}
|
||||
|
||||
const choose = async (value) => {
|
||||
try {
|
||||
await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } });
|
||||
toast(k('salvato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
};
|
||||
const replace = radio({ name: 'copia-incompleta', value: 'sostituisci', checked: true, onchange: choose, labelNode: h('span', h('b', k('sostituisci')), h('small', k('sostituisciAiuto'))) });
|
||||
const keep = radio({ name: 'copia-incompleta', value: 'tieni-completa', onchange: choose, labelNode: h('span', h('b', k('tieni')), h('small', k('tieniAiuto'))) });
|
||||
api('/api/connection/settings', { signal: page && page.signal }).then((settings) => {
|
||||
keep.input.checked = settings.incompleteCopy === 'tieni-completa';
|
||||
replace.input.checked = !keep.input.checked;
|
||||
}).catch(() => {});
|
||||
|
||||
return h('div.pannello.sessione-salvata',
|
||||
h('h2.sez', k('titolo')),
|
||||
...lines,
|
||||
h('p.aiuto.piccolo', k('nota')),
|
||||
h('h3.sez', k('incompleta')),
|
||||
h('div.scelte', { role: 'radiogroup', 'aria-label': k('incompleta') }, replace, keep));
|
||||
}
|
||||
|
||||
/** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */
|
||||
export function passwordNote(windows) {
|
||||
return h('div.avviso.nota-password', icon('shield-check', 's'),
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"nessunAccount": "Nessun account",
|
||||
"verifica": "Verifica richiesta",
|
||||
"scollegato": "Sessione chiusa",
|
||||
"copiaMancante": "Serve «Ho finito»",
|
||||
"accountDaLeggere": "Nome non ancora noto",
|
||||
"nonDisponibile": "Stato del motore non disponibile"
|
||||
},
|
||||
@@ -690,9 +691,31 @@
|
||||
"stati": {
|
||||
"notConnected": "Non collegato",
|
||||
"connected": "Collegato",
|
||||
"copyMissing": "Serve «Ho finito»",
|
||||
"verificationRequired": "Verifica richiesta",
|
||||
"browserUnavailable": "Browser non disponibile"
|
||||
},
|
||||
"copiaMancanteTitolo": "Manca la copia della sessione",
|
||||
"copiaMancanteTesto": "Il browser è collegato, ma Febe non ha ancora una copia della sessione per le richieste (o non riesce a leggerla). Apri la tua pagina iniziale nel browser e premi «Ho finito»: fino ad allora il motore aspetta.",
|
||||
"salvata": {
|
||||
"titolo": "Sessione salvata per le richieste",
|
||||
"copiata": "Copiata {quando}.",
|
||||
"nessuna": "Nessuna copia: premi «Ho finito» sulla tua pagina iniziale.",
|
||||
"illeggibile": "C'è un file, ma Febe non riesce a leggerlo (un'altra chiave o un file rovinato): conta come nessuna copia. Il prossimo «Ho finito» lo sostituisce.",
|
||||
"valori": "Valori della pagina: {presenti} su {attesi}.",
|
||||
"docId": "doc_id: {presenti} su {attesi}.",
|
||||
"cookie": "Cookie: {n}.",
|
||||
"mancano": "Mancano: {nomi}.",
|
||||
"servono": "{n} di questi servono alle richieste configurate: quelle richieste non partono e, alla prima, Febe si ferma come disconnessione.",
|
||||
"completa": "Nulla di ciò che le richieste configurate mandano manca.",
|
||||
"nota": "Qui ci sono solo conteggi e nomi, mai i valori.",
|
||||
"incompleta": "Se una copia nuova è incompleta",
|
||||
"sostituisci": "Sostituisci comunque (consigliato)",
|
||||
"sostituisciAiuto": "La copia nuova prende sempre il posto di quella salvata: una copia più vecchia potrebbe avere i cookie di un altro accesso.",
|
||||
"tieni": "Tieni la copia completa",
|
||||
"tieniAiuto": "Se alla copia nuova manca qualcosa che le richieste usano e quella salvata è completa, Febe tiene quella salvata e te lo dice.",
|
||||
"salvato": "Scelta salvata: vale dalla prossima copia."
|
||||
},
|
||||
"come": "Come collegarti",
|
||||
"passi": [
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user