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
{
///
/// 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».
///
private async Task 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;
}
///
/// 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.
///
private static bool HomeArrived(ReadResult result) =>
result.Contents.Count > 0 || result.Profiles.Any(p => p.LatestStoryAt is not null) || result.Page is not null;
///
/// The pagination of the feed: from the answer that brought the most posts not met before (:
/// 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).
///
private static PageInfo? FeedPage(IReadOnlyList reads, IReadOnlySet? 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);
/// Saves the posts not processed yet; returns true once known content has been met.
private Task ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList 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 ProcessSweepItemsAsync(RecipeRun run, IReadOnlyList reads, IReadOnlyList 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;
}
///
/// 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).
///
private async Task EnsureMineAsync(IReadOnlyList 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);
}
}