Files
Febe/src/Febe.Core/Collection/Recipes/RecipeRunner.Sweep.cs
T
Alby96andClaude Opus 5.5 31bbbf8bb7
verifica / controlli (push) Successful in 2m10s
verifica / prove (push) Successful in 26m16s
verifica / installatore (push) Successful in 5m39s
verifica / immagine (push) Successful in 28m39s
Instagram: Febe legge le risposte vere (campioni dal HAR del 21/10)
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>
2026-10-25 14:22:16 +01:00

163 lines
7.9 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>
/// Giro dei seguiti (spec §6.3): opens the home (1 counted action), reads the stories bar, and scrolls the recent
/// posts of followed profiles until it meets known content, with at most 8 bursts. Posts that arrive with complete
/// data are saved at once; incomplete series are saved with what arrived and completed by «Post singolo».
/// </summary>
private async Task<RecipeStatus> FollowingSweepAsync(RecipeRun run)
{
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
// 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 = 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++)
{
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
run.ThrowIfSignal();
await run.SettleAsync().ConfigureAwait(false);
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 = 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)
{
var items = Contents(reads);
var fresh = items.Skip(processed).ToList();
processed = items.Count;
return ProcessSweepItemsAsync(run, reads, fresh);
}
private async Task<bool> ProcessSweepItemsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, IReadOnlyList<ContentItem> items)
{
await EnsureMineAsync(reads, run).ConfigureAwait(false);
// Stories bar (H2): followed accounts whose latest story is newer than their last stories check.
foreach (var profile in reads.SelectMany(r => r.Result.Profiles).Where(p => p.LatestStoryAt is not null))
{
var account = await Writer.ObserveProfileAsync(profile, run.Session.SessionId, run.Ct).ConfigureAwait(false);
if (account is { State: not (AccountState.ArchiveOnly or AccountState.Unreachable) }
&& account.ContentTypes.HasFlag(ContentTypes.Stories)
&& profile.LatestStoryAt > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue))
{
run.AccountsWithStories.Add(account.Id);
}
}
var sawKnown = false;
foreach (var item in items)
{
if (item.Owner is null || !IsPostLike(item))
{
continue; // stories received in advance with the bar are saved only when shown, by «Storie di un account»
}
var account = await Writer.ObserveProfileAsync(item.Owner, run.Session.SessionId, run.Ct).ConfigureAwait(false);
if (account is null || account.State is AccountState.ArchiveOnly or AccountState.Unreachable || account.Id == 0)
{
continue; // not an account Febe keeps
}
var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false);
switch (saved.Outcome)
{
case SaveOutcome.Created:
run.NewEntries++;
run.AccountsWithNewPosts.Add(account.Id);
break;
case SaveOutcome.Known when !item.Pinned:
sawKnown = true;
break;
}
}
return sawKnown;
}
/// <summary>
/// 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)
{
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;
}
var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false);
if (mine is not null || await Env.Storage.Accounts.FindByInstagramIdAsync(viewer.Id, run.Ct).ConfigureAwait(false) is not null)
{
return;
}
var account = Account.Create(viewer.Username, StartingPoint.EverythingAndKeepUpdated, Env.Clock.Now, Env.Clock.LocalZone, isMine: true) with
{
InstagramId = viewer.Id,
};
await Env.Storage.Accounts.AddAsync(account, run.Ct).ConfigureAwait(false);
await Writer.EventAsync("account-collegato", $"Account collegato riconosciuto dai dati della pagina: {viewer.Username} («Tu»).", EventSeverity.Info, null, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
}