using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Browser.TestSupport;
using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
///
/// The story and highlight viewers on the scripted site, with and without the item shown in the address. Instagram's
/// highlight viewer stays on «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026): the recipe
/// counts the items against the list the page received. The test site writes the item in the address
/// («/storie/{username}/{id}/»): the recipe keeps reading it from there.
///
[TestClass]
public sealed class ViewerAddressTests
{
private const string SummerId = "17900000000000001";
private const string TravelId = "17900000000000002";
[TestMethod]
[DataRow(SummerId)]
[DataRow("highlight:" + SummerId)]
public async Task AHighlightViewerWithoutTheItemInTheAddressSavesTheItemsShownAndClosesAfterTheLast(string requested)
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
var (_, account) = await bed.AddCollectionsAsync();
var outcome = await bed.RunHighlightAsync(account, requested);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(4, outcome.NewEntries);
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, bed.Viewer.Seen, "Closed after the last item: never on to the next collection.");
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "Every item shown, in order.");
Assert.AreEqual(0, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Highlight })).Count(e => e.InstagramId!.StartsWith('v')), "The other collection received with it is not saved.");
Assert.AreEqual(3, bed.Viewer.NextClicks);
Assert.AreEqual(1, bed.Viewer.CloseClicks);
Assert.AreEqual(4, bed.Bed.Governor.Granted(ActionKind.StoryView), "One permit per item shown.");
bed.AssertNoItemCameOnScreenBeforeItsPermit();
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None), "Back on the profile.");
Assert.AreEqual("/evidenza/" + SummerId + "/", bed.Viewer.OpenedAt, "The collection is clicked by the identifier of its address.");
}
[TestMethod]
public async Task WithoutTheItemInTheAddressAVideoIsLeftBeforeItEndsAlsoWhenTheWatchWouldLastLonger()
{
// Mood × pace 1.2 and a draw near the top: the watch of a ten-second video would last 11.3 s, past its end but
// short of the old three-second margin. Clicked then, «next» would have skipped «p1».
var random = new FixedRandom(0.9);
var watch = StoryTimings.Watch(random, TimeSpan.FromSeconds(10), 1.2);
Assert.IsTrue(watch > TimeSpan.FromSeconds(10) && watch < TimeSpan.FromSeconds(13), $"Watch of {watch}.");
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, waitMultiplier: 1.2, random: random);
var (_, account) = await bed.AddCollectionsAsync([new("v0", Video: TimeSpan.FromSeconds(10)), new("p1"), new("p2")]);
var outcome = await bed.RunHighlightAsync(account, SummerId);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "v0", "p1", "p2" }, bed.Viewer.Seen, "Never on to the next collection.");
CollectionAssert.AreEqual(new[] { "v0", "p1", "p2" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "Every item shown, in order.");
Assert.AreEqual(2, bed.Viewer.NextClicks, "«next» on the video before it ended, then on «p1».");
Assert.AreEqual(1, bed.Viewer.CloseClicks);
bed.AssertNoItemCameOnScreenBeforeItsPermit();
Assert.IsFalse((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-altro-account"));
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task AnUnexpectedErrorInTheViewerClosesItAndKeepsWhatWasShown(bool itemInAddress)
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
var (_, account) = await bed.AddCollectionsAsync();
bed.Viewer.FailAtNextClick = 2;
var outcome = await bed.RunHighlightAsync(account, SummerId);
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, outcome.Message);
StringAssert.Contains(outcome.Message, "Errore imprevisto");
StringAssert.Contains(outcome.Message, nameof(InvalidOperationException));
Assert.AreEqual(1, bed.Viewer.CloseClicks, "The viewer is closed: left open it would move on by itself.");
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
CollectionAssert.AreEqual(new[] { "e0", "e1" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "The two items shown before the error are saved.");
Assert.IsTrue((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "ricetta-fallita"));
}
[TestMethod]
[DataRow(2, DisplayName = "The video ended: the viewer moved on by itself")]
[DataRow(30, DisplayName = "The video stalled: the viewer is still on it")]
public async Task WithoutTheItemInTheAddressAVideoThatMayHaveEndedIsNeverClickedPastNorCountedAsOver(int onScreenSeconds)
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, spacing: TimeSpan.FromSeconds(6));
var nadia = bed.Bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
var account = await bed.Bed.AddAccountAsync(nadia);
nadia.HighlightsWithItems.Add(("highlight:" + SummerId, "Estate", []));
var video = new ViewerItem("v0", TimeSpan.FromSeconds(onScreenSeconds), Video: TimeSpan.FromSeconds(2));
bed.Viewer.Add(ViewerAnswers.Highlight(nadia, SummerId, "Estate", [video, new ViewerItem("p1"), new ViewerItem("p2")]));
// The Governor makes the permit for «p1» wait 6 s: the two-second video may be over by then, with the viewer on
// «p1» by itself, or it may have stalled. The address does not say which: closed, without clicking «next».
var outcome = await bed.RunHighlightAsync(account, SummerId);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
var saved = (await bed.ItemsOfAsync(account, SummerId)).ToArray();
CollectionAssert.AreEqual(new[] { "v0" }, saved, "Only what was surely shown under its permit.");
CollectionAssert.IsSubsetOf(saved, bed.Viewer.Seen, "Nothing saved that was not on screen.");
Assert.AreEqual(0, bed.Viewer.NextClicks, "No click on a video that may have ended: it would have skipped «p1».");
Assert.AreEqual(1, bed.Viewer.CloseClicks);
Assert.AreEqual(2, bed.Bed.Governor.Granted(ActionKind.StoryView), "For «v0», and for «p1» before it could come on screen.");
Assert.IsTrue((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-chiuso-prima"), "The early close is recorded.");
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
}
[TestMethod]
public async Task WithoutTheItemInTheAddressOnlyStoriesAreCountedAsStories()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
var account = await bed.Bed.AddAccountAsync(marta);
// A post of the account arrives with the stories, ahead of them: counted by position it would take the place of «s0».
var post = ScriptedSite.Post(marta, new ScriptedPost("post1", bed.Bed.Clock.Now.AddDays(-1)));
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1")], post));
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "s0", "s1" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
Assert.AreEqual(0, (await bed.Bed.PostIdsAsync(account.Id)).Count, "The post received with the viewer is not saved by it.");
Assert.AreEqual(1, bed.Viewer.NextClicks);
Assert.AreEqual(1, bed.Viewer.CloseClicks);
Assert.AreEqual("/profilo/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
}
[TestMethod]
public async Task WithTheItemInTheAddressStoriesAreFollowedByTheAddressAsBefore()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
var account = await bed.Bed.AddAccountAsync(marta);
await bed.Bed.AddAccountAsync(bed.Bed.Site.Add(new ScriptedAccount("2001", "luca.prova")));
// «s1» stays on screen half a second: the viewer moves on to «s2» by itself while the recipe watches.
var stories = ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1", TimeSpan.FromMilliseconds(500)), new ViewerItem("s2")]);
bed.Viewer.Add(stories with { Next = "luca.prova" });
bed.Viewer.Add(ViewerAnswers.Stories(bed.Bed.Site.Accounts["luca.prova"], [new ViewerItem("l0")]));
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(3, outcome.NewEntries);
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, bed.Viewer.Seen, "Closed after the last story, before the next account.");
Assert.AreEqual(1, bed.Viewer.NextClicks, "From «s0» to «s1»; «s2» came by itself, and the address said so.");
Assert.AreEqual(3, bed.Bed.Governor.Granted(ActionKind.StoryView), "One permit per story shown.");
bed.AssertNoItemCameOnScreenBeforeItsPermit(); // «s2» too, that came by itself: its permit was asked on «s1»
Assert.AreEqual(1, bed.Viewer.CloseClicks);
Assert.AreEqual("/profilo/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
}
[TestMethod]
public async Task WithTheItemInTheAddressAPostArrivingAfterTheStoriesDoesNotHideTheLastOne()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
var account = await bed.Bed.AddAccountAsync(marta);
await bed.Bed.AddAccountAsync(bed.Bed.Site.Add(new ScriptedAccount("2001", "luca.prova")));
// The grid of the profile comes in an answer of its own, after the viewer opened: a post of the account.
var post = ScriptedSite.Post(marta, new ScriptedPost("post1", bed.Bed.Clock.Now.AddDays(-1)));
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]) with
{
Next = "luca.prova",
Then = new JsonObject { ["contenuti"] = new JsonArray(post) },
});
bed.Viewer.Add(ViewerAnswers.Stories(bed.Bed.Site.Accounts["luca.prova"], [new ViewerItem("l0")]));
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, bed.Viewer.Seen, "Closed after «s2», the last story: never on to the next account.");
Assert.AreEqual(2, bed.Viewer.NextClicks);
Assert.AreEqual(1, bed.Viewer.CloseClicks);
Assert.AreEqual(3, bed.Bed.Governor.Granted(ActionKind.StoryView), "No permit for a story after the last one.");
Assert.IsFalse((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-altro-account"));
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task AViewerThatDoesNotCloseStopsTheRunAsATargetNotFoundAndKeepsWhatWasShown(bool itemInAddress)
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
var (_, account) = await bed.AddCollectionsAsync();
bed.Viewer.IgnoresClose = true; // «viewer-close» is found, and the viewer stays open
var outcome = await bed.RunHighlightAsync(account, SummerId);
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
StringAssert.Contains(outcome.Message, SiteTargets.ViewerClose);
Assert.AreEqual(2, bed.Viewer.CloseClicks, "One more try on the way out.");
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "What was shown is saved all the same.");
}
[TestMethod]
public async Task ARefusedPermitWithAViewerThatDoesNotCloseStopsAsATargetNotFound()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, storyGrants: 2);
var (_, account) = await bed.AddCollectionsAsync();
bed.Viewer.IgnoresClose = true;
// Refused on «e1», the viewer is closed at once, but it stays open: the run says so, as a target not found
// (the session stops and puts the page at rest), not as a refusal (it would go on with the viewer open).
var outcome = await bed.RunHighlightAsync(account, SummerId);
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
StringAssert.Contains(outcome.Message, "Tetto delle storie raggiunto (prova).");
StringAssert.Contains(outcome.Message, SiteTargets.ViewerClose);
Assert.AreEqual(1, bed.Viewer.CloseClicks);
CollectionAssert.AreEqual(new[] { "e0", "e1" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray());
}
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task ACancellationWhileWatchingKeepsWhatWasShownAndThenGoesOn(bool itemInAddress)
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
var (_, account) = await bed.AddCollectionsAsync();
using var cancel = new CancellationTokenSource();
bed.Viewer.CancelAtWait = (3, cancel); // while watching «e2», as a pause or a signal that closes the session would
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: SummerId), cancel.Token);
Assert.AreEqual(RecipeStatus.Cancelled, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "The three items shown are saved.");
Assert.AreEqual(0, bed.Viewer.CloseClicks, "A cancelled run leaves the page as it is.");
}
[TestMethod]
public async Task ACancellationWhileWatchingStoriesKeepsTheStoriesShown()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
var account = await bed.Bed.AddAccountAsync(marta);
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]));
using var cancel = new CancellationTokenSource();
bed.Viewer.CancelAtWait = (2, cancel); // while watching «s1»
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id), cancel.Token);
Assert.AreEqual(RecipeStatus.Cancelled, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "s0", "s1" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
Assert.AreEqual(0, bed.Viewer.CloseClicks);
}
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public async Task AClickThatOpensAnAddressTheMapDoesNotTakeForTheViewerIsClosedBeforeTheRecipeStops(bool closes)
{
// The map wants the story in the address; the site opens the viewer without it.
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true, siteWritesItem: false);
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
var account = await bed.Bed.AddAccountAsync(marta);
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1")]));
bed.Viewer.IgnoresClose = !closes;
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
Assert.AreEqual(closes ? RecipeStatus.Failed : RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "s0" }, bed.Viewer.Seen, "No second click on what opened.");
Assert.AreEqual(1, bed.Viewer.CloseClicks, "What opened is closed like a viewer.");
Assert.AreEqual(closes ? "/profilo/marta.prova/" : "/storie/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
Assert.AreEqual(0, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Count);
}
[TestMethod]
public async Task WithTheItemInTheAddressTheViewerIsFollowedFromTheItemItOpensOn()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
var account = await bed.Bed.AddAccountAsync(marta);
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]));
bed.Viewer.StartAt = 1; // a site that opens on the first story not seen yet
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
CollectionAssert.AreEqual(new[] { "s1", "s2" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray(), "«s0» was received, never shown.");
}
[TestMethod]
public async Task ProfilesSuggestedBesideTheProfileAreNotItsPage()
{
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
var account = await bed.Bed.AddAccountAsync(new ScriptedAccount("2003", "nadia.prova")); // its profile never arrives
bed.Viewer.AlongsideEveryPage = new JsonObject
{
["suggeriti"] = new JsonArray(ScriptedSite.Profile(new ScriptedAccount("4001", "altro.prova")), ScriptedSite.Profile(new ScriptedAccount("4002", "ancora.prova"))),
};
var outcome = await bed.RunHighlightAsync(account, SummerId);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message, "An empty page, not «the collection is not on the profile».");
Assert.AreEqual(0, bed.Bed.Governor.Granted(ActionKind.StoryView));
Assert.IsNull(bed.Viewer.OpenedAt);
}
}
/// What the viewer of the scripted site receives, in the format of the test site (lettori.prova.json).
internal static class ViewerAnswers
{
/// A collection of as the viewer receives it: «highlight:» before the identifier, as Instagram writes it.
public static Viewable Highlight(ScriptedAccount owner, string id, string title, IReadOnlyList items, params Viewable[] alsoReceived)
{
var node = HighlightNode(owner, id, title, items);
var all = new JsonArray(node);
foreach (var other in alsoReceived)
{
all.Add(HighlightNode(owner, other.Key, other.Title, other.Items));
}
return new Viewable("evidenza", id, title, items, new JsonObject { ["raccolte"] = all });
}
private static JsonObject HighlightNode(ScriptedAccount owner, string id, string title, IReadOnlyList items) => new()
{
["numero"] = "highlight:" + id,
["titolo"] = title,
["autore"] = ScriptedSite.Lite(owner),
["contenuti"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: false))]),
};
/// The stories of as the viewer receives them, after when given.
public static Viewable Stories(ScriptedAccount owner, IReadOnlyList items, JsonObject? before = null)
{
var body = new JsonObject();
if (before is not null)
{
body["contenuti"] = new JsonArray(before);
}
body["storie"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: true))]);
body["autore"] = ScriptedSite.Lite(owner);
return new Viewable("storie", owner.Username, owner.Username, items, body);
}
private static JsonObject Item(ScriptedAccount owner, ViewerItem item, bool expires)
{
var takenAt = new DateTimeOffset(2026, 10, 13, 6, 0, 0, TimeSpan.Zero);
var node = ScriptedSite.Post(owner, new ScriptedPost(item.Id, takenAt)
{
ExpiresAt = expires ? takenAt.AddHours(24) : null,
Url = $"https://cdn.prova/m/{item.Id}.jpg",
});
if (item.Video is { } duration)
{
node["filmati"] = new JsonArray(new JsonObject { ["indirizzo"] = $"https://cdn.prova/m/{item.Id}.mp4", ["larghezza"] = 720, ["altezza"] = 1280, ["audio"] = true });
node["durata"] = duration.TotalSeconds;
}
return node;
}
}
/// An item of a viewer: how long it stays on screen before the viewer moves on by itself, and its video length.
internal sealed record ViewerItem(string Id, TimeSpan? OnScreen = null, TimeSpan? Video = null);
/// What a viewer shows for one owner (an account, or a collection), and what the page receives when it opens.
/// «storie» or «evidenza», the first segment of its address.
/// The owner in the address: user name, or identifier of the collection.
internal sealed record Viewable(string Kind, string Key, string Title, IReadOnlyList Items, JsonObject Body)
{
/// The owner the viewer moves on to by itself after the last item (another account, another collection).
public string? Next { get; init; }
/// An answer of its own the page receives right after (the grid of the profile, say).
public JsonObject? Then { get; init; }
}
///
/// The scripted site with a viewer, as a decorator: clicking a story ring or a collection opens its viewer on the first
/// item (or on ) and hands the capture what the page receives; «viewer-next» moves one item on; an
/// item moves on by itself after its time on screen (time is the virtual clock, which the waits move on); after the last
/// item the viewer goes on to or closes; «viewer-close» goes back to the page it was opened
/// from. The address carries the item shown only with .
///
internal sealed class ViewerSite(ScriptedSite site, CaptureCollector capture, VirtualClock clock) : IPageDriver
{
private static readonly TimeSpan PhotoOnScreen = TimeSpan.FromMinutes(1); // long: only clicks move a photo on, unless a test says so
private readonly Dictionary _viewables = new(StringComparer.OrdinalIgnoreCase);
private Viewable? _open;
private int _index;
private DateTimeOffset _since;
private int _responses;
private int _waits;
public bool AddressWithItem { get; init; }
/// The item the viewer opens on (a site that resumes from the first item not seen).
public int StartAt { get; set; }
/// The click on «next» (from 1) that throws, as a broken connection with the browser would.
public int? FailAtNextClick { get; set; }
/// «viewer-close» is found, but the viewer stays open (a click that lands on the wrong element).
public bool IgnoresClose { get; set; }
/// The wait (from 1) during which the source is cancelled: the wait then throws, as would.
public (int Wait, CancellationTokenSource Source)? CancelAtWait { get; set; }
/// An answer unrelated to the account (suggested profiles) that arrives with every page opened.
public JsonObject? AlongsideEveryPage { get; set; }
/// The items that came on screen, in order.
public List Seen { get; } = [];
public int NextClicks { get; private set; }
public int CloseClicks { get; private set; }
/// The address of the first viewer opened.
public string? OpenedAt { get; private set; }
public double WaitMultiplier { get; init; } = 1;
public void Add(Viewable viewable) => _viewables[viewable.Kind + "/" + viewable.Key] = viewable;
/// How many items have come on screen until now.
public int OnScreenSoFar()
{
Tick();
return Seen.Count;
}
public void BeginSession(double mood) => site.BeginSession(mood);
public async Task OpenAsync(string path, CancellationToken ct)
{
_open = null;
var load = await site.OpenAsync(path, ct);
if (AlongsideEveryPage is { } other)
{
Deliver(other);
}
return load;
}
public Task CurrentPathAsync(CancellationToken ct)
{
Tick();
if (_open is not { } open)
{
return Task.FromResult(site.CurrentPath);
}
var path = "/" + open.Kind + "/" + Uri.EscapeDataString(open.Key) + "/";
return Task.FromResult(AddressWithItem ? path + Uri.EscapeDataString(open.Items[_index].Id) + "/" : path);
}
public Task IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
public Task FindAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct) => site.FindAsync(target, parameters, ct);
public async Task ClickAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct)
{
Tick();
var check = await site.FindAsync(target, parameters, ct);
if (!check.Found)
{
return check;
}
var clicked = new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato.");
switch (target)
{
case SiteTargets.ProfileHighlight:
return Show("evidenza/" + parameters!["id"]) ? clicked : NotFound(target);
case SiteTargets.ProfileStoryRing or SiteTargets.HomeStory:
return Show("storie/" + parameters!["username"]) ? clicked : NotFound(target);
case SiteTargets.ViewerNext when _open is not null:
if (++NextClicks == FailAtNextClick)
{
throw new InvalidOperationException("Il collegamento con il navigatore si è interrotto (prova).");
}
MoveOn(clock.Now);
return clicked;
case SiteTargets.ViewerClose when _open is not null:
CloseClicks++;
if (!IgnoresClose)
{
_open = null;
}
return clicked;
default:
return clicked;
}
}
public Task ScrollBurstAsync(CancellationToken ct) => site.ScrollBurstAsync(ct);
public Task WaitAfterLoadAsync(CancellationToken ct) => site.WaitAfterLoadAsync(ct);
public Task WaitAsync(TimeSpan duration, CancellationToken ct)
{
clock.Advance(duration);
if (CancelAtWait is { } cancel && ++_waits == cancel.Wait)
{
cancel.Source.Cancel();
}
return ct.IsCancellationRequested ? Task.FromCanceled(ct) : Task.CompletedTask;
}
public Task MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
public Task HasSessionCookieAsync(CancellationToken ct) => Task.FromResult(true);
public Task RestAsync(CancellationToken ct)
{
_open = null;
return site.RestAsync(ct);
}
private static TargetCheck NotFound(string target) => new(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato.");
private static TimeSpan OnScreen(ViewerItem item) => item.OnScreen ?? item.Video ?? PhotoOnScreen;
private bool Show(string key)
{
if (!_viewables.TryGetValue(key, out var viewable))
{
return false;
}
Open(viewable, StartAt, clock.Now);
OpenedAt ??= "/" + viewable.Kind + "/" + viewable.Key + "/";
return true;
}
private void Open(Viewable viewable, int index, DateTimeOffset since)
{
_open = viewable;
_index = index;
_since = since;
Seen.Add(viewable.Items[index].Id);
Deliver(viewable.Body);
if (viewable.Then is { } then)
{
Deliver(then);
}
}
/// The viewer moves on by itself when an item has been on screen for its time.
private void Tick()
{
while (_open is { } open && clock.Now - _since >= OnScreen(open.Items[_index]))
{
MoveOn(_since + OnScreen(open.Items[_index]));
}
}
private void MoveOn(DateTimeOffset at)
{
var open = _open!;
if (_index + 1 < open.Items.Count)
{
_index++;
_since = at;
Seen.Add(open.Items[_index].Id);
return;
}
if (open.Next is { } next && _viewables.TryGetValue(open.Kind + "/" + next, out var following))
{
Open(following, 0, at);
return;
}
_open = null; // after the last item, with nothing after it, the viewer closes by itself
}
private void Deliver(JsonObject body)
{
var id = "v" + Interlocked.Increment(ref _responses).ToString(CultureInfo.InvariantCulture);
using var document = JsonDocument.Parse(body.ToJsonString());
capture.Accept(new ResponseDescriptor(id, HostKind.Site, "http://prova.local/dati", "prova.local", "/dati", 200, "application/json", "Fetch", false, clock.Now), document.RootElement);
}
}
/// A scripted bed whose page has a viewer; the Governor can make every story permit wait, like its minimum spacing.
internal sealed class ViewerBed : IAsyncDisposable
{
private ViewerBed(ScriptedBed bed, ViewerSite viewer, PermitWatcher permits, RecipeRunner runner)
{
Bed = bed;
Viewer = viewer;
Permits = permits;
Runner = runner;
}
public ScriptedBed Bed { get; }
public ViewerSite Viewer { get; }
/// What was on screen at each story permit granted.
public PermitWatcher Permits { get; }
public RecipeRunner Runner { get; }
/// Whether the map's viewer addresses carry the item shown.
/// Every story permit first waits this long (the Governor's minimum spacing).
/// Mood × pace of the page driver.
/// The random source of the recipes (a seeded one by default).
/// Whether the site writes the item in the address (as the map says, by default).
/// After this many story permits the Governor refuses, while the budget says there is room.
public static async Task CreateAsync(bool itemInAddress, TimeSpan? spacing = null, double waitMultiplier = 1, IRandomSource? random = null, bool? siteWritesItem = null, int? storyGrants = null)
{
var pages = ScriptedBed.TestSitePages.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
if (!itemInAddress)
{
pages[SitePages.StoryViewer] = "/storie/{username}/";
pages[SitePages.HighlightViewer] = "/evidenza/{highlight}/";
}
var bed = await ScriptedBed.CreateAsync(new SiteMap("prova", pages, SiteTargets.All, SiteTargets.All));
var viewer = new ViewerSite(bed.Site, bed.Runner.Env.Capture, bed.Clock) { AddressWithItem = siteWritesItem ?? itemInAddress, WaitMultiplier = waitMultiplier };
IGovernor governor = storyGrants is { } grants ? new StoryGrantsGovernor(bed.Governor, grants) : bed.Governor;
governor = spacing is { } wait ? new SpacedGovernor(governor, bed.Clock, wait) : governor;
var permits = new PermitWatcher(governor, viewer);
return new ViewerBed(bed, viewer, permits, new RecipeRunner(bed.Runner.Env with { Driver = viewer, Governor = permits, Random = random ?? bed.Runner.Env.Random }));
}
///
/// «nadia.prova» with two collections on her profile, «Estate» (e0–e3, or ) and «Viaggi»
/// (v0–v1): the viewer of «Estate» receives both, as Instagram's did, and goes on to «Viaggi» by itself after the last item.
///
public async Task<(ScriptedAccount Scripted, Account Account)> AddCollectionsAsync(IReadOnlyList? summer = null)
{
var nadia = Bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
var account = await Bed.AddAccountAsync(nadia);
nadia.HighlightsWithItems.Add(("highlight:17900000000000001", "Estate", []));
nadia.HighlightsWithItems.Add(("highlight:17900000000000002", "Viaggi", []));
summer ??= [new("e0"), new("e1"), new("e2"), new("e3")];
IReadOnlyList travel = [new("v0"), new("v1")];
var travelView = ViewerAnswers.Highlight(nadia, "17900000000000002", "Viaggi", travel);
Viewer.Add(ViewerAnswers.Highlight(nadia, "17900000000000001", "Estate", summer, travelView) with { Next = "17900000000000002" });
Viewer.Add(travelView);
return (nadia, account);
}
///
/// Every item that came on screen had its story permit before (rule 7, §6.3): the n-th permit was granted before
/// the n-th item came, and no item came without one.
///
public void AssertNoItemCameOnScreenBeforeItsPermit()
{
var atPermit = Permits.OnScreenAtStoryPermit;
for (var i = 0; i < atPermit.Count; i++)
{
Assert.IsTrue(atPermit[i] <= i, $"Story permit {i + 1} granted when {atPermit[i]} items had already come on screen ({string.Join(", ", Viewer.Seen)}).");
}
Assert.IsTrue(Viewer.Seen.Count <= atPermit.Count, $"{Viewer.Seen.Count} items came on screen ({string.Join(", ", Viewer.Seen)}) with {atPermit.Count} story permits.");
}
public Task RunAsync(RecipeRequest request, CancellationToken ct = default) => Runner.RunAsync(request, Bed.Session, ct);
public Task RunHighlightAsync(Account account, string highlightId) =>
RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: highlightId));
/// Instagram identifiers of the items of a collection, in their order.
public async Task> ItemsOfAsync(Account account, string highlightId)
{
var highlight = await Bed.Db.Highlights.FindAsync(account.Id, highlightId) ?? throw new AssertFailedException($"Raccolta {highlightId} non salvata.");
var ids = new List();
foreach (var item in (await Bed.Db.Highlights.ListItemsAsync(highlight.Id)).OrderBy(i => i.Position))
{
ids.Add((await Bed.Db.Entries.GetAsync(item.EntryId))!.InstagramId!);
}
return ids;
}
public ValueTask DisposeAsync() => Bed.DisposeAsync();
}
/// Grants what the inner Governor grants, but every story permit first waits (its minimum spacing).
internal sealed class SpacedGovernor(IGovernor inner, VirtualClock clock, TimeSpan spacing) : IGovernor
{
public Task RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
{
if (kind == ActionKind.StoryView)
{
clock.Advance(spacing);
}
return inner.RequestAsync(kind, accountId, ct);
}
}
/// Grants what the inner Governor grants, but refuses story permits after (the budget view still says there is room).
internal sealed class StoryGrantsGovernor(IGovernor inner, int grants) : IGovernor
{
private int _granted;
public Task RequestAsync(ActionKind kind, long? accountId, CancellationToken ct) =>
kind == ActionKind.StoryView && Interlocked.Increment(ref _granted) > grants
? Task.FromResult(Permit.Deny(kind, accountId, DenialReason.HourlyBudgetReached, "Tetto delle storie raggiunto (prova)."))
: inner.RequestAsync(kind, accountId, ct);
}
/// Passes every request on and records, at each story permit granted, how many items had come on screen.
internal sealed class PermitWatcher(IGovernor inner, ViewerSite viewer) : IGovernor
{
public List OnScreenAtStoryPermit { get; } = [];
public async Task RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
{
var permit = await inner.RequestAsync(kind, accountId, ct);
if (kind == ActionKind.StoryView && permit.Granted)
{
OnScreenAtStoryPermit.Add(viewer.OnScreenSoFar());
}
return permit;
}
}
/// A degenerate random source: always the same value (the draws of §7.2 come out the same every time).
internal sealed class FixedRandom(double value) : IRandomSource
{
public double NextDouble() => value;
}