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>
This commit is contained in:
1 parent
b3a7c31e5a
commit
31bbbf8bb7
69 files changed
+9184
-453
No files matched your search
@@ -34,11 +34,46 @@ public sealed class CollectionUnitTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramMapIsASkeletonWithEveryEntryEmpty()
|
||||
public void TheInstagramMapHasThePagesSeenInRealTrafficAndNoTargetYet()
|
||||
{
|
||||
var map = SiteMap.LoadInstagram();
|
||||
Assert.AreEqual("instagram", map.Site);
|
||||
Assert.AreEqual(SitePages.All.Count + SiteTargets.All.Count, map.Missing(SitePages.All, SiteTargets.All).Count, "Nothing is filled in before M0.");
|
||||
|
||||
// Pages: only those with evidence in the HAR of 21 October 2026 (Instagram's own route templates and the
|
||||
// Referer of the page's requests). The others have none and stay empty.
|
||||
string[] filled = [SitePages.Home, SitePages.Profile, SitePages.Post, SitePages.StoryViewer, SitePages.HighlightViewer];
|
||||
string[] empty = [SitePages.ProfileFrom, SitePages.ReelsFrom, SitePages.TaggedFrom, SitePages.Following, SitePages.FollowingFrom];
|
||||
CollectionAssert.AreEquivalent(SitePages.All.ToArray(), filled.Concat(empty).ToArray(), "Every page is decided.");
|
||||
Assert.IsTrue(filled.All(map.HasPage));
|
||||
CollectionAssert.AreEquivalent(empty.Select(p => $"pagina «{p}»").ToArray(), map.Missing(SitePages.All, []).ToArray());
|
||||
|
||||
Assert.AreEqual("/", map.BuildPath(SitePages.Home));
|
||||
Assert.AreEqual("/mario.rossi/", map.BuildPath(SitePages.Profile, new Dictionary<string, string> { ["username"] = "mario.rossi" }));
|
||||
Assert.AreEqual("/p/Abc_12-xYz9/", map.BuildPath(SitePages.Post, new Dictionary<string, string> { ["code"] = "Abc_12-xYz9" }));
|
||||
Assert.IsNotNull(map.Match(SitePages.Home, "/"));
|
||||
Assert.IsNull(map.Match(SitePages.Home, "/mario.rossi/"));
|
||||
Assert.AreEqual("mario.rossi", map.Match(SitePages.Profile, "/mario.rossi/")!["username"]);
|
||||
|
||||
// Viewers: matched only, never opened. The story viewer carries the account and the story shown.
|
||||
var story = map.Match(SitePages.StoryViewer, "/stories/mario/3456789012345678901/");
|
||||
Assert.AreEqual("mario", story!["username"]);
|
||||
Assert.AreEqual("3456789012345678901", story["id"]);
|
||||
Assert.IsNull(map.Match(SitePages.StoryViewer, "/stories/mario/"), "Without the story id the shape does not match (to be confirmed live).");
|
||||
Assert.IsNull(map.Match(SitePages.HighlightViewer, "/stories/mario/3456789012345678901/"));
|
||||
|
||||
// The highlight viewer: the 17 digits of the collection and no item id (the address stays the same while watching).
|
||||
var highlight = map.Match(SitePages.HighlightViewer, "/stories/highlights/17841400000000000/");
|
||||
CollectionAssert.AreEquivalent(new[] { "highlight" }, highlight!.Keys.ToArray());
|
||||
Assert.AreEqual("17841400000000000", highlight["highlight"]);
|
||||
|
||||
// Overlap: a highlight address also has the story viewer's shape, with «highlights» as user name. The story
|
||||
// recipe then sees «another account» and closes; the highlight recipe reads only its own page.
|
||||
Assert.AreEqual("highlights", map.Match(SitePages.StoryViewer, "/stories/highlights/17841400000000000/")!["username"]);
|
||||
|
||||
// Targets: none has evidence yet (the HAR had no documents and no element attributes).
|
||||
var missingTargets = map.Missing([], SiteTargets.All);
|
||||
Assert.AreEqual(SiteTargets.All.Count, missingTargets.Count);
|
||||
Assert.IsTrue(missingTargets.All(m => m.EndsWith("(vuoto)", StringComparison.Ordinal)), "Every target is listed, still empty.");
|
||||
|
||||
// The browser layer reads the same file: every target is a placeholder and is never looked up in the page.
|
||||
var targets = TargetMap.LoadEmbedded("bersagli.instagram.json");
|
||||
@@ -49,47 +84,77 @@ public sealed class CollectionUnitTests
|
||||
Assert.AreEqual(TargetStatus.NotConfigured, lookup.Status);
|
||||
Assert.AreEqual(0, cdp.Sent.Count, "A placeholder never reaches the page.");
|
||||
StringAssert.Contains(lookup.Message, "H11");
|
||||
|
||||
// The copy next to the executable is the same map.
|
||||
var copy = SiteMap.Load(Path.Combine(AppContext.BaseDirectory, "config", "bersagli.instagram.json"));
|
||||
CollectionAssert.AreEquivalent(map.Missing(SitePages.All, SiteTargets.All).ToArray(), copy.Missing(SitePages.All, SiteTargets.All).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecipesRefuseToRunOnInstagramWhileTheMapOrTheReadersAreSkeletons()
|
||||
public async Task OnInstagramOnlyRecipesThatNeedNoTargetGetPastTheMap()
|
||||
{
|
||||
using var temp = new TempFolder("ricette");
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new VirtualClock();
|
||||
var governor = new PermissiveGovernor();
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
RecipeEnvironment Environment(SiteMap map, ReaderVocabulary vocabulary) => new()
|
||||
|
||||
// The Instagram vocabulary is confirmed on real samples. To see which recipes get past the map without letting
|
||||
// any of them reach the page, the runs use a copy marked as a hypothesis: the readers' gate comes right after
|
||||
// the map's and stops them there.
|
||||
Assert.IsTrue(ReaderVocabulary.LoadInstagram().IsUsable, ReaderVocabulary.LoadInstagram().UnusableReason);
|
||||
var stopper = ReaderVocabulary.LoadInstagram() with { Status = VocabularyStatus.Hypothesis };
|
||||
Task<RecipeOutcome> RunAsync(RecipeKind kind) => new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = new UntouchableDriver(),
|
||||
Capture = new CaptureCollector(new ShapeReader(vocabulary), clock),
|
||||
Capture = new CaptureCollector(new ShapeReader(stopper), clock),
|
||||
Governor = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock),
|
||||
Storage = db,
|
||||
SiteMap = map,
|
||||
SiteMap = SiteMap.LoadInstagram(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(1),
|
||||
};
|
||||
}).RunAsync(new RecipeRequest(kind, 1), session, CancellationToken.None);
|
||||
|
||||
foreach (var kind in Enum.GetValues<RecipeKind>().Where(k => k != RecipeKind.FollowingSweep))
|
||||
static void Refused(RecipeKind kind, RecipeOutcome outcome, string missing)
|
||||
{
|
||||
var outcome = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite()))
|
||||
.RunAsync(new RecipeRequest(kind, 1), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, kind.ToString());
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, outcome.Status, kind.ToString());
|
||||
StringAssert.Contains(outcome.Message, "mappa dei bersagli non è ancora compilata");
|
||||
StringAssert.Contains(outcome.Message, missing, kind.ToString());
|
||||
}
|
||||
|
||||
var sweep = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite()))
|
||||
.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
StringAssert.Contains(sweep.Message, "pagina «home»");
|
||||
static void Passed(RecipeKind kind, RecipeOutcome outcome)
|
||||
{
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, outcome.Status, $"{kind}: {outcome.Message}");
|
||||
StringAssert.Contains(outcome.Message, "ipotesi", kind.ToString());
|
||||
}
|
||||
|
||||
var readers = await new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadInstagram()))
|
||||
.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, readers.Status);
|
||||
StringAssert.Contains(readers.Message, "ipotesi");
|
||||
// Recipes that click something: every target is still empty (H11), while their pages are all there.
|
||||
foreach (var kind in new[] { RecipeKind.AccountStories, RecipeKind.Highlight, RecipeKind.Tagged, RecipeKind.Reels })
|
||||
{
|
||||
var outcome = await RunAsync(kind);
|
||||
Refused(kind, outcome, "(vuoto)");
|
||||
Assert.IsFalse(outcome.Message!.Contains("pagina «", StringComparison.Ordinal), $"{kind}: {outcome.Message}");
|
||||
}
|
||||
|
||||
// Recipes that only open pages.
|
||||
Passed(RecipeKind.FollowingSweep, await RunAsync(RecipeKind.FollowingSweep));
|
||||
Passed(RecipeKind.SinglePost, await RunAsync(RecipeKind.SinglePost));
|
||||
|
||||
// The profile check and the backfill need no target: the «not found» marker is looked up only when configured.
|
||||
foreach (var kind in new[] { RecipeKind.ProfileCheck, RecipeKind.Backfill })
|
||||
{
|
||||
Assert.IsFalse(RecipeRunner.Requirements(kind).Targets.Contains(SiteTargets.ProfileNotFound), kind.ToString());
|
||||
Passed(kind, await RunAsync(kind));
|
||||
}
|
||||
|
||||
// No evidence of the address of the following list.
|
||||
Refused(RecipeKind.FollowingList, await RunAsync(RecipeKind.FollowingList), $"pagina «{SitePages.Following}»");
|
||||
|
||||
Assert.AreEqual(0, governor.Requests.Count, "No permit asked, no gesture, no page.");
|
||||
Assert.IsTrue((await db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "mappa-incompleta"));
|
||||
var events = await db.Events.ListAsync(new EventQuery());
|
||||
Assert.IsTrue(events.Any(e => e.Code == "mappa-incompleta"));
|
||||
Assert.IsTrue(events.Any(e => e.Code == "lettori-incompleti"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Sonda;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The tools with which Alberto provides evidence from his own browser: the conversion of a HAR into the probe's raw
|
||||
/// format (<c>febe-sonda da-har</c>) and the targets snippet for the DevTools console. The HAR is synthetic, written by
|
||||
/// the test: invented generic values, nothing that claims to be Instagram's format.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class HarImportTests
|
||||
{
|
||||
private const string FirstBody = """{"dati":{"elementi":[{"numero":"5512345678","nome":"mario.rossi","larghezza":1080}]}}""";
|
||||
private const string SecondBody = """{"stato":"ok","persone":[{"nome":"lucia.bianchi"}]}""";
|
||||
private const string EmbeddedBlock = """{"profilo":{"nome":"mario.rossi","privato":false}}""";
|
||||
private const string SecondEmbeddedBlock = """{"pagina":{"altre":false},"elementi":[]}""";
|
||||
|
||||
/// <summary>The request parameter that names a GraphQL operation (the only part of a request body ever read).</summary>
|
||||
private const string Operation = HarImporter.OperationParameter;
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyDataAnswersOfTheSiteAndEmbeddedDataAreKeptWithoutHeadersCookiesOrQueries()
|
||||
{
|
||||
using var temp = new TempFolder("har");
|
||||
var har = temp.Combine("prova.har");
|
||||
File.WriteAllText(har, SyntheticHar().ToJsonString());
|
||||
var raw = temp.Combine("grezzi");
|
||||
|
||||
var report = HarImporter.Import(har, raw);
|
||||
Assert.AreEqual(new HarImportReport(Entries: 12, DataResponses: 4, Documents: 1, DocumentBlocks: 2, OtherHosts: 2, NotData: 2, WithoutBody: 1, NotJson: 1, DocumentsWithoutData: 1), report);
|
||||
Assert.AreEqual(6, report.Written);
|
||||
|
||||
// Flat files named by number and kind: a GraphQL operation name only when it is one, never a path.
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "000001-ProvaElencoQuery.json", "000002-risposta.json", "000003-ProvaPaginaSuccessivaQuery.json", "000004-risposta.json", "000005-documento.json", "000006-documento.json", "LEGGIMI.txt" },
|
||||
Directory.GetFiles(raw).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray());
|
||||
|
||||
// Headers, cookies, query strings and request bodies never reach the output.
|
||||
foreach (var file in Directory.GetFiles(raw))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (var secret in new[] { "segreto", "sessionid", "cookie", "igsh", "variables", "pacchetto", "nascosto", "payload", "esterno" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(secret, StringComparison.OrdinalIgnoreCase), $"{Path.GetFileName(file)}: {secret}");
|
||||
}
|
||||
}
|
||||
|
||||
var first = Sample(raw, "000001-ProvaElencoQuery.json");
|
||||
var descriptor = first["descrittore"]!;
|
||||
Assert.AreEqual("https://www.instagram.com/graphql/query", descriptor["indirizzo"]!.GetValue<string>());
|
||||
Assert.AreEqual("sito", descriptor["host"]!.GetValue<string>());
|
||||
Assert.AreEqual(200, descriptor["stato"]!.GetValue<int>());
|
||||
Assert.AreEqual("text/javascript", descriptor["tipo"]!.GetValue<string>(), "Lower case, no parameters.");
|
||||
Assert.AreEqual("XHR", descriptor["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("2026-10-21T15:35:04Z", descriptor["quando"]!.GetValue<string>(), "UTC, to the second.");
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(FirstBody), first["corpo"]), "The base64 body, decoded and parsed.");
|
||||
CollectionAssert.AreEquivalent(new[] { "descrittore", "corpo" }, first.AsObject().Select(p => p.Key).ToArray());
|
||||
|
||||
var second = Sample(raw, "000002-risposta.json");
|
||||
Assert.AreEqual("https://www.instagram.com/api/v1/prova/mario.rossi/info/", second["descrittore"]!["indirizzo"]!.GetValue<string>());
|
||||
Assert.AreEqual("Fetch", second["descrittore"]!["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("application/json", second["descrittore"]!["tipo"]!.GetValue<string>());
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(SecondBody), second["corpo"]));
|
||||
|
||||
// A page document: one sample per valid JSON block it embeds, in order and with the document's descriptor, as
|
||||
// Febe's capture hands them to the readers; nothing of its scripts.
|
||||
var page = Sample(raw, "000005-documento.json");
|
||||
Assert.AreEqual("Document", page["descrittore"]!["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("text/html", page["descrittore"]!["tipo"]!.GetValue<string>());
|
||||
Assert.AreEqual("https://www.instagram.com/mario.rossi/", page["descrittore"]!["indirizzo"]!.GetValue<string>());
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(EmbeddedBlock), page["corpo"]));
|
||||
var nextBlock = Sample(raw, "000006-documento.json");
|
||||
Assert.IsTrue(JsonNode.DeepEquals(page["descrittore"], nextBlock["descrittore"]));
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(SecondEmbeddedBlock), nextBlock["corpo"]));
|
||||
|
||||
// The folder is a raw folder like the probe's: «ripulisci» and «verifica» work on it unchanged.
|
||||
var clean = temp.Combine("ripuliti");
|
||||
var cleaned = new SampleSanitizer(key: new byte[32]).SanitizeFolder(raw, clean);
|
||||
Assert.AreEqual(6, cleaned.Files);
|
||||
var verify = SampleVerifier.Verify(raw, clean);
|
||||
Assert.IsTrue(verify.Passed, string.Join("; ", verify.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind}")));
|
||||
Assert.IsFalse(File.ReadAllText(Path.Combine(clean, "000001-ProvaElencoQuery.json")).Contains("mario", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheConversionRefusesRepositoriesUsedFoldersAndFilesThatAreNotAHar()
|
||||
{
|
||||
using var temp = new TempFolder("har");
|
||||
var har = temp.Combine("prova.har");
|
||||
File.WriteAllText(har, SyntheticHar().ToJsonString());
|
||||
|
||||
// Raw output inside a repository: refused before anything is written.
|
||||
Directory.CreateDirectory(temp.Combine("progetto", ".git"));
|
||||
var inside = temp.Combine("progetto", "grezzi");
|
||||
StringAssert.Contains(Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(har, inside)).Message, "fuori dal repository");
|
||||
Assert.IsFalse(Directory.Exists(inside));
|
||||
|
||||
// The HAR itself holds cookies: it is not read from inside a repository either.
|
||||
var harInside = temp.Combine("progetto", "prova.har");
|
||||
File.Copy(har, harInside);
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(harInside, temp.Combine("altrove")));
|
||||
|
||||
// A folder that is already in use: refused, nothing is mixed or overwritten.
|
||||
var used = Directory.CreateDirectory(temp.Combine("usata")).FullName;
|
||||
File.WriteAllText(Path.Combine(used, "000001-risposta.json"), "{}");
|
||||
StringAssert.Contains(Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(har, used)).Message, "non è vuota");
|
||||
Assert.AreEqual("{}", File.ReadAllText(Path.Combine(used, "000001-risposta.json")));
|
||||
|
||||
Assert.ThrowsExactly<FileNotFoundException>(() => HarImporter.Import(temp.Combine("manca.har"), temp.Combine("nuova1")));
|
||||
File.WriteAllText(temp.Combine("non-har.har"), """{"altro":[]}""");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("non-har.har"), temp.Combine("nuova2")));
|
||||
File.WriteAllText(temp.Combine("rotto.har"), "{\"log\":");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("rotto.har"), temp.Combine("nuova3")));
|
||||
File.WriteAllText(temp.Combine("elenco.har"), "[1,2]");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("elenco.har"), temp.Combine("nuova4")));
|
||||
Assert.IsFalse(Directory.Exists(temp.Combine("nuova4")), "Nothing is created for a file that is not a HAR.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyNamesOfTheSiteCodeNameAFile()
|
||||
{
|
||||
Assert.AreEqual("PolarisStoriesV3HighlightsPageQuery", HarImporter.OperationName("PolarisStoriesV3HighlightsPageQuery"));
|
||||
Assert.AreEqual("usePolarisRegisterInRecentSearchesMutation", HarImporter.OperationName(" usePolarisRegisterInRecentSearchesMutation "));
|
||||
Assert.AreEqual("ProvaAggiornamentiSubscription", HarImporter.OperationName("ProvaAggiornamentiSubscription"));
|
||||
foreach (var value in new[] { null, "", "Query", "mario.rossi", "mario_rossi", "Pagina di mario Query", "Profilo12345Query", "/mario.rossi/Query", "ProvaElenco" })
|
||||
{
|
||||
Assert.IsNull(HarImporter.OperationName(value), value ?? "null");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTargetsSnippetOnlyListensAndReads()
|
||||
{
|
||||
var path = Febe.Tests.Desktop.Support.Repository.PathOf("tools", "bersagli", "raccogli-bersagli.js");
|
||||
var script = File.ReadAllText(path);
|
||||
|
||||
// The same deny-list as Febe's own page scripts: no gesture, no DOM change, no request, no cookie or storage.
|
||||
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(script);
|
||||
foreach (var word in new[] { "preventDefault", "stopPropagation", "stopImmediatePropagation", "postMessage", "document.cookie", "cookieStore", "Storage", "indexedDB", "fetch(", "XMLHttpRequest", "sendBeacon", "WebSocket", "new Image", "innerHTML", "outerHTML", "classList", ".style", "setAttribute", "removeAttribute", "eval(", "Function(", "open(" })
|
||||
{
|
||||
Assert.IsFalse(script.Contains(word, StringComparison.Ordinal), word);
|
||||
}
|
||||
|
||||
// One capturing click listener, and the function that copies the records.
|
||||
foreach (var part in new[] { "addEventListener('click', onClick, { capture: true, passive: true })", "globalThis.febeBersagli = ", "copy(text)" })
|
||||
{
|
||||
Assert.IsTrue(script.Contains(part, StringComparison.Ordinal), part);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, script.Split("addEventListener").Length - 1, "A single listener.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(Path.GetDirectoryName(path)!, "LEGGIMI.md")));
|
||||
}
|
||||
|
||||
private static JsonNode Sample(string folder, string name) => JsonNode.Parse(File.ReadAllText(Path.Combine(folder, name)))!;
|
||||
|
||||
private static string Base64(string text) => Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
|
||||
|
||||
private static JsonObject SyntheticHar()
|
||||
{
|
||||
static JsonArray Headers(params (string Name, string Value)[] headers) =>
|
||||
[.. headers.Select(h => (JsonNode)new JsonObject { ["name"] = h.Name, ["value"] = h.Value })];
|
||||
|
||||
static JsonObject Entry(string resourceType, string method, string url, int status, JsonObject content, JsonObject? postData = null, string started = "2026-10-21T17:35:04.512+02:00")
|
||||
{
|
||||
var request = new JsonObject
|
||||
{
|
||||
["method"] = method,
|
||||
["url"] = url,
|
||||
["httpVersion"] = "h3",
|
||||
["headers"] = Headers(("Cookie", "sessionid=segreto-cookie; ds_user_id=segreto-cookie"), ("X-Prova", "segreto-intestazione")),
|
||||
["queryString"] = new JsonArray(new JsonObject { ["name"] = "variables", ["value"] = "segreto-indirizzo" }),
|
||||
["cookies"] = new JsonArray(new JsonObject { ["name"] = "sessionid", ["value"] = "segreto-cookie" }),
|
||||
["headersSize"] = -1,
|
||||
["bodySize"] = 0,
|
||||
};
|
||||
if (postData is not null)
|
||||
{
|
||||
request["postData"] = postData;
|
||||
}
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["_resourceType"] = resourceType,
|
||||
["startedDateTime"] = started,
|
||||
["time"] = 123.4,
|
||||
["request"] = request,
|
||||
["response"] = new JsonObject
|
||||
{
|
||||
["status"] = status,
|
||||
["statusText"] = "",
|
||||
["httpVersion"] = "h3",
|
||||
["headers"] = Headers(("Set-Cookie", "prova=segreto-risposta"), ("Content-Type", "text/plain; segreto-intestazione")),
|
||||
["cookies"] = new JsonArray(new JsonObject { ["name"] = "prova", ["value"] = "segreto-risposta" }),
|
||||
["content"] = content,
|
||||
["redirectURL"] = "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static JsonObject Content(string mime, string? text, bool base64 = false)
|
||||
{
|
||||
var content = new JsonObject { ["size"] = text?.Length ?? 0, ["mimeType"] = mime };
|
||||
if (text is not null)
|
||||
{
|
||||
content["text"] = base64 ? Base64(text) : text;
|
||||
if (base64)
|
||||
{
|
||||
content["encoding"] = "base64";
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
static JsonObject Form(string text, params (string Name, string Value)[] parameters)
|
||||
{
|
||||
var form = new JsonObject { ["mimeType"] = "application/x-www-form-urlencoded", ["text"] = text };
|
||||
if (parameters.Length > 0)
|
||||
{
|
||||
form["params"] = Headers(parameters);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
var page = $$"""
|
||||
<!DOCTYPE html><html><head>
|
||||
<script>var nascosto = "segreto-script";</script>
|
||||
<script type="application/json" data-prova="1">{{EmbeddedBlock}}</script>
|
||||
<script type="application/json">{ "rotto": </script>
|
||||
</head><body><p>segreto-testo-della-pagina</p><script type="application/json">{{SecondEmbeddedBlock}}</script></body></html>
|
||||
""";
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["log"] = new JsonObject
|
||||
{
|
||||
["version"] = "1.2",
|
||||
["creator"] = new JsonObject { ["name"] = "WebInspector", ["version"] = "537.36" },
|
||||
["pages"] = new JsonArray(),
|
||||
["entries"] = new JsonArray(
|
||||
Entry("xhr", "POST", "https://www.instagram.com/graphql/query?variables=segreto-indirizzo", 200, Content("text/javascript; charset=utf-8", FirstBody, base64: true),
|
||||
Form($"av=segreto-corpo&{Operation}=ProvaElencoQuery&variables=segreto-corpo", ("av", "segreto-corpo"), (Operation, "ProvaElencoQuery"), ("variables", "segreto-corpo"))),
|
||||
Entry("fetch", "GET", "https://www.instagram.com/api/v1/prova/mario.rossi/info/?segreto=1", 200, Content("application/json", SecondBody)),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/graphql/query", 200, Content("application/json", """{"pagina":{"cursore":"QVFIUjBz","altre":true}}"""),
|
||||
Form($"{Operation}=ProvaPaginaSuccessivaQuery&x=segreto-corpo")),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/api/graphql", 200, Content("text/javascript", """{"dati":{"vuoto":null}}"""),
|
||||
Form($"{Operation}=mario.rossi", (Operation, "mario.rossi"))),
|
||||
Entry("script", "GET", "https://www.instagram.com/static/pacchetto.js", 200, Content("text/javascript", "console.log('segreto-script')")),
|
||||
Entry("image", "GET", "https://scontent.cdninstagram.com/v/foto.jpg?firma=segreto-indirizzo", 200, Content("image/jpeg", "segreto-immagine", base64: true)),
|
||||
Entry("document", "GET", "https://www.instagram.com/mario.rossi/?igsh=segreto-indirizzo", 200, Content("text/html; charset=utf-8", page)),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/ajax/prova/", 200, Content("text/javascript", """for (;;);{"payload":{"segreto":1}}""")),
|
||||
Entry("document", "GET", "https://www.instagram.com/altro/", 200, Content("text/html", "<html><body>segreto-senza-dati</body></html>")),
|
||||
Entry("xhr", "GET", "https://www.instagram.com/api/v1/vuota/", 200, Content("application/json", null)),
|
||||
Entry("fetch", "GET", "https://esterno.example/api/?segreto=1", 200, Content("application/json", """{"segreto":1}""")),
|
||||
Entry("fetch", "GET", "https://scontent.cdninstagram.com/v/dati.json", 200, Content("application/json", """{"segreto":1}"""))),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The reader with the Instagram vocabulary on the cleaned real samples of <c>tests/campioni/instagram</c>: answers
|
||||
/// Alberto's browser received on 21 October 2026 (HAR), cleaned with «febe-sonda ripulisci» and checked with
|
||||
/// «febe-sonda verifica» (spec §14.5, rule 10). Values are fakes of the same shape: the tests check shapes, sizes,
|
||||
/// dates and counts.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class InstagramReaderTests
|
||||
{
|
||||
private static readonly ReaderVocabulary Vocabulary = ReaderVocabulary.LoadInstagram();
|
||||
private static readonly ShapeReader Reader = new(Vocabulary);
|
||||
|
||||
private static string SampleFile(string name) =>
|
||||
Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
|
||||
private static ReadResult ReadSample(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return Reader.Read(document.RootElement.GetProperty("corpo"));
|
||||
}
|
||||
|
||||
private static string SampleBody(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return document.RootElement.GetProperty("corpo").GetRawText();
|
||||
}
|
||||
|
||||
private static string MimeOf(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return document.RootElement.GetProperty("descrittore").GetProperty("tipo").GetString()!;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramVocabularyIsConfirmedAndUsable()
|
||||
{
|
||||
Assert.AreEqual(VocabularyStatus.Confirmed, Vocabulary.Status);
|
||||
Assert.IsTrue(Vocabulary.IsUsable, Vocabulary.UnusableReason);
|
||||
Assert.AreEqual(0, Vocabulary.MissingConcepts.Count);
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.instagram.json")), "Editable without recompiling.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryKeyOfTheVocabularyComesFromTheRealSamples()
|
||||
{
|
||||
// Rule 10: the format is not invented. Every path of lettori.instagram.json exists, as nested keys, somewhere in
|
||||
// the cleaned samples; every relevance key is a key of the samples.
|
||||
var paths = new HashSet<string>(StringComparer.Ordinal);
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json"))
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(file));
|
||||
Collect(document.RootElement.GetProperty("corpo"), paths, names);
|
||||
}
|
||||
|
||||
var concepts = new[]
|
||||
{
|
||||
Vocabulary.Content.Id, Vocabulary.Content.Code, Vocabulary.Content.TakenAt, Vocabulary.Content.Caption, Vocabulary.Content.Images,
|
||||
Vocabulary.Content.Videos, Vocabulary.Content.Children, Vocabulary.Content.ChildCount, Vocabulary.Content.Owner, Vocabulary.Content.Pinned,
|
||||
Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height,
|
||||
Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate,
|
||||
Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt,
|
||||
Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items,
|
||||
Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer,
|
||||
};
|
||||
foreach (var path in concepts.SelectMany(c => c.Paths))
|
||||
{
|
||||
Assert.IsTrue(paths.Contains(path), $"«{path}» non compare in nessun campione ripulito di Instagram.");
|
||||
}
|
||||
|
||||
foreach (var key in Vocabulary.Relevance)
|
||||
{
|
||||
Assert.IsTrue(names.Contains(key), $"«{key}» non compare in nessun campione ripulito di Instagram.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GraphQlAnswersComeAsJavaScriptAndAreReadAsData()
|
||||
{
|
||||
// Why the capture reads «text/javascript»: the stories and highlights data of the samples was served that way.
|
||||
Assert.AreEqual("text/javascript", MimeOf("raccolta-in-evidenza"));
|
||||
Assert.AreEqual("application/json", MimeOf("post-video"));
|
||||
Assert.IsTrue(DataResponses.IsData("text/javascript", "XHR"));
|
||||
Assert.IsTrue(DataResponses.IsData("text/javascript", "Fetch"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/x-javascript", "XHR"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/json", "Fetch"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/json", null));
|
||||
Assert.IsFalse(DataResponses.IsData("text/javascript", "Script"), "Script files are never parsed.");
|
||||
Assert.IsFalse(DataResponses.IsData("text/javascript", null));
|
||||
Assert.IsFalse(DataResponses.IsData("text/html", "Document"));
|
||||
Assert.IsFalse(DataResponses.IsData("video/mp4", "Fetch"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AHighlightPageGivesTheCollectionsTheirStoriesAndTheirOwner()
|
||||
{
|
||||
var result = ReadSample("raccolta-in-evidenza");
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
Assert.AreEqual(2, result.Highlights.Count);
|
||||
foreach (var highlight in result.Highlights)
|
||||
{
|
||||
// «highlight:<17 digits>» in the data, «/stories/highlights/<17 digits>/» in the address: the reader keeps
|
||||
// the address form (the cleaned samples fake the letters of the prefix, not its shape).
|
||||
StringAssert.Matches(highlight.Id, new System.Text.RegularExpressions.Regex("^[0-9]{17}$"));
|
||||
Assert.AreEqual(4, highlight.Items.Count);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(highlight.Title));
|
||||
Assert.IsNotNull(highlight.Owner);
|
||||
Assert.IsTrue(highlight.Items.All(i => i.HighlightId == highlight.Id));
|
||||
|
||||
// The «user» of each item has only an identifier: the author is the owner of the collection.
|
||||
Assert.IsTrue(highlight.Items.All(i => i.Owner?.Id == highlight.Owner.Id && i.Owner.Username == highlight.Owner.Username));
|
||||
Assert.IsTrue(highlight.Items.All(i => i.ExpiresAt > i.TakenAt), "Highlight items keep the expiry they had as stories.");
|
||||
Assert.IsTrue(highlight.Items.All(i => i.Code is { Length: 11 }));
|
||||
Assert.IsTrue(highlight.Items.All(i => i.IsComplete && i.Files.Count == 1));
|
||||
}
|
||||
|
||||
Assert.AreEqual(result.Highlights.Sum(h => h.Items.Count), result.Contents.Count);
|
||||
Assert.IsFalse(result.Contents.Any(c => c.ExpiresAt is null && c.HighlightId is null), "Nothing here looks like a post.");
|
||||
Assert.AreEqual(true, result.Page?.HasMore);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(result.Page?.Cursor));
|
||||
Assert.IsTrue(result.Profiles.Any(p => p.Id == result.Highlights[0].Owner!.Id && p.IsPrivate == false));
|
||||
Assert.IsNull(result.Viewer, "xdt_viewer.user has no user name: the connected account is not recognized from it alone (H10).");
|
||||
Assert.IsNotNull(result.ViewerId, "Its identifier is kept, to recognize its profile in other answers.");
|
||||
Assert.IsFalse(result.Profiles.Any(p => p.Id == result.ViewerId), "In this answer the connected account has no profile.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StoryFilesTakeTheLargestImageAndTheFirstVideoVersion()
|
||||
{
|
||||
var items = ReadSample("raccolta-in-evidenza").Contents;
|
||||
var photos = items.Where(i => i.Files[0].Kind == MediaKind.Photo).ToList();
|
||||
var videos = items.Where(i => i.Files[0].Kind == MediaKind.Video).ToList();
|
||||
Assert.IsTrue(photos.Count > 0 && videos.Count > 0);
|
||||
|
||||
// The largest of the 10–14 candidates: 1206×2144 or 640×1136 in the samples.
|
||||
Assert.IsTrue(items.All(i => i.Files[0].Kind == MediaKind.Video || i.Files[0].Best.Area >= 640 * 1136));
|
||||
Assert.IsTrue(photos.All(p => p.Files[0].Best.Url.EndsWith(".jpg", StringComparison.Ordinal)));
|
||||
|
||||
// Story video versions (type 101, 102, 103) carry no size: the first one is taken, with the cover image.
|
||||
foreach (var video in videos.Select(v => v.Files[0]))
|
||||
{
|
||||
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
|
||||
Assert.IsNull(video.Best.Width);
|
||||
Assert.IsNotNull(video.Cover);
|
||||
Assert.IsTrue(video.Duration > TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheNextPageOfHighlightsIsReadLikeTheFirst()
|
||||
{
|
||||
var result = ReadSample("raccolta-pagina-successiva");
|
||||
var highlight = result.Highlights.Single();
|
||||
Assert.AreEqual(3, highlight.Items.Count);
|
||||
Assert.IsNotNull(highlight.Owner);
|
||||
Assert.IsNotNull(result.Page);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void APostPageGivesTheVideoItsCoverTheCaptionAndTheAuthor()
|
||||
{
|
||||
var result = ReadSample("post-video");
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
var post = result.Contents.Single();
|
||||
Assert.AreEqual(11, post.Code?.Length);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(post.Caption), "The caption is an object: its text is in caption.text.");
|
||||
Assert.IsNull(post.ExpiresAt);
|
||||
Assert.IsNull(post.HighlightId);
|
||||
Assert.IsTrue(post.IsComplete);
|
||||
Assert.IsNotNull(post.Owner);
|
||||
Assert.AreEqual(false, post.Owner.IsFollowed, "friendship_status.following of the author.");
|
||||
Assert.AreEqual(false, post.Owner.IsPrivate);
|
||||
Assert.IsNotNull(post.Owner.Picture);
|
||||
Assert.AreEqual(960, post.Owner.Picture.Width, "hd_profile_pic_url_info, the largest picture.");
|
||||
Assert.IsNotNull(post.Owner.LatestStoryAt);
|
||||
|
||||
var video = post.Files.Single();
|
||||
Assert.AreEqual(MediaKind.Video, video.Kind);
|
||||
Assert.AreEqual((720, 1280), (video.Best.Width, video.Best.Height));
|
||||
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
|
||||
Assert.AreEqual((720, 1280), (video.Cover?.Width, video.Cover?.Height), "The largest of the 12 candidates.");
|
||||
Assert.AreEqual(5.919, video.Duration!.Value.TotalSeconds, 0.001);
|
||||
Assert.AreEqual(false, result.Page?.HasMore, "more_available of the REST answer.");
|
||||
|
||||
var now = new DateTimeOffset(2026, 10, 25, 12, 0, 0, TimeSpan.Zero);
|
||||
var media = ReadMapping.ToMedia(post, now).Single();
|
||||
Assert.AreEqual(MediaKind.Video, media.Kind);
|
||||
Assert.AreEqual(video.Best.Url, media.SourceUrl);
|
||||
Assert.AreEqual(video.Cover!.Url, media.CoverUrl);
|
||||
Assert.AreEqual(post.TakenAt, ReadMapping.ToEntry(post, 1, EntryKind.Post, now).PublishedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProfilesOfSearchSuggestionsAndCommentsAreProfilesOnly()
|
||||
{
|
||||
var search = ReadSample("ricerca-profili");
|
||||
Assert.AreEqual(ReadShape.Recognized, search.Shape);
|
||||
Assert.AreEqual(5, search.Profiles.Count);
|
||||
Assert.AreEqual(0, search.Contents.Count);
|
||||
|
||||
var suggested = ReadSample("profili-suggeriti");
|
||||
Assert.AreEqual(3, suggested.Profiles.Count);
|
||||
Assert.IsTrue(suggested.Profiles.All(p => p.IsFollowed == false), "Suggested profiles are not followed.");
|
||||
Assert.AreEqual(0, suggested.Contents.Count);
|
||||
|
||||
var comments = ReadSample("commenti");
|
||||
Assert.AreEqual(0, comments.Contents.Count);
|
||||
Assert.IsTrue(comments.Profiles.Count > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnswersAboutOtherThingsAreUnrelatedNotAnUnknownFormat()
|
||||
{
|
||||
foreach (var name in new[] { "promozioni", "storia-vista" })
|
||||
{
|
||||
var result = ReadSample(name);
|
||||
Assert.AreEqual(ReadShape.Unrelated, result.Shape, name);
|
||||
Assert.IsNull(result.KeyStructure, name);
|
||||
}
|
||||
|
||||
// A response that speaks of contents but in keys nobody knows is still an unknown format (spec §6.4).
|
||||
var changed = Reader.Read("""{"data":{"feed":{"items":[{"pk":"1","taken_at":1777663535,"image_versions3":{"candidates":[]}}]}}}""");
|
||||
Assert.AreEqual(ReadShape.Unrecognized, changed.Shape);
|
||||
Assert.IsNotNull(changed.KeyStructure);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCollectorKeepsNothingOfUnrelatedAnswers()
|
||||
{
|
||||
var clock = new Febe.Tests.Browser.TestSupport.VirtualClock();
|
||||
var collector = new CaptureCollector(Reader, clock);
|
||||
var observer = (IResponseObserver)collector;
|
||||
var descriptor = new ResponseDescriptor("r1", HostKind.Site, "https://www.instagram.com/api/graphql", "www.instagram.com", "/api/graphql", 200, "text/javascript", "XHR", false, clock.Now);
|
||||
observer.OnResponse(descriptor);
|
||||
Assert.AreEqual(1, collector.Pending, "A JavaScript data answer is awaited like a JSON one.");
|
||||
var mark = collector.Mark();
|
||||
using (var promo = JsonDocument.Parse(File.ReadAllText(SampleFile("promozioni"))))
|
||||
{
|
||||
Assert.IsNull(collector.Accept(descriptor, promo.RootElement.GetProperty("corpo")));
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, collector.Pending);
|
||||
Assert.AreEqual(mark, collector.Mark(), "An unrelated answer is not «something new arrived».");
|
||||
using var highlights = JsonDocument.Parse(File.ReadAllText(SampleFile("raccolta-in-evidenza")));
|
||||
Assert.IsNotNull(collector.Accept(descriptor with { RequestId = "r2" }, highlights.RootElement.GetProperty("corpo")));
|
||||
Assert.AreEqual(ReadShape.Recognized, collector.Since(mark).Single().Result.Shape);
|
||||
|
||||
observer.OnResponse(descriptor with { RequestId = "r3", ResourceType = "Script" });
|
||||
Assert.AreEqual(0, collector.Pending, "A script file is not data.");
|
||||
|
||||
// The connected account's identifier is remembered even from an answer that is otherwise not kept.
|
||||
using var unrelated = JsonDocument.Parse("""{"data":{"xdt_viewer":{"user":{"id":"5512345","pk":"5512345"}},"segni":[1]}}""");
|
||||
var before = collector.Mark();
|
||||
Assert.IsNull(collector.Accept(descriptor with { RequestId = "r4" }, unrelated.RootElement));
|
||||
Assert.AreEqual(before, collector.Mark());
|
||||
Assert.AreEqual("5512345", collector.ViewerId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDataEmbeddedInAPageDocumentIsReadLikeAnAnswer()
|
||||
{
|
||||
// Each valid block is an answer of its own, as the capture hands it to the readers: the collections (which say
|
||||
// «has_next_page: true» of themselves) and the post (which says «more_available: false» of itself) keep each
|
||||
// their own pagination, whatever their order in the document.
|
||||
var head = $$"""
|
||||
<!DOCTYPE html><html><head>
|
||||
<script type="application/json" data-sjs>{"require":[["Bootloader","handle",null,[{"x":1}]]]}</script>
|
||||
<script>var notData = {"a":1};</script>
|
||||
<script type="application/json">{ not json </script>
|
||||
<script type="application/json">{{SampleBody("raccolta-in-evidenza")}}</script>
|
||||
</head><body>
|
||||
<script type="application/json" data-content-len="9" data-sjs>{"require":[["ScheduledServerJS","handle",null,[{"__bbox":{"result":{"data":
|
||||
""";
|
||||
var html = head + SampleBody("post-video") + """}}}]]]}</script></body></html>""";
|
||||
var reads = new List<ReadResult>();
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(html))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
reads.Add(Reader.Read(block.RootElement));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(3, reads.Count, "Only the valid application/json blocks, in order.");
|
||||
Assert.AreEqual(ReadShape.Unrelated, reads[0].Shape, "The loader's block is not about contents.");
|
||||
Assert.AreEqual(2, reads[1].Highlights.Count);
|
||||
Assert.AreEqual(true, reads[1].Page?.HasMore);
|
||||
Assert.AreEqual(ReadShape.Recognized, reads[2].Shape);
|
||||
Assert.AreEqual(1, reads[2].Contents.Count);
|
||||
Assert.AreEqual(0, reads[2].Highlights.Count);
|
||||
Assert.AreEqual(false, reads[2].Page?.HasMore, "The post's own pagination, not the collections'.");
|
||||
|
||||
Assert.IsFalse(DataResponses.EmbeddedJsonBlocks("<html><script>var a = 1;</script></html>").Any());
|
||||
Assert.IsTrue(DataResponses.IsPageDocument("text/html", isMainFrameDocument: true));
|
||||
Assert.IsFalse(DataResponses.IsPageDocument("text/html", isMainFrameDocument: false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ABadBlockOfAPageDocumentIsLeftOutAndTheNextOnesAreStillRead()
|
||||
{
|
||||
// Text that is not valid UTF-16 (a lone surrogate: JsonDocument throws ArgumentException, not JsonException),
|
||||
// a block nested deeper than any body may be, a blank one: none of them stops the reading of the document.
|
||||
const string Open = """<script type="application/json">""";
|
||||
var html = Open + "{\"a\":\"\ud800\"}</script>" + Open + new string('[', 300) + new string(']', 300) + "</script>"
|
||||
+ Open + " </script>" + Open + """{"b":[2]}</script>""";
|
||||
var blocks = new List<string>();
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(html))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
blocks.Add(block.RootElement.GetRawText());
|
||||
}
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { """{"b":[2]}""" }, blocks);
|
||||
}
|
||||
|
||||
private static void Collect(JsonElement element, HashSet<string> paths, HashSet<string> names)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
names.Add(property.Name);
|
||||
paths.Add(property.Name);
|
||||
foreach (var below in NestedPaths(property.Value))
|
||||
{
|
||||
paths.Add(property.Name + "." + below);
|
||||
}
|
||||
|
||||
Collect(property.Value, paths, names);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
Collect(item, paths, names);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dotted paths of object keys directly below <paramref name="element"/> (two levels are enough here).</summary>
|
||||
private static IEnumerable<string> NestedPaths(JsonElement element)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
yield return property.Name;
|
||||
if (property.Value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var deeper in property.Value.EnumerateObject())
|
||||
{
|
||||
yield return property.Name + "." + deeper.Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The recipes of the profile, the history, the sweep and the following list over answers shaped like Instagram's,
|
||||
/// without a browser: the cleaned real samples of <c>tests/campioni/instagram</c> (HAR of 21 October 2026), and
|
||||
/// variants built here from them where Instagram's answer is not in the samples (the profile, the grid, the feed, the
|
||||
/// stories bar, the following list: REPERTI «Not in the sample»). The variants use only keys of the samples and move
|
||||
/// their parts around; they say nothing new about Instagram's format. Unlike the test site, the page receives what it
|
||||
/// shows in several answers, one after the other, and answers about something else in between.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class InstagramRecipeTests
|
||||
{
|
||||
private const string AlbertoId = "1000";
|
||||
|
||||
[TestMethod]
|
||||
public void TheNotFoundMarkerIsOptionalAndTheTabsStillNeedTheirTargets()
|
||||
{
|
||||
foreach (var kind in new[] { RecipeKind.ProfileCheck, RecipeKind.Backfill })
|
||||
{
|
||||
Assert.AreEqual(0, RecipeRunner.Requirements(kind).Targets.Count, kind.ToString());
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.ProfileTabTagged }, RecipeRunner.Requirements(RecipeKind.Tagged).Targets.ToArray());
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.ProfileTabReels }, RecipeRunner.Requirements(RecipeKind.Reels).Targets.ToArray());
|
||||
|
||||
var map = InstagramBed.Map();
|
||||
var (pages, targets) = RecipeRunner.Requirements(RecipeKind.ProfileCheck);
|
||||
Assert.AreEqual(0, map.Missing(pages, targets).Count, "The profile page is enough for the check.");
|
||||
var tagged = RecipeRunner.Requirements(RecipeKind.Tagged);
|
||||
CollectionAssert.AreEqual(new[] { $"bersaglio «{SiteTargets.ProfileTabTagged}» (vuoto)" }, map.Missing(tagged.Pages, tagged.Targets).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheProfileCheckKeepsTheGridAndTheCollectionsThatComeAfterTheProfile()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2002", "marta.prova");
|
||||
var marta = Author("2002", "marta.prova");
|
||||
|
||||
// The profile first; the grid asked for only after the page has settled on it; then the collections and a
|
||||
// post of another account, both saying there is nothing more of themselves.
|
||||
bed.Page.OnOpen["/marta.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(marta), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(Grid(Posts(marta, 0, 12, bed.Clock.Now.AddDays(-1)), "griglia-12", hasNext: true), TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(1.9)),
|
||||
new(Highlights("2002", "marta.prova", hasNext: false), TimeSpan.FromSeconds(1.9), TimeSpan.FromSeconds(2.3)),
|
||||
new(Sample("post-video"), TimeSpan.FromSeconds(2.0), TimeSpan.FromSeconds(2.5)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The grid came after the profile and was read.");
|
||||
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count, "So were the collections, after the grid.");
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor, "The history goes on from the grid's own page.");
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "Neither «more_available: false» of the post nor «has_next_page: false» of the collections ends it.");
|
||||
Assert.IsFalse(bed.Page.Looked.Contains(SiteTargets.ProfileNotFound), "The marker is not in the map: it is not looked for.");
|
||||
Assert.IsFalse((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code is "mappa-incompleta" or "formato-non-riconosciuto"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheMarkerAMissingProfileIsAnEmptyPageAndWithItTheAccountIsUnreachable()
|
||||
{
|
||||
await using (var bed = await InstagramBed.CreateAsync())
|
||||
{
|
||||
var account = await bed.AddAccountAsync("2004", "sparito.prova");
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message);
|
||||
Assert.AreNotEqual(AccountState.Unreachable, (await bed.Db.Accounts.GetAsync(account.Id))!.State, "Nothing says the profile is gone.");
|
||||
Assert.IsFalse(bed.Page.Looked.Contains(SiteTargets.ProfileNotFound));
|
||||
}
|
||||
|
||||
await using (var bed = await InstagramBed.CreateAsync(InstagramBed.Map(SiteTargets.ProfileNotFound)))
|
||||
{
|
||||
var account = await bed.AddAccountAsync("2004", "sparito.prova");
|
||||
bed.Page.Present.Add(SiteTargets.ProfileNotFound);
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual(AccountState.Unreachable, stored!.State);
|
||||
Assert.AreEqual(UnreachableReason.NotFound, stored.UnreachableReason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnAnswerWithoutMorePagesOfSomethingElseDoesNotEndTheHistory()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova");
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-2);
|
||||
bed.Page.OnOpen["/luca.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(Grid(Posts(luca, 0, 12, newest), "griglia-12", hasNext: true), TimeSpan.Zero, TimeSpan.Zero),
|
||||
];
|
||||
|
||||
// The first burst brings only answers about something else, each saying it has no more: a post of another
|
||||
// account and the collections. The next page of the grid comes with the second burst.
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[Sample("post-video"), Highlights("2001", "luca.prova", hasNext: false)],
|
||||
[Grid(Posts(luca, 12, 24, newest), "griglia-24", hasNext: true)],
|
||||
[Grid(Posts(luca, 24, 30, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the grid, not of the post.");
|
||||
Assert.AreEqual(30, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The answers about something else did not count as a page.");
|
||||
Assert.AreEqual(3, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageOfAPostOfTheAccountNeitherEndsTheHistoryNorCountsAsItsNextPage()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova");
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-2);
|
||||
|
||||
// After the grid, the page of one of its posts: the REST answer of the samples, «more_available: false».
|
||||
bed.Page.OnOpen["/luca.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(Grid(Posts(luca, 0, 12, newest), "griglia-12", hasNext: true), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(PostPage(Posts(luca, 3, 4, newest)[0]), TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(400)),
|
||||
];
|
||||
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor, "The history goes on from the grid's own page.");
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "«more_available: false» of the page of one of its posts does not complete it.");
|
||||
|
||||
// The first burst brings only the page of another post already read; the next page of the grid comes with the second.
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(luca, 5, 6, newest)[0])],
|
||||
[Grid(Posts(luca, 12, 24, newest), "griglia-24", hasNext: true)],
|
||||
[Grid(Posts(luca, 24, 30, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the grid, not of the post.");
|
||||
Assert.AreEqual(30, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The page of a post already read did not count as a page.");
|
||||
Assert.AreEqual(3, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnTheTaggedTabThePageOfAPostAlreadyReadDoesNotEndTheWalk()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync(InstagramBed.Map(SiteTargets.ProfileTabTagged));
|
||||
bed.Page.Present.Add(SiteTargets.ProfileTabTagged);
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova", change: a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var other = Author("2005", "altro.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-3);
|
||||
|
||||
// On the tab every post of another account is an item of the walk, the page of one of them too.
|
||||
bed.Page.OnOpen["/luca.prova/"] = [new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
bed.Page.OnClick[SiteTargets.ProfileTabTagged] =
|
||||
[
|
||||
new(Grid(Posts(other, 0, 12, newest), "taggati-12", hasNext: true), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(PostPage(Posts(other, 4, 5, newest)[0]), TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(600)),
|
||||
];
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(other, 7, 8, newest)[0])],
|
||||
[Grid(Posts(other, 12, 20, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Tagged, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the tab, not of the post.");
|
||||
Assert.AreEqual(20, (await bed.PostIdsAsync(account.Id, EntryKind.Tagged)).Count);
|
||||
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{account.Id.ToString(CultureInfo.InvariantCulture)}.completo"));
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The tab and its second page; the page of a post is not one.");
|
||||
Assert.AreEqual(2, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageOfAPostAlreadyInTheFeedDoesNotEndTheSweep()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
var nadia = Author("2003", "nadia.prova");
|
||||
var newest = bed.Clock.Now.AddHours(-1);
|
||||
bed.Page.OnOpen["/"] = [new(Grid(Posts(nadia, 0, 6, newest), "feed-6", hasNext: true), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
bed.Page.OnScroll["/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(nadia, 2, 3, newest)[0])],
|
||||
[Grid(Posts(nadia, 6, 12, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "«more_available: false» of the page of a post read already is not the end of the feed.");
|
||||
Assert.AreEqual(2, bed.Page.Scrolls, "The feed's own end stops the sweep.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEmptyCollectionsOfAnAccountWithoutAnyAreNotAnEmptyGrid()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2002", "marta.prova");
|
||||
var marta = Author("2002", "marta.prova");
|
||||
|
||||
// No collections: their answer, an empty connection saying there are no more, comes before the grid, which
|
||||
// the page asks for only after it has settled on the profile.
|
||||
bed.Page.OnOpen["/marta.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(marta), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(NoHighlights(), TimeSpan.FromMilliseconds(400), TimeSpan.FromMilliseconds(800)),
|
||||
new(Grid(Posts(marta, 0, 12, bed.Clock.Now.AddDays(-1)), "griglia-12", hasNext: true), TimeSpan.FromSeconds(1.6), TimeSpan.FromSeconds(2.0)),
|
||||
];
|
||||
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The grid was still waited for.");
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor);
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "«has_next_page: false» of the empty collections does not complete the history.");
|
||||
|
||||
// When the grid does not come, the empty collections do not stand for it either.
|
||||
var other = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
bed.Page.OnOpen["/nadia.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(Author("2003", "nadia.prova")), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(NoHighlights(), TimeSpan.FromMilliseconds(400), TimeSpan.FromMilliseconds(800)),
|
||||
];
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, other.Id)).Status);
|
||||
stored = await bed.Db.Accounts.GetAsync(other.Id);
|
||||
Assert.IsNull(stored!.BackfillCompletedAt, "Nothing said the grid is empty.");
|
||||
Assert.IsNull(stored.BackfillCursor);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestedProfilesAreNeverSavedAsFollowed()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
await bed.AddMineAsync();
|
||||
|
||||
// A profile Febe keeps that Alberto does not follow, among the suggestions of the sample.
|
||||
var suggestions = Sample("profili-suggeriti");
|
||||
var suggested = suggestions["data"]!["xdt_api__v1__discover__chaining"]!["users"]!.AsArray().Select(u => u!["username"]!.GetValue<string>()).ToList();
|
||||
var kept = await bed.AddAccountAsync(suggestions["data"]!["xdt_api__v1__discover__chaining"]!["users"]![0]!["pk"]!.GetValue<string>(), suggested[0], followed: false);
|
||||
|
||||
var followed = Enumerable.Range(0, 4).Select(i => Author((3000 + i).ToString(CultureInfo.InvariantCulture), $"seguito{i}.prova")).ToList();
|
||||
bed.Page.OnOpen["/alberto.prova/seguiti-di-prova/"] =
|
||||
[
|
||||
new(suggestions, TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(ProfileAnswer(Author(AlbertoId, "alberto.prova", following: null)), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(FollowingList(followed), TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(700)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingList);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, outcome.Message);
|
||||
var list = (await bed.Db.Following.ListAsync()).Select(f => f.Username).ToList();
|
||||
CollectionAssert.AreEquivalent(new[] { "seguito0.prova", "seguito1.prova", "seguito2.prova", "seguito3.prova" }, list, "Neither the suggestions nor Alberto himself.");
|
||||
Assert.IsFalse((await bed.Db.Accounts.GetAsync(kept.Id))!.IsFollowed, "A suggested profile is not followed.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestionsAndAlbertoAloneAreNotTheFollowingList()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
await bed.AddMineAsync();
|
||||
bed.Page.OnOpen["/alberto.prova/seguiti-di-prova/"] =
|
||||
[
|
||||
new(Sample("profili-suggeriti"), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(ProfileAnswer(Author(AlbertoId, "alberto.prova", following: null)), TimeSpan.Zero, TimeSpan.Zero),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingList);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message);
|
||||
Assert.AreEqual(0, await bed.Db.Following.CountAsync());
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(RecipeRunner.FollowingKeys.Cursor));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheConnectedAccountIsRecognizedFromItsIdentifierAndItsEntryInTheStoriesBar()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
var nadia = Author("2003", "nadia.prova", latestStoryAt: bed.Clock.Now.AddHours(-2));
|
||||
|
||||
// The feed says who the connected account is by its identifier only (xdt_viewer.user, as in the samples);
|
||||
// its name comes later, with its own entry in the stories bar.
|
||||
bed.Page.OnOpen["/"] =
|
||||
[
|
||||
new(Grid(Posts(nadia, 0, 2, bed.Clock.Now.AddHours(-5)), "feed-2", hasNext: false, viewerId: AlbertoId), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(StoriesBar(Author(AlbertoId, "alberto.prova", following: null, latestStoryAt: bed.Clock.Now.AddHours(-1)), nadia), TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(900)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
var mine = await bed.Db.Accounts.GetMineAsync();
|
||||
Assert.IsNotNull(mine, "«Tu» from the identifier of one answer and the profile of another.");
|
||||
Assert.AreEqual("alberto.prova", mine.Username);
|
||||
Assert.AreEqual(AlbertoId, mine.InstagramId);
|
||||
Assert.AreEqual(2, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsTrue(outcome.AccountsWithStories.Contains(account.Id), "The stories bar came after the feed and was read.");
|
||||
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "account-collegato"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestedProfilesAloneAreNotTheHome()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
bed.Page.OnOpen["/"] = [new(Sample("profili-suggeriti"), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.FollowingSweep)).Status);
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.FollowingSweep)).Status);
|
||||
Assert.AreEqual(0, bed.Breaker.Signals.Count);
|
||||
var third = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.StoppedBySignal, third.Status, "Three homes with nothing but suggestions are three empty pages: " + third.Message);
|
||||
Assert.AreEqual("empty-pages", bed.Breaker.Signals.Single().Code);
|
||||
Assert.IsNull(await bed.Db.Accounts.GetMineAsync());
|
||||
}
|
||||
|
||||
// ----- Answers: the cleaned samples, and variants built from them -----
|
||||
|
||||
private static string SampleFile(string name) =>
|
||||
Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
|
||||
/// <summary>The body of a cleaned sample, as the page received it.</summary>
|
||||
private static JsonObject Sample(string name) =>
|
||||
JsonNode.Parse(File.ReadAllText(SampleFile(name)))!["corpo"]!.DeepClone().AsObject();
|
||||
|
||||
/// <summary>
|
||||
/// A profile as the post of the samples describes its author (pk, username, friendship_status, latest_reel_media,
|
||||
/// the pictures), with another identity. <paramref name="following"/> null: without friendship_status.
|
||||
/// </summary>
|
||||
private static JsonObject Author(string pk, string username, bool? following = true, DateTimeOffset? latestStoryAt = null)
|
||||
{
|
||||
var user = Sample("post-video")["items"]![0]!["user"]!.DeepClone().AsObject();
|
||||
user["pk"] = pk;
|
||||
user["pk_id"] = pk;
|
||||
user["id"] = pk;
|
||||
user["strong_id__"] = pk;
|
||||
user["username"] = username;
|
||||
user["full_name"] = username;
|
||||
if (following is { } value)
|
||||
{
|
||||
user["friendship_status"]!["following"] = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Remove("friendship_status");
|
||||
}
|
||||
|
||||
if (latestStoryAt is { } latest)
|
||||
{
|
||||
user["latest_reel_media"] = latest.ToUnixTimeSeconds();
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Remove("latest_reel_media");
|
||||
}
|
||||
|
||||
Retag(user, "a" + pk);
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>Posts of <paramref name="author"/>, one hour apart going back from <paramref name="newest"/>: the post of the samples, renumbered.</summary>
|
||||
private static List<JsonObject> Posts(JsonObject author, int from, int to, DateTimeOffset newest)
|
||||
{
|
||||
var template = Sample("post-video")["items"]![0]!;
|
||||
var authorPk = author["pk"]!.GetValue<string>();
|
||||
var posts = new List<JsonObject>();
|
||||
for (var i = from; i < to; i++)
|
||||
{
|
||||
var pk = authorPk + "9" + i.ToString("D4", CultureInfo.InvariantCulture);
|
||||
var post = template.DeepClone().AsObject();
|
||||
post["pk"] = pk;
|
||||
post["id"] = $"{pk}_{authorPk}";
|
||||
post["code"] = ("C" + pk).PadRight(11, 'x')[..11];
|
||||
post["taken_at"] = newest.AddHours(-i).ToUnixTimeSeconds();
|
||||
Retag(post, "p" + pk);
|
||||
post["user"] = author.DeepClone();
|
||||
post["owner"] = author.DeepClone();
|
||||
posts.Add(post);
|
||||
}
|
||||
|
||||
return posts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A page of posts: Instagram's grid and feed are not in the samples, so the posts go into the GraphQL connection
|
||||
/// the samples show (data.…connection.edges[].node, page_info), with xdt_viewer.user when given.
|
||||
/// </summary>
|
||||
private static JsonObject Grid(IEnumerable<JsonObject> posts, string? cursor, bool hasNext, string? viewerId = null)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var data = body["data"]!.AsObject();
|
||||
var connection = data["xdt_api__v1__feed__reels_media__connection"]!.AsObject();
|
||||
connection["edges"] = new JsonArray([.. posts.Select(p => (JsonNode)new JsonObject { ["node"] = p, ["cursor"] = null })]);
|
||||
connection["page_info"]!["end_cursor"] = cursor;
|
||||
connection["page_info"]!["has_next_page"] = hasNext;
|
||||
if (viewerId is null)
|
||||
{
|
||||
data.Remove("xdt_viewer");
|
||||
}
|
||||
else
|
||||
{
|
||||
var user = data["xdt_viewer"]!["user"]!;
|
||||
user["pk"] = viewerId;
|
||||
user["id"] = viewerId;
|
||||
user["user_id"] = viewerId;
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The collections of the samples, as if of another account, saying whether there are more of them.</summary>
|
||||
private static JsonObject Highlights(string pk, string username, bool hasNext)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var connection = body["data"]!["xdt_api__v1__feed__reels_media__connection"]!;
|
||||
foreach (var node in connection["edges"]!.AsArray().Select(e => e!["node"]!))
|
||||
{
|
||||
var owner = node["user"]!;
|
||||
owner["pk"] = pk;
|
||||
owner["id"] = pk;
|
||||
owner["user_id"] = pk;
|
||||
owner["username"] = username;
|
||||
foreach (var item in node["items"]!.AsArray())
|
||||
{
|
||||
item!["user"]!["pk"] = pk;
|
||||
item["user"]!["id"] = pk;
|
||||
item["user"]!["instagram_pk"] = pk;
|
||||
}
|
||||
}
|
||||
|
||||
connection["page_info"]!["has_next_page"] = hasNext;
|
||||
body["data"]!.AsObject().Remove("xdt_viewer");
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The collections of an account that has none: the connection of the samples without edges, saying there are no more.</summary>
|
||||
private static JsonObject NoHighlights()
|
||||
{
|
||||
var body = Highlights("0", "nessuno.prova", hasNext: false);
|
||||
body["data"]!["xdt_api__v1__feed__reels_media__connection"]!["edges"] = new JsonArray();
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The page of one post: the REST answer of the samples («more_available: false») with <paramref name="post"/> as its item.</summary>
|
||||
private static JsonObject PostPage(JsonObject post)
|
||||
{
|
||||
var body = Sample("post-video");
|
||||
body["items"] = new JsonArray(post);
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>A profile on its own (data.user): Instagram's profile answer is not in the samples.</summary>
|
||||
private static JsonObject ProfileAnswer(JsonObject profile) => new() { ["data"] = new JsonObject { ["user"] = profile.DeepClone() } };
|
||||
|
||||
/// <summary>
|
||||
/// The stories bar of the home, not in the samples: the reels of the samples (XDTReelDict) without what makes them a
|
||||
/// collection (title, items), one per account, its author in «user».
|
||||
/// </summary>
|
||||
private static JsonObject StoriesBar(params JsonObject[] authors)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var data = body["data"]!.AsObject();
|
||||
var connection = data["xdt_api__v1__feed__reels_media__connection"]!.AsObject();
|
||||
var template = connection["edges"]![0]!["node"]!;
|
||||
connection["edges"] = new JsonArray([.. authors.Select(author =>
|
||||
{
|
||||
var reel = template.DeepClone().AsObject();
|
||||
reel.Remove("title");
|
||||
reel.Remove("items");
|
||||
reel.Remove("cover_media");
|
||||
reel["id"] = author["pk"]!.GetValue<string>();
|
||||
reel["user"] = author.DeepClone();
|
||||
reel["latest_reel_media"] = author["latest_reel_media"]?.DeepClone();
|
||||
return (JsonNode)new JsonObject { ["node"] = reel, ["cursor"] = null };
|
||||
})]);
|
||||
connection.Remove("page_info");
|
||||
data.Remove("xdt_viewer");
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The following list, not in the samples: its profiles in «users», as the suggestions of the samples have them, and «more_available».</summary>
|
||||
private static JsonObject FollowingList(IEnumerable<JsonObject> profiles) => new()
|
||||
{
|
||||
["users"] = new JsonArray([.. profiles.Select(p => (JsonNode)p.DeepClone())]),
|
||||
["more_available"] = false,
|
||||
};
|
||||
|
||||
/// <summary>Gives the file addresses of a copied part their own name, so that copies are different files.</summary>
|
||||
private static void Retag(JsonNode node, string tag)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case JsonObject obj:
|
||||
foreach (var (key, value) in obj.ToList())
|
||||
{
|
||||
if (value is JsonValue v && v.TryGetValue<string>(out var text) && text.StartsWith("https://cdn.esempio/", StringComparison.Ordinal))
|
||||
{
|
||||
obj[key] = "https://cdn.esempio/" + tag + "-" + text["https://cdn.esempio/".Length..];
|
||||
}
|
||||
else if (value is not null)
|
||||
{
|
||||
Retag(value, tag);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonArray array:
|
||||
foreach (var item in array.Where(i => i is not null))
|
||||
{
|
||||
Retag(item!, tag);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ----- The bed: a page driver that hands the capture Instagram-shaped answers over time -----
|
||||
|
||||
/// <summary>An answer of a page: its response seen at <paramref name="Announced"/>, its body read at <paramref name="Delivered"/>.</summary>
|
||||
private sealed record Answer(JsonNode Body, TimeSpan Announced, TimeSpan Delivered);
|
||||
|
||||
/// <summary>A virtual clock that also runs what is due when time passes: bodies arrive while the recipe waits.</summary>
|
||||
private sealed class StepClock(DateTimeOffset start) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<(DateTimeOffset At, long Order, Action Action)> _due = [];
|
||||
private DateTimeOffset _now = start;
|
||||
private long _order;
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
||||
|
||||
public void After(TimeSpan delay, Action action)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_due.Add((_now + delay, _order++, action));
|
||||
}
|
||||
}
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
List<Action> due;
|
||||
lock (_gate)
|
||||
{
|
||||
if (time > TimeSpan.Zero)
|
||||
{
|
||||
_now += time;
|
||||
}
|
||||
|
||||
due = [.. _due.Where(d => d.At <= _now).OrderBy(d => d.At).ThenBy(d => d.Order).Select(d => d.Action)];
|
||||
_due.RemoveAll(d => d.At <= _now);
|
||||
}
|
||||
|
||||
foreach (var action in due)
|
||||
{
|
||||
action();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page: opening a path hands the capture its answers (each seen as a response first, its body read later, as
|
||||
/// the browser does), and so does a click on a target; a burst hands it the next answers queued for the path.
|
||||
/// Targets are found only when present.
|
||||
/// </summary>
|
||||
private sealed class InstagramPage(CaptureCollector capture, StepClock clock) : IPageDriver
|
||||
{
|
||||
private int _requests;
|
||||
|
||||
public Dictionary<string, List<Answer>> OnOpen { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, List<Answer>> OnClick { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, Queue<IReadOnlyList<JsonNode>>> OnScroll { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public HashSet<string> Present { get; } = [];
|
||||
|
||||
public List<string> Looked { get; } = [];
|
||||
|
||||
public int Scrolls { get; private set; }
|
||||
|
||||
public string CurrentPath { get; private set; } = "about:blank";
|
||||
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public void BeginSession(double mood)
|
||||
{
|
||||
}
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
CurrentPath = path;
|
||||
foreach (var answer in OnOpen.GetValueOrDefault(path) ?? [])
|
||||
{
|
||||
Send(answer.Body, answer.Announced, answer.Delivered);
|
||||
}
|
||||
|
||||
return Task.FromResult(new PageLoad(true, path, null));
|
||||
}
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => Task.FromResult(CurrentPath);
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
Looked.Add(target);
|
||||
return Task.FromResult(Present.Contains(target)
|
||||
? new TargetCheck(target, TargetCheckStatus.Found, 1, "Trovato.")
|
||||
: new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
|
||||
}
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
if (!Present.Contains(target))
|
||||
{
|
||||
return Task.FromResult(new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
|
||||
}
|
||||
|
||||
foreach (var answer in OnClick.GetValueOrDefault(target) ?? [])
|
||||
{
|
||||
Send(answer.Body, answer.Announced, answer.Delivered);
|
||||
}
|
||||
|
||||
return Task.FromResult(new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato."));
|
||||
}
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct)
|
||||
{
|
||||
Scrolls++;
|
||||
if (OnScroll.TryGetValue(CurrentPath, out var queue) && queue.Count > 0)
|
||||
{
|
||||
foreach (var body in queue.Dequeue())
|
||||
{
|
||||
Send(body, TimeSpan.Zero, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(true);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
CurrentPath = "about:blank";
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void Send(JsonNode body, TimeSpan announced, TimeSpan delivered)
|
||||
{
|
||||
var id = "r" + Interlocked.Increment(ref _requests).ToString(CultureInfo.InvariantCulture);
|
||||
var descriptor = new ResponseDescriptor(id, HostKind.Site, "https://sito.esempio/graphql/query", "sito.esempio", "/graphql/query", 200, "text/javascript", "XHR", false, clock.Now);
|
||||
var text = body.ToJsonString();
|
||||
void Announce() => ((IResponseObserver)capture).OnResponse(descriptor);
|
||||
void Deliver()
|
||||
{
|
||||
using var document = JsonDocument.Parse(text);
|
||||
capture.Accept(descriptor, document.RootElement);
|
||||
}
|
||||
|
||||
if (delivered <= TimeSpan.Zero)
|
||||
{
|
||||
Announce();
|
||||
Deliver();
|
||||
return;
|
||||
}
|
||||
|
||||
clock.After(announced, Announce);
|
||||
clock.After(delivered, Deliver);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Database, clock, Governor, signals and runner over <see cref="InstagramPage"/> and the Instagram vocabulary.</summary>
|
||||
private sealed class InstagramBed : IAsyncDisposable
|
||||
{
|
||||
private InstagramBed(TempFolder temp, FebeDatabase db, StepClock clock, InstagramPage page, RecipeRunner runner, TestSession session)
|
||||
{
|
||||
Temp = temp;
|
||||
Db = db;
|
||||
Clock = clock;
|
||||
Page = page;
|
||||
Runner = runner;
|
||||
Session = session;
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public FebeDatabase Db { get; }
|
||||
|
||||
public StepClock Clock { get; }
|
||||
|
||||
public InstagramPage Page { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
public TestSession Session { get; }
|
||||
|
||||
public PermissiveGovernor Governor => (PermissiveGovernor)Runner.Env.Governor;
|
||||
|
||||
public RecordingBreaker Breaker => (RecordingBreaker)Runner.Env.Breaker!;
|
||||
|
||||
/// <summary>
|
||||
/// Pages with Instagram's addresses where the samples show them (home, profile, post: route definitions of the
|
||||
/// HAR); the following list has an address of the test, Instagram's is not in the samples. Targets: only
|
||||
/// <paramref name="configured"/>.
|
||||
/// </summary>
|
||||
public static SiteMap Map(params string[] configured) => new(
|
||||
"instagram",
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[SitePages.Home] = "/",
|
||||
[SitePages.Profile] = "/{username}/",
|
||||
[SitePages.Post] = "/p/{code}/",
|
||||
[SitePages.Following] = "/{username}/seguiti-di-prova/",
|
||||
},
|
||||
configured,
|
||||
SiteTargets.All);
|
||||
|
||||
public static async Task<InstagramBed> CreateAsync(SiteMap? map = null)
|
||||
{
|
||||
var temp = new TempFolder("ricette-instagram");
|
||||
var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new StepClock(new DateTimeOffset(2026, 10, 25, 9, 0, 0, TimeSpan.Zero));
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
|
||||
var page = new InstagramPage(capture, clock);
|
||||
var breaker = new RecordingBreaker();
|
||||
var governor = new PermissiveGovernor();
|
||||
var runner = new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = page,
|
||||
Capture = capture,
|
||||
Governor = governor,
|
||||
Budget = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), breaker, clock),
|
||||
Storage = db,
|
||||
SiteMap = map ?? Map(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(7),
|
||||
Breaker = breaker,
|
||||
});
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
return new InstagramBed(temp, db, clock, page, runner, session);
|
||||
}
|
||||
|
||||
public Task<Account> AddAccountAsync(string instagramId, string username, bool followed = true, Func<Account, Account>? change = null)
|
||||
{
|
||||
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome) with
|
||||
{
|
||||
InstagramId = instagramId,
|
||||
IsFollowed = followed,
|
||||
};
|
||||
return Db.Accounts.AddAsync(change is null ? account : change(account));
|
||||
}
|
||||
|
||||
public Task<Account> AddMineAsync() =>
|
||||
Db.Accounts.AddAsync(Account.Create("alberto.prova", StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome, isMine: true) with { InstagramId = AlbertoId });
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, int? maxPages = null) =>
|
||||
Runner.RunAsync(new RecipeRequest(kind, accountId, MaxPages: maxPages), Session, CancellationToken.None);
|
||||
|
||||
public async Task<IReadOnlyList<string>> PostIdsAsync(long accountId, EntryKind kind = EntryKind.Post) =>
|
||||
[.. (await Db.Entries.ListByAccountAsync(accountId, new EntryListOptions { Kind = kind, Limit = 1000 })).Select(e => e.InstagramId!)];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Db.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The generic reader (spec §6.4) on the cleaned samples of <c>tests/campioni/prova</c>: captured from the test site,
|
||||
/// cleaned with «febe-sonda ripulisci» and checked with «febe-sonda verifica». Never real Instagram samples: there
|
||||
/// are none yet (rule 10).
|
||||
/// cleaned with «febe-sonda ripulisci» and checked with «febe-sonda verifica». The real Instagram samples have their
|
||||
/// own tests (<see cref="InstagramReaderTests"/>).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ReaderTests
|
||||
@@ -199,31 +199,16 @@ public sealed class ReaderTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheShippedVocabulariesLoadAndInstagramsIsOnlyAHypothesis()
|
||||
public void TheShippedVocabulariesLoad()
|
||||
{
|
||||
var test = ReaderVocabulary.LoadTestSite();
|
||||
Assert.IsTrue(test.IsUsable, test.UnusableReason);
|
||||
Assert.AreEqual(0, test.Relevance.Count, "On the test site every unknown answer is a format change.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.prova.json")), "Editable without recompiling.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.instagram.json")));
|
||||
|
||||
var instagram = ReaderVocabulary.LoadInstagram();
|
||||
Assert.AreEqual(VocabularyStatus.Hypothesis, instagram.Status);
|
||||
Assert.IsFalse(instagram.IsUsable);
|
||||
StringAssert.Contains(instagram.UnusableReason, "ipotesi");
|
||||
StringAssert.Contains(instagram.Note, "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0");
|
||||
|
||||
// Only the hint keys of spec §6.4: nothing invented (rule 10).
|
||||
var keys = new[]
|
||||
{
|
||||
instagram.Content.Id, instagram.Content.Code, instagram.Content.TakenAt, instagram.Content.Caption, instagram.Content.Images,
|
||||
instagram.Content.Videos, instagram.Content.Children, instagram.Content.ChildCount, instagram.Content.Owner, instagram.Content.Pinned,
|
||||
instagram.Content.ExpiresAt, instagram.Content.Duration, instagram.Version.Url, instagram.Version.Width, instagram.Version.Height,
|
||||
instagram.Version.HasAudio, instagram.Profile.Id, instagram.Profile.Username, instagram.Profile.DisplayName, instagram.Profile.IsPrivate,
|
||||
instagram.Profile.IsFollowed, instagram.Profile.PostCount, instagram.Profile.Picture, instagram.Profile.LatestStoryAt,
|
||||
instagram.Highlight.Id, instagram.Highlight.Title, instagram.Highlight.Owner, instagram.Highlight.Items,
|
||||
instagram.Page.HasMore, instagram.Page.Cursor, instagram.Viewer,
|
||||
}.SelectMany(k => k.Paths).Order().ToArray();
|
||||
CollectionAssert.AreEqual(new[] { "carousel_media", "code", "image_versions2.candidates", "pk", "taken_at", "video_versions" }, keys);
|
||||
// Instagram's vocabulary has its own tests on the real cleaned samples (InstagramReaderTests).
|
||||
Assert.IsTrue(ReaderVocabulary.LoadInstagram().IsUsable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -134,6 +134,39 @@ public sealed class RecipeRuleTests
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{account.Id}.cursore"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AProfileWithCollectionsAndNoPostsHasItsWholeHistoryInTheFirstAnswer()
|
||||
{
|
||||
// The test site sends the collections with the first page of the grid, here empty: the profile in the same
|
||||
// answer says there are no posts.
|
||||
await using var bed = await ScriptedBed.CreateAsync();
|
||||
var timeout = new RecipeOptions().DataTimeout;
|
||||
var vera = bed.Site.Add(new ScriptedAccount("2006", "vera.prova"));
|
||||
vera.HighlightsWithItems.Add(("h1", "Estate", []));
|
||||
var account = await bed.AddAccountAsync(vera, a => a with { State = AccountState.Backfilling });
|
||||
|
||||
var start = bed.Clock.Now;
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.IsTrue(bed.Clock.Now - start < timeout, "The empty grid came with the profile: no wait for another one.");
|
||||
Assert.AreEqual(1, (await bed.Db.Highlights.ListAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.IsTrue(check.BackfillFinished, "Its history is complete, with nothing in it.");
|
||||
|
||||
// The history of an account like it, not marked complete yet, ends at the profile without a page of its own.
|
||||
var lia = bed.Site.Add(new ScriptedAccount("2007", "lia.prova"));
|
||||
lia.HighlightsWithItems.Add(("h2", "Inverno", []));
|
||||
var other = await bed.AddAccountAsync(lia, a => a with { State = AccountState.Backfilling });
|
||||
start = bed.Clock.Now;
|
||||
var backfill = await bed.RunAsync(RecipeKind.Backfill, other.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, backfill.Status, backfill.Message);
|
||||
Assert.IsTrue(backfill.BackfillFinished, backfill.Message);
|
||||
Assert.IsTrue(bed.Clock.Now - start < timeout);
|
||||
Assert.AreEqual(0, bed.Governor.Granted(ActionKind.BackfillPage), "No page asked for after the profile.");
|
||||
Assert.AreEqual(0, bed.Site.Scrolls);
|
||||
Assert.AreEqual(0, bed.Breaker.Signals.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AResponseUnrelatedToThePageNeitherEndsTheWalkNorStopsTheRecipe()
|
||||
{
|
||||
|
||||
@@ -193,6 +193,24 @@ public sealed class SanitizerTests
|
||||
StringAssert.EndsWith(node["c"]!.GetValue<string>(), ".webp");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ValuesUnderSecretLikeKeysBecomeANeutralFillerOfTheSameShape()
|
||||
{
|
||||
// A fake drawn letter by letter from a long token still looks like a token to a secret scanner (gitleaks).
|
||||
var sanitizer = new SampleSanitizer(key: new byte[32]);
|
||||
// Built at run time, so the source itself holds no token-like literal next to a token-like key (gitleaks).
|
||||
var tracked = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("""{"version":5,"payload":{"is_analytics_tracked":true"""));
|
||||
var ranked = new Guid(0x18f2c1b0, 0xaa77, 0x4c2e, 0x9e, 0x1d, 0x0c, 0x6a, 0x1b, 0x2c, 0x3d, 0x4e).ToString();
|
||||
var node = sanitizer.Sanitize(JsonNode.Parse(new JsonObject { ["organic_tracking_token"] = tracked, ["rank_token"] = ranked, ["nome"] = "Lucia" }.ToJsonString()))!;
|
||||
Assert.AreEqual("xxx7xxxx", node["organic_tracking_token"]!.GetValue<string>()[..8]);
|
||||
Assert.IsTrue(node["organic_tracking_token"]!.GetValue<string>().All(c => c is 'x' or '7'));
|
||||
Assert.AreEqual("77x7x7x7-xx77-7x7x-7x7x-7x7x7x7x7x7x", node["rank_token"]!.GetValue<string>());
|
||||
Assert.AreNotEqual("Lucia", node["nome"]!.GetValue<string>());
|
||||
Assert.IsFalse(node["nome"]!.GetValue<string>().All(c => c == 'x'), "Ordinary values keep their varied fakes.");
|
||||
Assert.IsTrue(SampleSanitizer.LooksLikeSecretKey("client_cache_key"));
|
||||
Assert.IsFalse(SampleSanitizer.LooksLikeSecretKey("username"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProbeReadsOnlyThroughAReadOnlyScript() =>
|
||||
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(ProbeRecorder.InteractionScript);
|
||||
@@ -209,5 +227,31 @@ public sealed class SanitizerTests
|
||||
using var document = JsonDocument.Parse(text);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _));
|
||||
}
|
||||
|
||||
// The same for tests/campioni/instagram: no address of Instagram or of its CDN, every address a fake one.
|
||||
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json"))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (var host in new[] { "instagram.com", "cdninstagram", "fbcdn" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(host, StringComparison.OrdinalIgnoreCase), $"{file}: {host}");
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(text);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("descrittore", out _), file);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _), file);
|
||||
foreach (var address in Strings(document.RootElement).Where(v => v.StartsWith("http", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Assert.IsTrue(System.Text.RegularExpressions.Regex.IsMatch(address, @"^https://(sito|cdn|altro)\.esempio/"), $"{file}: indirizzo non ripulito");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> Strings(JsonElement element) => element.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => [element.GetString()!],
|
||||
JsonValueKind.Object => element.EnumerateObject().SelectMany(p => Strings(p.Value)),
|
||||
JsonValueKind.Array => element.EnumerateArray().SelectMany(Strings),
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the viewer of the scripted site receives, in the format of the test site (<c>lettori.prova.json</c>).</summary>
|
||||
internal static class ViewerAnswers
|
||||
{
|
||||
/// <summary>A collection of <paramref name="owner"/> as the viewer receives it: «highlight:» before the identifier, as Instagram writes it.</summary>
|
||||
public static Viewable Highlight(ScriptedAccount owner, string id, string title, IReadOnlyList<ViewerItem> 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<ViewerItem> items) => new()
|
||||
{
|
||||
["numero"] = "highlight:" + id,
|
||||
["titolo"] = title,
|
||||
["autore"] = ScriptedSite.Lite(owner),
|
||||
["contenuti"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: false))]),
|
||||
};
|
||||
|
||||
/// <summary>The stories of <paramref name="owner"/> as the viewer receives them, after <paramref name="before"/> when given.</summary>
|
||||
public static Viewable Stories(ScriptedAccount owner, IReadOnlyList<ViewerItem> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An item of a viewer: how long it stays on screen before the viewer moves on by itself, and its video length.</summary>
|
||||
internal sealed record ViewerItem(string Id, TimeSpan? OnScreen = null, TimeSpan? Video = null);
|
||||
|
||||
/// <summary>What a viewer shows for one owner (an account, or a collection), and what the page receives when it opens.</summary>
|
||||
/// <param name="Kind">«storie» or «evidenza», the first segment of its address.</param>
|
||||
/// <param name="Key">The owner in the address: user name, or identifier of the collection.</param>
|
||||
internal sealed record Viewable(string Kind, string Key, string Title, IReadOnlyList<ViewerItem> Items, JsonObject Body)
|
||||
{
|
||||
/// <summary>The owner the viewer moves on to by itself after the last item (another account, another collection).</summary>
|
||||
public string? Next { get; init; }
|
||||
|
||||
/// <summary>An answer of its own the page receives right after <see cref="Body"/> (the grid of the profile, say).</summary>
|
||||
public JsonObject? Then { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="StartAt"/>) 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 <see cref="Viewable.Next"/> or closes; «viewer-close» goes back to the page it was opened
|
||||
/// from. The address carries the item shown only with <see cref="AddressWithItem"/>.
|
||||
/// </summary>
|
||||
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<string, Viewable> _viewables = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Viewable? _open;
|
||||
private int _index;
|
||||
private DateTimeOffset _since;
|
||||
private int _responses;
|
||||
private int _waits;
|
||||
|
||||
public bool AddressWithItem { get; init; }
|
||||
|
||||
/// <summary>The item the viewer opens on (a site that resumes from the first item not seen).</summary>
|
||||
public int StartAt { get; set; }
|
||||
|
||||
/// <summary>The click on «next» (from 1) that throws, as a broken connection with the browser would.</summary>
|
||||
public int? FailAtNextClick { get; set; }
|
||||
|
||||
/// <summary>«viewer-close» is found, but the viewer stays open (a click that lands on the wrong element).</summary>
|
||||
public bool IgnoresClose { get; set; }
|
||||
|
||||
/// <summary>The wait (from 1) during which the source is cancelled: the wait then throws, as <see cref="Task.Delay(TimeSpan, CancellationToken)"/> would.</summary>
|
||||
public (int Wait, CancellationTokenSource Source)? CancelAtWait { get; set; }
|
||||
|
||||
/// <summary>An answer unrelated to the account (suggested profiles) that arrives with every page opened.</summary>
|
||||
public JsonObject? AlongsideEveryPage { get; set; }
|
||||
|
||||
/// <summary>The items that came on screen, in order.</summary>
|
||||
public List<string> Seen { get; } = [];
|
||||
|
||||
public int NextClicks { get; private set; }
|
||||
|
||||
public int CloseClicks { get; private set; }
|
||||
|
||||
/// <summary>The address of the first viewer opened.</summary>
|
||||
public string? OpenedAt { get; private set; }
|
||||
|
||||
public double WaitMultiplier { get; init; } = 1;
|
||||
|
||||
public void Add(Viewable viewable) => _viewables[viewable.Kind + "/" + viewable.Key] = viewable;
|
||||
|
||||
/// <summary>How many items have come on screen until now.</summary>
|
||||
public int OnScreenSoFar()
|
||||
{
|
||||
Tick();
|
||||
return Seen.Count;
|
||||
}
|
||||
|
||||
public void BeginSession(double mood) => site.BeginSession(mood);
|
||||
|
||||
public async Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
_open = null;
|
||||
var load = await site.OpenAsync(path, ct);
|
||||
if (AlongsideEveryPage is { } other)
|
||||
{
|
||||
Deliver(other);
|
||||
}
|
||||
|
||||
return load;
|
||||
}
|
||||
|
||||
public Task<string> 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<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => site.FindAsync(target, parameters, ct);
|
||||
|
||||
public async Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? 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<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The viewer moves on by itself when an item has been on screen for its time.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A scripted bed whose page has a viewer; the Governor can make every story permit wait, like its minimum spacing.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>What was on screen at each story permit granted.</summary>
|
||||
public PermitWatcher Permits { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
/// <param name="itemInAddress">Whether the map's viewer addresses carry the item shown.</param>
|
||||
/// <param name="spacing">Every story permit first waits this long (the Governor's minimum spacing).</param>
|
||||
/// <param name="waitMultiplier">Mood × pace of the page driver.</param>
|
||||
/// <param name="random">The random source of the recipes (a seeded one by default).</param>
|
||||
/// <param name="siteWritesItem">Whether the site writes the item in the address (as the map says, by default).</param>
|
||||
/// <param name="storyGrants">After this many story permits the Governor refuses, while the budget says there is room.</param>
|
||||
public static async Task<ViewerBed> 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 }));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «nadia.prova» with two collections on her profile, «Estate» (e0–e3, or <paramref name="summer"/>) 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.
|
||||
/// </summary>
|
||||
public async Task<(ScriptedAccount Scripted, Account Account)> AddCollectionsAsync(IReadOnlyList<ViewerItem>? 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<ViewerItem> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<RecipeOutcome> RunAsync(RecipeRequest request, CancellationToken ct = default) => Runner.RunAsync(request, Bed.Session, ct);
|
||||
|
||||
public Task<RecipeOutcome> RunHighlightAsync(Account account, string highlightId) =>
|
||||
RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: highlightId));
|
||||
|
||||
/// <summary>Instagram identifiers of the items of a collection, in their order.</summary>
|
||||
public async Task<IReadOnlyList<string>> 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<string>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Grants what the inner Governor grants, but every story permit first waits <paramref name="spacing"/> (its minimum spacing).</summary>
|
||||
internal sealed class SpacedGovernor(IGovernor inner, VirtualClock clock, TimeSpan spacing) : IGovernor
|
||||
{
|
||||
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
|
||||
{
|
||||
if (kind == ActionKind.StoryView)
|
||||
{
|
||||
clock.Advance(spacing);
|
||||
}
|
||||
|
||||
return inner.RequestAsync(kind, accountId, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Grants what the inner Governor grants, but refuses story permits after <paramref name="grants"/> (the budget view still says there is room).</summary>
|
||||
internal sealed class StoryGrantsGovernor(IGovernor inner, int grants) : IGovernor
|
||||
{
|
||||
private int _granted;
|
||||
|
||||
public Task<Permit> 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);
|
||||
}
|
||||
|
||||
/// <summary>Passes every request on and records, at each story permit granted, how many items had come on screen.</summary>
|
||||
internal sealed class PermitWatcher(IGovernor inner, ViewerSite viewer) : IGovernor
|
||||
{
|
||||
public List<int> OnScreenAtStoryPermit { get; } = [];
|
||||
|
||||
public async Task<Permit> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A degenerate random source: always the same value (the draws of §7.2 come out the same every time).</summary>
|
||||
internal sealed class FixedRandom(double value) : IRandomSource
|
||||
{
|
||||
public double NextDouble() => value;
|
||||
}
|
||||
Reference in new issue
Block a user