Instagram: Febe legge le risposte vere (campioni dal HAR del 21/10)
verifica / controlli (push) Successful in 2m10s
verifica / prove (push) Successful in 26m16s
verifica / installatore (push) Successful in 5m39s
verifica / immagine (push) Successful in 28m39s

Febe non estraeva nulla da Instagram per due motivi. Instagram manda i
dati di storie e raccolte (GraphQL) come text/javascript, e la cattura
leggeva solo le risposte dichiarate JSON: le scartava tutte. E i file di
Instagram (lettori, bersagli) erano scheletri, quindi le ricette si
rifiutavano di girare.

Alberto ha mandato un HAR del suo browser e una guida. La guida descrive
richieste costruite a mano, vietate dalle regole 2-4, e un formato che
nel HAR non compare: non si usa. Dal HAR si è letta solo la forma; le
risposte utili sono diventate campioni grezzi fuori dal repository,
ripuliti e verificati con febe-sonda (tests/Febe.Tests/campioni/instagram).

Che cosa cambia:
- la cattura legge le risposte text/javascript chieste dalla pagina (mai
  gli script) e ogni blocco JSON incorporato nel documento della pagina,
  e avvisa quando un corpo atteso non arriverà;
- le risposte che non parlano di contenuti (promozioni, «storia vista»)
  si ignorano invece di valere come formato non riconosciuto;
- lettori.instagram.json è confermato, con sole chiavi presenti nei
  campioni; identificativi delle raccolte nella forma dell'indirizzo;
- bersagli.instagram.json ha le pagine viste nel traffico vero; i
  bersagli restano vuoti (H11): storie, raccolte, Taggati e Reel
  aspettano lo script tools/bersagli/raccogli-bersagli.js;
- le ricette del profilo reggono dati in risposte diverse e prendono la
  paginazione solo dalla risposta che porta i loro post; l'elenco dei
  seguiti scarta i profili suggeriti; «Tu» si riconosce anche dal solo
  identificativo dell'account collegato;
- il visualizzatore delle raccolte conta i contenuti (l'indirizzo non
  cambia), chiede il permesso prima di ogni contenuto e si chiude sempre;
- una ricetta che la configurazione non lascia girare è «Da configurare»:
  non è un guasto, non si sospende, non si pianifica; le sospensioni
  dovute ai file vecchi si azzerano una volta al cambio dei file;
- la barra laterale dice «Collegato» dal cookie di sessione; i «Post
  singolo» per gli indirizzi scaduti non vengono più annullati;
- febe-sonda da-har; la ripulitura tiene latest_reel_media e mette un
  riempitivo neutro sotto le chiavi simili a segreti (gitleaks).

Prove su Windows: 783 superate, 76 saltate (Chromium e Xvfb, nella CI).
Nulla è stato provato contro Instagram. Dettagli e decisioni in
docs/stato.md e docs/decisioni.md (righe del 25 ottobre).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-25 14:22:16 +01:00
1 parent b3a7c31e5a
commit 31bbbf8bb7
69 files changed
+9184 -453

No files matched your search

