using Febe.Core.Abstractions; using Febe.Core.Collection.Readers; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; namespace Febe.Core.Collection.Recipes; public sealed partial class RecipeRunner { /// /// 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 /// §7.7 (one StoryView permit per story shown) and saves only the stories actually shown. After the last story it /// closes the viewer before it moves on by itself; a story of another account is not saved: the viewer is closed /// and the event recorded. /// private async Task AccountStoriesAsync(RecipeRun run) { var account = await LoadAccountAsync(run).ConfigureAwait(false); if (!CollectionWriter.Wants(account, EntryKind.Story)) { throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie» è spento per {account.Username}."); } await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false); if (_lastKind == RecipeKind.AccountStories) { await Env.Driver.WaitAsync(StoryTimings.BetweenAccounts(Env.Random, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false); } var parameters = Values(("username", account.Username)); var fromBar = Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory) && Env.SiteMap.Match(SitePages.Home, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is not null && (await run.FindAsync(SiteTargets.HomeStory, parameters).ConfigureAwait(false)).Found; if (!fromBar) { 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 => 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)!; 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 (!(await run.FindAsync(SiteTargets.ProfileStoryRing, parameters).ConfigureAwait(false)).Found) { await StoriesCheckedAsync(account, run).ConfigureAwait(false); return RecipeStatus.Completed; // no active stories: nothing to open } } var target = fromBar ? SiteTargets.HomeStory : SiteTargets.ProfileStoryRing; await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false); var viewerMark = Env.Capture.Mark(); 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 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); if (saved.Outcome == SaveOutcome.Created) { run.NewEntries++; } } } await StoriesCheckedAsync(account, run).ConfigureAwait(false); if (watched.Stop is { } stop) { throw stop; } return RecipeStatus.Completed; } /// /// Raccolta in evidenza (spec §6.3): opens the profile and the collection, watches its contents one by one (one /// 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). /// private async Task HighlightAsync(RecipeRun run) { var account = await LoadAccountAsync(run).ConfigureAwait(false); if (run.Request.HighlightId is not { Length: > 0 } highlightId) { throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta."); } if (!CollectionWriter.Wants(account, EntryKind.Highlight)) { throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}."); } 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))) { 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 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); 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."); } 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 watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false); var shown = watched.Shown; var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId); var ordered = new List(); foreach (var id in shown) { if (items.FirstOrDefault(i => i.Id == id) is not { } item) { continue; } var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false); if (created) { run.NewEntries++; } if (entry is not null) { ordered.Add(entry.Id); } } 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; } return RecipeStatus.Completed; } private async Task EnsureStoryBudgetAsync(RecipeRun run, Account account) { if (Env.Budget is { } budget) { var left = await budget.RemainingAsync(ActionKind.StoryView, account.Id, run.Ct).ConfigureAwait(false); if (left < Env.Options.MinStoryBudget) { throw RecipeRun.Stop(RecipeStatus.Denied, $"Il tetto delle storie ne consente ancora {left}: ne servono almeno {Env.Options.MinStoryBudget} per aprirle."); } } } /// Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed. private async Task> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary parameters, string viewerPage) { 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; } if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found) { break; } } throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non si è aperto dopo il clic."); } /// /// Watches a viewer that shows : 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 , 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. /// private async Task WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary opened) { var shown = new List(); var counted = new HashSet(StringComparer.Ordinal); var pendingPermit = true; // asked before the click that opened the viewer var position = opened; var stuck = 0; try { while (true) { run.ThrowIfSignal(); if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase)) { 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); } var id = position["id"]; if (counted.Add(id)) { 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); } // 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; } } catch (RecipeStopException stop) { if (stop.Status != RecipeStatus.StoppedBySignal) { // 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) { } } return new ViewerResult(shown, stop); } } /// What a viewer showed, and why it stopped early (the caller saves what was shown, then stops). private sealed record ViewerResult(List Shown, RecipeStopException? Stop); private static bool SamePosition(IReadOnlyDictionary a, IReadOnlyDictionary b) => a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase)); /// The items of the viewer for the owner, as received (waits for them the first time). private async Task> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account) { Func belongs = viewerPage == SitePages.StoryViewer ? c => IsOwnedBy(c, account) : c => c.HighlightId == owner; var present = Contents(Env.Capture.Since(mark), belongs); if (present.Count > 0) { return present; } var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false); run.Judge(reads, r => r.Contents.Any(belongs), null); return Contents(reads, belongs); } /// Waits until the address shows a viewer item different from ; null when the viewer is gone. private async Task?> WaitForViewerAsync(RecipeRun run, string viewerPage, IReadOnlyDictionary? previous) { var deadline = Env.Clock.Now + Env.Options.ViewerTimeout; while (true) { run.ThrowIfSignal(); var match = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)); if (match is not null && (previous is null || !SamePosition(match, previous))) { return match; } if (previous is not null && match is null) { return null; } if (Env.Clock.Now >= deadline) { return previous is null ? null : match; } await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false); } } /// Closes the viewer with its command and waits until it is gone. private async Task CloseViewerAsync(RecipeRun run, string viewerPage) { if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null) { return; } var click = await Env.Driver.ClickAsync(SiteTargets.ViewerClose, null, run.Ct).ConfigureAwait(false); if (!click.Found) { run.ThrowIfSignal(); throw RecipeRun.Stop(RecipeStatus.TargetNotFound, click.Message); } var deadline = Env.Clock.Now + Env.Options.ViewerTimeout; while (Env.Clock.Now < deadline) { if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null) { return; } 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 MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason) { if (account.State == AccountState.Unreachable && account.UnreachableReason == reason) { return; } await Env.Storage.Accounts.SetStateAsync(account.Id, AccountState.Unreachable, Env.Clock.Now, reason, run.Ct).ConfigureAwait(false); var why = reason switch { UnreachableReason.PrivateNotFollowed => "è un profilo privato che non segui", UnreachableReason.NotFound => "il profilo non esiste più", UnreachableReason.Renamed => "il nome ora appartiene a un altro profilo", _ => "non è raggiungibile", }; await Writer.EventAsync("account-non-raggiungibile", $"{account.Username} non è raggiungibile: {why}.", EventSeverity.Warning, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); } 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)); }