diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md new file mode 100644 index 0000000..ba1e7e4 --- /dev/null +++ b/docs/prove-dal-vivo.md @@ -0,0 +1,126 @@ +# Prove dal vivo (specifica §14.4) + +Le esegue **solo Alberto**, con l'**account di prova** (domanda 2 di §16), mai con l'account principale prima della +fine di M3. Ogni elenco dice che cosa fare, che cosa aspettarsi e che cosa riferire. Se in qualunque momento compare +una verifica, un CAPTCHA o un avviso dell'account: **fermarsi**, risolvere a mano nel browser, annotare l'ora e +riferire. + +--- + +## A. Sonda passiva di M0 + +Scopo: raccogliere ciò che Instagram manda al browser mentre navighi tu, per scrivere lettori e mappa dei bersagli +(ipotesi H1–H11 di `docs/sonda/esito.md`). **La sonda non compie gesti e non apre pagine da sola**: naviga solo Alberto. + +### A1. Prima di cominciare + +- Una cartella **fuori da qualunque repository git**, per esempio `~/febe-sonda/2026-10-14`. La sonda rifiuta una + cartella dentro un repository. +- Il programma: `dotnet run --project tools/Febe.Sonda -- …` dal repository, oppure l'eseguibile `febe-sonda`. +- Su Linux con un desktop basta il display normale; in Docker serve un display visibile (la sonda non ha una sua + vista remota): conviene farla su un computer con lo schermo. + +### A2. Avvio + +```sh +febe-sonda registra --cartella ~/febe-sonda/2026-10-14 [--display :0] [--chromium /percorso/chromium] +``` + +Si apre una finestra di Chromium vuota. Nella finestra scrivi tu `instagram.com` e accedi con l'account di prova +(password e codici li scrivi tu: la sonda non li vede e non li registra; registra solo le risposte JSON e i comandi +su cui passi). + +### A3. Che cosa aprire, nell'ordine + +Muoviti con calma, come faresti di solito. Per i comandi elencati in **grassetto**, prima di usarli **passaci sopra +col puntatore per un secondo**: è così che la sonda ne registra ruolo e nome accessibile (H11). + +1. **Home.** Attendi il caricamento; scorri piano per una decina di post. Passa sopra la **prima voce della barra + delle storie**. Ci si aspetta: la barra in alto, i post dei profili seguiti. +2. **Un profilo pubblico che non segui.** Scrivi l'indirizzo del profilo. Passa sopra **la foto del profilo**, le + **schede** (post, reel, taggati) e una **raccolta in evidenza**. Scorri la griglia per 3–4 schermate (devono + caricarsi altri post). +3. **Un profilo privato che segui.** Come al passo 2. +4. **Le storie di un seguito.** Dal suo profilo clicca la **foto con l'anello**. Guarda 2–3 storie; per andare avanti + clicca la **zona a destra** (passandoci sopra prima). Prima che finiscano, passa sopra la **X** e **chiudi**: non + lasciare che il visualizzatore passi da solo all'account successivo. +5. **Una raccolta in evidenza.** Da un profilo apri una **raccolta**, guarda 2 contenuti, **chiudi** con la X. Se + puoi, scegli una raccolta che contenga una storia ancora attiva (H9): per esempio pubblica una storia con l'account + di prova e mettila in evidenza. +6. **La scheda «Taggati»** di un profilo (anche il tuo) e la scheda **«Reel»**: aprile e scorri un poco. +7. **L'elenco dei profili che segui.** Dal tuo profilo apri **«Seguiti»** e scorri 3–4 schermate. +8. **Un post singolo**: aprine uno dalla griglia, meglio se è una serie con un video. + +Ci si aspetta: nessuna verifica, nessun avviso. La console della sonda non scrive nulla mentre navighi. + +### A4. Fine della registrazione + +Premi **Invio** nella console. La sonda dice quante risposte, navigazioni e interazioni ha registrato. Nella cartella: +`risposte/`, `navigazioni.jsonl`, `interazioni.jsonl`, `LEGGIMI.txt` e `profilo-browser/` (contiene la sessione: +**non si invia mai**). + +### A5. Ripulitura e verifica (sulla tua macchina) + +```sh +febe-sonda ripulisci --da ~/febe-sonda/2026-10-14 --a ~/febe-sonda/2026-10-14-ripuliti +febe-sonda verifica --grezzi ~/febe-sonda/2026-10-14 --ripuliti ~/febe-sonda/2026-10-14-ripuliti +``` + +La verifica deve dire **«Verifica superata»**. Se no, dice in quali file sopravvive un frammento (mai il frammento +stesso): non inviare nulla e riferisci il messaggio. + +### A6. Che cosa mandare + +1. La cartella **ripulita** (compressa) e il testo della verifica. +2. Per la mappa dei bersagli (H11): dal file **grezzo** `interazioni.jsonl`, le sole righe dei comandi + dell'interfaccia (anello delle storie, zona «avanti», X di chiusura, schede, raccolta, voce della barra, «Seguiti»). + **Prima di inviarle**, sostituisci a mano ogni nome di persona con `NOME`: servono il ruolo, il nome del comando + (per esempio «Chiudi») e la forma del collegamento, non i nomi. +3. Le note: a che ora hai fatto ogni passo, se qualcosa è andato diversamente da come descritto. + +Mai: la cartella grezza, la cartella `profilo-browser`, schermate con nomi di altre persone. + +### A7. Dopo + +Quando i lettori e la mappa sono stati scritti sui campioni ripuliti, **cancella la cartella grezza** (§14.5). + +--- + +## B. Prima sessione dal vivo, dopo M3 + +Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, e i file arrivare in libreria. + +### B1. Condizioni + +- M3 chiusa: prove del motore verdi e numeri della simulazione di 30 giorni letti da te. +- `bersagli.instagram.json` e `lettori.instagram.json` compilati sui campioni di M0 e portati a «confermato» + (altrimenti le ricette rispondono «la mappa dei bersagli non è ancora compilata» e non fanno nulla). +- Account di prova; nessun altro Febe acceso sullo stesso account. + +### B2. Passi + +1. Avvia Febe (Docker o Windows) e apri **Collegamento**: accedi a mano con l'account di prova. +2. In **Limiti e comportamento** controlla che il profilo sia **Prudente**. +3. Aggiungi **un solo** profilo **pubblico**, con pochi post (meno di 30), punto di partenza «Scarica tutto e tieni + aggiornato». Nient'altro. +4. Attendi: la prima sessione parte fra 2 e 10 minuti dall'avvio. Guarda la pagina **Attività**. + +### B3. Che cosa aspettarsi + +- Una sessione breve (2–10 minuti): un'apertura del profilo, qualche pagina di storico, poche azioni in tutto. +- Nessuna striscia rossa; nessun «formato non riconosciuto». +- In **Libreria**, nella cartella del profilo: `post//___.jpg|mp4`, e il file + `_febe.jsonl`. I file si aprono e sono le versioni grandi. +- A fine sessione il browser torna alla pagina vuota. + +### B4. Che cosa riferire + +- Schermata della pagina Attività a fine sessione (striscia della giornata e tetti). +- L'elenco dei file arrivati (nomi e dimensioni) e se qualcuno è rimasto «da scaricare», «scaduto» o «fallito». +- Ogni evento in giallo o rosso della cronologia, con l'ora. +- Se è comparsa una verifica: che cosa diceva, a che ora, che cosa stava facendo Febe (la pagina resta com'era). + +### B5. Se qualcosa va storto + +Febe si ferma da sola al primo segnale e non riparte senza «Riprendi». Non premere «Riprendi» prima di aver +risolto a mano nel browser e di avermi riferito che cosa è successo. diff --git a/docs/sonda/esito.md b/docs/sonda/esito.md new file mode 100644 index 0000000..e8ed94e --- /dev/null +++ b/docs/sonda/esito.md @@ -0,0 +1,41 @@ +# Esito delle ipotesi di M0 (specifica §6.6) + +Stato al 13 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**: per questo i +file di Instagram sono ancora scheletri e le ricette si rifiutano di girare su Instagram (vedi in fondo). + +Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram; +**da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A). + +| | Ipotesi | Stato | Come si prova (procedura esatta) | Che cosa ne dipende | +|---|---|---|---|---| +| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo** | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` | +| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo** | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` | +| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **Da provare dal vivo** | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) | +| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **Da provare dal vivo** | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` | +| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **Da provare dal vivo** | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) | +| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo** | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` | +| H7 | I file del CDN si scaricano con `Network.loadNetworkResource`; se no, con la via di riserva di §6.5 | **Da provare dal vivo**. In locale: scaricati integri (24 MB in 2,2 s; foto e video del sito di prova byte per byte) | Dopo la sonda, con la prima sessione dal vivo (parte B): file arrivati in Libreria, stato «scaricato». **Osservazione locale**: dalla pagina di riposo `about:blank` Chromium rifiuta gli indirizzi locali del CDN di prova (`net::ERR_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_CHECKS`); dalle pagine del sito funziona. Con il CDN pubblico va misurato se lo scaricamento regge anche dalla pagina di riposo | `BrowserFileFetcher`; la via `HttpClient` di §6.5 punto 3 **non è scritta**: resta dietro `IFileFetcher` finché H7 non dice che serve. Codici HTTP di «indirizzo scaduto» (in locale 403 e 410) | +| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito) | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) | +| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Da provare dal vivo** | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione | +| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Da provare dal vivo** | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» | +| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Scheletro pronto: `bersagli.instagram.json` | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette | +| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** (Windows, M6) | Prova usa e getta in WPF con WebView2 sulla pagina locale del sito di prova: `CallDevToolsProtocolMethodAsync` per `Network.getResponseBody`, `Input.dispatchMouseEvent`, `Page.startScreencast` | `WebView2Host` | +| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** (Windows, M6) | Nell'ordine di §6.6: finestra separata fuori vista con occlusione disattivata; poi composizione; poi Edge con `ChromiumProcessHost` | `WebView2Host` | +| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: lo stesso con l'applicazione | Profilo del browser nella cartella dei dati | +| S4 | In Docker, con la vista remota, si scrive in un modulo e si naviga con un ritardo sopportabile | **Provato in locale senza contenitore** (clic e tasti dalla vista remota arrivano alla pagina; vedi `esito-locale.md`); **da provare** nel contenitore su Unraid (M5) | Dalla pagina Collegamento: scrivere in un campo del sito di prova, poi accedere al sito vero con l'account di prova | Vista remota | +| S5 | Chromium in Docker parte con la sandbox | **Provato in locale** (`esito-locale.md`): come utente normale la sandbox è attiva; come root Chromium non parte senza `--no-sandbox`. **Da provare** nel contenitore con il profilo seccomp predefinito (M5) | `chrome://sandbox` letto in sola lettura, come in `esito-locale.md` | Compromesso eventuale di §11, da scrivere nella guida | +| S6 | Che cosa vede la pagina: `navigator.webdriver`, visibilità, fuoco, lingua, fuso | **Provato in locale per Chromium su Xvfb** (`esito-locale.md`): `webdriver` falso con porta fissa, pagina visibile, `it-IT`, `Europe/Rome`, fuoco dopo il primo evento del puntatore. **Da provare** con il Chromium di Debian (M5) e in WebView2 (M6) | Prova `BrowserIntegrationTests.ThePageSeesAnOrdinaryVisibleBrowser` | — | + +## Che cosa è pronto per ricevere gli esiti + +- `src/Febe.Core/Config/bersagli.instagram.json` (copiato in `config/`): **scheletro**. Elenca le pagine e i bersagli + di cui le ricette hanno bisogno, tutti vuoti e segnati con l'ipotesi da cui dipendono. Finché una voce necessaria è + vuota, la ricetta risponde «non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano …)» + senza aprire pagine e senza chiedere permessi. +- `src/Febe.Core/Config/lettori.instagram.json`: **ipotesi**. Contiene solo gli indizi di §6.4 (`pk`, `code`, + `taken_at`, `image_versions2.candidates`, `video_versions`, `carousel_media`); ogni altro concetto è vuoto. Con lo + stato «ipotesi» le ricette non girano. Va riempito sui campioni ripuliti e portato a «confermato». +- `segnali.json`: regole di partenza, ancora ipotesi H8. +- Sonda: `febe-sonda registra`, `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`). +- Il sito di prova fa girare tutte le ricette con un browser vero (`tests/Febe.Tests/Collection/`): è la prova che la + raccolta funziona **quando** mappa e vocabolario saranno compilati, non che Instagram si comporti allo stesso modo. diff --git a/src/Febe.Browser/Recipes/BrowserPageDriver.cs b/src/Febe.Browser/Recipes/BrowserPageDriver.cs new file mode 100644 index 0000000..62a8c7d --- /dev/null +++ b/src/Febe.Browser/Recipes/BrowserPageDriver.cs @@ -0,0 +1,214 @@ +using System.Text.Json; +using Febe.Browser.Cdp; +using Febe.Browser.Gestures; +using Febe.Browser.Hosting; +using Febe.Browser.Targets; +using Febe.Core.Abstractions; +using Febe.Core.Collection; +using Febe.Core.Collection.Recipes; +using Febe.Core.Domain; +using Febe.Core.Pacing; + +namespace Febe.Browser.Recipes; + +/// Options of . +public sealed record BrowserDriverOptions +{ + /// Address of the site the recipes visit, without a trailing slash (e.g. the local test site). + public required string SiteBaseUrl { get; init; } + + /// The «Ritmo dei gesti» slider. + public GesturePace Pace { get; init; } = GesturePace.Natural; + + /// Gesture timings («naturale» by default). + public GestureSettings Gestures { get; init; } = GestureSettings.Natural; + + /// How long a page may take to load and paint. + public TimeSpan LoadTimeout { get; init; } = TimeSpan.FromSeconds(30); + + /// Where the session cookie is checked (existence only). Null: not checked. + public SessionCookieOptions? SessionCookie { get; init; } + + /// True while Alberto uses the browser: gestures are not performed. + public Func? UserIsDriving { get; init; } +} + +/// +/// The page driver of the recipes over the browser layer (spec §6.1, §6.3, §7.7): navigation with Page.navigate, +/// read-only state with Runtime.evaluate, targets found with the target map and clicked with human gestures +/// through Input, wheel bursts, and the rest page. It never opens an address outside the site. +/// +public sealed class BrowserPageDriver : IPageDriver +{ + /// Read-only: the page has loaded and painted (input before the first paint is ignored by Chromium). + private const string ReadyExpression = + "document.readyState === 'complete' && performance.getEntriesByType('paint').length > 0"; + + private readonly ICdpSession _cdp; + private readonly HostClassifier _hosts; + private readonly IClock _clock; + private readonly IRandomSource _random; + private readonly BrowserDriverOptions _options; + private readonly TargetResolver _resolver; + private HumanGestures _gestures; + private TargetActions _actions; + + public BrowserPageDriver(ICdpSession cdp, TargetMap map, HostClassifier hosts, IClock clock, IRandomSource random, BrowserDriverOptions options) + { + _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); + _hosts = hosts ?? throw new ArgumentNullException(nameof(hosts)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _random = random ?? throw new ArgumentNullException(nameof(random)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + if (_hosts.Classify(options.SiteBaseUrl) != HostKind.Site) + { + throw new ArgumentException("L'indirizzo di base non è un indirizzo del sito.", nameof(options)); + } + + _resolver = new TargetResolver(cdp, map ?? throw new ArgumentNullException(nameof(map))); + (_gestures, _actions) = CreateGestures(1.0); + } + + public double WaitMultiplier => _gestures.Multiplier; + + public HumanGestures Gestures => _gestures; + + public void BeginSession(double mood) => (_gestures, _actions) = CreateGestures(mood); + + public async Task OpenAsync(string path, CancellationToken ct) + { + ArgumentException.ThrowIfNullOrEmpty(path); + if (!path.StartsWith('/') || path.StartsWith("//", StringComparison.Ordinal)) + { + throw new ArgumentException("Le ricette aprono solo percorsi del sito.", nameof(path)); + } + + var url = _options.SiteBaseUrl.TrimEnd('/') + path; + if (_hosts.Classify(url) != HostKind.Site) + { + return new PageLoad(false, string.Empty, "indirizzo fuori dal sito"); + } + + var result = await _cdp.NavigateAsync(url, ct).ConfigureAwait(false); + if (!result.Succeeded) + { + return new PageLoad(false, string.Empty, result.ErrorText); + } + + var deadline = _clock.Now + _options.LoadTimeout; + while (true) + { + try + { + var ready = await _cdp.EvaluateAsync(ReadyExpression, ct).ConfigureAwait(false); + if (ready.ValueKind == JsonValueKind.True) + { + break; + } + } + catch (Exception ex) when (ex is CdpCommandException or CdpEvaluationException) + { + // The document is being replaced: poll again. + } + + if (_clock.Now >= deadline) + { + return new PageLoad(false, await CurrentPathAsync(ct).ConfigureAwait(false), "la pagina non ha finito di caricare"); + } + + await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false); + } + + return new PageLoad(true, await CurrentPathAsync(ct).ConfigureAwait(false), null); + } + + public async Task CurrentPathAsync(CancellationToken ct) + { + for (var attempt = 0; ; attempt++) + { + try + { + var value = await _cdp.EvaluateAsync("location.pathname", ct).ConfigureAwait(false); + return value.ValueKind == JsonValueKind.String ? value.GetString() ?? string.Empty : string.Empty; + } + catch (Exception ex) when (attempt < 3 && ex is CdpCommandException or CdpEvaluationException) + { + await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false); + } + } + } + + public async Task IsOnSiteAsync(CancellationToken ct) + { + var href = await _cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false); + return _hosts.Classify(href) == HostKind.Site; + } + + public async Task FindAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct) + { + if (!_resolver.Map.Contains(target)) + { + return new TargetCheck(target, TargetCheckStatus.NotConfigured, 0, $"Bersaglio «{target}» assente dalla mappa."); + } + + var lookup = await _resolver.ResolveAsync(target, parameters, ct).ConfigureAwait(false); + return ToCheck(lookup, clicked: false); + } + + public async Task ClickAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct) + { + if (!_resolver.Map.Contains(target)) + { + return new TargetCheck(target, TargetCheckStatus.NotConfigured, 0, $"Bersaglio «{target}» assente dalla mappa."); + } + + // A person scrolls back as far as needed (e.g. to the stories bar after the sweep went down the feed). + var result = await _actions.ClickAsync(target, parameters, maxScrollBursts: 24, ct: ct).ConfigureAwait(false); + return ToCheck(result.Lookup, result.Clicked); + } + + public async Task ScrollBurstAsync(CancellationToken ct) + { + await _gestures.ScrollBurstAsync(1, ct).ConfigureAwait(false); + if (_random.Chance(_gestures.Settings.ScrollBackProbability)) + { + await _gestures.WaitAsync(new Interval(150, 600), ct).ConfigureAwait(false); + await _gestures.ScrollBackAsync(1, ct).ConfigureAwait(false); + } + + await _gestures.PauseAfterBurstAsync(ct).ConfigureAwait(false); + } + + public Task WaitAfterLoadAsync(CancellationToken ct) => _gestures.WaitAfterLoadAsync(ct); + + public Task WaitAsync(TimeSpan duration, CancellationToken ct) => _clock.Delay(duration, ct); + + public Task MaybeDistractionAsync(CancellationToken ct) => _gestures.MaybeDistractionAsync(ct); + + public async Task HasSessionCookieAsync(CancellationToken ct) => + _options.SessionCookie is { } cookie ? await SessionCookieProbe.HasSessionCookieAsync(_cdp, cookie, ct).ConfigureAwait(false) : null; + + public Task RestAsync(CancellationToken ct) => _cdp.RestAsync(ct); + + private (HumanGestures, TargetActions) CreateGestures(double mood) + { + var gestures = new HumanGestures(_cdp, _clock, _random, mood, _options.Pace, _options.UserIsDriving, _options.Gestures); + return (gestures, new TargetActions(_resolver, gestures)); + } + + private static TargetCheck ToCheck(TargetLookup lookup, bool clicked) + { + var status = lookup.Status switch + { + TargetStatus.Found => clicked ? TargetCheckStatus.Clicked : TargetCheckStatus.Found, + TargetStatus.NotFound => TargetCheckStatus.NotFound, + TargetStatus.NotVisible => TargetCheckStatus.NotVisible, + TargetStatus.IndexOutOfRange => TargetCheckStatus.NotFound, + TargetStatus.OutOfView => TargetCheckStatus.OutOfView, + TargetStatus.Obstructed => TargetCheckStatus.Obstructed, + TargetStatus.NotConfigured => TargetCheckStatus.NotConfigured, + _ => TargetCheckStatus.NotFound, + }; + return new TargetCheck(lookup.Id, status, lookup.Matches, lookup.Message); + } +} diff --git a/src/Febe.Browser/Recipes/CollectionPipeline.cs b/src/Febe.Browser/Recipes/CollectionPipeline.cs new file mode 100644 index 0000000..268855b --- /dev/null +++ b/src/Febe.Browser/Recipes/CollectionPipeline.cs @@ -0,0 +1,185 @@ +using Febe.Browser.Capture; +using Febe.Browser.Diagnostics; +using Febe.Browser.Download; +using Febe.Browser.Hosting; +using Febe.Browser.Targets; +using Febe.Core.Abstractions; +using Febe.Core.Collection; +using Febe.Core.Collection.Downloads; +using Febe.Core.Collection.Readers; +using Febe.Core.Collection.Recipes; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Browser.Recipes; + +/// The site the pipeline works on: its name (configuration files), address, hosts and session cookie. +/// «instagram» or «prova»: selects bersagli.{Name}.json and lettori.{Name}.json. +/// Address the recipes open pages under. +/// Site and CDN hosts. +/// Where the session cookie is checked (existence only). +public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie) +{ + /// + /// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and + /// says why, without touching the site. + /// + public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram); + + /// The local test site (tools/Febe.SitoDiProva) on «127.0.0.1:port», with its CDN on another host. + public static CollectionSite TestSite(string siteHost, string cdnHost) => + new("prova", $"http://{siteHost}", new HostClassifier([siteHost], [cdnHost]), new SessionCookieOptions("sessione_prova", $"http://{siteHost}/")); + + /// The stop-signal rules of the site. + public string SignalsFile => Name == "prova" ? "segnali.prova.json" : "segnali.json"; +} + +/// What needs. +public sealed record CollectionPipelineOptions +{ + public required ICdpSession Cdp { get; init; } + + public required CollectionSite Site { get; init; } + + public required IFebeStorage Storage { get; init; } + + public required LibraryIngest Ingest { get; init; } + + public required IGovernor Governor { get; init; } + + /// Remaining budgets for the «at least ten stories» check; usually the Governor itself. + public IBudgetView? Budget { get; init; } + + public required IDataBudget DataBudget { get; init; } + + /// The circuit breaker: signals are reported to it, and recipes stop when it opens. + public required ICircuitBreaker Breaker { get; init; } + + public required IClock Clock { get; init; } + + public required IRandomSource Random { get; init; } + + /// Temporary folder for downloads (under Dati). + public required string StagingFolder { get; init; } + + /// + /// Folder with editable copies of the configuration (Dati, spec §8.2): segnali.json, bersagli.*.json, + /// lettori.*.json. Files missing there come from the copies embedded in Febe.Core. + /// + public string? ConfigFolder { get; init; } + + public GesturePace Pace { get; init; } = GesturePace.Natural; + + public RecipeOptions Recipes { get; init; } = new(); + + /// True while Alberto uses the browser: gestures are not performed. + public Func? UserIsDriving { get; init; } + + public IBrowserLog? Log { get; init; } +} + +/// +/// The collection pipeline put together (spec §6): response tap, stop signals, readers, page driver, recipe runner and +/// download queue, all on one browser page. Disposing it stops listening to the page. +/// +public sealed class CollectionPipeline : IAsyncDisposable +{ + private readonly List _subscriptions = []; + + private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets) + { + Tap = tap; + Signals = signals; + Capture = capture; + Driver = driver; + Runner = runner; + Downloads = downloads; + SiteMap = siteMap; + Targets = targets; + } + + public ResponseTap Tap { get; } + + public SignalDetector Signals { get; } + + public CaptureCollector Capture { get; } + + public BrowserPageDriver Driver { get; } + + /// The of the engine. + public RecipeRunner Runner { get; } + + public DownloadQueue Downloads { get; } + + public SiteMap SiteMap { get; } + + public TargetMap Targets { get; } + + public ReaderVocabulary Vocabulary => Capture.Reader.Vocabulary; + + public static async Task StartAsync(CollectionPipelineOptions options, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(options); + string? Override(string file) => options.ConfigFolder is { } folder ? Path.Combine(folder, file) : null; + var site = options.Site; + var siteMap = SiteMap.LoadOrEmbedded(Override($"bersagli.{site.Name}.json"), $"bersagli.{site.Name}.json"); + var targets = TargetMap.LoadOrEmbedded(Override($"bersagli.{site.Name}.json"), $"bersagli.{site.Name}.json"); + var vocabulary = ReaderVocabulary.LoadOrEmbedded(Override($"lettori.{site.Name}.json"), $"lettori.{site.Name}.json"); + var rulesFile = Override(site.SignalsFile); + var rules = rulesFile is not null && File.Exists(rulesFile) ? SignalRules.Load(rulesFile) : SignalRules.LoadEmbedded(site.SignalsFile); + + var tap = new ResponseTap(options.Cdp, site.Hosts, options.Clock, options.Log); + var signals = new SignalDetector(rules, options.Breaker, options.Clock); + var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock); + var driver = new BrowserPageDriver(options.Cdp, targets, site.Hosts, options.Clock, options.Random, new BrowserDriverOptions + { + SiteBaseUrl = site.BaseUrl, + Pace = options.Pace, + SessionCookie = site.SessionCookie, + UserIsDriving = options.UserIsDriving, + }); + var runner = new RecipeRunner(new RecipeEnvironment + { + Driver = driver, + Capture = capture, + Governor = options.Governor, + Budget = options.Budget ?? options.Governor as IBudgetView, + Signals = signals, + Storage = options.Storage, + SiteMap = siteMap, + Clock = options.Clock, + Random = options.Random, + DataBudget = options.DataBudget, + Breaker = options.Breaker, + Options = options.Recipes, + }); + var downloads = new DownloadQueue( + options.Storage, + options.Ingest, + new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log), + options.DataBudget, + options.Clock, + options.Random, + new DownloadOptions { StagingFolder = options.StagingFolder }); + + var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets); + pipeline._subscriptions.Add(tap.AddObserver(signals)); + pipeline._subscriptions.Add(tap.AddConsumer(signals)); + pipeline._subscriptions.Add(tap.AddObserver(capture)); + pipeline._subscriptions.Add(tap.AddConsumer(capture)); + await tap.StartAsync(ct).ConfigureAwait(false); + return pipeline; + } + + public async ValueTask DisposeAsync() + { + foreach (var subscription in _subscriptions) + { + subscription.Dispose(); + } + + await Tap.DisposeAsync().ConfigureAwait(false); + } +} diff --git a/src/Febe.Browser/Targets/TargetMap.cs b/src/Febe.Browser/Targets/TargetMap.cs index 55cbaad..ede7da0 100644 --- a/src/Febe.Browser/Targets/TargetMap.cs +++ b/src/Febe.Browser/Targets/TargetMap.cs @@ -15,7 +15,14 @@ namespace Febe.Browser.Targets; /// Link shape on the path, e.g. «/{username}/», «/stories/**»: {name} or * is one segment, ** the rest. /// Which of the visible matches, in document order (0 = first, -1 = last). /// Hypothesis of spec §6.6 the target depends on (e.g. «H11»), when not yet confirmed. -public sealed record TargetSpec(string Id, IReadOnlyList Roles, string? NamePattern, string? HrefPattern, int Index, string? Hypothesis); +public sealed record TargetSpec(string Id, IReadOnlyList Roles, string? NamePattern, string? HrefPattern, int Index, string? Hypothesis) +{ + /// + /// False for a placeholder of a skeleton map (role, name and href written but empty, e.g. the first + /// bersagli.instagram.json): looking it up gives without touching the page. + /// + public bool IsConfigured => Roles.Count > 0 || NamePattern is not null || HrefPattern is not null; +} /// /// The target map of one site (bersagli.instagram.json, bersagli.prova.json), editable without @@ -62,6 +69,14 @@ public sealed partial class TargetMap public static TargetMap Load(string path) => Parse(File.ReadAllText(path), path); + /// A map shipped with Febe.Core (bersagli.prova.json, bersagli.instagram.json). + public static TargetMap LoadEmbedded(string fileName) => + Parse(Febe.Core.Collection.SiteMap.ReadEmbeddedText(fileName), fileName); + + /// Loads when it exists, otherwise the embedded file with the same name. + public static TargetMap LoadOrEmbedded(string? path, string embeddedName) => + !string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName); + public static TargetMap Parse(string json, string? source = null) { var name = source ?? "bersagli"; @@ -92,9 +107,12 @@ public sealed partial class TargetMap var roles = (dto.Role ?? string.Empty).Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(r => r.ToLowerInvariant()) .ToArray(); - if (roles.Length == 0 && string.IsNullOrWhiteSpace(dto.Name) && string.IsNullOrWhiteSpace(dto.Href)) + // A skeleton entry writes the three keys empty on purpose (still to be filled from the M0 samples); + // an entry that names none of them is a mistake. + var placeholder = dto.Role is not null && dto.Name is not null && dto.Href is not null; + if (roles.Length == 0 && string.IsNullOrWhiteSpace(dto.Name) && string.IsNullOrWhiteSpace(dto.Href) && !placeholder) { - throw new InvalidDataException($"{where}: serve almeno uno fra «role», «name» e «href»."); + throw new InvalidDataException($"{where}: serve almeno uno fra «role», «name» e «href» (vuoti tutti e tre per una voce ancora da compilare)."); } if (!string.IsNullOrWhiteSpace(dto.Name)) @@ -196,6 +214,9 @@ internal sealed class TargetMapFile public string? Note { get; set; } + /// Page addresses: read by Febe.Core.Collection.SiteMap, accepted and ignored here. + public Dictionary? Pages { get; set; } + public Dictionary? Targets { get; set; } } diff --git a/src/Febe.Browser/Targets/TargetResolver.cs b/src/Febe.Browser/Targets/TargetResolver.cs index 8308709..ae27a33 100644 --- a/src/Febe.Browser/Targets/TargetResolver.cs +++ b/src/Febe.Browser/Targets/TargetResolver.cs @@ -25,6 +25,9 @@ public enum TargetStatus /// Something covers the element (e.g. a dialog): clicking would hit something else. Obstructed, + + /// The map has the entry but it is still empty (skeleton to be filled from the M0 samples, H11). + NotConfigured, } /// One element matched by a target, as measured by the page. @@ -48,6 +51,7 @@ public sealed record TargetLookup(string Id, TargetStatus Status, TargetElement? TargetStatus.IndexOutOfRange => $"Bersaglio «{Id}»: trovati {Matches} elementi visibili, meno di quanti ne chiede la mappa.", TargetStatus.OutOfView => $"Bersaglio «{Id}» fuori dalla parte visibile della pagina.", TargetStatus.Obstructed => $"Bersaglio «{Id}» coperto da un altro elemento.", + TargetStatus.NotConfigured => $"Bersaglio «{Id}» ancora vuoto nella mappa: va compilato con i campioni della sonda (H11).", _ => $"Bersaglio «{Id}»: esito sconosciuto.", }; } @@ -188,6 +192,11 @@ public sealed class TargetResolver public async Task ResolveAsync(string id, IReadOnlyDictionary? parameters = null, CancellationToken ct = default) { var spec = _map.Get(id); + if (!spec.IsConfigured) + { + return new TargetLookup(id, TargetStatus.NotConfigured, null, 0, 0, 0); + } + var (all, width, height) = await MeasureAsync(spec, parameters, ct).ConfigureAwait(false); var visible = all.Where(e => e.Visible).ToList(); if (all.Count == 0) @@ -209,7 +218,13 @@ public sealed class TargetResolver /// Every element matching , visible or not, in document order (at most 200). public async Task> FindAllAsync(string id, IReadOnlyDictionary? parameters = null, CancellationToken ct = default) { - var (all, _, _) = await MeasureAsync(_map.Get(id), parameters, ct).ConfigureAwait(false); + var spec = _map.Get(id); + if (!spec.IsConfigured) + { + return []; + } + + var (all, _, _) = await MeasureAsync(spec, parameters, ct).ConfigureAwait(false); return all; } diff --git a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs new file mode 100644 index 0000000..efc18bc --- /dev/null +++ b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs @@ -0,0 +1,489 @@ +using System.Collections.Concurrent; +using System.Globalization; +using Febe.Core.Abstractions; +using Febe.Core.Collection.Recipes; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Core.Pacing; +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Downloads; + +/// Options of the download queue (spec §6.5). +public sealed record DownloadOptions +{ + /// + /// Folder for the temporary copy of a file while it downloads (under Dati, never the library). A partial download + /// never leaves a file with its final name (spec §6.5 point 4). + /// + public required string StagingFolder { get; init; } + + /// At most two downloads at the same time (spec §6.5 point 6). + public int MaxConcurrent { get; init; } = 2; + + /// Small random pause after each file. + public TimeSpan PauseMin { get; init; } = TimeSpan.FromMilliseconds(400); + + public TimeSpan PauseMax { get; init; } = TimeSpan.FromSeconds(3); + + /// + /// HTTP statuses that mean «the signed address expired». 403 and 410 for the test site; for the real CDN they are + /// a hypothesis to confirm with H7 in M0. + /// + public IReadOnlySet ExpiredStatuses { get; init; } = new HashSet { 403, 410 }; + + /// After this many failed attempts a file is «fallito». + public int MaxAttempts { get; init; } = 5; + + /// How many pending files are read from the database at a time. + public int BatchSize { get; init; } = 200; + + /// When idle, how long to wait before looking at the database again (a ends it earlier). + public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1); +} + +/// What one pass of the queue did. +public sealed record DownloadReport(int Stored, int Duplicates, int Skipped, int Expired, int Failed, int Retried, long Bytes, bool BudgetReached) +{ + public int Total => Stored + Duplicates + Skipped + Expired + Failed + Retried; +} + +/// +/// The download queue (spec §6.5): files waiting in the database, stories first (they expire), at most two at the +/// same time with small random pauses, inside the daily data budget. Each file goes through +/// (the browser, Network.loadNetworkResource) into a temporary file and then into the library through +/// (final name, SHA-256, duplicates of §9.5). The account's settings apply: video size +/// limit and «video delle storie» (skipped files become «saltato»). An expired address sends the file back to wait +/// and queues «Post singolo» — never for stories, which cannot be recovered. +/// +/// +/// It talks only to the CDN, never to the site, so it keeps working while the circuit breaker stops the site +/// (spec §7.6). The HttpClient fallback of §6.5 point 3 is deliberately not implemented: it stays behind +/// until H7 says whether it is needed (decision in docs/decisioni.md). +/// Addresses are never logged. +/// +public sealed class DownloadQueue +{ + private readonly IFebeStorage _storage; + private readonly LibraryIngest _ingest; + private readonly IFileFetcher _fetcher; + private readonly IDataBudget _budget; + private readonly IClock _clock; + private readonly IRandomSource _random; + private readonly DownloadOptions _options; + private readonly CollectionWriter _writer; + private readonly SemaphoreSlim _wake = new(0, int.MaxValue); + private readonly Lock _randomGate = new(); + + public DownloadQueue(IFebeStorage storage, LibraryIngest ingest, IFileFetcher fetcher, IDataBudget budget, IClock clock, IRandomSource random, DownloadOptions options) + { + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _ingest = ingest ?? throw new ArgumentNullException(nameof(ingest)); + _fetcher = fetcher ?? throw new ArgumentNullException(nameof(fetcher)); + _budget = budget ?? throw new ArgumentNullException(nameof(budget)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _random = random ?? throw new ArgumentNullException(nameof(random)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + if (_options.MaxConcurrent is < 1 or > 2) + { + throw new ArgumentOutOfRangeException(nameof(options), "Al massimo due scaricamenti insieme (specifica §6.5)."); + } + + _writer = new CollectionWriter(storage, clock); + } + + /// Raised after each file, for the interface (no addresses). + public event EventHandler? Progress; + + /// New files are waiting: ends the idle wait of . + public void Wake() => _wake.Release(); + + /// Works until cancelled: a pass over the waiting files, then an idle wait. + public async Task RunAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + var report = await RunOnceAsync(ct).ConfigureAwait(false); + var wait = report.BudgetReached ? TimeSpan.FromMinutes(30) : _options.IdlePoll; + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct); + var woken = _wake.WaitAsync(linked.Token); + var slept = _clock.Delay(wait, linked.Token); + await Task.WhenAny(woken, slept).ConfigureAwait(false); + await linked.CancelAsync().ConfigureAwait(false); + try + { + await Task.WhenAll(woken, slept).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + + ct.ThrowIfCancellationRequested(); + } + } + + /// One pass: downloads what is waiting until nothing is left or the data budget is reached. + public async Task RunOnceAsync(CancellationToken ct) + { + Directory.CreateDirectory(_options.StagingFolder); + var tally = new Tally(); + var attempted = new ConcurrentDictionary(); + var accounts = new ConcurrentDictionary(); + var singlePostQueued = new ConcurrentDictionary(); + while (!ct.IsCancellationRequested && !tally.BudgetReached) + { + var batch = (await _storage.Media.ListPendingDownloadsAsync(_options.BatchSize, ct).ConfigureAwait(false)) + .Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id)) + .ToList(); + if (batch.Count == 0) + { + break; + } + + var queue = new ConcurrentQueue(batch); + var workers = Enumerable.Range(0, _options.MaxConcurrent).Select(_ => Task.Run( + async () => + { + while (!tally.BudgetReached && queue.TryDequeue(out var pending)) + { + attempted[pending.Media.Id] = true; + await ProcessAsync(pending, tally, accounts, singlePostQueued, ct).ConfigureAwait(false); + await _clock.Delay(DrawPause(), ct).ConfigureAwait(false); + } + }, + ct)).ToList(); + await Task.WhenAll(workers).ConfigureAwait(false); + } + + return tally.ToReport(); + } + + private TimeSpan DrawPause() + { + lock (_randomGate) + { + return _random.Between(_options.PauseMin, _options.PauseMax); + } + } + + private async Task ProcessAsync(PendingDownload pending, Tally tally, ConcurrentDictionary accounts, ConcurrentDictionary singlePostQueued, CancellationToken ct) + { + var media = pending.Media; + if (!accounts.TryGetValue(pending.AccountId, out var account)) + { + account = await _storage.Accounts.GetAsync(pending.AccountId, ct).ConfigureAwait(false); + accounts[pending.AccountId] = account; + } + + var entry = await _storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false); + if (account is null || entry is null) + { + return; + } + + if (CollectionWriter.SkipReason(account, entry.Kind, media.Kind) is { } reason) + { + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, reason, _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Skipped); + Report(media, entry, DownloadStep.Skipped); + return; + } + + if (await _budget.RemainingTodayAsync(ct).ConfigureAwait(false) <= 0) + { + tally.BudgetReached = true; + return; + } + + if (!Uri.TryCreate(media.SourceUrl, UriKind.Absolute, out var address)) + { + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "Indirizzo del file non valido.", _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Failed); + return; + } + + var maxBytes = media.Kind == MediaKind.Video ? account.Limits.MaxVideoBytes : null; + var temp = Path.Combine(_options.StagingFolder, $"{SafeFileWriter.TempPrefix}{Guid.NewGuid():N}{SafeFileWriter.TempSuffix}"); + try + { + FetchResult result; + await using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true)) + { + result = await _fetcher.FetchAsync(address, file, new FetchOptions(maxBytes), ct).ConfigureAwait(false); + } + + if (result.Bytes > 0) + { + await _budget.RecordAsync(result.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false); + tally.AddBytes(result.Bytes); + } + + switch (result.Outcome) + { + case FetchOutcome.Completed: + await IngestAsync(account, entry, media, temp, maxBytes, tally, ct).ConfigureAwait(false); + return; + case FetchOutcome.TooLarge: + var limit = maxBytes is { } m ? ItalianText.Number(Math.Max(1, m / (1024 * 1024))) : "?"; + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, $"Video oltre il limite di {limit} MB impostato per l'account.", _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Skipped); + Report(media, entry, DownloadStep.Skipped); + return; + case FetchOutcome.HttpError when result.HttpStatus is { } status && _options.ExpiredStatuses.Contains(status): + await ExpiredAsync(entry, media, tally, singlePostQueued, ct).ConfigureAwait(false); + return; + case FetchOutcome.HostNotAllowed: + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "L'indirizzo non è del CDN: non si scarica (specifica §6.5).", _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Failed); + Report(media, entry, DownloadStep.Failed); + return; + default: + var error = result.HttpStatus is { } code + ? $"Il CDN ha risposto {code.ToString(CultureInfo.InvariantCulture)}." + : $"Errore di rete durante lo scaricamento ({result.Error ?? "senza dettagli"})."; + if (media.Attempts + 1 >= _options.MaxAttempts) + { + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, error, _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Failed); + Report(media, entry, DownloadStep.Failed); + } + else + { + await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, error, _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Retried); + } + + return; + } + } + catch (FileTooLargeException) + { + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Video oltre il limite impostato per l'account.", _clock.Now, CancellationToken.None).ConfigureAwait(false); + tally.Add(ref tally.Skipped); + } + catch (IOException ex) + { + // Disk full or similar: the file waits for the next pass (nothing was written under the final name). + await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, $"Scrittura non riuscita: {ex.GetType().Name}.", _clock.Now, CancellationToken.None).ConfigureAwait(false); + tally.Add(ref tally.Retried); + } + finally + { + TryDelete(temp); + } + } + + private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, Tally tally, CancellationToken ct) + { + MemoryStream? cover = null; + try + { + if (media.Kind == MediaKind.Video && Uri.TryCreate(media.CoverUrl, UriKind.Absolute, out var coverAddress)) + { + var buffer = new MemoryStream(); + var fetched = await _fetcher.FetchAsync(coverAddress, buffer, new FetchOptions(8L * 1024 * 1024), ct).ConfigureAwait(false); + if (fetched.Bytes > 0) + { + await _budget.RecordAsync(fetched.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false); + tally.AddBytes(fetched.Bytes); + } + + if (fetched.Succeeded) + { + buffer.Position = 0; + cover = buffer; + } + else + { + await buffer.DisposeAsync().ConfigureAwait(false); + } + } + + var highlightTitle = entry.Kind == EntryKind.Highlight + ? (await _storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false)).OrderBy(h => h.Position).FirstOrDefault()?.Title + : null; + MediaSaveResult saved; + await using (var content = new FileStream(temp, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true)) + { + saved = await _ingest.SaveMediaAsync( + account, + entry, + media, + new MediaContent { Content = content, Extension = Extension(temp, media), Cover = cover, MaxBytes = maxBytes }, + highlightTitle, + ct).ConfigureAwait(false); + } + + if (saved.Outcome == MediaSaveOutcome.Stored) + { + tally.Add(ref tally.Stored); + Report(media, entry, DownloadStep.Stored); + await AppendJournalWhenCompleteAsync(entry, ct).ConfigureAwait(false); + } + else + { + await IdenticalAsync(entry, media, saved.Identical!, ct).ConfigureAwait(false); + tally.Add(ref tally.Duplicates); + Report(media, entry, DownloadStep.Duplicate); + } + } + finally + { + if (cover is not null) + { + await cover.DisposeAsync().ConfigureAwait(false); + } + } + } + + /// + /// §9.5: the file just downloaded is identical to one already in the same account. The new file is discarded + /// before entering the library. When the existing file belongs to an imported entry without Instagram data, that + /// entry takes the data and the new record goes away; otherwise the new file is settled as «saltato» with a note. + /// + private async Task IdenticalAsync(Entry entry, Media media, MediaLocation existing, CancellationToken ct) + { + var files = await _storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false); + if (existing.Entry.InstagramId is null && existing.Entry.Kind == entry.Kind && files.Count == 1) + { + await _storage.Entries.RemoveAsync(entry.Id, ct).ConfigureAwait(false); + await _storage.Entries.UpdateAsync( + existing.Entry with + { + InstagramId = entry.InstagramId, + Code = existing.Entry.Code ?? entry.Code, + Caption = existing.Entry.Caption ?? entry.Caption, + AuthorUsername = existing.Entry.AuthorUsername ?? entry.AuthorUsername, + AuthorInstagramId = existing.Entry.AuthorInstagramId ?? entry.AuthorInstagramId, + }, + ct).ConfigureAwait(false); + await _writer.EventAsync("file-gia-in-libreria", "Un file appena scaricato era già in libreria fra quelli importati: non è stato copiato di nuovo, all'elemento esistente sono stati aggiunti i dati di Instagram.", EventSeverity.Info, entry.AccountId, null, ct).ConfigureAwait(false); + return; + } + + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Identico a un file già presente nell'account: non copiato di nuovo.", _clock.Now, ct).ConfigureAwait(false); + if (existing.Entry.Caption is null && entry.Caption is not null && existing.Entry.Provenance == Provenance.Imported) + { + await _storage.Entries.UpdateAsync(existing.Entry with { Caption = entry.Caption }, ct).ConfigureAwait(false); + } + } + + /// An expired address: back to wait and «Post singolo» queued; stories cannot be recovered (§6.5 point 5). + private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary singlePostQueued, CancellationToken ct) + { + if (entry.Kind is EntryKind.Story or EntryKind.Highlight or EntryKind.ProfilePicture) + { + var why = entry.Kind == EntryKind.Story + ? "Indirizzo scaduto: per le storie non c'è recupero dopo la scadenza." + : "Indirizzo scaduto: si rinnova alla prossima lettura del profilo."; + await _storage.Media.MarkFailedAsync(media.Id, entry.Kind == EntryKind.Story ? MediaState.Failed : MediaState.Expired, why, _clock.Now, ct).ConfigureAwait(false); + tally.Add(ref tally.Expired); + Report(media, entry, DownloadStep.Expired); + return; + } + + await _storage.Media.MarkFailedAsync(media.Id, MediaState.Expired, "Indirizzo scaduto: lo rinnova «Post singolo».", _clock.Now, ct).ConfigureAwait(false); + if (singlePostQueued.TryAdd(entry.Id, true)) + { + await _writer.QueueSinglePostAsync(entry, ct).ConfigureAwait(false); + } + + tally.Add(ref tally.Expired); + Report(media, entry, DownloadStep.Expired); + } + + private async Task AppendJournalWhenCompleteAsync(Entry entry, CancellationToken ct) + { + var files = await _storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false); + if (files.All(f => f.State is not (MediaState.ToDownload or MediaState.Expired))) + { + await _ingest.AppendJournalAsync(entry.Id, ct).ConfigureAwait(false); + } + } + + private void Report(Media media, Entry entry, DownloadStep step) => + Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step)); + + /// The extension from the content (magic numbers), else from the kind of file. + private static string Extension(string path, Media media) + { + Span head = stackalloc byte[12]; + using (var stream = File.OpenRead(path)) + { + var read = stream.Read(head); + head = head[..read]; + } + + if (head.Length >= 3 && head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF) + { + return ".jpg"; + } + + if (head.Length >= 8 && head[0] == 0x89 && head[1] == (byte)'P' && head[2] == (byte)'N' && head[3] == (byte)'G') + { + return ".png"; + } + + if (head.Length >= 12 && head[..4].SequenceEqual("RIFF"u8) && head[8..12].SequenceEqual("WEBP"u8)) + { + return ".webp"; + } + + if (head.Length >= 12 && head[4..8].SequenceEqual("ftyp"u8)) + { + return head[8..12].SequenceEqual("heic"u8) || head[8..12].SequenceEqual("heix"u8) ? ".heic" : ".mp4"; + } + + return media.Kind == MediaKind.Video ? ".mp4" : ".jpg"; + } + + private static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + private sealed class Tally + { + public int Stored; + public int Duplicates; + public int Skipped; + public int Expired; + public int Failed; + public int Retried; + private long _bytes; + private volatile bool _budgetReached; + + public bool BudgetReached + { + get => _budgetReached; + set => _budgetReached = value; + } + + public void Add(ref int counter) => Interlocked.Increment(ref counter); + + public void AddBytes(long bytes) => Interlocked.Add(ref _bytes, bytes); + + public DownloadReport ToReport() => + new(Stored, Duplicates, Skipped, Expired, Failed, Retried, Interlocked.Read(ref _bytes), BudgetReached); + } +} + +/// How a file of the queue ended. +public enum DownloadStep +{ + Stored, + Duplicate, + Skipped, + Expired, + Failed, +} + +/// Progress of the queue for the interface: identifiers only, never addresses. +public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step); diff --git a/src/Febe.Core/Collection/IStopSignals.cs b/src/Febe.Core/Collection/IStopSignals.cs new file mode 100644 index 0000000..0a156c7 --- /dev/null +++ b/src/Febe.Core/Collection/IStopSignals.cs @@ -0,0 +1,22 @@ +using Febe.Core.Abstractions; + +namespace Febe.Core.Collection; + +/// +/// What the recipes need from the stop-signal detection (spec §7.6): to know when a signal was raised, and to report +/// what only they can tell (empty pages, the session cookie). Implemented by . +/// +public interface IStopSignals +{ + /// Raised after a signal has been reported to the circuit breaker. + event EventHandler? SignalRaised; + + /// A page (or page of data) turned out empty; repeated empty pages raise a throttle signal. + Signal? ObserveEmptyPage(string? url = null); + + /// A page with content: resets the empty-page counter. + void ObserveNonEmptyPage(); + + /// Result of the session-cookie check: a missing cookie is a disconnection. + Signal? ObserveSessionCookie(bool present); +} diff --git a/src/Febe.Core/Collection/Readers/KeyStructure.cs b/src/Febe.Core/Collection/Readers/KeyStructure.cs new file mode 100644 index 0000000..d379219 --- /dev/null +++ b/src/Febe.Core/Collection/Readers/KeyStructure.cs @@ -0,0 +1,165 @@ +using System.Text; +using System.Text.Json; + +namespace Febe.Core.Collection.Readers; + +/// +/// Describes the key structure of a JSON response without any value (spec §6.4: «formato non riconosciuto» events +/// carry only the structure). Keys that look like identifiers become «#», so not even they leak. +/// +/// Example: {dati:{elenco:[{a,b,c:{d}}]},stato}. +public static class KeyStructure +{ + public const int DefaultMaxLength = 600; + private const int MaxDepth = 6; + private const int MaxKeysPerObject = 24; + + public static string Describe(JsonElement root, int maxLength = DefaultMaxLength) + { + var sb = new StringBuilder(); + Append(sb, root, 0); + if (sb.Length > maxLength) + { + sb.Length = Math.Max(0, maxLength - 1); + sb.Append('…'); + } + + return sb.ToString(); + } + + /// + /// True for keys that look like identifiers rather than names: long digit runs, long hexadecimal or mixed + /// letter-digit tokens. Shared with the sample sanitizer (spec §14.5). + /// + public static bool LooksLikeIdentifier(string key) + { + if (string.IsNullOrEmpty(key)) + { + return false; + } + + var digits = 0; + var letters = 0; + var others = 0; + foreach (var c in key) + { + if (char.IsAsciiDigit(c)) + { + digits++; + } + else if (char.IsAsciiLetter(c)) + { + letters++; + } + else if (c is not ('_' or '-')) + { + others++; + } + } + + if (digits >= 5 && letters == 0 && others == 0) + { + return true; // 17841400000, 1234567 + } + + if (others == 0 && key.Length >= 16 && digits >= 3 && letters >= 3) + { + return true; // tokens and hashes + } + + return others > 0 && digits >= 5; // e.g. «id:123456» + } + + private static void Append(StringBuilder sb, JsonElement element, int depth) + { + switch (element.ValueKind) + { + case JsonValueKind.Object: + if (depth >= MaxDepth) + { + sb.Append("{…}"); + return; + } + + sb.Append('{'); + var count = 0; + var identifierKeys = 0; + JsonElement? identifierSample = null; + foreach (var property in element.EnumerateObject()) + { + if (LooksLikeIdentifier(property.Name)) + { + identifierKeys++; + identifierSample ??= property.Value; + continue; + } + + if (count == MaxKeysPerObject) + { + sb.Append(",…"); + count++; + continue; + } + + if (count > MaxKeysPerObject) + { + continue; + } + + if (count > 0) + { + sb.Append(','); + } + + sb.Append(property.Name); + if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array) + { + sb.Append(':'); + Append(sb, property.Value, depth + 1); + } + + count++; + } + + if (identifierKeys > 0) + { + if (count > 0) + { + sb.Append(','); + } + + sb.Append('#'); + if (identifierSample is { ValueKind: JsonValueKind.Object or JsonValueKind.Array } sample) + { + sb.Append(':'); + Append(sb, sample, depth + 1); + } + } + + sb.Append('}'); + return; + case JsonValueKind.Array: + if (depth >= MaxDepth) + { + sb.Append("[…]"); + return; + } + + sb.Append('['); + foreach (var item in element.EnumerateArray()) + { + if (item.ValueKind is JsonValueKind.Object or JsonValueKind.Array) + { + Append(sb, item, depth + 1); + } + + break; // the first element stands for the others + } + + sb.Append(']'); + return; + default: + return; + } + } +} diff --git a/src/Febe.Core/Collection/Readers/ReadMapping.cs b/src/Febe.Core/Collection/Readers/ReadMapping.cs new file mode 100644 index 0000000..573df26 --- /dev/null +++ b/src/Febe.Core/Collection/Readers/ReadMapping.cs @@ -0,0 +1,99 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Collection.Readers; + +/// Turns what the reader recognized into domain records (spec §6.4: Entry, Media, Account, Highlight). +public static class ReadMapping +{ + /// The entry of a content item for an account. + /// The content. + /// Local key of the account the entry belongs to (for tagged posts: the tagged account). + /// Post, story, highlight item or tagged post. + /// Discovery time. + public static Entry ToEntry(ContentItem item, long accountId, EntryKind kind, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(item); + var foreignAuthor = kind == EntryKind.Tagged; + return new Entry + { + AccountId = accountId, + Kind = kind, + InstagramId = item.Id, + Code = item.Code, + PublishedAt = item.TakenAt, + Caption = item.Caption, + AuthorUsername = foreignAuthor ? item.Owner?.Username : null, + AuthorInstagramId = foreignAuthor ? item.Owner?.Id : null, + DiscoveredAt = now, + ExpiresAt = kind == EntryKind.Story ? item.ExpiresAt ?? item.TakenAt.AddHours(24) : null, + }; + } + + /// The files of a content item, positions from 1, with the addresses of the chosen versions. + public static IReadOnlyList ToMedia(ContentItem item, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(item); + return [.. item.Files.Select((file, index) => ToMedia(file, index + 1, now))]; + } + + public static Media ToMedia(ContentFile file, int position, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(file); + return new Media + { + Position = position, + Kind = file.Kind, + InstagramId = file.InstagramId, + Width = file.Best.Width, + Height = file.Best.Height, + Duration = file.Duration, + SourceUrl = file.Best.Url, + CoverUrl = file.Cover?.Url, + SourceSeenAt = now, + }; + } + + /// A profile picture as an entry: its identity is the address path of the picture (it changes with the picture). + public static (Entry Entry, Media Media)? ToProfilePicture(ProfileInfo profile, long accountId, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(profile); + if (profile.Picture is not { } picture || !Uri.TryCreate(picture.Url, UriKind.Absolute, out var uri)) + { + return null; + } + + var identity = "ritratto-" + Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(uri.AbsolutePath)))[..16]; + var entry = new Entry + { + AccountId = accountId, + Kind = EntryKind.ProfilePicture, + InstagramId = identity, + PublishedAt = now, + DiscoveredAt = now, + }; + var media = new Media + { + Position = 1, + Kind = MediaKind.Photo, + Width = picture.Width, + Height = picture.Height, + SourceUrl = picture.Url, + SourceSeenAt = now, + }; + return (entry, media); + } + + public static Highlight ToHighlight(HighlightInfo info, long accountId, int position, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(info); + return new Highlight + { + AccountId = accountId, + InstagramId = info.Id, + Title = string.IsNullOrWhiteSpace(info.Title) ? "Senza titolo" : info.Title.Trim(), + Position = position, + DiscoveredAt = now, + LastCheckedAt = now, + }; + } +} diff --git a/src/Febe.Core/Collection/Readers/ReadModels.cs b/src/Febe.Core/Collection/Readers/ReadModels.cs new file mode 100644 index 0000000..c59ec1b --- /dev/null +++ b/src/Febe.Core/Collection/Readers/ReadModels.cs @@ -0,0 +1,143 @@ +using System.Text; +using Febe.Core.Domain; + +namespace Febe.Core.Collection.Readers; + +/// One version of a file as the page received it: an address with its size. +/// Signed address: never logged (spec §13.2). +/// Width in pixels, when given. +/// Height in pixels, when given. +/// For videos: whether the rendition carries audio; null when the response does not say. +public sealed record FileVersion(string Url, int? Width, int? Height, bool? HasAudio) +{ + public long Area => (long)(Width ?? 0) * (Height ?? 0); + + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"Width = {Width}, Height = {Height}, HasAudio = {HasAudio}"); + return true; + } +} + +/// One file of a content item, with the version chosen for download (spec §6.5 point 1). +/// Photo or video. +/// Identifier of this file of a series, when the site gives one. +/// Largest image, or best video version complete with audio. +/// For videos: the largest cover image. +/// Video duration, when given. +public sealed record ContentFile(MediaKind Kind, string? InstagramId, FileVersion Best, FileVersion? Cover, TimeSpan? Duration); + +/// A profile as it appears in a response (author of content, profile page, list of followed profiles). +public sealed record ProfileInfo +{ + public required string Id { get; init; } + + public required string Username { get; init; } + + public string? DisplayName { get; init; } + + public bool? IsPrivate { get; init; } + + public bool? IsFollowed { get; init; } + + public int? PostCount { get; init; } + + /// Largest version of the profile picture. + public FileVersion? Picture { get; init; } + + /// Publication time of the latest active story (stories bar). + public DateTimeOffset? LatestStoryAt { get; init; } + + /// True when the response presents this profile as the connected account (H10). + public bool IsViewer { get; init; } +} + +/// A content node: a post, a story or an item of a highlight collection. +public sealed record ContentItem +{ + public required string Id { get; init; } + + public string? Code { get; init; } + + public required DateTimeOffset TakenAt { get; init; } + + /// Caption: never logged. + public string? Caption { get; init; } + + public ProfileInfo? Owner { get; init; } + + public bool Pinned { get; init; } + + public DateTimeOffset? ExpiresAt { get; init; } + + /// The files in order (one for a single photo or video, several for a series). + public required IReadOnlyList Files { get; init; } + + /// False when the series declares more files than the response carries: Post singolo completes it. + public bool IsComplete { get; init; } = true; + + /// Identifier of the highlight collection the item was found in, if any. + public string? HighlightId { get; init; } + + /// Order of appearance in the response, from 0. + public int Order { get; init; } + + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, Files = {Files.Count}, IsComplete = {IsComplete}"); + return true; + } +} + +/// A highlight collection, with its contents when the response carries them. +public sealed record HighlightInfo +{ + public required string Id { get; init; } + + public required string Title { get; init; } + + public ProfileInfo? Owner { get; init; } + + public FileVersion? Cover { get; init; } + + public IReadOnlyList Items { get; init; } = []; + + public int Order { get; init; } +} + +/// Pagination information of a page of data. +public sealed record PageInfo(bool? HasMore, string? Cursor); + +/// What the reader made of a response. +public enum ReadShape +{ + /// At least one content, profile or highlight was recognized. + Recognized, + + /// Nothing to read (empty lists, a bare status): not an error, but counts as an empty page. + Empty, + + /// A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4). + Unrecognized, +} + +/// Everything one response gave, detached from the JSON document (which is disposed right after). +public sealed record ReadResult +{ + public static ReadResult EmptyResult { get; } = new() { Shape = ReadShape.Empty }; + + public required ReadShape Shape { get; init; } + + public IReadOnlyList Contents { get; init; } = []; + + public IReadOnlyList Profiles { get; init; } = []; + + public IReadOnlyList Highlights { get; init; } = []; + + public PageInfo? Page { get; init; } + + public ProfileInfo? Viewer { get; init; } + + /// For unrecognized responses: the key structure, without any value (spec §6.4). + public string? KeyStructure { get; init; } +} diff --git a/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs b/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs new file mode 100644 index 0000000..d2c5de1 --- /dev/null +++ b/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs @@ -0,0 +1,434 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Febe.Core.Collection.Readers; + +/// +/// One concept of the vocabulary: the keys (or dotted paths, e.g. «image_versions2.candidates») under which a site +/// puts a piece of data. Empty means «not known yet». +/// +public sealed record VocabularyKeys(IReadOnlyList Paths) +{ + public static VocabularyKeys None { get; } = new([]); + + public bool IsSet => Paths.Count > 0; + + /// Each path split into its segments. + internal IReadOnlyList Segments { get; } = [.. Paths.Select(p => p.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))]; + + /// Looks the concept up in : the first path that exists wins. + public bool TryGet(JsonElement node, out JsonElement value) + { + if (node.ValueKind == JsonValueKind.Object) + { + foreach (var segments in Segments) + { + var current = node; + var found = true; + foreach (var segment in segments) + { + if (current.ValueKind != JsonValueKind.Object || !current.TryGetProperty(segment, out current)) + { + found = false; + break; + } + } + + if (found && current.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + { + value = current; + return true; + } + } + } + + value = default; + return false; + } + + /// True when the first segment of one of the paths is a property of . + public bool Has(JsonElement node) => TryGet(node, out _); + + public override string ToString() => Paths.Count == 0 ? "(non impostato)" : string.Join(" | ", Paths); +} + +/// Keys of a content node: a post, a story, an item of a highlight collection, or a file of a series. +public sealed record ContentKeys +{ + public VocabularyKeys Id { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Code { get; init; } = VocabularyKeys.None; + + /// Publication time: a number (Unix seconds, or milliseconds when very large) or an ISO 8601 text. + public VocabularyKeys TakenAt { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Caption { get; init; } = VocabularyKeys.None; + + /// The image versions: an array of version objects (or a single one). + public VocabularyKeys Images { get; init; } = VocabularyKeys.None; + + /// The video versions: an array of version objects (or a single one). + public VocabularyKeys Videos { get; init; } = VocabularyKeys.None; + + /// The files of a series, in order: each one is a content node without its own date. + public VocabularyKeys Children { get; init; } = VocabularyKeys.None; + + /// How many files the series declares: when more than the children received, the data is incomplete. + public VocabularyKeys ChildCount { get; init; } = VocabularyKeys.None; + + /// The author: a profile node. + public VocabularyKeys Owner { get; init; } = VocabularyKeys.None; + + /// True for content pinned on top of a profile (not «already known» for the stop rule). + public VocabularyKeys Pinned { get; init; } = VocabularyKeys.None; + + /// When a story stops being available (a date, as for ). + public VocabularyKeys ExpiresAt { get; init; } = VocabularyKeys.None; + + /// Video duration in seconds (on the node or on the video version). + public VocabularyKeys Duration { get; init; } = VocabularyKeys.None; +} + +/// Keys of one version of a file (one size of an image, one rendition of a video). +public sealed record VersionKeys +{ + public VocabularyKeys Url { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Width { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Height { get; init; } = VocabularyKeys.None; + + /// For videos: true when the rendition carries audio and video together (spec §6.5 point 1). + public VocabularyKeys HasAudio { get; init; } = VocabularyKeys.None; +} + +/// Keys of a profile node. +public sealed record ProfileKeys +{ + public VocabularyKeys Id { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Username { get; init; } = VocabularyKeys.None; + + public VocabularyKeys DisplayName { get; init; } = VocabularyKeys.None; + + public VocabularyKeys IsPrivate { get; init; } = VocabularyKeys.None; + + /// True when Alberto follows the profile. + public VocabularyKeys IsFollowed { get; init; } = VocabularyKeys.None; + + public VocabularyKeys PostCount { get; init; } = VocabularyKeys.None; + + /// Profile picture: a version object, an array of versions or an address. + public VocabularyKeys Picture { get; init; } = VocabularyKeys.None; + + /// When the latest active story was published (stories bar, H2). + public VocabularyKeys LatestStoryAt { get; init; } = VocabularyKeys.None; +} + +/// Keys of a highlight collection node. +public sealed record HighlightKeys +{ + public VocabularyKeys Id { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Title { get; init; } = VocabularyKeys.None; + + public VocabularyKeys Owner { get; init; } = VocabularyKeys.None; + + /// The contents of the collection, when the response carries them. + public VocabularyKeys Items { get; init; } = VocabularyKeys.None; +} + +/// Keys of the pagination information that comes with a page of data. +public sealed record PageKeys +{ + public VocabularyKeys HasMore { get; init; } = VocabularyKeys.None; + + /// Opaque resume point given by the site (the backfill stores it). + public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None; +} + +/// Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10). +public enum VocabularyStatus +{ + Confirmed, + + /// Hints only, to be confirmed with the M0 samples: recipes refuse to use it. + Hypothesis, +} + +/// +/// The key vocabulary of one site (lettori.instagram.json, lettori.prova.json): which keys mean what. +/// The reader finds data by shape, wherever it is in the response; the vocabulary only names the keys, so it can be +/// updated without recompiling when the site changes (spec §6.4). +/// +public sealed record ReaderVocabulary +{ + public required string Site { get; init; } + + public VocabularyStatus Status { get; init; } = VocabularyStatus.Hypothesis; + + public string? Note { get; init; } + + /// Where it was loaded from, for messages. + public string? Source { get; init; } + + public ContentKeys Content { get; init; } = new(); + + public VersionKeys Version { get; init; } = new(); + + public ProfileKeys Profile { get; init; } = new(); + + public HighlightKeys Highlight { get; init; } = new(); + + public PageKeys Page { get; init; } = new(); + + /// The key under which the response describes the connected account (H10). + public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None; + + /// + /// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is + /// a hypothesis, recipes refuse to run on the site. + /// + public IReadOnlyList MissingConcepts + { + get + { + var missing = new List(); + void Need(VocabularyKeys keys, string name) + { + if (!keys.IsSet) + { + missing.Add(name); + } + } + + Need(Content.Id, "content.id"); + Need(Content.TakenAt, "content.takenAt"); + Need(Content.Images, "content.images"); + Need(Content.Videos, "content.videos"); + Need(Version.Url, "version.url"); + Need(Version.Width, "version.width"); + Need(Version.Height, "version.height"); + Need(Profile.Id, "profile.id"); + Need(Profile.Username, "profile.username"); + return missing; + } + } + + /// True when recipes may rely on this vocabulary. + public bool IsUsable => Status == VocabularyStatus.Confirmed && MissingConcepts.Count == 0; + + /// Italian explanation of why the vocabulary cannot be used yet, or null. + public string? UnusableReason => IsUsable + ? null + : Status == VocabularyStatus.Hypothesis + ? $"Il vocabolario dei lettori per «{Site}» è ancora un'ipotesi, da confermare con i campioni di M0 (specifica §6.4, regola 10)." + : $"Il vocabolario dei lettori per «{Site}» è incompleto: mancano {string.Join(", ", MissingConcepts)}."; + + /// The shipped Instagram vocabulary (embedded lettori.instagram.json): hints only. + public static ReaderVocabulary LoadInstagram() => LoadEmbedded("lettori.instagram.json"); + + /// The vocabulary of the local test site (embedded lettori.prova.json). + public static ReaderVocabulary LoadTestSite() => LoadEmbedded("lettori.prova.json"); + + /// Loads when it exists, otherwise the embedded file with the same name. + public static ReaderVocabulary LoadOrEmbedded(string? path, string embeddedName) => + !string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName); + + public static ReaderVocabulary Load(string path) => Parse(File.ReadAllText(path), path); + + public static ReaderVocabulary LoadEmbedded(string fileName) + { + var resource = $"Febe.Core.Config.{fileName}"; + using var stream = typeof(ReaderVocabulary).Assembly.GetManifestResourceStream(resource) + ?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}"); + using var reader = new StreamReader(stream); + return Parse(reader.ReadToEnd(), fileName); + } + + public static ReaderVocabulary Parse(string json, string? source = null) + { + var name = source ?? "lettori"; + VocabularyFile? file; + try + { + file = JsonSerializer.Deserialize(json, VocabularyJsonContext.Default.VocabularyFile); + } + catch (JsonException ex) + { + throw new InvalidDataException($"{name}: file non valido (riga {ex.LineNumber + 1}): {ex.Message.Split('.')[0]}.", ex); + } + + if (file is null || string.IsNullOrWhiteSpace(file.Site)) + { + throw new InvalidDataException($"{name}: manca «site»."); + } + + var status = file.Status?.Trim().ToLowerInvariant() switch + { + "confermato" or "confirmed" => VocabularyStatus.Confirmed, + "ipotesi" or "hypothesis" or null or "" => VocabularyStatus.Hypothesis, + _ => throw new InvalidDataException($"{name}: stato «{file.Status}» sconosciuto (ammessi: confermato, ipotesi)."), + }; + + static VocabularyKeys K(List? paths) => + paths is null ? VocabularyKeys.None : new VocabularyKeys([.. paths.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p.Trim())]); + + var c = file.Content ?? new ContentDto(); + var v = file.Version ?? new VersionDto(); + var p = file.Profile ?? new ProfileDto(); + var h = file.Highlight ?? new HighlightDto(); + var g = file.Page ?? new PageDto(); + return new ReaderVocabulary + { + Site = file.Site.Trim(), + Status = status, + Note = file.Note, + Source = source, + Content = new ContentKeys + { + Id = K(c.Id), + Code = K(c.Code), + TakenAt = K(c.TakenAt), + Caption = K(c.Caption), + Images = K(c.Images), + Videos = K(c.Videos), + Children = K(c.Children), + ChildCount = K(c.ChildCount), + Owner = K(c.Owner), + Pinned = K(c.Pinned), + ExpiresAt = K(c.ExpiresAt), + Duration = K(c.Duration), + }, + Version = new VersionKeys { Url = K(v.Url), Width = K(v.Width), Height = K(v.Height), HasAudio = K(v.HasAudio) }, + Profile = new ProfileKeys + { + Id = K(p.Id), + Username = K(p.Username), + DisplayName = K(p.DisplayName), + IsPrivate = K(p.IsPrivate), + IsFollowed = K(p.IsFollowed), + PostCount = K(p.PostCount), + Picture = K(p.Picture), + LatestStoryAt = K(p.LatestStoryAt), + }, + Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) }, + Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) }, + Viewer = K(file.Viewer), + }; + } +} + +internal sealed class VocabularyFile +{ + public string? Site { get; set; } + + public string? Status { get; set; } + + public string? Note { get; set; } + + public ContentDto? Content { get; set; } + + public VersionDto? Version { get; set; } + + public ProfileDto? Profile { get; set; } + + public HighlightDto? Highlight { get; set; } + + public PageDto? Page { get; set; } + + public List? Viewer { get; set; } +} + +internal sealed class ContentDto +{ + public string? Note { get; set; } + + public List? Id { get; set; } + + public List? Code { get; set; } + + public List? TakenAt { get; set; } + + public List? Caption { get; set; } + + public List? Images { get; set; } + + public List? Videos { get; set; } + + public List? Children { get; set; } + + public List? ChildCount { get; set; } + + public List? Owner { get; set; } + + public List? Pinned { get; set; } + + public List? ExpiresAt { get; set; } + + public List? Duration { get; set; } +} + +internal sealed class VersionDto +{ + public string? Note { get; set; } + + public List? Url { get; set; } + + public List? Width { get; set; } + + public List? Height { get; set; } + + public List? HasAudio { get; set; } +} + +internal sealed class ProfileDto +{ + public string? Note { get; set; } + + public List? Id { get; set; } + + public List? Username { get; set; } + + public List? DisplayName { get; set; } + + public List? IsPrivate { get; set; } + + public List? IsFollowed { get; set; } + + public List? PostCount { get; set; } + + public List? Picture { get; set; } + + public List? LatestStoryAt { get; set; } +} + +internal sealed class HighlightDto +{ + public string? Note { get; set; } + + public List? Id { get; set; } + + public List? Title { get; set; } + + public List? Owner { get; set; } + + public List? Items { get; set; } +} + +internal sealed class PageDto +{ + public string? Note { get; set; } + + public List? HasMore { get; set; } + + public List? Cursor { get; set; } +} + +[JsonSourceGenerationOptions( + PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow)] +[JsonSerializable(typeof(VocabularyFile))] +internal sealed partial class VocabularyJsonContext : JsonSerializerContext; diff --git a/src/Febe.Core/Collection/Readers/ShapeReader.cs b/src/Febe.Core/Collection/Readers/ShapeReader.cs new file mode 100644 index 0000000..0b9dc25 --- /dev/null +++ b/src/Febe.Core/Collection/Readers/ShapeReader.cs @@ -0,0 +1,488 @@ +using System.Globalization; +using System.Text.Json; +using Febe.Core.Domain; + +namespace Febe.Core.Collection.Readers; + +/// +/// The generic reader (spec §6.4): walks any JSON tree and recognizes, wherever they are, the nodes that look like a +/// content (identifier, date, image or video versions, possibly a series), a profile (identifier and user name), a +/// highlight collection (identifier and title) and the pagination of a page. Which keys mean what comes from the +/// site's , never from fixed paths or addresses. +/// +/// +/// Version choice (spec §6.5 point 1): the largest image; for videos the largest among the versions complete with +/// audio (versions that do not say are taken as complete), or the largest of all when none has audio. +/// Thread-safe: the reader keeps no state between calls. +/// +public sealed class ShapeReader +{ + private const int MaxDepth = 64; + + private readonly ReaderVocabulary _v; + + public ShapeReader(ReaderVocabulary vocabulary) + { + _v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary)); + } + + public ReaderVocabulary Vocabulary => _v; + + /// Reads one response body. Never throws on unexpected shapes: they become . + public ReadResult Read(JsonElement root) + { + var walk = new Walk(); + Visit(root, walk, owner: null, highlightId: null, depth: 0); + + var profiles = walk.Profiles.Values.ToList(); + var viewer = profiles.FirstOrDefault(p => p.IsViewer); + if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0) + { + return new ReadResult + { + Shape = ReadShape.Recognized, + Contents = walk.Contents, + Profiles = profiles, + Highlights = walk.Highlights, + Page = walk.Page, + Viewer = viewer, + }; + } + + if (IsEmptyShape(root, walk.Page is not null)) + { + return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page }; + } + + return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) }; + } + + /// Reads a body given as text (tests, probe samples). + public ReadResult Read(string json) + { + using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 256 }); + return Read(document.RootElement); + } + + private void Visit(JsonElement node, Walk walk, ProfileInfo? owner, string? highlightId, int depth) + { + if (depth > MaxDepth) + { + return; + } + + if (node.ValueKind == JsonValueKind.Array) + { + foreach (var item in node.EnumerateArray()) + { + Visit(item, walk, owner, highlightId, depth + 1); + } + + return; + } + + if (node.ValueKind != JsonValueKind.Object) + { + return; + } + + if (walk.Page is null && (_v.Page.HasMore.Has(node) || _v.Page.Cursor.Has(node))) + { + walk.Page = new PageInfo( + _v.Page.HasMore.TryGet(node, out var more) ? AsBool(more) : null, + _v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null); + } + + if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer) + { + walk.AddProfile(viewer with { IsViewer = true }); + } + + if (IsContent(node)) + { + if (ReadContent(node, walk, owner, highlightId) is { } item) + { + walk.Contents.Add(item); + } + + return; + } + + if (IsHighlight(node)) + { + var highlightOwner = _v.Highlight.Owner.TryGet(node, out var ho) ? ReadProfile(ho) ?? owner : owner; + if (highlightOwner is not null) + { + walk.AddProfile(highlightOwner); + } + + var id = AsText(Get(_v.Highlight.Id, node))!; + var before = walk.Contents.Count; + if (_v.Highlight.Items.TryGet(node, out var items)) + { + Visit(items, walk, highlightOwner, id, depth + 1); + } + + walk.Highlights.Add(new HighlightInfo + { + Id = id, + Title = AsText(Get(_v.Highlight.Title, node)) ?? string.Empty, + Owner = highlightOwner, + Items = walk.Contents.Skip(before).ToList(), + Order = walk.Highlights.Count, + }); + return; + } + + var inherited = owner; + if (ReadProfile(node) is { } profile) + { + walk.AddProfile(profile); + inherited = profile; + } + else if (_v.Content.Owner.TryGet(node, out var ownerNode) && ReadProfile(ownerNode) is { } declared) + { + // An object that declares an author for what it contains (e.g. the stories of one account). + walk.AddProfile(declared); + inherited = declared; + } + + foreach (var property in node.EnumerateObject()) + { + if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array) + { + Visit(property.Value, walk, inherited, highlightId, depth + 1); + } + } + } + + private bool IsContent(JsonElement node) => + _v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node) + && (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node)); + + private bool IsHighlight(JsonElement node) => + _v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null; + + private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId) + { + var id = AsText(Get(_v.Content.Id, node)); + var takenAt = AsTime(Get(_v.Content.TakenAt, node)); + if (id is null || takenAt is null) + { + return null; + } + + var owner = _v.Content.Owner.TryGet(node, out var ownerNode) ? ReadProfile(ownerNode) ?? inheritedOwner : inheritedOwner; + if (owner is not null) + { + walk.AddProfile(owner); + } + + var files = new List(); + var hasChildren = _v.Content.Children.TryGet(node, out var children) && children.ValueKind == JsonValueKind.Array && children.GetArrayLength() > 0; + var declaredChildren = 0; + if (hasChildren) + { + foreach (var child in children.EnumerateArray()) + { + declaredChildren++; + if (child.ValueKind == JsonValueKind.Object && ReadFile(child) is { } file) + { + files.Add(file); + } + } + } + else if (ReadFile(node) is { } single) + { + files.Add(single); + } + + var complete = files.Count > 0 && (!hasChildren || files.Count == declaredChildren); + if (_v.Content.ChildCount.TryGet(node, out var countNode) && AsInt(countNode) is { } declared && declared > files.Count) + { + complete = false; + } + + return new ContentItem + { + Id = id, + Code = AsText(Get(_v.Content.Code, node)), + TakenAt = takenAt.Value, + Caption = AsText(Get(_v.Content.Caption, node)), + Owner = owner, + Pinned = _v.Content.Pinned.TryGet(node, out var pinned) && AsBool(pinned) == true, + ExpiresAt = AsTime(Get(_v.Content.ExpiresAt, node)), + Files = files, + IsComplete = complete, + HighlightId = highlightId, + Order = walk.Contents.Count, + }; + } + + private ContentFile? ReadFile(JsonElement node) + { + var videos = _v.Content.Videos.TryGet(node, out var v) ? ReadVersions(v) : []; + var images = _v.Content.Images.TryGet(node, out var i) ? ReadVersions(i) : []; + var id = AsText(Get(_v.Content.Id, node)); + var largestImage = images.Count == 0 ? null : images.MaxBy(x => x.Version.Area); + if (videos.Count > 0) + { + var complete = videos.Where(x => x.Version.HasAudio != false).ToList(); + var best = (complete.Count > 0 ? complete : videos).MaxBy(x => x.Version.Area)!; + var duration = AsSeconds(Get(_v.Content.Duration, node)) ?? AsSeconds(Get(_v.Content.Duration, best.Node)); + return new ContentFile(MediaKind.Video, id, best.Version, largestImage?.Version, duration); + } + + return largestImage is null ? null : new ContentFile(MediaKind.Photo, id, largestImage.Version, null, null); + } + + private List ReadVersions(JsonElement value) + { + var list = new List(); + switch (value.ValueKind) + { + case JsonValueKind.Array: + foreach (var item in value.EnumerateArray()) + { + if (ReadVersion(item) is { } version) + { + list.Add(new VersionNode(version, item)); + } + } + + break; + case JsonValueKind.Object: + case JsonValueKind.String: + if (ReadVersion(value) is { } single) + { + list.Add(new VersionNode(single, value)); + } + + break; + } + + return list; + } + + private FileVersion? ReadVersion(JsonElement node) + { + if (node.ValueKind == JsonValueKind.String) + { + return IsAddress(node.GetString()) ? new FileVersion(node.GetString()!, null, null, null) : null; + } + + if (node.ValueKind != JsonValueKind.Object) + { + return null; + } + + var url = AsText(Get(_v.Version.Url, node)); + if (!IsAddress(url)) + { + return null; + } + + return new FileVersion( + url!, + AsInt(Get(_v.Version.Width, node)), + AsInt(Get(_v.Version.Height, node)), + _v.Version.HasAudio.TryGet(node, out var audio) ? AsBool(audio) : null); + } + + private ProfileInfo? ReadProfile(JsonElement node) + { + if (node.ValueKind != JsonValueKind.Object) + { + return null; + } + + var id = AsText(Get(_v.Profile.Id, node)); + var username = AsText(Get(_v.Profile.Username, node)); + if (id is null || string.IsNullOrWhiteSpace(username)) + { + return null; + } + + FileVersion? picture = null; + if (_v.Profile.Picture.TryGet(node, out var pictureNode)) + { + picture = ReadVersions(pictureNode).MaxBy(x => x.Version.Area)?.Version; + } + + return new ProfileInfo + { + Id = id, + Username = username.Trim(), + DisplayName = AsText(Get(_v.Profile.DisplayName, node)), + IsPrivate = _v.Profile.IsPrivate.TryGet(node, out var p) ? AsBool(p) : null, + IsFollowed = _v.Profile.IsFollowed.TryGet(node, out var f) ? AsBool(f) : null, + PostCount = AsInt(Get(_v.Profile.PostCount, node)), + Picture = picture, + LatestStoryAt = AsTime(Get(_v.Profile.LatestStoryAt, node)), + }; + } + + /// + /// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top + /// (a bare status or error). Anything richer that nothing recognized is an unknown shape. + /// + private static bool IsEmptyShape(JsonElement root, bool hasPage) + { + var nested = false; + var nonEmptyArray = false; + Scan(root, 0, ref nested, ref nonEmptyArray); + return !nonEmptyArray && (hasPage || !nested); + } + + private static void Scan(JsonElement element, int depth, ref bool nested, ref bool nonEmptyArray) + { + if (depth > MaxDepth) + { + return; + } + + switch (element.ValueKind) + { + case JsonValueKind.Object: + foreach (var property in element.EnumerateObject()) + { + if (property.Value.ValueKind == JsonValueKind.Object) + { + nested = true; + } + + Scan(property.Value, depth + 1, ref nested, ref nonEmptyArray); + } + + break; + case JsonValueKind.Array: + if (element.GetArrayLength() > 0) + { + nonEmptyArray = true; + } + + break; + } + } + + private static JsonElement Get(VocabularyKeys keys, JsonElement node) => keys.TryGet(node, out var value) ? value : default; + + private static bool IsAddress(string? text) => + !string.IsNullOrWhiteSpace(text) + && Uri.TryCreate(text, UriKind.Absolute, out var uri) + && uri.Scheme is "http" or "https"; + + internal static string? AsText(JsonElement value) => value.ValueKind switch + { + JsonValueKind.String => string.IsNullOrEmpty(value.GetString()) ? null : value.GetString(), + JsonValueKind.Number => value.GetRawText(), + _ => null, + }; + + internal static int? AsInt(JsonElement value) + { + switch (value.ValueKind) + { + case JsonValueKind.Number when value.TryGetInt32(out var i): + return i; + case JsonValueKind.Number when value.TryGetDouble(out var d) && d is >= int.MinValue and <= int.MaxValue: + return (int)Math.Round(d); + case JsonValueKind.String when int.TryParse(value.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var s): + return s; + default: + return null; + } + } + + internal static bool? AsBool(JsonElement value) => value.ValueKind switch + { + JsonValueKind.True => true, + JsonValueKind.False => false, + JsonValueKind.Number => value.TryGetInt64(out var n) ? n != 0 : null, + JsonValueKind.String => value.GetString()?.Trim().ToLowerInvariant() switch + { + "true" or "1" or "sì" or "si" => true, + "false" or "0" or "no" => false, + _ => null, + }, + _ => null, + }; + + internal static TimeSpan? AsSeconds(JsonElement value) + { + double? seconds = value.ValueKind switch + { + JsonValueKind.Number when value.TryGetDouble(out var d) => d, + JsonValueKind.String when double.TryParse(value.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var s) => s, + _ => null, + }; + return seconds is { } x && x >= 0 && x < 1e7 ? TimeSpan.FromSeconds(x) : null; + } + + /// A date: Unix seconds (milliseconds when larger than 10^11), or ISO 8601 text. + internal static DateTimeOffset? AsTime(JsonElement value) + { + switch (value.ValueKind) + { + case JsonValueKind.Number when value.TryGetDouble(out var n): + return FromUnix(n); + case JsonValueKind.String: + var text = value.GetString(); + if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var numeric)) + { + return FromUnix(numeric); + } + + return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed) + ? parsed + : null; + default: + return null; + } + } + + private static DateTimeOffset? FromUnix(double value) + { + if (value <= 0 || double.IsNaN(value)) + { + return null; + } + + var ms = value > 1e11 ? value : value * 1000; + return ms < 253402300799000 ? DateTimeOffset.FromUnixTimeMilliseconds((long)ms) : null; + } + + private sealed record VersionNode(FileVersion Version, JsonElement Node); + + private sealed class Walk + { + public List Contents { get; } = []; + + public List Highlights { get; } = []; + + public Dictionary Profiles { get; } = new(StringComparer.Ordinal); + + public PageInfo? Page { get; set; } + + /// Merges what different parts of a response say about the same profile. + public void AddProfile(ProfileInfo profile) + { + if (!Profiles.TryGetValue(profile.Id, out var known)) + { + Profiles[profile.Id] = profile; + return; + } + + Profiles[profile.Id] = known with + { + DisplayName = known.DisplayName ?? profile.DisplayName, + IsPrivate = known.IsPrivate ?? profile.IsPrivate, + IsFollowed = known.IsFollowed ?? profile.IsFollowed, + PostCount = known.PostCount ?? profile.PostCount, + Picture = known.Picture ?? profile.Picture, + LatestStoryAt = known.LatestStoryAt ?? profile.LatestStoryAt, + IsViewer = known.IsViewer || profile.IsViewer, + }; + } + } +} diff --git a/src/Febe.Core/Collection/Recipes/CaptureCollector.cs b/src/Febe.Core/Collection/Recipes/CaptureCollector.cs new file mode 100644 index 0000000..843db7e --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/CaptureCollector.cs @@ -0,0 +1,199 @@ +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; + +namespace Febe.Core.Collection.Recipes; + +/// One response read by the reader, in arrival order. +/// Arrival number, from 1. +/// Sanitized descriptor (no query string). +/// What the reader recognized, detached from the body. +public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, ReadResult Result); + +/// +/// Bridge between the response tap and the recipes (spec §6.2, §6.4): every JSON body the site sends is read by the +/// as it arrives, and the recipes wait for what they expect after a gesture. Bodies are +/// never kept: only the reader's detached results are. +/// +/// +/// It also tracks which data responses are still on their way (their body not read yet), so a recipe can wait until +/// the page has settled. Thread-safe. +/// +public sealed class CaptureCollector : IResponseConsumer, IResponseObserver +{ + private const int MaxKept = 2000; + + private readonly ShapeReader _reader; + private readonly IClock _clock; + private readonly Lock _gate = new(); + private readonly List _reads = []; + private readonly Dictionary _pending = new(StringComparer.Ordinal); + private long _sequence; + + public CaptureCollector(ShapeReader reader, IClock clock) + { + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + } + + public ShapeReader Reader => _reader; + + /// How long a data response may stay «on its way» before it is forgotten (its body may never come). + public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15); + + /// Sequence number of the last read: pass it to to get what arrives after now. + public long Mark() + { + lock (_gate) + { + return _sequence; + } + } + + /// Reads that arrived after , oldest first. + public IReadOnlyList Since(long mark) + { + lock (_gate) + { + return [.. _reads.Where(r => r.Sequence > mark)]; + } + } + + /// Data responses whose body has not been read yet. + public int Pending + { + get + { + lock (_gate) + { + ExpirePending(); + return _pending.Count; + } + } + } + + /// + /// Waits until the reads after satisfy , or + /// passes. Returns the reads after the mark either way. + /// + public async Task> WaitAsync(long mark, Func, bool> until, TimeSpan timeout, TimeSpan poll, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(until); + var deadline = _clock.Now + timeout; + while (true) + { + var reads = Since(mark); + if (until(reads) || _clock.Now >= deadline) + { + return reads; + } + + await _clock.Delay(poll, ct).ConfigureAwait(false); + } + } + + /// + /// Waits until no data response is on its way and nothing new arrived for , at most + /// . + /// + public async Task SettleAsync(TimeSpan quiet, TimeSpan timeout, TimeSpan poll, CancellationToken ct) + { + var deadline = _clock.Now + timeout; + var lastSeen = Mark(); + var quietSince = _clock.Now; + while (_clock.Now < deadline) + { + await _clock.Delay(poll, ct).ConfigureAwait(false); + var current = Mark(); + if (current != lastSeen || Pending > 0) + { + lastSeen = current; + quietSince = _clock.Now; + continue; + } + + if (_clock.Now - quietSince >= quiet) + { + return; + } + } + } + + /// Forgets everything (start of a recipe). + public void Clear() + { + lock (_gate) + { + _reads.Clear(); + _pending.Clear(); + } + } + + ValueTask IResponseConsumer.ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct) + { + Accept(response, body.RootElement); + return ValueTask.CompletedTask; + } + + /// Reads one body (also used by tests and the probe samples). + public CapturedRead? Accept(ResponseDescriptor response, JsonElement body) + { + ArgumentNullException.ThrowIfNull(response); + lock (_gate) + { + _pending.Remove(response.RequestId); + } + + if (response.HostKind != HostKind.Site) + { + return null; + } + + var result = _reader.Read(body); + lock (_gate) + { + var read = new CapturedRead(++_sequence, response, result); + _reads.Add(read); + if (_reads.Count > MaxKept) + { + _reads.RemoveRange(0, _reads.Count - MaxKept); + } + + return read; + } + } + + void IResponseObserver.OnResponse(ResponseDescriptor response) + { + if (response.HostKind == HostKind.Site + && response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase) + && response.Status is >= 200 and < 600 && response.Status != 204) + { + lock (_gate) + { + _pending[response.RequestId] = _clock.Now; + } + } + } + + void IResponseObserver.OnNavigation(NavigationDescriptor navigation) + { + if (!navigation.SameDocument) + { + // Bodies of the previous document will not be read any more (the tap forgets them too). + lock (_gate) + { + _pending.Clear(); + } + } + } + + private void ExpirePending() + { + var limit = _clock.Now - PendingLifetime; + foreach (var key in _pending.Where(p => p.Value < limit).Select(p => p.Key).ToList()) + { + _pending.Remove(key); + } + } +} diff --git a/src/Febe.Core/Collection/Recipes/CollectionWriter.cs b/src/Febe.Core/Collection/Recipes/CollectionWriter.cs new file mode 100644 index 0000000..af448cb --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/CollectionWriter.cs @@ -0,0 +1,356 @@ +using System.Globalization; +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Recipes; + +/// What saving a content item did. +public enum SaveOutcome +{ + /// A new entry with its files to download. + Created, + + /// Already known (in any state, deleted included): nothing new. + Known, + + /// An imported entry recognized by account, kind and time (spec §9.5): it took the Instagram data. + Enriched, + + /// Not wanted: the account's switches or limits exclude it. + Excluded, +} + +/// Result of . +public sealed record SaveResult(SaveOutcome Outcome, Entry? Entry); + +/// +/// Turns what the readers recognized into stored records: entries and files (with the account's switches and limits), +/// imported entries recognized after the fact (spec §9.5), renamed accounts (spec §4.2), highlight collections and +/// their contents (H9), tasks for «Post singolo», and the readable events of the timeline. Never logs captions or +/// addresses. +/// +public sealed class CollectionWriter(IFebeStorage storage, IClock clock) +{ + /// Tolerance for recognizing imported entries by publication time (spec §9.5: two seconds). + public static readonly TimeSpan ImportedTimeTolerance = TimeSpan.FromSeconds(2); + + public IFebeStorage Storage => storage; + + /// + /// A profile seen in the data. The account is identified by its numeric id; when its name changed, a followed + /// profile is renamed (folder kept, notice raised) and a profile that is not followed becomes «Non raggiungibile» + /// until Alberto confirms the new name (spec §4.2). Returns the account, or null when Febe does not track it. + /// + public async Task ObserveProfileAsync(ProfileInfo profile, long? sessionId, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(profile); + var account = await storage.Accounts.FindByInstagramIdAsync(profile.Id, ct).ConfigureAwait(false); + if (account is null || string.Equals(account.Username, profile.Username, StringComparison.OrdinalIgnoreCase)) + { + return account; + } + + var now = clock.Now; + if (account.IsFollowed || profile.IsFollowed == true || account.IsMine) + { + var old = account.Username; + await storage.Accounts.RenameAsync(account.Id, profile.Username, now, ct).ConfigureAwait(false); + await EventAsync("account-rinominato", $"{old} ora si chiama {profile.Username}: nome aggiornato, la cartella resta la stessa.", EventSeverity.Warning, account.Id, sessionId, ct).ConfigureAwait(false); + } + else if (account.State != AccountState.Unreachable) + { + await storage.Accounts.SetStateAsync(account.Id, AccountState.Unreachable, now, UnreachableReason.Renamed, ct).ConfigureAwait(false); + await EventAsync("account-non-raggiungibile", $"{account.Username} ha cambiato nome e non è un profilo seguito: indica il nuovo nome per riprendere.", EventSeverity.Warning, account.Id, sessionId, ct).ConfigureAwait(false); + } + + return await storage.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false); + } + + /// + /// Stores the facts of a profile read during a check: identifier (first time), privacy, follow state, number of + /// posts, display name, time of the check. Returns the updated account. + /// + public async Task ApplyProfileAsync(Account account, ProfileInfo profile, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(profile); + if (account.InstagramId is null) + { + await storage.Accounts.UpdateAsync(account with { InstagramId = profile.Id }, ct).ConfigureAwait(false); + } + + await storage.Accounts.UpdateChecksAsync( + account.Id, + new AccountCheckTimes + { + LastProfileCheckAt = clock.Now, + PostCount = profile.PostCount, + IsPrivate = profile.IsPrivate, + IsFollowed = profile.IsFollowed, + DisplayName = profile.DisplayName, + }, + ct).ConfigureAwait(false); + return await storage.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account; + } + + /// Whether the account wants entries of this kind («Cosa scaricare», spec §4.4). + public static bool Wants(Account account, EntryKind kind) + { + ArgumentNullException.ThrowIfNull(account); + return kind switch + { + EntryKind.Post => (account.ContentTypes & (ContentTypes.PostPhotos | ContentTypes.PostVideos)) != 0, + EntryKind.Story => account.ContentTypes.HasFlag(ContentTypes.Stories), + EntryKind.Highlight => account.ContentTypes.HasFlag(ContentTypes.Highlights), + EntryKind.Tagged => account.ContentTypes.HasFlag(ContentTypes.Tagged), + EntryKind.ProfilePicture => account.ContentTypes.HasFlag(ContentTypes.ProfilePicture), + _ => false, + }; + } + + /// Why a file is skipped by the account's settings, or null when it is wanted. + public static string? SkipReason(Account account, EntryKind kind, MediaKind media) + { + ArgumentNullException.ThrowIfNull(account); + return (kind, media) switch + { + (EntryKind.Story, MediaKind.Video) when !account.Limits.StoryVideos => "Video delle storie esclusi nelle impostazioni dell'account.", + (EntryKind.Post, MediaKind.Video) when !account.ContentTypes.HasFlag(ContentTypes.PostVideos) => "«Video e reel» è spento per questo account.", + (EntryKind.Post, MediaKind.Photo) when !account.ContentTypes.HasFlag(ContentTypes.PostPhotos) => "«Foto dei post» è spento per questo account.", + _ => null, + }; + } + + /// + /// Saves a content item as an entry of for , unless it is known, + /// excluded by the account's settings, or an imported entry recognized by time (§9.5). An incomplete series is + /// saved with the files received and a «Post singolo» task is queued to complete it. + /// + public async Task SaveAsync(Account account, ContentItem item, EntryKind kind, long? sessionId, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(item); + if (!Wants(account, kind)) + { + return new SaveResult(SaveOutcome.Excluded, null); + } + + var known = await storage.Entries.FindAsync(account.Id, kind, item.Id, ct).ConfigureAwait(false); + if (known is not null) + { + await RefreshExpiredAsync(known, item, ct).ConfigureAwait(false); + return new SaveResult(SaveOutcome.Known, known); + } + + if (kind is EntryKind.Post or EntryKind.Tagged + && account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from) + { + return new SaveResult(SaveOutcome.Excluded, null); + } + + if (kind != EntryKind.ProfilePicture + && await storage.Entries.FindByPublicationTimeAsync(account.Id, kind, item.TakenAt, ImportedTimeTolerance, ct).ConfigureAwait(false) is { InstagramId: null } imported) + { + var enriched = imported with + { + InstagramId = item.Id, + Code = imported.Code ?? item.Code, + Caption = imported.Caption ?? item.Caption, + }; + await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false); + return new SaveResult(SaveOutcome.Enriched, enriched); + } + + var now = clock.Now; + var entry = ReadMapping.ToEntry(item, account.Id, kind, now); + var media = ReadMapping.ToMedia(item, now).Select(m => ApplyPolicy(account, kind, m)).ToList(); + var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false); + if (!added.Created) + { + return new SaveResult(SaveOutcome.Known, added.Stored.Entry); + } + + if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged) + { + await QueueSinglePostAsync(added.Stored.Entry, ct).ConfigureAwait(false); + } + + return new SaveResult(SaveOutcome.Created, added.Stored.Entry); + } + + /// Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256). + public async Task SaveProfilePictureAsync(Account account, ProfileInfo profile, CancellationToken ct) + { + if (!Wants(account, EntryKind.ProfilePicture) || ReadMapping.ToProfilePicture(profile, account.Id, clock.Now) is not { } picture) + { + return new SaveResult(SaveOutcome.Excluded, null); + } + + var added = await storage.Entries.AddAsync(picture.Entry, [picture.Media], ct).ConfigureAwait(false); + return new SaveResult(added.Created ? SaveOutcome.Created : SaveOutcome.Known, added.Stored.Entry); + } + + /// + /// Completes an entry from the full data of its post («Post singolo»): adds the files that were missing, gives + /// expired or failed files a fresh address (never for stories, spec §6.5 point 5), fills code and caption. + /// Returns how many files were added or refreshed. + /// + public async Task CompleteAsync(Entry entry, ContentItem item, Account account, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(item); + var now = clock.Now; + var current = await storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false); + var positions = current.Select(m => m.Position).ToHashSet(); + var received = ReadMapping.ToMedia(item, now).Select(m => ApplyPolicy(account, entry.Kind, m)).ToList(); + var missing = received.Where(m => !positions.Contains(m.Position)).ToList(); + var changed = 0; + if (missing.Count > 0) + { + await storage.Media.AddToEntryAsync(entry.Id, missing, ct).ConfigureAwait(false); + changed += missing.Count; + } + + if (entry.Kind != EntryKind.Story) + { + foreach (var file in current.Where(m => m.State is MediaState.Expired or MediaState.Failed || (m.State == MediaState.ToDownload && m.SourceUrl is null))) + { + if (received.FirstOrDefault(r => r.Position == file.Position) is { SourceUrl: { } url } fresh) + { + await storage.Media.UpdateSourceAsync(file.Id, url, fresh.CoverUrl, now, ct).ConfigureAwait(false); + changed++; + } + } + } + + if ((entry.Code is null && item.Code is not null) || (entry.Caption is null && item.Caption is not null)) + { + var latest = await storage.Entries.GetAsync(entry.Id, ct).ConfigureAwait(false) ?? entry; + await storage.Entries.UpdateAsync(latest with { Code = latest.Code ?? item.Code, Caption = latest.Caption ?? item.Caption }, ct).ConfigureAwait(false); + } + + return changed; + } + + /// + /// Records the highlight collections listed on a profile, in order; collections no longer listed are marked + /// removed (their contents and files stay). Returns the stored collections by Instagram id. + /// + public async Task> UpsertHighlightsAsync(Account account, IReadOnlyList listed, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(listed); + var now = clock.Now; + var stored = new Dictionary(StringComparer.Ordinal); + for (var i = 0; i < listed.Count; i++) + { + var info = listed[i]; + var existing = await storage.Highlights.FindAsync(account.Id, info.Id, ct).ConfigureAwait(false); + var record = existing is null + ? ReadMapping.ToHighlight(info, account.Id, i, now) + : existing with { Title = string.IsNullOrWhiteSpace(info.Title) ? existing.Title : info.Title.Trim(), Position = i, RemovedAt = null }; + stored[info.Id] = await storage.Highlights.UpsertAsync(record, ct).ConfigureAwait(false); + } + + if (stored.Count > 0) + { + foreach (var old in await storage.Highlights.ListAsync(account.Id, includeRemoved: false, ct).ConfigureAwait(false)) + { + if (old.InstagramId is not null && !stored.ContainsKey(old.InstagramId)) + { + await storage.Highlights.MarkRemovedAsync(old.Id, now, ct).ConfigureAwait(false); + } + } + } + + return stored; + } + + /// + /// Puts an item shown in a collection into it. A story already saved with the same identifier is referenced, not + /// downloaded again (H9); otherwise the item becomes an entry of kind «evidenza». Returns the entry, or null when + /// the account does not want highlights. + /// + public async Task<(Entry? Entry, bool Created)> LinkHighlightItemAsync(Account account, Highlight highlight, ContentItem item, long? sessionId, CancellationToken ct) + { + var existing = await storage.Entries.FindByInstagramIdAsync(account.Id, item.Id, ct).ConfigureAwait(false); + var reuse = existing.FirstOrDefault(e => e.Kind == EntryKind.Story) ?? existing.FirstOrDefault(e => e.Kind == EntryKind.Highlight); + var created = false; + if (reuse is null) + { + var saved = await SaveAsync(account, item, EntryKind.Highlight, sessionId, ct).ConfigureAwait(false); + reuse = saved.Entry; + created = saved.Outcome == SaveOutcome.Created; + } + + if (reuse is not null) + { + await storage.Highlights.AddItemAsync(highlight.Id, reuse.Id, ct).ConfigureAwait(false); + } + + return (reuse, created); + } + + /// Queues «Post singolo» for an entry (payload: the local entry id as text). + public Task QueueSinglePostAsync(Entry entry, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(entry); + var now = clock.Now; + return storage.Tasks.EnqueueAsync( + new EngineTask + { + Kind = EngineTaskKind.SinglePost, + AccountId = entry.AccountId, + DueAt = now, + Payload = entry.Id.ToString(CultureInfo.InvariantCulture), + CreatedAt = now, + }, + ct); + } + + /// Appends a line to the readable timeline (Italian; never captions, bodies or signed addresses). + public Task EventAsync(string code, string message, EventSeverity severity, long? accountId, long? sessionId, CancellationToken ct) => + storage.Events.AppendAsync( + new EventRecord + { + At = clock.Now, + Severity = severity, + Code = code, + Message = message, + AccountId = accountId, + SessionId = sessionId, + }, + ct); + + private static Media ApplyPolicy(Account account, EntryKind kind, Media media) => + SkipReason(account, kind, media.Kind) is { } reason + ? media with { State = MediaState.Skipped, SourceUrl = null, CoverUrl = null, LastError = reason } + : media; + + private async Task RefreshExpiredAsync(Entry known, ContentItem item, CancellationToken ct) + { + if (known.State is EntryState.Deleted) + { + return; + } + + var files = await storage.Media.ListByEntryAsync(known.Id, ct).ConfigureAwait(false); + var expired = files.Where(f => f.State == MediaState.Expired).ToList(); + if (expired.Count == 0) + { + return; + } + + var now = clock.Now; + var received = ReadMapping.ToMedia(item, now); + foreach (var file in expired) + { + if (received.FirstOrDefault(r => r.Position == file.Position) is { SourceUrl: { } url } fresh) + { + await storage.Media.UpdateSourceAsync(file.Id, url, fresh.CoverUrl, now, ct).ConfigureAwait(false); + } + } + } +} diff --git a/src/Febe.Core/Collection/Recipes/IPageDriver.cs b/src/Febe.Core/Collection/Recipes/IPageDriver.cs new file mode 100644 index 0000000..659e379 --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/IPageDriver.cs @@ -0,0 +1,101 @@ +using Febe.Core.Abstractions; + +namespace Febe.Core.Collection.Recipes; + +/// Outcome of looking a target up or clicking it. +public enum TargetCheckStatus +{ + Found, + + /// Clicked (for ). + Clicked, + + NotFound, + + NotVisible, + + OutOfView, + + Obstructed, + + /// The map has the entry but it is still empty (H11). + NotConfigured, +} + +/// Result of a target lookup or click. When not found, recipes stop and report: never coordinates (spec §7.7). +/// Target identifier of the map. +/// What happened. +/// Visible matches found. +/// Italian message for events, without page content. +public sealed record TargetCheck(string Id, TargetCheckStatus Status, int Matches, string Message) +{ + public bool Found => Status is TargetCheckStatus.Found or TargetCheckStatus.Clicked; +} + +/// Result of opening a page. +/// The page was loaded. +/// Path of the page now shown (no query string). +/// Browser error, without the address. +public sealed record PageLoad(bool Succeeded, string Path, string? Error); + +/// +/// What a recipe can do with the page (spec §6.3): open pages of the site, find and click targets of the target map, +/// scroll with human gestures, wait, and read the state of the page without changing it. Implemented over the browser +/// layer (Febe.Browser.Recipes.BrowserPageDriver); a fake implementation drives the simulation and unit tests. +/// +/// +/// Gestures go through Input only and never through scripts; a missing target is reported, never replaced by +/// coordinates; the driver refuses to open addresses outside the site. Counting actions is not the driver's job: the +/// recipe asks the Governor before every counted action. +/// +public interface IPageDriver +{ + /// Product of mood and gesture pace: multiplies the waits the recipes compute themselves (§7.7). + double WaitMultiplier { get; } + + /// A new session starts: gestures use its mood from now on. + void BeginSession(double mood); + + /// Opens a page of the site by path (starting with «/»), and waits until it is loaded and painted. + Task OpenAsync(string path, CancellationToken ct); + + /// Path of the current page (no query string), read without changing anything. + Task CurrentPathAsync(CancellationToken ct); + + /// True when the current page belongs to the site (links outside the site are never followed). + Task IsOnSiteAsync(CancellationToken ct); + + /// Looks a target up, read-only. + Task FindAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct); + + /// Clicks a target with a human gesture (bringing it into view with the wheel if needed). + Task ClickAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct); + + /// One burst of wheel events down, the pause after it, and now and then a small scroll back (§7.7). + Task ScrollBurstAsync(CancellationToken ct); + + /// The wait after a page load before the first gesture (median 2.2 s, 1–6 s). + Task WaitAfterLoadAsync(CancellationToken ct); + + /// Waits (already multiplied by the recipe when needed). + Task WaitAsync(TimeSpan duration, CancellationToken ct); + + /// With 8% probability, an extra wait of 15–90 s after an action. + Task MaybeDistractionAsync(CancellationToken ct); + + /// Whether the session cookie exists (never its value); null when it cannot be told. + Task HasSessionCookieAsync(CancellationToken ct); + + /// The rest page (spec §6.1). + Task RestAsync(CancellationToken ct); +} + +/// +/// Remaining budget of a category (spec §6.3: before opening the stories of an account the recipe checks that the +/// budget allows at least ten). Implemented by the Governor of the engine; tests use a permissive fake. +/// +public interface IBudgetView +{ + /// Actions of still allowed now (the stricter of hour and day, account limits included). + Task RemainingAsync(ActionKind kind, long? accountId, CancellationToken ct); +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeOptions.cs b/src/Febe.Core/Collection/Recipes/RecipeOptions.cs new file mode 100644 index 0000000..4318240 --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeOptions.cs @@ -0,0 +1,76 @@ +using Febe.Core.Abstractions; +using Febe.Core.Pacing; + +namespace Febe.Core.Collection.Recipes; + +/// Limits and technical timeouts of the recipes. Times are measured with . +public sealed record RecipeOptions +{ + /// How long to wait for the data of a page after opening it or after a gesture. + public TimeSpan DataTimeout { get; init; } = TimeSpan.FromSeconds(20); + + /// Quiet time without new data responses that counts as «the page has settled». + public TimeSpan SettleQuiet { get; init; } = TimeSpan.FromMilliseconds(700); + + /// How long to wait for the viewer to open, move on or close after a click. + public TimeSpan ViewerTimeout { get; init; } = TimeSpan.FromSeconds(10); + + /// Polling interval of read-only checks. + public TimeSpan Poll { get; init; } = TimeSpan.FromMilliseconds(100); + + /// Giro dei seguiti: at most this many scroll bursts (spec §6.3: 8). + public int SweepMaxBursts { get; init; } = 8; + + /// Scroll bursts allowed to bring in one more page of data before giving up. + public int BurstsPerPage { get; init; } = 12; + + /// Pages of history per run when the request does not say (Storico, Taggati, Reel). + public int PagesPerRun { get; init; } = 3; + + /// Pages of the following list per run when the request does not say. + public int FollowingPagesPerRun { get; init; } = 5; + + /// Stories are opened only when the budget allows at least this many (spec §6.3: ten). + public int MinStoryBudget { get; init; } = 10; + + /// The backfill stops while the account has more files than this waiting for download (spec §6.3: 60). + public int MaxPendingDownloadsForBackfill { get; init; } = 60; +} + +/// +/// The story timings of spec §7.7, for the «naturale» pace: photos 1.8–5 s; videos 40–100% of their duration, at most +/// 15 s; 1–4 s between one account and the next. Every value is multiplied by mood and pace. +/// +public static class StoryTimings +{ + public static readonly TimeSpan PhotoMin = TimeSpan.FromSeconds(1.8); + public static readonly TimeSpan PhotoMax = TimeSpan.FromSeconds(5); + public static readonly TimeSpan VideoMax = TimeSpan.FromSeconds(15); + public static readonly TimeSpan BetweenAccountsMin = TimeSpan.FromSeconds(1); + public static readonly TimeSpan BetweenAccountsMax = TimeSpan.FromSeconds(4); + + /// How long to watch a story before moving on. + /// Random source. + /// Duration of the video, or null for a photo (or a video of unknown length). + /// Mood × pace. + public static TimeSpan Watch(IRandomSource random, TimeSpan? videoDuration, double multiplier) + { + ArgumentNullException.ThrowIfNull(random); + TimeSpan wait; + if (videoDuration is { } duration && duration > TimeSpan.Zero) + { + var fraction = random.Between(0.4, 1.0); + wait = TimeSpan.FromTicks(Math.Min((long)(duration.Ticks * fraction), VideoMax.Ticks)); + } + else + { + wait = random.Between(PhotoMin, PhotoMax); + } + + return TimeSpan.FromTicks((long)(wait.Ticks * multiplier)); + } + + /// The pause between the stories of one account and those of the next. + public static TimeSpan BetweenAccounts(IRandomSource random, double multiplier) => + TimeSpan.FromTicks((long)(random.Between(BetweenAccountsMin, BetweenAccountsMax).Ticks * multiplier)); +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeRun.cs b/src/Febe.Core/Collection/Recipes/RecipeRun.cs new file mode 100644 index 0000000..14571aa --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeRun.cs @@ -0,0 +1,187 @@ +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; +using Febe.Core.Engine; + +namespace Febe.Core.Collection.Recipes; + +/// Stops a recipe where it is, with a status and an Italian message (internal control flow). +internal sealed class RecipeStopException(RecipeStatus status, string message) : Exception(message) +{ + public RecipeStatus Status { get; } = status; +} + +/// +/// The state of one recipe run: counted actions, new entries, the first stop signal seen, and the helpers every +/// recipe uses (ask the Governor, open a page, click a target, wait for data). Any of them stops the run with a +/// when something says to stop. +/// +internal sealed class RecipeRun : IDisposable +{ + private readonly RecipeRunner _runner; + private readonly IStopSignals _signals; + private Signal? _signal; + + public RecipeRun(RecipeRunner runner, RecipeRequest request, ISessionContext session, CancellationToken ct) + { + _runner = runner; + Request = request; + Session = session; + Ct = ct; + _signals = runner.Env.Signals; + _signals.SignalRaised += OnSignal; + } + + public RecipeRequest Request { get; } + + public ISessionContext Session { get; } + + public CancellationToken Ct { get; } + + public int Actions { get; set; } + + public int NewEntries { get; set; } + + public HashSet AccountsWithStories { get; } = []; + + public HashSet AccountsWithNewPosts { get; } = []; + + public bool Finished { get; set; } + + /// The first stop signal raised since the run started. + public Signal? Signal => Volatile.Read(ref _signal); + + /// Key structures of unrecognized responses seen in the run. + public List UnknownShapes { get; } = []; + + private RecipeEnvironment Env => _runner.Env; + + public void Dispose() => _signals.SignalRaised -= OnSignal; + + public static RecipeStopException Stop(RecipeStatus status, string message) => new(status, message); + + /// Stops the run when a signal was raised or the breaker is open. + public void ThrowIfSignal() + { + if (Signal is { } signal) + { + throw Stop(RecipeStatus.StoppedBySignal, RecipeRunner.Describe(signal)); + } + + if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions) + { + throw Stop(RecipeStatus.StoppedBySignal, breaker.State.LastSignal is { } last ? RecipeRunner.Describe(last) : "L'interruttore è aperto: la ricetta si ferma."); + } + } + + /// Asks the Governor for a counted action; stops in order when refused or when the session is over. + public async Task PermitAsync(ActionKind kind, long? accountId) + { + ThrowIfSignal(); + if (Env.Clock.Now > Session.PlannedEnd) + { + throw Stop(RecipeStatus.Denied, "La sessione è finita: la ricetta riprenderà alla prossima."); + } + + var permit = await Env.Governor.RequestAsync(kind, accountId, Ct).ConfigureAwait(false); + if (!permit.Granted) + { + throw Stop(RecipeStatus.Denied, permit.Message ?? $"Il Governatore non ha concesso l'azione ({permit.Reason})."); + } + + Actions++; + } + + /// Opens a page of the site map and waits after the load like a person (§7.7). + public async Task OpenAsync(string page, IReadOnlyDictionary? values = null) + { + var path = Env.SiteMap.BuildPath(page, values); + var load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false); + ThrowIfSignal(); + if (!load.Succeeded) + { + throw Stop(RecipeStatus.Failed, $"La pagina non si è caricata ({load.Error ?? "errore sconosciuto"})."); + } + + await EnsureOnSiteAsync().ConfigureAwait(false); + await Env.Driver.WaitAfterLoadAsync(Ct).ConfigureAwait(false); + ThrowIfSignal(); + return load; + } + + /// Clicks a target of the map; stops and reports when it cannot be found (never coordinates). + public async Task ClickAsync(string target, IReadOnlyDictionary? parameters = null) + { + ThrowIfSignal(); + var result = await Env.Driver.ClickAsync(target, parameters, Ct).ConfigureAwait(false); + if (!result.Found) + { + ThrowIfSignal(); + throw Stop(RecipeStatus.TargetNotFound, result.Message); + } + + ThrowIfSignal(); + await EnsureOnSiteAsync().ConfigureAwait(false); + } + + /// Read-only lookup of a target. + public Task FindAsync(string target, IReadOnlyDictionary? parameters = null) => + Env.Driver.FindAsync(target, parameters, Ct); + + /// The page must still be on the site: links outside it are never followed (spec §6.1). + public async Task EnsureOnSiteAsync() + { + if (!await Env.Driver.IsOnSiteAsync(Ct).ConfigureAwait(false)) + { + ThrowIfSignal(); + throw Stop(RecipeStatus.Failed, "La pagina ha portato fuori dal sito: la ricetta si ferma e non segue collegamenti esterni."); + } + } + + /// Waits for reads after that satisfy , or for a stop signal. + public async Task> WaitForDataAsync(long mark, Func expected, TimeSpan? timeout = null) + { + var reads = await Env.Capture.WaitAsync( + mark, + r => Signal is not null || r.Any(x => x.Result.Shape == ReadShape.Recognized && expected(x.Result)), + timeout ?? Env.Options.DataTimeout, + Env.Options.Poll, + Ct).ConfigureAwait(false); + ThrowIfSignal(); + return reads; + } + + /// Waits until no data response is on its way any more. + public async Task SettleAsync() + { + await Env.Capture.SettleAsync(Env.Options.SettleQuiet, Env.Options.DataTimeout, Env.Options.Poll, Ct).ConfigureAwait(false); + ThrowIfSignal(); + } + + /// + /// Judges the reads of a step that expected : recognized data resets the empty-page + /// counter; only unknown shapes stop the run with ; nothing at all is + /// an empty page (three in a row raise a throttle signal). Returns true when the expected data arrived. + /// + public bool Judge(IReadOnlyList reads, Func expected, string? where) + { + if (reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result))) + { + _signals.ObserveNonEmptyPage(); + return true; + } + + var unknown = reads.Where(r => r.Result.Shape == ReadShape.Unrecognized && r.Result.KeyStructure is not null).Select(r => r.Result.KeyStructure!).Distinct().ToList(); + if (unknown.Count > 0) + { + UnknownShapes.AddRange(unknown); + throw Stop(RecipeStatus.UnrecognizedFormat, "La risposta del sito ha una forma che i lettori non riconoscono."); + } + + _signals.ObserveEmptyPage(where); + ThrowIfSignal(); + return false; + } + + private void OnSignal(object? sender, Signal signal) => Interlocked.CompareExchange(ref _signal, signal, null); +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Lists.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Lists.cs new file mode 100644 index 0000000..188c7e5 --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Lists.cs @@ -0,0 +1,181 @@ +using System.Globalization; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Recipes; + +public sealed partial class RecipeRunner +{ + /// Setting keys of the following list reading, which may span several sessions (spec §4.2). + public static class FollowingKeys + { + public const string Cursor = "seguiti.cursore"; + public const string StartedAt = "seguiti.inizio"; + public const string Read = "seguiti.letti"; + } + + /// + /// Post singolo (spec §6.3, §6.5 point 5): opens the page of a post (1 counted action) when the grid did not give + /// all its files, or to get a fresh address for a file whose address expired. Never for stories. + /// + private async Task SinglePostAsync(RecipeRun run) + { + if (run.Request.EntryId is not { } entryId) + { + throw RecipeRun.Stop(RecipeStatus.Failed, "«Post singolo» ha bisogno dell'elemento da completare."); + } + + var entry = await Env.Storage.Entries.GetAsync(entryId, run.Ct).ConfigureAwait(false) + ?? throw RecipeRun.Stop(RecipeStatus.Failed, $"Elemento {entryId} non trovato."); + if (entry.Kind is EntryKind.Story or EntryKind.Highlight or EntryKind.ProfilePicture) + { + throw RecipeRun.Stop(RecipeStatus.Completed, "Per storie, raccolte e foto del profilo non c'è una pagina del post: nessun recupero."); + } + + if (entry.State == EntryState.Deleted || entry.Code is null) + { + throw RecipeRun.Stop(RecipeStatus.Completed, entry.Code is null ? "L'elemento non ha un codice: non si può aprire la sua pagina." : "Elemento eliminato: non si riscarica."); + } + + var account = await Env.Storage.Accounts.GetAsync(entry.AccountId, run.Ct).ConfigureAwait(false) + ?? throw RecipeRun.Stop(RecipeStatus.Failed, $"Account {entry.AccountId} non trovato."); + if (account.State == AccountState.ArchiveOnly) + { + throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta."); + } + + await run.PermitAsync(ActionKind.SinglePost, account.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync(SitePages.Post, Values(("code", entry.Code))).ConfigureAwait(false); + bool Matches(Readers.ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code); + var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(Matches)).ConfigureAwait(false); + if (!run.Judge(reads, r => r.Contents.Any(Matches), Env.SiteMap.BuildPath(SitePages.Post, Values(("code", entry.Code))))) + { + throw RecipeRun.Stop(RecipeStatus.Completed, "La pagina del post non ha dato il post: forse non esiste più."); + } + + var item = Contents(reads, Matches).First(); + var changed = await Writer.CompleteAsync(entry, item, account, run.Ct).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.Completed, changed == 0 ? "Post già completo." : $"Post completato: {changed} file da scaricare."); + } + + /// + /// Elenco dei seguiti (spec §4.2, §6.3): reads the list of the profiles Alberto follows, one page per permit, + /// over as many sessions as needed; the progress is stored («Letti 96 profili, continuo alla prossima sessione»). + /// is true when the end of the list was reached. + /// + private async Task FollowingListAsync(RecipeRun run) + { + var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false) + ?? throw RecipeRun.Stop(RecipeStatus.Failed, "Non conosco ancora il profilo collegato: serve prima un giro dei seguiti."); + var settings = Env.Storage.Settings; + var cursor = await settings.GetAsync(FollowingKeys.Cursor, run.Ct).ConfigureAwait(false); + var started = DateTimeOffset.TryParse(await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var s) ? s : (DateTimeOffset?)null; + var read = (int)(await settings.GetInt64Async(FollowingKeys.Read, run.Ct).ConfigureAwait(false) ?? 0); + var resume = cursor is not null && started is not null && Env.SiteMap.HasPage(SitePages.FollowingFrom); + if (!resume) + { + cursor = null; + read = 0; + started = Env.Clock.Now; + } + + var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun); + await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync( + resume ? SitePages.FollowingFrom : SitePages.Following, + resume ? Values(("username", mine.Username), ("cursor", cursor!)) : Values(("username", mine.Username))).ConfigureAwait(false); + var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false); + if (!run.Judge(reads, r => r.Profiles.Count > 0, null)) + { + throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage); + } + + var pages = 1; + var finished = false; + while (true) + { + read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false); + var page = LastPage(reads); + cursor = page?.Cursor ?? cursor; + if (page?.HasMore == false) + { + finished = true; + break; + } + + if (pages >= maxPages) + { + break; + } + + await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false); + reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false); + pages++; + if (reads.Count == 0) + { + break; + } + } + + if (finished) + { + var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started!.Value, run.Ct).ConfigureAwait(false); + await settings.SetManyAsync( + new Dictionary { [FollowingKeys.Cursor] = null, [FollowingKeys.StartedAt] = null, [FollowingKeys.Read] = null }, + run.Ct).ConfigureAwait(false); + run.Finished = true; + var message = $"Elenco dei seguiti letto: {ItalianText.Number(read)} profili" + (removed > 0 ? $", {ItalianText.Number(removed)} non più seguiti." : "."); + await Writer.EventAsync("seguiti-letti", message, EventSeverity.Success, null, run.Session.SessionId, run.Ct).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.Completed, message); + } + + await settings.SetManyAsync( + new Dictionary + { + [FollowingKeys.Cursor] = cursor, + [FollowingKeys.StartedAt] = started!.Value.ToString("O", CultureInfo.InvariantCulture), + [FollowingKeys.Read] = read.ToString(CultureInfo.InvariantCulture), + }, + run.Ct).ConfigureAwait(false); + var progress = $"Letti {ItalianText.Number(read)} profili, continuo alla prossima sessione"; + await Writer.EventAsync("seguiti-parziale", progress, EventSeverity.Info, null, run.Session.SessionId, run.Ct).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.Completed, progress); + } + + /// Stores one page of the following list in reading order; renamed followed accounts are recognized. + private async Task SaveFollowingPageAsync(RecipeRun run, IReadOnlyList reads, Account mine, int offset) + { + var now = Env.Clock.Now; + var seen = new HashSet(StringComparer.Ordinal); + var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => !p.IsViewer && p.Id != mine.InstagramId && seen.Add(p.Id)).ToList(); + var records = new List(profiles.Count); + for (var i = 0; i < profiles.Count; i++) + { + var p = profiles[i]; + records.Add(new FollowingRecord + { + InstagramId = p.Id, + Username = p.Username, + DisplayName = p.DisplayName, + IsPrivate = p.IsPrivate, + Position = offset + i, + ReadAt = now, + }); + if (await Writer.ObserveProfileAsync(p with { IsFollowed = true }, run.Session.SessionId, run.Ct).ConfigureAwait(false) is { IsFollowed: false } account) + { + await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { IsFollowed = true }, run.Ct).ConfigureAwait(false); + } + } + + if (records.Count > 0) + { + await Env.Storage.Following.UpsertAsync(records, run.Ct).ConfigureAwait(false); + } + + return records.Count; + } +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs new file mode 100644 index 0000000..1f44ecb --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -0,0 +1,401 @@ +using System.Globalization; +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; +using Febe.Core.Engine; + +namespace Febe.Core.Collection.Recipes; + +public sealed partial class RecipeRunner +{ + /// A walk through the pages of a profile tab (Storico on the grid, Taggati, Reel). + private sealed record ProfileWalk(EntryKind Kind, string? TabTarget, string ResumePage, string SettingPrefix) + { + public static readonly ProfileWalk Posts = new(EntryKind.Post, null, SitePages.ProfileFrom, "raccolta.post"); + public static readonly ProfileWalk Tagged = new(EntryKind.Tagged, SiteTargets.ProfileTabTagged, SitePages.TaggedFrom, "raccolta.taggati"); + public static readonly ProfileWalk Reels = new(EntryKind.Post, SiteTargets.ProfileTabReels, SitePages.ReelsFrom, "raccolta.reel"); + + public bool IsGrid => TabTarget is null; + + public string CursorKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.cursore"; + + public string CompletedKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.completo"; + } + + /// + /// Controllo del profilo (spec §6.3): opens the profile (1 counted action), reads its state, the first page of + /// posts and the list of highlight collections, keeps a copy of the profile picture when it changes, and stops at + /// known content. Pinned posts are recognized and skipped for the stop rule. + /// + private async Task ProfileCheckAsync(RecipeRun run) + { + var account = await LoadAccountAsync(run).ConfigureAwait(false); + var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false); + account = current; + var profile = FindProfile(reads, account)!; + + if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue) + && account.ContentTypes.HasFlag(ContentTypes.Stories)) + { + run.AccountsWithStories.Add(account.Id); + } + + var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList(); + await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false); + + if ((await Writer.SaveProfilePictureAsync(account, profile, run.Ct).ConfigureAwait(false)).Outcome == SaveOutcome.Created) + { + run.NewEntries++; + } + + var reachedKnown = false; + foreach (var item in Contents(reads, c => IsOwnedBy(c, account))) + { + var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false); + if (saved.Outcome == SaveOutcome.Created) + { + run.NewEntries++; + run.AccountsWithNewPosts.Add(account.Id); + } + else if (saved.Outcome == SaveOutcome.Known && !item.Pinned) + { + reachedKnown = true; // pinned posts are known but do not stop the check + break; + } + } + + var page = LastPage(reads); + if (!reachedKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null) + { + if (page?.HasMore == true && page.Cursor is { } cursor) + { + await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false); + } + else if (page?.HasMore == false) + { + await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); + } + } + + await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false); + return RecipeStatus.Completed; + } + + /// + /// Storico, Taggati and Reel (spec §6.3): one page per permit, resuming from the stored point and stopping at the + /// beginning of the profile. The backfill stops while the account has more than 60 files waiting for download or + /// the data budget is used up (the engine checks too, the recipe must stop as well). Once a tab has been walked to + /// the end, later runs only check its first page and stop at known content. + /// + private async Task WalkAsync(RecipeRun run, ProfileWalk walk) + { + var account = await LoadAccountAsync(run).ConfigureAwait(false); + if (!CollectionWriter.Wants(account, walk.Kind)) + { + throw RecipeRun.Stop(RecipeStatus.Completed, walk.Kind == EntryKind.Tagged + ? $"«Post in cui è taggato» è spento per {account.Username}." + : $"Foto e video dei post sono spenti per {account.Username}."); + } + + var settings = Env.Storage.Settings; + string? cursor; + bool checkOnly; + if (walk.IsGrid) + { + if (account.BackfillCompletedAt is not null) + { + run.Finished = true; + return RecipeStatus.Completed; + } + + cursor = account.BackfillCursor; + checkOnly = false; + } + else + { + cursor = await settings.GetAsync(walk.CursorKey(account.Id), run.Ct).ConfigureAwait(false); + checkOnly = await settings.GetAsync(walk.CompletedKey(account.Id), run.Ct).ConfigureAwait(false) is not null; + if (checkOnly) + { + cursor = null; + } + } + + if (!checkOnly) + { + await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false); + } + + var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun); + var parameters = Values(("username", account.Username)); + IReadOnlyList reads; + var pages = 0; + if (cursor is not null && Env.SiteMap.HasPage(walk.ResumePage)) + { + // Resume where the last run stopped: the page of the site that starts after the stored point. + await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", cursor))).ConfigureAwait(false); + reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false); + if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters))) + { + throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage); + } + + pages++; + } + else + { + (account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false); + if (walk.TabTarget is { } tab) + { + await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.ClickAsync(tab, parameters).ConfigureAwait(false); + await Env.Driver.WaitAfterLoadAsync(run.Ct).ConfigureAwait(false); + reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false); + if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, null)) + { + throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage); + } + + pages++; + } + } + + var finished = false; + var processed = new HashSet(StringComparer.Ordinal); + while (true) + { + var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, reads, processed, stopAtKnown: checkOnly).ConfigureAwait(false); + var page = LastPage(reads); + if (reachedLimit || page?.HasMore == false) + { + finished = !checkOnly || page?.HasMore == false; + break; + } + + if (checkOnly && reachedKnown) + { + break; + } + + cursor = page?.Cursor ?? cursor; + await StoreWalkCursorAsync(run, account, walk, cursor).ConfigureAwait(false); + if (pages >= maxPages) + { + break; + } + + if (!checkOnly) + { + await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false); + } + + await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false); + reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false); + pages++; + if (reads.Count == 0) + { + break; // nothing came in after the bursts (counted as an empty page) + } + } + + if (finished) + { + run.Finished = true; + if (walk.IsGrid) + { + await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); + await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); + } + else + { + await settings.SetManyAsync( + new Dictionary + { + [walk.CursorKey(account.Id)] = null, + [walk.CompletedKey(account.Id)] = Env.Clock.Now.ToString("O", CultureInfo.InvariantCulture), + }, + run.Ct).ConfigureAwait(false); + } + } + + return RecipeStatus.Completed; + } + + /// + /// Saves the new items of a walk page. Returns whether known content was met (only meaningful when + /// ) and whether a history limit of the account was reached (from a date, last N posts). + /// + private async Task<(bool ReachedKnown, bool ReachedLimit)> SaveWalkPageAsync(RecipeRun run, Account account, ProfileWalk walk, IReadOnlyList reads, HashSet processed, bool stopAtKnown) + { + var items = Contents(reads, c => walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account)) + .Where(c => processed.Add(c.Id)) + .ToList(); + foreach (var item in items) + { + if (walk.Kind != EntryKind.Tagged && !item.Pinned) + { + if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from) + { + return (false, true); + } + + if (account.Limits.Depth == HistoryDepth.LastPosts && account.Limits.LastPosts is { } last + && await Env.Storage.Entries.ListByAccountAsync(account.Id, new Storage.EntryListOptions { Kind = EntryKind.Post, Limit = last }, run.Ct).ConfigureAwait(false) is { } kept + && kept.Count >= last) + { + return (false, true); + } + } + + var saved = await Writer.SaveAsync(account, item, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false); + if (saved.Outcome == SaveOutcome.Created) + { + run.NewEntries++; + run.AccountsWithNewPosts.Add(account.Id); + } + else if (stopAtKnown && saved.Outcome == SaveOutcome.Known && !item.Pinned) + { + return (true, false); + } + } + + return (false, false); + } + + private async Task StoreWalkCursorAsync(RecipeRun run, Account account, ProfileWalk walk, string? cursor) + { + if (cursor is null) + { + return; + } + + if (walk.IsGrid) + { + await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false); + } + else + { + await Env.Storage.Settings.SetAsync(walk.CursorKey(account.Id), cursor, run.Ct).ConfigureAwait(false); + } + } + + /// + /// «Lo storico non corre più veloce dei download» (spec §6.3): stops while the account has more than 60 files waiting + /// or the data budget is used up. + /// + private async Task EnsureBackfillAllowedAsync(RecipeRun run, Account account) + { + var pending = await Env.Storage.Media.CountPendingDownloadsAsync(account.Id, run.Ct).ConfigureAwait(false); + if (pending > Env.Options.MaxPendingDownloadsForBackfill) + { + await Writer.EventAsync("storico-sospeso", $"Storico di {account.Username} sospeso: {ItalianText.Number(pending)} file aspettano di essere scaricati.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.Denied, $"Storico sospeso: {ItalianText.Number(pending)} file di {account.Username} aspettano di essere scaricati (più di {Env.Options.MaxPendingDownloadsForBackfill})."); + } + + if (Env.DataBudget is { } budget && await budget.RemainingTodayAsync(run.Ct).ConfigureAwait(false) <= 0) + { + throw RecipeRun.Stop(RecipeStatus.Denied, "Storico sospeso: il tetto giornaliero dei dati scaricati è raggiunto."); + } + } + + /// + /// Opens the profile page (1 counted action) and reads its state: missing profile, a name now used by another + /// account, private profile not followed (rule 6: not touched). Returns the updated account and the reads. + /// + private async Task<(Account Account, IReadOnlyList Reads)> OpenProfileAsync(RecipeRun run, Account account) + { + var parameters = Values(("username", account.Username)); + await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false); + if ((await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found) + { + await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile."); + } + + var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false); + if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters))) + { + throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage); + } + + var profile = FindProfile(reads, account)!; + if (account.InstagramId is { } known && profile.Id != known) + { + await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il nome {account.Username} ora appartiene a un altro profilo: l'account resta com'era."); + } + + account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false); + if (profile.IsPrivate == true && profile.IsFollowed == false) + { + await MarkUnreachableAsync(run, account, UnreachableReason.PrivateNotFollowed).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"{account.Username} è un profilo privato che non segui: non si tocca."); + } + + if (account.State == AccountState.Unreachable) + { + var state = account.BackfillCursor is not null && account.BackfillCompletedAt is null ? AccountState.Backfilling : AccountState.UpToDate; + await Env.Storage.Accounts.SetStateAsync(account.Id, state, Env.Clock.Now, null, run.Ct).ConfigureAwait(false); + await Writer.EventAsync("account-raggiungibile", $"{account.Username} è di nuovo raggiungibile.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); + account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account; + } + + return (account, reads); + } + + /// + /// Scrolls with bursts until a new page of data that satisfies arrives, at most + /// bursts. Returns the reads of that page (empty when none came). + /// + private async Task> ScrollForPageAsync(RecipeRun run, Func expected) + { + var mark = Env.Capture.Mark(); + for (var burst = 0; burst < Env.Options.BurstsPerPage; burst++) + { + await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false); + run.ThrowIfSignal(); + if (Env.Capture.Pending > 0 || Env.Capture.Since(mark).Count > 0) + { + await run.SettleAsync().ConfigureAwait(false); + } + + var reads = Env.Capture.Since(mark); + if (reads.Any(r => r.Result.Shape != ReadShape.Recognized || expected(r.Result))) + { + return run.Judge(reads, expected, null) + ? reads.Where(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)).ToList() + : []; + } + } + + run.Judge([], expected, null); + return []; + } + + /// Outcome message of a page that arrived without data (three in a row raise a throttle signal). + private const string EmptyPageMessage = "La pagina è arrivata vuota: nessun dato da leggere."; + + private static PageInfo? LastPage(IEnumerable reads) => + reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault(); +} + +/// Italian formatting for messages: thousands with a dot (spec: «48.212 elementi»). +public static class ItalianText +{ + public static string Number(long value) + { + var digits = Math.Abs(value).ToString(CultureInfo.InvariantCulture); + var groups = new List(); + for (var end = digits.Length; end > 0; end -= 3) + { + groups.Insert(0, digits[Math.Max(0, end - 3)..end]); + } + + return (value < 0 ? "-" : string.Empty) + string.Join('.', groups); + } +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Sweep.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Sweep.cs new file mode 100644 index 0000000..3d3a994 --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Sweep.cs @@ -0,0 +1,126 @@ +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; +using Febe.Core.Engine; + +namespace Febe.Core.Collection.Recipes; + +public sealed partial class RecipeRunner +{ + /// + /// Giro dei seguiti (spec §6.3): opens the home (1 counted action), reads the stories bar, and scrolls the recent + /// posts of followed profiles until it meets known content, with at most 8 bursts. Posts that arrive with complete + /// data are saved at once; incomplete series are saved with what arrived and completed by «Post singolo». + /// + private async Task FollowingSweepAsync(RecipeRun run) + { + await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync(SitePages.Home).ConfigureAwait(false); + var reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Profiles.Count > 0).ConfigureAwait(false); + run.Judge(reads, r => r.Contents.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Home)); + + var processed = 0; + var sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false); + var hasMore = reads.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? true; + + for (var burst = 0; burst < Env.Options.SweepMaxBursts && !sawKnown && hasMore; burst++) + { + var before = Env.Capture.Mark(); + await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false); + run.ThrowIfSignal(); + await run.SettleAsync().ConfigureAwait(false); + var more = Env.Capture.Since(before); + if (more.Count == 0) + { + continue; + } + + reads = [.. reads, .. more]; + sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false); + hasMore = more.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? hasMore; + } + + await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false); + return RecipeStatus.Completed; + } + + /// Saves the posts not processed yet; returns true once known content has been met. + private Task ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList reads, ref int processed) + { + var items = Contents(reads); + var fresh = items.Skip(processed).ToList(); + processed = items.Count; + return ProcessSweepItemsAsync(run, reads, fresh); + } + + private async Task ProcessSweepItemsAsync(RecipeRun run, IReadOnlyList reads, IReadOnlyList items) + { + await EnsureMineAsync(reads, run).ConfigureAwait(false); + + // Stories bar (H2): followed accounts whose latest story is newer than their last stories check. + foreach (var profile in reads.SelectMany(r => r.Result.Profiles).Where(p => p.LatestStoryAt is not null)) + { + var account = await Writer.ObserveProfileAsync(profile, run.Session.SessionId, run.Ct).ConfigureAwait(false); + if (account is { State: not (AccountState.ArchiveOnly or AccountState.Unreachable) } + && account.ContentTypes.HasFlag(ContentTypes.Stories) + && profile.LatestStoryAt > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)) + { + run.AccountsWithStories.Add(account.Id); + } + } + + var sawKnown = false; + foreach (var item in items) + { + if (item.Owner is null) + { + continue; + } + + var account = await Writer.ObserveProfileAsync(item.Owner, run.Session.SessionId, run.Ct).ConfigureAwait(false); + if (account is null || account.State is AccountState.ArchiveOnly or AccountState.Unreachable || account.Id == 0) + { + continue; // not an account Febe keeps + } + + var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false); + switch (saved.Outcome) + { + case SaveOutcome.Created: + run.NewEntries++; + run.AccountsWithNewPosts.Add(account.Id); + break; + case SaveOutcome.Known when !item.Pinned: + sawKnown = true; + break; + } + } + + return sawKnown; + } + + /// + /// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen. + /// + private async Task EnsureMineAsync(IReadOnlyList reads, RecipeRun run) + { + if (reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null) is not { } viewer) + { + return; + } + + var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false); + if (mine is not null || await Env.Storage.Accounts.FindByInstagramIdAsync(viewer.Id, run.Ct).ConfigureAwait(false) is not null) + { + return; + } + + var account = Account.Create(viewer.Username, StartingPoint.EverythingAndKeepUpdated, Env.Clock.Now, Env.Clock.LocalZone, isMine: true) with + { + InstagramId = viewer.Id, + }; + await Env.Storage.Accounts.AddAsync(account, run.Ct).ConfigureAwait(false); + await Writer.EventAsync("account-collegato", $"Account collegato riconosciuto dai dati della pagina: {viewer.Username} («Tu»).", EventSeverity.Info, null, run.Session.SessionId, run.Ct).ConfigureAwait(false); + } +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Viewer.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Viewer.cs new file mode 100644 index 0000000..a275175 --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Viewer.cs @@ -0,0 +1,425 @@ +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Recipes; + +public sealed partial class RecipeRunner +{ + /// + /// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the + /// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of + /// §7.7 (one StoryView permit per story shown) and saves only the stories actually shown. After the last story it + /// closes the viewer before it moves on by itself; a story of another account is not saved: the viewer is closed + /// and the event recorded. + /// + private async Task AccountStoriesAsync(RecipeRun run) + { + var account = await LoadAccountAsync(run).ConfigureAwait(false); + if (!CollectionWriter.Wants(account, EntryKind.Story)) + { + throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie» è spento per {account.Username}."); + } + + await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false); + if (_lastKind == RecipeKind.AccountStories) + { + await Env.Driver.WaitAsync(StoryTimings.BetweenAccounts(Env.Random, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false); + } + + var parameters = Values(("username", account.Username)); + var fromBar = Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory) + && Env.SiteMap.Match(SitePages.Home, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is not null + && (await run.FindAsync(SiteTargets.HomeStory, parameters).ConfigureAwait(false)).Found; + + if (!fromBar) + { + await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false); + var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false); + if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters))) + { + throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage); + } + + var profile = FindProfile(reads, account)!; + account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false); + if (profile.IsPrivate == true && profile.IsFollowed == false) + { + await MarkUnreachableAsync(run, account, UnreachableReason.PrivateNotFollowed).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"{account.Username} è un profilo privato che non segui: non si tocca."); + } + + if (!(await run.FindAsync(SiteTargets.ProfileStoryRing, parameters).ConfigureAwait(false)).Found) + { + await StoriesCheckedAsync(account, run).ConfigureAwait(false); + return RecipeStatus.Completed; // no active stories: nothing to open + } + } + + var target = fromBar ? SiteTargets.HomeStory : SiteTargets.ProfileStoryRing; + await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false); + var viewerMark = Env.Capture.Mark(); + var opened = await OpenViewerAsync(run, target, parameters, SitePages.StoryViewer).ConfigureAwait(false); + var watched = await WatchViewerAsync(run, SitePages.StoryViewer, "username", account.Username, account, viewerMark, opened).ConfigureAwait(false); + var shown = watched.Shown; + + var stories = Contents(Env.Capture.Since(viewerMark), c => IsOwnedBy(c, account)); + foreach (var id in shown) + { + if (stories.FirstOrDefault(s => s.Id == id) is { } story) + { + var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, run.Ct).ConfigureAwait(false); + if (saved.Outcome == SaveOutcome.Created) + { + run.NewEntries++; + } + } + } + + await StoriesCheckedAsync(account, run).ConfigureAwait(false); + if (watched.Stop is { } stop) + { + throw stop; + } + + return RecipeStatus.Completed; + } + + /// + /// Raccolta in evidenza (spec §6.3): opens the profile and the collection, watches its contents one by one (one + /// StoryView permit per content shown) and closes the viewer after the last one. A content that is a story already + /// saved is referenced, not downloaded again (H9). + /// + private async Task HighlightAsync(RecipeRun run) + { + var account = await LoadAccountAsync(run).ConfigureAwait(false); + if (run.Request.HighlightId is not { Length: > 0 } highlightId) + { + throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta."); + } + + if (!CollectionWriter.Wants(account, EntryKind.Highlight)) + { + throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}."); + } + + await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false); + var parameters = Values(("username", account.Username)); + await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false); + var mark = Env.Capture.Mark(); + await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false); + var reads = await run.WaitForDataAsync(mark, r => r.Highlights.Count > 0 || ProfileIn(r, account) is not null).ConfigureAwait(false); + if (!run.Judge(reads, r => r.Highlights.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Profile, parameters))) + { + throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage); + } + if (FindProfile(reads, account) is { } profile) + { + account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false); + } + + var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList(); + var collections = await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false); + if (!collections.TryGetValue(highlightId, out var highlight)) + { + var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false); + throw RecipeRun.Stop(RecipeStatus.Completed, known is null + ? "La raccolta non è nel profilo." + : $"La raccolta «{known.Title}» non è più nel profilo: i suoi file restano."); + } + + await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false); + var viewerMark = Env.Capture.Mark(); + var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, Values(("id", highlightId), ("username", account.Username)), SitePages.HighlightViewer).ConfigureAwait(false); + var watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false); + var shown = watched.Shown; + + var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId); + var ordered = new List(); + foreach (var id in shown) + { + if (items.FirstOrDefault(i => i.Id == id) is not { } item) + { + continue; + } + + var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false); + if (created) + { + run.NewEntries++; + } + + if (entry is not null) + { + ordered.Add(entry.Id); + } + } + + if (items.Count > 0 && items.All(i => shown.Contains(i.Id)) && ordered.Count == items.Count) + { + await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, run.Ct).ConfigureAwait(false); + } + + await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false); + if (watched.Stop is { } stop) + { + throw stop; + } + + return RecipeStatus.Completed; + } + + private async Task EnsureStoryBudgetAsync(RecipeRun run, Account account) + { + if (Env.Budget is { } budget) + { + var left = await budget.RemainingAsync(ActionKind.StoryView, account.Id, run.Ct).ConfigureAwait(false); + if (left < Env.Options.MinStoryBudget) + { + throw RecipeRun.Stop(RecipeStatus.Denied, $"Il tetto delle storie ne consente ancora {left}: ne servono almeno {Env.Options.MinStoryBudget} per aprirle."); + } + } + } + + /// Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed. + private async Task> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary parameters, string viewerPage) + { + for (var attempt = 0; attempt < 2; attempt++) + { + await run.ClickAsync(target, parameters).ConfigureAwait(false); + if (await WaitForViewerAsync(run, viewerPage, previous: null).ConfigureAwait(false) is { } opened) + { + return opened; + } + + if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found) + { + break; + } + } + + throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non si è aperto dopo il clic."); + } + + /// + /// Watches a viewer that shows : reads the item shown from the address of the page, waits + /// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by + /// itself) and closes the viewer after the last item of , or as soon as it shows something + /// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order. + /// + private async Task WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary opened) + { + var shown = new List(); + var counted = new HashSet(StringComparer.Ordinal); + var pendingPermit = true; // asked before the click that opened the viewer + var position = opened; + var stuck = 0; + try + { + while (true) + { + run.ThrowIfSignal(); + if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase)) + { + await CloseViewerAsync(run, viewerPage).ConfigureAwait(false); + await Writer.EventAsync( + "visualizzatore-altro-account", + viewerPage == SitePages.StoryViewer + ? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano." + : $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.", + EventSeverity.Warning, + account.Id, + run.Session.SessionId, + run.Ct).ConfigureAwait(false); + return new ViewerResult(shown, null); + } + + var id = position["id"]; + if (counted.Add(id)) + { + if (!pendingPermit) + { + // The viewer moved on by itself: this item was shown without asking first; ask now. + await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false); + } + + pendingPermit = false; + shown.Add(id); + } + + // The list of the account arrives with the viewer (H4): it tells which item is the last one. + var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false); + var item = list.FirstOrDefault(i => i.Id == id); + var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration; + await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false); + run.ThrowIfSignal(); + + var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)); + if (current is null) + { + return new ViewerResult(shown, null); // the viewer closed by itself + } + + if (!SamePosition(current, position)) + { + position = current; // it moved on by itself while we watched + continue; + } + + var index = list.FindIndex(i => i.Id == id); + if (list.Count > 0 && index == list.Count - 1) + { + await CloseViewerAsync(run, viewerPage).ConfigureAwait(false); + return new ViewerResult(shown, null); + } + + if (!pendingPermit) + { + await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false); + pendingPermit = true; + } + + await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false); + var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false); + if (next is null) + { + return new ViewerResult(shown, null); // closed after the last item + } + + if (SamePosition(next, current)) + { + if (++stuck >= 2) + { + throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti."); + } + + continue; // the click went unnoticed: watch a little more and try again + } + + stuck = 0; + position = next; + } + } + catch (RecipeStopException stop) + { + if (stop.Status != RecipeStatus.StoppedBySignal) + { + // Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is. + try + { + await CloseViewerAsync(run, viewerPage).ConfigureAwait(false); + } + catch (RecipeStopException) + { + } + } + + return new ViewerResult(shown, stop); + } + } + + /// What a viewer showed, and why it stopped early (the caller saves what was shown, then stops). + private sealed record ViewerResult(List Shown, RecipeStopException? Stop); + + private static bool SamePosition(IReadOnlyDictionary a, IReadOnlyDictionary b) => + a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase)); + + /// The items of the viewer for the owner, as received (waits for them the first time). + private async Task> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account) + { + Func belongs = viewerPage == SitePages.StoryViewer + ? c => IsOwnedBy(c, account) + : c => c.HighlightId == owner; + var present = Contents(Env.Capture.Since(mark), belongs); + if (present.Count > 0) + { + return present; + } + + var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false); + run.Judge(reads, r => r.Contents.Any(belongs), null); + return Contents(reads, belongs); + } + + /// Waits until the address shows a viewer item different from ; null when the viewer is gone. + private async Task?> WaitForViewerAsync(RecipeRun run, string viewerPage, IReadOnlyDictionary? previous) + { + var deadline = Env.Clock.Now + Env.Options.ViewerTimeout; + while (true) + { + run.ThrowIfSignal(); + var match = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)); + if (match is not null && (previous is null || !SamePosition(match, previous))) + { + return match; + } + + if (previous is not null && match is null) + { + return null; + } + + if (Env.Clock.Now >= deadline) + { + return previous is null ? null : match; + } + + await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false); + } + } + + /// Closes the viewer with its command and waits until it is gone. + private async Task CloseViewerAsync(RecipeRun run, string viewerPage) + { + if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null) + { + return; + } + + var click = await Env.Driver.ClickAsync(SiteTargets.ViewerClose, null, run.Ct).ConfigureAwait(false); + if (!click.Found) + { + run.ThrowIfSignal(); + throw RecipeRun.Stop(RecipeStatus.TargetNotFound, click.Message); + } + + var deadline = Env.Clock.Now + Env.Options.ViewerTimeout; + while (Env.Clock.Now < deadline) + { + if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null) + { + return; + } + + await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false); + } + } + + private async Task StoriesCheckedAsync(Account account, RecipeRun run) => + await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false); + + private async Task MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason) + { + if (account.State == AccountState.Unreachable && account.UnreachableReason == reason) + { + return; + } + + await Env.Storage.Accounts.SetStateAsync(account.Id, AccountState.Unreachable, Env.Clock.Now, reason, run.Ct).ConfigureAwait(false); + var why = reason switch + { + UnreachableReason.PrivateNotFollowed => "è un profilo privato che non segui", + UnreachableReason.NotFound => "il profilo non esiste più", + UnreachableReason.Renamed => "il nome ora appartiene a un altro profilo", + _ => "non è raggiungibile", + }; + await Writer.EventAsync("account-non-raggiungibile", $"{account.Username} non è raggiungibile: {why}.", EventSeverity.Warning, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false); + } + + private static ProfileInfo? ProfileIn(ReadResult result, Account account) => + result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase)); +} diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.cs new file mode 100644 index 0000000..1644423 --- /dev/null +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.cs @@ -0,0 +1,292 @@ +using Febe.Core.Abstractions; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; + +namespace Febe.Core.Collection.Recipes; + +/// Everything the recipes work with. +public sealed record RecipeEnvironment +{ + /// The page, through the browser (or a fake in tests and simulation). + public required IPageDriver Driver { get; init; } + + /// What the page receives, read by the site's readers. + public required CaptureCollector Capture { get; init; } + + /// The single point every counted action passes through (rule 7). + public required IGovernor Governor { get; init; } + + /// Stop signals: raised by the capture, reported by the recipes (empty pages, session cookie). + public required IStopSignals Signals { get; init; } + + public required IFebeStorage Storage { get; init; } + + /// Pages and targets of the site (bersagli.*.json). + public required SiteMap SiteMap { get; init; } + + public required IClock Clock { get; init; } + + public required IRandomSource Random { get; init; } + + /// Remaining budgets (stories need at least ten). Null: the check is left to the Governor alone. + public IBudgetView? Budget { get; init; } + + /// Daily data budget: the backfill stops when it is used up (spec §6.3). Null: not checked here. + public IDataBudget? DataBudget { get; init; } + + /// The circuit breaker, to stop when it opens. Null: only the signals of the run count. + public ICircuitBreaker? Breaker { get; init; } + + public RecipeOptions Options { get; init; } = new(); +} + +/// +/// The recipes of spec §6.3 over a page driver: Giro dei seguiti, Storie di un account, Controllo del profilo, Storico, +/// Raccolta in evidenza, Taggati, Reel, Post singolo, Elenco dei seguiti. +/// +/// +/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop +/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with +/// coordinates; an unknown response shape stops it with and an event +/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a +/// skeleton (the first Instagram files, to be filled after M0). +/// +public sealed partial class RecipeRunner : IRecipeRunner +{ + private long? _sessionId; + private RecipeKind? _lastKind; + + public RecipeRunner(RecipeEnvironment environment) + { + Env = environment ?? throw new ArgumentNullException(nameof(environment)); + Writer = new CollectionWriter(environment.Storage, environment.Clock); + } + + public RecipeEnvironment Env { get; } + + public CollectionWriter Writer { get; } + + /// Italian name of a recipe, for messages and events. + public static string Name(RecipeKind kind) => kind switch + { + RecipeKind.FollowingSweep => "Giro dei seguiti", + RecipeKind.AccountStories => "Storie di un account", + RecipeKind.ProfileCheck => "Controllo del profilo", + RecipeKind.Backfill => "Storico", + RecipeKind.Highlight => "Raccolta in evidenza", + RecipeKind.Tagged => "Taggati", + RecipeKind.Reels => "Reel", + RecipeKind.SinglePost => "Post singolo", + RecipeKind.FollowingList => "Elenco dei seguiti", + _ => kind.ToString(), + }; + + /// Pages and targets a recipe cannot work without. + public static (IReadOnlyList Pages, IReadOnlyList Targets) Requirements(RecipeKind kind) => kind switch + { + RecipeKind.FollowingSweep => ([SitePages.Home], []), + RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]), + RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]), + RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]), + RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]), + RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]), + RecipeKind.SinglePost => ([SitePages.Post], []), + RecipeKind.FollowingList => ([SitePages.Following], []), + _ => ([], []), + }; + + /// Italian description of a stop signal. + public static string Describe(Signal signal) => signal.Level switch + { + SignalLevel.Throttle => $"Segnale di rallentamento ({signal.Code}): la ricetta si ferma dov'è.", + SignalLevel.Challenge => $"Il sito chiede una verifica ({signal.Code}): Febe si ferma e lascia la pagina com'è.", + SignalLevel.Disconnect => $"La sessione è terminata ({signal.Code}): Febe si ferma e non tenta di rientrare.", + _ => $"Segnale {signal.Code}.", + }; + + public async Task RunAsync(RecipeRequest request, ISessionContext session, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(session); + var name = Name(request.Kind); + + var (pages, targets) = Requirements(request.Kind); + var missing = Env.SiteMap.Missing(pages, targets); + if (missing.Count > 0) + { + var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11)."; + await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false); + return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message); + } + + if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable) + { + var message = $"«{name}» non può girare: {unusable}"; + await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false); + return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message); + } + + if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions) + { + return new RecipeOutcome(RecipeStatus.Denied, 0, 0, "L'interruttore è aperto: nessuna azione verso il sito."); + } + + if (_sessionId != session.SessionId) + { + Env.Driver.BeginSession(session.Mood); + _sessionId = session.SessionId; + _lastKind = null; + } + + using var run = new RecipeRun(this, request, session, ct); + RecipeStatus status; + string? text = null; + try + { + await CheckSessionCookieAsync(run).ConfigureAwait(false); + status = request.Kind switch + { + RecipeKind.FollowingSweep => await FollowingSweepAsync(run).ConfigureAwait(false), + RecipeKind.AccountStories => await AccountStoriesAsync(run).ConfigureAwait(false), + RecipeKind.ProfileCheck => await ProfileCheckAsync(run).ConfigureAwait(false), + RecipeKind.Backfill => await WalkAsync(run, ProfileWalk.Posts).ConfigureAwait(false), + RecipeKind.Tagged => await WalkAsync(run, ProfileWalk.Tagged).ConfigureAwait(false), + RecipeKind.Reels => await WalkAsync(run, ProfileWalk.Reels).ConfigureAwait(false), + RecipeKind.Highlight => await HighlightAsync(run).ConfigureAwait(false), + RecipeKind.SinglePost => await SinglePostAsync(run).ConfigureAwait(false), + RecipeKind.FollowingList => await FollowingListAsync(run).ConfigureAwait(false), + _ => throw RecipeRun.Stop(RecipeStatus.Failed, $"Ricetta sconosciuta: {request.Kind}."), + }; + } + catch (RecipeStopException stop) + { + status = stop.Status; + text = stop.Message; + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + status = RecipeStatus.Cancelled; + text = "Ricetta interrotta."; + } + catch (OperationCanceledException ex) + { + // E.g. Alberto took the browser: the gesture was not performed. + status = RecipeStatus.Cancelled; + text = ex.Message; + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + status = RecipeStatus.Failed; + text = $"Errore imprevisto in «{name}» ({ex.GetType().Name}): {ex.Message}"; + } + + if (run.Signal is { } signal && status is not (RecipeStatus.StoppedBySignal or RecipeStatus.Cancelled)) + { + status = RecipeStatus.StoppedBySignal; + text = Describe(signal); + } + + try + { + await ReportAsync(run, status, text, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException) + { + // The timeline is a convenience: failing to write it never changes how the recipe ended. + } + + _lastKind = request.Kind; + return new RecipeOutcome(status, run.Actions, run.NewEntries, text) + { + AccountsWithStories = [.. run.AccountsWithStories], + AccountsWithNewPosts = [.. run.AccountsWithNewPosts], + BackfillFinished = run.Finished, + }; + } + + /// + /// The rest page (spec §6.1). After a verification request or a disconnection the page is left as it is, so that + /// Alberto sees what happened (spec §7.6): resting is skipped while the breaker says so. + /// + public Task RestAsync(CancellationToken ct) + { + if (Env.Breaker?.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected) + { + return Task.CompletedTask; + } + + return Env.Driver.RestAsync(ct); + } + + private async Task CheckSessionCookieAsync(RecipeRun run) + { + if (await Env.Driver.HasSessionCookieAsync(run.Ct).ConfigureAwait(false) is false) + { + Env.Signals.ObserveSessionCookie(false); + run.ThrowIfSignal(); + } + } + + private async Task ReportAsync(RecipeRun run, RecipeStatus status, string? text, CancellationToken ct) + { + var name = Name(run.Request.Kind); + var accountId = run.Request.AccountId; + switch (status) + { + case RecipeStatus.UnrecognizedFormat: + var shapes = run.UnknownShapes.Count == 0 ? "(nessuna struttura)" : string.Join(" · ", run.UnknownShapes.Take(3)); + await Writer.EventAsync("formato-non-riconosciuto", $"Formato non riconosciuto in «{name}». Struttura delle chiavi: {shapes}", EventSeverity.Warning, accountId, run.Session.SessionId, ct).ConfigureAwait(false); + if (accountId is { } id) + { + await Env.Storage.Accounts.AddNoticesAsync(id, AccountNotices.UnrecognizedFormat, Env.Clock.Now, ct).ConfigureAwait(false); + } + + break; + case RecipeStatus.TargetNotFound: + await Writer.EventAsync("bersaglio-non-trovato", $"«{name}» si è fermata: {text}", EventSeverity.Error, accountId, run.Session.SessionId, ct).ConfigureAwait(false); + break; + case RecipeStatus.Failed: + await Writer.EventAsync("ricetta-fallita", text ?? $"«{name}» non è riuscita.", EventSeverity.Error, accountId, run.Session.SessionId, ct).ConfigureAwait(false); + break; + } + } + + private async Task LoadAccountAsync(RecipeRun run) + { + if (run.Request.AccountId is not { } id) + { + throw RecipeRun.Stop(RecipeStatus.Failed, $"«{Name(run.Request.Kind)}» ha bisogno di un account."); + } + + var account = await Env.Storage.Accounts.GetAsync(id, run.Ct).ConfigureAwait(false) + ?? throw RecipeRun.Stop(RecipeStatus.Failed, $"Account {id} non trovato."); + if (account.State == AccountState.ArchiveOnly) + { + throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta."); + } + + return account; + } + + /// The profile of in the reads: same identifier, or same name when the identifier is not known yet. + private static ProfileInfo? FindProfile(IEnumerable reads, Account account) => + reads.SelectMany(r => r.Result.Profiles) + .Where(p => account.InstagramId is { } id ? p.Id == id || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase) : string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase)) + .OrderByDescending(p => (p.PostCount is null ? 0 : 1) + (p.IsPrivate is null ? 0 : 1)) + .FirstOrDefault(); + + /// Content items of the reads, in arrival order, without repetitions. + private static List Contents(IEnumerable reads, Func? filter = null) + { + var seen = new HashSet(StringComparer.Ordinal); + return [.. reads.SelectMany(r => r.Result.Contents).Where(c => (filter is null || filter(c)) && seen.Add(c.Id))]; + } + + private static bool IsOwnedBy(ContentItem item, Account account) => + item.Owner is { } owner && (account.InstagramId is { } id ? owner.Id == id : string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase)); + + private static IReadOnlyDictionary Values(params (string Key, string Value)[] pairs) => + pairs.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal); +} diff --git a/src/Febe.Core/Collection/SignalDetector.cs b/src/Febe.Core/Collection/SignalDetector.cs index 4ce5e71..f547c23 100644 --- a/src/Febe.Core/Collection/SignalDetector.cs +++ b/src/Febe.Core/Collection/SignalDetector.cs @@ -12,7 +12,7 @@ namespace Febe.Core.Collection; /// The same signal code is reported at most once per : a page that receives ten 429 /// responses in a second is one throttle, not ten. Thread-safe. /// -public sealed class SignalDetector : IResponseObserver, IResponseConsumer +public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStopSignals { private readonly SignalRules _rules; private readonly ICircuitBreaker _breaker; diff --git a/src/Febe.Core/Collection/SiteMap.cs b/src/Febe.Core/Collection/SiteMap.cs new file mode 100644 index 0000000..fa47bd2 --- /dev/null +++ b/src/Febe.Core/Collection/SiteMap.cs @@ -0,0 +1,276 @@ +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Febe.Core.Collection; + +/// Names of the pages of a site map (the «pages» section of bersagli.*.json). +public static class SitePages +{ + /// Home: stories bar and recent posts of followed profiles. + public const string Home = "home"; + + /// Profile page, with {username}. + public const string Profile = "profile"; + + /// Profile page starting after a resume point, with {username} and {cursor} (optional: backfill resume). + public const string ProfileFrom = "profileFrom"; + + /// Reels tab of a profile resuming after {cursor} (optional). + public const string ReelsFrom = "reelsFrom"; + + /// Tagged tab of a profile resuming after {cursor} (optional). + public const string TaggedFrom = "taggedFrom"; + + /// Single post page, with {code}. + public const string Post = "post"; + + /// List of the profiles Alberto follows, with {username} (Alberto's). + public const string Following = "following"; + + /// The same list resuming after {cursor} (optional). + public const string FollowingFrom = "followingFrom"; + + /// Shape of the address of the story viewer: {username} and {id} of the story shown. + public const string StoryViewer = "storyViewer"; + + /// Shape of the address of the highlight viewer: {highlight} and {id} of the item shown. + public const string HighlightViewer = "highlightViewer"; + + public static IReadOnlyList All { get; } = + [Home, Profile, ProfileFrom, ReelsFrom, TaggedFrom, Post, Following, FollowingFrom, StoryViewer, HighlightViewer]; +} + +/// Identifiers of the targets the recipes look for (the «targets» section of bersagli.*.json). +public static class SiteTargets +{ + /// An account in the stories bar of the home, with {username}. + public const string HomeStory = "home-story"; + + /// The profile picture with the stories ring, on a profile page, with {username}. + public const string ProfileStoryRing = "profile-story-ring"; + + /// Read-only marker of a profile that does not exist. + public const string ProfileNotFound = "profile-not-found"; + + public const string ProfileTabPosts = "profile-tab-posts"; + + public const string ProfileTabReels = "profile-tab-reels"; + + public const string ProfileTabTagged = "profile-tab-tagged"; + + /// A highlight collection on a profile page, with {id}. + public const string ProfileHighlight = "profile-highlight"; + + /// The zone or command that advances the viewer to the next story. + public const string ViewerNext = "viewer-next"; + + /// The command that closes the viewer. + public const string ViewerClose = "viewer-close"; + + public static IReadOnlyList All { get; } = + [HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose]; +} + +/// +/// The site-specific part of a target map file that the recipes need in Core: page addresses and which targets are +/// configured. How a target is found (role, accessible name, link shape) is the browser layer's business +/// (Febe.Browser.Targets.TargetMap, same file). +/// +public sealed partial class SiteMap +{ + private readonly Dictionary _pages; + private readonly HashSet _configuredTargets; + private readonly HashSet _knownTargets; + + public SiteMap(string site, IReadOnlyDictionary pages, IEnumerable configuredTargets, IEnumerable knownTargets, string? source = null) + { + Site = site; + Source = source; + _pages = pages.Where(p => !string.IsNullOrWhiteSpace(p.Value)).ToDictionary(p => p.Key, p => p.Value!.Trim(), StringComparer.Ordinal); + _configuredTargets = new HashSet(configuredTargets, StringComparer.Ordinal); + _knownTargets = new HashSet(knownTargets, StringComparer.Ordinal); + } + + public string Site { get; } + + public string? Source { get; } + + public bool HasPage(string name) => _pages.ContainsKey(name); + + public bool IsTargetConfigured(string id) => _configuredTargets.Contains(id); + + /// Pages and targets among the given ones that are still unset (Italian names for messages). + public IReadOnlyList Missing(IEnumerable pages, IEnumerable targets) + { + var missing = new List(); + missing.AddRange(pages.Where(p => !HasPage(p)).Select(p => $"pagina «{p}»")); + missing.AddRange(targets.Where(t => !IsTargetConfigured(t)).Select(t => _knownTargets.Contains(t) ? $"bersaglio «{t}» (vuoto)" : $"bersaglio «{t}» (assente)")); + return missing; + } + + /// The path of page with its {placeholders} filled (values escaped for an address). + /// The page is not configured. + public string BuildPath(string name, IReadOnlyDictionary? values = null) + { + if (!_pages.TryGetValue(name, out var pattern)) + { + throw new InvalidOperationException($"La pagina «{name}» non è impostata nella mappa {Source ?? Site}."); + } + + return Placeholder().Replace(pattern, m => + { + var key = m.Groups[1].Value; + if (values is null || !values.TryGetValue(key, out var value)) + { + throw new InvalidOperationException($"Manca il valore di «{{{key}}}» per la pagina «{name}»."); + } + + return Uri.EscapeDataString(value); + }); + } + + /// + /// Reads an address path against the shape of page (e.g. the story viewer): + /// returns the {placeholder} values, or null when the path does not have that shape. + /// + public IReadOnlyDictionary? Match(string name, string path) + { + if (!_pages.TryGetValue(name, out var pattern) || string.IsNullOrEmpty(path)) + { + return null; + } + + var shape = pattern.Split('?')[0]; + var names = new List(); + var regex = new StringBuilder("^"); + var last = 0; + foreach (Match m in Placeholder().Matches(shape)) + { + regex.Append(Regex.Escape(shape[last..m.Index])); + regex.Append("([^/]+)"); + names.Add(m.Groups[1].Value); + last = m.Index + m.Length; + } + + regex.Append(Regex.Escape(shape[last..])); + if (!shape.EndsWith('/')) + { + regex.Append("/?"); + } + + regex.Append('$'); + var match = Regex.Match(path, regex.ToString(), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(100)); + if (!match.Success) + { + return null; + } + + var result = new Dictionary(StringComparer.Ordinal); + for (var i = 0; i < names.Count; i++) + { + result[names[i]] = Uri.UnescapeDataString(match.Groups[i + 1].Value); + } + + return result; + } + + /// The target map of the local test site (embedded bersagli.prova.json). + public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json"); + + /// The Instagram skeleton (embedded bersagli.instagram.json): every entry is still unset (H11). + public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json"); + + public static SiteMap LoadOrEmbedded(string? path, string embeddedName) => + !string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName); + + public static SiteMap Load(string path) => Parse(File.ReadAllText(path), path); + + /// Text of an embedded configuration file (also used by the browser layer to parse the targets). + public static string ReadEmbeddedText(string fileName) + { + var resource = $"Febe.Core.Config.{fileName}"; + using var stream = typeof(SiteMap).Assembly.GetManifestResourceStream(resource) + ?? throw new FileNotFoundException($"Risorsa incorporata mancante: {resource}"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } + + public static SiteMap LoadEmbedded(string fileName) => Parse(ReadEmbeddedText(fileName), fileName); + + public static SiteMap Parse(string json, string? source = null) + { + var name = source ?? "bersagli"; + JsonDocument document; + try + { + document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + } + catch (JsonException ex) + { + throw new InvalidDataException($"{name}: file non valido (riga {ex.LineNumber + 1}).", ex); + } + + using (document) + { + var root = document.RootElement; + var site = root.TryGetProperty("site", out var s) && s.ValueKind == JsonValueKind.String ? s.GetString()! : "sito"; + var pages = new Dictionary(StringComparer.Ordinal); + if (root.TryGetProperty("pages", out var p) && p.ValueKind == JsonValueKind.Object) + { + foreach (var page in p.EnumerateObject()) + { + if (!SitePages.All.Contains(page.Name, StringComparer.Ordinal)) + { + throw new InvalidDataException($"{name}: pagina «{page.Name}» sconosciuta (ammesse: {string.Join(", ", SitePages.All)})."); + } + + var value = page.Value.ValueKind switch + { + JsonValueKind.String => page.Value.GetString(), + JsonValueKind.Object when page.Value.TryGetProperty("path", out var path) && path.ValueKind == JsonValueKind.String => path.GetString(), + _ => null, + }; + if (!string.IsNullOrWhiteSpace(value) && !value.StartsWith('/')) + { + throw new InvalidDataException($"{name}: la pagina «{page.Name}» è un percorso e comincia con «/»."); + } + + pages[page.Name] = value; + } + } + + var configured = new List(); + var known = new List(); + if (root.TryGetProperty("targets", out var t) && t.ValueKind == JsonValueKind.Object) + { + foreach (var target in t.EnumerateObject()) + { + known.Add(target.Name); + if (target.Value.ValueKind == JsonValueKind.Object && IsConfigured(target.Value)) + { + configured.Add(target.Name); + } + } + } + + return new SiteMap(site, pages, configured, known, source); + } + } + + private static bool IsConfigured(JsonElement target) + { + foreach (var key in new[] { "role", "name", "href" }) + { + if (target.TryGetProperty(key, out var value) && value.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(value.GetString())) + { + return true; + } + } + + return false; + } + + [GeneratedRegex(@"\{([A-Za-z][A-Za-z0-9_]*)\}", RegexOptions.CultureInvariant)] + private static partial Regex Placeholder(); +} diff --git a/src/Febe.Core/Config/bersagli.instagram.json b/src/Febe.Core/Config/bersagli.instagram.json new file mode 100644 index 0000000..05e63e0 --- /dev/null +++ b/src/Febe.Core/Config/bersagli.instagram.json @@ -0,0 +1,27 @@ +{ + "site": "instagram", + "note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.", + "pages": { + "home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." }, + "profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." }, + "profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." }, + "reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." }, + "taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." }, + "post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." }, + "following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." }, + "followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." }, + "storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." }, + "highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." } + }, + "targets": { + "home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." }, + "profile-story-ring": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Foto del profilo con l'anello delle storie." }, + "profile-not-found": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Segno, in sola lettura, di un profilo inesistente." }, + "profile-tab-posts": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post." }, + "profile-tab-reels": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei reel." }, + "profile-tab-tagged": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post in cui l'account è taggato." }, + "profile-highlight": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Una raccolta in evidenza ({id})." }, + "viewer-next": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Zona o comando per andare alla storia successiva." }, + "viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." } + } +} diff --git a/src/Febe.Core/Config/bersagli.prova.json b/src/Febe.Core/Config/bersagli.prova.json new file mode 100644 index 0000000..21e7da4 --- /dev/null +++ b/src/Febe.Core/Config/bersagli.prova.json @@ -0,0 +1,27 @@ +{ + "site": "prova", + "note": "Mappa dei bersagli del sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2). Le ricette sono le stesse di Instagram: cambia solo dove trovano le cose. Ruolo, nome accessibile e forma del collegamento; mai coordinate, mai nomi di classi.", + "pages": { + "home": "/", + "profile": "/profilo/{username}/", + "profileFrom": "/profilo/{username}/?dopo={cursor}", + "reelsFrom": "/profilo/{username}/reel/?dopo={cursor}", + "taggedFrom": "/profilo/{username}/taggati/?dopo={cursor}", + "post": "/post/{code}/", + "following": "/profilo/{username}/seguiti/", + "followingFrom": "/profilo/{username}/seguiti/?dopo={cursor}", + "storyViewer": "/storie/{username}/{id}/", + "highlightViewer": "/evidenza/{highlight}/{id}/" + }, + "targets": { + "home-story": { "role": "link", "href": "/storie/{username}/", "name": "^storie di ", "note": "Voce della barra delle storie nella pagina iniziale." }, + "profile-story-ring": { "role": "link", "href": "/storie/{username}/", "name": "^apri le storie", "note": "Foto del profilo con l'anello delle storie." }, + "profile-not-found": { "role": "heading", "name": "^profilo non trovato$" }, + "profile-tab-posts": { "role": "tab", "name": "^post$" }, + "profile-tab-reels": { "role": "tab", "name": "^reel$" }, + "profile-tab-tagged": { "role": "tab", "name": "^taggati$" }, + "profile-highlight": { "role": "link", "href": "/evidenza/{id}/" }, + "viewer-next": { "role": "button", "name": "^storia successiva$" }, + "viewer-close": { "role": "button", "name": "^chiudi$" } + } +} diff --git a/src/Febe.Core/Config/lettori.instagram.json b/src/Febe.Core/Config/lettori.instagram.json new file mode 100644 index 0000000..c8b9bb9 --- /dev/null +++ b/src/Febe.Core/Config/lettori.instagram.json @@ -0,0 +1,51 @@ +{ + "site": "instagram", + "status": "ipotesi", + "note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.", + "content": { + "note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.", + "id": ["pk"], + "code": ["code"], + "takenAt": ["taken_at"], + "caption": [], + "images": ["image_versions2.candidates"], + "videos": ["video_versions"], + "children": ["carousel_media"], + "childCount": [], + "owner": [], + "pinned": [], + "expiresAt": [], + "duration": [] + }, + "version": { + "note": "Da compilare con i campioni di M0 (H3, H5).", + "url": [], + "width": [], + "height": [], + "hasAudio": [] + }, + "profile": { + "note": "Da compilare con i campioni di M0 (H3, H10).", + "id": [], + "username": [], + "displayName": [], + "isPrivate": [], + "isFollowed": [], + "postCount": [], + "picture": [], + "latestStoryAt": [] + }, + "highlight": { + "note": "Da compilare con i campioni di M0 (H3, H9).", + "id": [], + "title": [], + "owner": [], + "items": [] + }, + "page": { + "note": "Da compilare con i campioni di M0 (H3).", + "hasMore": [], + "cursor": [] + }, + "viewer": [] +} diff --git a/src/Febe.Core/Config/lettori.prova.json b/src/Febe.Core/Config/lettori.prova.json new file mode 100644 index 0000000..884dd7f --- /dev/null +++ b/src/Febe.Core/Config/lettori.prova.json @@ -0,0 +1,48 @@ +{ + "site": "prova", + "status": "confermato", + "note": "Vocabolario dei lettori per il sito di prova locale (tools/Febe.SitoDiProva). Il formato dei dati è sintetico, progettato per Febe e descritto in tools/Febe.SitoDiProva/LEGGIMI.md: non imita Instagram. Le date sono testi ISO 8601 in UTC.", + "content": { + "note": "Un contenuto: post, storia o contenuto di una raccolta. Riconosciuto quando ha numero, data e almeno una fra foto, filmati e parti.", + "id": ["numero"], + "code": ["sigla"], + "takenAt": ["pubblicato"], + "caption": ["testo"], + "images": ["foto"], + "videos": ["filmati"], + "children": ["parti"], + "childCount": ["parti_totali"], + "owner": ["autore"], + "pinned": ["fissato"], + "expiresAt": ["scade"], + "duration": ["durata"] + }, + "version": { + "note": "Una versione di un file: indirizzo, dimensioni e, per i filmati, se ha anche l'audio.", + "url": ["indirizzo"], + "width": ["larghezza"], + "height": ["altezza"], + "hasAudio": ["audio"] + }, + "profile": { + "id": ["numero"], + "username": ["nome"], + "displayName": ["nome_visibile"], + "isPrivate": ["riservato"], + "isFollowed": ["seguito"], + "postCount": ["pubblicazioni"], + "picture": ["ritratto"], + "latestStoryAt": ["ultima_storia"] + }, + "highlight": { + "id": ["numero"], + "title": ["titolo"], + "owner": ["autore"], + "items": ["contenuti"] + }, + "page": { + "hasMore": ["altro"], + "cursor": ["dopo"] + }, + "viewer": ["io"] +} diff --git a/src/Febe.Core/Config/segnali.prova.json b/src/Febe.Core/Config/segnali.prova.json index 8f58d16..9073252 100644 --- a/src/Febe.Core/Config/segnali.prova.json +++ b/src/Febe.Core/Config/segnali.prova.json @@ -21,6 +21,13 @@ "hostKinds": ["site"], "on": ["navigation", "document"] }, + { + "code": "session-ended-url", + "level": "disconnect", + "path": "^/sessione-scaduta(/|$)", + "hostKinds": ["site"], + "on": ["navigation", "document"] + }, { "code": "wait-text", "level": "throttle", diff --git a/src/Febe.Core/Storage/IMediaStore.cs b/src/Febe.Core/Storage/IMediaStore.cs index 9c706c1..95dbfeb 100644 --- a/src/Febe.Core/Storage/IMediaStore.cs +++ b/src/Febe.Core/Storage/IMediaStore.cs @@ -42,6 +42,13 @@ public interface IMediaStore /// Task MarkFailedAsync(long mediaId, MediaState state, string? error, DateTimeOffset at, CancellationToken ct = default); + /// + /// Adds files to an existing entry at positions it does not have yet (files at positions already present are left + /// as they are) and recomputes the state of the entry. Used by «Post singolo» to complete a series that arrived + /// incomplete. Returns the files of the entry in position order. + /// + Task> AddToEntryAsync(long entryId, IReadOnlyList media, CancellationToken ct = default); + /// A fresh address read from the page: the file goes back to «da scaricare». Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default); diff --git a/src/Febe.Data/Stores/MediaStore.cs b/src/Febe.Data/Stores/MediaStore.cs index 8937895..8c377a2 100644 --- a/src/Febe.Data/Stores/MediaStore.cs +++ b/src/Febe.Data/Stores/MediaStore.cs @@ -175,6 +175,36 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore ct); } + public Task> AddToEntryAsync(long entryId, IReadOnlyList media, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(media); + if (media.Any(m => m.Position < 1)) + { + throw new ArgumentException("Le posizioni dei file partono da 1.", nameof(media)); + } + + return db.WriteAsync>( + w => + { + if (ReadEntryById(w.Command, entryId) is null) + { + throw new KeyNotFoundException($"Elemento {entryId} non trovato."); + } + + var present = ReadMediaOf(w.Command, entryId).Select(m => m.Position).ToHashSet(); + foreach (var file in media.OrderBy(m => m.Position).Where(m => present.Add(m.Position))) + { + var command = w.Command(InsertMediaSql); + BindMedia(command, file with { EntryId = entryId, Sha256 = file.Sha256?.ToLowerInvariant(), InstagramId = NormalizeId(file.InstagramId) }); + command.ExecuteNonQuery(); + } + + RecomputeState(w, entryId); + return ReadMediaOf(w.Command, entryId); + }, + ct); + } + public Task UpdateSourceAsync(long mediaId, string? sourceUrl, string? coverUrl, DateTimeOffset seenAt, CancellationToken ct = default) => db.WriteAsync( w => diff --git a/tests/Febe.Tests/Collection/CollectionUnitTests.cs b/tests/Febe.Tests/Collection/CollectionUnitTests.cs new file mode 100644 index 0000000..068ee0e --- /dev/null +++ b/tests/Febe.Tests/Collection/CollectionUnitTests.cs @@ -0,0 +1,363 @@ +using System.Collections.Concurrent; +using Febe.Browser.Targets; +using Febe.Core.Abstractions; +using Febe.Core.Collection; +using Febe.Core.Collection.Downloads; +using Febe.Core.Collection.Readers; +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; +using Febe.Tests.Support; + +namespace Febe.Tests.Collection; + +/// Site map, recipe guards, the writer and the download queue, without a browser. +[TestClass] +public sealed class CollectionUnitTests +{ + [TestMethod] + public void TheTestSiteMapBuildsAndReadsAddresses() + { + var map = SiteMap.LoadTestSite(); + Assert.AreEqual("/profilo/marta.prova/", map.BuildPath(SitePages.Profile, new Dictionary { ["username"] = "marta.prova" })); + Assert.AreEqual("/profilo/a%20b/?dopo=c%2612", map.BuildPath(SitePages.ProfileFrom, new Dictionary { ["username"] = "a b", ["cursor"] = "c&12" })); + var story = map.Match(SitePages.StoryViewer, "/storie/marta.prova/7300105520/"); + Assert.AreEqual("marta.prova", story!["username"]); + Assert.AreEqual("7300105520", story["id"]); + Assert.IsNull(map.Match(SitePages.StoryViewer, "/profilo/marta.prova/")); + Assert.IsNotNull(map.Match(SitePages.Home, "/")); + Assert.AreEqual(0, map.Missing(SitePages.All, SiteTargets.All).Count); + Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "bersagli.prova.json")), "Editable without recompiling."); + } + + [TestMethod] + public void TheInstagramMapIsASkeletonWithEveryEntryEmpty() + { + 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."); + + // 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"); + CollectionAssert.AreEquivalent(SiteTargets.All.ToArray(), targets.Targets.Keys.ToArray()); + Assert.IsTrue(targets.Targets.Values.All(t => !t.IsConfigured && t.Hypothesis == "H11")); + var cdp = new FakeCdpSession(new VirtualClock()); + var lookup = new TargetResolver(cdp, targets).ResolveAsync(SiteTargets.ViewerClose).GetAwaiter().GetResult(); + Assert.AreEqual(TargetStatus.NotConfigured, lookup.Status); + Assert.AreEqual(0, cdp.Sent.Count, "A placeholder never reaches the page."); + StringAssert.Contains(lookup.Message, "H11"); + } + + [TestMethod] + public async Task RecipesRefuseToRunOnInstagramWhileTheMapOrTheReadersAreSkeletons() + { + 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() + { + Driver = new UntouchableDriver(), + Capture = new CaptureCollector(new ShapeReader(vocabulary), clock), + Governor = governor, + Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock), + Storage = db, + SiteMap = map, + Clock = clock, + Random = new SeededRandom(1), + }; + + foreach (var kind in Enum.GetValues().Where(k => k != RecipeKind.FollowingSweep)) + { + 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()); + StringAssert.Contains(outcome.Message, "mappa dei bersagli non è ancora compilata"); + } + + var sweep = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite())) + .RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None); + StringAssert.Contains(sweep.Message, "pagina «home»"); + + 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"); + + 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")); + } + + [TestMethod] + public void StoryTimingsFollowSection77() + { + var random = new SeededRandom(3); + for (var i = 0; i < 500; i++) + { + var photo = StoryTimings.Watch(random, null, 1.0); + Assert.IsTrue(photo >= TimeSpan.FromSeconds(1.8) && photo <= TimeSpan.FromSeconds(5), photo.ToString()); + var video = StoryTimings.Watch(random, TimeSpan.FromSeconds(10), 1.0); + Assert.IsTrue(video >= TimeSpan.FromSeconds(4) && video <= TimeSpan.FromSeconds(10), video.ToString()); + var longVideo = StoryTimings.Watch(random, TimeSpan.FromSeconds(60), 1.0); + Assert.IsTrue(longVideo <= TimeSpan.FromSeconds(15), "At most 15 s."); + var between = StoryTimings.BetweenAccounts(random, 1.0); + Assert.IsTrue(between >= TimeSpan.FromSeconds(1) && between <= TimeSpan.FromSeconds(4)); + } + + Assert.AreEqual(2 * StoryTimings.Watch(new SeededRandom(9), null, 1.0).Ticks, StoryTimings.Watch(new SeededRandom(9), null, 2.0).Ticks, 1, "Mood and pace multiply the waits."); + Assert.AreEqual("48.212", ItalianText.Number(48212)); + Assert.AreEqual("1.000.000", ItalianText.Number(1_000_000)); + Assert.AreEqual("96", ItalianText.Number(96)); + } + + [TestMethod] + public async Task TheWriterRecognizesImportedEntriesAndAppliesTheAccountSettings() + { + using var temp = new TempFolder("scrittore"); + await using var library = await TestLibrary.CreateAsync(temp); + var db = library.Db; + var account = await db.Accounts.AddAsync(Make.Account("marta.prova", "1001") with + { + Limits = new AccountLimits { Depth = HistoryDepth.FromDate, FromDate = Make.T0.AddDays(-10), StoryVideos = false }, + }); + var writer = new CollectionWriter(db, library.Clock); + var imported = await db.Entries.AddAsync(new Entry + { + AccountId = account.Id, + Kind = EntryKind.Post, + PublishedAt = Make.T0.AddDays(-1), + Provenance = Provenance.Imported, + DiscoveredAt = Make.T0, + }, []); + + var reader = new ShapeReader(ReaderVocabulary.LoadTestSite()); + ContentItem Item(string id, DateTimeOffset at, bool video = false) => reader.Read($$""" + {"numero":"{{id}}","sigla":"S{{id}}","pubblicato":"{{at.UtcDateTime:yyyy-MM-ddTHH:mm:ssZ}}","testo":"didascalia","autore":{"numero":"1001","nome":"marta.prova"}, + "{{(video ? "filmati" : "foto")}}":[{"indirizzo":"https://cdn.esempio/{{id}}.{{(video ? "mp4" : "jpg")}}","larghezza":10,"altezza":10,"audio":true}]} + """).Contents.Single(); + + var enriched = await writer.SaveAsync(account, Item("500", Make.T0.AddDays(-1).AddSeconds(1)), EntryKind.Post, null, CancellationToken.None); + Assert.AreEqual(SaveOutcome.Enriched, enriched.Outcome, "Same account, kind and time within two seconds (§9.5)."); + var stored = await db.Entries.GetAsync(imported.Stored.Entry.Id); + Assert.AreEqual("500", stored!.InstagramId); + Assert.AreEqual("S500", stored.Code); + + Assert.AreEqual(SaveOutcome.Excluded, (await writer.SaveAsync(account, Item("501", Make.T0.AddDays(-30)), EntryKind.Post, null, CancellationToken.None)).Outcome, "Older than «da una data»."); + Assert.AreEqual(SaveOutcome.Excluded, (await writer.SaveAsync(account, Item("502", Make.T0), EntryKind.Tagged, null, CancellationToken.None)).Outcome, "«Post in cui è taggato» is off."); + Assert.AreEqual(SaveOutcome.Created, (await writer.SaveAsync(account, Item("503", Make.T0), EntryKind.Post, null, CancellationToken.None)).Outcome); + Assert.AreEqual(SaveOutcome.Known, (await writer.SaveAsync(account, Item("503", Make.T0), EntryKind.Post, null, CancellationToken.None)).Outcome); + + var story = await writer.SaveAsync(account, Item("504", Make.T0, video: true), EntryKind.Story, null, CancellationToken.None); + var video = (await db.Media.ListByEntryAsync(story.Entry!.Id)).Single(); + Assert.AreEqual(MediaState.Skipped, video.State, "«Video delle storie» is off: never downloaded."); + Assert.IsNull(video.SourceUrl); + } + + [TestMethod] + public async Task TheQueueRecoversExpiredAddressesSkipsTooLargeVideosAndPutsStoriesFirst() + { + using var temp = new TempFolder("coda"); + await using var library = await TestLibrary.CreateAsync(temp); + var db = library.Db; + var account = await db.Accounts.AddAsync(Make.Account("marta.prova", "1001") with { Limits = new AccountLimits { MaxVideoBytes = 1000 } }); + var post = await AddAsync(db, account, "p1", EntryKind.Post, Make.Photo(), "https://cdn.esempio/scaduto.jpg"); + var story = await AddAsync(db, account, "s1", EntryKind.Story, Make.Photo(), "https://cdn.esempio/storia-scaduta.jpg"); + var video = await AddAsync(db, account, "v1", EntryKind.Post, Make.Video(), "https://cdn.esempio/grande.mp4"); + var fine = await AddAsync(db, account, "f1", EntryKind.Story, Make.Photo(), "https://cdn.esempio/buono.jpg"); + var fetcher = new FakeFetcher(uri => uri.AbsolutePath switch + { + "/scaduto.jpg" or "/storia-scaduta.jpg" => (FetchOutcome.HttpError, 403, null), + "/grande.mp4" => (FetchOutcome.Completed, 200, new byte[5000]), + _ => (FetchOutcome.Completed, 200, TestFile.PhotoBytes(3, 64, 80)), + }); + var queue = new DownloadQueue(db, library.Ingest, fetcher, new FakeDataBudget(), library.Clock, new SeededRandom(1), + new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 }); + + var report = await queue.RunOnceAsync(CancellationToken.None); + Assert.AreEqual(1, report.Stored, report.ToString()); + Assert.AreEqual(2, report.Expired); + Assert.AreEqual(1, report.Skipped); + CollectionAssert.AreEqual(new[] { "/storia-scaduta.jpg", "/buono.jpg" }, fetcher.Order.Take(2).ToArray(), "Stories first: they expire."); + + Assert.AreEqual(MediaState.Expired, (await db.Media.ListByEntryAsync(post)).Single().State); + Assert.AreEqual(MediaState.Failed, (await db.Media.ListByEntryAsync(story)).Single().State, "No recovery for stories."); + var tasks = await db.Tasks.ListPendingAsync(10); + Assert.AreEqual(post.ToString(System.Globalization.CultureInfo.InvariantCulture), tasks.Single(t => t.Kind == EngineTaskKind.SinglePost).Payload); + var big = (await db.Media.ListByEntryAsync(video)).Single(); + Assert.AreEqual(MediaState.Skipped, big.State); + StringAssert.Contains(big.LastError, "limite"); + Assert.AreEqual(MediaState.Downloaded, (await db.Media.ListByEntryAsync(fine)).Single().State); + Assert.AreEqual(0, Directory.EnumerateFiles(temp.Combine("dati", "temporanei")).Count()); + } + + [TestMethod] + public async Task AFileIdenticalToAnImportedOneIsDiscardedAndTheImportedEntryTakesTheData() + { + using var temp = new TempFolder("doppioni"); + await using var library = await TestLibrary.CreateAsync(temp); + var db = library.Db; + var account = await db.Accounts.AddAsync(Make.Account("marta.prova", "1001")); + var bytes = TestFile.PhotoBytes(11, 120, 150); + var imported = await library.SaveAsync(account, new Entry + { + AccountId = account.Id, + Kind = EntryKind.Post, + PublishedAt = Make.T0.AddDays(-3), + Provenance = Provenance.Imported, + DiscoveredAt = Make.T0, + }, [new TestFile(Make.Photo(), bytes, ".jpg")]); + var downloaded = await AddAsync(db, account, "777", EntryKind.Post, Make.Photo(), "https://cdn.esempio/stesso.jpg", caption: "dal sito"); + + var queue = new DownloadQueue(db, library.Ingest, new FakeFetcher(_ => (FetchOutcome.Completed, 200, bytes)), new FakeDataBudget(), library.Clock, new SeededRandom(1), + new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei") }); + var report = await queue.RunOnceAsync(CancellationToken.None); + Assert.AreEqual(1, report.Duplicates, report.ToString()); + Assert.IsNull(await db.Entries.GetAsync(downloaded), "The new record goes away."); + var merged = await db.Entries.GetAsync(imported.Entry.Id); + Assert.AreEqual("777", merged!.InstagramId); + Assert.AreEqual("dal sito", merged.Caption); + Assert.AreEqual(1, Directory.EnumerateFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories).Count(), "One file in the library."); + } + + [TestMethod] + public async Task TheQueueStopsAtTheDataBudgetAndNeverRunsMoreThanTwoAtOnce() + { + using var temp = new TempFolder("tetto"); + await using var library = await TestLibrary.CreateAsync(temp); + var db = library.Db; + var account = await db.Accounts.AddAsync(Make.Account("marta.prova", "1001")); + for (var i = 0; i < 8; i++) + { + await AddAsync(db, account, $"p{i}", EntryKind.Post, Make.Photo(), $"https://cdn.esempio/{i}.jpg"); + } + + var fetcher = new FakeFetcher(uri => (FetchOutcome.Completed, 200, TestFile.PhotoBytes(int.Parse(uri.AbsolutePath[1..^4], System.Globalization.CultureInfo.InvariantCulture) + 20, 64, 80))) + { + Latency = TimeSpan.FromMilliseconds(30), + }; + var queue = new DownloadQueue(db, library.Ingest, fetcher, new FakeDataBudget(), library.Clock, new SeededRandom(1), + new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei") }); + Assert.AreEqual(8, (await queue.RunOnceAsync(CancellationToken.None)).Stored); + Assert.AreEqual(2, fetcher.MaxConcurrent, "At most two at the same time (§6.5)."); + + for (var i = 8; i < 12; i++) + { + await AddAsync(db, account, $"p{i}", EntryKind.Post, Make.Photo(), $"https://cdn.esempio/{i}.jpg"); + } + + var budget = new FakeDataBudget(bytesPerDay: 1); + var limited = new DownloadQueue(db, library.Ingest, fetcher, budget, library.Clock, new SeededRandom(1), + new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 }); + var report = await limited.RunOnceAsync(CancellationToken.None); + Assert.IsTrue(report.BudgetReached); + Assert.AreEqual(1, report.Stored, "The budget is checked before each file."); + Assert.AreEqual(3, await db.Media.CountPendingDownloadsAsync()); + Assert.ThrowsExactly(() => new DownloadQueue(db, library.Ingest, fetcher, budget, library.Clock, new SeededRandom(1), + new DownloadOptions { StagingFolder = temp.Path, MaxConcurrent = 3 })); + } + + private static async Task AddAsync(IFebeStorage db, Account account, string id, EntryKind kind, Media media, string url, string? caption = null) + { + var entry = new Entry + { + AccountId = account.Id, + Kind = kind, + InstagramId = id, + Code = "C" + id, + PublishedAt = Make.T0.AddHours(-id.Length), + Caption = caption, + DiscoveredAt = Make.T0, + ExpiresAt = kind == EntryKind.Story ? Make.T0.AddHours(20) : null, + }; + var added = await db.Entries.AddAsync(entry, [media with { SourceUrl = url, SourceSeenAt = Make.T0 }]); + return added.Stored.Entry.Id; + } + + /// A file fetcher answering from a table: no network at all. + private sealed class FakeFetcher(Func answer) : IFileFetcher + { + private int _current; + private int _max; + + public ConcurrentQueue Calls { get; } = new(); + + public IReadOnlyList Order => [.. Calls]; + + public TimeSpan Latency { get; init; } + + public int MaxConcurrent => Volatile.Read(ref _max); + + public async Task FetchAsync(Uri address, Stream destination, FetchOptions? options, CancellationToken ct) + { + Calls.Enqueue(address.AbsolutePath); + var now = Interlocked.Increment(ref _current); + int seen; + while ((seen = Volatile.Read(ref _max)) < now && Interlocked.CompareExchange(ref _max, now, seen) != seen) + { + } + + try + { + if (Latency > TimeSpan.Zero) + { + await Task.Delay(Latency, ct); + } + + var (outcome, status, bytes) = answer(address); + if (bytes is null) + { + return new FetchResult(outcome, 0, status, "errore di prova"); + } + + if (options?.MaxBytes is { } max && bytes.Length > max) + { + await destination.WriteAsync(bytes.AsMemory(0, (int)max), ct); + return new FetchResult(FetchOutcome.TooLarge, max, status, "troppo grande"); + } + + await destination.WriteAsync(bytes, ct); + return new FetchResult(outcome, bytes.Length, status, null); + } + finally + { + Interlocked.Decrement(ref _current); + } + } + } + + /// A driver that fails the test if a recipe touches it. + private sealed class UntouchableDriver : IPageDriver + { + public double WaitMultiplier => 1; + + public void BeginSession(double mood) + { + } + + public Task OpenAsync(string path, CancellationToken ct) => throw new AssertFailedException("La ricetta ha aperto una pagina."); + + public Task CurrentPathAsync(CancellationToken ct) => throw new AssertFailedException("La ricetta ha letto la pagina."); + + public Task IsOnSiteAsync(CancellationToken ct) => throw new AssertFailedException("La ricetta ha letto la pagina."); + + public Task FindAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct) => throw new AssertFailedException("La ricetta ha cercato un bersaglio."); + + public Task ClickAsync(string target, IReadOnlyDictionary? parameters, CancellationToken ct) => throw new AssertFailedException("La ricetta ha cliccato."); + + public Task ScrollBurstAsync(CancellationToken ct) => throw new AssertFailedException("La ricetta ha scorso la pagina."); + + public Task WaitAfterLoadAsync(CancellationToken ct) => Task.CompletedTask; + + public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Task.CompletedTask; + + public Task MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false); + + public Task HasSessionCookieAsync(CancellationToken ct) => throw new AssertFailedException("La ricetta ha controllato il cookie."); + + public Task RestAsync(CancellationToken ct) => Task.CompletedTask; + } +} diff --git a/tests/Febe.Tests/Collection/ProbeIntegrationTests.cs b/tests/Febe.Tests/Collection/ProbeIntegrationTests.cs new file mode 100644 index 0000000..9a2ce6d --- /dev/null +++ b/tests/Febe.Tests/Collection/ProbeIntegrationTests.cs @@ -0,0 +1,121 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Febe.Browser.Cdp; +using Febe.Browser.Gestures; +using Febe.Core.Abstractions; +using Febe.Core.Collection; +using Febe.SitoDiProva; +using Febe.Sonda; +using Febe.Tests.Collection.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Collection; + +/// +/// The passive probe (spec §14.5) on the local test site: the test plays Alberto (it navigates and moves the mouse), +/// the probe only listens. Then the whole M0 path: raw samples, cleaning, verification. +/// +[TestClass] +[DoNotParallelize] +public sealed class ProbeIntegrationTests +{ + private static SharedChromium? s_chromium; + private static string? s_unavailable; + + public TestContext TestContext { get; set; } = null!; + + [ClassInitialize] + public static async Task StartAsync(TestContext context) + { + s_unavailable = SharedChromium.UnavailableReason(); + if (s_unavailable is null) + { + s_chromium = await SharedChromium.StartAsync(); + } + } + + [ClassCleanup] + public static async Task StopAsync() + { + if (s_chromium is not null) + { + await s_chromium.DisposeAsync(); + s_chromium = null; + } + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task TheProbeRecordsResponsesAndTargetsWithoutGesturesAndItsSamplesCleanUp() + { + if (s_unavailable is not null) + { + Assert.Inconclusive(s_unavailable); + } + + await using var site = await TestSite.StartAsync(); + using var temp = new TempFolder("sonda"); + var raw = temp.Combine("grezzi"); + var hosts = new HostClassifier([site.SiteHost], [site.CdnHost]); + var recording = new RecordingCdp(s_chromium!.Cdp); + await using (var probe = new ProbeRecorder(recording, hosts, raw, pollEvery: TimeSpan.FromMilliseconds(100))) + { + await probe.StartAsync(); + + // Alberto opens a profile and points at the «Reel» tab. + var cdp = s_chromium.Cdp; + await cdp.NavigateAsync(site.Url("/profilo/marta.prova/")); + await cdp.WaitForLoadAsync(new SystemClock(), TimeSpan.FromSeconds(10)); + await Task.Delay(800); + var tab = await cdp.EvaluateAsync("(() => { const r = [...document.querySelectorAll('a[role=tab]')].find((a) => a.textContent === 'Reel').getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; })()"); + var alberto = new HumanGestures(cdp, new SystemClock(), new SeededRandom(5)); + await alberto.MoveToAsync(new PagePoint(tab.GetProperty("x").GetDouble(), tab.GetProperty("y").GetDouble())); + await Task.Delay(600); + await probe.StopAsync(); + Assert.IsTrue(probe.Stats.Responses >= 1, "The profile data was recorded."); + } + + Assert.IsFalse(recording.Methods.Any(m => m.StartsWith("Input.", StringComparison.Ordinal)), "The probe never performs a gesture."); + Assert.IsFalse(recording.Methods.Contains("Page.navigate"), "The probe never opens a page by itself."); + Assert.IsTrue(File.Exists(Path.Combine(raw, "LEGGIMI.txt"))); + + var responses = Directory.EnumerateFiles(Path.Combine(raw, "risposte")).ToList(); + Assert.IsTrue(responses.Count >= 1); + using (var sample = JsonDocument.Parse(File.ReadAllText(responses[0]))) + { + var url = sample.RootElement.GetProperty("descrittore").GetProperty("indirizzo").GetString()!; + Assert.IsFalse(url.Contains('?', StringComparison.Ordinal), "Never the query string."); + Assert.AreEqual("sito", sample.RootElement.GetProperty("descrittore").GetProperty("host").GetString()); + Assert.IsTrue(sample.RootElement.GetProperty("corpo").TryGetProperty("profilo", out _)); + } + + var interactions = File.ReadAllLines(Path.Combine(raw, "interazioni.jsonl")); + Assert.IsTrue( + interactions.Any(l => l.Contains("\"sopra\"", StringComparison.Ordinal) && l.Contains("\"role\":\"tab\"", StringComparison.Ordinal) && l.Contains("Reel", StringComparison.Ordinal)), + "The hovered tab is described with role and accessible name: " + string.Join(" | ", interactions)); + Assert.IsTrue(File.ReadAllText(Path.Combine(raw, "navigazioni.jsonl")).Contains("/profilo/marta.prova/", StringComparison.Ordinal)); + + // M0 path: clean, then verify. + var clean = temp.Combine("ripuliti"); + new SampleSanitizer(hosts: hosts).SanitizeFolder(raw, clean); + var report = SampleVerifier.Verify(raw, clean); + Assert.IsTrue(report.Passed, string.Join("; ", report.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind}"))); + Assert.IsTrue(File.ReadLines(Path.Combine(clean, "interazioni.jsonl")).Any(l => l.Contains("\"role\":\"tab\"", StringComparison.Ordinal)), "Roles survive the cleaning."); + } + + /// Forwards to the browser and records the command names (never parameters). + private sealed class RecordingCdp(ICdpSession inner) : ICdpSession + { + private readonly ConcurrentQueue _methods = new(); + + public IReadOnlyList Methods => [.. _methods]; + + public Task SendAsync(string method, object? parameters = null, CancellationToken ct = default) + { + _methods.Enqueue(method); + return inner.SendAsync(method, parameters, ct); + } + + public IDisposable On(string eventName, Action handler) => inner.On(eventName, handler); + } +} diff --git a/tests/Febe.Tests/Collection/ReaderTests.cs b/tests/Febe.Tests/Collection/ReaderTests.cs new file mode 100644 index 0000000..f9988c8 --- /dev/null +++ b/tests/Febe.Tests/Collection/ReaderTests.cs @@ -0,0 +1,253 @@ +using System.Text.Json; +using Febe.Core.Collection; +using Febe.Core.Collection.Readers; +using Febe.Core.Domain; + +namespace Febe.Tests.Collection; + +/// +/// The generic reader (spec §6.4) on the cleaned samples of tests/campioni/prova: 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). +/// +[TestClass] +public sealed class ReaderTests +{ + private static readonly ShapeReader Reader = new(ReaderVocabulary.LoadTestSite()); + + private static ReadResult ReadSample(string name) + { + var file = Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "prova"), $"*-{name}.json").Single(); + using var document = JsonDocument.Parse(File.ReadAllText(file)); + return Reader.Read(document.RootElement.GetProperty("corpo")); + } + + [TestMethod] + public void APostWithSeveralFilesKeepsTheirOrderAndTheBestVersions() + { + var result = ReadSample("post-serie"); + Assert.AreEqual(ReadShape.Recognized, result.Shape); + var post = result.Contents.Single(); + Assert.IsTrue(post.IsComplete); + Assert.IsNotNull(post.Code); + Assert.AreEqual(3, post.Files.Count); + CollectionAssert.AreEqual(new[] { MediaKind.Photo, MediaKind.Video, MediaKind.Photo }, post.Files.Select(f => f.Kind).ToArray()); + Assert.AreEqual((960, 1200), (post.Files[0].Best.Width, post.Files[0].Best.Height), "The largest image, not the first one."); + Assert.IsTrue(post.Files.All(f => f.InstagramId is not null), "Files of a series have their own identifiers."); + Assert.IsNotNull(post.Owner); + } + + [TestMethod] + public void AVideoTakesTheBestRenditionWithAudioAndItsCover() + { + var video = ReadSample("post-serie").Contents.Single().Files[1]; + Assert.AreEqual(MediaKind.Video, video.Kind); + Assert.AreEqual(720, video.Best.Width, "The 1080 rendition has no audio."); + Assert.AreEqual(true, video.Best.HasAudio); + Assert.AreEqual(TimeSpan.FromSeconds(2), video.Duration); + Assert.IsNotNull(video.Cover); + Assert.AreEqual(720, video.Cover.Width); + + var stories = ReadSample("storie").Contents; + Assert.AreEqual(4, stories.Count); + Assert.IsTrue(stories.All(s => s.ExpiresAt > s.TakenAt)); + Assert.AreEqual(1, stories.Count(s => s.Files[0].Kind == MediaKind.Video)); + Assert.AreEqual(1, stories.Select(s => s.Owner!.Id).Distinct().Count(), "The author of the list is inherited by every story."); + } + + [TestMethod] + public void APrivateProfileNotFollowedGivesItsStateAndNoContent() + { + var result = ReadSample("profilo-privato-non-seguito"); + Assert.AreEqual(ReadShape.Recognized, result.Shape); + var profile = result.Profiles.Single(); + Assert.AreEqual(true, profile.IsPrivate); + Assert.AreEqual(false, profile.IsFollowed); + Assert.AreEqual(0, result.Contents.Count); + Assert.AreEqual(false, result.Page?.HasMore); + } + + [TestMethod] + public void AnEmptyPageIsEmptyNotUnknown() + { + var result = ReadSample("pagina-vuota"); + Assert.AreEqual(ReadShape.Empty, result.Shape); + Assert.AreEqual(false, result.Page?.HasMore); + Assert.IsNull(result.KeyStructure); + } + + [TestMethod] + public void AnUnknownShapeIsReportedWithItsKeyStructureOnly() + { + var file = Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "prova"), "*-forma-sconosciuta.json").Single(); + using var document = JsonDocument.Parse(File.ReadAllText(file)); + var body = document.RootElement.GetProperty("corpo"); + var result = Reader.Read(body); + Assert.AreEqual(ReadShape.Unrecognized, result.Shape); + Assert.AreEqual("{risultati:{voci:[{chiave,valore,dettagli:{x,y}}]},versione}", result.KeyStructure); + foreach (var value in body.GetProperty("risultati").GetProperty("voci").EnumerateArray().Select(v => v.GetProperty("valore").GetString()!)) + { + Assert.IsFalse(result.KeyStructure!.Contains(value, StringComparison.Ordinal), "No value in the event."); + } + } + + [TestMethod] + public void TheHomeGivesTheConnectedAccountTheStoriesBarAndIncompleteSeries() + { + var result = ReadSample("inizio"); + Assert.IsNotNull(result.Viewer, "H10 on the test site: the connected account comes with the data."); + var bar = result.Profiles.Where(p => p.LatestStoryAt is not null).ToList(); + Assert.AreEqual(4, bar.Count); + Assert.AreEqual(6, result.Contents.Count); + Assert.IsTrue(result.Contents.Any(c => !c.IsComplete && c.Files.Count == 1), "A series with only its first file: incomplete."); + Assert.AreEqual(true, result.Page?.HasMore); + Assert.AreEqual(2, result.Page?.Cursor?.Length, "An opaque resume point (cleaned: same shape as «c6»)."); + } + + [TestMethod] + public void AProfilePageGivesPinnedPostsHighlightsAndTheNextPage() + { + var result = ReadSample("profilo-pubblico"); + Assert.AreEqual(12, result.Contents.Count); + Assert.AreEqual(2, result.Contents.Count(c => c.Pinned)); + Assert.IsTrue(result.Contents.Take(2).All(c => c.Pinned), "Pinned posts come first on the grid."); + CollectionAssert.AreEqual(new[] { "Qspblr", "Flvwvq" }.Select(t => t.Length).ToArray(), result.Highlights.Select(h => h.Title.Length).ToArray()); + Assert.AreEqual(3, result.Page?.Cursor?.Length); + var profile = result.Profiles.First(p => p.PostCount is not null); + Assert.AreEqual(18, profile.PostCount); + Assert.IsNotNull(profile.Picture); + Assert.AreEqual(320, profile.Picture.Width, "The largest profile picture."); + } + + [TestMethod] + public void AHighlightCarriesItsItemsInOrder() + { + var result = ReadSample("raccolta"); + var highlight = result.Highlights.Single(); + Assert.AreEqual(3, highlight.Items.Count); + Assert.IsTrue(highlight.Items.All(i => i.HighlightId == highlight.Id)); + CollectionAssert.AreEqual(new[] { 0, 1, 2 }, highlight.Items.Select(i => i.Order).ToArray()); + } + + [TestMethod] + public void TheFollowingListAndTheTaggedTabAreRead() + { + var following = ReadSample("seguiti"); + Assert.AreEqual(10, following.Profiles.Count); + Assert.AreEqual(3, following.Page?.Cursor?.Length); + + var tagged = ReadSample("taggati"); + Assert.AreEqual(3, tagged.Contents.Count); + Assert.AreEqual(1, tagged.Profiles.Count(p => p.PostCount is not null), "The tagged account itself."); + Assert.IsTrue(tagged.Contents.All(c => c.Owner!.Id != tagged.Profiles.First(p => p.PostCount is not null).Id), "Tagged posts belong to others."); + } + + [TestMethod] + public void DatesAreReadAsIsoTextOrUnixSeconds() + { + var iso = Reader.Read("""{"numero":"1","pubblicato":"2026-10-13T08:00:00Z","foto":[{"indirizzo":"https://cdn.esempio/a.jpg","larghezza":1,"altezza":1}]}"""); + var unix = Reader.Read("""{"numero":"1","pubblicato":1791878400,"foto":[{"indirizzo":"https://cdn.esempio/a.jpg","larghezza":1,"altezza":1}]}"""); + var millis = Reader.Read("""{"numero":"1","pubblicato":1791878400000,"foto":[{"indirizzo":"https://cdn.esempio/a.jpg","larghezza":1,"altezza":1}]}"""); + Assert.AreEqual(new DateTimeOffset(2026, 10, 13, 8, 0, 0, TimeSpan.Zero), iso.Contents.Single().TakenAt); + Assert.AreEqual(unix.Contents.Single().TakenAt, millis.Contents.Single().TakenAt); + } + + [TestMethod] + public void AVideoWithoutAnyAudioRenditionTakesTheLargest() + { + var result = Reader.Read(""" + {"numero":"9","pubblicato":"2026-10-13T08:00:00Z","durata":3.5, + "filmati":[{"indirizzo":"https://cdn.esempio/a.mp4","larghezza":360,"altezza":640,"audio":false}, + {"indirizzo":"https://cdn.esempio/b.mp4","larghezza":720,"altezza":1280,"audio":false}]} + """); + var file = result.Contents.Single().Files.Single(); + Assert.AreEqual(720, file.Best.Width); + Assert.AreEqual(TimeSpan.FromSeconds(3.5), file.Duration); + } + + [TestMethod] + public void MappingGivesDomainRecords() + { + var item = ReadSample("post-serie").Contents.Single(); + var now = new DateTimeOffset(2026, 10, 13, 9, 0, 0, TimeSpan.Zero); + var entry = ReadMapping.ToEntry(item, 7, EntryKind.Post, now); + Assert.AreEqual(item.Id, entry.InstagramId); + Assert.AreEqual(item.Code, entry.Code); + Assert.AreEqual(item.TakenAt, entry.PublishedAt); + Assert.IsNull(entry.ExpiresAt); + var media = ReadMapping.ToMedia(item, now); + CollectionAssert.AreEqual(new[] { 1, 2, 3 }, media.Select(m => m.Position).ToArray()); + Assert.IsTrue(media.All(m => m.SourceUrl is not null && m.SourceSeenAt == now)); + Assert.IsNotNull(media[1].CoverUrl); + + var story = ReadSample("storie").Contents[0]; + Assert.AreEqual(story.ExpiresAt, ReadMapping.ToEntry(story, 7, EntryKind.Story, now).ExpiresAt); + var tagged = ReadMapping.ToEntry(item, 7, EntryKind.Tagged, now); + Assert.AreEqual(item.Owner!.Username, tagged.AuthorUsername); + } + + [TestMethod] + public void KeyStructureHidesIdentifierKeysAndValues() + { + using var document = JsonDocument.Parse("""{"elenco":{"17841400000":{"nome":"segreto"},"17841400001":{"nome":"altro"}},"conteggio":2,"lista":[]}"""); + var structure = KeyStructure.Describe(document.RootElement); + Assert.AreEqual("{elenco:{#:{nome}},conteggio,lista:[]}", structure); + Assert.IsTrue(KeyStructure.LooksLikeIdentifier("17841400000")); + Assert.IsTrue(KeyStructure.LooksLikeIdentifier("a1b2c3d4e5f6a7b8c9")); + Assert.IsFalse(KeyStructure.LooksLikeIdentifier("image_versions2")); + Assert.IsFalse(KeyStructure.LooksLikeIdentifier("larghezza")); + } + + [TestMethod] + public void TheShippedVocabulariesLoadAndInstagramsIsOnlyAHypothesis() + { + var test = ReaderVocabulary.LoadTestSite(); + Assert.IsTrue(test.IsUsable, test.UnusableReason); + 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); + } + + [TestMethod] + [DataRow("""{ "site": "x", "content": { "id": ["a"], "colore": ["b"] } }""", DisplayName = "Unknown concepts are refused")] + [DataRow("""{ "content": {} }""", DisplayName = "The site is required")] + [DataRow("""{ "site": "x", "status": "forse" }""", DisplayName = "Unknown status")] + [DataRow("""{ "site": """, DisplayName = "Broken JSON")] + public void InvalidVocabulariesAreRefused(string json) => + Assert.ThrowsExactly(() => ReaderVocabulary.Parse(json, "lettori.test.json")); + + [TestMethod] + public void TheCollectorKeepsReadsInOrderAndTracksPendingBodies() + { + var clock = new Febe.Tests.Browser.TestSupport.VirtualClock(); + var collector = new Febe.Core.Collection.Recipes.CaptureCollector(Reader, clock); + var observer = (IResponseObserver)collector; + var descriptor = new ResponseDescriptor("r1", HostKind.Site, "http://127.0.0.1/dati", "127.0.0.1", "/dati", 200, "application/json", "Fetch", false, clock.Now); + observer.OnResponse(descriptor); + Assert.AreEqual(1, collector.Pending); + var mark = collector.Mark(); + using var document = JsonDocument.Parse("""{"contenuti":[],"pagina":{"altro":false}}"""); + collector.Accept(descriptor, document.RootElement); + Assert.AreEqual(0, collector.Pending); + Assert.AreEqual(ReadShape.Empty, collector.Since(mark).Single().Result.Shape); + Assert.IsNull(collector.Accept(descriptor with { HostKind = HostKind.Cdn }, document.RootElement), "Only the site's data is read."); + } +} diff --git a/tests/Febe.Tests/Collection/RecipeIntegrationTests.cs b/tests/Febe.Tests/Collection/RecipeIntegrationTests.cs new file mode 100644 index 0000000..3f6a8f8 --- /dev/null +++ b/tests/Febe.Tests/Collection/RecipeIntegrationTests.cs @@ -0,0 +1,420 @@ +using Febe.Core.Abstractions; +using Febe.Core.Collection.Recipes; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; +using Febe.SitoDiProva; +using Febe.Tests.Collection.Support; + +namespace Febe.Tests.Collection; + +/// +/// Every recipe of spec §6.3 against the local test site, with a real Chromium on a private Xvfb display. Never +/// Instagram. Time is compressed (a 2.2 s wait lasts about 0.2 s); the browser is shared and the tests run one at a time. +/// +[TestClass] +[DoNotParallelize] +public sealed class RecipeIntegrationTests +{ + private static SharedChromium? s_chromium; + private static string? s_unavailable; + + public TestContext TestContext { get; set; } = null!; + + private static SharedChromium Chromium => s_chromium ?? throw new InvalidOperationException("Browser non avviato."); + + [ClassInitialize] + public static async Task StartAsync(TestContext context) + { + s_unavailable = SharedChromium.UnavailableReason(); + if (s_unavailable is null) + { + s_chromium = await SharedChromium.StartAsync(); + } + } + + [ClassCleanup] + public static async Task StopAsync() + { + if (s_chromium is not null) + { + await s_chromium.DisposeAsync(); + s_chromium = null; + } + } + + [TestInitialize] + public void RequireBrowser() + { + if (s_unavailable is not null) + { + Assert.Inconclusive(s_unavailable); + } + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ProfileCheckReadsTheFirstPageSkipsPinnedPostsAndStopsAtKnownContent() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + + var first = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message); + Assert.AreEqual(1, first.CountedActions, "One profile opened."); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.ProfileOpen)); + var posts = await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Post }); + Assert.AreEqual(12, posts.Count, "The first page of the grid: 2 pinned and 10 recent posts."); + Assert.AreEqual(1, (await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.ProfilePicture })).Count); + Assert.AreEqual(13, first.NewEntries); + var highlights = await h.Db.Highlights.ListAsync(marta.Id); + CollectionAssert.AreEqual(new[] { "Estate", "Viaggi" }, highlights.Select(x => x.Title).ToArray()); + var account = await h.Db.Accounts.GetAsync(marta.Id); + Assert.AreEqual("c12", account!.BackfillCursor, "The backfill resumes after the first page."); + Assert.AreEqual(18, account.PostCount); + Assert.IsTrue(first.AccountsWithStories.Contains(marta.Id), "Marta has active stories."); + + // Largest image version, best video with audio, every file of the series. + var series = posts.First(p => p.Code is not null && h.Site.World.FindPost(p.Code)!.Files.Count == 3); + var files = await h.Db.Media.ListByEntryAsync(series.Id); + Assert.AreEqual(3, files.Count); + Assert.AreEqual(960, files[0].Width); + Assert.AreEqual(MediaKind.Video, files[1].Kind); + Assert.AreEqual(720, files[1].Width, "The 1080 rendition has no audio: not chosen."); + StringAssert.DoesNotMatch(files[1].SourceUrl!, new System.Text.RegularExpressions.Regex("muto")); + + // A new post on top; pinned posts are known but do not stop the check before reaching it. + lock (h.Site.World.Gate) + { + h.Site.World.Publish(h.Site.World.FindByUsername("marta.prova")!, "foto", DateTimeOffset.UtcNow); + } + + var second = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message); + Assert.AreEqual(1, second.NewEntries, "Only the new post."); + Assert.AreEqual(13, (await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Post })).Count); + + // A new profile picture: a second copy, named by the first eight hex digits of its SHA-256 once downloaded. + lock (h.Site.World.Gate) + { + h.Site.World.FindByUsername("marta.prova")!.PictureVersion++; + } + + var third = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(1, third.NewEntries, third.Message); + Assert.AreEqual(2, (await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.ProfilePicture })).Count); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task UnreachableProfilesAreRecognizedAndNotTouched() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var hidden = await h.AddAccountAsync("riservato.prova", withId: false); + var missing = await h.Db.Accounts.AddAsync(Account.Create("nessuno.prova", StartingPoint.EverythingAndKeepUpdated, h.Clock.Now, h.Clock.LocalZone)); + + var privateOutcome = await h.RunAsync(RecipeKind.ProfileCheck, hidden.Id); + Assert.AreEqual(RecipeStatus.AccountUnreachable, privateOutcome.Status, privateOutcome.Message); + var stored = await h.Db.Accounts.GetAsync(hidden.Id); + Assert.AreEqual(AccountState.Unreachable, stored!.State); + Assert.AreEqual(UnreachableReason.PrivateNotFollowed, stored.UnreachableReason); + Assert.AreEqual("1006", stored.InstagramId, "The identifier is learnt from the data."); + Assert.AreEqual(0, (await h.Db.Entries.ListByAccountAsync(hidden.Id)).Count); + + var missingOutcome = await h.RunAsync(RecipeKind.ProfileCheck, missing.Id); + Assert.AreEqual(RecipeStatus.AccountUnreachable, missingOutcome.Status, missingOutcome.Message); + Assert.AreEqual(UnreachableReason.NotFound, (await h.Db.Accounts.GetAsync(missing.Id))!.UnreachableReason); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task FollowingSweepSavesRecentPostsFlagsStoriesAndStopsAtKnownContent() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + var nadia = await h.AddAccountAsync("nadia.prova"); + var luca = await h.AddAccountAsync("luca.prova"); + + var first = await h.RunAsync(RecipeKind.FollowingSweep); + Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message); + Assert.AreEqual(1, first.CountedActions, "Only the home is counted."); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.Home)); + Assert.IsTrue(first.NewEntries > 0); + CollectionAssert.IsSubsetOf(new[] { marta.Id, nadia.Id, luca.Id }, first.AccountsWithStories.ToArray(), "The stories bar flags followed accounts with active stories."); + Assert.IsTrue(first.AccountsWithNewPosts.Contains(marta.Id)); + var mine = await h.Db.Accounts.GetMineAsync(); + Assert.AreEqual("alberto.prova", mine?.Username, "The connected account is learnt from the data (H10)."); + + // Series arrive incomplete in the home: saved with what came, completed later by «Post singolo». + var tasks = await h.Db.Tasks.ListPendingAsync(100); + Assert.IsTrue(tasks.Any(t => t.Kind == EngineTaskKind.SinglePost), "An incomplete series queues «Post singolo»."); + + var second = await h.RunAsync(RecipeKind.FollowingSweep); + Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message); + Assert.AreEqual(0, second.NewEntries, "Known content at the top: nothing new."); + Assert.IsTrue(h.Site.Control.DataRequests.Count(r => r.StartsWith("/dati/inizio", StringComparison.Ordinal)) >= 2); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task SinglePostCompletesASeriesThatArrivedIncomplete() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + await h.AddAccountAsync("marta.prova"); + await h.AddAccountAsync("luca.prova"); + await h.AddAccountAsync("giulia.prova"); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.FollowingSweep)).Status); + var task = (await h.Db.Tasks.ListPendingAsync(100)).First(t => t.Kind == EngineTaskKind.SinglePost); + var entryId = long.Parse(task.Payload!, System.Globalization.CultureInfo.InvariantCulture); + Assert.AreEqual(1, (await h.Db.Media.ListByEntryAsync(entryId)).Count); + + var outcome = await h.RunAsync(RecipeKind.SinglePost, task.AccountId, entryId); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.SinglePost)); + var files = await h.Db.Media.ListByEntryAsync(entryId); + Assert.AreEqual(3, files.Count, "The whole series."); + Assert.IsTrue(files.All(f => f.SourceUrl is not null && f.State == MediaState.ToDownload)); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task StoriesAreWatchedOneByOneSavedOnlyWhenShownAndTheViewerIsClosed() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + + var outcome = await h.RunAsync(RecipeKind.AccountStories, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + var stories = await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Story }); + Assert.AreEqual(4, stories.Count); + Assert.AreEqual(4, h.Governor.Granted(ActionKind.StoryView), "One permit per story shown."); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.ProfileOpen)); + Assert.IsTrue(stories.All(s => s.ExpiresAt is not null)); + Assert.AreEqual("/profilo/marta.prova/", await h.CurrentPathAsync(), "The viewer was closed before it moved on to the next account."); + Assert.IsFalse(h.Site.Control.DataRequests.Any(r => r.StartsWith("/dati/storie/nadia", StringComparison.Ordinal)), "The next account was never opened."); + Assert.IsNotNull((await h.Db.Accounts.GetAsync(marta.Id))!.LastStoriesCheckAt); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task ARefusedStoryPermitStopsInOrderAndSavesOnlyTheStoriesShown() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var giulia = await h.AddAccountAsync("giulia.prova"); + h.Governor.ReportedRemaining = 50; + h.Governor.Limit(ActionKind.StoryView, 2); + + // The budget view says 2 left: fewer than ten, the stories are not even opened. + var refused = await h.RunAsync(RecipeKind.AccountStories, giulia.Id); + Assert.AreEqual(RecipeStatus.Denied, refused.Status, refused.Message); + Assert.AreEqual(0, h.Governor.Granted(ActionKind.StoryView)); + + // With a budget view that allows more, the Governor still refuses after two: stop in order. + await using var h2 = await CollectionHarness.CreateAsync(Chromium); + var g2 = await h2.AddAccountAsync("giulia.prova"); + var governor = new LimitedButOptimisticGovernor(h2.Governor, ActionKind.StoryView, 2); + var runner = new RecipeRunner(h2.Runner.Env with { Governor = governor, Budget = null }); + var outcome = await runner.RunAsync(new RecipeRequest(RecipeKind.AccountStories, g2.Id), h2.Session, CancellationToken.None); + Assert.AreEqual(RecipeStatus.Denied, outcome.Status, outcome.Message); + Assert.AreEqual(2, (await h2.Db.Entries.ListByAccountAsync(g2.Id, new EntryListOptions { Kind = EntryKind.Story })).Count, "Two shown, two saved: never the whole list received."); + StringAssert.StartsWith(await h2.CurrentPathAsync(), "/profilo/giulia.prova/", "The viewer is closed when the recipe stops."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task AStoryOfAnotherAccountIsNotSavedAndTheViewerIsClosed() + { + await using var h = await CollectionHarness.CreateAsync(Chromium, factor: 4); + var nadia = await h.AddAccountAsync("nadia.prova"); + await h.AddAccountAsync("luca.prova"); + + // The viewer moves on by itself faster than the recipe watches: it reaches the next account (Luca). + h.Site.Control.StoryDuration = TimeSpan.FromMilliseconds(300); + var outcome = await h.RunAsync(RecipeKind.AccountStories, nadia.Id); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + var luca = await h.Db.Accounts.FindByUsernameAsync("luca.prova"); + Assert.AreEqual(0, (await h.Db.Entries.ListByAccountAsync(luca!.Id, new EntryListOptions { Kind = EntryKind.Story })).Count, "Stories of another account are never saved."); + Assert.IsTrue((await h.Db.Entries.ListByAccountAsync(nadia.Id, new EntryListOptions { Kind = EntryKind.Story })).Count <= 3); + var events = await h.Db.Events.ListAsync(new EventQuery()); + Assert.IsTrue(events.Any(e => e.Code == "visualizzatore-altro-account"), "The event is recorded."); + Assert.IsFalse((await h.CurrentPathAsync()).StartsWith("/storie/", StringComparison.Ordinal), "The viewer is closed."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task StoriesOpenFromTheStoriesBarWhenTheHomeIsOnScreen() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var nadia = await h.AddAccountAsync("nadia.prova"); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.FollowingSweep)).Status); + var opens = h.Governor.Granted(ActionKind.ProfileOpen); + + var outcome = await h.RunAsync(RecipeKind.AccountStories, nadia.Id); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + Assert.AreEqual(opens, h.Governor.Granted(ActionKind.ProfileOpen), "Opened from the bar: no profile page."); + Assert.AreEqual(3, (await h.Db.Entries.ListByAccountAsync(nadia.Id, new EntryListOptions { Kind = EntryKind.Story })).Count); + Assert.AreEqual("/", await h.CurrentPathAsync(), "Back on the home, viewer closed."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task AHighlightReferencesAStoryAlreadySavedInsteadOfDownloadingItAgain() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.AccountStories, marta.Id)).Status); + string summerId; + string sharedStory; + lock (h.Site.World.Gate) + { + var summer = h.Site.World.FindByUsername("marta.prova")!.Highlights[0]; + summerId = summer.Id; + sharedStory = summer.Items[2].Id; + } + + var outcome = await h.RunAsync(RecipeKind.Highlight, marta.Id, highlightId: summerId); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + Assert.AreEqual(2, outcome.NewEntries, "Two new contents; the third is a story already saved (H9)."); + var highlight = await h.Db.Highlights.FindAsync(marta.Id, summerId); + var items = await h.Db.Highlights.ListItemsAsync(highlight!.Id); + Assert.AreEqual(3, items.Count); + var linked = await h.Db.Entries.GetAsync(items[2].EntryId); + Assert.AreEqual(EntryKind.Story, linked!.Kind); + Assert.AreEqual(sharedStory, linked.InstagramId); + Assert.IsNull(await h.Db.Entries.FindAsync(marta.Id, EntryKind.Highlight, sharedStory)); + StringAssert.StartsWith(await h.CurrentPathAsync(), "/profilo/marta.prova/", "Viewer closed after the last content."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task BackfillTakesOnePagePerPermitAndResumesFromTheStoredPoint() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var luca = await h.AddAccountAsync("luca.prova"); + + var first = await h.RunAsync(RecipeKind.Backfill, luca.Id, maxPages: 1); + Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message); + Assert.IsFalse(first.BackfillFinished); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.ProfileOpen)); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.BackfillPage), "The profile page, then one more page for one permit."); + Assert.AreEqual(24, (await h.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post })).Count); + Assert.AreEqual("c24", (await h.Db.Accounts.GetAsync(luca.Id))!.BackfillCursor); + + h.Site.Control.ClearRequests(); + var second = await h.RunAsync(RecipeKind.Backfill, luca.Id, maxPages: 3); + Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message); + Assert.IsTrue(second.BackfillFinished, "The beginning of the profile was reached."); + Assert.IsTrue(h.Site.Control.DataRequests[0].Contains("dopo=c24", StringComparison.Ordinal), "Resumed from the stored point: " + h.Site.Control.DataRequests[0]); + var posts = await h.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post }); + Assert.AreEqual(40, posts.Count); + Assert.AreEqual(40, posts.Select(p => p.InstagramId).Distinct().Count()); + var account = await h.Db.Accounts.GetAsync(luca.Id); + Assert.IsNotNull(account!.BackfillCompletedAt); + Assert.IsNull(account.BackfillCursor); + + var third = await h.RunAsync(RecipeKind.Backfill, luca.Id); + Assert.IsTrue(third.BackfillFinished); + Assert.AreEqual(0, third.CountedActions, "A finished backfill does not touch the site."); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task BackfillStopsWhileTooManyFilesWaitForDownload() + { + await using var h = await CollectionHarness.CreateAsync(Chromium, new RecipeOptions { MaxPendingDownloadsForBackfill = 5 }); + var luca = await h.AddAccountAsync("luca.prova"); + var outcome = await h.RunAsync(RecipeKind.Backfill, luca.Id, maxPages: 3); + Assert.AreEqual(RecipeStatus.Denied, outcome.Status, outcome.Message); + StringAssert.Contains(outcome.Message, "aspettano di essere scaricati"); + Assert.AreEqual(12, (await h.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post })).Count, "Stopped after the first page."); + Assert.AreEqual(0, h.Governor.Granted(ActionKind.BackfillPage)); + Assert.AreEqual("c12", (await h.Db.Accounts.GetAsync(luca.Id))!.BackfillCursor, "The resume point is kept."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task TaggedAndReelsTabsWorkLikeTheGrid() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova", a => a with { ContentTypes = ContentTypes.All }); + + var tagged = await h.RunAsync(RecipeKind.Tagged, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, tagged.Status, tagged.Message); + Assert.IsTrue(tagged.BackfillFinished); + var entries = await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged }); + Assert.AreEqual(3, entries.Count); + Assert.IsTrue(entries.All(e => e.AuthorUsername is "luca.prova" or "paolo.prova"), "Tagged posts keep their author."); + + var reels = await h.RunAsync(RecipeKind.Reels, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, reels.Status, reels.Message); + var posts = await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Post }); + Assert.AreEqual(4, posts.Count, "Marta's four reels, stored as posts."); + + // A reel found again in the grid is the same entry: the grid adds the others only. + var check = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message); + posts = await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Post }); + Assert.AreEqual(posts.Count, posts.Select(p => p.InstagramId).Distinct().Count()); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task TheFollowingListIsReadOverSeveralSessionsWithItsProgressKept() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.FollowingSweep)).Status, "The sweep learns Alberto's account."); + + var first = await h.RunAsync(RecipeKind.FollowingList, maxPages: 2); + Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message); + Assert.AreEqual("Letti 20 profili, continuo alla prossima sessione", first.Message); + Assert.IsFalse(first.BackfillFinished); + Assert.AreEqual(2, h.Governor.Granted(ActionKind.FollowingListPage)); + Assert.AreEqual(20, await h.Db.Following.CountAsync()); + + h.Site.Control.ClearRequests(); + var second = await h.RunAsync(RecipeKind.FollowingList, maxPages: 2); + Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message); + Assert.IsTrue(second.BackfillFinished, "End of the list."); + StringAssert.Contains(h.Site.Control.DataRequests[0], "dopo=c20"); + var list = await h.Db.Following.ListAsync(); + Assert.AreEqual(28, list.Count); + Assert.AreEqual("marta.prova", list[0].Username); + Assert.IsNull(await h.Db.Settings.GetAsync(RecipeRunner.FollowingKeys.Cursor)); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task AFollowedProfileThatChangedNameIsRecognizedByItsIdentifier() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + lock (h.Site.World.Gate) + { + h.Site.World.FindByUsername("marta.prova")!.Username = "marta.nuova"; + } + + var outcome = await h.RunAsync(RecipeKind.FollowingSweep); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + var renamed = await h.Db.Accounts.GetAsync(marta.Id); + Assert.AreEqual("marta.nuova", renamed!.Username); + Assert.AreEqual("marta.prova", renamed.PreviousUsername); + Assert.IsTrue(renamed.Notices.HasFlag(AccountNotices.Renamed)); + Assert.IsTrue((await h.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "account-rinominato")); + } + + /// A Governor whose budget view is optimistic but which refuses a category after some grants. + private sealed class LimitedButOptimisticGovernor(PermissiveGovernor inner, ActionKind kind, int grants) : IGovernor + { + private int _granted; + + public Task RequestAsync(ActionKind requested, long? accountId, CancellationToken ct) + { + if (requested == kind && Interlocked.Increment(ref _granted) > grants) + { + return Task.FromResult(Permit.Deny(requested, accountId, DenialReason.HourlyBudgetReached, "Tetto orario delle storie raggiunto (prova).")); + } + + return inner.RequestAsync(requested, accountId, ct); + } + } +} diff --git a/tests/Febe.Tests/Collection/SanitizerTests.cs b/tests/Febe.Tests/Collection/SanitizerTests.cs new file mode 100644 index 0000000..1f8a088 --- /dev/null +++ b/tests/Febe.Tests/Collection/SanitizerTests.cs @@ -0,0 +1,213 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.Core.Collection; +using Febe.Sonda; +using Febe.Tests.Support; + +namespace Febe.Tests.Collection; + +/// +/// Cleaning of probe samples (spec §14.5) on synthetic raw samples written by the test: invented, generic shapes +/// with made-up people. Nothing real, nothing that claims to be Instagram's format. +/// +[TestClass] +public sealed class SanitizerTests +{ + private const string RawSample = """ + { + "descrittore": { "indirizzo": "https://www.instagram.com/api/qualcosa/mario.rossi", "host": "sito", "stato": 200, "tipo": "application/json" }, + "corpo": { + "utente": { "id": "5512345678", "nome_utente": "mario.rossi", "nome": "Mario Rossi", "privato": false, "seguiti_count": 312 }, + "elementi": [ + { + "id": 3187654321098765, + "taken_at": 1791878400, + "didascalia": "Cena con Lucia al lago di Garda!! 🍝", + "width": 1080, "height": 1350, "duration": 12.5, + "media_type": "image", + "url": "https://scontent-mxp1-1.cdninstagram.com/v/t51/123_456_n.jpg?stp=abc&oh=00_secret&oe=6712ABCD", + "pagina": "https://www.instagram.com/p/CxYz123/", + "visto": true, + "vuoto": null + } + ], + "per_id": { "17841400123456": { "nome_utente": "lucia.bianchi" } }, + "cursore": "QVFIUjBzNmFQZ0pNb2xKd2E3ZQ==", + "ripetuto": "mario.rossi" + } + } + """; + + [TestMethod] + public void StructureStaysAndEveryPersonalValueIsReplaced() + { + using var temp = new TempFolder("ripulitura"); + var raw = Directory.CreateDirectory(temp.Combine("grezzi")).FullName; + File.WriteAllText(Path.Combine(raw, "000001.json"), RawSample); + File.WriteAllText(Path.Combine(raw, "interazioni.jsonl"), """ + {"evento":"fuoco","percorso":"/mario.rossi/","elemento":{"role":"link","ariaLabel":"Storie di mario.rossi","href":{"host":"www.instagram.com","path":"/stories/mario.rossi/"}}} + {"evento":"sopra","percorso":"/","elemento":{"role":"button","ariaLabel":"Chiudi"}} + """); + Directory.CreateDirectory(Path.Combine(raw, SampleSanitizer.BrowserProfileFolder)); + File.WriteAllText(Path.Combine(raw, SampleSanitizer.BrowserProfileFolder, "Preferences.json"), """{"segreto":"cookie di sessione"}"""); + + var clean = temp.Combine("ripuliti"); + var report = new SampleSanitizer(key: new byte[32]).SanitizeFolder(raw, clean); + Assert.AreEqual(2, report.Files, "The browser profile is never part of the samples."); + Assert.IsFalse(Directory.Exists(Path.Combine(clean, SampleSanitizer.BrowserProfileFolder))); + + var cleaned = JsonNode.Parse(File.ReadAllText(Path.Combine(clean, "000001.json")))!; + var body = cleaned["corpo"]!; + var item = body["elementi"]![0]!; + + // Structure and ordinary keys stay. + CollectionAssert.AreEquivalent( + new[] { "id", "taken_at", "didascalia", "width", "height", "duration", "media_type", "url", "pagina", "visto", "vuoto" }, + item.AsObject().Select(p => p.Key).ToArray()); + + // Allowlisted fields stay: dimensions, durations, counts, type codes, dates; booleans and null always. + Assert.AreEqual(1080, item["width"]!.GetValue()); + Assert.AreEqual(12.5, item["duration"]!.GetValue()); + Assert.AreEqual(1791878400, item["taken_at"]!.GetValue()); + Assert.AreEqual("image", item["media_type"]!.GetValue()); + Assert.AreEqual(312, body["utente"]!["seguiti_count"]!.GetValue()); + Assert.IsTrue(item["visto"]!.GetValue()); + Assert.IsNull(item["vuoto"]); + + // Strings and long numbers: fake values of the same shape. + var name = body["utente"]!["nome_utente"]!.GetValue(); + Assert.AreNotEqual("mario.rossi", name); + Assert.AreEqual(11, name.Length); + Assert.AreEqual('.', name[5], "Punctuation keeps the shape."); + Assert.AreEqual(name, body["ripetuto"]!.GetValue(), "Equal values get equal fakes: relations survive."); + var id = item["id"]!.GetValue(); + Assert.AreNotEqual(3187654321098765, id); + Assert.AreEqual(16, id.ToString(System.Globalization.CultureInfo.InvariantCulture).Length); + Assert.AreEqual(10, body["utente"]!["id"]!.GetValue().Length); + var caption = item["didascalia"]!.GetValue(); + Assert.AreEqual("Cena con Lucia al lago di Garda!! 🍝".Length, caption.Length); + Assert.IsFalse(caption.Contains("Lucia", StringComparison.Ordinal)); + + // Addresses: only site or CDN, and the file extension. + StringAssert.StartsWith(item["url"]!.GetValue(), "https://cdn.esempio/"); + StringAssert.EndsWith(item["url"]!.GetValue(), ".jpg"); + StringAssert.StartsWith(item["pagina"]!.GetValue(), "https://sito.esempio/"); + StringAssert.StartsWith(cleaned["descrittore"]!["indirizzo"]!.GetValue(), "https://sito.esempio/"); + + // Keys that look like identifiers are replaced too. + var key = body["per_id"]!.AsObject().Single().Key; + Assert.AreNotEqual("17841400123456", key); + Assert.AreEqual(14, key.Length); + + var verify = SampleVerifier.Verify(raw, clean); + Assert.IsTrue(verify.Passed, string.Join("; ", verify.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind}"))); + Assert.IsTrue(verify.CheckedTokens > 10); + } + + [TestMethod] + public void TheVerificationFailsWhenARawValueSurvivesAndDoesNotPrintIt() + { + using var temp = new TempFolder("ripulitura"); + var raw = Directory.CreateDirectory(temp.Combine("grezzi")).FullName; + File.WriteAllText(Path.Combine(raw, "000001.json"), RawSample); + var clean = temp.Combine("ripuliti"); + new SampleSanitizer().SanitizeFolder(raw, clean); + + // Someone «fixes» a cleaned file by hand and puts a real name back. + var path = Path.Combine(clean, "000001.json"); + var node = JsonNode.Parse(File.ReadAllText(path))!; + node["corpo"]!["elementi"]![0]!["didascalia"] = "nota: lucia.bianchi"; + File.WriteAllText(path, node.ToJsonString()); + + var report = SampleVerifier.Verify(raw, clean); + Assert.IsFalse(report.Passed); + Assert.IsTrue(report.Leaks.All(l => l.CleanFile == "000001.json")); + Assert.IsTrue(report.Leaks.Any(l => l.Kind == "lettere")); + foreach (var leak in report.Leaks) + { + Assert.IsFalse(leak.ToString().Contains("lucia", StringComparison.OrdinalIgnoreCase), "Where, never what."); + } + + // A raw copy is the worst case. + var copy = temp.Combine("copia"); + Directory.CreateDirectory(copy); + File.Copy(Path.Combine(raw, "000001.json"), Path.Combine(copy, "000001.json")); + Assert.IsTrue(SampleVerifier.Verify(raw, copy).Leaks.Count > 5); + + // A missing cleaned file fails too. + File.Delete(path); + Assert.IsFalse(SampleVerifier.Verify(raw, clean).Passed); + } + + [TestMethod] + public void TheCleanFolderCannotBeInsideTheRawOne() + { + using var temp = new TempFolder("ripulitura"); + var raw = Directory.CreateDirectory(temp.Combine("grezzi")).FullName; + File.WriteAllText(Path.Combine(raw, "000001.json"), "{}"); + Assert.ThrowsExactly(() => new SampleSanitizer().SanitizeFolder(raw, Path.Combine(raw, "ripuliti"))); + } + + [TestMethod] + public void RawSamplesAreRefusedInsideAGitRepository() + { + using var temp = new TempFolder("sonda"); + Directory.CreateDirectory(temp.Combine("progetto", ".git")); + var inside = temp.Combine("progetto", "campioni", "grezzi"); + Assert.AreEqual(temp.Combine("progetto"), RepositoryGuard.FindRepository(inside)); + var refused = Assert.ThrowsExactly(() => RepositoryGuard.EnsureOutside(inside)); + StringAssert.Contains(refused.Message, "fuori dal repository"); + RepositoryGuard.EnsureOutside(temp.Combine("altrove")); + + // A worktree has a «.git» file instead of a folder: refused too. + Directory.CreateDirectory(temp.Combine("albero")); + File.WriteAllText(temp.Combine("albero", ".git"), "gitdir: /altrove/.git/worktrees/albero\n"); + Assert.IsNotNull(RepositoryGuard.FindRepository(temp.Combine("albero", "campioni"))); + } + + [TestMethod] + public void TheAllowlistIsShortAndExplicit() + { + var allow = SanitizerAllowlist.Default; + Assert.AreEqual(AllowedField.Dimension, allow.FieldOf("original_width")); + Assert.AreEqual(AllowedField.Date, allow.FieldOf("expiring_at")); + Assert.AreEqual(AllowedField.Count, allow.FieldOf("comment_count")); + Assert.AreEqual(AllowedField.None, allow.FieldOf("username")); + Assert.AreEqual(AllowedField.None, allow.FieldOf("caption")); + Assert.IsTrue(allow.KeepsString("media_type", "video")); + Assert.IsFalse(allow.KeepsString("media_type", "una frase lunga con 12345 cifre"), "A code must look like a code."); + Assert.IsTrue(allow.KeepsString("pubblicato", "2026-10-13T08:00:00Z")); + Assert.IsFalse(allow.KeepsString("pubblicato", "ieri sera")); + Assert.IsFalse(allow.KeepsString("width", "1080"), "Dimensions keep numbers only."); + } + + [TestMethod] + public void AddressesOutsideSiteAndCdnAreMarkedAsOther() + { + var sanitizer = new SampleSanitizer(hosts: new HostClassifier(["127.0.0.1"], ["127.0.0.2"])); + var node = sanitizer.Sanitize(JsonNode.Parse("""{"a":"http://127.0.0.2:8482/m/f1/960x1200.jpg?scad=1&firma=x","b":"http://127.0.0.1:8481/profilo/marta.prova/","c":"https://esterno.example/x.webp"}"""))!; + StringAssert.StartsWith(node["a"]!.GetValue(), "https://cdn.esempio/"); + StringAssert.EndsWith(node["a"]!.GetValue(), ".jpg"); + Assert.IsFalse(node["b"]!.GetValue().Contains("prova", StringComparison.Ordinal), "A user name after a dot is not an extension."); + StringAssert.StartsWith(node["c"]!.GetValue(), "https://altro.esempio/"); + StringAssert.EndsWith(node["c"]!.GetValue(), ".webp"); + } + + [TestMethod] + public void TheProbeReadsOnlyThroughAReadOnlyScript() => + Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(ProbeRecorder.InteractionScript); + + [TestMethod] + public void TheCleanedSamplesInTheRepositoryAreCleanedSamples() + { + // Every file of tests/campioni/prova comes out of «ripulisci»: fake addresses, no address of the test site. + foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "prova"), "*.json")) + { + var text = File.ReadAllText(file); + Assert.IsFalse(text.Contains("127.0.0.", StringComparison.Ordinal), file); + Assert.IsFalse(text.Contains("prova\"", StringComparison.Ordinal), file); + using var document = JsonDocument.Parse(text); + Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _)); + } + } +} diff --git a/tests/Febe.Tests/Collection/SignalTests.cs b/tests/Febe.Tests/Collection/SignalTests.cs index 0287a78..ff40764 100644 --- a/tests/Febe.Tests/Collection/SignalTests.cs +++ b/tests/Febe.Tests/Collection/SignalTests.cs @@ -24,7 +24,8 @@ public sealed class SignalTests var testSite = SignalRules.LoadTestSite(); Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "segnali.prova.json"))); - Assert.AreEqual(4, testSite.Rules.Count); + Assert.AreEqual(5, testSite.Rules.Count); + Assert.IsTrue(testSite.Rules.Any(r => r.Code == "session-ended-url" && r.Level == SignalLevel.Disconnect)); } [TestMethod] diff --git a/tests/Febe.Tests/Collection/StopAndDownloadIntegrationTests.cs b/tests/Febe.Tests/Collection/StopAndDownloadIntegrationTests.cs new file mode 100644 index 0000000..6473514 --- /dev/null +++ b/tests/Febe.Tests/Collection/StopAndDownloadIntegrationTests.cs @@ -0,0 +1,254 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Collection.Downloads; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.SitoDiProva; +using Febe.Tests.Collection.Support; + +namespace Febe.Tests.Collection; + +/// +/// Stop signals (spec §7.6) and the download queue (spec §6.5) against the local test site with a real Chromium. +/// +[TestClass] +[DoNotParallelize] +public sealed class StopAndDownloadIntegrationTests +{ + private static SharedChromium? s_chromium; + private static string? s_unavailable; + + public TestContext TestContext { get; set; } = null!; + + private static SharedChromium Chromium => s_chromium ?? throw new InvalidOperationException("Browser non avviato."); + + [ClassInitialize] + public static async Task StartAsync(TestContext context) + { + s_unavailable = SharedChromium.UnavailableReason(); + if (s_unavailable is null) + { + s_chromium = await SharedChromium.StartAsync(); + } + } + + [ClassCleanup] + public static async Task StopAsync() + { + if (s_chromium is not null) + { + await s_chromium.DisposeAsync(); + s_chromium = null; + } + } + + [TestInitialize] + public void RequireBrowser() + { + if (s_unavailable is not null) + { + Assert.Inconclusive(s_unavailable); + } + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task Http429StopsTheRecipeWithAThrottleSignal() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + h.Site.Control.Set(StopMode.TooManyRequests); + + var outcome = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message); + var signal = h.Breaker.Signals.Single(); + Assert.AreEqual(SignalLevel.Throttle, signal.Level); + Assert.AreEqual("http-429", signal.Code); + Assert.AreEqual(0, (await h.Db.Entries.ListByAccountAsync(marta.Id)).Count); + Assert.AreEqual("/profilo/marta.prova/", await h.CurrentPathAsync(), "The page is left as it is."); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AVerificationPageStopsEverythingAndIsLeftOnScreen() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + h.Site.Control.Set(StopMode.Challenge); + + var outcome = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message); + Assert.AreEqual(SignalLevel.Challenge, h.Breaker.Signals[0].Level); + Assert.AreEqual("challenge-url", h.Breaker.Signals[0].Code); + Assert.AreEqual("/verifica", await h.CurrentPathAsync()); + Assert.AreEqual(0, h.Governor.Requests.Count(r => r.Kind != ActionKind.ProfileOpen), "Nothing after the signal."); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AnEndedSessionIsADisconnectionAndFebeNeverTriesToComeBack() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + h.Site.Control.Set(StopMode.SessionEnded); + + var outcome = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message); + Assert.AreEqual(SignalLevel.Disconnect, h.Breaker.Signals[0].Level); + Assert.AreEqual("/sessione-scaduta", await h.CurrentPathAsync()); + Assert.IsFalse(await h.Driver.HasSessionCookieAsync(CancellationToken.None) ?? true, "The session cookie is gone."); + + // The next recipe sees the missing cookie before touching the site. + h.Site.Control.Reset(); + var next = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.StoppedBySignal, next.Status, next.Message); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.ProfileOpen), "No new attempt on the site."); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ASignalInTheMiddleOfABackfillStopsItWhereItIsKeepingWhatWasRead() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var luca = await h.AddAccountAsync("luca.prova"); + h.Site.Control.Set(StopMode.TooManyRequests, afterDataRequests: 1); + + var outcome = await h.RunAsync(RecipeKind.Backfill, luca.Id, maxPages: 3); + Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message); + Assert.AreEqual(12, (await h.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post })).Count, "The first page is kept."); + Assert.AreEqual("c12", (await h.Db.Accounts.GetAsync(luca.Id))!.BackfillCursor); + Assert.AreEqual(1, h.Governor.Granted(ActionKind.BackfillPage), "The permit of the page that got 429 was used; no more."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task ThreeEmptyPagesInARowAreAThrottleSignal() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var marta = await h.AddAccountAsync("marta.prova"); + h.Site.Control.Set(StopMode.EmptyPages); + + var first = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + var second = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message); + Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message); + Assert.AreEqual(0, h.Breaker.Signals.Count); + var third = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.StoppedBySignal, third.Status, third.Message); + Assert.AreEqual("empty-pages", h.Breaker.Signals.Single().Code); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AnUnknownResponseShapeStopsTheRecipeWithTheKeyStructureOnly() + { + await using var h = await CollectionHarness.CreateAsync(Chromium, new Febe.Core.Collection.Recipes.RecipeOptions { DataTimeout = TimeSpan.FromSeconds(8) }); + var marta = await h.AddAccountAsync("marta.prova"); + h.Site.Control.Set(StopMode.UnknownFormat); + + var outcome = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id); + Assert.AreEqual(RecipeStatus.UnrecognizedFormat, outcome.Status, outcome.Message); + var evt = (await h.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == "formato-non-riconosciuto"); + StringAssert.Contains(evt.Message, "{risposta:{voci:[{chiave,valore,dettagli:{x}}]},versione}"); + Assert.IsFalse(evt.Message.Contains("formato nuovo", StringComparison.Ordinal), "Only the structure, never the values."); + Assert.IsTrue((await h.Db.Accounts.GetAsync(marta.Id))!.Notices.HasFlag(AccountNotices.UnrecognizedFormat), "«Da controllare»."); + Assert.AreEqual(0, h.Breaker.Signals.Count, "A new format is not a stop signal."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task DownloadsArriveIntactInTheLibraryWithTheirNames() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var nadia = await h.AddAccountAsync("nadia.prova", a => a with { Limits = a.Limits with { StoryVideos = false } }); + var marta = await h.AddAccountAsync("marta.prova", a => a with { Limits = a.Limits with { StoryVideos = false } }); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.ProfileCheck, nadia.Id)).Status); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.AccountStories, marta.Id)).Status); + var pending = await h.Db.Media.CountPendingDownloadsAsync(); + Assert.IsTrue(pending >= 7, $"{pending} file in attesa."); + + // Downloads go through the frame of the page on screen (a page of the site). From the blank rest page Chromium + // refuses local addresses (net::ERR_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_CHECKS): an artefact of the local CDN on + // 127.0.0.2, to be measured with the real CDN in M0 (H7). See docs/sonda/esito.md. + var report = await h.Downloads.RunOnceAsync(CancellationToken.None); + Assert.AreEqual(0, report.Failed + report.Expired + report.Retried, report.ToString()); + Assert.AreEqual(pending, report.Stored, report.ToString()); + Assert.AreEqual(0, await h.Db.Media.CountPendingDownloadsAsync()); + Assert.IsTrue(h.DataBudget.Used > 0, "Bytes count toward the daily data budget."); + + var posts = await h.Db.Entries.ListByAccountAsync(nadia.Id, new EntryListOptions { Kind = EntryKind.Post }); + foreach (var post in posts) + { + var file = (await h.Db.Media.ListByEntryAsync(post.Id)).Single(); + Assert.AreEqual(MediaState.Downloaded, file.State); + var path = h.Library.Layout.FullPath(nadia, file.RelativePath!); + Assert.IsTrue(File.Exists(path), path); + StringAssert.StartsWith(file.RelativePath, $"post/{LocalCalendar.ToLocal(post.PublishedAt, h.Clock.LocalZone).Year}/"); + StringAssert.EndsWith(file.RelativePath, $"_{post.Code}_1.jpg"); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path))), file.Sha256); + var served = h.Site.Media.Picture(h.Site.World.FindPost(post.Code!)!.Files[0].MediaKey, 960, 1200); + CollectionAssert.AreEqual(served, await File.ReadAllBytesAsync(path), "The largest version, byte for byte."); + Assert.IsNull(file.SourceUrl, "Signed addresses are dropped once the file is saved."); + } + + var picture = (await h.Db.Entries.ListByAccountAsync(nadia.Id, new EntryListOptions { Kind = EntryKind.ProfilePicture })).Single(); + var pictureFile = (await h.Db.Media.ListByEntryAsync(picture.Id)).Single(); + StringAssert.StartsWith(pictureFile.RelativePath, "profilo/"); + StringAssert.EndsWith(pictureFile.RelativePath, $"_{pictureFile.Sha256![..8]}_1.jpg", "Profile pictures are named by the first eight hex digits of their SHA-256."); + + var stories = await h.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Story }); + var video = (await Task.WhenAll(stories.Select(s => h.Db.Media.ListByEntryAsync(s.Id)))).SelectMany(m => m).Single(m => m.Kind == MediaKind.Video); + Assert.AreEqual(MediaState.Skipped, video.State, "«Video delle storie» is off for Marta: never downloaded."); + Assert.IsTrue(File.Exists(Path.Combine(h.Library.Layout.AccountFolder(nadia), "_febe.jsonl")), "The account journal is written."); + Assert.AreEqual(0, Directory.EnumerateFiles(h.Temp.Combine("dati", "temporanei")).Count(), "No temporary file left behind."); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task AnExpiredAddressIsRecoveredThroughSinglePost() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var nadia = await h.AddAccountAsync("nadia.prova"); + h.Site.Control.AddressLifetime = TimeSpan.FromSeconds(1); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.ProfileCheck, nadia.Id)).Status); + await Task.Delay(TimeSpan.FromSeconds(2.2)); + + var expired = await h.Downloads.RunOnceAsync(CancellationToken.None); + Assert.AreEqual(0, expired.Stored); + Assert.AreEqual(4, expired.Expired, "Three posts and the profile picture."); + Assert.IsTrue(h.Site.Control.CdnExpired >= 4); + var tasks = (await h.Db.Tasks.ListPendingAsync(100)).Where(t => t.Kind == EngineTaskKind.SinglePost).ToList(); + Assert.AreEqual(3, tasks.Count, "One «Post singolo» per post; none for the profile picture."); + + h.Site.Control.AddressLifetime = TimeSpan.FromHours(6); + foreach (var task in tasks) + { + var outcome = await h.RunAsync(RecipeKind.SinglePost, task.AccountId, long.Parse(task.Payload!, System.Globalization.CultureInfo.InvariantCulture)); + Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message); + } + + var recovered = await h.Downloads.RunOnceAsync(CancellationToken.None); + Assert.AreEqual(3, recovered.Stored, recovered.ToString()); + var posts = await h.Db.Entries.ListByAccountAsync(nadia.Id, new EntryListOptions { Kind = EntryKind.Post }); + Assert.IsTrue(posts.All(p => p.State == EntryState.Downloaded)); + } + + [TestMethod] + [Timeout(90_000, CooperativeCancellation = true)] + public async Task DownloadsGoOnWhileTheSiteIsStoppedByAVerification() + { + await using var h = await CollectionHarness.CreateAsync(Chromium); + var nadia = await h.AddAccountAsync("nadia.prova"); + Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.ProfileCheck, nadia.Id)).Status); + h.Site.Control.Set(StopMode.Challenge); + Assert.AreEqual(RecipeStatus.StoppedBySignal, (await h.RunAsync(RecipeKind.ProfileCheck, nadia.Id)).Status); + Assert.AreEqual("/verifica", await h.CurrentPathAsync()); + + // The page stays on the verification: the queue downloads from the CDN without touching the site. + var report = await h.Downloads.RunOnceAsync(CancellationToken.None); + Assert.AreEqual(4, report.Stored, "Files already queued come from the CDN, not the site (spec §7.6)."); + Assert.AreEqual("/verifica", await h.CurrentPathAsync(), "Still on the verification page."); + } +} diff --git a/tests/Febe.Tests/Collection/Support/CollectionFakes.cs b/tests/Febe.Tests/Collection/Support/CollectionFakes.cs new file mode 100644 index 0000000..70c7809 --- /dev/null +++ b/tests/Febe.Tests/Collection/Support/CollectionFakes.cs @@ -0,0 +1,121 @@ +using System.Collections.Concurrent; +using Febe.Core.Abstractions; +using Febe.Core.Collection.Recipes; +using Febe.Core.Engine; + +namespace Febe.Tests.Collection.Support; + +/// +/// A clock that compresses time: waits for real only a fraction of the requested time, and +/// moves on by the whole of it. Recipes against a real browser keep their order of events, but a +/// 2.2-second «wait after load» lasts a few hundred milliseconds. +/// +public sealed class CompressedClock : IClock +{ + private readonly Lock _gate = new(); + private TimeSpan _offset; + + public CompressedClock(double factor = 10, TimeZoneInfo? zone = null) + { + Factor = factor; + LocalZone = zone ?? TimeZoneInfo.Utc; + } + + public double Factor { get; } + + public TimeZoneInfo LocalZone { get; } + + public DateTimeOffset Now + { + get + { + lock (_gate) + { + return DateTimeOffset.UtcNow + _offset; + } + } + } + + public async Task Delay(TimeSpan time, CancellationToken ct) + { + if (time <= TimeSpan.Zero) + { + ct.ThrowIfCancellationRequested(); + return; + } + + var real = TimeSpan.FromTicks((long)(time.Ticks / Factor)); + if (real >= TimeSpan.FromMilliseconds(1)) + { + await Task.Delay(real, ct).ConfigureAwait(false); + } + else + { + ct.ThrowIfCancellationRequested(); + await Task.Yield(); + } + + lock (_gate) + { + _offset += time - real; + } + } +} + +/// +/// A Governor that grants everything, records each request and can refuse a category after a number of grants +/// (to test the orderly stop of the recipes). Never used outside tests. +/// +public sealed class PermissiveGovernor : IGovernor, IBudgetView +{ + private readonly ConcurrentQueue<(ActionKind Kind, long? AccountId)> _requests = new(); + private readonly ConcurrentDictionary _limits = new(); + private readonly ConcurrentDictionary _granted = new(); + + public IReadOnlyList<(ActionKind Kind, long? AccountId)> Requests => [.. _requests]; + + /// Remaining budget reported to when no limit is set. + public int ReportedRemaining { get; set; } = 1000; + + public int Granted(ActionKind kind) => _granted.TryGetValue(kind, out var n) ? n : 0; + + /// After granted requests of , the next ones are refused. + public void Limit(ActionKind kind, int grants) => _limits[kind] = grants; + + public Task RequestAsync(ActionKind kind, long? accountId, CancellationToken ct) + { + _requests.Enqueue((kind, accountId)); + if (_limits.TryGetValue(kind, out var limit) && Granted(kind) >= limit) + { + return Task.FromResult(Permit.Deny(kind, accountId, DenialReason.HourlyBudgetReached, "Tetto orario raggiunto (prova).")); + } + + _granted.AddOrUpdate(kind, 1, (_, n) => n + 1); + return Task.FromResult(Permit.Grant(kind, accountId)); + } + + public Task RemainingAsync(ActionKind kind, long? accountId, CancellationToken ct) => + Task.FromResult(_limits.TryGetValue(kind, out var limit) ? Math.Max(0, limit - Granted(kind)) : ReportedRemaining); +} + +/// A daily data budget kept in memory. +public sealed class FakeDataBudget(long bytesPerDay = long.MaxValue / 4) : IDataBudget +{ + private long _used; + + public long Used => Interlocked.Read(ref _used); + + public Task RemainingTodayAsync(CancellationToken ct) => Task.FromResult(Math.Max(0, bytesPerDay - Used)); + + public Task RecordAsync(long bytes, long? accountId, CancellationToken ct) + { + Interlocked.Add(ref _used, bytes); + return Task.CompletedTask; + } +} + +/// A session context for one test. +public sealed record TestSession(long SessionId = 1, double Mood = 1.0) : ISessionContext +{ + public DateTimeOffset PlannedEnd { get; init; } = DateTimeOffset.MaxValue; +} diff --git a/tests/Febe.Tests/Collection/Support/CollectionHarness.cs b/tests/Febe.Tests/Collection/Support/CollectionHarness.cs new file mode 100644 index 0000000..f438f3a --- /dev/null +++ b/tests/Febe.Tests/Collection/Support/CollectionHarness.cs @@ -0,0 +1,207 @@ +using System.Collections.Concurrent; +using Febe.Browser.Capture; +using Febe.Browser.Cdp; +using Febe.Browser.Diagnostics; +using Febe.Browser.Download; +using Febe.Browser.Hosting; +using Febe.Browser.Recipes; +using Febe.Browser.Targets; +using Febe.Core.Abstractions; +using Febe.Core.Collection; +using Febe.Core.Collection.Downloads; +using Febe.Core.Collection.Readers; +using Febe.Core.Collection.Recipes; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.SitoDiProva; +using Febe.Tests.Browser.TestSupport; +using Febe.Tests.Support; + +namespace Febe.Tests.Collection.Support; + +/// +/// One Chromium on a private Xvfb display, shared by a test class (the collection tests run one at a time). +/// +public sealed class SharedChromium : IAsyncDisposable +{ + private SharedChromium(XvfbProcess xvfb, ChromiumProcessHost host, string profile, ConcurrentQueue log) + { + Xvfb = xvfb; + Host = host; + Profile = profile; + Log = log; + } + + public XvfbProcess Xvfb { get; } + + public ChromiumProcessHost Host { get; } + + public string Profile { get; } + + public ConcurrentQueue Log { get; } + + public ICdpSession Cdp => Host.Cdp; + + public static string? UnavailableReason() => RealBrowser.UnavailableReason(); + + public static async Task StartAsync() + { + var display = XvfbProcess.FindFreeDisplay(200, 299) ?? throw new InvalidOperationException("Nessun display libero."); + var log = new ConcurrentQueue(); + var browserLog = new DelegateBrowserLog((level, message, ex) => log.Enqueue($"{level}: {message} {ex?.Message}")); + var xvfb = new XvfbProcess(display, 1280, 900, log: browserLog); + await xvfb.StartAsync(CancellationToken.None); + var profile = Path.Combine(Path.GetTempPath(), "febe-raccolta-" + Guid.NewGuid().ToString("N")); + var host = new ChromiumProcessHost( + new ChromiumLaunchOptions { NoSandbox = RealBrowser.IsRoot, Environment = RealBrowser.BrowserEnvironment }, + log: browserLog); + try + { + await host.StartAsync(new BrowserOptions(profile, 1280, 900, LocalTestSite.FreePort(), RealBrowser.ChromiumPath(), display), CancellationToken.None); + } + catch + { + await host.DisposeAsync(); + await xvfb.DisposeAsync(); + throw; + } + + return new SharedChromium(xvfb, host, profile, log); + } + + public async ValueTask DisposeAsync() + { + await Host.DisposeAsync(); + await Xvfb.DisposeAsync(); + RealBrowser.TryDelete(Profile); + } +} + +/// +/// Everything one collection test needs, built fresh: the test site, the capture on the shared browser, the stop +/// signals, a library with its database, the page driver, the recipe runner and the download queue. +/// +internal sealed class CollectionHarness : IAsyncDisposable +{ + private CollectionHarness(SharedChromium chromium, TestSite site, TempFolder temp, TestLibrary library, CompressedClock clock) + { + Chromium = chromium; + Site = site; + Temp = temp; + Library = library; + Clock = clock; + } + + public SharedChromium Chromium { get; } + + public TestSite Site { get; } + + public TempFolder Temp { get; } + + public TestLibrary Library { get; } + + public CompressedClock Clock { get; } + + public CollectionPipeline Pipeline { get; private set; } = null!; + + public HostClassifier Hosts => new([Site.SiteHost], [Site.CdnHost]); + + public RecordingBreaker Breaker { get; } = new(); + + public PermissiveGovernor Governor { get; } = new(); + + public FakeDataBudget DataBudget { get; } = new(); + + public SignalDetector Signals => Pipeline.Signals; + + public CaptureCollector Capture => Pipeline.Capture; + + public BrowserPageDriver Driver => Pipeline.Driver; + + public RecipeRunner Runner => Pipeline.Runner; + + public DownloadQueue Downloads => Pipeline.Downloads; + + public Febe.Data.FebeDatabase Db => Library.Db; + + /// The engine session the recipes run in (a real row: events refer to it). + public TestSession Session { get; private set; } = new(); + + public static async Task CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10) + { + var site = await TestSite.StartAsync(new TestSiteOptions()); + var temp = new TempFolder("raccolta"); + var library = await TestLibrary.CreateAsync(temp); + var clock = new CompressedClock(factor, TestZones.Rome); + var harness = new CollectionHarness(chromium, site, temp, library, clock); + harness.Pipeline = await CollectionPipeline.StartAsync(new CollectionPipelineOptions + { + Cdp = chromium.Cdp, + Site = CollectionSite.TestSite(site.SiteHost, site.CdnHost), + Storage = library.Db, + Ingest = library.Ingest, + Governor = harness.Governor, + DataBudget = harness.DataBudget, + Breaker = harness.Breaker, + Clock = clock, + Random = new SeededRandom(20261013), + StagingFolder = temp.Combine("dati", "temporanei"), + Recipes = options ?? new RecipeOptions(), + }); + harness.Session = new TestSession((await library.Db.Sessions.StartAsync(clock.Now)).Id); + await harness.SignInAsync(); + return harness; + } + + /// + /// What Alberto does by hand before the engine runs: opens the site once, so that its session cookie exists (the + /// test site has no login form: the first visit starts the session). Then the browser goes back to rest. + /// + public async Task SignInAsync() + { + await Chromium.Cdp.NavigateAsync(Site.Url("/benvenuto")); + await Chromium.Cdp.WaitForLoadAsync(new Febe.Core.Abstractions.SystemClock(), TimeSpan.FromSeconds(10)); + await Chromium.Cdp.RestAsync(); + } + + /// Adds an account as Alberto would (by name, from the test site's world). + public async Task AddAccountAsync(string username, Func? change = null, bool withId = true) + { + string? id; + bool followed; + lock (Site.World.Gate) + { + var site = Site.World.FindByUsername(username); + id = site?.Id; + followed = site?.FollowedByViewer ?? false; + } + + var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome) with + { + InstagramId = withId ? id : null, + IsFollowed = followed, + }; + return await Db.Accounts.AddAsync(change is null ? account : change(account)); + } + + public Task RunAsync(RecipeKind kind, long? accountId = null, long? entryId = null, string? highlightId = null, int? maxPages = null) => + Runner.RunAsync(new RecipeRequest(kind, accountId, entryId, highlightId, maxPages), Session, CancellationToken.None); + + public Task CurrentPathAsync() => Driver.CurrentPathAsync(CancellationToken.None); + + public async ValueTask DisposeAsync() + { + await Pipeline.DisposeAsync(); + try + { + await Chromium.Cdp.RestAsync(); + } + catch (Exception ex) when (ex is CdpCommandException or BrowserUnavailableException or CdpDisconnectedException) + { + } + + await Site.DisposeAsync(); + await Library.DisposeAsync(); + Temp.Dispose(); + } +} diff --git a/tests/Febe.Tests/campioni/prova/000001-inizio.json b/tests/Febe.Tests/campioni/prova/000001-inizio.json new file mode 100644 index 0000000..1778052 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000001-inizio.json @@ -0,0 +1,298 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/76vtw613mz1q79w5", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "jhglrd" + }, + "corpo": { + "io": { + "numero": "8955", + "nome": "hlzthnx.jnxdk" + }, + "barra": [ + { + "numero": "5555", + "nome": "ndkwq.shzgd", + "nome_visibile": "Pxkjk gx xrfpm", + "riservato": false, + "seguito": true, + "pubblicazioni": 18, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/23wh5n049rr81521.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/h46r930r17f94226.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T15:11:20Z" + }, + { + "numero": "5966", + "nome": "mkntl.vqwhn", + "nome_visibile": "Rjlvk dh bknnh", + "riservato": false, + "seguito": true, + "pubblicazioni": 3, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/064248847xjl13s4.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/8w293gphn3jlm641.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T14:16:20Z" + }, + { + "numero": "0256", + "nome": "lcfs.gwcfg", + "nome_visibile": "Pnhm ll rrhml", + "riservato": false, + "seguito": true, + "pubblicazioni": 40, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/4z7l3q070rf331lb.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/j793r3nmp3m7j334.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T13:28:20Z" + }, + { + "numero": "6473", + "nome": "jscnhk.hsjhd", + "nome_visibile": "Gjcpzg pz xxrgj", + "riservato": true, + "seguito": true, + "pubblicazioni": 6, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/2dx14g1d9l3p3q74.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/g7g12rt483170931.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T12:29:20Z" + } + ], + "contenuti": [ + { + "numero": "3302689957", + "sigla": "8rcvdWt", + "pubblicato": "2026-10-10T14:48:20Z", + "testo": "Vcl dhzqkwhc jzp qhjbrnjb z shldz (zrlhx 432)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/0d6d26g8r5935972.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/x34032202148491c.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/83w592bg386k8609.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/90qk240653054970.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/v7gs5c4676403p19.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "5977241902", + "sigla": "kkjHtrm", + "pubblicato": "2026-10-09T17:18:20Z", + "testo": "Kdf lbrnqkhp jgp rlndgtxfhz c lpftbkpg (jwsvd 617)", + "fissato": false, + "autore": { + "numero": "5966", + "nome": "mkntl.vqwhn" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/bz06230s32v5302j.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/d4nh46r5232dm305.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/g287z3d071z69416.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "8040221611", + "sigla": "B7hR3PV", + "pubblicato": "2026-10-09T02:06:20Z", + "testo": "Zmx kdcdxtxd qsh czsmsbj r drzg (hvzlw 775)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/1718b0k40tg62335.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/67qg4t1f22l1l42d.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/c64ktw348d4p7n5d.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "5713768118", + "sigla": "rChwmFc", + "pubblicato": "2026-10-08T18:19:20Z", + "testo": "Jvt gvtcxpmj kph gwclq d wxksn (ztvfv 460)", + "fissato": false, + "autore": { + "numero": "6473", + "nome": "jscnhk.hsjhd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/0tj7n92s2t48021m.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/00st4z0v3lh55b8m.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/gpgkr6087n24455l.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "5060179360", + "sigla": "1D2tpsn", + "pubblicato": "2026-10-08T10:57:20Z", + "testo": "Dzm zbvgfxtg hmt szkmh k kpxhmjjbj (vjcrg 561)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/7z3z1l84nx9027lp.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/7d53931df99139s8.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/gf06gf6q767b2961.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "6686720181", + "sigla": "TqwwCvG", + "pubblicato": "2026-10-07T10:47:20Z", + "testo": "Dqr cldxlrdk lxc nwlszbwr v blhfr (mtqhp 671)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "parti": [ + { + "numero": "4391148625", + "foto": [ + { + "indirizzo": "https://cdn.esempio/zhzj06v06q4p7746.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/r85287t3l0f8937z.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/1z5tdb2994zbq0h0.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "parti_totali": 3 + } + ], + "pagina": { + "altro": true, + "dopo": "w3" + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000002-profilo-pubblico.json b/tests/Febe.Tests/campioni/prova/000002-profilo-pubblico.json new file mode 100644 index 0000000..b5f0ef3 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000002-profilo-pubblico.json @@ -0,0 +1,637 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/52bf0789xw73302n", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "hpccwvk-zvcgqkrc" + }, + "corpo": { + "profilo": { + "numero": "5555", + "nome": "ndkwq.shzgd", + "nome_visibile": "Pxkjk gx xrfpm", + "riservato": false, + "seguito": true, + "pubblicazioni": 18, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/23wh5n049rr81521.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/h46r930r17f94226.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T15:11:20Z" + }, + "raccolte": [ + { + "numero": "3688348931", + "titolo": "Wxmngt", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "copertina": { + "indirizzo": "https://cdn.esempio/1z6s13040g7z0691.jpg", + "larghezza": 160, + "altezza": 284 + } + }, + { + "numero": "3331216123", + "titolo": "Jpjhhx", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "copertina": { + "indirizzo": "https://cdn.esempio/0p2jfc2b0263j919.jpg", + "larghezza": 160, + "altezza": 284 + } + } + ], + "contenuti": [ + { + "numero": "0550913031", + "sigla": "jdd5w0f", + "pubblicato": "2026-09-28T00:28:20Z", + "testo": "Snz qfprnqzz zvp tcrltrwh k kgxq (hnnrv 634)", + "fissato": true, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/9948hlb7bb0ltqd3.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/28sh466jsc774p89.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/655qhv6z280782j5.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "6157292435", + "sigla": "8lHWJPg", + "pubblicato": "2026-09-21T16:40:20Z", + "testo": "Tbv mrfdlhmf lml nwrrdhnz k mnszp (gnglb 25)", + "fissato": true, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "parti": [ + { + "numero": "1552522150", + "foto": [ + { + "indirizzo": "https://cdn.esempio/3vf1c1n1mk43w89b.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/2221008r9z272t9h.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/5333k8w0996b3979.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "4565425648", + "filmati": [ + { + "indirizzo": "https://cdn.esempio/64tm3nnd6nq4940q.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/074212n7q00c2r00.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/ms25598364j44g7b.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/89663vt1nm66h24r.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/6m70rr25412np086.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "8323338275", + "foto": [ + { + "indirizzo": "https://cdn.esempio/k80njbg871fwg77b.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/c383cwr827pz18w4.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/415h8k26359x102r.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "parti_totali": 3 + }, + { + "numero": "3302689957", + "sigla": "8rcvdWt", + "pubblicato": "2026-10-10T14:48:20Z", + "testo": "Vcl dhzqkwhc jzp qhjbrnjb z shldz (zrlhx 432)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/0d6d26g8r5935972.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/x34032202148491c.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/83w592bg386k8609.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/90qk240653054970.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/v7gs5c4676403p19.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "8040221611", + "sigla": "B7hR3PV", + "pubblicato": "2026-10-09T02:06:20Z", + "testo": "Zmx kdcdxtxd qsh czsmsbj r drzg (hvzlw 775)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/1718b0k40tg62335.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/67qg4t1f22l1l42d.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/c64ktw348d4p7n5d.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "6686720181", + "sigla": "TqwwCvG", + "pubblicato": "2026-10-07T10:47:20Z", + "testo": "Dqr cldxlrdk lxc nwlszbwr v blhfr (mtqhp 671)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "parti": [ + { + "numero": "4391148625", + "foto": [ + { + "indirizzo": "https://cdn.esempio/zhzj06v06q4p7746.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/r85287t3l0f8937z.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/1z5tdb2994zbq0h0.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "9823770084", + "filmati": [ + { + "indirizzo": "https://cdn.esempio/wnr19826v154499b.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/q9v6mwrtbsv0xdw9.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/d9fgg81s94s0764w.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/48f0c0s2bkx7d256.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/715z79k6z3004ss1.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "8883127657", + "foto": [ + { + "indirizzo": "https://cdn.esempio/dfn95518270592f7.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/5095893x3k0780c6.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/t5ks39vq5zc981h8.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "parti_totali": 3 + }, + { + "numero": "6321126038", + "sigla": "jC81Q1b", + "pubblicato": "2026-10-05T23:37:20Z", + "testo": "Ndr grbgdxxd lkj jbbgxntjq b frtphxbh (tmpxs 590)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/6qr19112751l69r3.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/44172102cn8s1g9j.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/bsw10n29mr3g3c8q.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7876082571", + "sigla": "xGp6LQj", + "pubblicato": "2026-10-04T07:09:20Z", + "testo": "Cch bbgmbhxr tml htbzj c nzpjxvjnxp (ktqpr 025)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/h3157zk405828529.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/fxcw0h67d1w013q8.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/cpb269088h89ckq1.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "0363675401", + "sigla": "FLPGT73", + "pubblicato": "2026-10-02T19:34:20Z", + "testo": "Tww fjftnpqq wrn rbzpm p bbpgtk (qwmhj 275)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/70257lc16jzmv587.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/g3s36fpb68s4j118.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/zp1t83g6hb6r284v.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/37f247ft8t2z24tv.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/3303cgh77jx8t0w2.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "6106657355", + "sigla": "hjffss2", + "pubblicato": "2026-10-01T04:31:20Z", + "testo": "Cvc qwvcppph prp bsdrxxjv h zqfzqmh (fggll 021)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/66978h1mbz738419.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/b67r858s5x24bzff.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/hm173vf286gvjv37.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7932098954", + "sigla": "j6rFHQP", + "pubblicato": "2026-09-29T15:10:20Z", + "testo": "Vxf hhgcppgv pwr wbrfjjnn c qvqk (cqtkz 783)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "parti": [ + { + "numero": "9313115541", + "foto": [ + { + "indirizzo": "https://cdn.esempio/91492575z3r074n2.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/8d14mm694fq3csjr.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/ws694k42w7j109qd.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7013138795", + "filmati": [ + { + "indirizzo": "https://cdn.esempio/150k4k3j9wrx002j.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/80r054t7451679xl.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/52777993sq4k5fqh.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/d3744z6wh03sk9s9.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/5318z833z608945f.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "3338324319", + "foto": [ + { + "indirizzo": "https://cdn.esempio/8ft1345rlt407k64.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/404fs3nw5wwd894h.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/8975t5cpc6283cj0.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "parti_totali": 3 + }, + { + "numero": "7580432133", + "sigla": "57FWWCj", + "pubblicato": "2026-09-26T10:32:20Z", + "testo": "Gvw rccrfrsb wkq fzkf w qvqrtnzs (pwjsk 33)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/2cg52f5r39bghv81.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/080qn88f2r477k51.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/n65p6024s3lf1097.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "1418527932", + "sigla": "k4C1jws", + "pubblicato": "2026-09-24T19:24:20Z", + "testo": "Dgq tqbnskfk tkg zntpm t ghdbr (whghc 553)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/fkdvr64wwvt45870.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/315q378h2j2kc438.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/17tr0k4c93c2x8s1.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/9p6rh8r2p59b4rm1.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/7lk12bk36tw2x771.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + } + ], + "pagina": { + "altro": true, + "dopo": "n17" + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000003-profilo-pagina-successiva.json b/tests/Febe.Tests/campioni/prova/000003-profilo-pagina-successiva.json new file mode 100644 index 0000000..db562da --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000003-profilo-pagina-successiva.json @@ -0,0 +1,386 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/rm07847qj48b3072", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "jmjzbwb-dgmhpn-zzhdhcwbwj" + }, + "corpo": { + "contenuti": [ + { + "numero": "4502918696", + "sigla": "dMjn3v6", + "pubblicato": "2026-09-15T12:11:20Z", + "testo": "Trj ghqgmknx xmp qdlhqxnw m thmntff (xcgpp 682)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/4n88hwj0x9g1b141.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/gx1566hm0b487358.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/h19402tsmm64h1w1.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "8765793363", + "sigla": "2mFPBfG", + "pubblicato": "2026-09-13T14:49:20Z", + "testo": "Rnn hmkpgplk bfn lkdglvd w zppfl (ntgxt 056)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/2176j6p843x8415k.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/9nlv8pt4c85691cl.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/0t098j299t1j1044.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "0874654136", + "sigla": "3ccFRmS", + "pubblicato": "2026-09-11T15:10:20Z", + "testo": "Mnx dnqppdzf wmm lxsxr q xtdzv (fmgsp 444)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/40r4q9138s675d7r.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/60p0673c2h42fmvs.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/0m57r379b1tc211p.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "3324924951", + "sigla": "Tvmhgpb", + "pubblicato": "2026-09-09T17:57:20Z", + "testo": "Zvr jgvnlfmw trc hlzzw j ktwjs (tdnvx 482)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/4c93295d27f61210.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/kt97k7rk4802h475.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/n390f17c7p1h4p6l.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/6z08483011j5h6c7.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/2611l36636120380.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "5525237871", + "sigla": "6fw0qb2", + "pubblicato": "2026-09-07T19:28:20Z", + "testo": "Skn wwdhxkfr kmc dhssbjmjxs x swhdmkxl (bqqqv 876)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/j2k75j49l79bjh8m.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/l190x2hw6444j45n.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/54wp51n3108k7612.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "3506125164", + "sigla": "w4NmPhQ", + "pubblicato": "2026-09-05T21:52:20Z", + "testo": "Crr krvpbfrc cps wsqfvsgflw p txmcncjg (pwwnb 023)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/91jg371b71ff4035.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/htpgr2xf9cc1dfm7.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/249j349vplkfk424.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7747667947", + "sigla": "WNKBMWR", + "pubblicato": "2026-09-04T00:02:20Z", + "testo": "Ggk rbzswhvr qcx tmgf h lbvm (dgqlp 118)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/zv1d386z67w7nwlp.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/c3x03056k9926jh7.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/053dnmkv3239v2k9.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7784024018", + "sigla": "FtRGXMW", + "pubblicato": "2026-09-02T02:28:20Z", + "testo": "Xcf ktkdbxtn dxj dddvd t jblnj (bzskb 889)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/485181h51lg19p0k.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/j3439ckkps53fw56.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/zhcdmwk908d2c09j.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7393153212", + "sigla": "zT6sJjr", + "pubblicato": "2026-08-31T02:42:20Z", + "testo": "Jwd jqdpbfnw zzm zcpv b xgftbnj (rnkqj 107)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/428w24271h77j75d.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/70607m5x574394xr.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/5rnq242tj9596137.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7891992286", + "sigla": "1QLdfRR", + "pubblicato": "2026-08-29T05:59:20Z", + "testo": "Chd xjtrnvbv jdk cnsqrvtb r nzqf (xdsbn 982)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/6p5479gc02jj6s0z.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/7t7hr2mr58zrtf7m.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/1013303rt707407w.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7565829130", + "sigla": "Z4P6dHK", + "pubblicato": "2026-08-27T07:43:20Z", + "testo": "Ckn pbpfcqxc lxs xqrqplpm c kjnkq (bpjls 661)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/18w20s1c506f3z80.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/5t91m91223j97b0t.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/6c61570xt4s0v1f4.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/j4719937j47xfg3v.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/57gsn441s4l10892.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "8103152571", + "sigla": "GSj6xlF", + "pubblicato": "2026-08-25T10:12:20Z", + "testo": "Zdh vdqbdgxp dsb blvb w hsss (sgblz 068)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/5p54377549062d10.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/067mt8003l6638jb.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/s9bz0ddl476trsh1.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "pagina": { + "altro": true, + "dopo": "n20" + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000004-profilo-privato-non-seguito.json b/tests/Febe.Tests/campioni/prova/000004-profilo-privato-non-seguito.json new file mode 100644 index 0000000..a8bff43 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000004-profilo-privato-non-seguito.json @@ -0,0 +1,37 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/25602tp1p503hv93", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "kknqvzl-pmtgtmr-cbw-xsbdtqn" + }, + "corpo": { + "profilo": { + "numero": "1230", + "nome": "trhhflpwk.jghjf", + "nome_visibile": "Zrlmvdb mnhrfpzzv", + "riservato": true, + "seguito": false, + "pubblicazioni": 5, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/f453n389229j08cz.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/hg23k452n6kq3h26.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + }, + "contenuti": [], + "pagina": { + "altro": false, + "dopo": null + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000005-post-serie.json b/tests/Febe.Tests/campioni/prova/000005-post-serie.json new file mode 100644 index 0000000..6b648e2 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000005-post-serie.json @@ -0,0 +1,102 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/121076l2w14dpln2", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "cvzv-qdpsp" + }, + "corpo": { + "contenuto": { + "numero": "6686720181", + "sigla": "TqwwCvG", + "pubblicato": "2026-10-07T10:47:20Z", + "testo": "Dqr cldxlrdk lxc nwlszbwr v blhfr (mtqhp 671)", + "fissato": false, + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "parti": [ + { + "numero": "4391148625", + "foto": [ + { + "indirizzo": "https://cdn.esempio/zhzj06v06q4p7746.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/r85287t3l0f8937z.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/1z5tdb2994zbq0h0.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "9823770084", + "filmati": [ + { + "indirizzo": "https://cdn.esempio/wnr19826v154499b.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/q9v6mwrtbsv0xdw9.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/d9fgg81s94s0764w.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/48f0c0s2bkx7d256.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/715z79k6z3004ss1.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "8883127657", + "foto": [ + { + "indirizzo": "https://cdn.esempio/dfn95518270592f7.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/5095893x3k0780c6.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/t5ks39vq5zc981h8.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "parti_totali": 3 + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000006-storie.json b/tests/Febe.Tests/campioni/prova/000006-storie.json new file mode 100644 index 0000000..cd58f8b --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000006-storie.json @@ -0,0 +1,139 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/31632f51p8cn7scw", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "bfqhxs" + }, + "corpo": { + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "storie": [ + { + "numero": "4701597641", + "pubblicato": "2026-10-13T06:38:20Z", + "scade": "2026-10-14T06:38:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/189q0t5632714fcc.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/84vw8n35zdb64378.jpg", + "larghezza": 720, + "altezza": 1280 + }, + { + "indirizzo": "https://cdn.esempio/9780fl4p0980442k.jpg", + "larghezza": 180, + "altezza": 320 + } + ] + }, + { + "numero": "8905852591", + "pubblicato": "2026-10-13T08:11:20Z", + "scade": "2026-10-14T08:11:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/w7985ff6p815t616.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/442c758js6s5c5g8.jpg", + "larghezza": 720, + "altezza": 1280 + }, + { + "indirizzo": "https://cdn.esempio/8b5g5nz283v48333.jpg", + "larghezza": 180, + "altezza": 320 + } + ] + }, + { + "numero": "9513884481", + "pubblicato": "2026-10-13T11:36:20Z", + "scade": "2026-10-14T11:36:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/9687063g7904270w.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/vz310z8chrr5887w.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/j36755t64qh1nr74.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/67803n38j6cmsv0t.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/75l2gb30f0cl5p06.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "0613682151", + "pubblicato": "2026-10-13T15:11:20Z", + "scade": "2026-10-14T15:11:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/24j4tt8d6358rq8m.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/8vz4w53dnb9h7mzh.jpg", + "larghezza": 720, + "altezza": 1280 + }, + { + "indirizzo": "https://cdn.esempio/n0kl9g2379mz0x14.jpg", + "larghezza": 180, + "altezza": 320 + } + ] + } + ], + "successivo": "mkntl.vqwhn" + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000007-raccolta.json b/tests/Febe.Tests/campioni/prova/000007-raccolta.json new file mode 100644 index 0000000..4775152 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000007-raccolta.json @@ -0,0 +1,119 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/w0nrzbg537370cb3", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "wxrhhwml" + }, + "corpo": { + "raccolta": { + "numero": "3688348931", + "titolo": "Wxmngt", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "copertina": { + "indirizzo": "https://cdn.esempio/1z6s13040g7z0691.jpg", + "larghezza": 160, + "altezza": 284 + }, + "contenuti": [ + { + "numero": "2445846299", + "pubblicato": "2026-08-14T16:39:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/6rc62lqn469700xh.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/k468864wzj19p0db.jpg", + "larghezza": 720, + "altezza": 1280 + }, + { + "indirizzo": "https://cdn.esempio/04hf78n7pbl9325t.jpg", + "larghezza": 180, + "altezza": 320 + } + ] + }, + { + "numero": "5569978446", + "pubblicato": "2026-08-15T16:39:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "filmati": [ + { + "indirizzo": "https://cdn.esempio/4722w5smm74z9hz4.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/jw574n5630s84300.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/4s85629r8141ks8z.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/1574h2s0m88rlrbp.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/zrpbb8n47gc9n793.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "8905852591", + "pubblicato": "2026-10-13T08:11:20Z", + "autore": { + "numero": "5555", + "nome": "ndkwq.shzgd" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/w7985ff6p815t616.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/442c758js6s5c5g8.jpg", + "larghezza": 720, + "altezza": 1280 + }, + { + "indirizzo": "https://cdn.esempio/8b5g5nz283v48333.jpg", + "larghezza": 180, + "altezza": 320 + } + ] + } + ] + }, + "successiva": "3331216123" + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000008-seguiti.json b/tests/Febe.Tests/campioni/prova/000008-seguiti.json new file mode 100644 index 0000000..89838cc --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000008-seguiti.json @@ -0,0 +1,222 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/71kp36c44gt303c7", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "jvbzzgh" + }, + "corpo": { + "seguiti": [ + { + "numero": "5555", + "nome": "ndkwq.shzgd", + "nome_visibile": "Pxkjk gx xrfpm", + "riservato": false, + "seguito": true, + "pubblicazioni": 18, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/23wh5n049rr81521.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/h46r930r17f94226.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T15:11:20Z" + }, + { + "numero": "0256", + "nome": "lcfs.gwcfg", + "nome_visibile": "Pnhm ll rrhml", + "riservato": false, + "seguito": true, + "pubblicazioni": 40, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/4z7l3q070rf331lb.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/j793r3nmp3m7j334.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T13:28:20Z" + }, + { + "numero": "6473", + "nome": "jscnhk.hsjhd", + "nome_visibile": "Gjcpzg pz xxrgj", + "riservato": true, + "seguito": true, + "pubblicazioni": 6, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/2dx14g1d9l3p3q74.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/g7g12rt483170931.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T12:29:20Z" + }, + { + "numero": "5966", + "nome": "mkntl.vqwhn", + "nome_visibile": "Rjlvk dh bknnh", + "riservato": false, + "seguito": true, + "pubblicazioni": 3, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/064248847xjl13s4.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/8w293gphn3jlm641.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T14:16:20Z" + }, + { + "numero": "4360", + "nome": "gbbqw42.qjqvw", + "nome_visibile": "Jxbnh 58", + "riservato": false, + "seguito": true, + "pubblicazioni": 2, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/185g630w73pm8qb5.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/93738g757779h7x1.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + }, + { + "numero": "5845", + "nome": "qkgtd09.jnbfh", + "nome_visibile": "Tqhln 85", + "riservato": false, + "seguito": true, + "pubblicazioni": 2, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/9ghvw5b8p31779tx.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/32kdp8z37682n43g.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + }, + { + "numero": "0742", + "nome": "zthfc56.hxksl", + "nome_visibile": "Mmvnh 98", + "riservato": false, + "seguito": true, + "pubblicazioni": 2, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/z7p7k0l49g62h926.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/z732184kw81703m1.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + }, + { + "numero": "7782", + "nome": "bbxkn53.dlqhb", + "nome_visibile": "Wdtth 40", + "riservato": false, + "seguito": true, + "pubblicazioni": 2, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/32r3671m28vr9l97.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/g6z59qm27pl17vp1.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + }, + { + "numero": "0332", + "nome": "wdkxc49.gpzzf", + "nome_visibile": "Xjnln 58", + "riservato": false, + "seguito": true, + "pubblicazioni": 1, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/j7458l2d453xc2f5.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/043g3ct0dl8ql053.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + }, + { + "numero": "5233", + "nome": "bxpwf28.lpxgw", + "nome_visibile": "Fdcrb 54", + "riservato": false, + "seguito": true, + "pubblicazioni": 2, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/05z80g63354fk580.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/dm6692953m69h184.jpg", + "larghezza": 320, + "altezza": 320 + } + ] + } + ], + "pagina": { + "altro": true, + "dopo": "b44" + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000009-taggati.json b/tests/Febe.Tests/campioni/prova/000009-taggati.json new file mode 100644 index 0000000..137e0c6 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000009-taggati.json @@ -0,0 +1,185 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/52bf0789xw73302n", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "ptghjwf" + }, + "corpo": { + "profilo": { + "numero": "5555", + "nome": "ndkwq.shzgd", + "nome_visibile": "Pxkjk gx xrfpm", + "riservato": false, + "seguito": true, + "pubblicazioni": 18, + "ritratto": [ + { + "indirizzo": "https://cdn.esempio/23wh5n049rr81521.jpg", + "larghezza": 160, + "altezza": 160 + }, + { + "indirizzo": "https://cdn.esempio/h46r930r17f94226.jpg", + "larghezza": 320, + "altezza": 320 + } + ], + "ultima_storia": "2026-10-13T15:11:20Z" + }, + "contenuti": [ + { + "numero": "5623873993", + "sigla": "WTpK5ph", + "pubblicato": "2026-10-06T06:11:20Z", + "testo": "Knv hpkndmqd ckk vrjhdfbj s nrlmw (vmfsw 899)", + "fissato": false, + "autore": { + "numero": "3279", + "nome": "pngtg.ssrsw" + }, + "parti": [ + { + "numero": "2154030015", + "foto": [ + { + "indirizzo": "https://cdn.esempio/xw15jw99215k6s15.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/42g6sj65125p89rb.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/875vcm3snm538188.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "9740023776", + "filmati": [ + { + "indirizzo": "https://cdn.esempio/1485283h3b05k9tc.mp4", + "larghezza": 360, + "altezza": 640, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/sxv0m43lj14wd889.mp4", + "larghezza": 720, + "altezza": 1280, + "audio": true + }, + { + "indirizzo": "https://cdn.esempio/1dmrmv791m9007s2.mp4", + "larghezza": 1080, + "altezza": 1920, + "audio": false + } + ], + "foto": [ + { + "indirizzo": "https://cdn.esempio/kb36573f64w317x7.jpg", + "larghezza": 360, + "altezza": 640 + }, + { + "indirizzo": "https://cdn.esempio/36321504p7fg335j.jpg", + "larghezza": 720, + "altezza": 1280 + } + ], + "durata": 2 + }, + { + "numero": "3234632840", + "foto": [ + { + "indirizzo": "https://cdn.esempio/n46l1278wfk79b2c.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/2x67172s63r718nd.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/192l2721z70s2g76.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "parti_totali": 3 + }, + { + "numero": "7748249981", + "sigla": "9JJblgk", + "pubblicato": "2026-10-02T19:34:20Z", + "testo": "Qbn qllcxhlb gct kvscl q bcgn (mwqmg 612)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/l543l25vm9l51z8w.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/7228grh30hd9xx21.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/95hh432j47ks718t.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + }, + { + "numero": "7021565448", + "sigla": "ZcgM0pZ", + "pubblicato": "2026-09-21T05:03:20Z", + "testo": "Pvk jjgbdjnz dtb qwjmv q rlhw (clvpq 144)", + "fissato": false, + "autore": { + "numero": "0256", + "nome": "lcfs.gwcfg" + }, + "foto": [ + { + "indirizzo": "https://cdn.esempio/5lp63c52f971n3b6.jpg", + "larghezza": 480, + "altezza": 600 + }, + { + "indirizzo": "https://cdn.esempio/998wbk3t50b977rb.jpg", + "larghezza": 960, + "altezza": 1200 + }, + { + "indirizzo": "https://cdn.esempio/kw1r90cs5fq4223h.jpg", + "larghezza": 240, + "altezza": 300 + } + ] + } + ], + "pagina": { + "altro": false, + "dopo": null + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000010-pagina-vuota.json b/tests/Febe.Tests/campioni/prova/000010-pagina-vuota.json new file mode 100644 index 0000000..d2eb765 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000010-pagina-vuota.json @@ -0,0 +1,17 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/rm07847qj48b3072", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "qxzhzr-rkwks" + }, + "corpo": { + "contenuti": [], + "pagina": { + "altro": false, + "dopo": null + } + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/000011-forma-sconosciuta.json b/tests/Febe.Tests/campioni/prova/000011-forma-sconosciuta.json new file mode 100644 index 0000000..b170943 --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/000011-forma-sconosciuta.json @@ -0,0 +1,33 @@ +{ + "descrittore": { + "indirizzo": "https://sito.esempio/nt7w77859pc7037c", + "host": "sito", + "stato": 200, + "tipo": "application/json", + "risorsa": "Fetch", + "nome": "nwsgk-dmvmwznjphl" + }, + "corpo": { + "risultati": { + "voci": [ + { + "chiave": "T9k6M1g0", + "valore": "lcxrgkjp lq zwtnv mhv gjdmlb prvlmkc mmvtddf", + "dettagli": { + "x": 12, + "y": 7 + } + }, + { + "chiave": "N9x7S6t2", + "valore": "gb xxcxfnm jhvdttdq", + "dettagli": { + "x": 3, + "y": 4 + } + } + ] + }, + "versione": 3 + } +} \ No newline at end of file diff --git a/tests/Febe.Tests/campioni/prova/LEGGIMI.md b/tests/Febe.Tests/campioni/prova/LEGGIMI.md new file mode 100644 index 0000000..12f613c --- /dev/null +++ b/tests/Febe.Tests/campioni/prova/LEGGIMI.md @@ -0,0 +1,28 @@ +# Campioni ripuliti del sito di prova + +Risposte JSON del **sito di prova locale** (`tools/Febe.SitoDiProva`), non di Instagram. Servono alle prove dei +lettori (`tests/Febe.Tests/Collection/ReaderTests.cs`) e hanno fatto lo stesso percorso che faranno i campioni veri +di M0 (specifica §14.5): + +1. campioni grezzi scritti **fuori dal repository**, nel formato della sonda (descrittore + corpo): + `febe-sito-di-prova campioni --cartella `; il campione `forma-sconosciuta` è stato scritto + a mano nella stessa cartella per avere una forma che nessun lettore conosce; +2. ripulitura: `febe-sonda ripulisci --da --a tests/Febe.Tests/campioni/prova --sito 127.0.0.1 --cdn 127.0.0.2`; +3. verifica: `febe-sonda verifica --grezzi --ripuliti tests/Febe.Tests/campioni/prova` → «Verifica superata». + +Per questo nomi, didascalie, identificativi, cursori e indirizzi sono valori finti della stessa forma: le prove +controllano forme, dimensioni, date e conteggi, non i valori. + +| File | Che cosa contiene | +|---|---| +| `000001-inizio` | pagina iniziale: account collegato, barra delle storie, prima pagina dei post dei seguiti (serie incomplete) | +| `000002-profilo-pubblico` | profilo pubblico seguito: post fissati in cima, raccolte, prima pagina della griglia | +| `000003-profilo-pagina-successiva` | pagina successiva della griglia (scorrimento) | +| `000004-profilo-privato-non-seguito` | profilo privato non seguito: stato, nessun contenuto | +| `000005-post-serie` | post singolo con tre file (foto, video con e senza audio, foto) | +| `000006-storie` | elenco completo delle storie di un account, con un video | +| `000007-raccolta` | raccolta in evidenza con i suoi contenuti | +| `000008-seguiti` | prima pagina dell'elenco dei seguiti | +| `000009-taggati` | scheda «Taggati» di un profilo | +| `000010-pagina-vuota` | pagina di dati vuota | +| `000011-forma-sconosciuta` | risposta di forma sconosciuta | diff --git a/tools/Febe.SitoDiProva/DataApi.cs b/tools/Febe.SitoDiProva/DataApi.cs new file mode 100644 index 0000000..a6a4782 --- /dev/null +++ b/tools/Febe.SitoDiProva/DataApi.cs @@ -0,0 +1,323 @@ +using System.Globalization; +using System.Text.Json.Nodes; + +namespace Febe.SitoDiProva; + +/// +/// The JSON the pages fetch, in the site's own synthetic format (LEGGIMI.md). It is what the response tap captures +/// and what the readers of lettori.prova.json read. Keys are Italian and the shape is ours: it does not +/// imitate Instagram. +/// +public sealed class DataApi(World world, CdnSigner signer, SiteControl control, Func cdnBase, TimeProvider time) +{ + public const int FeedPageSize = 6; + public const int GridPageSize = 12; + public const int FollowingPageSize = 10; + + private DateTimeOffset Now => time.GetUtcNow(); + + /// Home: the connected account, the stories bar and the first page of the feed. + public JsonObject Home() + { + var feed = world.Feed(); + return new JsonObject + { + ["io"] = ProfileLite(world.Viewer), + ["barra"] = new JsonArray([.. world.StoryBar(Now).Select(a => (JsonNode)Profile(a))]), + ["contenuti"] = new JsonArray([.. feed.Take(FeedPageSize).Select(p => (JsonNode)Post(p, inFeed: true))]), + ["pagina"] = Page(feed.Count, 0, FeedPageSize), + }; + } + + public JsonObject HomeMore(string? after) + { + var feed = world.Feed(); + var offset = ParseCursor(after); + return new JsonObject + { + ["contenuti"] = new JsonArray([.. feed.Skip(offset).Take(FeedPageSize).Select(p => (JsonNode)Post(p, inFeed: true))]), + ["pagina"] = Page(feed.Count, offset, FeedPageSize), + }; + } + + /// A profile page: profile, highlights (first page only) and a page of the tab. Null when it does not exist. + public JsonObject? Profile(string username, ProfileTab tab, string? after) + { + var account = world.FindByUsername(username); + if (account is null) + { + return null; + } + + var result = new JsonObject { ["profilo"] = Profile(account) }; + if (account.IsPrivate && !account.FollowedByViewer) + { + result["contenuti"] = new JsonArray(); + result["pagina"] = new JsonObject { ["altro"] = false, ["dopo"] = null }; + return result; + } + + var offset = ParseCursor(after); + if (tab == ProfileTab.Posts && offset == 0) + { + result["raccolte"] = new JsonArray([.. account.Highlights.Select(h => (JsonNode)Highlight(h, withItems: false))]); + } + + var grid = world.Grid(account, tab); + result["contenuti"] = new JsonArray([.. grid.Skip(offset).Take(GridPageSize).Select(p => (JsonNode)Post(p, inFeed: false))]); + result["pagina"] = Page(grid.Count, offset, GridPageSize); + return result; + } + + public JsonObject? ProfileMore(string username, ProfileTab tab, string? after) + { + var account = world.FindByUsername(username); + if (account is null || (account.IsPrivate && !account.FollowedByViewer)) + { + return null; + } + + var grid = world.Grid(account, tab); + var offset = ParseCursor(after); + return new JsonObject + { + ["contenuti"] = new JsonArray([.. grid.Skip(offset).Take(GridPageSize).Select(p => (JsonNode)Post(p, inFeed: false))]), + ["pagina"] = Page(grid.Count, offset, GridPageSize), + }; + } + + public JsonObject? SinglePost(string code) + { + var post = world.FindPost(code); + if (post is null || (post.Owner.IsPrivate && !post.Owner.FollowedByViewer)) + { + return null; + } + + return new JsonObject { ["contenuto"] = Post(post, inFeed: false) }; + } + + /// All the active stories of an account (the page receives the whole list in advance), and who comes next. + public JsonObject? Stories(string username) + { + var account = world.FindByUsername(username); + if (account is null || (account.IsPrivate && !account.FollowedByViewer)) + { + return null; + } + + var bar = world.StoryBar(Now); + var index = bar.ToList().IndexOf(account); + var next = index >= 0 && index + 1 < bar.Count ? bar[index + 1].Username : null; + return new JsonObject + { + ["autore"] = ProfileLite(account), + ["storie"] = new JsonArray([.. account.Stories.Where(s => s.ExpiresAt > Now).Select(s => (JsonNode)Story(s))]), + ["successivo"] = next, + }; + } + + public JsonObject? HighlightItems(string id) + { + var highlight = world.FindHighlight(id); + if (highlight is null) + { + return null; + } + + var siblings = highlight.Owner.Highlights; + var index = siblings.IndexOf(highlight); + return new JsonObject + { + ["raccolta"] = Highlight(highlight, withItems: true), + ["successiva"] = index + 1 < siblings.Count ? siblings[index + 1].Id : null, + }; + } + + public JsonObject Following(string? after) + { + var list = world.Following; + var offset = ParseCursor(after); + return new JsonObject + { + ["seguiti"] = new JsonArray([.. list.Skip(offset).Take(FollowingPageSize).Select(a => (JsonNode)Profile(a))]), + ["pagina"] = Page(list.Count, offset, FollowingPageSize), + }; + } + + public static JsonObject EmptyPage() => new() + { + ["contenuti"] = new JsonArray(), + ["pagina"] = new JsonObject { ["altro"] = false, ["dopo"] = null }, + }; + + /// A response in a shape the readers do not know: what a site that changed its format would send. + public static JsonObject UnknownShape() => new() + { + ["risposta"] = new JsonObject + { + ["voci"] = new JsonArray( + new JsonObject { ["chiave"] = "A1", ["valore"] = "un formato nuovo", ["dettagli"] = new JsonObject { ["x"] = 1 } }, + new JsonObject { ["chiave"] = "B2", ["valore"] = "che nessun lettore conosce", ["dettagli"] = new JsonObject { ["x"] = 2 } }), + }, + ["versione"] = 2, + }; + + public static int ParseCursor(string? cursor) => + cursor is { Length: > 1 } && cursor[0] == 'c' && int.TryParse(cursor.AsSpan(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) && n >= 0 ? n : 0; + + public static string Cursor(int offset) => "c" + offset.ToString(CultureInfo.InvariantCulture); + + private static JsonObject Page(int total, int offset, int size) + { + var more = offset + size < total; + return new JsonObject { ["altro"] = more, ["dopo"] = more ? Cursor(offset + size) : null }; + } + + private JsonObject ProfileLite(SiteAccount account) => new() + { + ["numero"] = account.Id, + ["nome"] = account.Username, + }; + + private JsonObject Profile(SiteAccount account) + { + var node = new JsonObject + { + ["numero"] = account.Id, + ["nome"] = account.Username, + ["nome_visibile"] = account.DisplayName, + ["riservato"] = account.IsPrivate, + ["seguito"] = account.FollowedByViewer, + ["pubblicazioni"] = account.Posts.Count, + ["ritratto"] = new JsonArray( + Version(account.PictureKey, 160, 160, video: false), + Version(account.PictureKey, 320, 320, video: false)), + }; + if (account.LatestStoryAt(Now) is { } latest && (!account.IsPrivate || account.FollowedByViewer)) + { + node["ultima_storia"] = Date(latest); + } + + return node; + } + + private JsonObject Post(SitePost post, bool inFeed) + { + var node = new JsonObject + { + ["numero"] = post.Id, + ["sigla"] = post.Code, + ["pubblicato"] = Date(post.PublishedAt), + ["testo"] = post.Caption, + ["fissato"] = post.Pinned && !inFeed, + ["autore"] = ProfileLite(post.Owner), + }; + if (post.Files.Count == 1) + { + AddFile(node, post.Files[0]); + } + else + { + // The feed carries only the first file of a series, with the declared count: the post is incomplete there + // and «Post singolo» completes it. Profile grids and post pages carry the whole series. + var parts = inFeed ? post.Files.Take(1) : post.Files; + node["parti"] = new JsonArray([.. parts.Select(f => + { + var part = new JsonObject { ["numero"] = f.Id }; + AddFile(part, f); + return (JsonNode)part; + })]); + node["parti_totali"] = post.Files.Count; + } + + return node; + } + + private JsonObject Story(SiteStory story) + { + var node = new JsonObject + { + ["numero"] = story.Id, + ["pubblicato"] = Date(story.PublishedAt), + ["scade"] = Date(story.ExpiresAt), + ["autore"] = ProfileLite(story.Owner), + }; + AddFile(node, story.File); + return node; + } + + private JsonObject Highlight(SiteHighlight highlight, bool withItems) + { + var node = new JsonObject + { + ["numero"] = highlight.Id, + ["titolo"] = highlight.Title, + ["autore"] = ProfileLite(highlight.Owner), + ["copertina"] = highlight.Items.Count > 0 ? Version(highlight.Items[0].File.MediaKey, 160, 284, video: false) : null, + }; + if (withItems) + { + node["contenuti"] = new JsonArray([.. highlight.Items.Select(i => + { + var item = new JsonObject + { + ["numero"] = i.Id, + ["pubblicato"] = Date(i.PublishedAt), + ["autore"] = ProfileLite(i.Owner), + }; + AddFile(item, i.File); + return (JsonNode)item; + })]); + } + + return node; + } + + /// + /// The versions of a file. Images: a medium, the largest and a small one (in this order: the largest is not the + /// first). Videos: two renditions with audio and a larger one without audio (the reader must not pick it), plus + /// cover images. + /// + private void AddFile(JsonObject node, SiteFile file) + { + if (file.IsVideo) + { + node["filmati"] = new JsonArray( + Version(file.MediaKey, file.Width / 2, file.Height / 2, video: true, audio: true), + Version(file.MediaKey, file.Width, file.Height, video: true, audio: true), + Version(file.MediaKey, file.Width * 3 / 2, file.Height * 3 / 2, video: true, audio: false)); + node["foto"] = new JsonArray( + Version(file.MediaKey, file.Width / 2, file.Height / 2, video: false), + Version(file.MediaKey, file.Width, file.Height, video: false)); + node["durata"] = file.DurationSeconds; + } + else + { + node["foto"] = new JsonArray( + Version(file.MediaKey, file.Width / 2, file.Height / 2, video: false), + Version(file.MediaKey, file.Width, file.Height, video: false), + Version(file.MediaKey, file.Width / 4, file.Height / 4, video: false)); + } + } + + private JsonObject Version(string key, int width, int height, bool video, bool audio = true) + { + var size = $"{width.ToString(CultureInfo.InvariantCulture)}x{height.ToString(CultureInfo.InvariantCulture)}"; + var path = video ? $"/m/{key}/{size}{(audio ? string.Empty : "-muto")}.mp4" : $"/m/{key}/{size}.jpg"; + var node = new JsonObject + { + ["indirizzo"] = cdnBase() + signer.Sign(path, Now + control.AddressLifetime), + ["larghezza"] = width, + ["altezza"] = height, + }; + if (video) + { + node["audio"] = audio; + } + + return node; + } + + private static string Date(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture); +} diff --git a/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj b/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj index 7cb71f4..322bb92 100644 --- a/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj +++ b/tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj @@ -1,10 +1,22 @@ - + Exe febe-sito-di-prova Febe.SitoDiProva + + + + + + + + + + diff --git a/tools/Febe.SitoDiProva/LEGGIMI.md b/tools/Febe.SitoDiProva/LEGGIMI.md new file mode 100644 index 0000000..f13a00a --- /dev/null +++ b/tools/Febe.SitoDiProva/LEGGIMI.md @@ -0,0 +1,115 @@ +# Sito di prova di Febe + +Sito locale per far girare ricette, cattura, lettori, scaricamenti e motore con un browser vero **senza toccare +Instagram** (specifica §14.2). Pagine spoglie, nessun marchio né grafica di Instagram, **nessuna pagina di accesso**: +non deve somigliargli, deve solo comportarsi come un sito che carica i dati in JSON mentre si scorre. + +## Avvio + +```sh +dotnet run --project tools/Febe.SitoDiProva -- [--porta 8481] [--porta-cdn 8482] [--indirizzo-cdn 127.0.0.2] [--seme 13] +``` + +- Il sito ascolta su `127.0.0.1:`; il «CDN» che serve foto e video su un **secondo indirizzo** + (`127.0.0.2:`, oppure `127.0.0.1` su un'altra porta dove `127.0.0.2` non si può usare), così i cookie + del sito non gli arrivano. +- I dati sono **sintetici** e si generano da un seme: stesso seme, stessi account, post, codici e didascalie. Le date + sono relative al momento dell'avvio (le storie sono attive per 24 ore da lì). +- Le prove automatiche lo avviano dentro il processo con `TestSite.StartAsync(...)` (porte libere scelte da sole). +- Campioni grezzi per le prove dei lettori: `dotnet run --project tools/Febe.SitoDiProva -- campioni --cartella ` + (poi `febe-sonda ripulisci`, vedi `tests/Febe.Tests/campioni/prova/LEGGIMI.md`). + +## Il mondo + +| Account | Che cos'è | +|---|---| +| `alberto.prova` | l'account collegato («Tu»); da lui si apre l'elenco dei seguiti | +| `marta.prova` | pubblico, seguito: 18 post (foto, serie di tre file, video = reel), 2 post fissati, 4 storie (una è un video), raccolte «Estate» e «Viaggi»; compare nei taggati di Luca e di Paolo | +| `luca.prova` | pubblico, seguito: 40 post (storico su più pagine), 2 storie, raccolta «Montagna» | +| `giulia.prova` | privato, seguito: 6 post, 5 storie | +| `nadia.prova` | pubblico, seguito: 3 post, 3 storie | +| `paolo.prova` | pubblico, **non** seguito: 8 post, 1 storia | +| `riservato.prova` | privato, **non** seguito: non si tocca | +| `amico01.prova` … `amico24.prova` | seguiti, uno o due post ciascuno (l'elenco dei seguiti ha 28 profili) | +| qualunque altro nome | non esiste: la pagina risponde 404 con il titolo «Profilo non trovato» | + +La barra delle storie elenca i seguiti con storie attive, dalla più recente: Marta, Nadia, Luca, Giulia. Una delle +storie attive di Marta è anche nella raccolta «Estate», con lo **stesso identificativo** (ipotesi H9). + +## Pagine + +| Indirizzo | Che cosa fa | +|---|---| +| `/` | pagina iniziale: barra delle storie (collegamenti «Storie di …») e post recenti dei seguiti; scorrendo carica altre pagine | +| `/profilo/{nome}/` | profilo: foto (con «Apri le storie di …» se ci sono storie), raccolte («Raccolta …»), schede `Post`, `Reel`, `Taggati` (ruolo `tab`), griglia che carica altre pagine scorrendo; `?dopo={cursore}` riparte da un punto della griglia | +| `/profilo/{nome}/reel/`, `/profilo/{nome}/taggati/` | le altre schede, con lo stesso scorrimento | +| `/profilo/alberto.prova/seguiti/` | elenco dei profili seguiti, a pagine, scorrendo; accetta `?dopo=` | +| `/storie/{nome}/` | visualizzatore: una storia alla volta, barra di avanzamento, zona «Storia successiva», pulsante «Chiudi». L'indirizzo diventa `/storie/{nome}/{id}/` per la storia mostrata. **Come i siti veri, dopo l'ultima storia passa da solo all'account successivo della barra**: chi lo usa deve chiuderlo prima | +| `/evidenza/{id}/` | visualizzatore di una raccolta, come sopra (`/evidenza/{id}/{contenuto}/`); dopo l'ultimo contenuto passa alla raccolta successiva dello stesso account | +| `/post/{codice}/` | pagina di un post, con tutti i file | +| `/verifica` | pagina di verifica, semplice testo | +| `/sessione-scaduta` | pagina di sessione terminata, semplice testo (non è un modulo di accesso) | + +La mappa dei bersagli di queste pagine è `src/Febe.Core/Config/bersagli.prova.json` (copiata accanto al programma +in `config/`), i segnali di arresto sono in `segnali.prova.json`. + +## Formato dei dati + +Le pagine caricano i dati con `fetch` da `/dati/...` e li leggono davvero (così il browser consegna il corpo alla +cattura). Il formato è **nostro**, con chiavi italiane: non imita Instagram e non va usato come indizio sul formato +di Instagram (regola 10). Il vocabolario che lo descrive ai lettori è `src/Febe.Core/Config/lettori.prova.json`. + +| Indirizzo dei dati | Risposta | +|---|---| +| `/dati/inizio` | `{ io, barra: [profilo], contenuti: [contenuto], pagina }` | +| `/dati/inizio/altri?dopo=` | `{ contenuti, pagina }` | +| `/dati/profilo/{nome}?scheda=post\|reel\|taggati&dopo=` | `{ profilo, raccolte (solo prima pagina dei post), contenuti, pagina }` | +| `/dati/profilo/{nome}/altri?scheda=&dopo=` | `{ contenuti, pagina }` | +| `/dati/post/{codice}` | `{ contenuto }` | +| `/dati/storie/{nome}` | `{ autore, storie: [contenuto], successivo }`: tutte le storie attive arrivano subito | +| `/dati/evidenza/{id}` | `{ raccolta: { numero, titolo, autore, contenuti }, successiva }` | +| `/dati/seguiti?dopo=` | `{ seguiti: [profilo], pagina }` | + +Oggetti: + +```text +profilo { numero, nome, nome_visibile, riservato, seguito, pubblicazioni, ritratto: [versione], ultima_storia? } +contenuto { numero, sigla?, pubblicato, testo?, fissato, autore: { numero, nome }, + foto: [versione] | filmati: [versione] + foto (copertina) + durata | parti: [file] + parti_totali, + scade? (storie) } +file { numero, foto | filmati + durata } +versione { indirizzo, larghezza, altezza, audio? (filmati) } +pagina { altro, dopo } +``` + +- Date in testo ISO 8601, UTC (`2026-10-13T08:00:00Z`); durate in secondi. +- Le immagini hanno tre versioni (media, grande, piccola: la più grande **non** è la prima); i video due versioni con + audio e una più grande **senza** audio, che i lettori non devono scegliere. +- Nei post della pagina iniziale una serie arriva **incompleta**: solo il primo file e `parti_totali`. Profilo e pagina + del post la danno intera (è il caso «Post singolo»). +- Cursori opachi `c{n}`. +- Gli indirizzi dei file sono firmati e scadono: `/m/{chiave}/{L}x{A}.jpg?scad={unix}&firma={hmac}` (durata + predefinita 6 ore). Un indirizzo scaduto riceve 403. Le foto sono generate con SkiaSharp dalla chiave (stessa + chiave, stessa immagine a ogni dimensione); i video sono due MP4 minuscoli generati una volta con ffmpeg + (`Risorse/filmato-con-audio.mp4`, `Risorse/filmato-muto.mp4`), resi unici aggiungendo in coda un riquadro `free`. + +## Casi di arresto e comandi per le prove + +Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...` sul sito. + +| Comando | Effetto | +|---|---| +| `/_controllo/modo?valore=troppe-richieste[&dopo=N]` | le richieste di dati ricevono 429 (dopo N richieste) | +| `/_controllo/modo?valore=verifica` | le pagine rimandano a `/verifica`; i dati rispondono 403 e la pagina ci va da sola | +| `/_controllo/modo?valore=sessione-scaduta` | il cookie `sessione_prova` si cancella e le pagine vanno a `/sessione-scaduta` | +| `/_controllo/modo?valore=vuoto` | le pagine di dati arrivano vuote | +| `/_controllo/modo?valore=formato-sconosciuto` | i dati arrivano in una forma che nessun lettore conosce | +| `/_controllo/modo?valore=normale`, `/_controllo/reimposta` | tutto torna normale | +| `/_controllo/durata-storie?ms=` | quanto resta a schermo una storia prima che il visualizzatore vada avanti da solo | +| `/_controllo/scadenza-indirizzi?secondi=` | durata degli indirizzi firmati consegnati da quel momento | +| `/_controllo/rinomina?da=&a=` | un account cambia nome (stesso numero) | +| `/_controllo/ritratto?nome=` | nuova foto del profilo | +| `/_controllo/pubblica?nome=&tipo=foto\|video\|serie` | nuovo post in cima | +| `/_controllo/stato` | modo attuale e numero di richieste di dati | + +Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla prima visita di una pagina. diff --git a/tools/Febe.SitoDiProva/MediaFactory.cs b/tools/Febe.SitoDiProva/MediaFactory.cs new file mode 100644 index 0000000..2a8771c --- /dev/null +++ b/tools/Febe.SitoDiProva/MediaFactory.cs @@ -0,0 +1,133 @@ +using System.Buffers.Binary; +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; +using SkiaSharp; + +namespace Febe.SitoDiProva; + +/// +/// Generates the files the «CDN» serves: JPEG pictures drawn with SkiaSharp from the media key (same key, same +/// picture at every size) and short MP4 videos made unique with a trailing «free» box. Results are cached. +/// +public sealed class MediaFactory +{ + private static readonly Lazy VideoWithAudio = new(() => ReadResource("filmato-con-audio.mp4")); + private static readonly Lazy VideoWithoutAudio = new(() => ReadResource("filmato-muto.mp4")); + + private readonly ConcurrentDictionary _cache = new(StringComparer.Ordinal); + + /// A JPEG of × for . + public byte[] Picture(string key, int width, int height) => + _cache.GetOrAdd($"p|{key}|{width}|{height}", _ => DrawPicture(key, Math.Clamp(width, 16, 2048), Math.Clamp(height, 16, 2048))); + + /// An MP4 for : with audio (complete) or video only. + public byte[] Video(string key, int width, int height, bool withAudio) => + _cache.GetOrAdd($"v|{key}|{width}|{height}|{withAudio}", _ => + { + var template = withAudio ? VideoWithAudio.Value : VideoWithoutAudio.Value; + var payload = Encoding.ASCII.GetBytes($"febe-sito-di-prova {key} {width}x{height} {(withAudio ? "audio" : "muto")}"); + var result = new byte[template.Length + 8 + payload.Length]; + template.CopyTo(result, 0); + BinaryPrimitives.WriteUInt32BigEndian(result.AsSpan(template.Length), (uint)(8 + payload.Length)); + "free"u8.CopyTo(result.AsSpan(template.Length + 4)); + payload.CopyTo(result, template.Length + 8); + return result; + }); + + private static byte[] DrawPicture(string key, int width, int height) + { + var seed = BinaryPrimitives.ReadInt32LittleEndian(SHA256.HashData(Encoding.UTF8.GetBytes(key))); + var random = new Random(seed); + using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + using (var canvas = new SKCanvas(bitmap)) + { + SKColor RandomColor() => new((byte)random.Next(256), (byte)random.Next(256), (byte)random.Next(256)); + using (var background = new SKPaint()) + { + background.Shader = SKShader.CreateLinearGradient( + new SKPoint(0, 0), + new SKPoint(width, height), + [RandomColor(), RandomColor(), RandomColor()], + null, + SKShaderTileMode.Clamp); + canvas.DrawRect(0, 0, width, height, background); + } + + // Shapes in relative coordinates: every size shows the same picture. + using var paint = new SKPaint { IsAntialias = true }; + var shapes = 8 + random.Next(8); + for (var i = 0; i < shapes; i++) + { + paint.Color = RandomColor().WithAlpha((byte)(150 + random.Next(100))); + var x = (float)(random.NextDouble() * width); + var y = (float)(random.NextDouble() * height); + var w = (float)((0.08 + (random.NextDouble() * 0.35)) * width); + var h = (float)((0.08 + (random.NextDouble() * 0.35)) * height); + if (random.Next(2) == 0) + { + canvas.DrawRect(x - (w / 2), y - (h / 2), w, h, paint); + } + else + { + canvas.DrawOval(new SKRect(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2)), paint); + } + } + } + + using var image = SKImage.FromBitmap(bitmap); + using var data = image.Encode(SKEncodedImageFormat.Jpeg, 85); + return data.ToArray(); + } + + private static byte[] ReadResource(string name) + { + using var stream = typeof(MediaFactory).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}") + ?? throw new FileNotFoundException($"Risorsa mancante: {name}"); + using var memory = new MemoryStream(); + stream.CopyTo(memory); + return memory.ToArray(); + } +} + +/// +/// Signed, expiring CDN addresses (spec §6.5: «gli indirizzi scadono»): /m/{key}/{w}x{h}.jpg?scad=…&firma=…. +/// The signature is an HMAC of path and expiry with a key drawn at start-up; an address past its expiry gets 403. +/// +public sealed class CdnSigner +{ + private readonly byte[] _key = RandomNumberGenerator.GetBytes(32); + + public string Sign(string path, DateTimeOffset expiresAt) + { + var expiry = expiresAt.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture); + return $"{path}?scad={expiry}&firma={Signature(path, expiry)}"; + } + + /// Checks an address: , or . + public CdnCheck Check(string path, string? expiry, string? signature, DateTimeOffset now) + { + if (string.IsNullOrEmpty(expiry) || string.IsNullOrEmpty(signature) + || !long.TryParse(expiry, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var seconds)) + { + return CdnCheck.Invalid; + } + + if (!CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(Signature(path, expiry)), Encoding.ASCII.GetBytes(signature))) + { + return CdnCheck.Invalid; + } + + return DateTimeOffset.FromUnixTimeSeconds(seconds) < now ? CdnCheck.Expired : CdnCheck.Valid; + } + + private string Signature(string path, string expiry) => + Convert.ToHexStringLower(HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(path + "|" + expiry)))[..24]; +} + +public enum CdnCheck +{ + Valid, + Expired, + Invalid, +} diff --git a/tools/Febe.SitoDiProva/Pages.cs b/tools/Febe.SitoDiProva/Pages.cs new file mode 100644 index 0000000..7536f44 --- /dev/null +++ b/tools/Febe.SitoDiProva/Pages.cs @@ -0,0 +1,96 @@ +using System.Globalization; +using System.Net; + +namespace Febe.SitoDiProva; + +/// The HTML of the site: plain pages, no branding, no login form. Data is filled in by sito.js. +internal static class Pages +{ + public static string Home() => Layout("Inizio", "inizio", string.Empty, """ +

Inizio

+
+
+
+ """); + + public static string Profile(string username, ProfileTab tab) + { + var u = Encode(username); + var tabName = tab switch { ProfileTab.Reels => "reel", ProfileTab.Tagged => "taggati", _ => "post" }; + string Tab(string label, string path, ProfileTab which) => + $"""{label}"""; + return Layout($"Profilo di {username}", "profilo", $"""data-utente="{Html(username)}" data-scheda="{tabName}" """, $""" +
+
+ +
+
+ """); + } + + public static string ProfileNotFound(string username) => Layout("Profilo non trovato", "nessuna", string.Empty, $""" +

Profilo non trovato

+

Il profilo «{Html(username)}» non esiste o non è più disponibile.

+

Torna all'inizio

+ """); + + public static string Following(string username) => Layout($"Profili seguiti da {username}", "seguiti", $"""data-utente="{Html(username)}" """, """ +

Profili seguiti

+
    +
    + """); + + public static string Post(string code) => Layout("Post", "post", $"""data-sigla="{Html(code)}" """, """ +
    + """); + + public static string Viewer(string kind, TimeSpan storyDuration) => + $""" + + + {(kind == "storie" ? "Storie" : "Raccolta")} + +
    +
    +
    + + + + + + """; + + public static string Challenge() => Layout("Verifica", "nessuna", string.Empty, """ +

    Verifica richiesta

    +

    Il sito di prova chiede una verifica. Febe deve fermarsi e avvisare: qui non c'è niente da compilare.

    + """); + + public static string SessionEnded() => Layout("Sessione scaduta", "nessuna", string.Empty, """ +

    Sessione scaduta

    +

    La sessione del sito di prova è terminata. Febe deve fermarsi e non tentare di rientrare.

    + """); + + public static string NotFound() => Layout("Pagina non trovata", "nessuna", string.Empty, "

    Pagina non trovata

    "); + + private static string Layout(string title, string page, string attributes, string main) => $""" + + + {Html(title)} · Sito di prova + +
    Sito di prova di FebeInizioSeguiti
    +
    + {main} +
    + + + + """; + + private static string Html(string text) => WebUtility.HtmlEncode(text); + + private static string Encode(string text) => Uri.EscapeDataString(text); +} diff --git a/tools/Febe.SitoDiProva/Program.cs b/tools/Febe.SitoDiProva/Program.cs index d0d3c6b..2043057 100644 --- a/tools/Febe.SitoDiProva/Program.cs +++ b/tools/Febe.SitoDiProva/Program.cs @@ -1,4 +1,108 @@ -// Local test site (spec §14.2). Filled in by milestones M0 and M2. -var app = WebApplication.CreateBuilder(args).Build(); -app.MapGet("/", () => "Sito di prova di Febe"); -app.Run(); +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.SitoDiProva; + +// Local test site (spec §14.2). +// febe-sito-di-prova [--porta 8481] [--porta-cdn 8482] [--indirizzo-cdn 127.0.0.2] [--seme 13] +// febe-sito-di-prova campioni --cartella [--seme 13] +if (args.Length > 0 && args[0] == "campioni") +{ + return await DumpSamplesAsync(args[1..]); +} + +var options = new TestSiteOptions +{ + Port = IntOption(args, "--porta", 8481), + CdnPort = IntOption(args, "--porta-cdn", 8482), + CdnAddress = Option(args, "--indirizzo-cdn") ?? "127.0.0.2", + Seed = IntOption(args, "--seme", 13), + ConsoleLog = true, +}; +await using var site = await TestSite.StartAsync(options); +Console.WriteLine($"Sito di prova: {site.SiteUrl}/ · CDN: {site.CdnUrl}/ · seme {options.Seed.ToString(CultureInfo.InvariantCulture)}"); +Console.WriteLine($"Casi di arresto: {site.SiteUrl}/_controllo/modo?valore=troppe-richieste|verifica|sessione-scaduta|vuoto|normale"); +Console.WriteLine("Ctrl+C per fermare."); +var stop = new TaskCompletionSource(); +Console.CancelKeyPress += (_, e) => +{ + e.Cancel = true; + stop.TrySetResult(); +}; +await stop.Task; +return 0; + +// Writes the JSON responses of the main pages in the raw format of the probe (descriptor + body), to be cleaned with +// «febe-sonda ripulisci». The data is synthetic, but the samples follow the same path as real ones (spec §14.5). +static async Task DumpSamplesAsync(string[] args) +{ + var folder = Option(args, "--cartella"); + if (string.IsNullOrWhiteSpace(folder)) + { + Console.Error.WriteLine("Indicare --cartella ."); + return 2; + } + + Directory.CreateDirectory(folder); + await using var site = await TestSite.StartAsync(new TestSiteOptions { Seed = IntOption(args, "--seme", 13) }); + string marta, luca, code; + lock (site.World.Gate) + { + marta = site.World.FindByUsername("marta.prova")!.Username; + luca = site.World.FindByUsername("luca.prova")!.Username; + code = site.World.FindByUsername("marta.prova")!.Posts.First(p => p.Files.Count > 1).Code; + } + + var samples = new (string Name, string Path)[] + { + ("inizio", "/dati/inizio"), + ("profilo-pubblico", $"/dati/profilo/{marta}?scheda=post"), + ("profilo-pagina-successiva", $"/dati/profilo/{luca}/altri?scheda=post&dopo=c12"), + ("profilo-privato-non-seguito", "/dati/profilo/riservato.prova?scheda=post"), + ("post-serie", $"/dati/post/{code}"), + ("storie", $"/dati/storie/{marta}"), + ("raccolta", $"/dati/evidenza/{site.World.FindByUsername("marta.prova")!.Highlights[0].Id}"), + ("seguiti", "/dati/seguiti"), + ("taggati", $"/dati/profilo/{marta}?scheda=taggati"), + }; + + var number = 0; + foreach (var (name, path) in samples) + { + var body = JsonNode.Parse(await site.GetDataAsync(path)); + await WriteSampleAsync(folder, ++number, name, site.Url(path), 200, body); + } + + site.Control.Set(StopMode.EmptyPages); + await WriteSampleAsync(folder, ++number, "pagina-vuota", site.Url($"/dati/profilo/{luca}/altri?scheda=post&dopo=c48"), 200, JsonNode.Parse(await site.GetDataAsync($"/dati/profilo/{luca}/altri?scheda=post&dopo=c48"))); + Console.WriteLine($"Scritti {number.ToString(CultureInfo.InvariantCulture)} campioni grezzi in {folder}."); + return 0; +} + +static async Task WriteSampleAsync(string folder, int number, string name, string url, int status, JsonNode? body) +{ + var sample = new JsonObject + { + ["descrittore"] = new JsonObject + { + ["indirizzo"] = url.Split('?')[0], + ["host"] = "sito", + ["stato"] = status, + ["tipo"] = "application/json", + ["risorsa"] = "Fetch", + ["nome"] = name, + }, + ["corpo"] = body, + }; + var file = Path.Combine(folder, $"{number.ToString("000000", CultureInfo.InvariantCulture)}-{name}.json"); + await File.WriteAllTextAsync(file, sample.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); +} + +static string? Option(string[] args, string name) +{ + var index = Array.IndexOf(args, name); + return index >= 0 && index + 1 < args.Length ? args[index + 1] : null; +} + +static int IntOption(string[] args, string name, int fallback) => + int.TryParse(Option(args, name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : fallback; diff --git a/tools/Febe.SitoDiProva/Risorse/filmato-con-audio.mp4 b/tools/Febe.SitoDiProva/Risorse/filmato-con-audio.mp4 new file mode 100644 index 0000000..8742aa8 Binary files /dev/null and b/tools/Febe.SitoDiProva/Risorse/filmato-con-audio.mp4 differ diff --git a/tools/Febe.SitoDiProva/Risorse/filmato-muto.mp4 b/tools/Febe.SitoDiProva/Risorse/filmato-muto.mp4 new file mode 100644 index 0000000..ca1a6f5 Binary files /dev/null and b/tools/Febe.SitoDiProva/Risorse/filmato-muto.mp4 differ diff --git a/tools/Febe.SitoDiProva/Risorse/sito.css b/tools/Febe.SitoDiProva/Risorse/sito.css new file mode 100644 index 0000000..477d82d --- /dev/null +++ b/tools/Febe.SitoDiProva/Risorse/sito.css @@ -0,0 +1,39 @@ +/* Sito di prova di Febe: pagine spoglie, nessun marchio. */ +* { box-sizing: border-box; } +body { margin: 0; font: 15px/1.4 system-ui, sans-serif; background: #f4f4f2; color: #222; } +a { color: #1d5c8c; } +header.sito { padding: 10px 16px; background: #fff; border-bottom: 1px solid #ddd; display: flex; gap: 16px; align-items: center; } +header.sito strong { font-weight: 600; } +main { max-width: 980px; margin: 0 auto; padding: 16px; } +.avviso { padding: 12px; background: #fff3cd; border: 1px solid #e0c46c; margin: 12px 0; } +.barra { display: flex; gap: 12px; overflow-x: auto; padding: 8px 0 16px; } +.barra a { display: flex; flex-direction: column; align-items: center; gap: 4px; text-decoration: none; color: #333; font-size: 12px; } +.barra img, .anello img { width: 64px; height: 64px; border-radius: 50%; border: 3px solid #c84; display: block; } +.flusso article { background: #fff; border: 1px solid #ddd; margin: 0 0 24px; padding: 12px; min-height: 640px; } +.flusso article img { width: 480px; height: 600px; object-fit: cover; display: block; background: #ccc; } +.testata { display: flex; gap: 24px; align-items: center; padding: 16px 0; } +.testata .foto { width: 96px; height: 96px; border-radius: 50%; display: block; } +.anello img { width: 96px; height: 96px; } +nav.schede { display: flex; gap: 24px; border-top: 1px solid #ccc; padding: 8px 0; margin: 8px 0 16px; } +nav.schede a[aria-selected="true"] { font-weight: 700; } +.raccolte { display: flex; gap: 16px; padding: 8px 0; } +.raccolte a { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: #333; font-size: 12px; } +.raccolte img { width: 56px; height: 56px; border-radius: 50%; object-fit: cover; } +.griglia { display: grid; grid-template-columns: repeat(3, 300px); gap: 8px; } +.griglia a { display: block; width: 300px; height: 375px; background: #ccc; position: relative; } +.griglia img { width: 300px; height: 375px; object-fit: cover; display: block; } +.griglia .segno { position: absolute; top: 6px; right: 8px; color: #fff; font-size: 12px; text-shadow: 0 0 3px #000; } +.elenco { list-style: none; margin: 0; padding: 0; } +.elenco li { height: 120px; display: flex; align-items: center; gap: 16px; border-bottom: 1px solid #ddd; background: #fff; padding: 0 16px; } +.elenco img { width: 56px; height: 56px; border-radius: 50%; } +.sentinella { height: 40px; } +.caricamento { color: #888; padding: 12px; } +body.visualizzatore { background: #111; color: #eee; overflow: hidden; } +.palco { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; } +.palco img, .palco video { max-width: 405px; max-height: 720px; width: 405px; height: 720px; object-fit: cover; background: #333; } +.progressi { position: fixed; top: 8px; left: 50%; transform: translateX(-50%); width: 405px; display: flex; gap: 4px; z-index: 3; } +.progressi span { flex: 1; height: 3px; background: #555; } +.progressi span.vista { background: #eee; } +.chi { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 3; font-size: 13px; } +button.zona-avanti { position: fixed; top: 60px; bottom: 60px; left: 50%; right: 80px; background: transparent; border: 0; z-index: 2; cursor: pointer; } +button.chiudi { position: fixed; top: 16px; right: 24px; z-index: 4; background: #333; color: #eee; border: 1px solid #777; width: 44px; height: 44px; font-size: 20px; cursor: pointer; } diff --git a/tools/Febe.SitoDiProva/Risorse/sito.js b/tools/Febe.SitoDiProva/Risorse/sito.js new file mode 100644 index 0000000..c31b192 --- /dev/null +++ b/tools/Febe.SitoDiProva/Risorse/sito.js @@ -0,0 +1,246 @@ +// Sito di prova di Febe (specifica §14.2). Pagine spoglie che caricano i dati in JSON con fetch, come fa un sito +// vero: è ciò che la cattura di Febe riceve. Nessun marchio, nessuna pagina di accesso. +'use strict'; +(() => { + const corpo = document.body; + const qs = new URLSearchParams(location.search); + + function el(tag, attributi, ...figli) { + const nodo = document.createElement(tag); + for (const [nome, valore] of Object.entries(attributi || {})) { + if (valore === null || valore === undefined || valore === false) continue; + if (nome === 'testo') nodo.textContent = valore; + else nodo.setAttribute(nome, valore === true ? '' : String(valore)); + } + for (const figlio of figli) if (figlio) nodo.appendChild(figlio); + return nodo; + } + + function avviso(testo) { + const principale = document.querySelector('main') || corpo; + principale.appendChild(el('div', { class: 'avviso', role: 'status', testo })); + } + + async function carica(indirizzo) { + const risposta = await fetch(indirizzo, { credentials: 'same-origin', headers: { Accept: 'application/json' } }); + let dati = null; + try { dati = await risposta.json(); } catch { dati = null; } + if (risposta.status === 401) { location.href = '/sessione-scaduta'; throw new Error('sessione'); } + if (risposta.status === 403 && dati && dati.errore === 'verifica') { location.href = '/verifica'; throw new Error('verifica'); } + if (risposta.status === 429) { avviso('Troppe richieste: riprova più tardi.'); throw new Error('troppe'); } + if (!risposta.ok) throw new Error('stato ' + risposta.status); + return dati; + } + + // La versione più piccola per mostrare, la più grande non serve alla pagina. + function piccola(versioni) { + if (!versioni || !versioni.length) return null; + return versioni.reduce((a, b) => (a.larghezza * a.altezza <= b.larghezza * b.altezza ? a : b)).indirizzo; + } + + function copertina(contenuto) { + if (contenuto.foto) return piccola(contenuto.foto); + if (contenuto.parti && contenuto.parti.length) return piccola(contenuto.parti[0].foto); + return null; + } + + function percorsoSicuro(p) { + return typeof p === 'string' && p.startsWith('/') && !p.startsWith('//') ? p : '/'; + } + + // Carica altre pagine quando la sentinella si avvicina alla parte visibile, come un sito che scorre all'infinito. + function scorrimentoInfinito(sentinella, prossima) { + let occupato = false; + let finito = false; + const osservatore = new IntersectionObserver(async (voci) => { + if (!voci.some((v) => v.isIntersecting) || occupato || finito) return; + occupato = true; + try { finito = !(await prossima()); } catch { finito = true; } + occupato = false; + if (!finito) { osservatore.unobserve(sentinella); osservatore.observe(sentinella); } + }, { rootMargin: '0px 0px 300px 0px' }); + osservatore.observe(sentinella); + } + + function articolo(contenuto) { + const autore = contenuto.autore ? contenuto.autore.nome : ''; + const immagine = copertina(contenuto); + return el('article', {}, + el('header', {}, el('a', { href: '/profilo/' + encodeURIComponent(autore) + '/', testo: autore })), + el('a', { href: '/post/' + encodeURIComponent(contenuto.sigla || '') + '/' }, immagine ? el('img', { src: immagine, alt: '' }) : null), + el('p', { testo: contenuto.testo || '' })); + } + + function tessera(contenuto) { + const immagine = copertina(contenuto); + const segno = contenuto.fissato ? 'Fissato' : (contenuto.parti ? 'Serie' : (contenuto.filmati ? 'Video' : '')); + return el('a', { href: '/post/' + encodeURIComponent(contenuto.sigla || '') + '/' }, + immagine ? el('img', { src: immagine, alt: '' }) : null, + segno ? el('span', { class: 'segno', testo: segno }) : null); + } + + async function inizio() { + const barra = document.getElementById('barra'); + const flusso = document.getElementById('flusso'); + const dati = await carica('/dati/inizio'); + for (const p of dati.barra || []) { + barra.appendChild(el('a', { href: '/storie/' + encodeURIComponent(p.nome) + '/?da=%2F', 'aria-label': 'Storie di ' + p.nome }, + el('img', { src: piccola(p.ritratto), alt: '' }), el('span', { testo: p.nome }))); + } + for (const c of dati.contenuti || []) flusso.appendChild(articolo(c)); + let pagina = dati.pagina || {}; + scorrimentoInfinito(document.getElementById('sentinella'), async () => { + if (!pagina.altro) return false; + const altri = await carica('/dati/inizio/altri?dopo=' + encodeURIComponent(pagina.dopo)); + for (const c of altri.contenuti || []) flusso.appendChild(articolo(c)); + pagina = altri.pagina || {}; + return !!pagina.altro; + }); + } + + async function profilo() { + const utente = corpo.dataset.utente; + const scheda = corpo.dataset.scheda; + const dopo = qs.get('dopo'); + const dati = await carica('/dati/profilo/' + encodeURIComponent(utente) + '?scheda=' + scheda + (dopo ? '&dopo=' + encodeURIComponent(dopo) : '')); + const p = dati.profilo; + const testata = document.getElementById('testata'); + const ritratto = piccola(p.ritratto); + if (p.ultima_storia) { + testata.appendChild(el('a', { class: 'anello', href: '/storie/' + encodeURIComponent(p.nome) + '/?da=' + encodeURIComponent(location.pathname), 'aria-label': 'Apri le storie di ' + p.nome }, + el('img', { src: ritratto, alt: '' }))); + } else { + testata.appendChild(el('img', { class: 'foto', src: ritratto, alt: 'Foto del profilo di ' + p.nome })); + } + testata.appendChild(el('div', {}, el('h1', { testo: p.nome }), el('p', { testo: p.nome_visibile + ' · ' + p.pubblicazioni + ' post' }))); + if (p.riservato && !p.seguito) { + document.getElementById('contenuto').appendChild(el('p', { class: 'avviso', testo: 'Questo profilo è privato.' })); + return; + } + const raccolte = document.getElementById('raccolte'); + for (const r of dati.raccolte || []) { + raccolte.appendChild(el('a', { href: '/evidenza/' + encodeURIComponent(r.numero) + '/?da=' + encodeURIComponent(location.pathname), 'aria-label': 'Raccolta ' + r.titolo }, + r.copertina ? el('img', { src: r.copertina.indirizzo, alt: '' }) : null, el('span', { testo: r.titolo }))); + } + const griglia = document.getElementById('griglia'); + for (const c of dati.contenuti || []) griglia.appendChild(tessera(c)); + let pagina = dati.pagina || {}; + scorrimentoInfinito(document.getElementById('sentinella'), async () => { + if (!pagina.altro) return false; + const altri = await carica('/dati/profilo/' + encodeURIComponent(utente) + '/altri?scheda=' + scheda + '&dopo=' + encodeURIComponent(pagina.dopo)); + for (const c of altri.contenuti || []) griglia.appendChild(tessera(c)); + pagina = altri.pagina || {}; + return !!pagina.altro; + }); + } + + async function seguiti() { + const elenco = document.getElementById('elenco'); + const dopo = qs.get('dopo'); + const riga = (p) => el('li', {}, el('img', { src: piccola(p.ritratto), alt: '' }), + el('a', { href: '/profilo/' + encodeURIComponent(p.nome) + '/', testo: p.nome }), el('span', { testo: p.nome_visibile })); + const dati = await carica('/dati/seguiti' + (dopo ? '?dopo=' + encodeURIComponent(dopo) : '')); + for (const p of dati.seguiti || []) elenco.appendChild(riga(p)); + let pagina = dati.pagina || {}; + scorrimentoInfinito(document.getElementById('sentinella'), async () => { + if (!pagina.altro) return false; + const altri = await carica('/dati/seguiti?dopo=' + encodeURIComponent(pagina.dopo)); + for (const p of altri.seguiti || []) elenco.appendChild(riga(p)); + pagina = altri.pagina || {}; + return !!pagina.altro; + }); + } + + async function post() { + const dati = await carica('/dati/post/' + encodeURIComponent(corpo.dataset.sigla)); + const c = dati.contenuto; + const contenitore = document.getElementById('contenuto'); + contenitore.appendChild(el('h1', { testo: (c.autore ? c.autore.nome : '') })); + for (const parte of c.parti || [c]) { + const immagine = piccola(parte.foto); + if (immagine) contenitore.appendChild(el('img', { src: immagine, alt: '', width: 480 })); + } + contenitore.appendChild(el('p', { testo: c.testo || '' })); + } + + // Visualizzatore di storie e raccolte: una voce alla volta, avanzamento da solo o con la zona «Storia successiva». + // Dopo l'ultima voce passa da solo all'account (o alla raccolta) successivo, come i siti veri: chi lo usa + // deve chiuderlo prima, se non vuole andare avanti. + async function visualizzatore(tipo) { + const parti = location.pathname.split('/').filter(Boolean); + let chiave = decodeURIComponent(parti[1] || ''); + const idIniziale = parti[2] ? decodeURIComponent(parti[2]) : null; + const origine = percorsoSicuro(qs.get('da')); + const durataFoto = Number(corpo.dataset.durata || 5000); + const palco = document.getElementById('palco'); + const progressi = document.getElementById('progressi'); + const chi = document.getElementById('chi'); + let voci = []; + let successivo = null; + let indice = 0; + let timer = null; + + async function apri(k) { + chiave = k; + if (tipo === 'storie') { + const g = await carica('/dati/storie/' + encodeURIComponent(k)); + voci = g.storie || []; + successivo = g.successivo; + chi.textContent = g.autore ? g.autore.nome : ''; + } else { + const g = await carica('/dati/evidenza/' + encodeURIComponent(k)); + voci = (g.raccolta && g.raccolta.contenuti) || []; + successivo = g.successiva; + chi.textContent = g.raccolta ? g.raccolta.titolo : ''; + } + } + + function chiudi() { + clearTimeout(timer); + location.href = origine; + } + + function mostra() { + const voce = voci[indice]; + history.replaceState(null, '', '/' + tipo + '/' + encodeURIComponent(chiave) + '/' + encodeURIComponent(voce.numero) + '/' + location.search); + palco.replaceChildren(); + if (voce.filmati) { + const conAudio = voce.filmati.filter((f) => f.audio !== false); + palco.appendChild(el('video', { src: piccola(conAudio.length ? conAudio : voce.filmati), muted: true, autoplay: true, playsinline: true })); + } else { + palco.appendChild(el('img', { src: piccola(voce.foto), alt: '' })); + } + progressi.replaceChildren(...voci.map((_, i) => el('span', { class: i <= indice ? 'vista' : '' }))); + clearTimeout(timer); + timer = setTimeout(avanti, voce.filmati ? Math.max(500, (voce.durata || 2) * 1000) : durataFoto); + } + + async function avanti() { + clearTimeout(timer); + if (indice + 1 < voci.length) { indice++; mostra(); return; } + if (successivo) { + await apri(successivo); + indice = 0; + if (voci.length) { mostra(); return; } + } + chiudi(); + } + + document.getElementById('avanti').addEventListener('click', () => { avanti(); }); + document.getElementById('chiudi').addEventListener('click', chiudi); + await apri(chiave); + if (!voci.length) { chiudi(); return; } + indice = idIniziale ? Math.max(0, voci.findIndex((v) => v.numero === idIniziale)) : 0; + mostra(); + } + + const avvio = { + inizio, + profilo, + seguiti, + post, + storie: () => visualizzatore('storie'), + evidenza: () => visualizzatore('evidenza'), + }[corpo.dataset.pagina]; + if (avvio) avvio().catch(() => {}); +})(); diff --git a/tools/Febe.SitoDiProva/SiteControl.cs b/tools/Febe.SitoDiProva/SiteControl.cs new file mode 100644 index 0000000..f2411c3 --- /dev/null +++ b/tools/Febe.SitoDiProva/SiteControl.cs @@ -0,0 +1,111 @@ +using System.Collections.Concurrent; + +namespace Febe.SitoDiProva; + +/// The stop cases the site can play (spec §14.2), switched by the tests through /_controllo. +public enum StopMode +{ + /// Everything works. + Normal, + + /// Data requests get HTTP 429 (Rallentamento). + TooManyRequests, + + /// Pages are redirected to /verifica; data requests get 403 and the page moves there (Verifica). + Challenge, + + /// The session cookie is removed and pages move to /sessione-scaduta (Disconnessione). + SessionEnded, + + /// Data requests return empty pages. + EmptyPages, + + /// Data requests return a shape no reader knows (the site «changed»). + UnknownFormat, +} + +/// Switches and counters of the test site. Thread-safe. +public sealed class SiteControl +{ + private readonly Lock _gate = new(); + private readonly ConcurrentQueue _dataRequests = new(); + private StopMode _mode = StopMode.Normal; + private int _armAfter; + + /// How long a photo story stays on screen before the viewer moves on by itself. + public TimeSpan StoryDuration { get; set; } = TimeSpan.FromSeconds(5); + + /// Validity of the CDN addresses handed out from now on. + public TimeSpan AddressLifetime { get; set; } = TimeSpan.FromHours(6); + + /// Paths with query of every data request, in arrival order (for the tests). + public IReadOnlyList DataRequests => [.. _dataRequests]; + + /// Number of files served by the CDN. + public int CdnFilesServed => _cdnFiles; + + /// Number of CDN requests refused because the address had expired. + public int CdnExpired => _cdnExpired; + + private int _cdnFiles; + private int _cdnExpired; + + public StopMode Mode + { + get + { + lock (_gate) + { + return _armAfter > 0 ? StopMode.Normal : _mode; + } + } + } + + /// Sets a stop case; with it starts after that many more data requests. + public void Set(StopMode mode, int afterDataRequests = 0) + { + lock (_gate) + { + _mode = mode; + _armAfter = Math.Max(0, afterDataRequests); + } + } + + /// Back to normal; counters cleared; default story duration and address lifetime. + public void Reset() + { + lock (_gate) + { + _mode = StopMode.Normal; + _armAfter = 0; + } + + _dataRequests.Clear(); + StoryDuration = TimeSpan.FromSeconds(5); + AddressLifetime = TimeSpan.FromHours(6); + Interlocked.Exchange(ref _cdnFiles, 0); + Interlocked.Exchange(ref _cdnExpired, 0); + } + + public void ClearRequests() => _dataRequests.Clear(); + + /// Records a data request and returns the mode that applies to it. + internal StopMode OnDataRequest(string pathAndQuery) + { + _dataRequests.Enqueue(pathAndQuery); + lock (_gate) + { + if (_armAfter > 0) + { + _armAfter--; + return StopMode.Normal; + } + + return _mode; + } + } + + internal void OnCdnServed() => Interlocked.Increment(ref _cdnFiles); + + internal void OnCdnExpired() => Interlocked.Increment(ref _cdnExpired); +} diff --git a/tools/Febe.SitoDiProva/TestSite.cs b/tools/Febe.SitoDiProva/TestSite.cs new file mode 100644 index 0000000..13355c7 --- /dev/null +++ b/tools/Febe.SitoDiProva/TestSite.cs @@ -0,0 +1,496 @@ +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json.Nodes; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace Febe.SitoDiProva; + +/// Options of the test site. +public sealed record TestSiteOptions +{ + /// Port of the site on 127.0.0.1; 0 picks a free one. + public int Port { get; init; } + + /// Port of the «CDN»; 0 picks a free one. + public int CdnPort { get; init; } + + /// Address of the «CDN»: a second loopback address, so cookies of the site do not reach it. + public string CdnAddress { get; init; } = "127.0.0.2"; + + /// Seed of the synthetic data. + public int Seed { get; init; } = 13; + + /// Clock of the site (dates, address expiry). + public TimeProvider Time { get; init; } = TimeProvider.System; + + /// Write requests to the console (the command-line tool does; tests do not). + public bool ConsoleLog { get; init; } +} + +/// +/// The local test site of spec §14.2, served on 127.0.0.1 with its «CDN» on a second address. Pages are plain and +/// fetch JSON in a synthetic format of our own; stop cases are switched through or the +/// /_controllo endpoints. Never Instagram, never anything that looks like it. +/// +public sealed class TestSite : IAsyncDisposable +{ + /// Name of the session cookie of the site. + public const string SessionCookie = "sessione_prova"; + + private readonly WebApplication _app; + private readonly TimeProvider _time; + + private TestSite(WebApplication app, World world, SiteControl control, MediaFactory media, CdnSigner signer, int sitePort, string cdnAddress, int cdnPort, TimeProvider time) + { + _app = app; + World = world; + Control = control; + Media = media; + Signer = signer; + SitePort = sitePort; + CdnAddress = cdnAddress; + CdnPort = cdnPort; + _time = time; + } + + public World World { get; } + + public SiteControl Control { get; } + + public MediaFactory Media { get; } + + public CdnSigner Signer { get; } + + public int SitePort { get; } + + public string CdnAddress { get; } + + public int CdnPort { get; } + + /// «127.0.0.1:port»: an entry for the host classifier. + public string SiteHost => $"127.0.0.1:{SitePort.ToString(CultureInfo.InvariantCulture)}"; + + public string CdnHost => $"{CdnAddress}:{CdnPort.ToString(CultureInfo.InvariantCulture)}"; + + public string SiteUrl => $"http://{SiteHost}"; + + public string CdnUrl => $"http://{CdnHost}"; + + public string Url(string path) => SiteUrl + path; + + public static async Task StartAsync(TestSiteOptions? options = null, CancellationToken ct = default) + { + options ??= new TestSiteOptions(); + var cdnAddress = CanBind(options.CdnAddress) ? options.CdnAddress : "127.0.0.1"; + var sitePort = options.Port > 0 ? options.Port : FreePort(IPAddress.Loopback); + var cdnPort = options.CdnPort > 0 ? options.CdnPort : FreePort(IPAddress.Parse(cdnAddress)); + if (cdnAddress == "127.0.0.1" && cdnPort == sitePort) + { + cdnPort = FreePort(IPAddress.Loopback); + } + + var world = World.Generate(options.Seed, options.Time.GetUtcNow()); + var control = new SiteControl(); + var media = new MediaFactory(); + var signer = new CdnSigner(); + + var builder = WebApplication.CreateSlimBuilder(); + builder.Services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(2)); + builder.Logging.ClearProviders(); + if (options.ConsoleLog) + { + builder.Logging.AddSimpleConsole(o => o.SingleLine = true); + builder.Logging.SetMinimumLevel(LogLevel.Warning); + } + + builder.WebHost.UseKestrel(k => + { + k.Listen(IPAddress.Loopback, sitePort); + k.Listen(IPAddress.Parse(cdnAddress), cdnPort); + }); + + var app = builder.Build(); + var site = new TestSite(app, world, control, media, signer, sitePort, cdnAddress, cdnPort, options.Time); + app.Run(site.HandleAsync); + await app.StartAsync(ct).ConfigureAwait(false); + return site; + } + + public async ValueTask DisposeAsync() + { + await _app.StopAsync().ConfigureAwait(false); + await _app.DisposeAsync().ConfigureAwait(false); + } + + /// The JSON of a data endpoint as the page would receive it (sample capture, tests). + public async Task GetDataAsync(string pathAndQuery, CancellationToken ct = default) + { + using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false }); + return await client.GetStringAsync(new Uri(Url(pathAndQuery)), ct).ConfigureAwait(false); + } + + private DataApi Api => new(World, Signer, Control, () => CdnUrl, _time); + + private async Task HandleAsync(HttpContext context) + { + context.Response.Headers.CacheControl = "no-store"; + if (context.Connection.LocalPort == CdnPort && context.Connection.LocalIpAddress?.ToString() == CdnAddress) + { + await ServeCdnAsync(context).ConfigureAwait(false); + return; + } + + var path = context.Request.Path.Value ?? "/"; + if (path.StartsWith("/_controllo/", StringComparison.Ordinal)) + { + await ControlAsync(context, path["/_controllo/".Length..]).ConfigureAwait(false); + return; + } + + if (path.StartsWith("/risorse/", StringComparison.Ordinal)) + { + await ResourceAsync(context, path["/risorse/".Length..]).ConfigureAwait(false); + return; + } + + if (path.StartsWith("/dati/", StringComparison.Ordinal)) + { + await DataAsync(context, path).ConfigureAwait(false); + return; + } + + await PageAsync(context, path).ConfigureAwait(false); + } + + private async Task PageAsync(HttpContext context, string path) + { + var mode = Control.Mode; + if (path is "/verifica" or "/verifica/") + { + await HtmlAsync(context, 200, Pages.Challenge()).ConfigureAwait(false); + return; + } + + if (path is "/sessione-scaduta" or "/sessione-scaduta/") + { + await HtmlAsync(context, 200, Pages.SessionEnded()).ConfigureAwait(false); + return; + } + + if (path == "/favicon.ico") + { + context.Response.StatusCode = 404; + return; + } + + switch (mode) + { + case StopMode.Challenge: + context.Response.Redirect("/verifica?motivo=prova"); + return; + case StopMode.SessionEnded: + ExpireSession(context); + context.Response.Redirect("/sessione-scaduta"); + return; + } + + if (!context.Request.Cookies.ContainsKey(SessionCookie)) + { + context.Response.Cookies.Append(SessionCookie, "attiva", new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true }); + } + + var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray(); + string html; + var status = 200; + lock (World.Gate) + { + switch (segments) + { + case []: + html = Pages.Home(); + break; + case ["profilo", var user, ..] when World.FindByUsername(user) is null: + html = Pages.ProfileNotFound(user); + status = 404; + break; + case ["profilo", var user]: + html = Pages.Profile(user, ProfileTab.Posts); + break; + case ["profilo", var user, "reel"]: + html = Pages.Profile(user, ProfileTab.Reels); + break; + case ["profilo", var user, "taggati"]: + html = Pages.Profile(user, ProfileTab.Tagged); + break; + case ["profilo", var user, "seguiti"] when World.FindByUsername(user)?.IsViewer == true: + html = Pages.Following(user); + break; + case ["post", var code, ..]: + html = Pages.Post(code); + break; + case ["storie", _, ..]: + html = Pages.Viewer("storie", Control.StoryDuration); + break; + case ["evidenza", _, ..]: + html = Pages.Viewer("evidenza", Control.StoryDuration); + break; + default: + html = Pages.NotFound(); + status = 404; + break; + } + } + + await HtmlAsync(context, status, html).ConfigureAwait(false); + } + + private async Task DataAsync(HttpContext context, string path) + { + var query = context.Request.Query; + var mode = Control.OnDataRequest(path + context.Request.QueryString.Value); + switch (mode) + { + case StopMode.TooManyRequests: + await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false); + return; + case StopMode.Challenge: + await JsonAsync(context, 403, new JsonObject { ["errore"] = "verifica" }).ConfigureAwait(false); + return; + case StopMode.SessionEnded: + ExpireSession(context); + await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione" }).ConfigureAwait(false); + return; + case StopMode.EmptyPages: + await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false); + return; + case StopMode.UnknownFormat: + await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false); + return; + } + + var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray(); + var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts }; + var after = query["dopo"].ToString(); + JsonObject? result; + lock (World.Gate) + { + var api = Api; + result = segments switch + { + ["dati", "inizio"] => api.Home(), + ["dati", "inizio", "altri"] => api.HomeMore(after), + ["dati", "profilo", var user] => api.Profile(user, tab, after), + ["dati", "profilo", var user, "altri"] => api.ProfileMore(user, tab, after), + ["dati", "post", var code] => api.SinglePost(code), + ["dati", "storie", var user] => api.Stories(user), + ["dati", "evidenza", var id] => api.HighlightItems(id), + ["dati", "seguiti"] => api.Following(after), + _ => null, + }; + } + + if (result is null) + { + await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false); + return; + } + + await JsonAsync(context, 200, result).ConfigureAwait(false); + } + + private async Task ServeCdnAsync(HttpContext context) + { + var path = context.Request.Path.Value ?? string.Empty; + var query = context.Request.Query; + var check = Signer.Check(path, query["scad"].ToString(), query["firma"].ToString(), _time.GetUtcNow()); + if (check != CdnCheck.Valid) + { + if (check == CdnCheck.Expired) + { + Control.OnCdnExpired(); + } + + context.Response.StatusCode = 403; + context.Response.ContentType = "text/plain; charset=utf-8"; + await context.Response.WriteAsync(check == CdnCheck.Expired ? "Indirizzo scaduto." : "Firma non valida.").ConfigureAwait(false); + return; + } + + // /m/{key}/{w}x{h}.jpg, /m/{key}/{w}x{h}.mp4, /m/{key}/{w}x{h}-muto.mp4 + var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries); + if (segments is not ["m", var key, var file] || !TryParseSize(file, out var width, out var height, out var extension, out var silent)) + { + context.Response.StatusCode = 404; + return; + } + + var bytes = extension == "mp4" ? Media.Video(key, width, height, !silent) : Media.Picture(key, width, height); + Control.OnCdnServed(); + context.Response.ContentType = extension == "mp4" ? "video/mp4" : "image/jpeg"; + context.Response.ContentLength = bytes.Length; + await context.Response.Body.WriteAsync(bytes).ConfigureAwait(false); + } + + private async Task ControlAsync(HttpContext context, string command) + { + var q = context.Request.Query; + JsonObject answer = new() { ["ok"] = true }; + lock (World.Gate) + { + switch (command) + { + case "stato": + answer["modo"] = Control.Mode.ToString(); + answer["richieste"] = Control.DataRequests.Count; + break; + case "modo": + var mode = q["valore"].ToString() switch + { + "troppe-richieste" => StopMode.TooManyRequests, + "verifica" => StopMode.Challenge, + "sessione-scaduta" => StopMode.SessionEnded, + "vuoto" => StopMode.EmptyPages, + "formato-sconosciuto" => StopMode.UnknownFormat, + _ => StopMode.Normal, + }; + Control.Set(mode, int.TryParse(q["dopo"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var after) ? after : 0); + answer["modo"] = mode.ToString(); + break; + case "reimposta": + Control.Reset(); + break; + case "durata-storie": + Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture)); + break; + case "scadenza-indirizzi": + Control.AddressLifetime = TimeSpan.FromSeconds(int.Parse(q["secondi"].ToString(), CultureInfo.InvariantCulture)); + break; + case "rinomina": + var account = World.FindByUsername(q["da"].ToString()); + if (account is null) + { + answer["ok"] = false; + } + else + { + account.Username = q["a"].ToString(); + } + + break; + case "ritratto": + if (World.FindByUsername(q["nome"].ToString()) is { } owner) + { + owner.PictureVersion++; + } + + break; + case "pubblica": + if (World.FindByUsername(q["nome"].ToString()) is { } author) + { + var post = World.Publish(author, q["tipo"].ToString() is { Length: > 0 } t ? t : "foto", _time.GetUtcNow()); + answer["sigla"] = post.Code; + answer["numero"] = post.Id; + } + + break; + default: + answer["ok"] = false; + break; + } + } + + await JsonAsync(context, answer["ok"]!.GetValue() ? 200 : 400, answer).ConfigureAwait(false); + } + + private static async Task ResourceAsync(HttpContext context, string name) + { + if (name is not ("sito.js" or "sito.css")) + { + context.Response.StatusCode = 404; + return; + } + + await using var stream = typeof(TestSite).Assembly.GetManifestResourceStream($"Febe.SitoDiProva.Risorse.{name}"); + if (stream is null) + { + context.Response.StatusCode = 404; + return; + } + + context.Response.ContentType = name.EndsWith(".js", StringComparison.Ordinal) ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8"; + await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); + } + + private static void ExpireSession(HttpContext context) => + context.Response.Cookies.Delete(SessionCookie, new CookieOptions { Path = "/" }); + + private static Task HtmlAsync(HttpContext context, int status, string html) + { + context.Response.StatusCode = status; + context.Response.ContentType = "text/html; charset=utf-8"; + return context.Response.WriteAsync(html); + } + + private static Task JsonAsync(HttpContext context, int status, JsonObject body) + { + context.Response.StatusCode = status; + context.Response.ContentType = "application/json; charset=utf-8"; + return context.Response.WriteAsync(body.ToJsonString(), Encoding.UTF8); + } + + private static bool TryParseSize(string file, out int width, out int height, out string extension, out bool silent) + { + width = height = 0; + extension = string.Empty; + silent = false; + var dot = file.LastIndexOf('.'); + if (dot < 0) + { + return false; + } + + extension = file[(dot + 1)..]; + var name = file[..dot]; + if (name.EndsWith("-muto", StringComparison.Ordinal)) + { + silent = true; + name = name[..^"-muto".Length]; + } + + var x = name.IndexOf('x', StringComparison.Ordinal); + return x > 0 + && int.TryParse(name.AsSpan(0, x), NumberStyles.Integer, CultureInfo.InvariantCulture, out width) + && int.TryParse(name.AsSpan(x + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out height) + && extension is "jpg" or "mp4"; + } + + private static bool CanBind(string address) + { + try + { + using var probe = new TcpListener(IPAddress.Parse(address), 0); + probe.Start(); + probe.Stop(); + return true; + } + catch (Exception ex) when (ex is SocketException or FormatException) + { + return false; + } + } + + private static int FreePort(IPAddress address) + { + var probe = new TcpListener(address, 0); + probe.Start(); + var port = ((IPEndPoint)probe.LocalEndpoint).Port; + probe.Stop(); + return port; + } +} diff --git a/tools/Febe.SitoDiProva/World.cs b/tools/Febe.SitoDiProva/World.cs new file mode 100644 index 0000000..a0869c3 --- /dev/null +++ b/tools/Febe.SitoDiProva/World.cs @@ -0,0 +1,387 @@ +using System.Globalization; + +namespace Febe.SitoDiProva; + +/// One file of a post or story: a photo or a short video, served by the «CDN» in several sizes. +public sealed class SiteFile +{ + public required string Id { get; init; } + + public required bool IsVideo { get; init; } + + /// Size of the largest version. + public required int Width { get; init; } + + public required int Height { get; init; } + + /// Video duration in seconds. + public double DurationSeconds { get; init; } + + /// Key of the generated content on the CDN: same key, same picture at every size. + public string MediaKey => "f" + Id; +} + +/// A post of the grid (a reel when it is a single video). +public sealed class SitePost +{ + public required string Id { get; init; } + + public required string Code { get; init; } + + public required DateTimeOffset PublishedAt { get; init; } + + public required string Caption { get; init; } + + public required SiteAccount Owner { get; init; } + + public bool Pinned { get; set; } + + public bool IsReel { get; init; } + + public required IReadOnlyList Files { get; init; } + + /// Accounts tagged in the post (it appears in their «Taggati» tab). + public List Tagged { get; } = []; +} + +/// A story (24 hours) or an item of a highlight collection. +public sealed class SiteStory +{ + public required string Id { get; init; } + + public required DateTimeOffset PublishedAt { get; init; } + + public required SiteAccount Owner { get; init; } + + public required SiteFile File { get; init; } + + public DateTimeOffset ExpiresAt => PublishedAt.AddHours(24); +} + +public sealed class SiteHighlight +{ + public required string Id { get; init; } + + public required string Title { get; init; } + + public required SiteAccount Owner { get; init; } + + public List Items { get; } = []; +} + +public sealed class SiteAccount +{ + public required string Id { get; init; } + + /// Current user name (it can change: rename detection). + public required string Username { get; set; } + + public required string DisplayName { get; init; } + + public bool IsPrivate { get; init; } + + /// Alberto follows this profile. + public bool FollowedByViewer { get; init; } + + /// This is Alberto's account (the connected one). + public bool IsViewer { get; init; } + + /// Incremented when the profile picture changes. + public int PictureVersion { get; set; } = 1; + + /// Posts, newest first. + public List Posts { get; } = []; + + /// Active stories, oldest first (viewing order). + public List Stories { get; } = []; + + public List Highlights { get; } = []; + + public string PictureKey => $"ritratto-{Id}-{PictureVersion.ToString(CultureInfo.InvariantCulture)}"; + + public DateTimeOffset? LatestStoryAt(DateTimeOffset now) => + Stories.Where(s => s.ExpiresAt > now).Select(s => (DateTimeOffset?)s.PublishedAt).Max(); +} + +/// Which tab of a profile. +public enum ProfileTab +{ + Posts, + Reels, + Tagged, +} + +/// +/// The synthetic world of the test site, generated from a seed (spec §14.2): Alberto's account, followed and not +/// followed profiles, a private one he follows and one he does not, posts with several files, videos, pinned posts, +/// stories, highlight collections, tagged posts and reels. Nothing here is real or imitates Instagram's data. +/// +/// Thread-safety: callers hold while reading or changing the world. +public sealed class World +{ + private const string CodeAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789"; + + private static readonly string[] Words = + [ + "mare", "montagna", "colazione", "tramonto", "libro", "gatto", "bicicletta", "concerto", "pioggia", "giardino", + "lago", "treno", "mercato", "pane", "neve", "festa", "museo", "ponte", "piazza", "sentiero", + ]; + + private readonly Random _random; + private readonly HashSet _codes = new(StringComparer.Ordinal); + private long _nextPostId = 3_100_000_000; + private long _nextFileId = 5_200_000_000; + private long _nextStoryId = 7_300_000_000; + private long _nextHighlightId = 8_400_000_000; + + private World(int seed, DateTimeOffset now) + { + _random = new Random(seed); + Seed = seed; + CreatedAt = now; + } + + public Lock Gate { get; } = new(); + + public int Seed { get; } + + public DateTimeOffset CreatedAt { get; } + + public List Accounts { get; } = []; + + public SiteAccount Viewer => Accounts.First(a => a.IsViewer); + + /// Generates the world. anchors every date (stories are active for 24 hours from it). + public static World Generate(int seed, DateTimeOffset now) + { + var world = new World(seed, new DateTimeOffset(now.UtcDateTime.Ticks - (now.UtcDateTime.Ticks % TimeSpan.TicksPerSecond), TimeSpan.Zero)); + world.Build(); + return world; + } + + public SiteAccount? FindByUsername(string username) => + Accounts.FirstOrDefault(a => string.Equals(a.Username, username, StringComparison.OrdinalIgnoreCase)); + + public SiteAccount? FindById(string id) => Accounts.FirstOrDefault(a => a.Id == id); + + public SitePost? FindPost(string code) => + Accounts.SelectMany(a => a.Posts).FirstOrDefault(p => string.Equals(p.Code, code, StringComparison.Ordinal)); + + public SiteHighlight? FindHighlight(string id) => + Accounts.SelectMany(a => a.Highlights).FirstOrDefault(h => h.Id == id); + + public SiteFile? FindFile(string mediaKey) => + Accounts.SelectMany(a => a.Posts.SelectMany(p => p.Files) + .Concat(a.Stories.Select(s => s.File)) + .Concat(a.Highlights.SelectMany(h => h.Items.Select(i => i.File)))) + .FirstOrDefault(f => f.MediaKey == mediaKey); + + /// Profiles Alberto follows, in the order of his list. + public IReadOnlyList Following => [.. Accounts.Where(a => a.FollowedByViewer)]; + + /// Followed profiles with active stories, latest story first (the stories bar). + public IReadOnlyList StoryBar(DateTimeOffset now) => + [.. Accounts.Where(a => a.FollowedByViewer && a.LatestStoryAt(now) is not null).OrderByDescending(a => a.LatestStoryAt(now))]; + + /// Recent posts of followed profiles, newest first (the home feed). + public IReadOnlyList Feed() => + [.. Accounts.Where(a => a.FollowedByViewer).SelectMany(a => a.Posts).OrderByDescending(p => p.PublishedAt).ThenBy(p => p.Id, StringComparer.Ordinal)]; + + /// The posts of a profile tab: pinned posts first on the main grid, then newest first. + public IReadOnlyList Grid(SiteAccount account, ProfileTab tab) => tab switch + { + ProfileTab.Posts => [.. account.Posts.Where(p => p.Pinned).OrderByDescending(p => p.PublishedAt), .. account.Posts.Where(p => !p.Pinned)], + ProfileTab.Reels => [.. account.Posts.Where(p => p.IsReel)], + ProfileTab.Tagged => [.. Accounts.SelectMany(a => a.Posts).Where(p => p.Tagged.Contains(account)).OrderByDescending(p => p.PublishedAt)], + _ => [], + }; + + /// A new post on top of an account (control endpoint «pubblica»). + public SitePost Publish(SiteAccount account, string kind, DateTimeOffset at) + { + var post = NewPost(account, at, kind); + account.Posts.Insert(0, post); + return post; + } + + /// A new active story (control endpoint «storia»). + public SiteStory AddStory(SiteAccount account, bool video, DateTimeOffset at) + { + var story = NewStory(account, at, video); + account.Stories.Add(story); + return story; + } + + private void Build() + { + var now = CreatedAt; + var me = Add("1000", "alberto.prova", "Alberto (prova)", followed: false, viewer: true); + var marta = Add("1001", "marta.prova", "Marta di prova", followed: true); + var luca = Add("1002", "luca.prova", "Luca di prova", followed: true); + var giulia = Add("1003", "giulia.prova", "Giulia di prova", followed: true, isPrivate: true); + var nadia = Add("1004", "nadia.prova", "Nadia di prova", followed: true); + var paolo = Add("1005", "paolo.prova", "Paolo di prova", followed: false); + var riservato = Add("1006", "riservato.prova", "Profilo riservato", followed: false, isPrivate: true); + for (var i = 1; i <= 24; i++) + { + var n = i.ToString("00", CultureInfo.InvariantCulture); + Add((1100 + i).ToString(CultureInfo.InvariantCulture), $"amico{n}.prova", $"Amico {n}", followed: true); + } + + // Posts, oldest first, so that each list ends newest first. + AddPosts(me, 4, now.AddDays(-30), TimeSpan.FromDays(5), i => "foto"); + AddPosts(marta, 18, now.AddDays(-30), TimeSpan.FromHours(38), i => (i % 5) switch { 0 => "serie", 2 => "video", _ => "foto" }); + AddPosts(luca, 40, now.AddDays(-80), TimeSpan.FromHours(46), i => i % 7 == 3 ? "video" : "foto"); + AddPosts(giulia, 6, now.AddDays(-20), TimeSpan.FromDays(3), i => i == 2 ? "serie" : "foto"); + AddPosts(nadia, 3, now.AddDays(-10), TimeSpan.FromDays(3), i => "foto"); + AddPosts(paolo, 8, now.AddDays(-15), TimeSpan.FromDays(1.5), i => i == 5 ? "serie" : "foto"); + AddPosts(riservato, 5, now.AddDays(-15), TimeSpan.FromDays(2), i => "foto"); + foreach (var friend in Accounts.Where(a => a.Username.StartsWith("amico", StringComparison.Ordinal))) + { + AddPosts(friend, 1 + _random.Next(2), now.AddDays(-40 - _random.Next(20)), TimeSpan.FromDays(4), i => "foto"); + } + + // Two of Marta's older posts are pinned on top of her grid. + marta.Posts[8].Pinned = true; + marta.Posts[12].Pinned = true; + + // Tagged posts: Luca and Paolo tag Marta; Marta tags Alberto. + luca.Posts[3].Tagged.Add(marta); + luca.Posts[9].Tagged.Add(marta); + paolo.Posts[2].Tagged.Add(marta); + marta.Posts[4].Tagged.Add(me); + + // Stories, oldest first; the bar order is Marta, Nadia, Luca, Giulia. + AddStories(marta, now, [-10, -8, -5, -1], videoAt: 2); + AddStories(nadia, now, [-6, -4, -2], videoAt: -1); + AddStories(luca, now, [-9, -3], videoAt: -1); + AddStories(giulia, now, [-20, -16, -12, -8, -4], videoAt: 3); + AddStories(paolo, now, [-7], videoAt: -1); + + // Highlights: Marta's «Estate» also holds one of her active stories, with the same identifier (H9). + var summer = NewHighlight(marta, "Estate"); + summer.Items.Add(NewStory(marta, now.AddDays(-60), video: false)); + summer.Items.Add(NewStory(marta, now.AddDays(-59), video: true)); + summer.Items.Add(marta.Stories[1]); + var travels = NewHighlight(marta, "Viaggi"); + travels.Items.Add(NewStory(marta, now.AddDays(-90), video: false)); + travels.Items.Add(NewStory(marta, now.AddDays(-89), video: false)); + var mountains = NewHighlight(luca, "Montagna"); + mountains.Items.Add(NewStory(luca, now.AddDays(-120), video: false)); + mountains.Items.Add(NewStory(luca, now.AddDays(-119), video: false)); + } + + private SiteAccount Add(string id, string username, string displayName, bool followed, bool viewer = false, bool isPrivate = false) + { + var account = new SiteAccount + { + Id = id, + Username = username, + DisplayName = displayName, + FollowedByViewer = followed, + IsViewer = viewer, + IsPrivate = isPrivate, + }; + Accounts.Add(account); + return account; + } + + private void AddPosts(SiteAccount account, int count, DateTimeOffset first, TimeSpan step, Func kind) + { + for (var i = 0; i < count; i++) + { + var jitter = TimeSpan.FromMinutes(_random.Next(0, 180)); + account.Posts.Insert(0, NewPost(account, first + (step * i) + jitter, kind(i))); + } + } + + private void AddStories(SiteAccount account, DateTimeOffset now, int[] hoursAgo, int videoAt) + { + for (var i = 0; i < hoursAgo.Length; i++) + { + account.Stories.Add(NewStory(account, now.AddHours(hoursAgo[i]).AddMinutes(-_random.Next(0, 30)), video: i == videoAt)); + } + } + + private SitePost NewPost(SiteAccount account, DateTimeOffset at, string kind) + { + var files = kind switch + { + "serie" => new List { NewPhoto(960, 1200), NewVideo(720, 1280), NewPhoto(960, 1200) }, + "video" => [NewVideo(720, 1280)], + _ => [NewPhoto(960, 1200)], + }; + return new SitePost + { + Id = (_nextPostId += 7919 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture), + Code = NewCode(), + PublishedAt = at, + Caption = Caption(), + Owner = account, + IsReel = kind == "video", + Files = files, + }; + } + + private SiteStory NewStory(SiteAccount account, DateTimeOffset at, bool video) => new() + { + Id = (_nextStoryId += 104_729 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture), + PublishedAt = at, + Owner = account, + File = video ? NewVideo(720, 1280) : NewPhoto(720, 1280), + }; + + private SiteHighlight NewHighlight(SiteAccount account, string title) + { + var highlight = new SiteHighlight + { + Id = (_nextHighlightId += 15_485_863).ToString(CultureInfo.InvariantCulture), + Title = title, + Owner = account, + }; + account.Highlights.Add(highlight); + return highlight; + } + + private SiteFile NewPhoto(int width, int height) => new() + { + Id = (_nextFileId += 1_299_709 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture), + IsVideo = false, + Width = width, + Height = height, + }; + + private SiteFile NewVideo(int width, int height) => new() + { + Id = (_nextFileId += 1_299_709 + _random.Next(1000)).ToString(CultureInfo.InvariantCulture), + IsVideo = true, + Width = width, + Height = height, + DurationSeconds = 2, + }; + + private string NewCode() + { + while (true) + { + var chars = new char[7]; + for (var i = 0; i < chars.Length; i++) + { + chars[i] = CodeAlphabet[_random.Next(CodeAlphabet.Length)]; + } + + var code = new string(chars); + if (_codes.Add(code)) + { + return code; + } + } + } + + private string Caption() + { + var a = Words[_random.Next(Words.Length)]; + var b = Words[_random.Next(Words.Length)]; + return $"Una giornata fra {a} e {b} (prova {_random.Next(1, 1000).ToString(CultureInfo.InvariantCulture)})"; + } +} diff --git a/tools/Febe.Sonda/Febe.Sonda.csproj b/tools/Febe.Sonda/Febe.Sonda.csproj index dbe4f13..7c3b8c2 100644 --- a/tools/Febe.Sonda/Febe.Sonda.csproj +++ b/tools/Febe.Sonda/Febe.Sonda.csproj @@ -10,6 +10,10 @@ + + + + diff --git a/tools/Febe.Sonda/ProbeRecorder.cs b/tools/Febe.Sonda/ProbeRecorder.cs new file mode 100644 index 0000000..70f1b85 --- /dev/null +++ b/tools/Febe.Sonda/ProbeRecorder.cs @@ -0,0 +1,272 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.Browser.Capture; +using Febe.Browser.Cdp; +using Febe.Core.Abstractions; +using Febe.Core.Collection; + +namespace Febe.Sonda; + +/// Refuses sample folders inside a git repository (spec §14.5: raw samples stay outside the repository). +public static class RepositoryGuard +{ + /// The repository that contains (its root), or null. + public static string? FindRepository(string folder) + { + var current = new DirectoryInfo(Path.GetFullPath(folder)); + while (current is not null) + { + var marker = Path.Combine(current.FullName, ".git"); + if (Directory.Exists(marker) || File.Exists(marker)) + { + return current.FullName; + } + + current = current.Parent; + } + + return null; + } + + /// The folder is inside a repository. + public static void EnsureOutside(string folder) + { + if (FindRepository(folder) is { } repository) + { + throw new InvalidOperationException( + $"La cartella «{Path.GetFullPath(folder)}» sta dentro un repository git ({repository}): i campioni grezzi contengono dati di altre persone e devono stare fuori dal repository (specifica §14.5). Scegli un'altra cartella."); + } + } +} + +/// Counters of a recording. +public sealed record ProbeStats(int Responses, int Navigations, int Interactions); + +/// +/// The passive probe of M0 (spec §14.5): while Alberto browses by hand, it stores every JSON response the page receives +/// (sanitized descriptor + body) and, for the elements he hovers and focuses, the attributes useful to the target map +/// (role, accessible name, aria-label, link shape), read with a read-only Runtime.evaluate polled every few +/// hundred milliseconds. It never navigates and never performs a gesture: no Input.* command is ever sent. +/// +/// Raw files: risposte/NNNNNN.json, navigazioni.jsonl, interazioni.jsonl. +public sealed class ProbeRecorder : IResponseConsumer, IResponseObserver, IAsyncDisposable +{ + /// Read-only description of the hovered and focused interactive elements. + internal const string InteractionScript = """ + (() => { + const clean = (s) => (s || '').replace(/\s+/g, ' ').trim().slice(0, 160); + const interactive = (el) => el && el.closest ? el.closest('a[href], button, [role], input, textarea, select, summary, [tabindex]') : null; + const shape = (href) => { + try { + const u = new URL(href, document.baseURI); + return { host: u.host, path: u.pathname }; + } catch { return null; } + }; + const describe = (el) => { + if (!el || el === document.body || el === document.documentElement) return null; + const link = el.getAttribute('href'); + return { + tag: el.tagName.toLowerCase(), + role: clean(el.getAttribute('role')), + ariaLabel: clean(el.getAttribute('aria-label')), + name: clean(el.getAttribute('aria-label') || el.getAttribute('alt') || el.getAttribute('title') || el.textContent), + href: link ? shape(link) : null, + type: clean(el.getAttribute('type')), + }; + }; + const hovered = document.querySelectorAll(':hover'); + return { + path: location.pathname, + hover: describe(interactive(hovered.length ? hovered[hovered.length - 1] : null)), + focus: describe(interactive(document.activeElement)), + }; + })() + """; + + private readonly ICdpSession _cdp; + private readonly HostClassifier _hosts; + private readonly IClock _clock; + private readonly string _folder; + private readonly TimeSpan _pollEvery; + private readonly SemaphoreSlim _write = new(1, 1); + private readonly CancellationTokenSource _stop = new(); + private ResponseTap? _tap; + private Task? _poller; + private int _responses; + private int _navigations; + private int _interactions; + private string? _lastHover; + private string? _lastFocus; + + public ProbeRecorder(ICdpSession cdp, HostClassifier hosts, string folder, IClock? clock = null, TimeSpan? pollEvery = null) + { + _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); + _hosts = hosts ?? throw new ArgumentNullException(nameof(hosts)); + _folder = Path.GetFullPath(folder); + _clock = clock ?? new SystemClock(); + _pollEvery = pollEvery ?? TimeSpan.FromMilliseconds(400); + } + + public string Folder => _folder; + + public ProbeStats Stats => new(Volatile.Read(ref _responses), Volatile.Read(ref _navigations), Volatile.Read(ref _interactions)); + + public async Task StartAsync(CancellationToken ct = default) + { + RepositoryGuard.EnsureOutside(_folder); + Directory.CreateDirectory(Path.Combine(_folder, "risposte")); + await File.WriteAllTextAsync( + Path.Combine(_folder, "LEGGIMI.txt"), + "Campioni GREZZI della sonda di Febe: contengono dati personali di Alberto e di altre persone.\n" + + "Non vanno nel repository e non si inviano: si ripuliscono con «febe-sonda ripulisci», si controllano con «febe-sonda verifica»\n" + + "e si cancellano alla fine di M0 (specifica §14.5).\n", + ct).ConfigureAwait(false); + + _tap = new ResponseTap(_cdp, _hosts, _clock); + _tap.AddConsumer(this); + _tap.AddObserver(this); + await _tap.StartAsync(ct).ConfigureAwait(false); + _poller = Task.Run(() => PollAsync(_stop.Token), CancellationToken.None); + } + + public async Task StopAsync() + { + await _stop.CancelAsync().ConfigureAwait(false); + if (_poller is not null) + { + try + { + await _poller.ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + } + + if (_tap is not null) + { + await _tap.DisposeAsync().ConfigureAwait(false); + _tap = null; + } + } + + public async ValueTask DisposeAsync() + { + await StopAsync().ConfigureAwait(false); + _stop.Dispose(); + _write.Dispose(); + } + + async ValueTask IResponseConsumer.ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct) + { + var number = Interlocked.Increment(ref _responses); + var sample = new JsonObject + { + ["descrittore"] = new JsonObject + { + ["indirizzo"] = response.Url, + ["host"] = response.HostKind switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" }, + ["stato"] = response.Status, + ["tipo"] = response.MimeType, + ["risorsa"] = response.ResourceType, + ["quando"] = response.At.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture), + }, + ["corpo"] = JsonNode.Parse(body.RootElement.GetRawText()), + }; + var file = Path.Combine(_folder, "risposte", number.ToString("000000", CultureInfo.InvariantCulture) + ".json"); + await File.WriteAllTextAsync(file, sample.ToJsonString(), ct).ConfigureAwait(false); + } + + void IResponseObserver.OnResponse(ResponseDescriptor response) + { + } + + void IResponseObserver.OnNavigation(NavigationDescriptor navigation) + { + Interlocked.Increment(ref _navigations); + var line = new JsonObject + { + ["quando"] = navigation.At.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture), + ["indirizzo"] = navigation.Url, + ["host"] = navigation.HostKind switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" }, + ["stesso_documento"] = navigation.SameDocument, + }; + _ = AppendLineAsync("navigazioni.jsonl", line); + } + + private async Task PollAsync(CancellationToken ct) + { + while (!ct.IsCancellationRequested) + { + try + { + var state = await _cdp.EvaluateAsync(InteractionScript, ct).ConfigureAwait(false); + if (state.ValueKind == JsonValueKind.Object) + { + _lastHover = await RecordAsync(state, "hover", "sopra", _lastHover).ConfigureAwait(false); + _lastFocus = await RecordAsync(state, "focus", "fuoco", _lastFocus).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + catch (Exception ex) when (ex is CdpCommandException or CdpEvaluationException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException) + { + // Page changing or browser restarting: try again at the next tick. + } + + await _clock.Delay(_pollEvery, ct).ConfigureAwait(false); + } + } + + /// Writes a line when the described element changed; returns the new «last seen» value. + private async Task RecordAsync(JsonElement state, string property, string kind, string? last) + { + if (!state.TryGetProperty(property, out var element) || element.ValueKind != JsonValueKind.Object) + { + return null; + } + + var raw = element.GetRawText(); + if (raw == last) + { + return last; + } + + Interlocked.Increment(ref _interactions); + var node = JsonNode.Parse(raw)!.AsObject(); + if (node["href"] is JsonObject href && href["host"]?.GetValue() is { } linkHost) + { + // Only whether the link stays on the site: the host of an external link may say something about a person. + href["host"] = _hosts.Classify($"https://{linkHost}/") switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" }; + } + + var line = new JsonObject + { + ["quando"] = _clock.Now.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture), + ["evento"] = kind, + ["percorso"] = state.TryGetProperty("path", out var path) ? path.GetString() : null, + ["elemento"] = node, + }; + await AppendLineAsync("interazioni.jsonl", line).ConfigureAwait(false); + return raw; + } + + private async Task AppendLineAsync(string name, JsonObject line) + { + await _write.WaitAsync().ConfigureAwait(false); + try + { + await File.AppendAllTextAsync(Path.Combine(_folder, name), line.ToJsonString() + "\n").ConfigureAwait(false); + } + catch (ObjectDisposedException) + { + } + finally + { + _write.Release(); + } + } +} diff --git a/tools/Febe.Sonda/Program.cs b/tools/Febe.Sonda/Program.cs index f99107c..7082a16 100644 --- a/tools/Febe.Sonda/Program.cs +++ b/tools/Febe.Sonda/Program.cs @@ -1,2 +1,171 @@ -// Passive probe (spec §14.5). Filled in by milestone M0. -Console.WriteLine("febe-sonda"); +using System.Globalization; +using Febe.Browser.Diagnostics; +using Febe.Browser.Hosting; +using Febe.Core.Abstractions; +using Febe.Core.Collection; +using Febe.Sonda; + +// Passive probe of M0 (spec §14.5). +// febe-sonda registra --cartella [--display :0 | --xvfb] [--porta 9333] [--chromium ] [--no-sandbox] +// [--sito --cdn ] (solo per provarla sul sito di prova) +// febe-sonda ripulisci --da --a [--ammessi ] [--sito --cdn ] +// febe-sonda verifica --grezzi --ripuliti [--ammessi ] +return args.Length == 0 ? Usage() : args[0] switch +{ + "registra" => await RecordAsync(args[1..]), + "ripulisci" => Sanitize(args[1..]), + "verifica" => Verify(args[1..]), + _ => Usage(), +}; + +static int Usage() +{ + Console.Error.WriteLine(""" + Uso: + febe-sonda registra --cartella [--display :0 | --xvfb] [--porta 9333] [--chromium ] [--no-sandbox] + febe-sonda ripulisci --da --a [--ammessi ] + febe-sonda verifica --grezzi --ripuliti [--ammessi ] + La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti. + """); + return 2; +} + +static async Task RecordAsync(string[] args) +{ + var folder = Option(args, "--cartella"); + if (string.IsNullOrWhiteSpace(folder)) + { + Console.Error.WriteLine("Indicare --cartella ."); + return 2; + } + + try + { + RepositoryGuard.EnsureOutside(folder); + } + catch (InvalidOperationException ex) + { + Console.Error.WriteLine(ex.Message); + return 3; + } + + var log = new DelegateBrowserLog((level, message, _) => + { + if (level >= BrowserLogLevel.Warning) + { + Console.Error.WriteLine(message); + } + }); + XvfbProcess? xvfb = null; + var display = Option(args, "--display"); + if (args.Contains("--xvfb")) + { + display = XvfbProcess.FindFreeDisplay() ?? throw new InvalidOperationException("Nessun display libero per Xvfb."); + xvfb = new XvfbProcess(display, 1280, 900, log: log); + await xvfb.StartAsync(CancellationToken.None); + Console.WriteLine($"Xvfb avviato su {display}: il browser non è visibile da qui (serve la vista remota di Febe o un display vero con --display)."); + } + + var hosts = Hosts(args); + var profile = Path.Combine(Path.GetFullPath(folder), SampleSanitizer.BrowserProfileFolder); + var host = new ChromiumProcessHost(new ChromiumLaunchOptions { NoSandbox = args.Contains("--no-sandbox") }, log: log); + try + { + await host.StartAsync( + new BrowserOptions(profile, 1280, 900, int.TryParse(Option(args, "--porta"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) ? port : 9333, Option(args, "--chromium"), display), + CancellationToken.None); + await using var recorder = new ProbeRecorder(host.Cdp, hosts, folder); + await recorder.StartAsync(); + Console.WriteLine($""" + Sonda in ascolto. Campioni grezzi in: {recorder.Folder} + Accedi e naviga a mano nella finestra del browser seguendo docs/prove-dal-vivo.md. + La sonda non compie gesti e non apre pagine da sola. Premi Invio (o Ctrl+C) per terminare. + """); + var stop = new TaskCompletionSource(); + Console.CancelKeyPress += (_, e) => + { + e.Cancel = true; + stop.TrySetResult(); + }; + _ = Task.Run(() => + { + Console.ReadLine(); + stop.TrySetResult(); + }); + await stop.Task; + await recorder.StopAsync(); + var stats = recorder.Stats; + Console.WriteLine($"Registrate {stats.Responses} risposte, {stats.Navigations} navigazioni, {stats.Interactions} interazioni."); + Console.WriteLine("Ora: febe-sonda ripulisci --da --a , poi febe-sonda verifica."); + return 0; + } + finally + { + await host.DisposeAsync(); + if (xvfb is not null) + { + await xvfb.DisposeAsync(); + } + } +} + +static int Sanitize(string[] args) +{ + var from = Option(args, "--da"); + var to = Option(args, "--a"); + if (string.IsNullOrWhiteSpace(from) || string.IsNullOrWhiteSpace(to)) + { + Console.Error.WriteLine("Indicare --da e --a ."); + return 2; + } + + var allowlist = Option(args, "--ammessi") is { } path ? SanitizerAllowlist.Load(path) : SanitizerAllowlist.Default; + var report = new SampleSanitizer(allowlist, Hosts(args)).SanitizeFolder(from, to); + Console.WriteLine($"Ripuliti {report.Files} file ({report.Lines} righe): {report.ReplacedStrings} testi, {report.ReplacedNumbers} numeri, {report.ReplacedKeys} chiavi, {report.Addresses} indirizzi sostituiti."); + var verify = SampleVerifier.Verify(from, to, allowlist); + Console.WriteLine(verify.Passed ? "Verifica superata." : $"Verifica NON superata: {verify.Leaks.Count} frammenti sopravvissuti."); + return verify.Passed ? 0 : 1; +} + +static int Verify(string[] args) +{ + var raw = Option(args, "--grezzi"); + var clean = Option(args, "--ripuliti"); + if (string.IsNullOrWhiteSpace(raw) || string.IsNullOrWhiteSpace(clean)) + { + Console.Error.WriteLine("Indicare --grezzi e --ripuliti ."); + return 2; + } + + var allowlist = Option(args, "--ammessi") is { } path ? SanitizerAllowlist.Load(path) : SanitizerAllowlist.Default; + var report = SampleVerifier.Verify(raw, clean, allowlist); + Console.WriteLine($"Grezzi: {report.RawFiles} file; ripuliti: {report.CleanFiles}; frammenti controllati: {report.CheckedTokens}."); + foreach (var missing in report.MissingCleanFiles) + { + Console.WriteLine($"Manca la copia ripulita di {missing}."); + } + + foreach (var leak in report.Leaks) + { + // Where, never what: the value itself stays on this machine. + Console.WriteLine($"Sopravvive un frammento di {leak.Length} {leak.Kind} in {leak.CleanFile}."); + } + + Console.WriteLine(report.Passed ? "Verifica superata: nessun valore dei grezzi sopravvive fuori dall'elenco ammesso." : "Verifica NON superata."); + return report.Passed ? 0 : 1; +} + +static HostClassifier Hosts(string[] args) +{ + var site = Option(args, "--sito"); + var cdn = Option(args, "--cdn"); + return site is null && cdn is null + ? HostClassifier.Instagram + : new HostClassifier((site ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries), (cdn ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries)); +} + +static string? Option(string[] args, string name) +{ + var index = Array.IndexOf(args, name); + return index >= 0 && index + 1 < args.Length ? args[index + 1] : null; +} diff --git a/tools/Febe.Sonda/SampleSanitizer.cs b/tools/Febe.Sonda/SampleSanitizer.cs new file mode 100644 index 0000000..4e21712 --- /dev/null +++ b/tools/Febe.Sonda/SampleSanitizer.cs @@ -0,0 +1,369 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.Core.Collection; + +namespace Febe.Sonda; + +/// What a cleaning run did. +public sealed record SanitizeReport(int Files, int Lines, int ReplacedStrings, int ReplacedNumbers, int ReplacedKeys, int Addresses); + +/// +/// Cleans raw probe samples by allowlist (spec §14.5): structure and keys stay; every string and every long number +/// becomes a fake value of the same shape (letters for letters, digits for digits, punctuation kept), except the short +/// list of fields that say nothing about a person (); keys that look like identifiers +/// are replaced too; addresses keep only «site or CDN» and the file extension. +/// +/// +/// Equal values get equal fakes within a run (relations between responses survive), and a fake never contains a +/// sensitive run of any raw sample (it is drawn again). Fake letters are consonants only, so they cannot spell the +/// words of a caption. The browser profile folder of the probe is never read. +/// +public sealed class SampleSanitizer +{ + /// The probe's browser profile: holds the session, never part of the samples. + public const string BrowserProfileFolder = "profilo-browser"; + + private const string Consonants = "bcdfghjklmnpqrstvwxz"; + + /// + /// File extensions an address may keep. Only known file types: the last segment of a page address may be a user + /// name with a dot («nome.cognome»), and its «extension» would leak part of it. + /// + private static readonly HashSet FileExtensions = new(StringComparer.Ordinal) + { + "jpg", "jpeg", "png", "webp", "heic", "heif", "gif", "avif", "mp4", "m4v", "mov", "webm", "m4a", "mp3", "aac", + "m3u8", "mpd", "ts", "json", "js", "css", "html", "htm", "txt", "xml", "svg", "ico", "woff", "woff2", + }; + + private readonly SanitizerAllowlist _allowlist; + private readonly HostClassifier _hosts; + private readonly byte[] _key; + private readonly Dictionary _fakes = new(StringComparer.Ordinal); + private HashSet _sensitive = new(StringComparer.Ordinal); + private int[] _lengths = []; + private int _strings; + private int _numbers; + private int _keys; + private int _addresses; + + public SampleSanitizer(SanitizerAllowlist? allowlist = null, HostClassifier? hosts = null, byte[]? key = null) + { + _allowlist = allowlist ?? SanitizerAllowlist.Default; + _hosts = hosts ?? HostClassifier.Instagram; + _key = key ?? RandomNumberGenerator.GetBytes(32); + } + + /// Raw sample files of a folder: *.json and *.jsonl, outside the browser profile. + public static IReadOnlyList SampleFiles(string folder) => + [.. Directory.EnumerateFiles(folder, "*.*", SearchOption.AllDirectories) + .Where(f => f.EndsWith(".json", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".jsonl", StringComparison.OrdinalIgnoreCase)) + .Where(f => !Path.GetRelativePath(folder, f).Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Contains(BrowserProfileFolder, StringComparer.Ordinal)) + .Order(StringComparer.Ordinal)]; + + /// Cleans every sample of into , same relative names. + public SanitizeReport SanitizeFolder(string rawFolder, string cleanFolder) + { + var raw = Path.GetFullPath(rawFolder); + var clean = Path.GetFullPath(cleanFolder); + if (!Directory.Exists(raw)) + { + throw new DirectoryNotFoundException($"La cartella dei campioni grezzi non esiste: {raw}"); + } + + if (clean.StartsWith(raw + Path.DirectorySeparatorChar, StringComparison.Ordinal) || clean == raw) + { + throw new InvalidOperationException("La cartella dei campioni ripuliti non può stare dentro quella dei grezzi."); + } + + var files = SampleFiles(raw); + var tokens = new SensitiveTokens(_allowlist); + var documents = new List<(string Relative, bool Lines, List Nodes)>(); + foreach (var file in files) + { + var relative = Path.GetRelativePath(raw, file); + var isLines = file.EndsWith(".jsonl", StringComparison.OrdinalIgnoreCase); + var nodes = new List(); + foreach (var text in isLines ? File.ReadLines(file).Where(l => !string.IsNullOrWhiteSpace(l)) : [File.ReadAllText(file)]) + { + using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 }); + tokens.Add(document.RootElement); + nodes.Add(JsonNode.Parse(text, documentOptions: new JsonDocumentOptions { MaxDepth = 256 })); + } + + documents.Add((relative, isLines, nodes)); + } + + UseSensitive(tokens); + var lines = 0; + foreach (var (relative, isLines, nodes) in documents) + { + var target = Path.Combine(clean, relative); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + if (isLines) + { + File.WriteAllLines(target, nodes.Select(n => Sanitize(n)?.ToJsonString() ?? "null")); + lines += nodes.Count; + } + else + { + File.WriteAllText(target, Sanitize(nodes[0])?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }) ?? "null"); + } + } + + return new SanitizeReport(documents.Count, lines, _strings, _numbers, _keys, _addresses); + } + + /// Cleans one document (tests). Call first to avoid collisions with other samples. + public JsonNode? Sanitize(JsonNode? node, string? key = null) + { + switch (node) + { + case null: + return null; + case JsonObject obj: + var result = new JsonObject(); + foreach (var (name, value) in obj) + { + var cleanName = SensitiveTokens.IsDataKey(name) ? FakeKey(name) : name; + result[cleanName] = Sanitize(value, name); + } + + return result; + case JsonArray array: + var list = new JsonArray(); + foreach (var item in array) + { + list.Add(Sanitize(item, key)); + } + + return list; + case JsonValue value: + return SanitizeValue(value, key); + default: + return null; + } + } + + /// Sets the raw tokens that fakes must never contain. + public void UseSensitive(SensitiveTokens tokens) + { + _sensitive = [.. tokens.Effective]; + _lengths = [.. tokens.Lengths.Order()]; + } + + private JsonNode? SanitizeValue(JsonValue value, string? key) + { + var element = value.GetValue(); + switch (element.ValueKind) + { + case JsonValueKind.True: + case JsonValueKind.False: + case JsonValueKind.Null: + return JsonValue.Create(element); + case JsonValueKind.Number: + var raw = element.GetRawText(); + var digits = raw.Count(char.IsAsciiDigit); + var integral = !raw.Contains('.', StringComparison.Ordinal) && !raw.Contains('e', StringComparison.OrdinalIgnoreCase); + if (_allowlist.KeepsNumber(key) || (integral && digits < 5) || (!integral && digits < 6)) + { + return JsonValue.Create(element); + } + + _numbers++; + return JsonNode.Parse(FakeNumber(raw)); + case JsonValueKind.String: + var text = element.GetString() ?? string.Empty; + if (text.Length == 0 || _allowlist.KeepsString(key, text)) + { + return JsonValue.Create(text); + } + + if (Uri.TryCreate(text, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https") + { + _addresses++; + return JsonValue.Create(FakeAddress(text, uri)); + } + + _strings++; + return JsonValue.Create(Fake(text, "s")); + default: + return JsonValue.Create(element); + } + } + + private string FakeKey(string key) + { + _keys++; + return Fake(key, "k"); + } + + private string FakeNumber(string raw) + { + var fake = Fake(raw, "n"); + + // A JSON number must not start with 0 (except «0.x»): keep the first digit non-zero. + var first = -1; + for (var i = 0; i < fake.Length; i++) + { + if (char.IsAsciiDigit(fake[i])) + { + first = i; + break; + } + } + + if (first >= 0 && fake[first] == '0' && raw[first] != '0') + { + fake = string.Concat(fake.AsSpan(0, first), "7", fake.AsSpan(first + 1)); + } + + return fake; + } + + private string FakeAddress(string text, Uri uri) + { + if (_fakes.TryGetValue("u|" + text, out var known)) + { + return known; + } + + var host = _hosts.Classify(uri) switch + { + HostKind.Site => "sito", + HostKind.Cdn => "cdn", + _ => "altro", + }; + var last = uri.AbsolutePath.Split('/').LastOrDefault() ?? string.Empty; + var dot = last.LastIndexOf('.'); + var extension = dot > 0 && FileExtensions.Contains(last[(dot + 1)..].ToLowerInvariant()) ? last[dot..].ToLowerInvariant() : string.Empty; + var token = Fake(Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)))[..16], "u"); + var fake = $"https://{host}.esempio/{token}{extension}"; + _fakes["u|" + text] = fake; + return fake; + } + + /// A fake with the shape of , the same for the same value in this run. + private string Fake(string original, string kind) + { + var cacheKey = kind + "|" + original; + if (_fakes.TryGetValue(cacheKey, out var known)) + { + return known; + } + + for (var salt = 0; ; salt++) + { + var candidate = Shape(original, kind, salt); + if ((candidate != original || !original.Any(char.IsLetterOrDigit)) && !ContainsSensitive(candidate)) + { + _fakes[cacheKey] = candidate; + return candidate; + } + + if (salt > 64) + { + // Practically unreachable; fall back to a neutral filler of the same length. + var filler = new string(original.Select(c => char.IsLetter(c) ? 'x' : char.IsDigit(c) ? '7' : c).ToArray()); + _fakes[cacheKey] = filler; + return filler; + } + } + } + + private string Shape(string original, string kind, int salt) + { + var stream = Bytes($"{kind}|{salt.ToString(CultureInfo.InvariantCulture)}|{original}", original.Length); + var sb = new StringBuilder(original.Length); + for (var i = 0; i < original.Length; i++) + { + var c = original[i]; + var r = stream[i]; + if (char.IsLetter(c)) + { + var letter = Consonants[r % Consonants.Length]; + sb.Append(char.IsUpper(c) ? char.ToUpperInvariant(letter) : letter); + } + else if (char.IsDigit(c)) + { + sb.Append((char)('0' + (r % 10))); + } + else if (char.IsSurrogate(c) || char.IsSymbol(c)) + { + sb.Append('·'); // emoji and symbols carry meaning in captions: replaced by a neutral dot + } + else + { + sb.Append(c); + } + } + + return sb.ToString(); + } + + private byte[] Bytes(string seed, int length) + { + var result = new byte[Math.Max(length, 1)]; + var block = 0; + var offset = 0; + while (offset < result.Length) + { + var hash = HMACSHA256.HashData(_key, Encoding.UTF8.GetBytes(seed + "#" + block.ToString(CultureInfo.InvariantCulture))); + var take = Math.Min(hash.Length, result.Length - offset); + Array.Copy(hash, 0, result, offset, take); + offset += take; + block++; + } + + return result; + } + + private bool ContainsSensitive(string candidate) + { + if (_sensitive.Count == 0) + { + return false; + } + + foreach (var token in SensitiveTokensOf(candidate)) + { + foreach (var length in _lengths) + { + if (length > token.Length) + { + break; + } + + for (var i = 0; i + length <= token.Length; i++) + { + if (_sensitive.Contains(token.Substring(i, length))) + { + return true; + } + } + } + } + + return false; + } + + private static IEnumerable SensitiveTokensOf(string text) + { + var start = -1; + for (var i = 0; i <= text.Length; i++) + { + var isPart = i < text.Length && char.IsLetterOrDigit(text[i]); + if (isPart && start < 0) + { + start = i; + } + else if (!isPart && start >= 0) + { + yield return text[start..i].ToLowerInvariant(); + start = -1; + } + } + } +} diff --git a/tools/Febe.Sonda/SampleVerifier.cs b/tools/Febe.Sonda/SampleVerifier.cs new file mode 100644 index 0000000..8c02e71 --- /dev/null +++ b/tools/Febe.Sonda/SampleVerifier.cs @@ -0,0 +1,110 @@ +using System.Text; +using System.Text.Json; + +namespace Febe.Sonda; + +/// One leak found by the verification: where, never what (the value itself is not printed). +/// Cleaned file (relative path) where a raw piece survives. +/// Length of the surviving piece. +/// «lettere» or «cifre». +public sealed record SampleLeak(string CleanFile, int Length, string Kind); + +/// Result of the verification of cleaned samples. +public sealed record VerifyReport(int RawFiles, int CleanFiles, int CheckedTokens, IReadOnlyList Leaks, IReadOnlyList MissingCleanFiles) +{ + public bool Passed => Leaks.Count == 0 && MissingCleanFiles.Count == 0 && CleanFiles > 0; +} + +/// +/// The check of spec §14.5, run on Alberto's machine: fails if any run of four or more letters and digits (five for +/// numbers) of the raw samples survives in the cleaned ones, outside the allowlist. It prints where, never the value. +/// +public static class SampleVerifier +{ + public static VerifyReport Verify(string rawFolder, string cleanFolder, SanitizerAllowlist? allowlist = null) + { + var raw = Path.GetFullPath(rawFolder); + var clean = Path.GetFullPath(cleanFolder); + var tokens = new SensitiveTokens(allowlist ?? SanitizerAllowlist.Default); + var rawFiles = SampleSanitizer.SampleFiles(raw); + foreach (var file in rawFiles) + { + foreach (var text in Documents(file)) + { + using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 }); + tokens.Add(document.RootElement); + } + } + + var missing = rawFiles.Select(f => Path.GetRelativePath(raw, f)).Where(r => !File.Exists(Path.Combine(clean, r))).ToList(); + var cleanFiles = Directory.Exists(clean) ? SampleSanitizer.SampleFiles(clean) : []; + var sensitive = tokens.Effective; + var leaks = new List(); + foreach (var file in cleanFiles) + { + var atoms = new StringBuilder(); + foreach (var text in Documents(file)) + { + using var document = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 256 }); + Atoms(document.RootElement, atoms, 0); + } + + var haystack = atoms.ToString().ToLowerInvariant(); + foreach (var token in sensitive) + { + if (haystack.Contains(token, StringComparison.Ordinal)) + { + leaks.Add(new SampleLeak(Path.GetRelativePath(clean, file), token.Length, token.Any(char.IsLetter) ? "lettere" : "cifre")); + } + } + } + + return new VerifyReport(rawFiles.Count, cleanFiles.Count, sensitive.Count, leaks, missing); + } + + private static IEnumerable Documents(string file) => + file.EndsWith(".jsonl", StringComparison.OrdinalIgnoreCase) + ? File.ReadLines(file).Where(l => !string.IsNullOrWhiteSpace(l)) + : [File.ReadAllText(file)]; + + /// + /// Every value and every data key of a cleaned document, separated so that tokens cannot span two of them. + /// Ordinary keys are structure, copied from the raw samples on purpose: they are not looked at. + /// + private static void Atoms(JsonElement element, StringBuilder sb, int depth) + { + if (depth > 256) + { + return; + } + + switch (element.ValueKind) + { + case JsonValueKind.Object: + foreach (var property in element.EnumerateObject()) + { + if (SensitiveTokens.IsDataKey(property.Name)) + { + sb.Append(property.Name).Append('\u0001'); + } + + Atoms(property.Value, sb, depth + 1); + } + + break; + case JsonValueKind.Array: + foreach (var item in element.EnumerateArray()) + { + Atoms(item, sb, depth + 1); + } + + break; + case JsonValueKind.String: + sb.Append(element.GetString()).Append('\u0001'); + break; + case JsonValueKind.Number: + sb.Append(element.GetRawText()).Append('\u0001'); + break; + } + } +} diff --git a/tools/Febe.Sonda/SanitizerAllowlist.cs b/tools/Febe.Sonda/SanitizerAllowlist.cs new file mode 100644 index 0000000..aa1a640 --- /dev/null +++ b/tools/Febe.Sonda/SanitizerAllowlist.cs @@ -0,0 +1,121 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace Febe.Sonda; + +/// Kind of a field that says nothing about a person (spec §14.5). +public enum AllowedField +{ + None, + Dimension, + Duration, + Count, + Code, + Date, +} + +/// +/// The short list of fields the sanitizer keeps (ripulitura.json): dimensions, durations, counts, type codes and +/// dates. Everything else is replaced. Booleans and null are always kept: they cannot identify anyone. +/// +public sealed partial class SanitizerAllowlist +{ + private readonly List<(Regex Pattern, AllowedField Field)> _rules; + + public SanitizerAllowlist(IEnumerable<(string KeyPattern, AllowedField Field)> rules) + { + _rules = [.. rules.Select(r => (new Regex("^" + Regex.Escape(r.KeyPattern.Trim().ToLowerInvariant()).Replace("\\*", ".*", StringComparison.Ordinal) + "$", RegexOptions.CultureInvariant), r.Field))]; + } + + /// The shipped list (embedded ripulitura.json). + public static SanitizerAllowlist Default { get; } = Parse(ReadEmbedded()); + + public static SanitizerAllowlist Load(string path) => Parse(File.ReadAllText(path)); + + public static SanitizerAllowlist Parse(string json) + { + using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); + var rules = new List<(string, AllowedField)>(); + if (!document.RootElement.TryGetProperty("categories", out var categories) || categories.ValueKind != JsonValueKind.Object) + { + throw new InvalidDataException("ripulitura.json: manca «categories»."); + } + + foreach (var category in categories.EnumerateObject()) + { + var field = category.Name.ToLowerInvariant() switch + { + "dimension" => AllowedField.Dimension, + "duration" => AllowedField.Duration, + "count" => AllowedField.Count, + "code" => AllowedField.Code, + "date" => AllowedField.Date, + _ => throw new InvalidDataException($"ripulitura.json: categoria «{category.Name}» sconosciuta (ammesse: dimension, duration, count, code, date)."), + }; + if (category.Value.TryGetProperty("keys", out var keys) && keys.ValueKind == JsonValueKind.Array) + { + foreach (var key in keys.EnumerateArray()) + { + if (key.GetString() is { Length: > 0 } pattern) + { + rules.Add((pattern, field)); + } + } + } + } + + return new SanitizerAllowlist(rules); + } + + public AllowedField FieldOf(string? key) + { + if (string.IsNullOrEmpty(key)) + { + return AllowedField.None; + } + + var lower = key.ToLowerInvariant(); + foreach (var (pattern, field) in _rules) + { + if (pattern.IsMatch(lower)) + { + return field; + } + } + + return AllowedField.None; + } + + /// True when a number under is kept as it is. + public bool KeepsNumber(string? key) => FieldOf(key) != AllowedField.None; + + /// True when a string under is kept: short type codes, and dates under date keys. + public bool KeepsString(string? key, string value) => FieldOf(key) switch + { + AllowedField.Code => value.Length <= 40 && CodeShape().IsMatch(value) && !LongDigits().IsMatch(value), + AllowedField.Date => value.Length <= 40 && (DateShape().IsMatch(value) + || (UnixShape().IsMatch(value) && long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _))), + _ => false, + }; + + private static string ReadEmbedded() + { + using var stream = typeof(SanitizerAllowlist).Assembly.GetManifestResourceStream("Febe.Sonda.ripulitura.json") + ?? throw new FileNotFoundException("Risorsa incorporata mancante: ripulitura.json"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd(); + } + + [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9_./+\- ]*$", RegexOptions.CultureInvariant)] + private static partial Regex CodeShape(); + + [GeneratedRegex(@"\d{3,}", RegexOptions.CultureInvariant)] + private static partial Regex LongDigits(); + + [GeneratedRegex(@"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$", RegexOptions.CultureInvariant)] + private static partial Regex DateShape(); + + [GeneratedRegex(@"^\d{9,13}$", RegexOptions.CultureInvariant)] + private static partial Regex UnixShape(); +} diff --git a/tools/Febe.Sonda/SensitiveTokens.cs b/tools/Febe.Sonda/SensitiveTokens.cs new file mode 100644 index 0000000..d2f4ff4 --- /dev/null +++ b/tools/Febe.Sonda/SensitiveTokens.cs @@ -0,0 +1,129 @@ +using System.Text.Json; +using Febe.Core.Collection.Readers; + +namespace Febe.Sonda; + +/// +/// The pieces of raw samples that must not survive the cleaning (spec §14.5): every run of four or more letters and +/// digits found in the values (strings, long numbers) and in the keys that look like identifiers, except the +/// structure (ordinary keys) and the values the allowlist keeps. Purely numeric runs count from five digits: shorter +/// numbers (dimensions, counts) identify nobody. +/// +public sealed class SensitiveTokens +{ + /// Words of address structure that the cleaned samples write themselves. + private static readonly string[] AddressWords = ["http", "https", "www", "html", "json", "jpeg", "webp", "heic", "esempio"]; + + private readonly HashSet _tokens = new(StringComparer.Ordinal); + private readonly HashSet _excluded = new(StringComparer.Ordinal); + + public SensitiveTokens(SanitizerAllowlist allowlist) + { + Allowlist = allowlist; + foreach (var word in AddressWords) + { + _excluded.Add(word); + } + } + + public SanitizerAllowlist Allowlist { get; } + + /// Tokens that must not appear in the cleaned samples (lower case). + public IReadOnlySet Effective + { + get + { + var set = new HashSet(_tokens, StringComparer.Ordinal); + set.ExceptWith(_excluded); + return set; + } + } + + /// Lengths of the effective tokens, for window checks. + public IReadOnlySet Lengths => Effective.Select(t => t.Length).ToHashSet(); + + public void Add(JsonElement root) => Walk(root, key: null, depth: 0); + + /// Alphanumeric runs of that would be sensitive, lower case. + public static IEnumerable Tokenize(string text) + { + var start = -1; + for (var i = 0; i <= text.Length; i++) + { + var isPart = i < text.Length && char.IsLetterOrDigit(text[i]); + if (isPart && start < 0) + { + start = i; + } + else if (!isPart && start >= 0) + { + var token = text[start..i]; + start = -1; + var letters = token.Any(char.IsLetter); + if ((letters && token.Length >= 4) || (!letters && token.Length >= 5)) + { + yield return token.ToLowerInvariant(); + } + } + } + } + + /// True when the key is data rather than structure (sanitizer replaces it). + public static bool IsDataKey(string key) => + KeyStructure.LooksLikeIdentifier(key) || key.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '_' or '-')); + + private void Walk(JsonElement element, string? key, int depth) + { + if (depth > 256) + { + return; + } + + switch (element.ValueKind) + { + case JsonValueKind.Object: + foreach (var property in element.EnumerateObject()) + { + var target = IsDataKey(property.Name) ? _tokens : _excluded; + foreach (var token in Tokenize(property.Name)) + { + target.Add(token); + } + + if (!IsDataKey(property.Name)) + { + // A whole ordinary key is structure too (e.g. «ultima_storia»). + _excluded.Add(property.Name.ToLowerInvariant()); + } + + Walk(property.Value, property.Name, depth + 1); + } + + break; + case JsonValueKind.Array: + foreach (var item in element.EnumerateArray()) + { + Walk(item, key, depth + 1); + } + + break; + case JsonValueKind.String: + var text = element.GetString() ?? string.Empty; + var kept = Allowlist.KeepsString(key, text); + foreach (var token in Tokenize(text)) + { + (kept ? _excluded : _tokens).Add(token); + } + + break; + case JsonValueKind.Number: + var raw = element.GetRawText(); + foreach (var token in Tokenize(raw)) + { + (Allowlist.KeepsNumber(key) ? _excluded : _tokens).Add(token); + } + + break; + } + } +} diff --git a/tools/Febe.Sonda/ripulitura.json b/tools/Febe.Sonda/ripulitura.json new file mode 100644 index 0000000..13d8c9a --- /dev/null +++ b/tools/Febe.Sonda/ripulitura.json @@ -0,0 +1,25 @@ +{ + "note": "Elenco di ciò che la ripulitura dei campioni lascia com'è (specifica §14.5). Tutto il resto si sostituisce: ogni stringa e ogni numero lungo diventano un valore finto della stessa forma. Le chiavi si confrontano senza maiuscole; «*» vale per qualunque parte del nome. Si ammettono solo campi che non dicono nulla di una persona.", + "categories": { + "dimension": { + "note": "Dimensioni in pixel: si tengono i numeri.", + "keys": ["width", "height", "*_width", "*_height", "larghezza", "altezza"] + }, + "duration": { + "note": "Durate: si tengono i numeri.", + "keys": ["duration", "*_duration", "durata"] + }, + "count": { + "note": "Conteggi: si tengono i numeri.", + "keys": ["count", "*_count", "pubblicazioni", "parti_totali"] + }, + "code": { + "note": "Codici di tipo e di stato: si tengono i numeri e i testi brevi fatti di lettere, senza cifre ripetute. «role», «tag» ed «evento» sono i ruoli e i tipi degli elementi registrati dalla sonda (link, button, tab...); «host» è già ridotto dalla sonda a sito, cdn o altro.", + "keys": ["type", "*_type", "status", "tipo", "stato", "risorsa", "host", "role", "tag", "evento"] + }, + "date": { + "note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4.", + "keys": ["taken_at", "*_at", "pubblicato", "scade", "ultima_storia", "quando"] + } + } +}