+3
View File
@@ -24,4 +24,7 @@ public sealed class DeferredRecipeRunner : IRecipeRunner
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
/// <summary>The real runner's answer; before the browser is up nothing is known, and nothing is held back.</summary>
public string? NotConfiguredReason(RecipeKind kind) => _target?.NotConfiguredReason(kind);
}
+35
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Collection;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Engine;
@@ -372,6 +373,7 @@ public sealed class FebeApp : IAsyncDisposable
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
var changes = Web.Services.GetRequiredService<LibraryChanges>();
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
@@ -412,6 +414,39 @@ public sealed class FebeApp : IAsyncDisposable
}
}
/// <summary>
/// Which reader vocabulary and target map the collection uses, in the log: where each came from (embedded in Febe or
/// the copy in the Data folder) and in what state, never what is in them; a warning when a copy in the Data folder
/// hides a better embedded file. Then the engine clears, once, the suspensions and failures of the recipes counted
/// against other files (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Before the engine loop starts.
/// </summary>
private async Task CheckCollectionConfigurationAsync(CollectionPipeline pipeline, EngineHost engine, CancellationToken ct)
{
try
{
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
foreach (var line in configuration.Lines)
{
Log.Info("raccolta", line);
}
foreach (var warning in configuration.Warnings)
{
Log.Warn("raccolta", warning);
}
if (await engine.ApplyCollectionConfigurationAsync(configuration.Fingerprint, ct).ConfigureAwait(false))
{
Log.Info("raccolta", $"Configurazione della raccolta diversa dall'ultimo avvio (impronta {configuration.Fingerprint[..12]}): sospensioni ed errori contati delle ricette azzerati.");
}
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
// Never a reason not to collect: the suspensions stay as they are, «Riattiva» still clears them.
Log.Warn("raccolta", "Non riesco a confrontare la configurazione della raccolta con quella dell'ultimo avvio: le ricette sospese restano come sono.", ex);
}
}
/// <summary>
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
/// the site once, so that its session cookie exists — then back to the rest page.
+182 -78
View File
@@ -19,8 +19,17 @@ public sealed record ResponseTapOptions
/// <summary>How long to wait for one body before giving up on it (one stuck request must not block the others).</summary>
public TimeSpan BodyTimeout { get; init; } = TimeSpan.FromSeconds(15);
/// <summary>Decides from the declared MIME type whether a body is worth parsing as JSON.</summary>
public Func<string, bool> IsJsonMimeType { get; init; } = static mime => mime.Contains("json", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Decides from the declared MIME type and the resource type whether a body is worth parsing as JSON
/// (<see cref="DataResponses.IsData"/>: JSON, and JavaScript the page fetched itself).
/// </summary>
public Func<string, string?, bool> IsDataResponse { get; init; } = DataResponses.IsData;
/// <summary>
/// Whether the main document of a site page is read too, for the JSON blocks it embeds
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>).
/// </summary>
public bool ReadPageDocuments { get; init; } = true;
/// <summary>Per-resource buffer of the browser (<c>Network.enable</c> maxResourceBufferSize).</summary>
public int BrowserResourceBufferBytes { get; init; } = 32 * 1024 * 1024;
@@ -37,22 +46,26 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
/// and the metadata of every response and main-frame navigation to <see cref="IResponseObserver"/>s.
/// </summary>
/// <remarks>
/// It does not filter by address: readers recognise data by its shape (spec §6.4). Bodies stay in memory for the
/// time of the reading, are never written to disk and never logged. Event handlers only queue work; bodies are
/// fetched and parsed on a background worker, one at a time.
/// It does not filter by address: readers recognise data by its shape (spec §6.4). A body is read when the browser
/// declares it as JSON, or as JavaScript fetched by the page (Instagram's GraphQL answers), and the main document of a
/// site page is read for the JSON blocks it embeds, each handed to consumers as an answer of its own with the
/// document's descriptor. Bodies stay in memory for the time of the reading, are never written to disk and never
/// logged. Event handlers only queue work; bodies are fetched and parsed on a background worker, one at a time.
/// </remarks>
public sealed class ResponseTap : IAsyncDisposable
{
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
private readonly ICdpSession _cdp;
private readonly HostClassifier _hosts;
private readonly IClock _clock;
private readonly IBrowserLog _log;
private readonly ResponseTapOptions _options;
private readonly ConcurrentDictionary<string, ResponseDescriptor> _inFlight = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, PendingBody> _inFlight = new(StringComparer.Ordinal);
private readonly Lock _gate = new();
private readonly List<IResponseConsumer> _consumers = [];
private readonly List<IResponseObserver> _observers = [];
private readonly Channel<ResponseDescriptor> _queue = Channel.CreateUnbounded<ResponseDescriptor>(new UnboundedChannelOptions { SingleReader = true });
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
private readonly CancellationTokenSource _lifetime = new();
private readonly List<IDisposable> _subscriptions = [];
private Task? _worker;
@@ -181,7 +194,14 @@ public sealed class ResponseTap : IAsyncDisposable
private void OnReconnected(object? sender, EventArgs e)
{
_inFlight.Clear();
foreach (var key in _inFlight.Keys)
{
if (_inFlight.TryRemove(key, out _))
{
NotifyDropped(key);
}
}
_ = Task.Run(async () =>
{
try
@@ -240,16 +260,21 @@ public sealed class ResponseTap : IAsyncDisposable
}
}
if (_options.IsJsonMimeType(mime) && status is >= 200 and < 600 && status != 204)
if (_options.IsDataResponse(mime, type) && status is >= 200 and < 600 && status != 204)
{
_inFlight[requestId] = descriptor;
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: false);
}
else if (_options.ReadPageDocuments && descriptor.HostKind == HostKind.Site && status is >= 200 and < 300
&& DataResponses.IsPageDocument(mime, isMainDocument))
{
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: true);
}
}
private void OnLoadingFinished(JsonElement p)
{
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|| !_inFlight.TryRemove(requestId, out var descriptor))
|| !_inFlight.TryRemove(requestId, out var pending))
{
return;
}
@@ -258,17 +283,19 @@ public sealed class ResponseTap : IAsyncDisposable
if (length > _options.MaxBodyBytes)
{
Interlocked.Increment(ref _skipped);
NotifyDropped(requestId);
return;
}
_queue.Writer.TryWrite(descriptor);
_queue.Writer.TryWrite(pending);
}
private void OnLoadingFailed(JsonElement p)
{
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId)
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
&& _inFlight.TryRemove(requestId, out _))
{
_inFlight.TryRemove(requestId, out _);
NotifyDropped(requestId);
}
}
@@ -284,8 +311,16 @@ public sealed class ResponseTap : IAsyncDisposable
_mainFrameId = frame.TryGetProperty("id", out var id) ? id.GetString() : _mainFrameId;
// Requests of the previous document that never finished (e.g. a body the page did not read: Chromium then
// sends no loadingFinished) will not finish any more: forget them.
_inFlight.Clear();
// sends no loadingFinished) will not finish any more: forget them. The new document itself is kept: the frame
// commits it before its body has finished loading (its request id is the frame's loader id).
var loader = frame.TryGetProperty("loaderId", out var l) ? l.GetString() : null;
foreach (var key in _inFlight.Keys)
{
if (key != loader && _inFlight.TryRemove(key, out _))
{
NotifyDropped(key);
}
}
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
}
@@ -325,64 +360,128 @@ public sealed class ResponseTap : IAsyncDisposable
private async Task WorkAsync(CancellationToken ct)
{
await foreach (var descriptor in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
try
{
IResponseConsumer[] consumers;
lock (_gate)
await foreach (var pending in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
{
consumers = [.. _consumers];
try
{
await HandleAsync(pending, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// One unexpected body must not stop the capture of the following ones. Only the type: the message
// of a parsing error may quote the body.
_log.Warn($"Cattura: errore imprevisto nella lettura di una risposta ({ex.GetType().Name}).");
NotifyDropped(pending.Descriptor.RequestId);
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
}
if (consumers.Length == 0)
/// <summary>Fetches one body and hands it to the consumers; tells the observers once when nothing reached them.</summary>
private async Task HandleAsync(PendingBody pending, CancellationToken ct)
{
var descriptor = pending.Descriptor;
IResponseConsumer[] consumers;
lock (_gate)
{
consumers = [.. _consumers];
}
if (consumers.Length == 0)
{
NotifyDropped(descriptor.RequestId);
return;
}
byte[]? bytes;
try
{
bytes = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
{
// The body may already be evicted from the browser's buffer, or the page navigated away.
Interlocked.Increment(ref _bodyErrors);
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
NotifyDropped(descriptor.RequestId);
return;
}
var delivered = bytes is null ? 0
: pending.IsPageDocument ? await ConsumeDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
: await ConsumeBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
if (delivered == 0)
{
NotifyDropped(descriptor.RequestId);
}
}
/// <summary>The body of a data response, as one answer. Returns how many answers reached the consumers (0 or 1).</summary>
private async Task<int> ConsumeBodyAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
{
JsonDocument document;
try
{
document = JsonDocument.Parse(bytes, BodyOptions);
}
catch (JsonException)
{
// Not JSON after all (e.g. Instagram's «for (;;);» answers of /ajax/, which carry no contents): skipped.
Interlocked.Increment(ref _parseErrors);
return 0;
}
using (document)
{
await DeliverAsync(descriptor, document, consumers, ct).ConfigureAwait(false);
return 1;
}
}
/// <summary>
/// The JSON blocks a page document embeds, each handed to the consumers as an answer of its own with the document's
/// descriptor, so that a pagination stays with the block that carries it
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). One block at a time: each is disposed before the next is parsed.
/// Returns how many blocks reached the consumers; a document without any is not data, and not a parse error.
/// </summary>
private async Task<int> ConsumeDocumentAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
{
var delivered = 0;
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)))
{
using (block)
{
continue;
delivered++;
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
}
}
JsonDocument? document;
return delivered;
}
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IResponseConsumer[] consumers, CancellationToken ct)
{
Interlocked.Increment(ref _jsonBodies);
foreach (var consumer in consumers)
{
try
{
document = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
{
// The body may already be evicted from the browser's buffer, or the page navigated away.
Interlocked.Increment(ref _bodyErrors);
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
continue;
}
if (document is null)
{
continue;
}
using (document)
{
Interlocked.Increment(ref _jsonBodies);
foreach (var consumer in consumers)
{
try
{
await consumer.ConsumeAsync(descriptor, document, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
}
}
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
}
}
}
private async Task<JsonDocument?> FetchBodyAsync(string requestId, CancellationToken ct)
/// <summary>The decoded bytes of a body, or null when the browser gives none or it cannot be decoded.</summary>
private async Task<byte[]?> FetchBodyAsync(string requestId, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(_options.BodyTimeout);
@@ -402,34 +501,39 @@ public sealed class ResponseTap : IAsyncDisposable
}
var encoded = result.TryGetProperty("base64Encoded", out var b) && b.ValueKind == JsonValueKind.True;
byte[] bytes;
if (encoded)
if (!encoded)
{
if (!body.TryGetBytesFromBase64(out var decoded))
{
Interlocked.Increment(ref _parseErrors);
return null;
}
bytes = decoded;
}
else
{
bytes = Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
return Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
}
try
if (!body.TryGetBytesFromBase64(out var decoded))
{
return JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 256 });
}
catch (JsonException)
{
// Declared as JSON but it is not (or has a prefix): readers will be told by the probe in M0.
Interlocked.Increment(ref _parseErrors);
return null;
}
return decoded;
}
/// <summary>Tells the observers that a body they may be waiting for will not come.</summary>
private void NotifyDropped(string requestId)
{
foreach (var observer in SnapshotObservers())
{
try
{
observer.OnBodyDropped(requestId);
}
catch (Exception ex)
{
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
}
}
}
/// <summary>A body to fetch once its loading has finished.</summary>
private sealed record PendingBody(ResponseDescriptor Descriptor, bool IsPageDocument);
private IResponseObserver[] SnapshotObservers()
{
lock (_gate)
@@ -23,8 +23,8 @@ namespace Febe.Browser.Recipes;
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
{
/// <summary>
/// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and
/// says why, without touching the site.
/// Instagram. Its reader vocabulary is confirmed on real cleaned samples and its map has the pages seen in real
/// traffic, not yet the targets: a recipe that needs a target refuses to run and says why, without touching the site.
/// </summary>
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
@@ -0,0 +1,194 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Engine;
namespace Febe.Core.Collection;
/// <summary>One configuration file of the collection as it was loaded.</summary>
/// <param name="Name">File name: <c>lettori.instagram.json</c>, <c>bersagli.instagram.json</c>.</param>
/// <param name="OverridePath">The editable copy in the Data folder that was loaded; null for the copy embedded in Febe.</param>
/// <param name="Text">Its content (for the fingerprint only: never logged).</param>
public sealed record CollectionConfigurationFile(string Name, string? OverridePath, string Text)
{
public bool IsOverride => OverridePath is not null;
/// <summary>Where it came from, in Italian, for the log: never what is in it.</summary>
public string Origin => OverridePath is { } path
? $"la copia nella cartella dei dati ({path})"
: $"il file incorporato in Febe ({Name})";
}
/// <summary>
/// The reader vocabulary and target map one site runs on, as the collection pipeline loaded them: where each came from
/// (the copy embedded in Febe, or an editable copy in the Data folder, which always wins), its state, the recipes they
/// leave unable to run, and a fingerprint of their content. The engine clears the suspensions of the recipes when the
/// fingerprint changes (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Nothing here comes from the site.
/// </summary>
public sealed class CollectionConfiguration
{
private CollectionConfiguration(
string site,
ReaderVocabulary vocabulary,
SiteMap map,
CollectionConfigurationFile vocabularyFile,
CollectionConfigurationFile mapFile,
ReaderVocabulary? embeddedVocabulary,
SiteMap? embeddedMap)
{
Site = site;
Vocabulary = vocabulary;
Map = map;
VocabularyFile = vocabularyFile;
MapFile = mapFile;
EmbeddedVocabulary = embeddedVocabulary;
EmbeddedMap = embeddedMap;
Blocked = BlockedBy(map, vocabulary);
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
}
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
public string Site { get; }
public ReaderVocabulary Vocabulary { get; }
public SiteMap Map { get; }
public CollectionConfigurationFile VocabularyFile { get; }
public CollectionConfigurationFile MapFile { get; }
/// <summary>The vocabulary embedded in Febe, when there is one (the same as <see cref="Vocabulary"/> without a copy).</summary>
public ReaderVocabulary? EmbeddedVocabulary { get; }
/// <summary>The map embedded in Febe, when there is one (the same as <see cref="Map"/> without a copy).</summary>
public SiteMap? EmbeddedMap { get; }
/// <summary>Recipes these files do not let run (<see cref="RecipeStatus.NotConfigured"/>), in the order of <see cref="RecipeKind"/>.</summary>
public IReadOnlyList<RecipeKind> Blocked { get; }
/// <summary>SHA-256 of the two files as loaded (lower-case hexadecimal), line endings aside.</summary>
public string Fingerprint { get; }
/// <summary>What the log says at start-up: where each file came from and in what state, and what cannot run.</summary>
public IReadOnlyList<string> Lines
{
get
{
var all = Enum.GetValues<RecipeKind>().Length;
var vocabularyState = Vocabulary.Status == VocabularyStatus.Confirmed ? "confermato" : "ipotesi";
if (Vocabulary.MissingConcepts.Count > 0)
{
vocabularyState += $", {Vocabulary.MissingConcepts.Count.ToString(CultureInfo.InvariantCulture)} concetti ancora senza chiavi";
}
var missing = Map.Missing(SitePages.All, SiteTargets.All).Count;
var mapState = missing == 0 ? "tutte le voci compilate" : $"{missing.ToString(CultureInfo.InvariantCulture)} voci vuote o assenti";
return
[
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
Blocked.Count == 0
? "Con questa configurazione tutte le ricette possono girare."
: $"Con questa configurazione non possono girare {Blocked.Count.ToString(CultureInfo.InvariantCulture)} ricette su {all.ToString(CultureInfo.InvariantCulture)}: {Names(Blocked)}.",
];
}
}
/// <summary>
/// A copy in the Data folder that hides a better embedded file: a vocabulary still «ipotesi» while the embedded one
/// is «confermato», or a map that leaves recipes unable to run that the embedded one lets run. A stale copy would
/// otherwise keep the new files of an update from ever being used.
/// </summary>
public IReadOnlyList<string> Warnings
{
get
{
var warnings = new List<string>();
if (VocabularyFile.IsOverride && EmbeddedVocabulary is { } embedded
&& Vocabulary.Status == VocabularyStatus.Hypothesis && embedded.Status == VocabularyStatus.Confirmed)
{
warnings.Add($"Il vocabolario dei lettori in {VocabularyFile.OverridePath} è ancora un'ipotesi, mentre quello incorporato in Febe è confermato: la copia nella cartella dei dati nasconde quello nuovo. Toglila (o aggiornala) e riavvia Febe.");
}
if (MapFile.IsOverride && EmbeddedMap is { } embeddedMap)
{
var hidden = MissingFrom(Map).Except(MissingFrom(embeddedMap)).ToList();
if (hidden.Count > 0)
{
warnings.Add($"La mappa dei bersagli in {MapFile.OverridePath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare ({Names(hidden)}): la copia nella cartella dei dati nasconde quella nuova. Toglila (o aggiornala) e riavvia Febe.");
}
}
return warnings;
}
}
/// <summary>
/// Describes what was loaded for <paramref name="site"/>: <paramref name="vocabulary"/> and <paramref name="map"/>
/// as the pipeline loaded them (their <c>Source</c> tells a Data-folder copy from the embedded file). The text of a
/// copy is read again from its path for the fingerprint.
/// </summary>
/// <exception cref="IOException">A copy in the Data folder cannot be read any more.</exception>
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map)
{
ArgumentException.ThrowIfNullOrWhiteSpace(site);
ArgumentNullException.ThrowIfNull(vocabulary);
ArgumentNullException.ThrowIfNull(map);
var vocabularyFile = LoadedFile($"lettori.{site}.json", vocabulary.Source);
var mapFile = LoadedFile($"bersagli.{site}.json", map.Source);
var embeddedVocabulary = vocabularyFile.IsOverride ? Try(() => ReaderVocabulary.LoadEmbedded(vocabularyFile.Name)) : vocabulary;
var embeddedMap = mapFile.IsOverride ? Try(() => SiteMap.LoadEmbedded(mapFile.Name)) : map;
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap);
}
/// <summary>The recipes a map and a vocabulary do not let run, by the same rule as the runner's.</summary>
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary)
{
ArgumentNullException.ThrowIfNull(map);
ArgumentNullException.ThrowIfNull(vocabulary);
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
}
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
private static RecipeKind[] MissingFrom(SiteMap map) =>
[.. Enum.GetValues<RecipeKind>().Where(kind =>
{
var (pages, targets) = RecipeRunner.Requirements(kind);
return map.Missing(pages, targets).Count > 0;
})];
private static CollectionConfigurationFile LoadedFile(string name, string? source)
{
if (source is { Length: > 0 } path && !string.Equals(path, name, StringComparison.Ordinal))
{
return new CollectionConfigurationFile(name, path, File.ReadAllText(path));
}
return new CollectionConfigurationFile(name, null, SiteMap.ReadEmbeddedText(name));
}
private static T? Try<T>(Func<T> load)
where T : class
{
try
{
return load();
}
catch (Exception ex) when (ex is FileNotFoundException or InvalidDataException)
{
return null;
}
}
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
{
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
}
private static string Names(IEnumerable<RecipeKind> kinds) => string.Join(", ", kinds.Select(RecipeRunner.Name));
}
+106
View File
@@ -0,0 +1,106 @@
using System.Text.Json;
using System.Text.RegularExpressions;
namespace Febe.Core.Collection;
/// <summary>
/// Which responses of the page carry data worth reading (spec §6.2), decided from what the browser declares about
/// them, never from the address.
/// </summary>
/// <remarks>
/// Instagram serves its GraphQL data (<c>/graphql/query</c>, <c>/api/graphql</c>) as <c>text/javascript</c>, and only
/// the REST answers (<c>/api/v1/...</c>) as <c>application/json</c> (HAR of Alberto's browser, 21 October 2026). A
/// JavaScript type counts only when the page itself fetched it (XHR, Fetch): script files are never parsed.
/// </remarks>
public static partial class DataResponses
{
/// <summary>Largest page document whose embedded data is read.</summary>
public const int MaxDocumentChars = 16 * 1024 * 1024;
private static readonly JsonDocumentOptions BlockOptions = new() { MaxDepth = 256 };
/// <summary>True for a body worth parsing as JSON data.</summary>
/// <param name="mimeType">Declared MIME type, without parameters.</param>
/// <param name="resourceType">Browser resource type (Document, XHR, Fetch, Script...), when known.</param>
public static bool IsData(string mimeType, string? resourceType)
{
ArgumentNullException.ThrowIfNull(mimeType);
if (mimeType.Contains("json", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return mimeType.Contains("javascript", StringComparison.OrdinalIgnoreCase)
&& resourceType is not null
&& (resourceType.Equals("XHR", StringComparison.OrdinalIgnoreCase) || resourceType.Equals("Fetch", StringComparison.OrdinalIgnoreCase));
}
/// <summary>True for an HTML document of the main frame: the data it embeds is read too (<see cref="EmbeddedJsonBlocks"/>).</summary>
public static bool IsPageDocument(string mimeType, bool isMainFrameDocument) =>
isMainFrameDocument && mimeType.Equals("text/html", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// The JSON blocks a page embeds in <c>&lt;script type="application/json"&gt;</c> elements, one parsed document per
/// block, in document order; none when there is none. Blocks that are not valid JSON are left out.
/// </summary>
/// <remarks>
/// Single-page sites put the data of the first screen in the document itself and fetch only the following pages:
/// without this, the first page of a profile opened by address would arrive «empty». The reader recognizes the data by
/// shape wherever it sits inside a block (spec §6.4).
/// <para>
/// Every block is an answer of its own and is read on its own, like a response: joined to the others, the
/// pagination of one block (collections that say «has_next_page» of themselves, a post that says
/// «more_available: false» of itself) would end up on the items of another and end a walk early. The blocks are
/// parsed lazily, one per step of the enumeration: the caller disposes each before taking the next, so a large
/// document never has all its blocks in memory at once.
/// </para>
/// </remarks>
public static IEnumerable<JsonDocument> EmbeddedJsonBlocks(string html)
{
ArgumentNullException.ThrowIfNull(html);
return html.Length > MaxDocumentChars ? [] : Blocks(html);
}
private static IEnumerable<JsonDocument> Blocks(string html)
{
for (var match = NextBlock(html, previous: null); match is not null; match = NextBlock(html, match))
{
var body = match.Groups["body"];
if (TryParse(html.AsMemory(body.Index, body.Length)) is { } block)
{
yield return block;
}
}
}
/// <summary>The block element after <paramref name="previous"/> (the first one when null), or null at the end.</summary>
private static Match? NextBlock(string html, Match? previous)
{
try
{
var match = previous is null ? JsonScript().Match(html) : previous.NextMatch();
return match.Success ? match : null;
}
catch (RegexMatchTimeoutException)
{
// A pathological document: the blocks found so far have been given, the rest is left out.
return null;
}
}
private static JsonDocument? TryParse(ReadOnlyMemory<char> text)
{
try
{
return JsonDocument.Parse(text, BlockOptions);
}
catch (Exception ex) when (ex is JsonException or ArgumentException)
{
// Not JSON, or too deep; ArgumentException: text that is not valid UTF-16 (a lone surrogate). Left out.
return null;
}
}
[GeneratedRegex("""<script\b[^>]*?\btype\s*=\s*["']?application/json["']?[^>]*>(?<body>.*?)</script\s*>""", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 5000)]
private static partial Regex JsonScript();
}
+3 -2
View File
@@ -73,8 +73,9 @@ public sealed class HostClassifier
}
/// <summary>
/// Instagram's public host names: the site and the two CDN families its pages load files from.
/// Public knowledge, not response formats; still to be confirmed by the M0 probe.
/// Instagram's public host names: the site and the two CDN families its pages load files from. In the HAR of
/// 21 October 2026 the data came from www.instagram.com (logging from graph.instagram.com), the video files from
/// scontent-*.cdninstagram.com and the scripts from static.cdninstagram.com; fbcdn.net is public knowledge.
/// </summary>
public static HostClassifier Instagram { get; } = new(
["instagram.com"],
@@ -69,4 +69,13 @@ public interface IResponseObserver
void OnResponse(ResponseDescriptor response);
void OnNavigation(NavigationDescriptor navigation);
/// <summary>
/// The body of a data response announced by <see cref="OnResponse"/> will not reach the consumers: it failed to
/// load, was too large, was not JSON after all (Instagram's «for (;;);» answers), or the page moved on. Observers
/// that wait for bodies stop waiting for this one.
/// </summary>
void OnBodyDropped(string requestId)
{
}
}
@@ -127,6 +127,12 @@ public enum ReadShape
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
Unrecognized,
/// <summary>
/// Nothing the vocabulary speaks about: none of its relevance keys appears anywhere (promotions, logging, a search
/// box). Ignored: neither data, nor an empty page, nor an unknown shape (<see cref="ReaderVocabulary.Relevance"/>).
/// </summary>
Unrelated,
}
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
@@ -146,6 +152,12 @@ public sealed record ReadResult
public ProfileInfo? Viewer { get; init; }
/// <summary>
/// Identifier of the connected account, also when the answer describes it with nothing else (Instagram's
/// <c>xdt_viewer.user</c>): a profile with this identifier in another answer is the connected account (H10).
/// </summary>
public string? ViewerId { get; init; }
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
public string? KeyStructure { get; init; }
}
@@ -185,6 +185,15 @@ public sealed record ReaderVocabulary
/// <summary>The key under which the response describes the connected account (H10).</summary>
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
/// <summary>
/// Keys at least one of which, anywhere in a response, makes it «about contents or profiles». A response that has
/// none of them is <see cref="ReadShape.Unrelated"/> and ignored, instead of counting as an unknown shape: a real site
/// sends many JSON answers that have nothing to do with contents (Instagram: promotions, logging, «seen» marks).
/// Plain key names, not paths. Empty: every response counts (the test site, where any unknown answer is a format
/// change).
/// </summary>
public IReadOnlyList<string> Relevance { get; init; } = [];
/// <summary>
/// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is
/// a hypothesis, recipes refuse to run on the site.
@@ -319,6 +328,7 @@ public sealed record ReaderVocabulary
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
Viewer = K(file.Viewer),
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
};
}
}
@@ -342,6 +352,15 @@ internal sealed class VocabularyFile
public PageDto? Page { get; set; }
public List<string>? Viewer { get; set; }
public RelevanceDto? Relevance { get; set; }
}
internal sealed class RelevanceDto
{
public string? Note { get; set; }
public List<string>? Keys { get; set; }
}
internal sealed class ContentDto
@@ -20,10 +20,12 @@ public sealed class ShapeReader
private const int MaxDepth = 64;
private readonly ReaderVocabulary _v;
private readonly HashSet<string> _relevance;
public ShapeReader(ReaderVocabulary vocabulary)
{
_v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary));
_relevance = new HashSet<string>(vocabulary.Relevance, StringComparer.Ordinal);
}
public ReaderVocabulary Vocabulary => _v;
@@ -34,6 +36,12 @@ public sealed class ShapeReader
var walk = new Walk();
Visit(root, walk, owner: null, highlightId: null, depth: 0);
if (walk.ViewerId is { } viewerId && walk.Profiles.TryGetValue(viewerId, out var own))
{
// The connected account described by its identifier only, and its profile elsewhere in the same answer.
walk.Profiles[viewerId] = own with { IsViewer = true };
}
var profiles = walk.Profiles.Values.ToList();
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
@@ -46,12 +54,18 @@ public sealed class ShapeReader
Highlights = walk.Highlights,
Page = walk.Page,
Viewer = viewer,
ViewerId = viewer?.Id ?? walk.ViewerId,
};
}
if (IsEmptyShape(root, walk.Page is not null))
{
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page };
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page, ViewerId = walk.ViewerId };
}
if (_relevance.Count > 0 && !HasAnyKey(root, 0))
{
return new ReadResult { Shape = ReadShape.Unrelated, ViewerId = walk.ViewerId };
}
return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) };
@@ -93,9 +107,18 @@ public sealed class ShapeReader
_v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null);
}
if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer)
if (_v.Viewer.TryGet(node, out var viewerNode))
{
walk.AddProfile(viewer with { IsViewer = true });
if (ReadProfile(viewerNode) is { } viewer)
{
walk.AddProfile(viewer with { IsViewer = true });
}
else if (viewerNode.ValueKind == JsonValueKind.Object)
{
// Instagram describes the connected account with its identifier only (xdt_viewer.user): kept, so a
// profile with the same identifier can be recognized as the connected account (H10).
walk.ViewerId ??= AsText(Get(_v.Profile.Id, viewerNode));
}
}
if (IsContent(node))
@@ -116,7 +139,7 @@ public sealed class ShapeReader
walk.AddProfile(highlightOwner);
}
var id = AsText(Get(_v.Highlight.Id, node))!;
var id = HighlightId(AsText(Get(_v.Highlight.Id, node))!);
var before = walk.Contents.Count;
if (_v.Highlight.Items.TryGet(node, out var items))
{
@@ -160,8 +183,26 @@ public sealed class ShapeReader
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
/// <summary>
/// A highlight collection: identifier and title, and — when the vocabulary names them — an owner or its items, so
/// that any other object with an «id» and a «title» (a promotion, a section of a page) is not taken for one.
/// </summary>
private bool IsHighlight(JsonElement node) =>
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null;
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null
&& ((!_v.Highlight.Owner.IsSet && !_v.Highlight.Items.IsSet) || _v.Highlight.Owner.Has(node) || _v.Highlight.Items.Has(node));
/// <summary>
/// The identifier of a collection as its address carries it: Instagram writes «highlight:17841…» in the data and
/// «/stories/highlights/17841…/» in the address (HAR of 21/10/2026), so a «kind:» prefix made of letters is dropped.
/// </summary>
internal static string HighlightId(string id)
{
var colon = id.IndexOf(':', StringComparison.Ordinal);
return colon > 0 && colon < id.Length - 1 && id.AsSpan(0, colon).IndexOfAnyExcept(Letters) < 0 ? id[(colon + 1)..] : id;
}
private static readonly System.Buffers.SearchValues<char> Letters =
System.Buffers.SearchValues.Create("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_");
private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId)
{
@@ -322,6 +363,41 @@ public sealed class ShapeReader
};
}
/// <summary>True when one of the relevance keys of the vocabulary is a property name anywhere under <paramref name="element"/>.</summary>
private bool HasAnyKey(JsonElement element, int depth)
{
if (depth > MaxDepth)
{
return false;
}
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
if (_relevance.Contains(property.Name) || HasAnyKey(property.Value, depth + 1))
{
return true;
}
}
return false;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
if (HasAnyKey(item, depth + 1))
{
return true;
}
}
return false;
default:
return false;
}
}
/// <summary>
/// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top
/// (a bare status or error). Anything richer that nothing recognized is an unknown shape.
@@ -464,6 +540,9 @@ public sealed class ShapeReader
public PageInfo? Page { get; set; }
/// <summary>Identifier of the connected account when the answer gives no more than that.</summary>
public string? ViewerId { get; set; }
/// <summary>Merges what different parts of a response say about the same profile.</summary>
public void AddProfile(ProfileInfo profile)
{
@@ -29,6 +29,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
private readonly List<CapturedRead> _reads = [];
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
private long _sequence;
private string? _viewerId;
public CaptureCollector(ShapeReader reader, IClock clock)
{
@@ -41,6 +42,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
/// <summary>How long a data response may stay «on its way» before it is forgotten (its body may never come).</summary>
public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15);
/// <summary>
/// Identifier of the connected account in the latest site answer that gave one (<see cref="ReadResult.ViewerId"/>),
/// also an answer that is otherwise <see cref="ReadShape.Unrelated"/> and not kept.
/// </summary>
public string? ViewerId
{
get
{
lock (_gate)
{
return _viewerId;
}
}
}
/// <summary>Sequence number of the last read: pass it to <see cref="Since"/> to get what arrives after now.</summary>
public long Mark()
{
@@ -135,7 +151,10 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
return ValueTask.CompletedTask;
}
/// <summary>Reads one body (also used by tests and the probe samples).</summary>
/// <summary>
/// Reads one body (also used by tests and the probe samples). Returns null, and keeps nothing, for responses that
/// are not the site's or that are <see cref="ReadShape.Unrelated"/>.
/// </summary>
public CapturedRead? Accept(ResponseDescriptor response, JsonElement body)
{
ArgumentNullException.ThrowIfNull(response);
@@ -150,6 +169,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
}
var result = _reader.Read(body);
if (result.ViewerId is { } viewerId)
{
lock (_gate)
{
_viewerId = viewerId;
}
}
if (result.Shape == ReadShape.Unrelated)
{
// Not about contents (promotions, logging): neither data nor an empty page, and not «something new
// arrived» for SettleAsync, or a page that keeps logging would never look settled.
return null;
}
lock (_gate)
{
var read = new CapturedRead(++_sequence, response, result);
@@ -166,7 +200,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
void IResponseObserver.OnResponse(ResponseDescriptor response)
{
if (response.HostKind == HostKind.Site
&& response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase)
&& DataResponses.IsData(response.MimeType, response.ResourceType)
&& response.Status is >= 200 and < 600 && response.Status != 204)
{
lock (_gate)
@@ -176,6 +210,14 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
}
}
void IResponseObserver.OnBodyDropped(string requestId)
{
lock (_gate)
{
_pending.Remove(requestId);
}
}
void IResponseObserver.OnNavigation(NavigationDescriptor navigation)
{
if (!navigation.SameDocument)
@@ -1,5 +1,6 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
@@ -98,8 +99,12 @@ public sealed partial class RecipeRunner
await run.OpenAsync(
byPage ? SitePages.FollowingFrom : SitePages.Following,
byPage ? Values(("username", mine.Username), ("cursor", stored!)) : Values(("username", mine.Username))).ConfigureAwait(false);
var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => r.Profiles.Count > 0, null))
// Only followed profiles say the list came: the page also receives suggested profiles (not followed) and
// Alberto's own profile, which would pass for a list that is not there.
bool Listed(ReadResult r) => r.Profiles.Any(p => IsListed(p, mine));
var reads = await WaitAndSettleAsync(run, mark, Listed).ConfigureAwait(false);
if (!run.Judge(reads, Listed, null))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
@@ -109,7 +114,9 @@ public sealed partial class RecipeRunner
while (true)
{
read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false);
var page = LastPage(reads);
// The pagination of the list, never that of another answer (the suggestions, a post, the collections).
var page = PageOf(reads, r => r.Profiles.Where(p => IsListed(p, mine)).Select(p => p.Id), r => r.Shape == ReadShape.Empty);
if (catchingUp && ((page?.Cursor is { } c && string.Equals(c, stored, StringComparison.Ordinal)) || read >= readBefore))
{
catchingUp = false; // back where the last run stopped
@@ -133,7 +140,7 @@ public sealed partial class RecipeRunner
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
var counted = !catchingUp;
reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false);
reads = await ScrollForPageAsync(run, Listed).ConfigureAwait(false);
if (counted)
{
pages++;
@@ -175,12 +182,20 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.Completed, progress);
}
/// <summary>
/// A profile of the following list: not Alberto himself, and not one the answer says he does not follow (Instagram
/// sends suggested profiles with «friendship_status.following: false», HAR of 21/10/2026). A profile that does not
/// say is taken as listed: it came with the list.
/// </summary>
private static bool IsListed(ProfileInfo profile, Account mine) =>
profile.IsFollowed != false && !profile.IsViewer && profile.Id != mine.InstagramId;
/// <summary>Stores one page of the following list in reading order; renamed followed accounts are recognized.</summary>
private async Task<int> SaveFollowingPageAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, Account mine, int offset)
{
var now = Env.Clock.Now;
var seen = new HashSet<string>(StringComparer.Ordinal);
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => !p.IsViewer && p.Id != mine.InstagramId && seen.Add(p.Id)).ToList();
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => IsListed(p, mine) && seen.Add(p.Id)).ToList();
var records = new List<FollowingRecord>(profiles.Count);
for (var i = 0; i < profiles.Count; i++)
{
@@ -122,6 +122,13 @@ public sealed partial class RecipeRunner
/// <summary>Items already saved by the caller (they are not saved again).</summary>
public HashSet<string> Processed { get; init; } = new(StringComparer.Ordinal);
/// <summary>
/// The reads the walk starts from answer a gesture of the walk itself (a resume page, a tab): a bare empty answer
/// among them is its empty page. After opening the profile it is not: an empty answer there may be about
/// something else (the collections of an account that has none).
/// </summary>
public bool StartsFromOwnAnswer { get; init; }
}
/// <summary>
@@ -134,9 +141,9 @@ public sealed partial class RecipeRunner
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
var (current, reads) = await OpenProfileAsync(run, account, waitForGrid: true).ConfigureAwait(false);
account = current;
var profile = FindProfile(reads, account)!;
var profile = AccountProfile(reads, account)!;
if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)
&& account.ContentTypes.HasFlag(ContentTypes.Stories))
@@ -174,7 +181,7 @@ public sealed partial class RecipeRunner
}
}
var page = LastPage(reads);
var page = WalkPage(reads, account, walk, ownAnswer: false);
if (!sawKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
{
if (page?.HasMore == true && page.Cursor is { } cursor)
@@ -218,7 +225,7 @@ public sealed partial class RecipeRunner
var before = ParseTime(await settings.GetAsync(keys[2], run.Ct).ConfigureAwait(false));
async Task ClearAsync() => await settings.SetManyAsync(keys.ToDictionary(k => k, _ => (string?)null), run.Ct).ConfigureAwait(false);
if (LastPage(reads)?.HasMore == false)
if (WalkPage(reads, account, walk, ownAnswer: false)?.HasMore == false)
{
if (stored is not null || before is not null)
{
@@ -234,6 +241,7 @@ public sealed partial class RecipeRunner
IReadOnlyList<CapturedRead> start = reads;
ResumePoint? catchUpTo = null;
var pages = 0;
var ownStart = false;
if (!tailIsNew)
{
if (stored is null)
@@ -246,13 +254,14 @@ public sealed partial class RecipeRunner
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
start = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(start, r => r.Contents.Count > 0 || r.Page is not null, null))
start = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
if (!run.Judge(start, r => IsWalkPage(r, account, walk), null))
{
return; // an empty page, counted: the gap stays for the next check
}
pages = 1;
ownStart = true;
}
else
{
@@ -266,6 +275,7 @@ public sealed partial class RecipeRunner
{
CatchUpTo = catchUpTo,
PagesRead = pages,
StartsFromOwnAnswer = ownStart,
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
CheckDownloads = true,
@@ -345,14 +355,15 @@ public sealed partial class RecipeRunner
IReadOnlyList<CapturedRead> reads;
var pages = 0;
ResumePoint? catchUpTo = null;
var ownStart = true; // a resume page or a tab; not the profile as opened
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
{
// Resume where the last run stopped: the page of the site that starts after the stored point.
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
@@ -361,15 +372,16 @@ public sealed partial class RecipeRunner
}
else
{
(account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
(account, reads) = await OpenProfileAsync(run, account, waitForGrid: walk.IsGrid).ConfigureAwait(false);
ownStart = walk.TabTarget is not null;
if (walk.TabTarget is { } tab)
{
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.ClickAsync(tab, parameters).ConfigureAwait(false);
await Env.Driver.WaitAfterLoadAsync(run.Ct).ConfigureAwait(false);
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, null))
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), null))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
@@ -387,6 +399,7 @@ public sealed partial class RecipeRunner
{
CatchUpTo = catchUpTo,
PagesRead = pages,
StartsFromOwnAnswer = ownStart,
MaxPages = maxPages,
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
CheckDownloads = !checkOnly,
@@ -441,10 +454,12 @@ public sealed partial class RecipeRunner
var pending = rules.CatchUpTo;
var pages = rules.PagesRead;
var catchUp = 0;
var ownAnswer = rules.StartsFromOwnAnswer;
IReadOnlySet<string>? seen = null; // the first page: only what its own answers bring
while (true)
{
var items = PageItems(reads, account, walk);
var page = LastPage(reads);
var page = WalkPage(reads, account, walk, ownAnswer, seen);
if (pending is not null && pending.IsReachedBy(page, items, i => walk.IsChronological && !IsPinned(i, items, walk)))
{
pending = null; // this page holds the stored point: from here on the walk goes on as usual
@@ -483,7 +498,13 @@ public sealed partial class RecipeRunner
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var counted = pending is null;
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
// Only items of the walk not read yet say the next page came: an answer about something else that arrives
// meanwhile (a post of another account, the collections), or one that brings again a post already read
// (the page of that post), neither counts as it nor ends the walk with its pagination.
reads = await ScrollForPageAsync(run, r => r.Contents.Any(c => IsWalkItem(c, account, walk) && !rules.Processed.Contains(c.Id))).ConfigureAwait(false);
ownAnswer = true;
seen = rules.Processed;
if (counted)
{
pages++;
@@ -561,7 +582,124 @@ public sealed partial class RecipeRunner
/// <summary>The posts of a walk page: of the account (tagged: of others), never a story or a collection item.</summary>
private static IReadOnlyList<ContentItem> PageItems(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk) =>
Contents(reads, c => IsPostLike(c) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account)));
Contents(reads, c => IsWalkItem(c, account, walk));
/// <summary>An item of a walk: a post of the account (tagged: of another account), never a story or a collection item.</summary>
private static bool IsWalkItem(ContentItem item, Account account, ProfileWalk walk) =>
IsPostLike(item) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(item, account) : IsOwnedBy(item, account));
/// <summary>An answer that brings items of the walk.</summary>
private static bool CarriesWalk(ReadResult result, Account account, ProfileWalk walk) =>
result.Contents.Any(c => IsWalkItem(c, account, walk));
/// <summary>
/// An answer to a gesture of the walk (a resume page, a tab) that is a page of it on its own: it brings items of the
/// walk, or it is an empty page of it (<see cref="IsEmptyWalkPage"/>).
/// </summary>
private static bool IsWalkPage(ReadResult result, Account account, ProfileWalk walk) =>
CarriesWalk(result, account, walk) || IsEmptyWalkPage(result, account, walk, ownAnswer: true);
/// <summary>
/// The end of a tab with nothing in it: a pagination and no item. With the profile of the account (the test site
/// sends it with every page of the tab), when nothing else comes with it, or — on the grid — when that profile says
/// it has no posts (the test site sends the collections with the first page of the grid). A bare empty answer only
/// when it answers a gesture of the walk (<paramref name="ownAnswer"/>): on Instagram the collections of an account
/// that has none are an empty connection with «has_next_page: false», as an empty grid would be, and they come
/// with the profile too.
/// </summary>
private static bool IsEmptyWalkPage(ReadResult result, Account account, ProfileWalk walk, bool ownAnswer) =>
result.Page is not null && result.Shape switch
{
ReadShape.Empty => ownAnswer,
ReadShape.Recognized => ProfileIn(result, account) is { } profile
&& ((result.Contents.Count == 0 && result.Highlights.Count == 0)
|| (walk.IsGrid && profile.PostCount == 0 && !result.Contents.Any(IsPostLike))),
_ => false,
};
/// <summary>
/// The pagination of a walk page: from the answer that brought the most items of the walk not read before
/// (<paramref name="seen"/>: the pages already read); when none did, from the last empty page of the walk
/// (<paramref name="ownAnswer"/>: the reads answer a gesture of the walk, <see cref="IsEmptyWalkPage"/>). Never from
/// an answer about something else, nor from one that only brings again a post already read: on Instagram the page
/// of a post says «more_available: false» of its single post and the collections say «has_next_page» of
/// themselves (HAR of 21/10/2026), and either would end the walk, or mark the history complete, where the grid
/// goes on.
/// </summary>
private static PageInfo? WalkPage(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk, bool ownAnswer, IReadOnlySet<string>? seen = null) =>
PageOf(reads, r => r.Contents.Where(c => IsWalkItem(c, account, walk)).Select(c => c.Id), r => IsEmptyWalkPage(r, account, walk, ownAnswer), seen);
/// <summary>
/// The pagination of a page of a list (a profile tab, the feed, the following list): from the answer that brings
/// the most items of the list not met before — in <paramref name="seen"/>, or in an earlier answer of the same page
/// with a pagination of its own — the last one on a tie; when none brings any, from the last empty page. An answer
/// that only brings again items already met, or fewer new ones than another (the page of a single post next to the
/// grid), never gives it.
/// </summary>
private static PageInfo? PageOf(IEnumerable<CapturedRead> reads, Func<ReadResult, IEnumerable<string>> itemIds, Func<ReadResult, bool> isEmptyPage, IReadOnlySet<string>? seen = null)
{
var met = new HashSet<string>(StringComparer.Ordinal);
PageInfo? withItems = null;
var most = 0;
PageInfo? empty = null;
foreach (var result in reads.Select(r => r.Result).Where(r => r.Page is not null))
{
var carried = 0;
var fresh = 0;
foreach (var id in itemIds(result))
{
carried++;
if (met.Add(id) && seen?.Contains(id) != true)
{
fresh++;
}
}
if (fresh > 0)
{
if (fresh >= most)
{
most = fresh;
withItems = result.Page;
}
}
else if (carried == 0 && isEmptyPage(result))
{
empty = result.Page;
}
}
return withItems ?? empty;
}
/// <summary>
/// The profile of the account as all the answers of the page describe it: the same profile can come in several
/// of them (the profile itself, the author of the posts, the owner of the collections), each with part of its
/// facts. The best described one is completed with what the others say; of the pictures, the largest.
/// </summary>
private static ProfileInfo? AccountProfile(IReadOnlyList<CapturedRead> reads, Account account)
{
if (FindProfile(reads, account) is not { } best)
{
return null;
}
foreach (var other in reads.SelectMany(r => r.Result.Profiles).Where(p => p.Id == best.Id).ToList())
{
best = best with
{
DisplayName = best.DisplayName ?? other.DisplayName,
IsPrivate = best.IsPrivate ?? other.IsPrivate,
IsFollowed = best.IsFollowed ?? other.IsFollowed,
PostCount = best.PostCount ?? other.PostCount,
Picture = other.Picture is { } picture && (best.Picture is null || picture.Area > best.Picture.Area) ? picture : best.Picture,
LatestStoryAt = best.LatestStoryAt ?? other.LatestStoryAt,
IsViewer = best.IsViewer || other.IsViewer,
};
}
return best;
}
/// <summary>Pinned on top of the profile: the vocabulary says so, or (newest first) the order of the page does.</summary>
private bool IsPinned(ContentItem item, IReadOnlyList<ContentItem> page, ProfileWalk walk) =>
@@ -591,28 +729,32 @@ public sealed partial class RecipeRunner
}
/// <summary>
/// Opens the profile page (1 counted action) and reads its state: missing profile, a name now used by another
/// account, private profile not followed (rule 6: not touched). Returns the updated account and the reads.
/// Opens the profile page (1 counted action) and reads its state: missing profile (when the map has its marker), a
/// name now used by another account, private profile not followed (rule 6: not touched). The profile, the posts
/// and the collections may come in different answers, and not together: after the profile the page is left to
/// settle, and with <paramref name="waitForGrid"/> the first page of posts is waited for too. Returns the updated
/// account and everything the page received.
/// </summary>
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account)
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account, bool waitForGrid = false)
{
var parameters = Values(("username", account.Username));
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
if ((await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
if (Env.SiteMap.IsTargetConfigured(SiteTargets.ProfileNotFound)
&& (await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
{
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
}
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
var reads = await WaitAndSettleAsync(run, mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
var profile = FindProfile(reads, account)!;
var profile = AccountProfile(reads, account)!;
if (account.InstagramId is { } known && profile.Id != known)
{
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
@@ -634,9 +776,58 @@ public sealed partial class RecipeRunner
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
}
if (waitForGrid)
{
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
}
return (account, reads);
}
/// <summary>
/// Waits for <paramref name="expected"/> after <paramref name="mark"/>, then lets the page settle and returns
/// everything that arrived since the mark: what one page shows can come in several answers, the expected one not
/// always last, and stopping at the first that matches would lose the others. When the expected data does not
/// come, returns what came, to be judged.
/// </summary>
private async Task<IReadOnlyList<CapturedRead>> WaitAndSettleAsync(RecipeRun run, long mark, Func<ReadResult, bool> expected)
{
var reads = await run.WaitForDataAsync(mark, expected).ConfigureAwait(false);
if (!reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
{
return reads;
}
await run.SettleAsync().ConfigureAwait(false);
return Env.Capture.Since(mark);
}
/// <summary>
/// The first page of the grid, when it did not come with the profile: the page may ask for it only after drawing
/// the profile, later than it takes to settle. Waits for posts of the account or an empty grid that is surely its
/// own (<see cref="IsEmptyWalkPage"/>: a bare empty answer may be the collections), then lets the page settle again.
/// Nothing is judged here (the profile came): a profile without posts that does not say so only costs the wait.
/// </summary>
private async Task<IReadOnlyList<CapturedRead>> WaitForGridAsync(RecipeRun run, long mark, Account account, IReadOnlyList<CapturedRead> reads)
{
var walk = ProfileWalk.Posts;
bool Arrived(IReadOnlyList<CapturedRead> list) => PageItems(list, account, walk).Count > 0 || WalkPage(list, account, walk, ownAnswer: false) is not null;
if (Arrived(reads))
{
return reads;
}
var arrived = await Env.Capture.WaitAsync(mark, list => run.Signal is not null || Arrived(list), Env.Options.DataTimeout, Env.Options.Poll, run.Ct).ConfigureAwait(false);
run.ThrowIfSignal();
if (!Arrived(arrived))
{
return arrived;
}
await run.SettleAsync().ConfigureAwait(false);
return Env.Capture.Since(mark);
}
/// <summary>
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Only the expected data ends the bursts: a response the page
@@ -674,9 +865,6 @@ public sealed partial class RecipeRunner
/// <summary>Outcome message of a page that arrived without data (three in a row raise a throttle signal).</summary>
private const string EmptyPageMessage = "La pagina è arrivata vuota: nessun dato da leggere.";
private static PageInfo? LastPage(IEnumerable<CapturedRead> reads) =>
reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault();
private static DateTimeOffset? ParseTime(string? value) =>
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var time) ? time : null;
@@ -17,34 +17,61 @@ public sealed partial class RecipeRunner
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Profiles.Count > 0).ConfigureAwait(false);
run.Judge(reads, r => r.Contents.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Home));
// The feed and the stories bar may come in different answers: after the first, the page is left to settle.
var reads = await WaitAndSettleAsync(run, mark, HomeArrived).ConfigureAwait(false);
run.Judge(reads, HomeArrived, Env.SiteMap.BuildPath(SitePages.Home));
var processed = 0;
var sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
var hasMore = reads.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? true;
var hasMore = FeedPage(reads)?.HasMore ?? true;
// Everything after the last read taken, so that nothing arriving while the posts are saved is missed.
var seen = reads.Count > 0 ? reads[^1].Sequence : mark;
for (var burst = 0; burst < Env.Options.SweepMaxBursts && !sawKnown && hasMore; burst++)
{
var before = Env.Capture.Mark();
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
run.ThrowIfSignal();
await run.SettleAsync().ConfigureAwait(false);
var more = Env.Capture.Since(before);
var more = Env.Capture.Since(seen);
if (more.Count == 0)
{
continue;
}
seen = more[^1].Sequence;
var met = Contents(reads, IsPostLike).Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
reads = [.. reads, .. more];
sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
hasMore = more.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? hasMore;
hasMore = FeedPage(more, met)?.HasMore ?? hasMore;
}
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>
/// The home arrived: posts, an account of the stories bar (it says when its latest story was published) or a page
/// of the feed. Profiles alone do not say it: Instagram also sends suggested profiles, not followed (HAR of
/// 21/10/2026), and they would pass for a home that is not there.
/// </summary>
private static bool HomeArrived(ReadResult result) =>
result.Contents.Count > 0 || result.Profiles.Any(p => p.LatestStoryAt is not null) || result.Page is not null;
/// <summary>
/// The pagination of the feed: from the answer that brought the most posts not met before (<paramref name="met"/>:
/// the earlier answers of the run); when none did, from an answer that brought no contents nor collections (an
/// empty feed). Never from an answer that brought only stories or collection items (the collections say
/// «has_next_page» of themselves), nor from one that only brings again a post already met (the page of that post
/// says «more_available: false» of itself).
/// </summary>
private static PageInfo? FeedPage(IReadOnlyList<CapturedRead> reads, IReadOnlySet<string>? met = null) =>
PageOf(
reads,
r => r.Contents.Where(IsPostLike).Select(c => c.Id),
r => (r.Shape is ReadShape.Empty or ReadShape.Recognized) && r.Contents.Count == 0 && r.Highlights.Count == 0,
met);
/// <summary>Saves the posts not processed yet; returns true once known content has been met.</summary>
private Task<bool> ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, ref int processed)
{
@@ -101,11 +128,20 @@ public sealed partial class RecipeRunner
}
/// <summary>
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen.
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen: an answer that
/// presents it with its name, or — Instagram's way, whose «xdt_viewer.user» gives only an identifier (HAR of
/// 21/10/2026) — the identifier from one answer of the run and the profile with that identifier, name included,
/// from any answer of the run (his own entry in the stories bar, for instance).
/// </summary>
private async Task EnsureMineAsync(IReadOnlyList<CapturedRead> reads, RecipeRun run)
{
if (reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null) is not { } viewer)
var viewer = reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null);
if (viewer is null && (reads.Select(r => r.Result.ViewerId).FirstOrDefault(id => id is not null) ?? Env.Capture.ViewerId) is { } viewerId)
{
viewer = reads.SelectMany(r => r.Result.Profiles).FirstOrDefault(p => p.Id == viewerId);
}
if (viewer is null)
{
return;
}
@@ -1,3 +1,4 @@
using System.Runtime.ExceptionServices;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Domain;
@@ -11,6 +12,17 @@ public sealed partial class RecipeRunner
/// <summary>A story stays on offer for a day (spec §4.3: «storie attive nelle 24 ore»).</summary>
private static readonly TimeSpan StoryLifetime = TimeSpan.FromHours(24);
/// <summary>
/// Without the item in the address, how long before a video ends the gesture that leaves it («next», or close) starts
/// at the latest: the pointer travel and the pause on the target of §7.7 (up to 1.2 s) with room to spare, multiplied
/// by mood and pace like the gesture. The viewer moves on by itself when the video ends, and the address would not
/// say so: a «next» pressed after that would skip an item.
/// </summary>
private static readonly TimeSpan VideoClickLead = TimeSpan.FromSeconds(1.5);
/// <summary>The placeholder of a viewer address that names the item shown; optional (Instagram's highlight viewer has none).</summary>
private const string ItemKey = "id";
/// <summary>
/// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the
/// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of
@@ -66,7 +78,7 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{ring.Message} Il profilo di {account.Username} dice però che c'è una storia attiva: la mappa dei bersagli va controllata.");
}
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
await StoriesCheckedAsync(account, run.Ct).ConfigureAwait(false);
return RecipeStatus.Completed; // no active stories: nothing to open
}
}
@@ -77,13 +89,14 @@ public sealed partial class RecipeRunner
var opened = await OpenViewerAsync(run, target, parameters, SitePages.StoryViewer).ConfigureAwait(false);
var watched = await WatchViewerAsync(run, SitePages.StoryViewer, "username", account.Username, account, viewerMark, opened).ConfigureAwait(false);
var shown = watched.Shown;
var ct = watched.StoreToken(run);
var stories = Contents(Env.Capture.Since(viewerMark), c => IsOwnedBy(c, account));
foreach (var id in shown)
{
if (stories.FirstOrDefault(s => s.Id == id) is { } story)
{
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, run.Ct).ConfigureAwait(false);
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, ct).ConfigureAwait(false);
if (saved.Outcome == SaveOutcome.Created)
{
run.NewEntries++;
@@ -91,12 +104,8 @@ public sealed partial class RecipeRunner
}
}
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
if (watched.Stop is { } stop)
{
throw stop;
}
await StoriesCheckedAsync(account, ct).ConfigureAwait(false);
watched.ThrowIfStopped();
return RecipeStatus.Completed;
}
@@ -105,10 +114,15 @@ public sealed partial class RecipeRunner
/// StoryView permit per content shown) and closes the viewer after the last one. A content that is a story already
/// saved is referenced, not downloaded again (H9).
/// </summary>
/// <remarks>
/// Collections are compared in the form of their address: Instagram writes «highlight:1790…» in its data and
/// «/stories/highlights/1790…/» in the address (HAR of 21/10/2026); the reader keeps the second, and the requested
/// identifier is taken in either form.
/// </remarks>
private async Task<RecipeStatus> HighlightAsync(RecipeRun run)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
if (run.Request.HighlightId is not { Length: > 0 } highlightId)
if (run.Request.HighlightId is not { Length: > 0 } requested)
{
throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta.");
}
@@ -118,26 +132,38 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}.");
}
var highlightId = ShapeReader.HighlightId(requested);
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
var parameters = Values(("username", account.Username));
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
var reads = await run.WaitForDataAsync(mark, r => r.Highlights.Count > 0 || ProfileIn(r, account) is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => r.Highlights.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
// Only this account's profile or collections say the page arrived: profiles suggested beside it do not.
var reads = await run.WaitForDataAsync(mark, r => OwnProfileOrCollectionsIn(r, account)).ConfigureAwait(false);
if (!reads.Any(r => r.Result.Highlights.Any(h => h.Id == highlightId && IsHighlightOf(h, account))))
{
// The collections may come in an answer of their own, after the profile: let the page settle first.
await run.SettleAsync().ConfigureAwait(false);
reads = Env.Capture.Since(mark);
}
if (!run.Judge(reads, r => OwnProfileOrCollectionsIn(r, account), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
if (FindProfile(reads, account) is { } profile)
{
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
}
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => IsHighlightOf(h, account)).ToList();
var collections = await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
if (!collections.TryGetValue(highlightId, out var highlight))
{
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false);
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false)
?? (requested == highlightId ? null : await Env.Storage.Highlights.FindAsync(account.Id, requested, run.Ct).ConfigureAwait(false));
throw RecipeRun.Stop(RecipeStatus.Completed, known is null
? "La raccolta non è nel profilo."
: $"La raccolta «{known.Title}» non è più nel profilo: i suoi file restano.");
@@ -145,11 +171,13 @@ public sealed partial class RecipeRunner
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
var viewerMark = Env.Capture.Mark();
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, Values(("id", highlightId), ("username", account.Username)), SitePages.HighlightViewer).ConfigureAwait(false);
var target = Values(("id", highlightId), ("username", account.Username), ("title", highlight.Title));
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, target, SitePages.HighlightViewer).ConfigureAwait(false);
var watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false);
var shown = watched.Shown;
var ct = watched.StoreToken(run);
var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId);
var items = Contents(Env.Capture.Since(viewerMark), c => InCollection(c, highlightId));
var ordered = new List<long>();
foreach (var id in shown)
{
@@ -158,7 +186,7 @@ public sealed partial class RecipeRunner
continue;
}
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false);
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, ct).ConfigureAwait(false);
if (created)
{
run.NewEntries++;
@@ -172,15 +200,11 @@ public sealed partial class RecipeRunner
if (items.Count > 0 && items.All(i => shown.Contains(i.Id)) && ordered.Count == items.Count)
{
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, run.Ct).ConfigureAwait(false);
}
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
if (watched.Stop is { } stop)
{
throw stop;
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, ct).ConfigureAwait(false);
}
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, ct).ConfigureAwait(false);
watched.ThrowIfStopped();
return RecipeStatus.Completed;
}
@@ -196,15 +220,29 @@ public sealed partial class RecipeRunner
}
}
/// <summary>Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed.</summary>
private async Task<IReadOnlyDictionary<string, string>> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
/// <summary>
/// Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed. Returns the address
/// shown and when the first click started (the first item cannot have come on screen before). When the click takes
/// the page to an address the map does not take for the viewer (its shape in the map may be wrong), what opened is
/// closed like a viewer before the recipe stops: left open, it would move on by itself to other accounts.
/// </summary>
private async Task<ViewerOpening> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
{
var before = await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false);
var clickedAt = Env.Clock.Now;
for (var attempt = 0; attempt < 2; attempt++)
{
await run.ClickAsync(target, parameters).ConfigureAwait(false);
if (await WaitForViewerAsync(run, viewerPage, previous: null).ConfigureAwait(false) is { } opened)
{
return opened;
return new ViewerOpening(opened, clickedAt);
}
if (!string.Equals(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false), before, StringComparison.Ordinal))
{
// The click was noticed, but what opened has not the shape of the viewer: no second click on it.
await CloseAsync(run, path => !string.Equals(path, before, StringComparison.Ordinal)).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.Failed, $"Dopo il clic l'indirizzo non ha la forma «{viewerPage}» della mappa {Env.SiteMap.Source ?? Env.SiteMap.Site}: ciò che si è aperto è stato chiuso. La forma va controllata.");
}
if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found)
@@ -217,141 +255,383 @@ public sealed partial class RecipeRunner
}
/// <summary>
/// Watches a viewer that shows <paramref name="opened"/>: reads the item shown from the address of the page, waits
/// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by
/// itself) and closes the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something
/// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order.
/// Watches a viewer that shows <paramref name="opened"/>: on each item it first asks the StoryView permit for the
/// item after it (before it can come on screen, by a click or by itself), then waits the time of §7.7, and closes
/// the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something else. The item
/// shown is read from the address when the address carries it (<see cref="FollowAddressAsync"/>), otherwise counted
/// (<see cref="FollowCountAsync"/>). On any stop other than a signal, an unexpected error included, the viewer is
/// closed first; a viewer that stays open stops the run as a target not found. A cancellation leaves the page as it
/// is. Returns the identifiers shown, in order, each under its permit.
/// </summary>
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary<string, string> opened)
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, ViewerOpening opened)
{
var shown = new List<string>();
var counted = new HashSet<string>(StringComparer.Ordinal);
var pendingPermit = true; // asked before the click that opened the viewer
var position = opened;
var stuck = 0;
var viewer = new ViewerWatch(viewerPage, ownerKey, owner, account, mark);
try
{
while (true)
try
{
run.ThrowIfSignal();
if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase))
if (!opened.Position.ContainsKey(ownerKey))
{
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
await Writer.EventAsync(
"visualizzatore-altro-account",
viewerPage == SitePages.StoryViewer
? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
: $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.",
EventSeverity.Warning,
account.Id,
run.Session.SessionId,
run.Ct).ConfigureAwait(false);
return new ViewerResult(shown, null);
throw RecipeRun.Stop(RecipeStatus.Failed, $"La forma dell'indirizzo «{viewerPage}» nella mappa {Env.SiteMap.Source ?? Env.SiteMap.Site} non dice di chi è il visualizzatore: manca «{{{ownerKey}}}».");
}
var id = position["id"];
if (counted.Add(id))
if (opened.Position.ContainsKey(ItemKey))
{
if (!pendingPermit)
{
// The viewer moved on by itself: this item was shown without asking first; ask now.
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
}
pendingPermit = false;
shown.Add(id);
await FollowAddressAsync(run, viewer, opened.Position, shown).ConfigureAwait(false);
}
else
{
await FollowCountAsync(run, viewer, opened, shown).ConfigureAwait(false);
}
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false);
var item = list.FirstOrDefault(i => i.Id == id);
var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
run.ThrowIfSignal();
var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
if (current is null)
{
return new ViewerResult(shown, null); // the viewer closed by itself
}
if (!SamePosition(current, position))
{
position = current; // it moved on by itself while we watched
continue;
}
var index = list.FindIndex(i => i.Id == id);
if (list.Count > 0 && index == list.Count - 1)
{
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
return new ViewerResult(shown, null);
}
if (!pendingPermit)
{
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
pendingPermit = true;
}
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false);
if (next is null)
{
return new ViewerResult(shown, null); // closed after the last item
}
if (SamePosition(next, current))
{
if (++stuck >= 2)
{
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
}
continue; // the click went unnoticed: watch a little more and try again
}
stuck = 0;
position = next;
return new ViewerResult(shown, null);
}
}
catch (RecipeStopException stop)
{
if (stop.Status != RecipeStatus.StoppedBySignal)
catch (RecipeStopException stop)
{
// Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is.
try
{
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
}
catch (RecipeStopException)
{
}
var stillOpen = stop.Status == RecipeStatus.StoppedBySignal ? null : await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
return new ViewerResult(shown, Worse(stop, stillOpen));
}
return new ViewerResult(shown, stop);
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
// Not even an unexpected error leaves the viewer open; what was shown until then is saved all the same.
var stillOpen = await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
return new ViewerResult(shown, Worse(RecipeRun.Stop(RecipeStatus.Failed, $"Errore imprevisto in «{Name(run.Request.Kind)}» ({ex.GetType().Name}): {ex.Message}"), stillOpen));
}
}
catch (OperationCanceledException cancelled)
{
// A pause, the session closed by a signal, Alberto taking the browser: the page is left as it is, what was
// shown under its permit is saved all the same, then the cancellation goes on.
return new ViewerResult(shown, null, ExceptionDispatchInfo.Capture(cancelled));
}
}
/// <summary>What a viewer showed, and why it stopped early (the caller saves what was shown, then stops).</summary>
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop);
/// <summary>
/// Follows a viewer whose address carries the item shown (the test site: «/storie/{username}/{id}/»): every
/// position is read from the address, so an item the viewer skipped or showed by itself is known for what it is.
/// The permit asked on an item covers the next one, also when it comes by itself; an item that comes by itself
/// after what the list gave as the last one had no permit: the viewer is closed and it is not saved.
/// </summary>
private async Task FollowAddressAsync(RecipeRun run, ViewerWatch viewer, IReadOnlyDictionary<string, string> opened, List<string> shown)
{
var counted = new HashSet<string>(StringComparer.Ordinal);
var permitted = true; // asked before the click that opened the viewer: for the first item on screen
var position = opened;
var stuck = 0;
while (true)
{
run.ThrowIfSignal();
if (!viewer.ShowsOwner(position))
{
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
return;
}
var id = position[ItemKey];
if (counted.Add(id))
{
if (!permitted)
{
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
? $"Il visualizzatore è andato avanti da solo dopo quella che per la pagina era l'ultima storia di {viewer.Account.Username}: chiuso, la storia in più non si salva."
: $"Il visualizzatore è andato avanti da solo dopo quello che per la pagina era l'ultimo contenuto della raccolta di {viewer.Account.Username}: chiuso, il contenuto in più non si salva.").ConfigureAwait(false);
return;
}
permitted = false;
shown.Add(id);
}
var since = Env.Clock.Now;
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
var index = list.FindIndex(i => i.Id == id);
var last = list.Count > 0 && index == list.Count - 1;
if (!last && !permitted)
{
// The permit for the item after this one, before it can come on screen.
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
permitted = true;
}
await WatchAsync(run, index < 0 ? null : VideoDuration(list[index]), since, latest: null).ConfigureAwait(false);
run.ThrowIfSignal();
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
if (current is null)
{
return; // the viewer closed by itself
}
if (!SamePosition(current, position))
{
position = current; // it moved on by itself while we watched
continue;
}
if (last)
{
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
return;
}
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
var next = await WaitForViewerAsync(run, viewer.Page, previous: current).ConfigureAwait(false);
if (next is null)
{
return; // closed after the last item
}
if (SamePosition(next, current))
{
if (++stuck >= 2)
{
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
}
continue; // the click went unnoticed: watch a little more and try again
}
stuck = 0;
position = next;
}
}
/// <summary>
/// Follows a viewer whose address does not say which item is shown: Instagram's highlight viewer stays on
/// «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026). The items are counted against the
/// list the page received for the owner: the first one shown is the first of the list, and each click on «next»
/// moves one on. A move the viewer makes by itself cannot be seen, so it is never counted: a video, which moves the
/// viewer on when it ends, is left before then (<see cref="VideoClickLead"/>), and when that is no longer possible
/// (the Governor's wait for the permit took its time) the viewer is closed without clicking «next», the items after
/// it not saved. A photo is never taken as over, because how long the site keeps it is not in the data: should the
/// viewer leave one by itself, the count falls behind and its last «next» takes the viewer to another collection,
/// where it is closed. A click the page ignores would put the count ahead: nothing in the address or in the data
/// tells it yet (to be measured live).
/// </summary>
private async Task FollowCountAsync(RecipeRun run, ViewerWatch viewer, ViewerOpening opened, List<string> shown)
{
var position = opened.Position;
var index = 0;
var appearedAfter = opened.ClickedAt; // the item at «index» did not come on screen before this
while (true)
{
run.ThrowIfSignal();
if (!viewer.ShowsOwner(position))
{
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
return;
}
var since = Env.Clock.Now;
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
if (index >= list.Count)
{
// The page described nothing (more) for this owner: which item is on screen cannot be told.
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
return;
}
// On screen under the permit asked before it could come: before opening, or on the item before it.
var item = list[index];
if (!shown.Contains(item.Id, StringComparer.Ordinal))
{
shown.Add(item.Id);
}
var last = index == list.Count - 1;
var video = VideoDuration(item);
DateTimeOffset? leaveBy = video is { } duration && duration > TimeSpan.Zero
? appearedAfter + duration - TimeSpan.FromTicks((long)(VideoClickLead.Ticks * Env.Driver.WaitMultiplier))
: null;
if (!last)
{
// The permit for the item after this one, before it can come on screen; asked only while the viewer
// surely has not moved on by itself, and the item still has to be left in time once it is granted.
if (!Passed(leaveBy))
{
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
}
if (Passed(leaveBy))
{
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
? $"Una storia video di {viewer.Account.Username} poteva essere già finita, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», le storie successive non si salvano questa volta."
: $"Un video della raccolta di {viewer.Account.Username} poteva essere già finito, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», i contenuti successivi non si salvano questa volta.").ConfigureAwait(false);
return;
}
}
await WatchAsync(run, video, since, leaveBy).ConfigureAwait(false);
run.ThrowIfSignal();
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
if (current is null)
{
return; // the viewer closed by itself
}
if (!viewer.ShowsOwner(current))
{
position = current; // it moved on by itself to another owner while we watched
continue;
}
if (last)
{
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
return;
}
var pressedAfter = Env.Clock.Now;
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
index++;
appearedAfter = pressedAfter;
position = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
if (position is null)
{
return; // the viewer closed: the item after was not shown
}
}
}
/// <summary>True once <paramref name="moment"/> has come (never for none).</summary>
private bool Passed(DateTimeOffset? moment) => moment is { } end && Env.Clock.Now >= end;
/// <summary>
/// Waits the time of §7.7 on an item on screen since <paramref name="since"/>: what the recipe waited meanwhile (the
/// Governor's spacing before the permit for the next item) is part of it. Never past <paramref name="latest"/>.
/// </summary>
private async Task WatchAsync(RecipeRun run, TimeSpan? video, DateTimeOffset since, DateTimeOffset? latest)
{
var until = since + StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier);
if (latest is { } end && end < until)
{
until = end;
}
var wait = until - Env.Clock.Now;
if (wait > TimeSpan.Zero)
{
await Env.Driver.WaitAsync(wait, run.Ct).ConfigureAwait(false);
}
}
private static TimeSpan? VideoDuration(ContentItem item) => item.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
/// <summary>The viewer went on to another account or collection: closed, and the event recorded.</summary>
private async Task LeaveOtherOwnerAsync(RecipeRun run, ViewerWatch viewer)
{
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
await Writer.EventAsync(
"visualizzatore-altro-account",
viewer.Page == SitePages.StoryViewer
? $"Dopo le storie di {viewer.Account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
: $"Il visualizzatore è passato a un'altra raccolta di {viewer.Account.Username}: chiuso senza salvarla.",
EventSeverity.Warning,
viewer.Account.Id,
run.Session.SessionId,
run.Ct).ConfigureAwait(false);
}
/// <summary>
/// The viewer may be on an item not shown under a permit, or not known: closed before the end, without clicking
/// «next», and the event recorded. What it may show now is not saved.
/// </summary>
private async Task CloseEarlyAsync(RecipeRun run, ViewerWatch viewer, string why)
{
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
await Writer.EventAsync("visualizzatore-chiuso-prima", why, EventSeverity.Info, viewer.Account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
/// <summary>
/// Closes the viewer on the way out of a stop, unless a signal says to leave the page as it is; never throws, but
/// for a cancellation. Returns why the viewer may still be open (it did not close with its command), otherwise null.
/// </summary>
private async Task<RecipeStopException?> TryCloseViewerAsync(RecipeRun run, string viewerPage)
{
try
{
run.ThrowIfSignal();
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
return null;
}
catch (RecipeStopException stop)
{
// After a signal the page stays as it is; otherwise the command was not found or the viewer did not close.
return stop.Status == RecipeStatus.TargetNotFound ? stop : null;
}
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
{
// Whether it closed is not known (the browser may be gone): the stop being reported is the first one.
return null;
}
}
/// <summary>
/// The stop to report: a viewer left open outranks a milder first stop, as a target not found, which makes the
/// session stop and put the page at rest.
/// </summary>
private static RecipeStopException Worse(RecipeStopException first, RecipeStopException? stillOpen) =>
stillOpen is null || first.Status == RecipeStatus.TargetNotFound
? first
: RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{first.Message} {stillOpen.Message}");
/// <summary>The address a viewer opened on, and when the click that opened it started.</summary>
private sealed record ViewerOpening(IReadOnlyDictionary<string, string> Position, DateTimeOffset ClickedAt);
/// <summary>
/// What a viewer showed, and why it stopped early: a stop, or a cancellation. The caller saves what was shown, then
/// goes on with the stop (<see cref="ThrowIfStopped"/>).
/// </summary>
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop, ExceptionDispatchInfo? Cancelled = null)
{
/// <summary>The token to store what was shown with: stopped early, the run's own may be cancelled already, or a moment later (storage only).</summary>
public CancellationToken StoreToken(RecipeRun run) => Stop is null && Cancelled is null ? run.Ct : CancellationToken.None;
/// <summary>Goes on with the cancellation or the stop, once what was shown is stored.</summary>
public void ThrowIfStopped()
{
Cancelled?.Throw();
if (Stop is { } stop)
{
throw stop;
}
}
}
/// <summary>A viewer being watched: its page, the placeholder of its owner in the address, the owner, the account, the mark of its data.</summary>
private sealed record ViewerWatch(string Page, string OwnerKey, string Owner, Account Account, long Mark)
{
/// <summary>True when the address still shows the owner watched (an account, or a collection).</summary>
public bool ShowsOwner(IReadOnlyDictionary<string, string> position) =>
position.TryGetValue(OwnerKey, out var shown) && string.Equals(shown, Owner, StringComparison.OrdinalIgnoreCase);
}
private static bool SamePosition(IReadOnlyDictionary<string, string> a, IReadOnlyDictionary<string, string> b) =>
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase));
/// <summary>The items of the viewer for the owner, as received (waits for them the first time).</summary>
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account)
/// <summary>
/// The items of the viewer for the owner, as received (waits for them the first time). The stories of an account are
/// only what looks like a story (it expires and is in no collection): a post of the account arriving meanwhile (the
/// grid comes in an answer of its own, also after the viewer opened) would hide which story is the last one, or,
/// counted by position, move every position after it.
/// </summary>
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, ViewerWatch viewer)
{
Func<ContentItem, bool> belongs = viewerPage == SitePages.StoryViewer
? c => IsOwnedBy(c, account)
: c => c.HighlightId == owner;
var present = Contents(Env.Capture.Since(mark), belongs);
Func<ContentItem, bool> belongs = viewer.Page == SitePages.StoryViewer
? c => IsOwnedBy(c, viewer.Account) && c.ExpiresAt is not null && c.HighlightId is null
: c => InCollection(c, viewer.Owner);
var present = Contents(Env.Capture.Since(viewer.Mark), belongs);
if (present.Count > 0)
{
return present;
}
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
var reads = await run.WaitForDataAsync(viewer.Mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
run.Judge(reads, r => r.Contents.Any(belongs), null);
return Contents(reads, belongs);
}
@@ -383,10 +663,20 @@ public sealed partial class RecipeRunner
}
}
/// <summary>Closes the viewer with its command and waits until it is gone.</summary>
private async Task CloseViewerAsync(RecipeRun run, string viewerPage)
/// <summary>Closes the viewer with its command and waits until it is gone; stops the run when it stays open.</summary>
private Task CloseViewerAsync(RecipeRun run, string viewerPage) =>
CloseAsync(run, path => Env.SiteMap.Match(viewerPage, path) is not null);
/// <summary>
/// Clicks «viewer-close» while the address says something is open (<paramref name="isOpen"/>) and waits until it is
/// gone. Never after a signal (the page stays as it is). A command that is not found, or a viewer still open after
/// <see cref="RecipeOptions.ViewerTimeout"/>, stops the run as a target not found: the session then stops and the
/// page is put at rest.
/// </summary>
private async Task CloseAsync(RecipeRun run, Func<string, bool> isOpen)
{
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
run.ThrowIfSignal();
if (!isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
{
return;
}
@@ -399,19 +689,20 @@ public sealed partial class RecipeRunner
}
var deadline = Env.Clock.Now + Env.Options.ViewerTimeout;
while (Env.Clock.Now < deadline)
while (isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
{
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
if (Env.Clock.Now >= deadline)
{
return;
run.ThrowIfSignal();
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"Il visualizzatore non si è chiuso con «{SiteTargets.ViewerClose}»: il bersaglio della mappa va controllato.");
}
await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false);
}
}
private async Task StoriesCheckedAsync(Account account, RecipeRun run) =>
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
private async Task StoriesCheckedAsync(Account account, CancellationToken ct) =>
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, ct).ConfigureAwait(false);
private async Task MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason)
{
@@ -433,4 +724,18 @@ public sealed partial class RecipeRunner
private static ProfileInfo? ProfileIn(ReadResult result, Account account) =>
result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase));
/// <summary>The profile of the account, or one of its collections: what says that its profile page arrived.</summary>
private static bool OwnProfileOrCollectionsIn(ReadResult result, Account account) =>
ProfileIn(result, account) is not null || result.Highlights.Any(h => IsHighlightOf(h, account));
/// <summary>A collection of the account: its owner is the account, or the answer does not say whose it is.</summary>
private static bool IsHighlightOf(HighlightInfo highlight, Account account) =>
highlight.Owner is not { } owner
|| (account.InstagramId is { } id && owner.Id == id)
|| string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase);
/// <summary>An item received inside collection <paramref name="highlightId"/> (both in the form of the address).</summary>
private static bool InCollection(ContentItem item, string highlightId) =>
item.HighlightId is { } id && string.Equals(ShapeReader.HighlightId(id), highlightId, StringComparison.Ordinal);
}
@@ -50,11 +50,13 @@ public sealed record RecipeEnvironment
/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop
/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with
/// coordinates; an unknown response shape stops it with <see cref="RecipeStatus.UnrecognizedFormat"/> and an event
/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a
/// skeleton (the first Instagram files, to be filled after M0).
/// that carries only the key structure. A recipe refuses to run, as <see cref="RecipeStatus.NotConfigured"/>, while the
/// site's map lacks a page or target it needs or the reader vocabulary is not usable (Instagram's targets, H11).
/// </remarks>
public sealed partial class RecipeRunner : IRecipeRunner
{
private readonly Lock _refusalsGate = new();
private readonly HashSet<RecipeKind> _refusalsReported = [];
private long? _sessionId;
private RecipeKind? _lastKind;
@@ -83,15 +85,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
_ => kind.ToString(),
};
/// <summary>Pages and targets a recipe cannot work without.</summary>
/// <summary>
/// Pages and targets a recipe cannot work without. «profile-not-found» is not among them: it is looked up only when
/// the map sets it, and without it a profile that does not exist gives no data, judged like any page that arrives
/// empty.
/// </summary>
public static (IReadOnlyList<string> Pages, IReadOnlyList<string> Targets) Requirements(RecipeKind kind) => kind switch
{
RecipeKind.FollowingSweep => ([SitePages.Home], []),
RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]),
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], []),
RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]),
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]),
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileTabTagged]),
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileTabReels]),
RecipeKind.SinglePost => ([SitePages.Post], []),
RecipeKind.FollowingList => ([SitePages.Following], []),
_ => ([], []),
@@ -112,20 +118,23 @@ public sealed partial class RecipeRunner : IRecipeRunner
ArgumentNullException.ThrowIfNull(session);
var name = Name(request.Kind);
var (pages, targets) = Requirements(request.Kind);
var missing = Env.SiteMap.Missing(pages, targets);
if (missing.Count > 0)
// A map or a vocabulary that lacks what the recipe needs is a state of the configuration, not a failure of the
// recipe: nothing is done, nothing counts towards suspension, and it is said once per recipe and process (the
// engine stops planning it, NotConfiguredReason).
if (Refusal(request.Kind) is { } refusal)
{
var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11).";
await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message);
}
bool first;
lock (_refusalsGate)
{
first = _refusalsReported.Add(request.Kind);
}
if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable)
{
var message = $"«{name}» non può girare: {unusable}";
await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message);
if (first)
{
await Writer.EventAsync(refusal.Code, refusal.Message + SessionComposer.NotConfiguredTail, EventSeverity.Warning, null, session.SessionId, ct).ConfigureAwait(false);
}
return new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, refusal.Message);
}
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
@@ -206,6 +215,28 @@ public sealed partial class RecipeRunner : IRecipeRunner
};
}
/// <inheritdoc/>
public string? NotConfiguredReason(RecipeKind kind) => Refusal(kind)?.Message;
/// <summary>
/// Why the site's configuration does not let <paramref name="kind"/> run, with the code of its timeline line: pages
/// or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when it can run.
/// </summary>
private (string Code, string Message)? Refusal(RecipeKind kind)
{
var name = Name(kind);
var (pages, targets) = Requirements(kind);
var missing = Env.SiteMap.Missing(pages, targets);
if (missing.Count > 0)
{
return ("mappa-incompleta", $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}).");
}
return Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
? ("lettori-incompleti", $"«{name}» non può girare: {unusable}")
: null;
}
/// <summary>
/// The rest page (spec §6.1). After a verification request or a disconnection the page is left as it is, so that
/// Alberto sees what happened (spec §7.6): resting is skipped while the breaker says so.
+6 -3
View File
@@ -31,10 +31,13 @@ public static class SitePages
/// <summary>The same list resuming after {cursor} (optional).</summary>
public const string FollowingFrom = "followingFrom";
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
/// <summary>Shape of the address of the story viewer: {username}, and {id} of the story shown when the address carries it.</summary>
public const string StoryViewer = "storyViewer";
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
/// <summary>
/// Shape of the address of the highlight viewer: {highlight}, and {id} of the item shown when the address carries it
/// (Instagram's does not: «/stories/highlights/{highlight}/» stays the same from item to item).
/// </summary>
public const string HighlightViewer = "highlightViewer";
public static IReadOnlyList<string> All { get; } =
@@ -178,7 +181,7 @@ public sealed partial class SiteMap
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
/// <summary>The Instagram map (embedded <c>bersagli.instagram.json</c>): the pages seen in real traffic, targets still unset (H11).</summary>
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
+11 -11
View File
@@ -1,17 +1,17 @@
{
"site": "instagram",
"note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
"note": "Mappa di Instagram, aggiornata il 25 ottobre 2026 (specifica §6.3). PAGINE: compilate solo quelle che hanno una prova reale nel file HAR del browser di Alberto del 21 ottobre 2026, cioè i modelli di indirizzo che Instagram stesso manda al browser (/ajax/bulk-route-definitions/) e i percorsi del Referer delle richieste fatte dalla pagina: home, profile, post, storyViewer, highlightViewer. Restano vuote, senza prove: following e followingFrom (quindi «Elenco dei seguiti» non gira), profileFrom, reelsFrom e taggedFrom (facoltative). Le parti facoltative dei modelli di Instagram ({?tab}, {?initial_media_id}) non si scrivono: qui ogni segnaposto vale esattamente un segmento. BERSAGLI: tutti ancora VUOTI (ipotesi H11). Il HAR aveva solo risposte Fetch/XHR: nessun documento e nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Si compilano con docs/prove-dal-vivo.md, parte A bis (tools/bersagli/raccogli-bersagli.js). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
"pages": {
"home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." },
"profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." },
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." },
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." },
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." },
"post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." },
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." },
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." },
"storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." },
"highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." }
"home": { "path": "/", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti. Prova: modello «/» (PolarisFeedRoute) nelle definizioni delle pagine. Che cosa arrivi caricandola (H1) non è nel HAR e resta da provare." },
"profile": { "path": "/{username}/", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}. Prova: modello /{username}/{?tab}/{?view_type}/{?igshid}/ (PolarisProfilePostsTabRoute), senza le parti facoltative. I valori di {?tab} non si vedono nel campione." },
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Nessuna prova di un indirizzo del genere: resta vuota e lo storico riprende scorrendo." },
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel. Nessuna prova: la scheda non è nel campione." },
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati. Nessuna prova: la scheda non è nel campione." },
"post": { "path": "/p/{code}/", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code} (11 caratteri). Prova: il percorso /p/{code}/ nel Referer delle richieste della pagina di un post. Instagram usa anche /{username}/reel/{code}/ (modello /{username}/{permalink_key}/{shortcode}/): Febe apre la forma /p/." },
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}. Nessuna prova nel campione: resta vuota e «Elenco dei seguiti» non gira finché non arriva (parte A bis)." },
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa. Nessuna prova." },
"storyViewer": { "path": "/stories/{username}/{id}/", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata. Prova: modello /stories/{username}/{?initial_media_id}/ (PolarisStoriesV3Route). DA CONFERMARE che l'indirizzo segua ogni storia (l'{id} cambia a ogni avanzamento) e che porti l'{id} fin dall'apertura: senza {id} questa forma non corrisponde e la ricetta si ferma dicendo che il visualizzatore non si è aperto. Anche /stories/highlights/<cifre>/ ha questa forma, con username «highlights»: per le Storie di un account è «un altro account» e il visualizzatore si chiude; la ricetta delle raccolte legge solo highlightViewer." },
"highlightViewer": { "path": "/stories/highlights/{highlight}/", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} sono le 17 cifre dell'identificativo (nei dati «highlight:<cifre>», ridotto alle cifre dal lettore). Prova: il Referer delle richieste fatte guardando una raccolta e il modello /stories/highlights/{highlight_reel_id}/ (PolarisStoriesV3HighlightsRoute). Non c'è l'{id} del contenuto mostrato: l'indirizzo resta lo stesso mentre si guarda, quindi la posizione nella raccolta non si legge dall'indirizzo." }
},
"targets": {
"home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." },
+33 -29
View File
@@ -1,51 +1,55 @@
{
"site": "instagram",
"status": "ipotesi",
"note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.",
"status": "confermato",
"note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome, quindi da solo non basta a riconoscerlo (H10 resta aperta).",
"content": {
"note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.",
"note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza e raccolta-pagina-successiva. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media): chiave vista ma sempre vuota nei campioni, il formato dei figli è un indizio di §6.4 da confermare con un campione di un post con più file.",
"id": ["pk"],
"code": ["code"],
"takenAt": ["taken_at"],
"caption": [],
"caption": ["caption.text"],
"images": ["image_versions2.candidates"],
"videos": ["video_versions"],
"children": ["carousel_media"],
"childCount": [],
"owner": [],
"childCount": ["carousel_media_count"],
"owner": ["user", "owner"],
"pinned": [],
"expiresAt": [],
"duration": []
"expiresAt": ["expiring_at"],
"duration": ["video_duration"]
},
"version": {
"note": "Da compilare con i campioni di M0 (H3, H5).",
"url": [],
"width": [],
"height": [],
"note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).",
"url": ["url"],
"width": ["width"],
"height": ["height"],
"hasAudio": []
},
"profile": {
"note": "Da compilare con i campioni di M0 (H3, H10).",
"id": [],
"username": [],
"displayName": [],
"isPrivate": [],
"isFollowed": [],
"note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia. Il numero dei post non compare in nessun campione: resta vuoto.",
"id": ["pk", "id"],
"username": ["username"],
"displayName": ["full_name"],
"isPrivate": ["is_private"],
"isFollowed": ["friendship_status.following"],
"postCount": [],
"picture": [],
"latestStoryAt": []
"picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"],
"latestStoryAt": ["latest_reel_media"]
},
"highlight": {
"note": "Da compilare con i campioni di M0 (H3, H9).",
"id": [],
"title": [],
"owner": [],
"items": []
"note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva.",
"id": ["id"],
"title": ["title"],
"owner": ["user"],
"items": ["items"]
},
"page": {
"note": "Da compilare con i campioni di M0 (H3).",
"hasMore": [],
"cursor": []
"note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.",
"hasMore": ["has_next_page", "more_available"],
"cursor": ["end_cursor"]
},
"viewer": []
"relevance": {
"note": "Una risposta che non contiene nessuna di queste chiavi non parla di contenuti né di profili e si ignora: promozioni, registri, il segno «storia vista», le definizioni delle pagine. Senza questo elenco ognuna conterebbe come «formato non riconosciuto».",
"keys": ["image_versions2", "video_versions", "carousel_media", "taken_at", "username"]
},
"viewer": ["xdt_viewer.user"]
}
+2
View File
@@ -403,6 +403,8 @@ public static class EngineEventCodes
public const string ManualCheck = "controlla-ora";
public const string RecipeFailed = "ricetta-fallita";
public const string SettingsChanged = "impostazioni-motore";
public const string RecipeNotConfigured = "configurazione-incompleta";
public const string CollectionConfigurationChanged = "configurazione-raccolta";
/// <summary>Prefix of the per-recipe lines («Appena fatto»): "ricetta." + recipe kind.</summary>
public const string RecipePrefix = "ricetta.";
+13
View File
@@ -74,6 +74,12 @@ public enum RecipeStatus
/// <summary>Unexpected error; message says what happened.</summary>
Failed,
/// <summary>
/// Refused before anything was done: the target map or the reader vocabulary of the site does not have what the
/// recipe needs yet. A state of the configuration, not a failure of the recipe: it never counts towards suspension.
/// </summary>
NotConfigured,
}
/// <summary>Result of a recipe run, used by the scheduler to plan what comes next.</summary>
@@ -115,6 +121,13 @@ public interface IRecipeRunner
/// <summary>Puts the browser on the empty rest page (end of session, pauses, night).</summary>
Task RestAsync(CancellationToken ct);
/// <summary>
/// Why <paramref name="kind"/> cannot run on the configuration of the site in use (target map, reader vocabulary),
/// in Italian; null when it can, or when the runner cannot tell. The engine does not plan such a recipe: running it
/// would only end in <see cref="RecipeStatus.NotConfigured"/>.
/// </summary>
string? NotConfiguredReason(RecipeKind kind) => null;
}
/// <summary>Daily byte budget for CDN downloads (category «dati scaricati», spec §7.4).</summary>
+48
View File
@@ -259,6 +259,11 @@ public sealed class EngineHost : IAsyncDisposable
}
var kind = CheckPolicy.WantsProfileChecks(account) ? EngineTaskKind.ProfileCheck : EngineTaskKind.AccountStories;
if (_composer.NotConfiguredReason(CheckPolicy.RecipeOf(kind)) is { } notConfigured)
{
return new CheckNowResult(CheckNowStatus.Refused, notConfigured + " Il controllo non parte.");
}
var category = kind == EngineTaskKind.ProfileCheck ? ActionKind.ProfileOpen : ActionKind.StoryView;
var budget = await _s.Governor.EvaluateBudgetAsync(category, accountId, ct).ConfigureAwait(false);
if (!budget.Granted && budget.Reason != DenialReason.AccountNotContactable)
@@ -397,6 +402,49 @@ public sealed class EngineHost : IAsyncDisposable
return resumed;
}
/// <summary>
/// The collection configuration in use: <paramref name="fingerprint"/> of the reader vocabulary and target map of the
/// site as loaded. When it differs from the stored one — or none is stored yet, the first start that knows it —
/// every suspension and consecutive failure of the recipes is cleared once, since they were counted against other
/// files, with one line in the timeline when there was something to clear; then the fingerprint is stored. Called at
/// start-up, before <see cref="StartAsync"/>. True when the configuration had changed.
/// </summary>
public async Task<bool> ApplyCollectionConfigurationAsync(string fingerprint, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint);
var settings = _s.Storage.Settings;
if (string.Equals(await settings.GetAsync(EngineSettingKeys.CollectionConfiguration, ct).ConfigureAwait(false), fingerprint, StringComparison.Ordinal))
{
return false;
}
await _health.LoadAsync(ct).ConfigureAwait(false);
var (suspended, hadFailures) = await _health.ResetAllAsync(ct).ConfigureAwait(false);
if (suspended.Count > 0)
{
var names = string.Join(", ", suspended.Select(k => "«" + ItalianText.Capitalize(SessionComposer.RecipeName(k)) + "»"));
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.CollectionConfigurationChanged,
$"La configurazione della raccolta è cambiata: le ricette sospese ripartono ({names}).",
ct: ct).ConfigureAwait(false);
}
else if (hadFailures)
{
await _s.Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.CollectionConfigurationChanged,
"La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.",
ct: ct).ConfigureAwait(false);
}
// Stored last: if Febe stops in between, the next start clears again, which changes nothing.
await settings.SetAsync(EngineSettingKeys.CollectionConfiguration, fingerprint, ct).ConfigureAwait(false);
Wake();
_s.Events.Publish(EngineNotificationKind.StateChanged);
return true;
}
/// <summary>Stores and applies new engine settings, then replans.</summary>
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
{
+6
View File
@@ -45,6 +45,12 @@ public static class EngineSettingKeys
/// <summary>Last completed Giro dei seguiti, Unix milliseconds (it read the stories bar of every followed account).</summary>
public const string LastSweep = "motore.ultimo-giro";
/// <summary>
/// Fingerprint of the collection configuration the suspensions and failure counts refer to (reader vocabulary and
/// target map of the site, as loaded): when it changes they are cleared once.
/// </summary>
public const string CollectionConfiguration = "motore.configurazione-raccolta";
}
/// <summary>
+1
View File
@@ -28,6 +28,7 @@ public sealed record RecentAction(
RecipeStatus.AccountUnreachable => "Non raggiungibile",
RecipeStatus.Cancelled => "Interrotto",
RecipeStatus.Failed => "Errore",
RecipeStatus.NotConfigured => "Da configurare",
_ => null,
};
}
+23 -1
View File
@@ -5,7 +5,9 @@ namespace Febe.Core.Engine;
/// <summary>
/// Consecutive failures per recipe and suspended recipes (spec §6.4: after three «formato non riconosciuto» in a row
/// the recipe is suspended and the interface says so). Persisted in the settings table.
/// the recipe is suspended and the interface says so). Persisted in the settings table. A refusal because the
/// configuration of the site is incomplete (<see cref="RecipeStatus.NotConfigured"/>) is not a failure and never
/// reaches it; a change of that configuration clears it (<see cref="ResetAllAsync"/>).
/// </summary>
internal sealed class RecipeHealth
{
@@ -110,6 +112,26 @@ internal sealed class RecipeHealth
return removed;
}
/// <summary>
/// The collection configuration changed: every suspension and every consecutive failure goes, since they were
/// counted against other files. Returns the recipes that were suspended and whether any failure was counted.
/// </summary>
public async Task<(IReadOnlyList<RecipeKind> Suspended, bool HadFailures)> ResetAllAsync(CancellationToken ct)
{
RecipeKind[] suspended;
bool hadFailures;
lock (_gate)
{
suspended = [.. _suspended.Keys.Order()];
hadFailures = _failures.Count > 0;
_suspended.Clear();
_failures.Clear();
}
await SaveAsync(ct).ConfigureAwait(false);
return (suspended, hadFailures);
}
private Task SaveAsync(CancellationToken ct)
{
string failures;
+191 -17
View File
@@ -14,6 +14,9 @@ namespace Febe.Core.Engine;
/// </summary>
internal sealed class SessionComposer
{
/// <summary>What every line about a recipe the configuration does not let run adds (the runner's included).</summary>
internal const string NotConfiguredTail = " Febe non la avvia finché la configurazione non è completa, e non la conta fra i problemi della ricetta.";
private static readonly TimeSpan DefaultWindow = TimeSpan.FromHours(16);
private readonly EngineServices _s;
@@ -24,6 +27,13 @@ internal sealed class SessionComposer
private readonly Lock _noticeGate = new();
private readonly HashSet<(string Code, long? Account, DateOnly Day)> _notices = [];
// Recipes the configuration of the site does not let run. The configuration is loaded once per process, so what a
// run learned holds until the end, and each recipe is said once (_notConfiguredSaid), not at every session.
private readonly Lock _configurationGate = new();
private readonly Dictionary<RecipeKind, string> _notConfigured = [];
private readonly HashSet<RecipeKind> _notConfiguredSaid = [];
private readonly List<string> _notConfiguredToSay = [];
// The interface calls SyncQueueAsync while a session may be running. A recipe's task is Running in the database
// between its start and its bookkeeping, and then has its successor: under this gate the queue is looked at only
// when every task is pending, in flight (_inFlight) or already replaced by its successor, never in between.
@@ -102,6 +112,7 @@ internal sealed class SessionComposer
// Normally the next sweep will cover them: explicit checks only when no sweep can run, or after a long gap.
var sweepUnavailable = _health.IsSuspended(RecipeKind.FollowingSweep)
|| NotConfiguredReason(RecipeKind.FollowingSweep) is not null
|| !(await _s.Governor.EvaluateBudgetAsync(ActionKind.Home, null, ct).ConfigureAwait(false)).Granted;
var factor = sweepUnavailable ? 1 : 2;
var uncovered = accounts.Values
@@ -184,9 +195,9 @@ internal sealed class SessionComposer
/// <summary>
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks of accounts that may not be
/// contacted are cancelled. Commands of Alberto are left alone, and so is the task of the recipe in progress: its
/// own bookkeeping plans the next one.
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks the account no longer wants,
/// or of accounts that may not be contacted, are cancelled (a «Post singolo» only in the second case). Commands of
/// Alberto are left alone, and so is the task of the recipe in progress: its own bookkeeping plans the next one.
/// </summary>
public async Task<Dictionary<long, Account>> SyncQueueAsync(CancellationToken ct)
{
@@ -212,7 +223,14 @@ internal sealed class SessionComposer
{
var tasks = byAccount[account.Id].Where(t => !t.IsManual).ToList();
var wanted = WantedKinds(account);
foreach (var task in tasks.Where(t => t.Kind != EngineTaskKind.HighlightCheck && !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
// Nothing is planned that the configuration of the site does not let run: it would only be refused.
foreach (var kind in wanted.Keys.Where(k => !CanRun(CheckPolicy.RecipeOf(k))).ToList())
{
wanted.Remove(kind);
}
foreach (var task in tasks.Where(t => !Keeps(t, account, wanted)))
{
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
}
@@ -233,12 +251,13 @@ internal sealed class SessionComposer
}
var anyFollowed = accounts.Values.Any(a => a.IsFollowed && CheckPolicy.IsContactable(a));
var sweepWanted = anyFollowed && CanRun(RecipeKind.FollowingSweep);
var sweeps = pending.Where(t => t.Kind == EngineTaskKind.FollowingSweep && !t.IsManual).ToList();
if (anyFollowed && sweeps.Count == 0)
if (sweepWanted && sweeps.Count == 0)
{
await EnsureSweepTaskAsync(_s.Runtime.NextSessionAt ?? now, ct).ConfigureAwait(false);
}
else if (!anyFollowed)
else if (!sweepWanted)
{
foreach (var sweep in sweeps)
{
@@ -246,9 +265,28 @@ internal sealed class SessionComposer
}
}
await SayNotConfiguredAsync().ConfigureAwait(false);
return accounts;
}
/// <summary>Whether <see cref="SyncQueueLockedAsync"/> leaves a pending planned task of the account where it is.</summary>
private bool Keeps(EngineTask task, Account account, Dictionary<EngineTaskKind, DateTimeOffset?> wanted) => task.Kind switch
{
// One per collection: SyncHighlightsAsync.
EngineTaskKind.HighlightCheck => true,
// Queued by the collection, not by the settings of the account: a series the grid did not give whole, an
// address that expired (spec §6.5 point 5). Nothing would queue it again, so it waits while the recipe cannot
// run, and goes only with an account that may not be contacted.
EngineTaskKind.SinglePost => CheckPolicy.IsContactable(account),
// Flagged by the stories bar: kept until it runs, when it can.
EngineTaskKind.AccountStories when task.Priority >= Options.FlaggedStoriesPriority =>
wanted.ContainsKey(task.Kind) || (CheckPolicy.IsContactable(account) && CanRun(RecipeKind.AccountStories)),
_ => wanted.ContainsKey(task.Kind),
};
/// <summary>
/// «Raccolta in evidenza» (spec §6.3) for an account that wants «Storie in evidenza»: one task per collection the
/// profile check found (payload: its Instagram identifier), due at once for a collection never looked at, then
@@ -270,6 +308,11 @@ internal sealed class SessionComposer
}
}
if (collections.Count > 0 && !CanRun(RecipeKind.Highlight))
{
collections.Clear();
}
foreach (var task in planned.Where(t => t.Payload is null || !collections.ContainsKey(t.Payload)))
{
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
@@ -295,11 +338,73 @@ internal sealed class SessionComposer
private bool InFlight(long accountId, EngineTaskKind kind, string? payload) =>
_inFlight is { } task && task.AccountId == accountId && task.Kind == kind && (payload is null || task.Payload == payload);
/// <summary>The Giro dei seguiti shown in the queue at the next session.</summary>
public Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct) =>
Store.Tasks.EnqueueAsync(
/// <summary>The Giro dei seguiti shown in the queue at the next session (when the configuration lets it run).</summary>
public async Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct)
{
if (!CanRun(RecipeKind.FollowingSweep))
{
await SayNotConfiguredAsync().ConfigureAwait(false);
return;
}
await Store.Tasks.EnqueueAsync(
new EngineTask { Kind = EngineTaskKind.FollowingSweep, DueAt = dueAt, CreatedAt = Clock.Now },
ct);
ct).ConfigureAwait(false);
}
/// <summary>
/// Why the configuration of the site in use (target map, reader vocabulary) does not let <paramref name="kind"/>
/// run, as the runner says or as a run of it said; null when it can.
/// </summary>
internal string? NotConfiguredReason(RecipeKind kind)
{
lock (_configurationGate)
{
if (_notConfigured.TryGetValue(kind, out var known))
{
return known;
}
}
return _runner.NotConfiguredReason(kind);
}
/// <summary>
/// False when the configuration does not let <paramref name="kind"/> run. The first time, its reason is kept to be
/// said in the timeline (<see cref="SayNotConfiguredAsync"/>): once per recipe and process, not at every session.
/// </summary>
private bool CanRun(RecipeKind kind)
{
if (NotConfiguredReason(kind) is not { } reason)
{
return true;
}
lock (_configurationGate)
{
if (_notConfiguredSaid.Add(kind))
{
_notConfiguredToSay.Add(reason);
}
}
return false;
}
private async Task SayNotConfiguredAsync()
{
string[] reasons;
lock (_configurationGate)
{
reasons = [.. _notConfiguredToSay];
_notConfiguredToSay.Clear();
}
foreach (var reason in reasons)
{
await _s.Events.WriteAsync(EventSeverity.Warning, EngineEventCodes.RecipeNotConfigured, reason + NotConfiguredTail, ct: CancellationToken.None).ConfigureAwait(false);
}
}
private Dictionary<EngineTaskKind, DateTimeOffset?> WantedKinds(Account account)
{
@@ -314,7 +419,7 @@ internal sealed class SessionComposer
if (profile)
{
// A profile that is not followed shows its stories only on its page: one visit serves both checks.
wanted[EngineTaskKind.ProfileCheck] = !account.IsFollowed && stories
wanted[EngineTaskKind.ProfileCheck] = VisitServesStories(account)
? Earliest(account.NextProfileCheckAt, account.NextStoriesCheckAt)
: account.NextProfileCheckAt;
}
@@ -336,7 +441,21 @@ internal sealed class SessionComposer
private static DateTimeOffset? Earliest(DateTimeOffset? a, DateTimeOffset? b) =>
a is null || b is null ? null : a < b ? a : b;
private static bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
/// <summary>
/// Whether a visit of the profile also checks its stories, so that it comes at the shorter of the two intervals: a
/// profile that is not followed, with «Storie» on, while the configuration lets «Storie di un account» run. Without
/// it the visit is a plain profile check (story times are left as they are, for when the stories can run).
/// </summary>
private bool VisitServesStories(Account account) =>
!account.IsFollowed && CheckPolicy.WantsStories(account) && CanRun(RecipeKind.AccountStories);
/// <summary>Interval of a visit of the profile (<see cref="CheckPolicy.VisitInterval"/> only when it serves the stories).</summary>
private TimeSpan VisitInterval(Account account, TimeSpan window) =>
VisitServesStories(account)
? CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay)
: CheckPolicy.ProfileCheckInterval(account);
private bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
{
if (task.Kind == EngineTaskKind.AccountStories)
{
@@ -347,8 +466,7 @@ internal sealed class SessionComposer
return task.Kind == EngineTaskKind.ProfileCheck
&& task.AccountId is { } id
&& accounts.TryGetValue(id, out var account)
&& !account.IsFollowed
&& CheckPolicy.WantsStories(account)
&& VisitServesStories(account)
&& (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now);
}
@@ -361,7 +479,7 @@ internal sealed class SessionComposer
{
var interval = task.Kind == EngineTaskKind.AccountStories
? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay)
: CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay);
: VisitInterval(account, window);
items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval)));
}
else
@@ -545,6 +663,15 @@ internal sealed class SessionComposer
var now = Clock.Now;
var flagged = new HashSet<long>(outcome.AccountsWithStories);
// No check is queued that the configuration does not let run: it would only wait, and go at the next session.
// Nothing is lost: until their stories are checked, every sweep flags these accounts again.
if (flagged.Count > 0 && !CanRun(RecipeKind.AccountStories))
{
flagged.Clear();
await SayNotConfiguredAsync().ConfigureAwait(false);
}
foreach (var id in flagged)
{
if (accounts.TryGetValue(id, out var account) && CheckPolicy.IsContactable(account) && CheckPolicy.WantsStories(account))
@@ -615,6 +742,12 @@ internal sealed class SessionComposer
return;
}
if (!CanRun(RecipeKind.Backfill))
{
await SayNotConfiguredAsync().ConfigureAwait(false);
return;
}
var now = Clock.Now;
var zone = Clock.LocalZone;
var today = LocalCalendar.Today(now, zone);
@@ -683,6 +816,25 @@ internal sealed class SessionComposer
return null;
}
if (!CanRun(request.Kind))
{
await SayNotConfiguredAsync().ConfigureAwait(false);
if (task is { IsManual: true })
{
// A command of Alberto that cannot be carried out with these files: dropped, and he is told why.
await Store.Tasks.CancelAsync(task.Id, Clock.Now, CancellationToken.None).ConfigureAwait(false);
await _s.Events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.RecipeNotConfigured,
$"La tua richiesta ({RecipeName(request.Kind)}{Of(account)}) è annullata: {NotConfiguredReason(request.Kind)}",
account?.Id,
state.Context.SessionId,
CancellationToken.None).ConfigureAwait(false);
}
return null;
}
var category = CheckPolicy.CategoryOf(request.Kind);
if (state.Exhausted.Contains(category))
{
@@ -875,6 +1027,26 @@ internal sealed class SessionComposer
$"Formato non riconosciuto durante {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
break;
case RecipeStatus.NotConfigured:
// Not a failure: the files of the site do not let it run. Never counted towards suspension, not tried
// again in this process (the runner has said why); a command of Alberto is dropped, planned work waits.
lock (_configurationGate)
{
_notConfigured.TryAdd(kind, outcome.Message ?? $"«{ItalianText.Capitalize(RecipeName(kind))}» non può girare con la configurazione attuale.");
_notConfiguredSaid.Add(kind);
}
if (task is { IsManual: true })
{
writes.Add(Store.Tasks.CancelAsync(task.Id, now, ct));
}
else if (task is not null)
{
await RequeueAsync(task, "Configurazione incompleta", now).ConfigureAwait(false);
}
break;
case RecipeStatus.AccountUnreachable:
if (task is not null)
{
@@ -955,9 +1127,10 @@ internal sealed class SessionComposer
{
case RecipeKind.ProfileCheck:
{
// A profile not followed is visited at the earlier of its post check and its story check.
// A profile not followed is visited at the earlier of its post check and its story check (while the
// stories can run: otherwise only for its posts).
var next = now + CheckPolicy.NextCheckDelay(_s.Random, CheckPolicy.ProfileCheckInterval(account));
DateTimeOffset? storiesNext = !account.IsFollowed && CheckPolicy.WantsStories(account)
DateTimeOffset? storiesNext = VisitServesStories(account)
? now + CheckPolicy.NextStoryCheckDelay(_s.Random, CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay))
: null;
state.LastVisitNext = storiesNext;
@@ -1164,6 +1337,7 @@ internal sealed class SessionComposer
RecipeStatus.UnrecognizedFormat => "Formato non riconosciuto",
RecipeStatus.AccountUnreachable => "Non raggiungibile",
RecipeStatus.Cancelled => "Interrotto",
RecipeStatus.NotConfigured => "Configurazione della raccolta incompleta",
_ => "Non riuscito",
};
return (title, detail);
+18 -9
View File
@@ -4,6 +4,7 @@ using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
@@ -24,8 +25,8 @@ public static class EngineApi
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) =>
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
{
@@ -78,13 +79,19 @@ public static class EngineApi
endpoints.MapGet("/api/eventi", StreamAsync);
}
/// <summary>The engine as the interface needs it.</summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct)
/// <summary>
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
/// (or there is none in this process) the connection is asked.
/// </summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(monitor);
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(tracker);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(connection);
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
var state = snapshot.Mode switch
@@ -92,9 +99,10 @@ public static class EngineApi
EngineMode.NotConnected => "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
_ => mine is null ? "notConnected" : "connected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
_ => "connected",
};
var connection = state == "notConnected"
var link = state == "notConnected"
? new ConnectionDto(state, null, null, null)
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
@@ -109,7 +117,7 @@ public static class EngineApi
canResume = snapshot.Mode == EngineMode.Paused;
}
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, connection, canResume);
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, link, canResume);
}
/// <summary>
@@ -123,7 +131,8 @@ public static class EngineApi
IFebeStorage storage,
BrowserUseTracker tracker,
LibraryChanges library,
IClock clock)
IClock clock,
IConnectionService connection)
{
ArgumentNullException.ThrowIfNull(context);
var response = context.Response;
@@ -235,7 +244,7 @@ public static class EngineApi
async Task SendEngineAsync()
{
var dto = await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false);
var dto = await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false);
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
}
}