Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 17:32:35 +00:00
1 parent e2c987873b
commit 4fc5a6c0d4
74 files changed
+12689 -13

No files matched your search

@@ -0,0 +1,401 @@
using System.Globalization;
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>A walk through the pages of a profile tab (Storico on the grid, Taggati, Reel).</summary>
private sealed record ProfileWalk(EntryKind Kind, string? TabTarget, string ResumePage, string SettingPrefix)
{
public static readonly ProfileWalk Posts = new(EntryKind.Post, null, SitePages.ProfileFrom, "raccolta.post");
public static readonly ProfileWalk Tagged = new(EntryKind.Tagged, SiteTargets.ProfileTabTagged, SitePages.TaggedFrom, "raccolta.taggati");
public static readonly ProfileWalk Reels = new(EntryKind.Post, SiteTargets.ProfileTabReels, SitePages.ReelsFrom, "raccolta.reel");
public bool IsGrid => TabTarget is null;
public string CursorKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.cursore";
public string CompletedKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.completo";
}
/// <summary>
/// Controllo del profilo (spec §6.3): opens the profile (1 counted action), reads its state, the first page of
/// posts and the list of highlight collections, keeps a copy of the profile picture when it changes, and stops at
/// known content. Pinned posts are recognized and skipped for the stop rule.
/// </summary>
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
account = current;
var profile = FindProfile(reads, account)!;
if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)
&& account.ContentTypes.HasFlag(ContentTypes.Stories))
{
run.AccountsWithStories.Add(account.Id);
}
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
if ((await Writer.SaveProfilePictureAsync(account, profile, run.Ct).ConfigureAwait(false)).Outcome == SaveOutcome.Created)
{
run.NewEntries++;
}
var reachedKnown = false;
foreach (var item in Contents(reads, c => IsOwnedBy(c, account)))
{
var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false);
if (saved.Outcome == SaveOutcome.Created)
{
run.NewEntries++;
run.AccountsWithNewPosts.Add(account.Id);
}
else if (saved.Outcome == SaveOutcome.Known && !item.Pinned)
{
reachedKnown = true; // pinned posts are known but do not stop the check
break;
}
}
var page = LastPage(reads);
if (!reachedKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
{
if (page?.HasMore == true && page.Cursor is { } cursor)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false);
}
else if (page?.HasMore == false)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
}
}
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>
/// Storico, Taggati and Reel (spec §6.3): one page per permit, resuming from the stored point and stopping at the
/// beginning of the profile. The backfill stops while the account has more than 60 files waiting for download or
/// the data budget is used up (the engine checks too, the recipe must stop as well). Once a tab has been walked to
/// the end, later runs only check its first page and stop at known content.
/// </summary>
private async Task<RecipeStatus> WalkAsync(RecipeRun run, ProfileWalk walk)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
if (!CollectionWriter.Wants(account, walk.Kind))
{
throw RecipeRun.Stop(RecipeStatus.Completed, walk.Kind == EntryKind.Tagged
? $"«Post in cui è taggato» è spento per {account.Username}."
: $"Foto e video dei post sono spenti per {account.Username}.");
}
var settings = Env.Storage.Settings;
string? cursor;
bool checkOnly;
if (walk.IsGrid)
{
if (account.BackfillCompletedAt is not null)
{
run.Finished = true;
return RecipeStatus.Completed;
}
cursor = account.BackfillCursor;
checkOnly = false;
}
else
{
cursor = await settings.GetAsync(walk.CursorKey(account.Id), run.Ct).ConfigureAwait(false);
checkOnly = await settings.GetAsync(walk.CompletedKey(account.Id), run.Ct).ConfigureAwait(false) is not null;
if (checkOnly)
{
cursor = null;
}
}
if (!checkOnly)
{
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
}
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun);
var parameters = Values(("username", account.Username));
IReadOnlyList<CapturedRead> reads;
var pages = 0;
if (cursor 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", 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)))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
pages++;
}
else
{
(account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
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))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
pages++;
}
}
var finished = false;
var processed = new HashSet<string>(StringComparer.Ordinal);
while (true)
{
var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, reads, processed, stopAtKnown: checkOnly).ConfigureAwait(false);
var page = LastPage(reads);
if (reachedLimit || page?.HasMore == false)
{
finished = !checkOnly || page?.HasMore == false;
break;
}
if (checkOnly && reachedKnown)
{
break;
}
cursor = page?.Cursor ?? cursor;
await StoreWalkCursorAsync(run, account, walk, cursor).ConfigureAwait(false);
if (pages >= maxPages)
{
break;
}
if (!checkOnly)
{
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
}
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
pages++;
if (reads.Count == 0)
{
break; // nothing came in after the bursts (counted as an empty page)
}
}
if (finished)
{
run.Finished = true;
if (walk.IsGrid)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
else
{
await settings.SetManyAsync(
new Dictionary<string, string?>
{
[walk.CursorKey(account.Id)] = null,
[walk.CompletedKey(account.Id)] = Env.Clock.Now.ToString("O", CultureInfo.InvariantCulture),
},
run.Ct).ConfigureAwait(false);
}
}
return RecipeStatus.Completed;
}
/// <summary>
/// Saves the new items of a walk page. Returns whether known content was met (only meaningful when
/// <paramref name="stopAtKnown"/>) and whether a history limit of the account was reached (from a date, last N posts).
/// </summary>
private async Task<(bool ReachedKnown, bool ReachedLimit)> SaveWalkPageAsync(RecipeRun run, Account account, ProfileWalk walk, IReadOnlyList<CapturedRead> reads, HashSet<string> processed, bool stopAtKnown)
{
var items = Contents(reads, c => walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account))
.Where(c => processed.Add(c.Id))
.ToList();
foreach (var item in items)
{
if (walk.Kind != EntryKind.Tagged && !item.Pinned)
{
if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from)
{
return (false, true);
}
if (account.Limits.Depth == HistoryDepth.LastPosts && account.Limits.LastPosts is { } last
&& await Env.Storage.Entries.ListByAccountAsync(account.Id, new Storage.EntryListOptions { Kind = EntryKind.Post, Limit = last }, run.Ct).ConfigureAwait(false) is { } kept
&& kept.Count >= last)
{
return (false, true);
}
}
var saved = await Writer.SaveAsync(account, item, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false);
if (saved.Outcome == SaveOutcome.Created)
{
run.NewEntries++;
run.AccountsWithNewPosts.Add(account.Id);
}
else if (stopAtKnown && saved.Outcome == SaveOutcome.Known && !item.Pinned)
{
return (true, false);
}
}
return (false, false);
}
private async Task StoreWalkCursorAsync(RecipeRun run, Account account, ProfileWalk walk, string? cursor)
{
if (cursor is null)
{
return;
}
if (walk.IsGrid)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false);
}
else
{
await Env.Storage.Settings.SetAsync(walk.CursorKey(account.Id), cursor, run.Ct).ConfigureAwait(false);
}
}
/// <summary>
/// «Lo storico non corre più veloce dei download» (spec §6.3): stops while the account has more than 60 files waiting
/// or the data budget is used up.
/// </summary>
private async Task EnsureBackfillAllowedAsync(RecipeRun run, Account account)
{
var pending = await Env.Storage.Media.CountPendingDownloadsAsync(account.Id, run.Ct).ConfigureAwait(false);
if (pending > Env.Options.MaxPendingDownloadsForBackfill)
{
await Writer.EventAsync("storico-sospeso", $"Storico di {account.Username} sospeso: {ItalianText.Number(pending)} file aspettano di essere scaricati.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.Denied, $"Storico sospeso: {ItalianText.Number(pending)} file di {account.Username} aspettano di essere scaricati (più di {Env.Options.MaxPendingDownloadsForBackfill}).");
}
if (Env.DataBudget is { } budget && await budget.RemainingTodayAsync(run.Ct).ConfigureAwait(false) <= 0)
{
throw RecipeRun.Stop(RecipeStatus.Denied, "Storico sospeso: il tetto giornaliero dei dati scaricati è raggiunto.");
}
}
/// <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.
/// </summary>
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account)
{
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)
{
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);
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)!;
if (account.InstagramId is { } known && profile.Id != known)
{
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il nome {account.Username} ora appartiene a un altro profilo: l'account resta com'era.");
}
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
if (profile.IsPrivate == true && profile.IsFollowed == false)
{
await MarkUnreachableAsync(run, account, UnreachableReason.PrivateNotFollowed).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"{account.Username} è un profilo privato che non segui: non si tocca.");
}
if (account.State == AccountState.Unreachable)
{
var state = account.BackfillCursor is not null && account.BackfillCompletedAt is null ? AccountState.Backfilling : AccountState.UpToDate;
await Env.Storage.Accounts.SetStateAsync(account.Id, state, Env.Clock.Now, null, run.Ct).ConfigureAwait(false);
await Writer.EventAsync("account-raggiungibile", $"{account.Username} è di nuovo raggiungibile.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
}
return (account, reads);
}
/// <summary>
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Returns the reads of that page (empty when none came).
/// </summary>
private async Task<IReadOnlyList<CapturedRead>> ScrollForPageAsync(RecipeRun run, Func<ReadResult, bool> expected)
{
var mark = Env.Capture.Mark();
for (var burst = 0; burst < Env.Options.BurstsPerPage; burst++)
{
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
run.ThrowIfSignal();
if (Env.Capture.Pending > 0 || Env.Capture.Since(mark).Count > 0)
{
await run.SettleAsync().ConfigureAwait(false);
}
var reads = Env.Capture.Since(mark);
if (reads.Any(r => r.Result.Shape != ReadShape.Recognized || expected(r.Result)))
{
return run.Judge(reads, expected, null)
? reads.Where(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)).ToList()
: [];
}
}
run.Judge([], expected, null);
return [];
}
/// <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();
}
/// <summary>Italian formatting for messages: thousands with a dot (spec: «48.212 elementi»).</summary>
public static class ItalianText
{
public static string Number(long value)
{
var digits = Math.Abs(value).ToString(CultureInfo.InvariantCulture);
var groups = new List<string>();
for (var end = digits.Length; end > 0; end -= 3)
{
groups.Insert(0, digits[Math.Max(0, end - 3)..end]);
}
return (value < 0 ? "-" : string.Empty) + string.Join('.', groups);
}
}