Ricette fatte di richieste, un permesso per richiesta (#36, S3)
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 21m4s
verifica / installatore (push) Successful in 5m21s
verifica / immagine (push) Successful in 19m0s

Otto ricette (controllo del profilo, storico, taggati, reel, storie di un
account, raccolta in evidenza, post singolo, elenco dei seguiti) hanno una
strada per richieste dirette accanto a quella con il browser. Ci vanno solo
se ogni ruolo che servono è un'operazione configurata di richieste.<sito>.json:
con Instagram nessuna lo è e Febe non costruisce il client del sito, quindi il
comportamento con Instagram non cambia fino a S4.

Ogni richiesta prende il suo permesso dal Governatore nella categoria di ciò
che chiede (la prima pagina dei post conta come profilo); i segnali delle
risposte vanno all'interruttore e fermano la ricetta prima di ogni altra
richiesta. Se manca un valore o la pagina successiva, la ricetta torna alle
pagine per quella volta e il motore controlla tutti e due i tetti. I tetti non
cambiano: il dimezzamento delle storie viste è tolto perché toccava anche il
browser e i «Su misura» salvati, e resta una domanda per Alberto prima di S4.

Il simulatore ha --raccolta pagine|richieste con il costo delle operazioni
separate di Instagram: sei simulazioni di 30 giorni senza superamenti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 12:10:54 +01:00
1 parent 4dcbd0b096
commit 63acae4e73
46 files changed
+3724 -136

No files matched your search

+22 -14
View File
@@ -336,6 +336,8 @@ Le risposte vanno ai lettori come quelle catturate (§6.2, §6.4), con gli stess
**Che cosa non cambia.** Sola lettura (regola 5), Governatore (regola 7), arresto al primo segnale (regola 8), niente CAPTCHA (regola 3), formati mai inventati (regola 10), browser usato così com'è per l'accesso e le verifiche (regola 2).
**Le ricette per richieste (tappa S3).** Una ricetta va per richieste quando ogni ruolo che le serve (§6.3) appartiene a un'operazione configurata di `richieste.<sito>.json`; altrimenti va con il browser, come prima. Con Instagram nessuna delle dieci operazioni è ancora configurata: tutte le ricette restano sulle pagine finché la tappa S4 non porta la sessione salvata e i `doc_id`. Febe per Windows e Febe in Docker non costruiscono ancora il client del sito per il motore (S4); lo usano le prove, con il sito di prova. Una ricetta per richieste non tocca mai la pagina, e dopo un segnale non torna alle pagine (regola 7): si ferma.
### 6.1 Il browser
- **Docker**: il Chromium della distribuzione, avviato come un browser normale con finestra su un display virtuale (Xvfb), profilo in `/dati/browser`.
@@ -382,19 +384,19 @@ Un componente `ResponseTap` ascolta le risposte JSON che la pagina riceve dal si
Una ricetta è una sequenza di azioni con uno scopo. Sono poche e fisse. I passi qui sotto descrivono l'intenzione; i dettagli concreti si definiscono sui campioni.
**In riscrittura (issue #36).** Le ricette diventano sequenze di richieste del client del sito (§6.0) invece che di gesti, e la mappa dei bersagli non servirà più. Ogni richiesta è un'azione con il suo permesso. Le storie di un account si leggono con una sola richiesta e non risultano viste (§3, decisione del 16 novembre 2026). Restano «non configurate», finché non ci sono i campioni con le risposte (regola 10): l'elenco dei seguiti, le pagine successive dei post, le pagine della home. Finché una ricetta non è riscritta e unita, vale la tabella qui sotto.
**Per richieste (issue #36, tappa S3).** Una ricetta può essere una sequenza di richieste del client del sito (§6.0) invece che di gesti. Ogni operazione di `richieste.<sito>.json` dice con `roles` a che cosa serve; un ruolo appartiene a una sola operazione, una ricerca non ne ha, e un ruolo di «pagina successiva» (`posts-next`, `tagged-next`, `reels-next`, `highlight-next`, `following-next`) vuole un'operazione con il cursore. La ricetta va per richieste solo se tutti i ruoli della colonna «Per richieste» sono di operazioni configurate; il ruolo fra parentesi serve alle pagine successive e, se manca, la ricetta legge la prima pagina, tiene il punto e lo dice («le pagine successive non sono ancora configurate»); la Raccolta in evidenza non ha punto e la volta dopo ricomincia dalla prima pagina. Ogni richiesta è un'azione con il suo permesso nella categoria di ciò che chiede: la prima pagina dei post conta come profilo (`firstPageCategory`), le successive come storico. Fra una risposta e la richiesta successiva della stessa ricetta c'è un'attesa di 1–6 s (mediana 2,2 s), fra due pagine di 2–8 s (mediana 3,5 s), con l'8% di probabilità di 15–90 s in più; la prima richiesta della ricetta non aspetta, perché la distanza dal resto la tiene il Governatore (§7.7). Le storie di un account si leggono con una sola richiesta e non risultano viste (§3, decisione del 16 novembre 2026): una richiesta, una «storia vista», senza il controllo del minimo di storie. Mancano ancora i campioni (regola 10) per l'elenco dei seguiti, le pagine successive dei post e le pagine della home: il Giro dei seguiti resta sulle pagine.
| Ricetta | Che cosa fa | Azioni contate |
|---|---|---|
| **Giro dei seguiti** | Apre la home, legge la barra delle storie e scorre i post recenti dei profili seguiti finché incontra contenuti già noti, con un massimo di 8 raffiche di scorrimento. I post che arrivano con i dati completi si salvano subito | 1 home |
| **Storie di un account** | Apre il visualizzatore dal profilo o dalla barra, guarda le storie di quell'account una a una e salva quelle mostrate | 1 storia per storia mostrata |
| **Controllo del profilo** | Apre la pagina del profilo; legge stato, prima pagina dei post, elenco delle raccolte in evidenza; si ferma ai contenuti già noti | 1 profilo |
| **Storico** | Dal profilo scorre all'indietro una pagina per volta e riprende dal punto in cui si era fermato | 1 pagina di storico per caricamento |
| **Raccolta in evidenza** | Apre una raccolta e ne guarda i contenuti nuovi | 1 storia per contenuto mostrato |
| **Taggati** e **Reel** | Come Controllo e Storico, sulle rispettive schede del profilo | come sopra |
| **Post singolo** | Apre la pagina di un post: quando la griglia non ha dato tutti i dati, o per recuperare un indirizzo scaduto (§6.5) | 1 post |
| **Elenco dei seguiti** | Apre l'elenco dei profili seguiti da Alberto e lo scorre. Solo su richiesta | 1 pagina di elenco per caricamento |
| **Ricerca dei profili** | Solo mentre Alberto scrive nella finestra «Aggiungi account» (§4.2), anche durante una sessione, a turno con il motore fra un'azione e l'altra. Apre «Cerca» e fa clic nella casella; prima di scrivere controlla che il fuoco sia nella casella; scrive con `Input.dispatchKeyEvent` a ritmo umano solo lettere, numeri, «.», «_» e spazi, e cancella con il tasto di cancellazione; non preme mai Invio, Tab o Esc. Legge la risposta che la pagina riceve (`PolarisSearchBoxRefetchableQuery`, riconosciuta dalla forma) e **non fa mai clic su un risultato**, che finirebbe fra le ricerche recenti di Alberto (una scrittura). Fuori sessione, a finestra chiusa o dopo qualche minuto senza lettere nuove, torna alla pagina di riposo | 1 ricerca di profili per apertura, clic nella casella e raffica di tasti |
| Ricetta | Che cosa fa | Azioni contate | Per richieste |
|---|---|---|---|
| **Giro dei seguiti** | Apre la home, legge la barra delle storie e scorre i post recenti dei profili seguiti finché incontra contenuti già noti, con un massimo di 8 raffiche di scorrimento. I post che arrivano con i dati completi si salvano subito | 1 home | sempre con le pagine |
| **Storie di un account** | Apre il visualizzatore dal profilo o dalla barra, guarda le storie di quell'account una a una e salva quelle mostrate | 1 storia per storia mostrata | `stories`: 1 storia vista per account |
| **Controllo del profilo** | Apre la pagina del profilo; legge stato, prima pagina dei post, elenco delle raccolte in evidenza; si ferma ai contenuti già noti | 1 profilo | `profile`, `posts`, `highlights` (`posts-next`): un profilo per richiesta (sul sito di prova una sola richiesta; con le operazioni separate di Instagram 2, più 1 per l'elenco delle raccolte una volta al giorno), le pagine che colmano il vuoto come storico |
| **Storico** | Dal profilo scorre all'indietro una pagina per volta e riprende dal punto in cui si era fermato | 1 pagina di storico per caricamento | `posts`, `posts-next`: 1 pagina di storico per pagina, la prima come profilo |
| **Raccolta in evidenza** | Apre una raccolta e ne guarda i contenuti nuovi | 1 storia per contenuto mostrato | `highlight` (`highlight-next`): 1 storia vista per pagina |
| **Taggati** e **Reel** | Come Controllo e Storico, sulle rispettive schede del profilo | come sopra | `tagged` (`tagged-next`), `reels` (`reels-next`): 1 azione per pagina nella categoria dell'operazione (sul sito di prova: storico) |
| **Post singolo** | Apre la pagina di un post: quando la griglia non ha dato tutti i dati, o per recuperare un indirizzo scaduto (§6.5) | 1 post | `post`: 1 post |
| **Elenco dei seguiti** | Apre l'elenco dei profili seguiti da Alberto e lo scorre. Solo su richiesta | 1 pagina di elenco per caricamento | `following` (`following-next`): 1 pagina di elenco per pagina |
| **Ricerca dei profili** | Solo mentre Alberto scrive nella finestra «Aggiungi account» (§4.2), anche durante una sessione, a turno con il motore fra un'azione e l'altra. Apre «Cerca» e fa clic nella casella; prima di scrivere controlla che il fuoco sia nella casella; scrive con `Input.dispatchKeyEvent` a ritmo umano solo lettere, numeri, «.», «_» e spazi, e cancella con il tasto di cancellazione; non preme mai Invio, Tab o Esc. Legge la risposta che la pagina riceve (`PolarisSearchBoxRefetchableQuery`, riconosciuta dalla forma) e **non fa mai clic su un risultato**, che finirebbe fra le ricerche recenti di Alberto (una scrittura). Fuori sessione, a finestra chiusa o dopo qualche minuto senza lettere nuove, torna alla pagina di riposo | 1 ricerca di profili per apertura, clic nella casella e raffica di tasti | sempre con le pagine |
Regole comuni:
@@ -404,6 +406,7 @@ Regole comuni:
- **Le storie di un account finiscono con quell'account.** Dopo l'ultima storia la ricetta chiude il visualizzatore, prima che passi da solo all'account successivo. Se compare comunque una storia di un altro account, non si salva, si chiude e si registra l'accaduto.
- **Lo storico non corre più veloce dei download.** Lo storico di un account si sospende finché quell'account ha più di 60 file in attesa di essere scaricati o il tetto dei dati è raggiunto: gli indirizzi scadono, e accumularli non serve.
- Se a metà ricetta compare un segnale di §7.6, la ricetta si ferma dov'è e lascia la pagina com'è, così Alberto vede che cosa è successo.
- **Per richieste**, una risposta 404 con JSON è un «non trovato» per la ricetta (profilo non raggiungibile, raccolta non più nel profilo, post sparito), mai un segnale. Per le storie di un account il «non trovato» non basta a dire «nessuna storia»: la ricetta chiede il profilo (un profilo aperto), come le pagine lo aprono prima del visualizzatore, e un profilo sparito o privato che Alberto non segue rende l'account non raggiungibile (regola 6); altrimenti è un giorno senza storie. Quel 404 non conta come pagina vuota, e una risposta delle storie riconosciuta conta come dati. Un 5xx con JSON, una risposta che non arriva, troppo grande o rovinata fanno fallire la ricetta, che non riprova da sola (H19, da confermare), e contano come pagina vuota: tre di fila sono un Rallentamento. L'elenco delle raccolte in evidenza, quando ha un'operazione sua, si chiede per ultimo (dopo la prima pagina salvata e il vuoto colmato), al più una volta ogni 24 ore per account, sempre in un controllo a mano, mai per un account con «Storie in evidenza» spento; un permesso negato lo rimanda al controllo successivo (da confermare). Una raccolta in evidenza si legge al più per le pagine di una ricetta (3), e i contenuti di ogni pagina si collegano appena letti; l'ordine della raccolta si salva solo letta fino in fondo. Con un punto salvato e senza l'operazione della pagina successiva, Taggati, Reel ed Elenco dei seguiti vanno con le pagine, se le pagine li sanno fare; altrimenti Taggati e Reel leggono la prima pagina per le novità in cima e il punto resta com'è. Il motore, prima di far partire una ricetta, guarda il tetto della sua prima azione su quella strada: per richieste Taggati e Reel cominciano con una pagina di storico, non con un profilo aperto. Il cursore salvato si riprende così com'è (H18): un cursore rifiutato ferma la ricetta per la sua regola, e il punto non si cancella da solo. Un valore che la richiesta vuole e Febe non ha (l'identificativo dell'account, il codice del post) rimanda la ricetta alle pagine, se le pagine la sanno fare, e lo scrive fra gli eventi.
**Mappa dei bersagli.** Per agire, una ricetta deve trovare poche cose nella pagina: l'immagine del profilo con l'anello delle storie, il comando per chiudere il visualizzatore, la zona per andare avanti, le schede del profilo, l'elenco dei seguiti, il comando «Cerca» e la sua casella (`search-open`, `search-box`). Come trovarle sta in un file di configurazione per sito (`bersagli.instagram.json`, `bersagli.prova.json`), non nel codice: ruolo dell'elemento, nome accessibile, forma del collegamento. Mai coordinate fisse, mai nomi di classi generate. Il file si aggiorna senza ricompilare, ed è la seconda cosa da ritoccare, dopo i lettori, quando Instagram cambia.
@@ -450,6 +453,9 @@ Finché una voce non ha un esito scritto in `docs/sonda/esito.md`, non costruirc
| H15 | Le richieste sono accettate con i soli campi di versione letti all'accesso, senza i campi che la pagina calcola a ogni richiesta (`__req`, `__csr`, `__dyn`, `__s`) |
| H16 | Che cosa risponde il sito a una sessione scaduta o da verificare: rinvio, stato, campi del JSON (la ricerca su internet indica `login_required`, `checkpoint_required` e `require_login`, non verificati) |
| H17 | Il CDN dà i file a una richiesta senza cookie con l'user agent della sessione |
| H18 | I cursori sono gli stessi per pagine e richieste: un punto salvato dalle pagine si riprende con una richiesta, e viceversa |
| H19 | Un 404 con JSON vuol dire risorsa assente, un 5xx errore temporaneo: la ricetta non insiste e si riprova al giro dopo (da confermare, Alberto) |
| H20 | Una raccolta in evidenza si chiede con l'identificativo che il profilo dà nell'elenco delle raccolte, così com'è (sul sito di prova sì; su Instagram potrebbe servire il prefisso `highlight:`) |
| S1 | In WebView2 funzionano attraverso CDP il corpo delle risposte, i gesti e i fotogrammi della pagina |
| S2 | Su Windows la pagina continua a caricare e a rispondere allo scorrimento quando la finestra del browser non è in vista |
| S3 | L'accesso fatto a mano sopravvive al riavvio del programma, in Docker e su Windows |
@@ -510,7 +516,7 @@ Il Governatore è l'unico punto da cui passa un'azione del motore verso il sito.
- I tetti orari valgono su una finestra mobile di 60 minuti; quelli giornalieri sul giorno di calendario nel fuso di Alberto.
- Il conteggio sta nella tabella `action_log`, non in memoria.
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati, ricerche di profili. Ogni richiesta del client del sito (§6.0) è un'azione e conta nella categoria di ciò che chiede: un permesso per richiesta, mai uno per più richieste. I tetti per richiesta si ricalcolano con la tappa S3 di #36.
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati, ricerche di profili. Ogni richiesta del client del sito (§6.0) è un'azione e conta nella categoria di ciò che chiede: un permesso per richiesta, mai uno per più richieste. Ricalcolati con la tappa S3 di #36: una richiesta delle storie è una sola «storia vista» per tutte le storie dell'account (§7.5); le altre categorie contavano già una pagina per caricamento. Nessun tetto cambia con S3.
- **Ricerche di profili** (issue #37) hanno tetti propri e larghi (§7.5), che fanno da guardia e non devono mai fermare l'uso normale, e non consumano i tetti della raccolta. Non chiedono una sessione e non contano fra le azioni della sessione. L'ordine dei controlli: interruttore (ogni segnale di §7.6 ferma anche la ricerca), browser in uso da Alberto, pausa, fascia oraria, tetto orario e giornaliero proprio, distanza propria fra due passi della ricerca (1,2 s per il ritmo), 1,2 s di distanza dalle azioni del motore in entrambi i versi. Le riduzioni (avvio graduale, tetti dimezzati) valgono anche qui. Le foto dei risultati contano fra i dati scaricati.
- Sopra l'80% di un tetto l'interfaccia lo segnala in ambra. Raggiunto il tetto, quella categoria si ferma fino all'ora o al giorno dopo; le altre proseguono, salvo la regola sullo storico di §6.3.
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte, non il loro prodotto.
@@ -536,6 +542,7 @@ I valori sono **stime di partenza scelte con prudenza**. Non sono limiti ufficia
| Avvio graduale | 7 giorni | 5 giorni | 3 giorni |
- «Prudente» è il predefinito. «Rapido» chiede conferma e mostra l'etichetta «Più rischio». Se Alberto modifica un valore, il profilo diventa «Su misura».
- «Storie viste» conta una storia mostrata con il browser o una richiesta del client del sito (una per account, §6.3). Con la tappa S3 di #36 i valori non cambiano, perché valgono anche per le storie mostrate con il browser e per un «Su misura» già salvato: con Instagram Febe va ancora per pagine. Da decidere (Alberto) prima che Instagram passi alle richieste (S4): se dimezzarli (25 / 150, 40 / 250, 60 / 400), dato che una richiesta porta tutte le storie di un account, e il nome («storie viste» o «richieste di storie»). Le simulazioni di 30 giorni non superano mai i tetti, per pagine e per richieste (§14.3). Quando Instagram passerà alle richieste (S4) un controllo del profilo costerà due profili aperti (profilo e griglia sono due operazioni), più l'elenco delle raccolte una volta al giorno: da confermare se raddoppiare «Profili aperti» o accettare meno controlli. La simulazione di 30 giorni con quel costo (`--raccolta richieste`, §14.3), con «Prudente»: profili aperti sempre al tetto (100 al giorno, 12 all'ora), storico di 2.000 post in 27 giorni invece di 10, post dei non seguiti scoperti in 7 ore e mezza invece di 4 e un quarto, 11 storie su 1.472 scadute senza essere viste (nessuna per pagine); nessun superamento dei tetti.
- «Storico per account al giorno» è il valore di partenza del limite che ogni account ha nelle proprie impostazioni (§4.4).
- Limiti di ciò che l'interfaccia accetta: pausa minima non sotto i 5 minuti; sessione non oltre i 30; fascia non oltre le 20 ore; nessun tetto oltre il doppio di «Rapido».
@@ -543,7 +550,7 @@ I valori sono **stime di partenza scelte con prudenza**. Non sono limiti ufficia
L'interruttore riceve segnali dalle ricette, dalla cattura e dal client del sito. L'elenco di partenza sta in un file di configurazione (`segnali.json`), così si aggiorna senza ricompilare; va completato dopo M0 (H8, H16).
Per il client del sito (§6.0) sono segnali anche: un rinvio (3xx) verso le pagine d'accesso, di verifica, di controllo o di sospensione, che non si segue mai; gli stati 401 e 403; un documento HTML dove il modello aspetta JSON; un JSON senza i campi attesi; un `Set-Cookie` che cancella il cookie di sessione. Finché le forme vere delle risposte di sessione scaduta o da verificare non sono note (H16), questi casi valgono come **Verifica**: Febe si ferma, avvisa, e decide Alberto se rifare l'accesso.
Per il client del sito (§6.0) sono segnali anche: un rinvio (3xx) verso le pagine d'accesso, di verifica, di controllo o di sospensione, che non si segue mai; gli stati 401 e 403; un documento HTML dove il modello aspetta JSON; un JSON senza i campi attesi; un `Set-Cookie` che cancella il cookie di sessione. Finché le forme vere delle risposte di sessione scaduta o da verificare non sono note (H16), questi casi valgono come **Verifica**: Febe si ferma, avvisa, e decide Alberto se rifare l'accesso. Un 404 o un 5xx con un JSON non è un segnale: lo legge la ricetta (§6.3). Il segnale ferma la ricetta prima di qualunque altra richiesta, e la risposta che l'ha portato non va ai lettori.
| Livello | Segnali | Che cosa fa Febe |
|---|---|---|
@@ -890,6 +897,7 @@ Eventi che meritano un avviso: verifica richiesta, disconnessione, fermo per ral
`--simula 30g --profilo prudente` fa girare il motore con l'orologio virtuale contro un mondo finto e produce un resoconto, anche in CSV.
- Il mondo: 40 account, 25 seguiti e 15 no, con frequenze di pubblicazione diverse (in media un post ogni tre giorni; storie quotidiane per metà degli account); un account con uno storico di 2.000 post; qualche rallentamento inserito a caso. Per la simulazione si può usare un `IBrowserHost` finto che risponde con i dati dei campioni, senza avviare un browser.
- `--raccolta richieste` simula le ricette per richieste (§6.3): nessuna raffica di scorrimento, le attese fra una richiesta e l'altra, una sola storia vista per le storie di un account. Un controllo del profilo costa come con le operazioni separate di Instagram, il caso prudente: due profili aperti (profilo e prima pagina dei post), più uno per l'elenco delle raccolte se non è stato chiesto nelle ultime 24 ore; la prima pagina dello storico di un account mai controllato conta come profilo. Sul sito di prova una sola richiesta porta tutto: la simulazione misura il costo che avrà Instagram con la tappa S4. `--raccolta pagine`, il predefinito, i gesti del browser. Il resoconto dice quale delle due.
- Il resoconto: sessioni al giorno; azioni per categoria al giorno e nell'ora peggiore; tempo medio e massimo tra la pubblicazione di un contenuto e la sua scoperta; giorni necessari per lo storico di 2.000 post; numero di superamenti dei tetti, che deve essere zero.
È il modo in cui Alberto giudica un profilo prima di usarlo, e il controllo principale della tappa M3.
+18
View File
@@ -389,3 +389,21 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-16 | `SiteAnswerSignals` (Febe.Core) legge i segnali di §7.6 da una `SiteAnswer`, qualunque cosa l'abbia portata: prima le regole di stato di `segnali.json` (429), poi il cookie di sessione cancellato, un rinvio, 401 e 403, poi con qualunque stato HTML al posto del JSON, un corpo che non è JSON (anche vuoto) e le regole di testo, infine, esclusi 404 e 5xx con un JSON (risposta, decide la ricetta o la tappa S3), i campi attesi mancanti; questi casi sono Verifica marcata H16. Non è ancora collegato al motore (S3). `SiteAnswer.RootFieldsPresent` dice se il client ha trovato i campi attesi | Decisione del 16 novembre (H16: Verifica finché le forme vere non sono note); un «attendi qualche minuto» in un JSON breve resta un Rallentamento anche senza i campi attesi. §6.0 ferma su una risposta che non è JSON senza eccezioni di stato: una pagina d'accesso o d'errore HTML servita con 404 o 5xx non è un «non trovato» |
| 2026-11-16 | Il sito di prova risponde al client del sito sotto `/api/` (`/api/dati/…` come `/dati/…`, e `POST /api/graphql` con la query `ProvaProfiloQuery`), controllando cookie `sessione_prova`, `x-csrftoken` uguale al cookie `csrftoken`, `x-app-id`, `doc_id`, gettoni e tipi delle variabili, con risposte generiche marcate H16 (302 all'accesso, 401, 403 HTML, 400); le pagine restano su `/dati/`, che non controlla nulla. `richieste.prova.json` passa a `/api/` e aggiunge `x-app-id`, `x-csrftoken` e la query GraphQL; `SiteControl.ReplyToDirect` gioca 429, rinvii, HTML, JSON senza campi, cookie rinnovato o cancellato, nuovo claim; i modi armati «dopo N richieste di dati» contano anche le richieste del client, e `sessione-scaduta` chiude la sessione anche sul sito | Le pagine del sito di prova non mandano `x-csrftoken`: controllare `/dati/` avrebbe cambiato le prove con il browser. Il sito non dà ancora alle pagine nessuno dei valori che controlla (cookie `csrftoken`, `app_id`, `lsd`, `fb_dtsg`, il `doc_id` di `ProvaProfiloQuery`, un claim): li mettono le prove nella sessione; li deve esporre la tappa S4, con la copia della sessione. Con le ricette sul client del sito (S3) un arresto «dopo N richieste» non sarebbe mai scattato |
| 2026-11-16 | Il sito di prova apre una sessione nuova (`aperta-N`, mai riusata) a ogni visita senza sessione viva, e chiude la sessione dalla stessa parte sia per le pagine sia per `/api/`; `attiva` resta solo come sessione iniziale per le prove senza browser | Dopo una sessione scaduta un nuovo accesso deve dare una sessione che anche il client del sito accetta, altrimenti le prove di «nuovo accesso e Riprendi» (S3, S4) non possono passare |
| 2026-11-17 | Una ricetta va per richieste (tappa S3 di #36) quando ogni ruolo che le serve è di un'operazione configurata di `richieste.<sito>.json`: i ruoli (`roles`) stanno nel catalogo, uno per operazione, mai su una ricerca, e un ruolo di pagina successiva vuole il cursore; il catalogo rifiuta il resto quando si carica | Il catalogo è già il file che si scrive dai campioni (regola 9): un ruolo nuovo non chiede di ricompilare, e una ricetta non parte mai con un'operazione che non è stata vista |
| 2026-11-17 | Con Instagram nessuna ricetta va per richieste: le dieci operazioni restano non configurate, Febe per Windows e Febe in Docker non costruiscono il client del sito per il motore, e senza rotte l'impronta della configurazione resta quella di prima | Il comportamento con Instagram non cambia finché la tappa S4 non porta sessione salvata e `doc_id`; un'impronta diversa avrebbe tolto le sospensioni senza motivo |
| 2026-11-17 | La prima pagina dei post conta come profilo (`firstPageCategory` di un'operazione «storico» senza cursore), le pagine successive come storico; ogni richiesta ha il permesso della sua categoria e il client lo ricontrolla | Il controllo del profilo per pagine contava un profilo per la pagina con la prima griglia: contare la stessa griglia come storico avrebbe consumato il tetto dello storico con i soli controlli |
| 2026-11-17 | Le storie di un account per richieste sono una sola «storia vista» (una richiesta, tutte le storie), senza il controllo del minimo di storie; i tetti delle storie viste restano 50 / 300, 80 / 500, 120 / 800 e il minimo del visualizzatore resta 10. Se dimezzarli (25 / 150, 40 / 250, 60 / 400) lo decide Alberto prima di S4 | Il tetto contava le storie mostrate una a una e con le richieste lo stesso numero permette più storie. Dimezzarlo in S3 avrebbe però cambiato il comportamento con Instagram: le storie mostrate con il browser, quando i bersagli saranno compilati, e il massimo di «Su misura», con un «Su misura» già salvato oltre il nuovo massimo che non si sarebbe più potuto salvare. Le simulazioni di 30 giorni non superano mai i tetti, per pagine e per richieste |
| 2026-11-17 | Attese fra le richieste della stessa ricetta: 1–6 s dopo una risposta (mediana 2,2 s), 2–8 s fra due pagine (mediana 3,5 s), 8% di probabilità di 15–90 s in più, moltiplicate per l'umore; la prima richiesta della ricetta non aspetta | Una persona che legge non chiede la pagina dopo subito; la distanza dalla ricetta precedente la tiene già il Governatore (§7.7), e un'attesa in più all'inizio avrebbe solo allungato le sessioni |
| 2026-11-17 | Per richieste un 404 con JSON è un «non trovato» della ricetta (profilo non raggiungibile `NotFound`, raccolta non più nel profilo, post sparito, nessuna storia), mai un segnale; un 5xx con JSON, una risposta mancante, troppo grande o rovinata fanno fallire la ricetta e contano come pagina vuota (tre di fila: Rallentamento), senza riprovare nella stessa ricetta (H19) | Il sito di prova e Instagram usano il 404 per ciò che non c'è; ripetere subito una richiesta che il sito ha rifiutato è il comportamento di un programma, non di una persona |
| 2026-11-17 | Una ricetta per richieste a cui manca un valore (identificativo dell'account, codice del post) torna alle pagine se le pagine la sanno fare, e lo scrive fra gli eventi («richieste-valore-mancante»); dopo un segnale non torna mai alle pagine | Il primo controllo di un account aggiunto a mano non ha ancora l'identificativo: senza ripiego non sarebbe mai partito. Dopo un segnale la regola 7 vuole l'arresto, non un'altra strada |
| 2026-11-17 | Senza l'operazione della pagina successiva la ricetta legge la prima pagina, tiene il cursore e lo dice («richieste-pagine-successive»): il punto resta salvato per quando l'operazione sarà configurata. Con un punto già salvato (Taggati, Reel, Elenco dei seguiti) la ricetta va con le pagine, se le pagine la sanno fare; altrimenti Taggati e Reel leggono la prima pagina per le novità in cima e il punto resta com'è | Le pagine successive dei post di Instagram non hanno ancora un campione (H3): fermarsi senza perdere il punto è meglio che non leggere nulla |
| 2026-11-17 | Una raccolta in evidenza si chiede con l'identificativo salvato dal controllo del profilo, così com'è (H20); una raccolta che Febe non conosce ancora non si chiede | Sul sito di prova l'identificativo è quello; su Instagram potrebbe servire il prefisso `highlight:`, da vedere sui campioni, e inventarlo violerebbe la regola 9 |
| 2026-11-17 | Il simulatore ha `--raccolta pagine|richieste` (`SimulatedCollection`): per richieste niente raffiche di scorrimento, le attese di `RequestTimings` fra una richiesta e l'altra e una storia vista per account; un controllo del profilo costa come le operazioni separate di Instagram, il caso prudente: 2 profili aperti (profilo e prima pagina dei post), più 1 per l'elenco delle raccolte se non è stato chiesto nelle ultime 24 ore, e la prima pagina dello storico di un account mai controllato conta come profilo | Per giudicare i tetti nuovi prima di usarli (§14.3), con lo stesso mondo e lo stesso seme delle pagine, e sul costo che avrà Instagram con la tappa S4 (domanda 1 ad Alberto), non su quello del sito di prova, dove una richiesta porta tutto. Con «Prudente» per richieste i profili aperti arrivano al tetto (100 al giorno, 12 all'ora), lo storico di 2.000 post si completa in 27 giorni invece di 10, la scoperta dei post dei non seguiti passa da 4 ore e 14 a 7 ore e 32 minuti e 11 storie su 1.472 scadono senza essere viste (nessuna per pagine); con «Equilibrato» e «Rapido» i profili aperti arrivano al tetto del giorno (180, 300), lo storico si completa in 7 e 4 giorni |
| 2026-11-17 | Il sito di prova scrive un campione dei reel (`000012-reel`, `/dati/profilo/{nome}?scheda=reel`), ripulito con `febe-sonda ripulisci` e verificato; l'operazione `reel` di `richieste.prova.json` è configurata su quello | Ogni operazione configurata ha il suo campione (regola 9); i pseudonimi del campione nuovo sono diversi da quelli di 000001–000011 perché la ripulitura li estrae a ogni esecuzione |
| 2026-11-17 | Le ricette per richieste sono file parziali di `RecipeRunner` (`RecipeRunner.Requests*.cs`, `RecipeRun.Requests.cs`) con un ambiente delle richieste facoltativo (`SiteRequestEnvironment`), che fino alla tappa S4 impostano solo le prove | Riusano permessi, segnali e salvataggi delle ricette per pagine; Febe in produzione non cambia |
| 2026-11-17 | Senza sessione salvata, o con un segnale nella risposta, la ricetta per richieste si ferma come Disconnessione o con il livello del segnale, mai con un ritorno alle pagine | Regola 7: browser e client del sito non usano la sessione insieme, e dopo un segnale ci si ferma |
| 2026-11-17 | L'elenco delle raccolte in evidenza si chiede al più una volta ogni 24 ore per account (`HighlightsTrayInterval`), sempre in un controllo a mano, mai con «Storie in evidenza» spento; quando ha un'operazione sua si chiede per ultimo, dopo la prima pagina salvata e il vuoto colmato, e un permesso negato lo rimanda al controllo dopo; quando la griglia e l'elenco arrivano nella stessa risposta non costa nulla in più. Da confermare (Alberto) | Le raccolte cambiano di rado: risparmia profili aperti quando, con Instagram, l'elenco sarà un'operazione a parte |
| 2026-11-17 | `IStopSignals.Report` porta al rilevatore un segnale già letto da `SiteAnswerSignals`; il rilevatore lo passa all'interruttore come quelli della pagina, con la stessa finestra contro i doppioni, senza rileggere la risposta | I segnali delle risposte passano dallo stesso rilevatore e dallo stesso interruttore; rileggere il testo avrebbe contato due volte lo stesso segnale |
| 2026-11-17 | Un «non trovato» delle storie di un account per richieste non è ancora «nessuna storia»: la ricetta chiede il profilo (un profilo aperto) e fa ciò che fanno le pagine: profilo sparito o privato non seguito, account non raggiungibile; altrimenti nessuna storia. Quel 404 non conta come pagina vuota; una risposta delle storie riconosciuta conta come dati | Il sito di prova risponde 404 alle storie di un profilo privato che Alberto non segue: senza il profilo l'account restava da contattare a ogni giro (regola 6), e tre 404 di fila sarebbero diventati un Rallentamento di tutto il motore |
| 2026-11-17 | Una raccolta in evidenza per richieste legge al più `PagesPerRun` pagine per volta e collega i contenuti di ogni pagina appena letta; l'ordine della raccolta si salva solo letta fino in fondo | Una raccolta lunga non consuma da sola l'ora delle storie viste, e un arresto su una pagina successiva non butta ciò che si è già letto e pagato |
| 2026-11-17 | Il motore controlla il tetto della prima azione della strada che la ricetta prende (`IRecipeRunner.FirstCategory`): per richieste Taggati e Reel cominciano con una pagina di storico, non con un profilo aperto; per pagine e con Instagram resta `CheckPolicy.CategoryOf`. Una ricetta per richieste può tornare alle pagine per un'esecuzione (valore mancante, pagina successiva senza richiesta): il motore la salta se è esaurito l'uno o l'altro tetto e, dopo un rifiuto, li ricontrolla tutti e due | Con il tetto sbagliato una sessione senza pagine di storico avrebbe fatto partire una dopo l'altra ricette destinate al rifiuto, e dopo il rifiuto non avrebbe segnato esaurita la categoria giusta |
+3
View File
@@ -147,6 +147,9 @@ Febe salva le storie solo dopo averle **aperte** nel visualizzatore, come una vi
Febe risultano viste** e tu compari tra gli spettatori. Non esiste una visione anonima. Per un account in cui non vuoi
comparire, spegni «Storie» (e «Storie in evidenza», che si aprono allo stesso modo).
Quando le storie si leggono con il client del sito, una sola richiesta per account, non risultano viste. Con Instagram
Febe usa ancora le pagine; il client del sito arriva più avanti.
## Comandi
- **Controlla ora:** mette quel controllo in cima alla coda. Passa comunque dai tetti: se il tetto è esaurito Febe lo
+14
View File
@@ -126,3 +126,17 @@ la stessa ricetta la sospendono**, e Attività lo dice. Che cosa fare: raccoglie
passiva (vedi [Ipotesi da verificare](Ipotesi-da-verificare) e [Sviluppo](Sviluppo)), aggiornare il lettore sulla copia
ripulita, poi riattivare la ricetta da Attività. Allo stesso modo, se Febe non trova nella pagina un comando che gli
serve («bersaglio non trovato»), si ferma e lo segnala, senza cliccare a caso.
## Ricette per richieste
Una ricetta può leggere i dati con le richieste del client del sito invece che con i gesti nel browser: il rapporto
della configurazione lo dice per ciascuna («Controllo del profilo: per richieste (…)»). Ogni richiesta chiede il suo
permesso ai tetti, come una pagina. Un profilo, una raccolta o un post che il sito dice «non trovato» non è un
arresto: l'account o il contenuto risultano non più raggiungibili. Se il «non trovato» riguarda le storie di un
account, Febe guarda il suo profilo, come farebbe con il browser: un profilo sparito, o privato e che non segui,
diventa non raggiungibile; altrimenti quell'account oggi non ha storie. Un errore del sito (5xx) o una risposta che
non arriva fanno fallire la ricetta, che riprova al giro successivo; tre risposte vuote di fila sono un rallentamento.
Fra gli eventi può comparire «le pagine successive non sono ancora configurate per le richieste»: Febe ha letto la
prima pagina e tiene il punto (una raccolta in evidenza, che non ha punto, la prossima volta ricomincia dalla
prima pagina), oppure, se c'era già un punto salvato, questa volta usa le pagine. Con Instagram
Febe usa ancora le pagine; il client del sito arriva più avanti.
+3
View File
@@ -38,6 +38,9 @@ ritoccati guardando che cosa succede.
recupera prima, ma rallentamenti e verifiche diventano più probabili.
- Se cambi un valore, il profilo diventa **«Su misura»**; scegliendo un profilo torni ai suoi valori.
- «Storico per account al giorno» è il valore di partenza del limite che ogni account ha nelle sue impostazioni.
- «Storie viste» conta una storia aperta nel visualizzatore oppure, quando le storie di un account si leggono con una
sola richiesta, quella richiesta.
Con Instagram Febe usa ancora le pagine; il client del sito arriva più avanti.
- Limiti di ciò che l'interfaccia accetta: pausa minima non sotto i 5 minuti; sessione non oltre i 30; fascia non oltre
le 20 ore; nessun tetto oltre il doppio di «Rapido»; almeno un giorno attivo.
- I limiti salvati valgono da subito, anche per il motore che sta lavorando.
+3 -1
View File
@@ -120,13 +120,15 @@ vera e non invia messaggi Telegram.
## Simulazione
```sh
dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente [--csv resoconto.csv] [--seme 7]
dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente [--raccolta pagine|richieste] [--csv resoconto.csv] [--seme 7]
```
Fa girare il motore vero con l'orologio virtuale contro un mondo finto (40 account, 25 seguiti, uno con uno storico di
2.000 post, qualche rallentamento a caso) e scrive il resoconto: sessioni al giorno, azioni per categoria al giorno e
nell'ora peggiore, tempo medio e massimo fra pubblicazione e scoperta, giorni per lo storico, superamenti dei tetti
(devono essere zero). Profili: `prudente`, `equilibrato`, `rapido`. È il modo per giudicare un profilo prima di usarlo.
Con `--raccolta richieste` le ricette simulate costano come per richieste (#36): una «storia vista» per le storie di
un account, tutte in una risposta, e le attese del client del sito invece dei gesti; senza, per pagine.
## Il sito di prova
+46 -1
View File
@@ -1,12 +1,57 @@
# Stato
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
Aggiornato il 16 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
Aggiornato il 17 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
fra le sessioni; ciò che è da fare si legge nelle issue aperte.
## In breve
**17 novembre 2026: le ricette fatte di richieste** (#36, tappa S3).
- Otto ricette hanno ora una strada per richieste accanto a quella con il browser: Controllo del profilo, Storico,
Taggati, Reel, Storie di un account, Raccolta in evidenza, Post singolo ed Elenco dei seguiti
(`RecipeRunner.Requests*.cs`, `RecipeRun.Requests.cs`, `SiteRequestEnvironment`). Il Giro dei seguiti e la ricerca
dei profili restano sul browser: per la home non ci sono campioni.
- Ogni operazione di `richieste.<sito>.json` dice a che cosa serve (`roles`); una ricetta va per richieste solo se
ogni ruolo che le serve è di un'operazione configurata. **Con Instagram non cambia nulla**: le sue dieci operazioni
restano non configurate e Febe per Windows e in Docker non costruiscono il client del sito (S4).
- Un permesso del Governatore per ogni richiesta, nella categoria di ciò che chiede; la prima pagina dei post conta
come profilo (`firstPageCategory`). Attese fra le richieste di 1–6 s e fra le pagine di 2–8 s, con l'8% di pause
di 15–90 s, sempre in più della distanza del Governatore. Le storie di un account sono una richiesta e una «storia
vista», e non risultano viste; un «non trovato» delle storie chiede il profilo per sapere se è privato o sparito.
- Segnali: `IStopSignals.Report` porta all'interruttore quelli di `SiteAnswerSignals`; la ricetta si ferma prima di
ogni altra richiesta. Un 404 o un 5xx con JSON è una pagina vuota e un esito della ricetta, senza nuovo tentativo.
- Se manca un valore (identificativo dell'account, codice del post) o l'operazione della pagina successiva, la
ricetta torna alle pagine per quella volta e lo dice. Il motore controlla il tetto della prima azione della strada
(`IRecipeRunner.FirstCategory`) e salta la ricetta se è esaurito quello delle richieste o quello delle pagine.
- **Tetti**: nessuno cambia. Il dimezzamento delle storie viste proposto dal progetto è stato tolto, perché valeva
anche per le storie mostrate con il browser e per un «Su misura» già salvato, cioè cambiava Instagram; se
dimezzarle quando Instagram passerà alle richieste è una domanda per Alberto.
- Simulatore: `--raccolta pagine|richieste`; per richieste un controllo del profilo costa come le operazioni separate
di Instagram (2 profili aperti, più 1 al giorno per l'elenco delle raccolte). Sei simulazioni di 30 giorni, tutte
senza superamenti: con «Prudente» per richieste i profili aperti stanno al tetto e lo storico di 2.000 post finisce
in 27 giorni invece di 10 (Equilibrato 7 invece di 5, Rapido 4 come per pagine).
- Sito di prova: nuovo campione ripulito `000012-reel`; l'operazione `reel` è configurata. Prove nuove: 69 in tre classi
(`RequestRecipeTests`, `RequestRoutingTests`, `RequestRecipeSiteTests` sul sito di prova vero, più alcune esistenti
ritoccate). Revisione su tre lenti (16 punti, 15 reali e corretti, uno voluto), controllo finale (2 difetti,
corretti a mano), revisione finale indipendente (3 punti
minori confermati e corretti: il messaggio «il punto resta salvato» per una raccolta in evidenza, che un punto non
ce l'ha; un'attesa in più prima della richiesta delle storie dopo un altro account; il costo «1 profilo» nella
tabella di §6.3).
- Controlli: `dotnet build -warnaserror` pulito; `dotnet test tests/Febe.Tests` 1230 superate, 86 saltate (Chromium,
solo nella CI); `tests/Febe.Tests.Windows` 17 su 17.
- **Non verificato**: le prove con Chromium (CI); le pagine successive della Raccolta in evidenza (nessun campione
paginato); `FirstCategory` dentro il motore con una ricetta che torna alle pagine (oggi Taggati e Reel partono solo
dopo un controllo del profilo riuscito, quindi il caso non si presenta); niente su Instagram (regola 1). Ipotesi
nuove H18 (cursori), H19 (404 e 5xx), H20 (`highlight_id`).
- **Domande per Alberto** (anche su #36): raddoppiare «Profili aperti» quando Instagram passerà alle richieste?
Dimezzare allora le storie viste e chiamarle «richieste di storie»? Un 404, un 5xx o un sito muto contano come
pagina vuota senza nuovo tentativo? Elenco delle raccolte al più una volta ogni 24 ore per account? Giro dei
seguiti e ricerca restano sul browser anche dopo S4? Senza browser da dove viene l'`account_id`? Che forma ha
`highlight_id` (con `highlight:` o senza)? Prima di passare il controllo alle richieste va configurato
`posts-next`: confermi l'ordine? Un «non trovato» delle storie costa un profilo aperto: va bene?
**16 novembre 2026: richieste dirette con la sessione copiata dal browser** (#36, tappe S0, S1 e S2; #52).
- Il HAR nuovo di Alberto (home, due ricerche, due profili) è stato letto solo in forma aggregata, senza stampare
+4
View File
@@ -1,3 +1,4 @@
using Febe.Core.Abstractions;
using Febe.Core.Engine;
namespace Febe.App;
@@ -27,4 +28,7 @@ public sealed class DeferredRecipeRunner : IRecipeRunner
/// <summary>The real runner's answer; before the browser is up nothing is known, and nothing is held back.</summary>
public string? NotConfiguredReason(RecipeKind kind) => _target?.NotConfiguredReason(kind);
/// <summary>The real runner's answer; before the browser is up, the category by the pages.</summary>
public ActionKind FirstCategory(RecipeKind kind) => _target?.FirstCategory(kind) ?? CheckPolicy.CategoryOf(kind);
}
+2
View File
@@ -435,6 +435,8 @@ public sealed class FebeApp : IAsyncDisposable
PageTurns = services.PageTurns,
SearchOptions = search.Options,
SearchPhotos = search.Photos,
// Requests: S4 (#36). Until then every recipe goes by the browser.
},
ct).ConfigureAwait(false);
runner.Target = Pipeline.Runner;
@@ -9,6 +9,7 @@ using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
@@ -104,8 +105,19 @@ public sealed record CollectionPipelineOptions
/// <summary>Where the photos of the search results are kept (memory). Null: the search fetches no photo.</summary>
public SearchPhotoCache? SearchPhotos { get; init; }
/// <summary>
/// The site client and its catalog (issue #36, S3): the recipes whose roles are all configured go by requests.
/// Null: every recipe goes by the browser. Production leaves it unset until S4.
/// </summary>
public SiteRequestOptions? Requests { get; init; }
}
/// <summary>The site client of the pipeline and the catalog of its operations (issue #36, S3).</summary>
/// <param name="Requester">The site client: one request at a time, each with its permit.</param>
/// <param name="Catalog">The operations of <c>richieste.&lt;sito&gt;.json</c> and their roles.</param>
public sealed record SiteRequestOptions(ISiteRequester Requester, RequestCatalog Catalog);
/// <summary>
/// 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.
@@ -191,6 +203,14 @@ public sealed class CollectionPipeline : IAsyncDisposable
Options = options.Recipes,
Diagnostics = diagnostics,
PageTurns = options.PageTurns,
Requests = options.Requests is { } requests
? new SiteRequestEnvironment(
requests.Requester,
requests.Catalog,
new SiteAnswerSignals(rules, site.SessionCookie.CookieName),
options.Pace,
message => options.Log?.Write(BrowserLogLevel.Warning, message))
: null,
});
var fetcher = new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log);
var downloads = new DownloadQueue(
@@ -3,6 +3,7 @@ using System.Security.Cryptography;
using System.Text;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Engine;
namespace Febe.Core.Collection;
@@ -36,7 +37,8 @@ public sealed class CollectionConfiguration
CollectionConfigurationFile vocabularyFile,
CollectionConfigurationFile mapFile,
ReaderVocabulary? embeddedVocabulary,
SiteMap? embeddedMap)
SiteMap? embeddedMap,
RequestCatalog? requests)
{
Site = site;
Vocabulary = vocabulary;
@@ -45,10 +47,17 @@ public sealed class CollectionConfiguration
MapFile = mapFile;
EmbeddedVocabulary = embeddedVocabulary;
EmbeddedMap = embeddedMap;
Blocked = BlockedBy(map, vocabulary);
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
ByRequests = requests is null ? [] : RequestRoutes(requests);
Blocked = BlockedBy(map, vocabulary, ByRequests.Select(r => r.Kind));
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile, ByRequests);
}
/// <summary>
/// The recipes that go by requests with the catalog given to <see cref="Describe"/> (issue #36, S3), with the names of
/// their operations, in the order of <see cref="RecipeKind"/>; empty without a catalog.
/// </summary>
public IReadOnlyList<(RecipeKind Kind, IReadOnlyList<string> Operations)> ByRequests { get; }
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
public string Site { get; }
@@ -90,6 +99,7 @@ public sealed class CollectionConfiguration
[
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
.. ByRequests.Select(r => $"{RecipeRunner.Name(r.Kind)}: per richieste ({string.Join(", ", r.Operations)})."),
Blocked.Count == 0
? "Con questa configurazione tutte le ricette possono girare."
: $"Con questa configurazione non possono girare {Blocked.Count.ToString(CultureInfo.InvariantCulture)} ricette su {all.ToString(CultureInfo.InvariantCulture)}: {Names(Blocked)}.",
@@ -131,8 +141,15 @@ public sealed class CollectionConfiguration
/// as the pipeline loaded them (their <c>Source</c> tells a Data-folder copy from the embedded file). The text of a
/// copy is read again from its path for the fingerprint.
/// </summary>
/// <param name="site">The site name of the files.</param>
/// <param name="vocabulary">The reader vocabulary as loaded.</param>
/// <param name="map">The target map as loaded.</param>
/// <param name="requests">
/// The catalog of the site client, when the recipes have it (issue #36, S3): the recipes it lets go by requests need
/// only the vocabulary, and its roles are part of the fingerprint. Null: every recipe goes by the browser.
/// </param>
/// <exception cref="IOException">A copy in the Data folder cannot be read any more.</exception>
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map)
public static CollectionConfiguration Describe(string site, ReaderVocabulary vocabulary, SiteMap map, RequestCatalog? requests = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(site);
ArgumentNullException.ThrowIfNull(vocabulary);
@@ -141,15 +158,40 @@ public sealed class CollectionConfiguration
var mapFile = LoadedFile($"bersagli.{site}.json", map.Source);
var embeddedVocabulary = vocabularyFile.IsOverride ? Try(() => ReaderVocabulary.LoadEmbedded(vocabularyFile.Name)) : vocabulary;
var embeddedMap = mapFile.IsOverride ? Try(() => SiteMap.LoadEmbedded(mapFile.Name)) : map;
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap);
return new CollectionConfiguration(site, vocabulary, map, vocabularyFile, mapFile, embeddedVocabulary, embeddedMap, requests);
}
/// <summary>The recipes a map and a vocabulary do not let run, by the same rule as the runner's.</summary>
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary)
/// <param name="map">The target map.</param>
/// <param name="vocabulary">The reader vocabulary.</param>
/// <param name="byRequests">Recipes that go by requests: the map does not block them.</param>
public static IReadOnlyList<RecipeKind> BlockedBy(SiteMap map, ReaderVocabulary vocabulary, IEnumerable<RecipeKind>? byRequests = null)
{
ArgumentNullException.ThrowIfNull(map);
ArgumentNullException.ThrowIfNull(vocabulary);
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
if (!vocabulary.IsUsable)
{
return Enum.GetValues<RecipeKind>();
}
var routed = byRequests?.ToHashSet() ?? [];
return [.. MissingFrom(map).Where(kind => !routed.Contains(kind))];
}
/// <summary>The recipes <paramref name="catalog"/> lets go by requests, with the names of their operations.</summary>
public static IReadOnlyList<(RecipeKind Kind, IReadOnlyList<string> Operations)> RequestRoutes(RequestCatalog catalog)
{
ArgumentNullException.ThrowIfNull(catalog);
var routes = new List<(RecipeKind, IReadOnlyList<string>)>();
foreach (var kind in Enum.GetValues<RecipeKind>())
{
if (kind != RecipeKind.FollowingSweep && RecipeRunner.RequestOperations(catalog, kind) is { } operations)
{
routes.Add((kind, [.. operations.Select(o => o.Name)]));
}
}
return routes;
}
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
@@ -183,10 +225,17 @@ public sealed class CollectionConfiguration
}
}
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map, IReadOnlyList<(RecipeKind Kind, IReadOnlyList<string> Operations)> byRequests)
{
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
var routes = byRequests.Select(r => $"{r.Kind}={string.Join(',', r.Operations)}");
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
// The routes by requests change what runs: a new role clears the suspensions too. None: the fingerprint of S2.
if (byRequests.Count > 0)
{
text += "\nrichieste\n" + string.Join('\n', routes);
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
}
+7
View File
@@ -19,4 +19,11 @@ public interface IStopSignals
/// <summary>Result of the session-cookie check: a missing cookie is a disconnection.</summary>
Signal? ObserveSessionCookie(bool present);
/// <summary>
/// A signal read elsewhere, from an answer of the site client (<see cref="Requests.SiteAnswerSignals"/>, issue #36):
/// it goes to the circuit breaker through the same detector, with the same deduplication, as the captured ones.
/// Returns the signal when it was reported, null when the same code was reported within the deduplication window.
/// </summary>
Signal? Report(Signal signal);
}
@@ -41,6 +41,56 @@ public sealed record RecipeOptions
/// <summary>The backfill stops while the account has more files than this waiting for download (spec §6.3: 60).</summary>
public int MaxPendingDownloadsForBackfill { get; init; } = 60;
/// <summary>
/// Controllo del profilo by requests: the tray of the highlight collections, when it is an operation of its own, is
/// asked at most once in this time per account (a manual check always asks).
/// </summary>
public TimeSpan HighlightsTrayInterval { get; init; } = DefaultHighlightsTrayInterval;
/// <summary>The default of <see cref="HighlightsTrayInterval"/> (also the simulator's).</summary>
public static readonly TimeSpan DefaultHighlightsTrayInterval = TimeSpan.FromHours(24);
}
/// <summary>
/// The waits between the requests of one recipe (issue #36, S3), for the «naturale» pace: 1–6 s (median 2.2 s) after
/// an answer before the next request, 2–8 s (median 3.5 s) between two pages of a walk, and on any of them an 8% chance
/// of a longer pause of 15–90 s. Every value is multiplied by mood and pace. They come on top of the Governor's minimum
/// spacing (§7.7), never in its place.
/// </summary>
public static class RequestTimings
{
public static readonly TimeSpan AfterAnswerMin = TimeSpan.FromSeconds(1);
public static readonly TimeSpan AfterAnswerMax = TimeSpan.FromSeconds(6);
public static readonly TimeSpan AfterAnswerMedian = TimeSpan.FromSeconds(2.2);
public static readonly TimeSpan BetweenPagesMin = TimeSpan.FromSeconds(2);
public static readonly TimeSpan BetweenPagesMax = TimeSpan.FromSeconds(8);
public static readonly TimeSpan BetweenPagesMedian = TimeSpan.FromSeconds(3.5);
public static readonly TimeSpan LongPauseMin = TimeSpan.FromSeconds(15);
public static readonly TimeSpan LongPauseMax = TimeSpan.FromSeconds(90);
/// <summary>The chance of a longer pause on a gap.</summary>
public const double LongPauseChance = 0.08;
/// <summary>The wait after an answer, before the next request of the same run.</summary>
public static TimeSpan AfterAnswer(IRandomSource random, double multiplier) =>
Gap(random, AfterAnswerMin, AfterAnswerMax, AfterAnswerMedian, multiplier);
/// <summary>The wait between two pages of a walk.</summary>
public static TimeSpan BetweenPages(IRandomSource random, double multiplier) =>
Gap(random, BetweenPagesMin, BetweenPagesMax, BetweenPagesMedian, multiplier);
private static TimeSpan Gap(IRandomSource random, TimeSpan min, TimeSpan max, TimeSpan median, double multiplier)
{
ArgumentNullException.ThrowIfNull(random);
var wait = random.Between(min, max, median);
if (random.Chance(LongPauseChance))
{
wait += random.Between(LongPauseMin, LongPauseMax);
}
return TimeSpan.FromTicks((long)(wait.Ticks * multiplier));
}
}
/// <summary>
@@ -0,0 +1,152 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Requests;
using Febe.Core.Engine;
using Febe.Core.Pacing;
namespace Febe.Core.Collection.Recipes;
/// <summary>Which wait of <see cref="RequestTimings"/> comes before a request.</summary>
internal enum RequestGap
{
/// <summary>The first request of the run: none.</summary>
None,
/// <summary>After an answer, before the next request of the same run.</summary>
AfterAnswer,
/// <summary>Between two pages of a walk.</summary>
BetweenPages,
}
/// <summary>What one request of a run gave: the reads of its answer, or a «not found» of the site (a 404 with JSON).</summary>
/// <param name="Operation">The operation asked.</param>
/// <param name="Reads">What the readers made of the answer (empty for a «not found»).</param>
/// <param name="NotFound">The site said the resource is not there (H19): counted as an empty page, the recipe decides.</param>
internal sealed record RequestReply(SiteOperation Operation, IReadOnlyList<CapturedRead> Reads, bool NotFound);
internal sealed partial class RecipeRun
{
/// <summary>The requests of the site client this run made (each under its own permit).</summary>
public int RequestsAsked { get; private set; }
/// <summary>
/// One request of the site client in this run (issue #36, S3): the wait of <paramref name="gap"/>, then the permit
/// of the Governor in the category of the request (<see cref="SiteOperation.CategoryFor"/>), then the request with
/// that very permit, never another (rule 8). A refusal of the Governor stops the run in order as for a page. The
/// answer is read for the stop signals of §7.6 first (<see cref="SiteAnswerSignals"/>): a signal goes to the
/// detector and the circuit breaker and stops the run where it is, before any other request. A 404 with JSON is an
/// empty page and a «not found» for the recipe; a 5xx with JSON, an answer that never came or broke, an empty page
/// and a failure of the run, never tried again in it (H19). Otherwise the body goes to the readers, only to them,
/// and the reads of that answer come back. The diagnostics see the request as a page fetch: the shape of the path
/// and the status, never a value (rule 10). With <paramref name="notFoundIsEmpty"/> false a 404 is not counted as an
/// empty page: the recipe explains it itself (the stories of an account, whose «not found» may be a private
/// profile or no stories at all).
/// </summary>
public async Task<RequestReply> AskAsync(SiteOperation operation, SiteRequest request, long? accountId, RequestGap gap, bool notFoundIsEmpty = true)
{
ArgumentNullException.ThrowIfNull(operation);
ArgumentNullException.ThrowIfNull(request);
var requests = Env.Requests ?? throw new InvalidOperationException("Il client del sito non è configurato per le ricette.");
ThrowIfSignal();
// The first request of a run waits nothing here: the engine has spaced the runs already.
if (gap != RequestGap.None && RequestsAsked > 0)
{
var multiplier = Session.Mood * GesturePaceFactors.For(requests.Pace);
var wait = gap == RequestGap.BetweenPages
? RequestTimings.BetweenPages(Env.Random, multiplier)
: RequestTimings.AfterAnswer(Env.Random, multiplier);
await Env.Clock.Delay(wait, Ct).ConfigureAwait(false);
}
var permit = await PermitAsync(operation.CategoryFor(request), accountId, opensPage: true).ConfigureAwait(false);
RequestsAsked++;
SiteAnswer answer;
try
{
answer = await requests.Requester.SendAsync(request, permit, Ct).ConfigureAwait(false);
}
catch (SiteSessionMissingException missing)
{
// No saved session, or one without what the catalog asks: a disconnection, never a way back to the pages
// (rule 7: the browser and the site client never use the session together).
var stop = SiteAnswerSignals.ForMissingSession(missing, Env.Clock.Now);
_signals.Report(stop.Signal);
throw Stop(RecipeStatus.StoppedBySignal, stop.Message);
}
catch (SiteUnreachableException unreachable)
{
Env.Signals.ObserveEmptyPage(operation.PathShape);
ThrowIfSignal();
throw Stop(RecipeStatus.Failed, $"Il sito non ha risposto a «{operation.Name}» ({Why(unreachable.Reason)}): si riprova al prossimo giro.");
}
catch (SiteRequestRefusedException refused)
{
// Refused before leaving (a stale catalog, or a bug of Febe): nothing reached the site.
requests.Warn?.Invoke($"Client del sito: richiesta «{operation.Name}» rifiutata prima di partire.");
throw new RecipeStopException(RecipeStatus.Failed, refused.Message) { ErrorType = refused.GetType().Name };
}
var descriptor = new ResponseDescriptor(
"richiesta-" + _runner.NextRequestNumber().ToString(CultureInfo.InvariantCulture),
HostKind.Site,
operation.PathShape,
string.Empty,
operation.PathShape,
answer.Status,
answer.MimeType,
"Fetch",
false,
Env.Clock.Now);
Env.Diagnostics?.OnResponse(descriptor);
Env.Diagnostics?.OnLoadingFinished(descriptor.RequestId, answer.Body.Length);
if (requests.AnswerSignals.Classify(operation, answer, Env.Clock.Now) is { } signal)
{
Env.Diagnostics?.OnBodyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
_signals.Report(signal.Signal);
throw Stop(RecipeStatus.StoppedBySignal, signal.Hypothesis is { } hypothesis ? $"{signal.Message} (ipotesi {hypothesis})" : signal.Message);
}
if (answer.Status == 404)
{
Env.Diagnostics?.OnBodyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
if (notFoundIsEmpty)
{
Env.Signals.ObserveEmptyPage(operation.PathShape);
ThrowIfSignal();
}
return new RequestReply(operation, [], NotFound: true);
}
if (answer.Status >= 500)
{
Env.Diagnostics?.OnBodyDropped(descriptor.RequestId, BodyDropReason.NoConsumers);
Env.Signals.ObserveEmptyPage(operation.PathShape);
ThrowIfSignal();
throw Stop(RecipeStatus.Failed, $"Il sito ha risposto con un errore ({answer.Status.ToString(CultureInfo.InvariantCulture)}) a «{operation.Name}»: si riprova al prossimo giro.");
}
var mark = Env.Capture.Mark();
await _runner.Delivery.DeliverBodyAsync(descriptor, answer.Body, [Env.Capture], Ct).ConfigureAwait(false);
var reads = Env.Capture.Since(mark).Where(r => string.Equals(r.Response.RequestId, descriptor.RequestId, StringComparison.Ordinal)).ToList();
ThrowIfSignal();
return new RequestReply(operation, reads, NotFound: false);
}
/// <summary>
/// An answer the readers recognized, whose content the recipe does not judge (the stories of an account: none is a
/// quiet day): the site gives data, so the count of empty pages in a row starts again.
/// </summary>
public void SawData() => _signals.ObserveNonEmptyPage();
private static string Why(SiteUnreachableReason reason) => reason switch
{
SiteUnreachableReason.Timeout => "nessuna risposta in tempo",
SiteUnreachableReason.TooLarge => "risposta troppo grande",
SiteUnreachableReason.Broken => "risposta rovinata",
_ => "collegamento non riuscito",
};
}
@@ -20,7 +20,7 @@ internal sealed class RecipeStopException(RecipeStatus status, string message) :
/// recipe uses (ask the Governor, open a page, click a target, wait for data). Any of them stops the run with a
/// <see cref="RecipeStopException"/> when something says to stop.
/// </summary>
internal sealed class RecipeRun : IDisposable
internal sealed partial class RecipeRun : IDisposable
{
private readonly RecipeRunner _runner;
private readonly IStopSignals _signals;
@@ -81,9 +81,10 @@ internal sealed class RecipeRun : IDisposable
/// <summary>
/// Asks the Governor for a counted action; stops in order when refused or when the session is over. With
/// <paramref name="opensPage"/> (the next step opens a page), this is a turn point of the page (issue #37): when the
/// profile search waits, it gets the page for one step first, and the checks run again after it.
/// profile search waits, it gets the page for one step first, and the checks run again after it. Returns the
/// permit granted: a request of the site client goes with that very permit (one per request, rule 8).
/// </summary>
public async Task PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
public async Task<Permit> PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
{
ThrowIfSignal();
if (opensPage && Env.PageTurns is { } turns && turns.EngineTurn is { } turn && await turns.YieldAsync(turn, Ct).ConfigureAwait(false))
@@ -104,6 +105,7 @@ internal sealed class RecipeRun : IDisposable
}
Actions++;
return permit;
}
/// <summary>Opens a page of the site map and waits after the load like a person (§7.7).</summary>
@@ -22,6 +22,37 @@ public sealed partial class RecipeRunner
/// all its files, or to get a fresh address for a file whose address expired. Never for stories.
/// </summary>
private async Task<RecipeStatus> SinglePostAsync(RecipeRun run)
{
var (entry, account) = await LoadPostEntryAsync(run, needsCode: true).ConfigureAwait(false);
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).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, PostNotFoundMessage);
}
return await CompletePostAsync(run, entry, account, Contents(reads, Matches).First()).ConfigureAwait(false);
}
/// <summary>Completes the entry with the post just read, whatever brought it, and ends the run with what changed.</summary>
private async Task<RecipeStatus> CompletePostAsync(RecipeRun run, Entry entry, Account account, Readers.ContentItem item)
{
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.");
}
/// <summary>Outcome message of a post page (or answer) that did not give the post.</summary>
private const string PostNotFoundMessage = "La pagina del post non ha dato il post: forse non esiste più.";
/// <summary>
/// The entry a «Post singolo» completes and its account: it must exist, be a post (never a story, a collection item
/// or a profile picture), not be deleted, and — with <paramref name="needsCode"/> — have its code; its account must
/// not be «Solo archivio». Stops the run otherwise.
/// </summary>
private async Task<(Entry Entry, Account Account)> LoadPostEntryAsync(RecipeRun run, bool needsCode)
{
if (run.Request.EntryId is not { } entryId)
{
@@ -35,9 +66,9 @@ public sealed partial class RecipeRunner
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)
if (entry.State == EntryState.Deleted || (needsCode && 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.");
throw RecipeRun.Stop(RecipeStatus.Completed, needsCode && 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)
@@ -47,19 +78,7 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
}
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).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.");
return (entry, account);
}
/// <summary>
@@ -157,9 +176,20 @@ public sealed partial class RecipeRunner
read = Math.Max(read, readBefore); // not back there yet: the stored point stays
}
return await FinishFollowingAsync(run, finished, read, started!.Value, cursor).ConfigureAwait(false);
}
/// <summary>
/// The end of a run of the following list, whatever turned its pages: at the end of the list the profiles not read
/// since it started are removed and the progress cleared («seguiti-letti»); otherwise the progress is stored for the
/// next session («seguiti-parziale»). Always ends the run.
/// </summary>
private async Task<RecipeStatus> FinishFollowingAsync(RecipeRun run, bool finished, int read, DateTimeOffset started, string? cursor)
{
var settings = Env.Storage.Settings;
if (finished)
{
var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started!.Value, run.Ct).ConfigureAwait(false);
var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started, run.Ct).ConfigureAwait(false);
await settings.SetManyAsync(
new Dictionary<string, string?> { [FollowingKeys.Cursor] = null, [FollowingKeys.StartedAt] = null, [FollowingKeys.Read] = null },
run.Ct).ConfigureAwait(false);
@@ -173,7 +203,7 @@ public sealed partial class RecipeRunner
new Dictionary<string, string?>
{
[FollowingKeys.Cursor] = cursor,
[FollowingKeys.StartedAt] = started!.Value.ToString("O", CultureInfo.InvariantCulture),
[FollowingKeys.StartedAt] = started.ToString("O", CultureInfo.InvariantCulture),
[FollowingKeys.Read] = read.ToString(CultureInfo.InvariantCulture),
},
run.Ct).ConfigureAwait(false);
@@ -95,6 +95,9 @@ public sealed partial class RecipeRunner
/// <summary>No page came after the bursts (counted as an empty page).</summary>
NoData,
/// <summary>By requests: the pages go on, but there is no request for the next one (no cursor, or its role not configured).</summary>
NoNext,
}
/// <summary>The rules of one walk over the pages of a profile, starting from the page on screen.</summary>
@@ -143,22 +146,55 @@ public sealed partial class RecipeRunner
var account = await LoadAccountAsync(run).ConfigureAwait(false);
var (current, reads) = await OpenProfileAsync(run, account, waitForGrid: true).ConfigureAwait(false);
account = current;
var profile = AccountProfile(reads, account)!;
await RecordCheckedProfileAsync(run, account, AccountProfile(reads, account)!, reads, highlights: true).ConfigureAwait(false);
var (items, tailIsNew, fillGap) = await SaveFirstGridPageAsync(run, account, reads).ConfigureAwait(false);
if (fillGap)
{
await FillGapAsync(run, account, reads, items, tailIsNew).ConfigureAwait(false);
}
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>
/// What a profile check keeps of the profile, whatever brought it: whether it has stories newer than the last
/// look, the list of its highlight collections (when <paramref name="highlights"/>: the list was read), a copy of
/// its picture when it changed.
/// </summary>
private async Task RecordCheckedProfileAsync(RecipeRun run, Account account, ProfileInfo profile, IReadOnlyList<CapturedRead> reads, bool highlights)
{
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 (highlights)
{
await UpsertListedHighlightsAsync(run, account, reads).ConfigureAwait(false);
}
if ((await Writer.SaveProfilePictureAsync(account, profile, run.Ct).ConfigureAwait(false)).Outcome == SaveOutcome.Created)
{
run.NewEntries++;
}
}
/// <summary>The highlight collections of the account that <paramref name="reads"/> list, stored.</summary>
private Task UpsertListedHighlightsAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads)
{
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
return Writer.UpsertHighlightsAsync(account, listed, run.Ct);
}
/// <summary>
/// Saves the first page of the grid of a profile check, whatever brought it, and starts or ends the history when
/// it has not started yet. Returns the items of the page, whether the last regular one was new, and whether the
/// gap below the page is to be filled (the history has started or ended: <see cref="FillGapAsync"/>).
/// </summary>
private async Task<(IReadOnlyList<ContentItem> Items, bool TailIsNew, bool FillGap)> SaveFirstGridPageAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads)
{
// The whole first page is read (it is on screen already): known posts at its top do not hide new ones below
// them, e.g. when the giro dei seguiti saved only the newest. Pinned posts are known but stop nothing.
var walk = ProfileWalk.Posts;
@@ -197,14 +233,12 @@ public sealed partial class RecipeRunner
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
run.Finished = account.State == AccountState.Backfilling;
}
}
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
{
await FillGapAsync(run, account, reads, items, tailIsNew: tail == SaveOutcome.Created).ConfigureAwait(false);
return (items, tail == SaveOutcome.Created, false);
}
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
return RecipeStatus.Completed;
var fillGap = CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null);
return (items, tail == SaveOutcome.Created, fillGap);
}
/// <summary>
@@ -313,37 +347,14 @@ public sealed partial class RecipeRunner
private async Task<RecipeStatus> WalkAsync(RecipeRun run, ProfileWalk walk)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
if (!CollectionWriter.Wants(account, walk.Kind))
if (await WalkStartAsync(run, account, walk).ConfigureAwait(false) is not { } start)
{
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}.");
return RecipeStatus.Completed;
}
var (cursor, checkOnly) = start;
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;
}
}
var target = cursor is null ? null : ResumePoint.Parse(cursor, await settings.GetAsync(walk.MarkKey(account.Id), run.Ct).ConfigureAwait(false));
if (!checkOnly)
{
@@ -406,6 +417,18 @@ public sealed partial class RecipeRunner
Store = (next, last) => StoreWalkPointAsync(run, account, walk, next, last),
}).ConfigureAwait(false);
await FinishWalkAsync(run, account, walk, end, checkOnly, caughtUp, catchUpPages).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>
/// The end of a walk of Storico, Taggati or Reel, whatever turned its pages: at the beginning of the profile, or a
/// history limit (not on a check-only walk), the walk is complete and its point cleared; when the stored point was
/// not found again by scrolling, the timeline says so and the point stays.
/// </summary>
private async Task FinishWalkAsync(RecipeRun run, Account account, ProfileWalk walk, WalkEnd end, bool checkOnly, bool caughtUp, int catchUpPages)
{
var settings = Env.Storage.Settings;
if (end == WalkEnd.EndOfList || (end == WalkEnd.Limit && !checkOnly))
{
run.Finished = true;
@@ -438,8 +461,6 @@ public sealed partial class RecipeRunner
run.Session.SessionId,
run.Ct).ConfigureAwait(false);
}
return RecipeStatus.Completed;
}
/// <summary>
@@ -754,7 +775,23 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
var profile = AccountProfile(reads, account)!;
account = await ApplyProfileStateAsync(run, account, AccountProfile(reads, account)!).ConfigureAwait(false);
if (waitForGrid)
{
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
}
return (account, reads);
}
/// <summary>
/// What the profile just read says of the account, whatever brought it (the page or a request): a name now used by
/// another account, private profile not followed (rule 6: not touched; both stop the run as
/// <see cref="RecipeStatus.AccountUnreachable"/>), the facts of the profile, an unreachable account reachable again.
/// Returns the updated account.
/// </summary>
private async Task<Account> ApplyProfileStateAsync(RecipeRun run, Account account, ProfileInfo profile)
{
if (account.InstagramId is { } known && profile.Id != known)
{
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
@@ -776,12 +813,7 @@ public sealed partial class RecipeRunner
account = await Env.Storage.Accounts.GetAsync(account.Id, run.Ct).ConfigureAwait(false) ?? account;
}
if (waitForGrid)
{
reads = await WaitForGridAsync(run, mark, account, reads).ConfigureAwait(false);
}
return (account, reads);
return account;
}
/// <summary>
@@ -0,0 +1,117 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>
/// Post singolo by requests (spec §6.3, §6.5 point 5): one request (one SinglePost) for the post, by its code or its
/// identifier as the operation asks. A «not found» or an answer without the post ends the run as by the page.
/// </summary>
private async Task<RecipeStatus> SinglePostByRequestsAsync(RecipeRun run)
{
var operation = Catalog.ForRole(RequestRole.Post)!;
var (entry, account) = await LoadPostEntryAsync(run, needsCode: operation.RequiredValues.Contains(CaseValues.Code)).ConfigureAwait(false);
var values = AccountValues(account);
Put(values, CaseValues.Code, entry.Code);
Put(values, CaseValues.MediaId, entry.InstagramId);
var reply = await AskAsync(run, operation, values, null, account.Id, RequestGap.None).ConfigureAwait(false);
if (reply.NotFound)
{
throw RecipeRun.Stop(RecipeStatus.Completed, PostNotFoundMessage);
}
bool Matches(ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code);
if (!run.Judge(reply.Reads, r => r.Contents.Any(Matches), operation.PathShape))
{
throw RecipeRun.Stop(RecipeStatus.Completed, PostNotFoundMessage);
}
return await CompletePostAsync(run, entry, account, Contents(reply.Reads, Matches).First()).ConfigureAwait(false);
}
/// <summary>
/// Elenco dei seguiti by requests (spec §4.2, §6.3): the first page, or the page after the stored cursor, then one
/// request per page (one FollowingListPage each) until the end of the list or the pages of the run; the progress is
/// stored as by the page (<see cref="FinishFollowingAsync"/>). The stored point is asked for directly, never found
/// again by reading the list from the top.
/// </summary>
private async Task<RecipeStatus> FollowingListByRequestsAsync(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 = ParseTime(await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false));
var read = (int)(await settings.GetInt64Async(FollowingKeys.Read, run.Ct).ConfigureAwait(false) ?? 0);
var stored = cursor is not null && started is not null ? cursor : null;
var first = Catalog.ForRole(RequestRole.Following)!;
var next = Catalog.ForRole(RequestRole.FollowingNext);
if (stored is null)
{
cursor = null;
read = 0;
started = Env.Clock.Now;
}
else if (next is null)
{
await NextPagesNotConfiguredAsync(run, null).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.Completed, $"Letti {ItalianText.Number(read)} profili: le pagine successive non sono ancora configurate per le richieste.");
}
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
var values = AccountValues(mine);
bool Listed(ReadResult r) => r.Profiles.Any(p => IsListed(p, mine));
var reply = stored is null
? await AskAsync(run, first, values, null, mine.Id, RequestGap.None).ConfigureAwait(false)
: await AskAsync(run, next!, values, stored, mine.Id, RequestGap.None).ConfigureAwait(false);
var pages = 1;
var finished = false;
while (true)
{
if (reply.NotFound || !run.Judge(reply.Reads, Listed, null))
{
if (pages == 1)
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
break;
}
read += await SaveFollowingPageAsync(run, reply.Reads, mine, read).ConfigureAwait(false);
var page = PageOf(reply.Reads, r => r.Profiles.Where(p => IsListed(p, mine)).Select(p => p.Id), r => r.Shape == ReadShape.Empty);
cursor = page?.Cursor ?? cursor;
if (page?.HasMore == false)
{
finished = true;
break;
}
if (pages >= maxPages)
{
break;
}
if (next is null || page?.Cursor is not { } following)
{
if (next is null)
{
await NextPagesNotConfiguredAsync(run, null).ConfigureAwait(false);
}
break;
}
reply = await AskAsync(run, next, values, following, mine.Id, RequestGap.BetweenPages).ConfigureAwait(false);
pages++;
}
return await FinishFollowingAsync(run, finished, read, started!.Value, cursor).ConfigureAwait(false);
}
}
@@ -0,0 +1,396 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>The last time the list of highlight collections of an account was asked by requests.</summary>
private static string HighlightsTrayKey(long accountId) => $"raccolte.vassoio.{accountId.ToString(CultureInfo.InvariantCulture)}";
/// <summary>
/// Controllo del profilo by requests (spec §6.3): the profile (one ProfileOpen), the first page of posts and the
/// list of collections, each asked only when another operation carries it (the test site gives all three in one
/// answer). Then the same as by the page: what the profile says, the first page saved, the gap below it filled by
/// the next pages, when they are configured. The list of collections, when it has an operation of its own, comes
/// last (a stop on it loses nothing already read; a refused permit leaves it for the next check), at most once every
/// <see cref="RecipeOptions.HighlightsTrayInterval"/> and only for an account that wants its collections, always on a
/// manual run. An answer of the posts or of the list that the readers do not know is an unrecognized format.
/// </summary>
private async Task<RecipeStatus> ProfileCheckByRequestsAsync(RecipeRun run)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
var profileOperation = Catalog.ForRole(RequestRole.Profile)!;
var reply = await AskAsync(run, profileOperation, AccountValues(account), null, account.Id, RequestGap.None).ConfigureAwait(false);
if (reply.NotFound)
{
await ProfileNotFoundAsync(run, account).ConfigureAwait(false);
}
var reads = new List<CapturedRead>(reply.Reads);
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, profileOperation.PathShape))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
account = await ApplyProfileStateAsync(run, account, AccountProfile(reads, account)!).ConfigureAwait(false);
var asked = new List<SiteOperation> { profileOperation };
var postsOperation = Catalog.ForRole(RequestRole.Posts)!;
if (!asked.Contains(postsOperation))
{
reply = await AskAsync(run, postsOperation, AccountValues(account), null, account.Id, RequestGap.AfterAnswer).ConfigureAwait(false);
var checkedAccount = account;
JudgeUnknown(run, reply, r => IsWalkPage(r, checkedAccount, ProfileWalk.Posts));
reads.AddRange(reply.Reads);
asked.Add(postsOperation);
}
var highlightsOperation = Catalog.ForRole(RequestRole.Highlights)!;
var highlights = asked.Contains(highlightsOperation);
if (highlights)
{
await HighlightsTrayReadAsync(run, account).ConfigureAwait(false);
}
await RecordCheckedProfileAsync(run, account, AccountProfile(reads, account)!, reads, highlights).ConfigureAwait(false);
var (items, tailIsNew, fillGap) = await SaveFirstGridPageAsync(run, account, reads).ConfigureAwait(false);
if (fillGap)
{
await FillGapByRequestsAsync(run, account, reads, items, tailIsNew).ConfigureAwait(false);
}
if (!highlights && await HighlightsTrayDueAsync(run, account).ConfigureAwait(false))
{
try
{
reply = await AskAsync(run, highlightsOperation, AccountValues(account), null, account.Id, RequestGap.AfterAnswer).ConfigureAwait(false);
}
catch (RecipeStopException stop) when (stop.Status == RecipeStatus.Denied)
{
// No permit, or the session is over: the check itself is done, the list waits for the next one.
return RecipeStatus.Completed;
}
if (!reply.NotFound)
{
JudgeUnknown(run, reply, r => r.Highlights.Count > 0);
await UpsertListedHighlightsAsync(run, account, reply.Reads).ConfigureAwait(false);
await HighlightsTrayReadAsync(run, account).ConfigureAwait(false);
}
}
return RecipeStatus.Completed;
}
/// <summary>
/// An answer whose content the recipe takes as it comes (none may be a fact of the profile): judged only when the
/// readers did not recognize part of it, which stops the run as an unrecognized format.
/// </summary>
private static void JudgeUnknown(RecipeRun run, RequestReply reply, Func<ReadResult, bool> expected)
{
if (!reply.NotFound && reply.Reads.Any(r => r.Result.Shape == ReadShape.Unrecognized))
{
run.Judge(reply.Reads, expected, reply.Operation.PathShape);
}
}
private Task HighlightsTrayReadAsync(RecipeRun run, Account account) =>
Env.Storage.Settings.SetAsync(HighlightsTrayKey(account.Id), Env.Clock.Now.ToString("O", CultureInfo.InvariantCulture), run.Ct);
/// <summary>
/// Whether the list of collections is to be asked this time: only for an account that wants its collections, then
/// never asked, older than the interval, or a manual run.
/// </summary>
private async Task<bool> HighlightsTrayDueAsync(RecipeRun run, Account account)
{
if (!CollectionWriter.Wants(account, EntryKind.Highlight))
{
return false;
}
if (run.Request.Manual)
{
return true;
}
var last = ParseTime(await Env.Storage.Settings.GetAsync(HighlightsTrayKey(account.Id), run.Ct).ConfigureAwait(false));
return last is not { } at || Env.Clock.Now - at >= Env.Options.HighlightsTrayInterval;
}
/// <summary>The site said the profile is not there (a 404 with JSON): the account is unreachable, as by the page.</summary>
private async Task ProfileNotFoundAsync(RecipeRun run, Account account)
{
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
}
/// <summary>
/// The gap below the first page of a check, by requests (<see cref="FillGapAsync"/>): from the cursor of the first
/// page when its last post was new, otherwise from the stored point; at most
/// <see cref="RecipeOptions.GapPagesPerCheck"/> pages, until known posts. Without a request for the next pages the
/// point is stored and the timeline says so. A refused permit, the end of the session or too many files waiting for
/// download leave the gap for later.
/// </summary>
private async Task FillGapByRequestsAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads, IReadOnlyList<ContentItem> firstPage, bool tailIsNew)
{
var walk = ProfileWalk.Gap;
var settings = Env.Storage.Settings;
var keys = new[] { walk.CursorKey(account.Id), walk.MarkKey(account.Id), walk.KnownBeforeKey(account.Id) };
var storedCursor = await settings.GetAsync(keys[0], run.Ct).ConfigureAwait(false);
var stored = storedCursor is null ? null : ResumePoint.Parse(storedCursor, await settings.GetAsync(keys[1], run.Ct).ConfigureAwait(false));
var before = ParseTime(await settings.GetAsync(keys[2], run.Ct).ConfigureAwait(false));
async Task ClearAsync() => await settings.SetManyAsync(keys.ToDictionary(k => k, _ => (string?)null), run.Ct).ConfigureAwait(false);
var first = WalkPage(reads, account, walk, ownAnswer: false);
if (first?.HasMore == false)
{
if (stored is not null || before is not null)
{
await ClearAsync().ConfigureAwait(false);
}
return;
}
var floor = Earliest(before, stored?.LastAt);
Task StoreAsync(string cursor, ContentItem? last) => settings.SetManyAsync(
new Dictionary<string, string?>
{
[keys[0]] = cursor,
[keys[1]] = ResumePoint.MarkOf(last),
[keys[2]] = floor?.ToString("O", CultureInfo.InvariantCulture),
},
run.Ct);
string? cursor;
if (tailIsNew)
{
cursor = first?.Cursor;
if (cursor is not null)
{
await StoreAsync(cursor, firstPage.LastOrDefault()).ConfigureAwait(false);
}
}
else
{
cursor = stored?.Cursor;
}
if (cursor is null)
{
return;
}
var next = Catalog.ForRole(RequestRole.PostsNext);
if (next is null)
{
await NextPagesNotConfiguredAsync(run, account.Id).ConfigureAwait(false);
return;
}
try
{
var end = await WalkRequestPagesAsync(run, account, walk, next, cursor, new WalkRules
{
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
CheckDownloads = true,
AnnounceSuspension = false,
Processed = new HashSet<string>(firstPage.Select(i => i.Id), StringComparer.Ordinal),
Store = StoreAsync,
}).ConfigureAwait(false);
if (end is WalkEnd.EndOfList or WalkEnd.Limit or WalkEnd.Known)
{
await ClearAsync().ConfigureAwait(false);
}
}
catch (RecipeStopException stop) when (stop.Status == RecipeStatus.Denied)
{
// No permit, the session is over, or too many files wait for download: the gap waits for the next check.
}
}
/// <summary>
/// Storico, Taggati and Reel by requests (spec §6.3): the same stored point, rules and end as by the page
/// (<see cref="WalkAsync"/>), but the point is never looked for by scrolling: the cursor is asked for directly. The
/// first page of the grid comes with the profile (one ProfileOpen, not counted among the pages of the run, as by the
/// page); the first page of a tab is counted. Without a request for the next pages the stored point stays.
/// </summary>
private async Task<RecipeStatus> WalkByRequestsAsync(RecipeRun run, ProfileWalk walk, RequestRole firstRole, RequestRole nextRole)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
if (await WalkStartAsync(run, account, walk).ConfigureAwait(false) is not { } start)
{
return RecipeStatus.Completed;
}
var (cursor, checkOnly) = start;
if (!checkOnly)
{
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
}
var next = Catalog.ForRole(nextRole);
var rules = new WalkRules
{
MaxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun),
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
CheckDownloads = !checkOnly,
Store = (point, last) => StoreWalkPointAsync(run, account, walk, point, last),
};
WalkEnd end;
if (cursor is not null && next is not null)
{
end = await WalkRequestPagesAsync(run, account, walk, next, cursor, rules).ConfigureAwait(false);
}
else
{
if (cursor is not null)
{
// A stored point and no request for the page after it (nor pages that could go on from it): the walk
// waits there, and the first page is read for what is new on top. The point stays as it is.
checkOnly = true;
rules = rules with { MaxPages = 1, Stop = KnownStop.Any, Store = (_, _) => Task.CompletedTask };
}
var firstOperation = Catalog.ForRole(firstRole)!;
var reply = await AskAsync(run, firstOperation, AccountValues(account), null, account.Id, RequestGap.None).ConfigureAwait(false);
if (reply.NotFound)
{
await ProfileNotFoundAsync(run, account).ConfigureAwait(false);
}
if (AccountProfile(reply.Reads, account) is { } profile)
{
account = await ApplyProfileStateAsync(run, account, profile).ConfigureAwait(false);
}
if (!run.Judge(reply.Reads, r => IsWalkPage(r, account, walk), firstOperation.PathShape))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
end = await WalkRequestPagesAsync(run, account, walk, next, reply.Reads, rules with { PagesRead = walk.IsGrid ? 0 : 1 }).ConfigureAwait(false);
}
if (next is null && (end == WalkEnd.NoNext || (cursor is not null && end != WalkEnd.EndOfList)))
{
await NextPagesNotConfiguredAsync(run, account.Id).ConfigureAwait(false);
}
await FinishWalkAsync(run, account, walk, end, checkOnly, caughtUp: true, catchUpPages: 0).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>The pages of a walk by requests from a stored cursor: the first request is for the page after it.</summary>
private Task<WalkEnd> WalkRequestPagesAsync(RecipeRun run, Account account, ProfileWalk walk, SiteOperation next, string cursor, WalkRules rules) =>
WalkRequestPagesAsync(run, account, walk, next, null, rules, cursor);
/// <summary>
/// The pages of a walk by requests, from a page in hand (<paramref name="reads"/>) or from <paramref name="cursor"/>:
/// each page saved, then the end of the profile, a history limit, known content (when the rules say so), the pages
/// of the run, or a page that cannot be asked (<see cref="WalkEnd.NoNext"/>); otherwise its point stored and the next
/// page asked with its cursor, one permit each (<see cref="SiteOperation.CategoryFor"/>). A «not found» or an empty
/// answer ends the walk as an empty page (<see cref="WalkEnd.NoData"/>).
/// </summary>
private async Task<WalkEnd> WalkRequestPagesAsync(RecipeRun run, Account account, ProfileWalk walk, SiteOperation? next, IReadOnlyList<CapturedRead>? reads, WalkRules rules, string? cursor = null)
{
var pages = rules.PagesRead;
IReadOnlySet<string>? seen = null; // a first page in hand: only what its own answer brings
while (true)
{
if (reads is null)
{
if (next is null || cursor is null)
{
return WalkEnd.NoNext;
}
if (rules.CheckDownloads)
{
await EnsureBackfillAllowedAsync(run, account, rules.AnnounceSuspension).ConfigureAwait(false);
}
var reply = await AskAsync(run, next, AccountValues(account), cursor, account.Id, RequestGap.BetweenPages).ConfigureAwait(false);
pages++;
if (reply.NotFound || !run.Judge(reply.Reads, r => IsWalkPage(r, account, walk), null))
{
return WalkEnd.NoData;
}
reads = reply.Reads;
seen = rules.Processed;
}
var items = PageItems(reads, account, walk);
var page = WalkPage(reads, account, walk, ownAnswer: true, seen);
var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, items, rules.Processed, rules.Stop).ConfigureAwait(false);
if (reachedLimit)
{
return WalkEnd.Limit;
}
if (page?.HasMore == false)
{
return WalkEnd.EndOfList;
}
if (reachedKnown)
{
return WalkEnd.Known;
}
if (page?.Cursor is not { } following)
{
return WalkEnd.NoNext;
}
await rules.Store(following, items.LastOrDefault()).ConfigureAwait(false);
if (pages >= rules.MaxPages)
{
return WalkEnd.Pages;
}
cursor = following;
reads = null;
}
}
/// <summary>
/// Where a walk of Storico, Taggati or Reel starts, whatever turns its pages: the stored cursor and whether the walk
/// only checks the first page (the tab was walked to the end). Null when there is nothing to do: the history of the
/// grid is complete. Stops the run when the account does not want the content of the walk.
/// </summary>
private async Task<(string? Cursor, bool CheckOnly)?> WalkStartAsync(RecipeRun run, Account account, ProfileWalk walk)
{
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}.");
}
if (walk.IsGrid)
{
if (account.BackfillCompletedAt is not null)
{
run.Finished = true;
return null;
}
return (account.BackfillCursor, false);
}
var settings = Env.Storage.Settings;
var checkOnly = await settings.GetAsync(walk.CompletedKey(account.Id), run.Ct).ConfigureAwait(false) is not null;
var cursor = checkOnly ? null : await settings.GetAsync(walk.CursorKey(account.Id), run.Ct).ConfigureAwait(false);
return (cursor, checkOnly);
}
}
@@ -0,0 +1,203 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Pacing;
namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>
/// Storie di un account by requests (spec §6.3): one request (one StoryView) gives the active stories of the
/// account, all saved; no viewer, so no minimum of stories left in the budget. No story is a quiet day, not an
/// empty page: only an answer the readers do not recognize is judged, and a recognized one counts as data. A «not
/// found» is not a quiet day yet: the account may be gone, or private and no longer followed (rule 6), which the
/// browser learns by opening the profile first. So the profile is asked (one ProfileOpen), as by the page, and says
/// which; without a profile operation the «not found» counts as an empty page.
/// </summary>
private async Task<RecipeStatus> AccountStoriesByRequestsAsync(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}.");
}
// No wait before the one request, not even after the stories of another account: the Governor keeps the
// distance from the previous action (§6.3, §7.7).
var operation = Catalog.ForRole(RequestRole.Stories)!;
var profileOperation = Catalog.ForRole(RequestRole.Profile);
var reply = await AskAsync(run, operation, AccountValues(account), null, account.Id, RequestGap.None, notFoundIsEmpty: profileOperation is null).ConfigureAwait(false);
if (reply.NotFound)
{
if (profileOperation is not null)
{
await StoriesNotFoundAsync(run, account, profileOperation).ConfigureAwait(false);
}
}
else
{
bool IsStory(ContentItem c) => IsOwnedBy(c, account) && c.ExpiresAt is not null && c.HighlightId is null;
if (reply.Reads.Any(r => r.Result.Shape == ReadShape.Unrecognized))
{
run.Judge(reply.Reads, r => r.Contents.Any(IsStory), null);
}
else if (reply.Reads.Any(r => r.Result.Shape == ReadShape.Recognized))
{
run.SawData();
}
foreach (var story in Contents(reply.Reads, IsStory))
{
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.Ct).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>
/// The stories of an account were «not found»: the profile says why. Gone: unreachable (a «not found» of the
/// profile, counted as an empty page). Private and not followed: unreachable, never touched again (rule 6). Otherwise
/// a day without stories. Each case as by the page (<see cref="ApplyProfileStateAsync"/>).
/// </summary>
private async Task StoriesNotFoundAsync(RecipeRun run, Account account, SiteOperation profileOperation)
{
var reply = await AskAsync(run, profileOperation, AccountValues(account), null, account.Id, RequestGap.AfterAnswer).ConfigureAwait(false);
if (reply.NotFound)
{
await ProfileNotFoundAsync(run, account).ConfigureAwait(false);
}
if (!run.Judge(reply.Reads, r => ProfileIn(r, account) is not null, profileOperation.PathShape))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
await ApplyProfileStateAsync(run, account, AccountProfile(reply.Reads, account)!).ConfigureAwait(false);
}
/// <summary>
/// Raccolta in evidenza by requests (spec §6.3): the collection must be known already (the profile check lists the
/// collections); one request (one StoryView) per page of its contents, each content linked to its entry (a story
/// already saved is referenced, not downloaded again, H9). The order of the collection is stored only when all its
/// pages were read.
/// </summary>
private async Task<RecipeStatus> HighlightByRequestsAsync(RecipeRun run)
{
var account = await LoadAccountAsync(run).ConfigureAwait(false);
if (run.Request.HighlightId is not { Length: > 0 } requested)
{
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}.");
}
var highlightId = ShapeReader.HighlightId(requested);
var highlight = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false)
?? (requested == highlightId ? null : await Env.Storage.Highlights.FindAsync(account.Id, requested, run.Ct).ConfigureAwait(false))
?? throw RecipeRun.Stop(RecipeStatus.Completed, "La raccolta non è ancora nota: la legge il prossimo controllo del profilo.");
var values = AccountValues(account);
Put(values, CaseValues.HighlightId, highlight.InstagramId);
var operation = Catalog.ForRole(RequestRole.Highlight)!;
if (operation.RequiredValues.Contains(CaseValues.HighlightId) && !values.ContainsKey(CaseValues.HighlightId))
{
throw RecipeRun.Stop(RecipeStatus.Completed, $"Per la raccolta «{highlight.Title}» di {account.Username} manca {ValueName(CaseValues.HighlightId)}; si riprova al prossimo giro.");
}
bool Inside(ContentItem c) => InCollection(c, highlightId);
bool Expected(ReadResult r) => r.Contents.Any(Inside) || r.Highlights.Any(h => h.Id == highlightId);
var reply = await AskAsync(run, operation, values, null, account.Id, RequestGap.None).ConfigureAwait(false);
if (reply.NotFound)
{
throw RecipeRun.Stop(RecipeStatus.Completed, $"La raccolta «{highlight.Title}» non è più nel profilo: i suoi file restano.");
}
if (!run.Judge(reply.Reads, Expected, operation.PathShape))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
// Each page is linked as soon as it is read: a stop on a later page (a refused permit, a signal, an error) keeps
// what was already read and paid for, as the viewer keeps what it showed.
var items = Contents(reply.Reads, Inside);
var seen = new HashSet<string>(items.Select(i => i.Id), StringComparer.Ordinal);
var ordered = new List<long>();
var linkedAll = await LinkHighlightPageAsync(run, account, highlight, items, ordered).ConfigureAwait(false);
var page = PageOf(reply.Reads, r => r.Contents.Where(Inside).Select(c => c.Id), r => r.Shape == ReadShape.Empty);
var next = Catalog.ForRole(RequestRole.HighlightNext);
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.PagesPerRun);
var pages = 1;
while (page is { HasMore: true, Cursor: { } cursor } && next is not null && pages < maxPages)
{
reply = await AskAsync(run, next, values, cursor, account.Id, RequestGap.BetweenPages).ConfigureAwait(false);
pages++;
if (reply.NotFound || !run.Judge(reply.Reads, Expected, null))
{
break; // an empty page: the order of the collection is not stored this time
}
var more = Contents(reply.Reads, c => Inside(c) && !seen.Contains(c.Id));
page = PageOf(reply.Reads, r => r.Contents.Where(Inside).Select(c => c.Id), r => r.Shape == ReadShape.Empty, seen);
items.AddRange(more);
seen.UnionWith(more.Select(i => i.Id));
linkedAll &= await LinkHighlightPageAsync(run, account, highlight, more, ordered).ConfigureAwait(false);
if (more.Count == 0)
{
break;
}
}
// Read to the end only when the last page says so: a cap of the run, an empty page or a page with nothing new
// leave the order of the collection as it was (rule 11), only links added.
var complete = page?.HasMore != true;
if (!complete && next is null)
{
await NextPagesNotConfiguredAsync(run, account.Id, pointKept: false).ConfigureAwait(false);
}
if (complete && items.Count > 0 && linkedAll)
{
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);
return RecipeStatus.Completed;
}
/// <summary>Links the contents of one page of a collection to their entries; true when every one has its entry.</summary>
private async Task<bool> LinkHighlightPageAsync(RecipeRun run, Account account, Highlight highlight, IReadOnlyList<ContentItem> items, List<long> ordered)
{
var all = true;
foreach (var item in items)
{
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);
}
else
{
all = false;
}
}
return all;
}
}
@@ -0,0 +1,290 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>
/// The roles a recipe needs to go by requests (issue #36, S3), and the role that goes on to the next page when there
/// is one. The Giro dei seguiti never goes by requests in S3: its operations have no samples.
/// </summary>
public static (IReadOnlyList<RequestRole> Required, RequestRole? Next) RequestNeeds(RecipeKind kind) => kind switch
{
RecipeKind.ProfileCheck => ([RequestRole.Profile, RequestRole.Posts, RequestRole.Highlights], RequestRole.PostsNext),
RecipeKind.Backfill => ([RequestRole.Posts, RequestRole.PostsNext], null),
RecipeKind.Tagged => ([RequestRole.Tagged], RequestRole.TaggedNext),
RecipeKind.Reels => ([RequestRole.Reels], RequestRole.ReelsNext),
RecipeKind.AccountStories => ([RequestRole.Stories], null),
RecipeKind.Highlight => ([RequestRole.Highlight], RequestRole.HighlightNext),
RecipeKind.SinglePost => ([RequestRole.Post], null),
RecipeKind.FollowingList => ([RequestRole.Following], RequestRole.FollowingNext),
_ => ([], null),
};
/// <summary>
/// The operations of <paramref name="catalog"/> that let <paramref name="kind"/> go by requests, in the order of its
/// roles and without repetitions; null when a role it needs is missing or not configured.
/// </summary>
public static IReadOnlyList<SiteOperation>? RequestOperations(RequestCatalog catalog, RecipeKind kind)
{
ArgumentNullException.ThrowIfNull(catalog);
var (required, next) = RequestNeeds(kind);
if (required.Count == 0)
{
return null;
}
var operations = new List<SiteOperation>();
foreach (var role in required)
{
if (catalog.ForRole(role) is not { } operation)
{
return null;
}
if (!operations.Contains(operation))
{
operations.Add(operation);
}
}
if (next is { } more && catalog.ForRole(more) is { } continuation && !operations.Contains(continuation))
{
operations.Add(continuation);
}
return operations;
}
/// <summary>
/// True when <paramref name="kind"/> goes by requests: the site client is there and every role the recipe needs is
/// a configured operation of its catalog. On Instagram nothing is configured yet: always false.
/// </summary>
public bool HasRequestRoute(RecipeKind kind) =>
Env.Requests is { } requests && kind != RecipeKind.FollowingSweep && RequestOperations(requests.Catalog, kind) is not null;
/// <summary>
/// The budget category of the first action of <paramref name="kind"/> on its route: by requests, the category of
/// the operation of its first role (Taggati and Reel start with a page of the tab, BackfillPage, not with the
/// profile); by the pages, and for the Storico (whose first page counts as the profile without a stored point and
/// as a page with one, the same on both routes), <see cref="CheckPolicy.CategoryOf"/>.
/// </summary>
public ActionKind FirstCategory(RecipeKind kind) =>
kind != RecipeKind.Backfill && HasRequestRoute(kind) && Catalog.ForRole(RequestNeeds(kind).Required[0]) is { } first
? first.Category
: CheckPolicy.CategoryOf(kind);
private RequestCatalog Catalog => Env.Requests!.Catalog;
/// <summary>
/// Whether this run can go by requests: every value its first requests need is known (the identifier of the
/// account, the code of the post…). When one is missing the run goes by the pages, if they can run, with an Info
/// line; otherwise it ends <see cref="RecipeStatus.Completed"/> with an Info line and is tried again at the next round
/// (never <see cref="RecipeStatus.NotConfigured"/>: the engine would not plan it again in this process). A missing
/// saved session is not a missing value: it is a disconnection (rule 7), never a way back to the pages.
/// </summary>
private async Task<bool> ChooseRequestRouteAsync(RecipeRun run)
{
var (missing, who) = await MissingRequestValueAsync(run).ConfigureAwait(false);
if (missing is null)
{
if (Refusal(run.Request.Kind) is null && await NextPagesNeededAsync(run).ConfigureAwait(false))
{
// A stored point whose next page has no request: the pages can go on from it, the requests cannot.
await Writer.EventAsync("richieste-pagine-successive", $"Le pagine successive di «{Name(run.Request.Kind)}» non sono ancora configurate per le richieste: questa volta si passa dalle pagine.", EventSeverity.Info, run.Request.AccountId, run.Session.SessionId, run.Ct).ConfigureAwait(false);
return false;
}
return true;
}
if (Refusal(run.Request.Kind) is null)
{
await Writer.EventAsync("richieste-valore-mancante", $"«{Name(run.Request.Kind)}»{(who is null ? string.Empty : $" di {who}")}: manca {missing}, questa volta si passa dalle pagine.", EventSeverity.Info, run.Request.AccountId, run.Session.SessionId, run.Ct).ConfigureAwait(false);
return false;
}
var message = $"Per {who ?? $"«{Name(run.Request.Kind)}»"} manca {missing}; si riprova al prossimo giro.";
await Writer.EventAsync("richieste-valore-mancante", message, EventSeverity.Info, run.Request.AccountId, run.Session.SessionId, run.Ct).ConfigureAwait(false);
throw RecipeRun.Stop(RecipeStatus.Completed, message);
}
/// <summary>
/// Whether the run would start from a stored point (Taggati, Reel, Elenco dei seguiti) whose next page has no
/// configured request: by requests it could not go on.
/// </summary>
private async Task<bool> NextPagesNeededAsync(RecipeRun run)
{
var kind = run.Request.Kind;
if (RequestNeeds(kind).Next is not { } nextRole || Catalog.ForRole(nextRole) is not null)
{
return false;
}
var settings = Env.Storage.Settings;
switch (kind)
{
case RecipeKind.Tagged or RecipeKind.Reels when run.Request.AccountId is { } id:
var walk = kind == RecipeKind.Tagged ? ProfileWalk.Tagged : ProfileWalk.Reels;
return await settings.GetAsync(walk.CompletedKey(id), run.Ct).ConfigureAwait(false) is null
&& await settings.GetAsync(walk.CursorKey(id), run.Ct).ConfigureAwait(false) is not null;
case RecipeKind.FollowingList:
return await settings.GetAsync(FollowingKeys.Cursor, run.Ct).ConfigureAwait(false) is not null
&& await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false) is not null;
default:
return false;
}
}
/// <summary>
/// The first value of the case the first requests of the run need and do not have, in Italian, with the user name
/// it is missing for; (null, null) when nothing is missing, or when what is missing is the run's own data (no account,
/// no entry), which the recipe reports itself.
/// </summary>
private async Task<(string? Missing, string? Who)> MissingRequestValueAsync(RecipeRun run)
{
Dictionary<string, string> available;
string? who;
var request = run.Request;
switch (request.Kind)
{
case RecipeKind.SinglePost:
{
var entry = request.EntryId is { } entryId ? await Env.Storage.Entries.GetAsync(entryId, run.Ct).ConfigureAwait(false) : null;
var account = entry is null ? null : await Env.Storage.Accounts.GetAsync(entry.AccountId, run.Ct).ConfigureAwait(false);
if (entry is null || account is null)
{
return (null, null);
}
available = AccountValues(account);
Put(available, CaseValues.Code, entry.Code);
Put(available, CaseValues.MediaId, entry.InstagramId);
who = account.Username;
break;
}
case RecipeKind.FollowingList:
{
var mine = await Env.Storage.Accounts.GetMineAsync(run.Ct).ConfigureAwait(false);
available = mine is null ? new Dictionary<string, string>(StringComparer.Ordinal) : AccountValues(mine);
who = null;
break;
}
default:
{
var account = request.AccountId is { } id ? await Env.Storage.Accounts.GetAsync(id, run.Ct).ConfigureAwait(false) : null;
if (account is null)
{
return (null, null);
}
available = AccountValues(account);
who = account.Username;
break;
}
}
foreach (var role in RequestNeeds(request.Kind).Required)
{
var operation = Catalog.ForRole(role)!;
// The collection of a Raccolta in evidenza is looked up by the recipe: unknown, it ends without a request.
foreach (var name in operation.RequiredValues.Where(v => v is not (CaseValues.Cursor or CaseValues.HighlightId)))
{
if (!available.ContainsKey(name))
{
return (ValueName(name), who);
}
}
}
return (null, null);
}
/// <summary>The values of the case an account gives: its user name and, once known, its identifier.</summary>
private static Dictionary<string, string> AccountValues(Account account)
{
var values = new Dictionary<string, string>(StringComparer.Ordinal);
Put(values, CaseValues.Username, account.Username);
Put(values, CaseValues.AccountId, account.InstagramId);
return values;
}
/// <summary>Adds a value only when it has the form of its name (<see cref="CaseValues.HasForm"/>): one without is missing.</summary>
private static void Put(Dictionary<string, string> values, string name, string? value)
{
if (!string.IsNullOrEmpty(value) && CaseValues.HasForm(name, value))
{
values[name] = value;
}
}
private static string ValueName(string name) => name switch
{
CaseValues.AccountId => "l'identificativo dell'account",
CaseValues.Username => "il nome utente",
CaseValues.Code => "il codice del post",
CaseValues.MediaId => "l'identificativo del post",
CaseValues.HighlightId => "l'identificativo della raccolta",
_ => $"il valore «{name}»",
};
/// <summary>The recipe by requests (spec §6.3, column «Per richieste»): the page is never touched.</summary>
private Task<RecipeStatus> RunByRequestsAsync(RecipeRun run) => run.Request.Kind switch
{
RecipeKind.ProfileCheck => ProfileCheckByRequestsAsync(run),
RecipeKind.Backfill => WalkByRequestsAsync(run, ProfileWalk.Posts, RequestRole.Posts, RequestRole.PostsNext),
RecipeKind.Tagged => WalkByRequestsAsync(run, ProfileWalk.Tagged, RequestRole.Tagged, RequestRole.TaggedNext),
RecipeKind.Reels => WalkByRequestsAsync(run, ProfileWalk.Reels, RequestRole.Reels, RequestRole.ReelsNext),
RecipeKind.AccountStories => AccountStoriesByRequestsAsync(run),
RecipeKind.Highlight => HighlightByRequestsAsync(run),
RecipeKind.SinglePost => SinglePostByRequestsAsync(run),
RecipeKind.FollowingList => FollowingListByRequestsAsync(run),
_ => throw RecipeRun.Stop(RecipeStatus.Failed, $"«{Name(run.Request.Kind)}» non va per richieste."),
};
/// <summary>
/// One request of <paramref name="operation"/> with the values it takes from <paramref name="available"/>, and
/// <paramref name="cursor"/> when it takes one (<see cref="RecipeRun.AskAsync"/>).
/// </summary>
private static Task<RequestReply> AskAsync(RecipeRun run, SiteOperation operation, IReadOnlyDictionary<string, string> available, string? cursor, long? accountId, RequestGap gap, bool notFoundIsEmpty = true)
{
var values = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var name in operation.RequiredValues.Concat(operation.OptionalValues))
{
if (name == CaseValues.Cursor)
{
if (cursor is not null)
{
values[name] = cursor;
}
}
else if (available.TryGetValue(name, out var value))
{
values[name] = value;
}
}
return run.AskAsync(operation, new SiteRequest(operation.Name, values), accountId, gap, notFoundIsEmpty);
}
/// <summary>
/// The pages after the one in hand cannot be asked: the role that goes on is not configured. Said once per run; the
/// stored point stays (S4: configure the next pages before switching a recipe to requests). A Raccolta in evidenza
/// keeps no point (<paramref name="pointKept"/> false): it starts again from its first page next time.
/// </summary>
private Task NextPagesNotConfiguredAsync(RecipeRun run, long? accountId, bool pointKept = true) =>
Writer.EventAsync(
"richieste-pagine-successive",
$"Le pagine successive di «{Name(run.Request.Kind)}» non sono ancora configurate per le richieste: {(pointKept ? "il punto resta salvato." : "la prossima volta si ricomincia dalla prima pagina.")}",
EventSeverity.Info,
accountId,
run.Session.SessionId,
run.Ct);
}
@@ -50,6 +50,12 @@ public sealed record RecipeEnvironment
/// action that opens a page, when the search waits. Null: no search, no turn points.
/// </summary>
public PageTurns? PageTurns { get; init; }
/// <summary>
/// The site client and its catalog (issue #36, S3): a recipe whose roles are all configured reads the site by
/// requests, never touching the page. Null: every recipe goes by the browser (production until S4).
/// </summary>
public SiteRequestEnvironment? Requests { get; init; }
}
/// <summary>
@@ -68,14 +74,23 @@ public sealed partial class RecipeRunner : IRecipeRunner
private readonly Lock _refusalsGate = new();
private readonly HashSet<RecipeKind> _refusalsReported = [];
private long? _sessionId;
private long? _kindSessionId;
private RecipeKind? _lastKind;
private long _requests;
public RecipeRunner(RecipeEnvironment environment)
{
Env = environment ?? throw new ArgumentNullException(nameof(environment));
Writer = new CollectionWriter(environment.Storage, environment.Clock) { Diagnostics = environment.Diagnostics };
Delivery = new ResponseDelivery("Client del sito", environment.Requests?.Warn is { } warn ? (message, _) => warn(message) : null);
}
/// <summary>Hands the answers of the site client to the readers, as the response tap does for the page.</summary>
internal ResponseDelivery Delivery { get; }
/// <summary>The number of the next request of the site client (its identifier for the readers and the diagnostics).</summary>
internal long NextRequestNumber() => Interlocked.Increment(ref _requests);
public RecipeEnvironment Env { get; }
public CollectionWriter Writer { get; }
@@ -130,8 +145,8 @@ public sealed partial class RecipeRunner : IRecipeRunner
// A map or a vocabulary that lacks what the recipe needs is a state of the configuration, not a failure of the
// recipe: nothing is done, nothing counts towards suspension, and it is said once per recipe and process (the
// engine stops planning it, NotConfiguredReason).
if (Refusal(request.Kind) is { } refusal)
// engine stops planning it, NotConfiguredReason). A recipe that can go by requests needs only the vocabulary.
if (BlockingRefusal(request.Kind) is { } refusal)
{
bool first;
lock (_refusalsGate)
@@ -154,33 +169,32 @@ public sealed partial class RecipeRunner : IRecipeRunner
return new RecipeOutcome(RecipeStatus.Denied, 0, 0, "L'interruttore è aperto: nessuna azione verso il sito.");
}
if (_sessionId != session.SessionId)
if (_kindSessionId != session.SessionId)
{
Env.Driver.BeginSession(session.Mood);
_sessionId = session.SessionId;
_kindSessionId = session.SessionId;
_lastKind = null;
}
// By requests the page is never touched: no gesture session, no cookie check of the browser (rule 7).
var byRequests = HasRequestRoute(request.Kind);
if (!byRequests)
{
BeginPageSession(session);
}
using var run = new RecipeRun(this, request, session, ct);
RecipeStatus status;
string? text = null;
string? errorType = null;
try
{
await CheckSessionCookieAsync(run).ConfigureAwait(false);
status = request.Kind switch
if (byRequests && !await ChooseRequestRouteAsync(run).ConfigureAwait(false))
{
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}."),
};
byRequests = false;
BeginPageSession(session);
}
status = byRequests ? await RunByRequestsAsync(run).ConfigureAwait(false) : await RunByPagesAsync(run).ConfigureAwait(false);
}
catch (RecipeStopException stop)
{
@@ -206,6 +220,44 @@ public sealed partial class RecipeRunner : IRecipeRunner
errorType = ex.GetType().Name;
}
return await EndAsync(run, status, text, errorType).ConfigureAwait(false);
}
/// <summary>A new engine session for the page: the driver draws its mood once per session.</summary>
private void BeginPageSession(ISessionContext session)
{
if (_sessionId != session.SessionId)
{
Env.Driver.BeginSession(session.Mood);
_sessionId = session.SessionId;
}
}
/// <summary>The recipe by the browser: the session cookie of the page first, then the gestures (spec §6.3).</summary>
private async Task<RecipeStatus> RunByPagesAsync(RecipeRun run)
{
var request = run.Request;
await CheckSessionCookieAsync(run).ConfigureAwait(false);
return 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}."),
};
}
/// <summary>How a run ended, whatever route it took: the signal, the timeline, the diagnostics, the outcome.</summary>
private async Task<RecipeOutcome> EndAsync(RecipeRun run, RecipeStatus status, string? text, string? errorType)
{
var request = run.Request;
var session = run.Session;
if (run.Signal is { } signal && status is not (RecipeStatus.StoppedBySignal or RecipeStatus.Cancelled))
{
status = RecipeStatus.StoppedBySignal;
@@ -242,11 +294,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
}
/// <inheritdoc/>
public string? NotConfiguredReason(RecipeKind kind) => Refusal(kind)?.Message;
public string? NotConfiguredReason(RecipeKind kind) => BlockingRefusal(kind)?.Message;
/// <summary>
/// Why the site's configuration does not let <paramref name="kind"/> run, with the code of its timeline line: pages
/// or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when it can run.
/// What keeps <paramref name="kind"/> from running at all: with a request route (<see cref="HasRequestRoute"/>) only
/// a reader vocabulary that cannot be relied on, otherwise everything <see cref="Refusal"/> says.
/// </summary>
private (string Code, string Message)? BlockingRefusal(RecipeKind kind) =>
HasRequestRoute(kind) ? VocabularyRefusal(kind) : Refusal(kind);
/// <summary>
/// Why the site's configuration does not let <paramref name="kind"/> run by the browser, with the code of its
/// timeline line: pages or targets missing from the map, or a reader vocabulary that cannot be relied on. Null when
/// it can run.
/// </summary>
private (string Code, string Message)? Refusal(RecipeKind kind)
{
@@ -258,11 +318,15 @@ public sealed partial class RecipeRunner : IRecipeRunner
return ("mappa-incompleta", $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}).");
}
return Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
? ("lettori-incompleti", $"«{name}» non può girare: {unusable}")
: null;
return VocabularyRefusal(kind);
}
/// <summary>A reader vocabulary that cannot be relied on: no route can read the site with it.</summary>
private (string Code, string Message)? VocabularyRefusal(RecipeKind kind) =>
Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable
? ("lettori-incompleti", $"«{Name(kind)}» non può girare: {unusable}")
: null;
/// <summary>
/// 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.
@@ -0,0 +1,22 @@
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
namespace Febe.Core.Collection.Recipes;
/// <summary>
/// What the recipes need to read the site by requests instead of pages (issue #36, S3): the site client, the catalog
/// with the roles of its operations, the reading of the stop signals in its answers, and the pace of the waits. Set in
/// <see cref="RecipeEnvironment.Requests"/> only where a request route is wanted: until S4 only the tests set it, and in
/// production every recipe goes by the browser.
/// </summary>
/// <param name="Requester">The site client (HTTP, or the test double): one request at a time, each with its permit.</param>
/// <param name="Catalog">The operations of <c>richieste.&lt;sito&gt;.json</c> and their roles.</param>
/// <param name="AnswerSignals">The stop signals of §7.6 read from the answers.</param>
/// <param name="Pace">The «Ritmo dei gesti»: multiplies the waits between requests like the waits of the gestures.</param>
/// <param name="Warn">Receives Italian warnings (names and shapes only, never values); null discards them.</param>
public sealed record SiteRequestEnvironment(
ISiteRequester Requester,
RequestCatalog Catalog,
SiteAnswerSignals AnswerSignals,
GesturePace Pace = GesturePace.Natural,
Action<string>? Warn = null);
@@ -111,9 +111,11 @@ public static class SiteRequestGuard
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: intestazioni o campi senza una fonte stabilita.");
}
if (permit.Kind != operation.Category)
// The first page of a «storico» operation with «firstPageCategory» counts as the profile open (S3).
var category = operation.CategoryFor(request);
if (permit.Kind != category)
{
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è per {permit.Kind}, l'operazione conta come {operation.Category}.");
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: il permesso è per {permit.Kind}, la richiesta conta come {category}.");
}
if (operation.CheckValues(request) is { } problem)
@@ -69,6 +69,90 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
};
}
/// <summary>
/// The part an operation plays in the recipes (issue #36, S3): the recipes ask for a role, never for an operation by
/// name, because each site names its operations its own way. Written in <c>richieste.&lt;sito&gt;.json</c> as
/// <c>"roles": [ ... ]</c> with the spellings of <see cref="RequestRoles"/>. A role belongs to one operation at most; a
/// role on an operation that is not configured is not available (<see cref="RequestCatalog.ForRole"/>).
/// </summary>
public enum RequestRole
{
/// <summary>The profile of an account (<c>profile</c>).</summary>
Profile,
/// <summary>The first page of the posts of a profile (<c>posts</c>).</summary>
Posts,
/// <summary>A later page of the posts, from a cursor (<c>posts-next</c>).</summary>
PostsNext,
/// <summary>The tray of the highlight collections of a profile (<c>highlights</c>).</summary>
Highlights,
/// <summary>The first page of the posts an account is tagged in (<c>tagged</c>).</summary>
Tagged,
/// <summary>A later page of the tagged posts (<c>tagged-next</c>).</summary>
TaggedNext,
/// <summary>The first page of the reels of a profile (<c>reels</c>).</summary>
Reels,
/// <summary>A later page of the reels (<c>reels-next</c>).</summary>
ReelsNext,
/// <summary>The active stories of an account (<c>stories</c>).</summary>
Stories,
/// <summary>The items of one highlight collection (<c>highlight</c>).</summary>
Highlight,
/// <summary>A later page of the items of a collection (<c>highlight-next</c>).</summary>
HighlightNext,
/// <summary>A single post (<c>post</c>).</summary>
Post,
/// <summary>The first page of the list of profiles Alberto follows (<c>following</c>).</summary>
Following,
/// <summary>A later page of that list (<c>following-next</c>).</summary>
FollowingNext,
}
/// <summary>The spellings of <see cref="RequestRole"/> in the catalog file.</summary>
public static class RequestRoles
{
private static readonly FrozenDictionary<string, RequestRole> ByName = new Dictionary<string, RequestRole>(StringComparer.Ordinal)
{
["profile"] = RequestRole.Profile,
["posts"] = RequestRole.Posts,
["posts-next"] = RequestRole.PostsNext,
["highlights"] = RequestRole.Highlights,
["tagged"] = RequestRole.Tagged,
["tagged-next"] = RequestRole.TaggedNext,
["reels"] = RequestRole.Reels,
["reels-next"] = RequestRole.ReelsNext,
["stories"] = RequestRole.Stories,
["highlight"] = RequestRole.Highlight,
["highlight-next"] = RequestRole.HighlightNext,
["post"] = RequestRole.Post,
["following"] = RequestRole.Following,
["following-next"] = RequestRole.FollowingNext,
}.ToFrozenDictionary(StringComparer.Ordinal);
/// <summary>The role written as <paramref name="name"/>, or null for an unknown spelling.</summary>
public static RequestRole? Parse(string? name) =>
name is not null && ByName.TryGetValue(name.Trim(), out var role) ? role : null;
/// <summary>The spelling of <paramref name="role"/> in the file.</summary>
public static string Name(RequestRole role) => ByName.First(p => p.Value == role).Key;
/// <summary>A role that goes on from a cursor of the previous answer (<c>-next</c>).</summary>
public static bool IsNext(RequestRole role) =>
role is RequestRole.PostsNext or RequestRole.TaggedNext or RequestRole.ReelsNext or RequestRole.HighlightNext or RequestRole.FollowingNext;
}
/// <summary>
/// One operation of <c>richieste.&lt;sito&gt;.json</c>: what the site client may ask (issue #36, spec §6.0). Written from
/// the real request shapes of <c>febe-sonda richieste</c> (§14.5) and documented by a cleaned sample of its answer
@@ -95,9 +179,13 @@ public sealed partial class SiteOperation
IReadOnlySet<string> optional,
IReadOnlyList<string> parameterOrder,
IReadOnlyList<string> headerOrder,
IReadOnlyList<string> bodyOrder)
IReadOnlyList<string> bodyOrder,
IReadOnlySet<RequestRole> roles,
ActionKind? firstPageCategory)
{
Name = name;
Roles = roles;
FirstPageCategory = firstPageCategory;
Kind = kind;
Method = method;
Path = path;
@@ -148,6 +236,32 @@ public sealed partial class SiteOperation
/// </summary>
public ActionKind Category { get; }
/// <summary>The parts the operation plays in the recipes (<c>"roles"</c>, S3); empty when it plays none.</summary>
public IReadOnlySet<RequestRole> Roles { get; }
/// <summary>
/// The category of the first page, asked without a cursor (<c>"firstPageCategory"</c>, only on a «storico»
/// operation): <see cref="ActionKind.ProfileOpen"/>, because in the browser the first page of the grid came with the
/// profile. Null: every request counts in <see cref="Category"/>.
/// </summary>
public ActionKind? FirstPageCategory { get; }
/// <summary>True when the operation always needs <c>{cursor}</c>.</summary>
public bool RequiresCursor => RequiredValues.Contains(CaseValues.Cursor);
/// <summary>True when the operation takes <c>{cursor}</c> or <c>{cursor?}</c>.</summary>
public bool TakesCursor => RequiresCursor || OptionalValues.Contains(CaseValues.Cursor);
/// <summary>
/// The category <paramref name="request"/> counts in: <see cref="FirstPageCategory"/> for a first page (no cursor)
/// when the operation has one, otherwise <see cref="Category"/>.
/// </summary>
public ActionKind CategoryFor(SiteRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return FirstPageCategory is { } first && !request.Values.ContainsKey(CaseValues.Cursor) ? first : Category;
}
/// <summary>
/// False when the shapes do not tell everything the request needs (a variable whose name the probe removed, a
/// value the shapes do not show, a header or field whose source is still <see cref="ValueSourceKind.Pending"/>):
@@ -317,6 +431,7 @@ public sealed partial class RequestCatalog
}.ToFrozenSet(StringComparer.Ordinal);
private readonly FrozenDictionary<string, SiteOperation> _byName;
private readonly FrozenDictionary<RequestRole, SiteOperation> _byRole;
private RequestCatalog(string site, IReadOnlyList<SiteOperation> operations, string? source)
{
@@ -324,6 +439,7 @@ public sealed partial class RequestCatalog
Operations = operations;
Source = source ?? $"richieste.{site}.json";
_byName = operations.ToFrozenDictionary(o => o.Name, StringComparer.Ordinal);
_byRole = operations.SelectMany(o => o.Roles.Select(r => (Role: r, Operation: o))).ToFrozenDictionary(x => x.Role, x => x.Operation);
}
/// <summary>The site name of the file (<c>instagram</c>, <c>prova</c>).</summary>
@@ -341,6 +457,17 @@ public sealed partial class RequestCatalog
public bool TryGet(string name, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out SiteOperation? operation) =>
_byName.TryGetValue(name, out operation);
/// <summary>
/// The operation that plays <paramref name="role"/>, when it can be asked: null when no operation holds the role,
/// or when the one that holds it is not configured. A role on an operation that is not configured does not exist
/// for the recipes: on Instagram, where nothing is configured yet, every recipe stays as it was.
/// </summary>
public SiteOperation? ForRole(RequestRole role) =>
_byRole.TryGetValue(role, out var operation) && operation.IsConfigured && operation.PendingValues.Count == 0 ? operation : null;
/// <summary>The operation that holds <paramref name="role"/>, configured or not (documentation and tests only).</summary>
public SiteOperation? HolderOf(RequestRole role) => _byRole.GetValueOrDefault(role);
/// <summary>The Instagram catalog (embedded <c>richieste.instagram.json</c>).</summary>
public static RequestCatalog LoadInstagram() => LoadEmbedded("richieste.instagram.json");
@@ -381,6 +508,7 @@ public sealed partial class RequestCatalog
var operations = new List<SiteOperation>(file.Operations.Count);
var names = new HashSet<string>(StringComparer.Ordinal);
var roleHolders = new Dictionary<RequestRole, string>();
for (var i = 0; i < file.Operations.Count; i++)
{
var dto = file.Operations[i] ?? throw new InvalidDataException($"{name}, operazione {(i + 1).ToString(CultureInfo.InvariantCulture)}: voce vuota.");
@@ -390,6 +518,14 @@ public sealed partial class RequestCatalog
throw new InvalidDataException($"{name}: l'operazione «{operation.Name}» compare due volte.");
}
foreach (var role in operation.Roles)
{
if (!roleHolders.TryAdd(role, operation.Name))
{
throw new InvalidDataException($"{name}: il ruolo «{RequestRoles.Name(role)}» è sia di «{roleHolders[role]}» sia di «{operation.Name}»: un ruolo appartiene a una sola operazione.");
}
}
operations.Add(operation);
}
@@ -676,11 +812,59 @@ public sealed partial class RequestCatalog
throw new InvalidDataException($"{where}: un'operazione non configurata dice perché («reason»).");
}
var roles = Roles(dto.Roles, category, required, optional, where);
ActionKind? firstPageCategory = null;
if (dto.FirstPageCategory is not null)
{
if (category != ActionKind.BackfillPage)
{
throw new InvalidDataException($"{where}: «firstPageCategory» si scrive solo per un'operazione della categoria «storico».");
}
firstPageCategory = ParseCategory(dto.FirstPageCategory, where);
if (firstPageCategory != ActionKind.ProfileOpen)
{
throw new InvalidDataException($"{where}: «firstPageCategory» ammette solo «profilo» (la prima pagina della griglia arriva con il profilo).");
}
}
return new SiteOperation(
name, kind, method!, path, category, configured, reason, parameters.ToFrozenDictionary(StringComparer.Ordinal),
headers.ToFrozenDictionary(StringComparer.Ordinal), body.ToFrozenDictionary(StringComparer.Ordinal), variables,
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal),
[.. parameters.Keys], [.. headers.Keys], [.. body.Keys]);
[.. parameters.Keys], [.. headers.Keys], [.. body.Keys], roles, firstPageCategory);
}
/// <summary>The roles of an operation, checked against its category and its cursor.</summary>
private static FrozenSet<RequestRole> Roles(List<string?>? names, ActionKind category, SortedSet<string> required, SortedSet<string> optional, string where)
{
var roles = new HashSet<RequestRole>();
foreach (var text in names ?? [])
{
if (RequestRoles.Parse(text) is not { } role)
{
throw new InvalidDataException($"{where}: ruolo «{text}» sconosciuto (ammessi: profile, posts, posts-next, highlights, tagged, tagged-next, reels, reels-next, stories, highlight, highlight-next, post, following, following-next).");
}
if (category == ActionKind.ProfileSearch)
{
throw new InvalidDataException($"{where}: una ricerca non ha ruoli nelle ricette.");
}
if (RequestRoles.IsNext(role) && !required.Contains(CaseValues.Cursor) && !optional.Contains(CaseValues.Cursor))
{
throw new InvalidDataException($"{where}: il ruolo «{RequestRoles.Name(role)}» va da una pagina alla successiva e vuole un'operazione con «{{cursor}}» o «{{cursor?}}».");
}
if (!RequestRoles.IsNext(role) && required.Contains(CaseValues.Cursor))
{
throw new InvalidDataException($"{where}: il ruolo «{RequestRoles.Name(role)}» chiede la prima pagina, senza cursore, e l'operazione vuole sempre «{{cursor}}».");
}
roles.Add(role);
}
return roles.ToFrozenSet();
}
private static Dictionary<string, ValueSource> Sources(Dictionary<string, string?>? entries, string where, string what, bool isBody)
@@ -880,6 +1064,10 @@ internal sealed class OperationDto
public List<string>? Shapes { get; set; }
public string? Note { get; set; }
public List<string?>? Roles { get; set; }
public string? FirstPageCategory { get; set; }
}
[JsonSourceGenerationOptions(
@@ -188,6 +188,13 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
public Signal? ObserveSessionCookie(bool present) =>
present ? null : Raise(SignalLevel.Disconnect, SignalRules.SessionCookieMissingCode, null);
/// <inheritdoc/>
public Signal? Report(Signal signal)
{
ArgumentNullException.ThrowIfNull(signal);
return Raise(signal.Level, signal.Code, signal.Url);
}
private bool UserIsOnPage() => UserOwnsPage?.Invoke() == true;
private Signal? Raise(SignalLevel level, string code, string? url)
@@ -89,6 +89,7 @@
"method": "POST",
"path": "/api/graphql",
"category": "profilo",
"roles": ["profile"],
"configured": false,
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9); la variabile senza nome è un vero/falso di valore non noto",
"headers": {
@@ -165,6 +166,8 @@
"method": "POST",
"path": "/api/graphql",
"category": "storico",
"roles": ["posts"],
"firstPageCategory": "profilo",
"configured": false,
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
"headers": {
@@ -248,6 +251,7 @@
"method": "POST",
"path": "/api/graphql",
"category": "storico",
"roles": ["reels"],
"configured": false,
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"headers": {
@@ -326,6 +330,7 @@
"method": "POST",
"path": "/api/graphql",
"category": "storico",
"roles": ["tagged"],
"configured": false,
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"headers": {
@@ -401,6 +406,7 @@
"method": "POST",
"path": "/api/graphql",
"category": "profilo",
"roles": ["highlights"],
"configured": false,
"reason": "le variabili sono note, ma intestazioni e campi della pagina e del browser (come __dyn, __csr, referer, sec-ch-ua e quello con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"headers": {
@@ -473,6 +479,7 @@
"method": "POST",
"path": "/api/graphql",
"category": "storia",
"roles": ["stories"],
"configured": false,
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
"headers": {
@@ -550,6 +557,7 @@
"method": "POST",
"path": "/graphql/query",
"category": "storia",
"roles": ["highlight"],
"configured": false,
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9)",
"headers": {
@@ -630,6 +638,7 @@
"method": "POST",
"path": "/graphql/query",
"category": "storia",
"roles": ["highlight-next"],
"configured": false,
"reason": "una variabile della forma ha il nome tolto dalla sonda («(nome tolto)»): senza il nome vero la richiesta non si scrive (regola 9); anche il valore di first non è noto (un numero che cambia)",
"headers": {
@@ -715,6 +724,7 @@
"method": "GET",
"path": "/api/v1/media/{media_id}/info/",
"category": "post",
"roles": ["post"],
"configured": false,
"reason": "il percorso è noto, ma intestazioni della pagina e del browser (come referer, sec-ch-ua e quella con il nome tolto dalla sonda) hanno ancora la fonte «pending»: finché non si sa da dove vengono i valori la richiesta non si scrive (regola 9, tappa S4)",
"headers": {
+15 -3
View File
@@ -66,6 +66,7 @@
"method": "POST",
"path": "/api/graphql",
"category": "profilo",
"roles": ["profile", "posts", "highlights"],
"configured": true,
"headers": {
"accept": "constant:*/*",
@@ -104,6 +105,7 @@
"method": "GET",
"path": "/api/dati/profilo/{username}/altri",
"category": "storico",
"roles": ["posts-next"],
"configured": true,
"parameters": {
"dopo": "{cursor}",
@@ -128,6 +130,7 @@
"method": "GET",
"path": "/api/dati/profilo/{username}",
"category": "storico",
"roles": ["tagged"],
"configured": true,
"parameters": {
"scheda": "constant:taggati"
@@ -149,8 +152,8 @@
"method": "GET",
"path": "/api/dati/profilo/{username}",
"category": "storico",
"configured": false,
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
"roles": ["reels"],
"configured": true,
"parameters": {
"scheda": "constant:reel"
},
@@ -159,7 +162,12 @@
"user-agent": "session:user_agent",
"x-app-id": "session:app_id",
"x-csrftoken": "cookie:csrftoken"
}
},
"rootFields": [
"contenuti"
],
"sample": "000012-reel",
"note": "Nessuna operazione per le pagine successive: i reel di ogni account del sito di prova stanno in una pagina (12)."
},
{
"name": "post",
@@ -167,6 +175,7 @@
"method": "GET",
"path": "/api/dati/post/{code}",
"category": "post",
"roles": ["post"],
"configured": true,
"headers": {
"accept": "constant:application/json",
@@ -185,6 +194,7 @@
"method": "GET",
"path": "/api/dati/storie/{username}",
"category": "storia",
"roles": ["stories"],
"configured": true,
"headers": {
"accept": "constant:application/json",
@@ -203,6 +213,7 @@
"method": "GET",
"path": "/api/dati/evidenza/{highlight_id}",
"category": "storia",
"roles": ["highlight"],
"configured": true,
"headers": {
"accept": "constant:application/json",
@@ -221,6 +232,7 @@
"method": "GET",
"path": "/api/dati/seguiti",
"category": "seguiti",
"roles": ["following", "following-next"],
"configured": true,
"parameters": {
"dopo": "{cursor?}"
+7
View File
@@ -128,6 +128,13 @@ public interface IRecipeRunner
/// would only end in <see cref="RecipeStatus.NotConfigured"/>.
/// </summary>
string? NotConfiguredReason(RecipeKind kind) => null;
/// <summary>
/// The budget category the first action of <paramref name="kind"/> takes on the route this runner gives it (the
/// engine skips the recipe when that budget is exhausted, and marks it exhausted after a refusal). By default the
/// category of the recipe by the pages (<see cref="CheckPolicy.CategoryOf"/>).
/// </summary>
ActionKind FirstCategory(RecipeKind kind) => CheckPolicy.CategoryOf(kind);
}
/// <summary>Daily byte budget for CDN downloads (category «dati scaricati», spec §7.4).</summary>
+15 -4
View File
@@ -835,8 +835,10 @@ internal sealed class SessionComposer
return null;
}
var category = CheckPolicy.CategoryOf(request.Kind);
if (state.Exhausted.Contains(category))
// By requests a recipe can still go back to the pages for one run (a value missing, a next page without a
// request), and its first action is then that of the pages: both budgets must have room.
var category = _runner.FirstCategory(request.Kind);
if (state.Exhausted.Contains(category) || state.Exhausted.Contains(CheckPolicy.CategoryOf(request.Kind)))
{
return null;
}
@@ -1006,10 +1008,19 @@ internal sealed class SessionComposer
await RequeueAsync(task, "Rimandata: tetto raggiunto", now).ConfigureAwait(false);
}
var recheck = await _s.Governor.EvaluateBudgetAsync(CheckPolicy.CategoryOf(kind), request.AccountId, ct).ConfigureAwait(false);
// The refusal may have come on the route of the requests or, gone back to them, of the pages.
var first = _runner.FirstCategory(kind);
var pages = CheckPolicy.CategoryOf(kind);
if (pages != first
&& (await _s.Governor.EvaluateBudgetAsync(pages, request.AccountId, ct).ConfigureAwait(false)).Reason is DenialReason.HourlyBudgetReached or DenialReason.DailyBudgetReached)
{
state.Exhausted.Add(pages);
}
var recheck = await _s.Governor.EvaluateBudgetAsync(first, request.AccountId, ct).ConfigureAwait(false);
if (recheck.Reason is DenialReason.HourlyBudgetReached or DenialReason.DailyBudgetReached)
{
state.Exhausted.Add(CheckPolicy.CategoryOf(kind));
state.Exhausted.Add(first);
}
else if (recheck.Reason is DenialReason.BreakerOpen or DenialReason.OutsideActiveWindow or DenialReason.Paused or DenialReason.UserIsDriving)
{
+4 -1
View File
@@ -23,6 +23,9 @@ public sealed record SimulationOptions
public SimulatedWorldOptions? World { get; init; }
/// <summary>Whether the simulated recipes go by the pages or by requests (<c>--raccolta</c>); it wins over <see cref="World"/>.</summary>
public SimulatedCollection Collection { get; init; } = SimulatedCollection.Pages;
public EngineOptions? Engine { get; init; }
/// <summary>Full engine settings (e.g. a «Su misura» profile); when null, <see cref="Profile"/> with the other defaults.</summary>
@@ -61,7 +64,7 @@ public static class EngineSimulation
var clock = new VirtualClock(start, zone);
await EngineSettingsStore.SaveAsync(storage.Settings, options.Settings ?? new EngineSettings { ProfileKind = options.Profile }, ct).ConfigureAwait(false);
var services = await EngineServices.CreateAsync(storage, clock, new SeededRandom(options.Seed), options.Engine, ct: ct).ConfigureAwait(false);
var worldOptions = options.World ?? new SimulatedWorldOptions { Seed = options.Seed };
var worldOptions = (options.World ?? new SimulatedWorldOptions { Seed = options.Seed }) with { Collection = options.Collection };
var world = new SimulatedWorld(storage, services.Governor, services.Governor, services.Breaker, clock, worldOptions);
await world.InitializeAsync(start, end, services.Runtime.Profile, ct).ConfigureAwait(false);
+133 -8
View File
@@ -1,5 +1,6 @@
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Pacing;
@@ -7,9 +8,26 @@ using Febe.Core.Storage;
namespace Febe.Core.Simulation;
/// <summary>How the simulated recipes read the site (issue #36, S3).</summary>
public enum SimulatedCollection
{
/// <summary>By the pages of the browser: one StoryView per story shown, the profile opened for a profile not followed.</summary>
Pages,
/// <summary>
/// By the requests of the site client: one StoryView per request of the stories of an account (all of them in one
/// answer), no profile opened first, the waits of <see cref="RequestTimings"/> instead of the
/// gestures.
/// </summary>
Requests,
}
/// <summary>The fake world of the simulation (spec §14.3).</summary>
public sealed record SimulatedWorldOptions
{
/// <summary>Whether the simulated recipes go by the pages or by requests (<c>--raccolta</c>).</summary>
public SimulatedCollection Collection { get; init; } = SimulatedCollection.Pages;
public int FollowedAccounts { get; init; } = 25;
public int NotFollowedAccounts { get; init; } = 15;
@@ -116,10 +134,15 @@ public sealed class SimulatedWorld : IRecipeRunner
public WorldStats Stats { get; } = new();
/// <summary>Whether the recipes of this world go by the pages or by requests.</summary>
public SimulatedCollection Collection => _options.Collection;
public IReadOnlyList<SimAccount> Accounts => _accounts;
private double Pace => GesturePaceFactors.For(_options.Pace);
private bool ByRequests => _options.Collection == SimulatedCollection.Requests;
/// <summary>Creates the accounts in the database and the publications of the period [start, end).</summary>
public async Task InitializeAsync(DateTimeOffset start, DateTimeOffset end, CautionProfile profile, CancellationToken ct = default)
{
@@ -335,22 +358,66 @@ public sealed class SimulatedWorld : IRecipeRunner
}
account.LastProfileOpen = _clock.Now;
await WaitAsync(session, 1, 6, 2.2, ct).ConfigureAwait(false);
var bursts = _random.CountBetween(1, 3);
for (var b = 0; b < bursts; b++)
var counted = 1;
if (ByRequests)
{
await WaitAsync(session, 0.4, 4, 1.1, ct).ConfigureAwait(false);
// The cost of Instagram's split operations, the conservative case (the test site answers all in one): the
// profile, then the first page of posts, each one ProfileOpen.
await RequestGapAsync(session, ct).ConfigureAwait(false);
var posts = await AskAsync(ActionKind.ProfileOpen, account.Id, ct).ConfigureAwait(false);
if (!posts.Granted)
{
return Denied(counted, 0);
}
counted++;
if (posts.Throttled)
{
return Signal(counted, 0);
}
}
else
{
await WaitAsync(session, 1, 6, 2.2, ct).ConfigureAwait(false);
var bursts = _random.CountBetween(1, 3);
for (var b = 0; b < bursts; b++)
{
await WaitAsync(session, 0.4, 4, 1.1, ct).ConfigureAwait(false);
}
}
var now = _clock.Now;
var firstPage = account.Posts.Where(p => p.PublishedAt <= now).OrderByDescending(p => p.PublishedAt).Take(PostsPerPage);
var fresh = firstPage.Where(p => p.DiscoveredAt is null).ToList();
await StorePostsAsync(account, fresh, now, history: false, ct).ConfigureAwait(false);
return new RecipeOutcome(RecipeStatus.Completed, 1, fresh.Count);
if (ByRequests && (account.LastTrayAt is not { } tray || now - tray >= RecipeOptions.DefaultHighlightsTrayInterval))
{
// The list of collections, at most once a day per account, after the first page is saved: refused, it waits
// for the next check. The waits come only between two requests, as in the recipe.
await RequestGapAsync(session, ct).ConfigureAwait(false);
var listed = await AskAsync(ActionKind.ProfileOpen, account.Id, ct).ConfigureAwait(false);
if (listed.Granted)
{
counted++;
if (listed.Throttled)
{
return Signal(counted, fresh.Count);
}
account.LastTrayAt = _clock.Now;
}
}
return new RecipeOutcome(RecipeStatus.Completed, counted, fresh.Count);
}
private async Task<RecipeOutcome> StoriesAsync(SimAccount account, ISessionContext session, CancellationToken ct)
{
if (ByRequests)
{
return await StoriesByRequestAsync(account, session, ct).ConfigureAwait(false);
}
var counted = 0;
var now = _clock.Now;
if (!account.Followed && (account.LastProfileOpen is not { } opened || now - opened > TimeSpan.FromMinutes(2)))
@@ -412,10 +479,65 @@ public sealed class SimulatedWorld : IRecipeRunner
return new RecipeOutcome(RecipeStatus.Completed, counted, seen);
}
/// <summary>The stories of an account by one request: one StoryView, every active story in the answer.</summary>
private async Task<RecipeOutcome> StoriesByRequestAsync(SimAccount account, ISessionContext session, CancellationToken ct)
{
var permit = await AskAsync(ActionKind.StoryView, account.Id, ct).ConfigureAwait(false);
if (!permit.Granted)
{
return Denied(0, 0);
}
if (permit.Throttled)
{
return Signal(1, 0);
}
await RequestGapAsync(session, ct).ConfigureAwait(false);
var at = _clock.Now;
var seen = 0;
foreach (var story in account.Stories.Where(s => s.PublishedAt <= at && s.ExpiresAt > at && s.SeenAt is null).ToList())
{
story.SeenAt = at;
Stats.StoryViews.Add((story.PublishedAt, at));
await StoreStoryAsync(account, story, at, ct).ConfigureAwait(false);
seen++;
}
var day = LocalCalendar.Today(_clock.Now, _clock.LocalZone);
Stats.StoryChecks[(account.Id, day)] = Stats.StoryChecks.GetValueOrDefault((account.Id, day)) + 1;
return new RecipeOutcome(RecipeStatus.Completed, 1, seen);
}
/// <summary>The wait after an answer of the site client (<see cref="RequestTimings.AfterAnswer"/>).</summary>
private Task RequestGapAsync(ISessionContext session, CancellationToken ct) =>
_clock.Delay(RequestTimings.AfterAnswer(_random, session.Mood * Pace), ct);
private async Task<RecipeOutcome> BackfillAsync(SimAccount account, int maxPages, ISessionContext session, CancellationToken ct)
{
var pages = 0;
var stored = 0;
var counted = 0;
if (ByRequests && account.HistoryCursor == 0 && account.LastProfileOpen is null && account.History.Count > 0)
{
// No profile check stored a point yet: the first page of the grid is asked without a cursor, and counts as
// the profile (firstPageCategory), not among the pages of the run.
var first = await AskAsync(ActionKind.ProfileOpen, account.Id, ct).ConfigureAwait(false);
if (!first.Granted)
{
return Denied(0, 0);
}
counted++;
if (first.Throttled)
{
return Signal(counted, 0);
}
account.LastProfileOpen = _clock.Now;
await RequestGapAsync(session, ct).ConfigureAwait(false);
}
while (pages < maxPages && _clock.Now < session.PlannedEnd)
{
if (account.HistoryCursor >= account.History.Count)
@@ -426,13 +548,13 @@ public sealed class SimulatedWorld : IRecipeRunner
var permit = await AskAsync(ActionKind.BackfillPage, account.Id, ct).ConfigureAwait(false);
if (!permit.Granted)
{
return pages > 0 ? new RecipeOutcome(RecipeStatus.Completed, pages, stored) : Denied(0, 0);
return pages > 0 ? new RecipeOutcome(RecipeStatus.Completed, counted + pages, stored) : Denied(counted, 0);
}
pages++;
if (permit.Throttled)
{
return Signal(pages, stored);
return Signal(counted + pages, stored);
}
await WaitAsync(session, 2, 8, 3.5, ct).ConfigureAwait(false);
@@ -449,7 +571,7 @@ public sealed class SimulatedWorld : IRecipeRunner
Stats.BackfillFinishedAt = _clock.Now;
}
return new RecipeOutcome(RecipeStatus.Completed, pages, stored) { BackfillFinished = finished };
return new RecipeOutcome(RecipeStatus.Completed, counted + pages, stored) { BackfillFinished = finished };
}
private async Task<RecipeOutcome> SimpleAsync(ActionKind kind, long? accountId, ISessionContext session, CancellationToken ct)
@@ -660,6 +782,9 @@ public sealed class SimAccount(long id, string username, bool followed, int inde
internal List<SimStory> Stories { get; } = [];
internal DateTimeOffset? LastProfileOpen { get; set; }
/// <summary>When the list of highlight collections was last asked by requests.</summary>
internal DateTimeOffset? LastTrayAt { get; set; }
}
internal sealed class SimPost(string id, DateTimeOffset publishedAt, int files, bool hasVideo)
@@ -45,6 +45,9 @@ public sealed class SimulationReport
public required CautionProfileKind Profile { get; init; }
/// <summary>Whether the simulated recipes went by the pages or by requests.</summary>
public SimulatedCollection Collection { get; init; }
public required int Seed { get; init; }
public required DateTimeOffset Start { get; init; }
@@ -306,6 +309,7 @@ public sealed class SimulationReport
return new SimulationReport
{
Profile = profile.Kind,
Collection = world.Collection,
Seed = options.Seed,
Start = start,
End = end,
@@ -353,6 +357,7 @@ public sealed class SimulationReport
var firstDay = LocalCalendar.Today(Start, Zone);
var lastDay = LocalCalendar.Today(End - TimeSpan.FromTicks(1), Zone);
b.AppendLine($"Simulazione del motore: {ItalianText.Count(Days.Count, "giorno", "giorni")} con il profilo «{ItalianText.Profile(Profile)}» (seme {Seed.ToString(CultureInfo.InvariantCulture)})");
b.AppendLine(Collection == SimulatedCollection.Requests ? "Raccolta: per richieste" : "Raccolta: per pagine");
b.AppendLine($"Periodo: dal {ItalianText.Day(firstDay)} alle {ItalianText.Clock(Start, Zone)} al {ItalianText.Day(lastDay)}, fuso {Zone.Id}");
b.AppendLine($"Mondo finto: {ItalianText.Number(Accounts)} account ({ItalianText.Number(FollowedAccounts)} seguiti, {ItalianText.Number(Accounts - FollowedAccounts)} no), {ItalianText.Number(PublishedPosts)} post e {ItalianText.Number(PublishedStories)} storie pubblicati nel periodo, uno storico di {ItalianText.Number(BackfillPosts)} post");
b.AppendLine("I tetti del profilo sono stime prudenti, non limiti ufficiali di Instagram.");
+23 -2
View File
@@ -6,7 +6,7 @@ using Febe.Data;
namespace Febe.Server;
/// <summary>
/// <c>--simula 30g --profilo prudente [--csv percorso] [--seme n]</c> (spec §14.3): runs the engine under the virtual
/// <c>--simula 30g --profilo prudente [--raccolta pagine|richieste] [--csv percorso] [--seme n]</c> (spec §14.3): runs the engine under the virtual
/// clock against the fake world, in a temporary database, and prints the Italian report. Never opens a browser and
/// never contacts any site. Exit code 0 when no budget was exceeded, 1 otherwise, 2 for wrong arguments.
/// </summary>
@@ -21,7 +21,7 @@ internal static class SimulateCommand
if (!TryParse(args, out var options, out var csv, out var problem))
{
await error.WriteLineAsync(problem).ConfigureAwait(false);
await error.WriteLineAsync("Uso: --simula 30g --profilo prudente|equilibrato|rapido [--csv percorso.csv] [--seme numero]").ConfigureAwait(false);
await error.WriteLineAsync("Uso: --simula 30g --profilo prudente|equilibrato|rapido [--raccolta pagine|richieste] [--csv percorso.csv] [--seme numero]").ConfigureAwait(false);
return 2;
}
@@ -102,6 +102,27 @@ internal static class SimulateCommand
break;
}
case "--raccolta":
{
var value = Next();
SimulatedCollection? collection = value?.ToLowerInvariant() switch
{
"pagine" => SimulatedCollection.Pages,
"richieste" => SimulatedCollection.Requests,
_ => null,
};
if (collection is null)
{
problem = value is null
? "Dopo --raccolta serve pagine o richieste."
: $"Raccolta sconosciuta: «{value}». Si sceglie fra pagine e richieste.";
return false;
}
options = options with { Collection = collection.Value };
break;
}
case "--csv":
csv = Next();
if (string.IsNullOrWhiteSpace(csv))
@@ -483,6 +483,7 @@ public sealed class HttpSiteRequesterTests
["profilo-altri"] = (V((CaseValues.Username, "luca.prova"), (CaseValues.Cursor, "c12")), "/dati/profilo/luca.prova/altri?dopo=c12&scheda=post"),
[TestSite.ProfileQuery] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=post"),
["taggati"] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=taggati"),
["reel"] = (V((CaseValues.Username, "luca.prova")), "/dati/profilo/luca.prova?scheda=reel"),
["post"] = (V((CaseValues.Code, code)), "/dati/post/" + code),
["storie"] = (V((CaseValues.Username, "marta.prova")), "/dati/storie/marta.prova"),
["evidenza"] = (V((CaseValues.HighlightId, highlight)), "/dati/evidenza/" + Uri.EscapeDataString(highlight)),
@@ -573,6 +573,8 @@ public sealed class ProfileSearchTests
return null;
}
public Signal? Report(Signal signal) => null;
}
private sealed class FakeBreaker : ICircuitBreaker
@@ -0,0 +1,217 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.SitoDiProva;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// The recipes by requests (issue #36, S3) against the real test site on 127.0.0.1, through the HTTP site client, never
/// Instagram: what the site has comes into the archive without the page, one permit per request, and the stop cases of
/// the site stop the run.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
public sealed class RequestRecipeSiteTests
{
private static readonly RequestCatalog Catalog = RequestCatalog.LoadTestSite();
[TestMethod]
public async Task TheCheckAndTheHistoryReadTheWholeGrid()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (id, posts) = Facts(site, "luca.prova", a => a.Posts.Count);
var luca = await bed.AddAccountAsync(id, "luca.prova", a => a with { State = AccountState.Backfilling });
var check = await bed.RunAsync(RecipeKind.ProfileCheck, luca.Id);
var history = await bed.RunAsync(RecipeKind.Backfill, luca.Id, maxPages: 10);
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
Assert.AreEqual(RecipeStatus.Completed, history.Status, history.Message);
Assert.IsTrue(history.BackfillFinished, "The beginning of the profile was reached.");
Assert.AreEqual(0, bed.Page.Touched);
Assert.AreEqual(posts, (await bed.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Count);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(luca.Id))!.BackfillCompletedAt);
Assert.AreEqual(bed.Governor.Requests.Count, bed.Governor.Requests.Count(r => r.Kind is ActionKind.ProfileOpen or ActionKind.BackfillPage));
}
[TestMethod]
public async Task StoriesCollectionTaggedAndReelsComeWithoutThePage()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (martaId, _) = Facts(site, "marta.prova", a => 0);
string highlight;
int items;
lock (site.World.Gate)
{
var account = site.World.FindByUsername("marta.prova")!;
highlight = account.Highlights[0].Id;
items = account.Highlights[0].Items.Count;
}
var (lucaId, reels) = Facts(site, "luca.prova", a => a.Posts.Count(p => p.IsReel));
var marta = await bed.AddAccountAsync(martaId, "marta.prova", a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
var luca = await bed.AddAccountAsync(lucaId, "luca.prova");
var stories = await bed.RunAsync(RecipeKind.AccountStories, marta.Id);
var check = await bed.RunAsync(RecipeKind.ProfileCheck, marta.Id);
var collection = await bed.RunAsync(RecipeKind.Highlight, marta.Id, highlightId: highlight);
var tagged = await bed.RunAsync(RecipeKind.Tagged, marta.Id);
var reel = await bed.RunAsync(RecipeKind.Reels, luca.Id);
foreach (var outcome in new[] { stories, check, collection, tagged, reel })
{
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
}
Assert.AreEqual(0, bed.Page.Touched);
Assert.IsTrue(stories.NewEntries > 0);
var stored = (await bed.Db.Highlights.FindAsync(marta.Id, highlight))!;
Assert.AreEqual(items, (await bed.Db.Highlights.ListItemsAsync(stored.Id)).Count, "Every content of the collection is linked, in its order.");
Assert.IsTrue((await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count > 0);
Assert.AreEqual(reels, reel.NewEntries, "Every reel of the account, in one page.");
}
[TestMethod]
public async Task TheFollowingListIsReadToTheEndByItsCursors()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
int following;
lock (site.World.Gate)
{
following = site.World.Following.Count;
}
await bed.AddAccountAsync("1000", "alberto.prova", isMine: true);
var outcome = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 10);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.IsTrue(outcome.BackfillFinished, outcome.Message);
StringAssert.StartsWith(outcome.Message, $"Elenco dei seguiti letto: {following} profili");
Assert.AreEqual(0, bed.Page.Touched);
Assert.IsTrue(bed.Governor.Requests.All(r => r.Kind == ActionKind.FollowingListPage));
}
[TestMethod]
public async Task APrivateProfileAndAMissingOneAreUnreachable()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var hidden = await bed.AddAccountAsync("1006", "riservato.prova");
var missing = await bed.AddAccountAsync(null, "nessuno.prova");
var first = await bed.RunAsync(RecipeKind.ProfileCheck, hidden.Id);
var second = await bed.RunAsync(RecipeKind.ProfileCheck, missing.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, first.Status, first.Message);
Assert.AreEqual(UnreachableReason.PrivateNotFollowed, (await bed.Db.Accounts.GetAsync(hidden.Id))!.UnreachableReason);
Assert.AreEqual(RecipeStatus.AccountUnreachable, second.Status, second.Message);
Assert.AreEqual(UnreachableReason.NotFound, (await bed.Db.Accounts.GetAsync(missing.Id))!.UnreachableReason);
Assert.AreEqual(0, bed.Breaker.Signals.Count);
}
[TestMethod]
public async Task TheStoriesOfAPrivateProfileNotFollowedMakeItUnreachableAsByThePage()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var hidden = await bed.AddAccountAsync("1006", "riservato.prova");
var outcome = await bed.RunAsync(RecipeKind.AccountStories, hidden.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
Assert.AreEqual(UnreachableReason.PrivateNotFollowed, (await bed.Db.Accounts.GetAsync(hidden.Id))!.UnreachableReason);
CollectionAssert.AreEqual(new[] { ActionKind.StoryView, ActionKind.ProfileOpen }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(0, bed.Breaker.Signals.Count);
Assert.AreEqual(0, bed.Page.Touched);
}
[TestMethod]
public async Task TheGapBelowANewFirstPageIsFilledByTheNextPageUntilKnownPosts()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (id, _) = Facts(site, "luca.prova", a => 0);
var luca = await bed.AddAccountAsync(id, "luca.prova");
var first = await bed.RunAsync(RecipeKind.ProfileCheck, luca.Id);
var known = (await bed.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Count;
lock (site.World.Gate)
{
var account = site.World.FindByUsername("luca.prova")!;
for (var i = 0; i < 14; i++)
{
site.World.Publish(account, "foto", DateTimeOffset.UtcNow.AddMinutes(i));
}
}
var requestsBefore = bed.Governor.Requests.Count;
var second = await bed.RunAsync(RecipeKind.ProfileCheck, luca.Id);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
Assert.AreEqual(14, second.NewEntries, "The first page and the two new posts of the page after it.");
Assert.AreEqual(known + 14, (await bed.Db.Entries.ListByAccountAsync(luca.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Count);
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.BackfillPage }, bed.Governor.Requests.Skip(requestsBefore).Select(r => r.Kind).ToArray(), "One page of the gap, then known posts.");
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{luca.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)}.cursore"), "The gap is filled: no point left.");
Assert.AreEqual(0, bed.Page.Touched);
}
[TestMethod]
public async Task TooManyRequestsOfTheSiteStopTheRun()
{
await using var site = await SyntheticSite.StartAsync();
await using var bed = await BedAsync(site);
var (id, _) = Facts(site, "marta.prova", a => 0);
var marta = await bed.AddAccountAsync(id, "marta.prova");
site.Control.Set(StopMode.TooManyRequests);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, marta.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(SignalLevel.Throttle, bed.Breaker.Signals.Single().Level);
Assert.AreEqual(1, bed.Governor.Requests.Count, "Nothing asked after the signal.");
}
[TestMethod]
public async Task WithoutASavedSessionTheRunStopsAsADisconnection()
{
await using var site = await SyntheticSite.StartAsync();
var clock = new VirtualClock(DateTimeOffset.UtcNow);
var requester = new HttpSiteRequester(Catalog, new InMemorySiteSession(null), HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), clock);
await using var bed = await RequestBed.CreateAsync(catalog: Catalog, requester: requester, clock: clock);
var (id, _) = Facts(site, "marta.prova", a => 0);
var marta = await bed.AddAccountAsync(id, "marta.prova");
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, marta.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(SignalLevel.Disconnect, bed.Breaker.Signals.Single().Level);
Assert.AreEqual(0, bed.Page.Touched, "Never a way back to the pages (rule 7).");
}
private static async Task<RequestBed> BedAsync(TestSite site)
{
var clock = new VirtualClock(DateTimeOffset.UtcNow);
var requester = new HttpSiteRequester(Catalog, new InMemorySiteSession(HttpSiteRequesterTests.Values()), HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), clock);
return await RequestBed.CreateAsync(catalog: Catalog, requester: requester, clock: clock);
}
private static (string Id, int Count) Facts(TestSite site, string username, Func<SiteAccount, int> count)
{
lock (site.World.Gate)
{
var account = site.World.FindByUsername(username)!;
return (account.Id, count(account));
}
}
}
@@ -0,0 +1,655 @@
using System.Globalization;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// The recipes by requests (issue #36, S3) on the cleaned samples of the test site, through the scripted site client:
/// the page is never touched, every request has its own permit in the category of its operation, the answers go to the
/// readers and the stop cases of §7.6 stop the run where it is.
/// </summary>
[TestClass]
public sealed class RequestRecipeTests
{
[TestMethod]
public async Task TheProfileCheckIsOneRequestThatGivesProfileGridAndCollections()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched, "The page is never touched.");
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(1, outcome.CountedActions);
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count);
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count, "The collections came in the same answer.");
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolte.vassoio.{Id(account)}"));
var stored = (await bed.Db.Accounts.GetAsync(account.Id))!;
Assert.AreEqual("n17", stored.BackfillCursor, "The history starts from the cursor of the first page.");
}
[TestMethod]
public async Task ASecondCheckWithNothingNewAsksOnceMore()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, outcome.NewEntries);
Assert.AreEqual(2, bed.Scripted!.Sent.Count, "Known posts: no gap to fill.");
}
[TestMethod]
public async Task TheGapBelowANewFirstPageGoesOnByItsCursor()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
var sent = bed.Scripted!.Sent;
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, sent.Select(s => s.Operation).ToArray());
Assert.AreEqual("n17", sent[1].Values[CaseValues.Cursor]);
Assert.AreEqual("ndkwq.shzgd", sent[1].Values[CaseValues.Username]);
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual("n17", await bed.Db.Settings.GetAsync($"raccolta.lacuna.{Id(account)}.cursore"), "The page after was not of the account: the point stays.");
Assert.AreEqual(1, bed.Clock.Delays.Count(d => d >= TimeSpan.FromSeconds(2)), "One wait between the two pages, none before the first request.");
}
[TestMethod]
public async Task TheHistoryStartsWithTheProfileAndGoesOnByRequests()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { State = AccountState.Backfilling });
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 3);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched);
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray(), "The first page comes with the profile.");
Assert.AreEqual("n17", (await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCursor);
}
[TestMethod]
public async Task AStoredCursorIsAskedForDirectly()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c24", State = AccountState.Backfilling });
await bed.RunAsync(RecipeKind.Backfill, account.Id);
var sent = bed.Scripted!.Sent.Single();
Assert.AreEqual("profilo-altri", sent.Operation);
Assert.AreEqual("c24", sent.Values[CaseValues.Cursor]);
Assert.AreEqual(ActionKind.BackfillPage, bed.Governor.Requests.Single().Kind);
}
[TestMethod]
public async Task TaggedAndReelsEndAtTheLastPageAndAreMarkedComplete()
{
await using var bed = await RequestBed.CreateAsync();
var marta = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
var reels = await bed.AddAccountAsync("6104", "lmxm.bgwrl");
var tagged = await bed.RunAsync(RecipeKind.Tagged, marta.Id);
var reel = await bed.RunAsync(RecipeKind.Reels, reels.Id);
Assert.AreEqual(RecipeStatus.Completed, tagged.Status, tagged.Message);
Assert.AreEqual(RecipeStatus.Completed, reel.Status, reel.Message);
Assert.AreEqual(0, bed.Page.Touched);
CollectionAssert.AreEqual(new[] { "taggati", "reel" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.BackfillPage, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(3, (await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count);
Assert.AreEqual(6, (await bed.Db.Entries.ListByAccountAsync(reels.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count);
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{Id(marta)}.completo"));
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.reel.{Id(reels)}.completo"));
}
[TestMethod]
public async Task TheStoriesOfAnAccountAreOneRequestWithoutTheMinimumOfTen()
{
await using var bed = await RequestBed.CreateAsync();
bed.Governor.ReportedRemaining = 1; // by the viewer the recipe would not even start
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched);
Assert.AreEqual("storie", bed.Scripted!.Sent.Single().Operation);
Assert.AreEqual(ActionKind.StoryView, bed.Governor.Requests.Single().Kind, "One StoryView for all the stories of the answer.");
Assert.AreEqual(4, outcome.NewEntries);
Assert.AreEqual(4, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story, Limit = 100 })).Count);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.LastStoriesCheckAt);
}
[TestMethod]
public async Task TheStoriesOfTwoAccountsInARowDoNotWaitBeforeTheirRequest()
{
// §6.3: the first request of a recipe does not wait, the Governor keeps the distance (unlike the viewer, which
// waits 1–4 s between two accounts).
await using var bed = await RequestBed.CreateAsync();
var first = await bed.AddSampleAccountAsync();
var second = await bed.AddAccountAsync("6666", "altra.prova");
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.AccountStories, first.Id)).Status);
var before = bed.Clock.Now;
await bed.RunAsync(RecipeKind.AccountStories, second.Id);
Assert.HasCount(2, bed.Scripted!.Sent);
Assert.AreEqual(before, bed.Clock.Now, "No wait between the two accounts.");
}
[TestMethod]
public async Task NoStoriesIsAQuietDayNotAnEmptyPage()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, outcome.NewEntries);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.LastStoriesCheckAt);
}
[TestMethod]
public async Task ACollectionNotKnownYetWaitsForTheProfileCheck()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.Highlight, account.Id, highlightId: "3688348931");
Assert.AreEqual(RecipeStatus.Completed, outcome.Status);
StringAssert.Contains(outcome.Message, "non è ancora nota");
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.AreEqual(0, bed.Governor.Requests.Count);
}
[TestMethod]
public async Task AKnownCollectionIsReadByItsIdentifier()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var outcome = await bed.RunAsync(RecipeKind.Highlight, account.Id, highlightId: "3688348931");
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
var sent = bed.Scripted!.Sent[^1];
Assert.AreEqual("evidenza", sent.Operation);
Assert.AreEqual("3688348931", sent.Values[CaseValues.HighlightId]);
Assert.AreEqual(ActionKind.StoryView, bed.Governor.Requests[^1].Kind);
Assert.AreEqual(3, outcome.NewEntries);
var highlight = (await bed.Db.Highlights.FindAsync(account.Id, "3688348931"))!;
Assert.IsNotNull(highlight.LastCheckedAt);
}
[TestMethod]
public async Task ASinglePostIsAskedByItsCode()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var entry = await AddPostAsync(bed, account, "6686720181", "TqwwCvG");
var outcome = await bed.RunAsync(RecipeKind.SinglePost, entryId: entry);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
StringAssert.StartsWith(outcome.Message, "Post completato");
Assert.AreEqual("TqwwCvG", bed.Scripted!.Sent.Single().Values[CaseValues.Code]);
Assert.AreEqual(ActionKind.SinglePost, bed.Governor.Requests.Single().Kind);
}
[TestMethod]
public async Task APostWithoutCodeGoesByThePageWhenThePageCanRun()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
var entry = await AddPostAsync(bed, account, "6686720181", null);
var outcome = await bed.RunAsync(RecipeKind.SinglePost, entryId: entry);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.IsTrue(bed.Page.Touched > 0, "The page route was taken.");
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, "The page of the bed refuses everything.");
Assert.IsTrue((await bed.EventCodesAsync()).Contains("richieste-valore-mancante"));
}
[TestMethod]
public async Task APostWithoutCodeWaitsWhenThePageCannotRun()
{
var map = new SiteMap("prova", new Dictionary<string, string?> { [SitePages.Profile] = "/profilo/{username}/" }, [], SiteTargets.All);
await using var bed = await RequestBed.CreateAsync(map);
var account = await bed.AddSampleAccountAsync();
var entry = await AddPostAsync(bed, account, "6686720181", null);
var outcome = await bed.RunAsync(RecipeKind.SinglePost, entryId: entry);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, "Never NotConfigured: the engine would stop planning it.");
StringAssert.Contains(outcome.Message, "il codice del post");
Assert.AreEqual(0, bed.Page.Touched);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
}
[TestMethod]
public async Task TheFollowingListStoresItsCursorAndAsksForItNextTime()
{
await using var bed = await RequestBed.CreateAsync();
await bed.AddAccountAsync("17841400000000077", "alberto.prova", isMine: true);
var first = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 1);
var second = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 1);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
StringAssert.StartsWith(first.Message, "Letti 10 profili");
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
var sent = bed.Scripted!.Sent;
Assert.IsFalse(sent[0].Values.ContainsKey(CaseValues.Cursor), "The first page without «dopo».");
Assert.AreEqual("b44", sent[1].Values[CaseValues.Cursor]);
Assert.AreEqual(0, bed.Page.Touched);
CollectionAssert.AreEqual(new[] { ActionKind.FollowingListPage, ActionKind.FollowingListPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
}
[TestMethod]
[DataRow(ScriptedReply.TooManyRequests, SignalLevel.Throttle)]
[DataRow(ScriptedReply.RedirectToLogin, SignalLevel.Challenge)]
[DataRow(ScriptedReply.RedirectToChallenge, SignalLevel.Challenge)]
[DataRow(ScriptedReply.HtmlInsteadOfJson, SignalLevel.Challenge)]
[DataRow(ScriptedReply.MissingRootField, SignalLevel.Challenge)]
[DataRow(ScriptedReply.SessionCookieDeleted, SignalLevel.Challenge)]
public async Task AStopSignalInTheAnswerStopsTheRunWhereItIs(ScriptedReply reply, SignalLevel level)
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
bed.Scripted!.Then(reply);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(1, bed.Scripted.Sent.Count, "No other request after the signal.");
Assert.AreEqual(level, bed.Breaker.Signals.Single().Level);
Assert.AreEqual(0, outcome.NewEntries);
Assert.AreEqual(0, bed.Page.Touched);
}
[TestMethod]
public async Task AProfileTheSiteDoesNotHaveMakesTheAccountUnreachable()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
var stored = (await bed.Db.Accounts.GetAsync(account.Id))!;
Assert.AreEqual(AccountState.Unreachable, stored.State);
Assert.AreEqual(UnreachableReason.NotFound, stored.UnreachableReason);
Assert.AreEqual(0, bed.Breaker.Signals.Count, "A «not found» is not a stop signal.");
}
[TestMethod]
[DataRow(ScriptedReply.ServerError500, "(500)")]
[DataRow(ScriptedReply.ServerError503, "(503)")]
[DataRow(ScriptedReply.Timeout, "nessuna risposta in tempo")]
[DataRow(ScriptedReply.Unreachable, "collegamento non riuscito")]
[DataRow(ScriptedReply.TooLarge, "risposta troppo grande")]
[DataRow(ScriptedReply.Broken, "risposta rovinata")]
public async Task AnErrorOfTheSiteFailsTheRunWithoutRetrying(ScriptedReply reply, string said)
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(reply);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, outcome.Message);
StringAssert.Contains(outcome.Message, said);
Assert.AreEqual(1, bed.Scripted.Sent.Count, "Never tried again in the run.");
Assert.IsTrue((await bed.EventCodesAsync()).Contains("ricetta-fallita"));
Assert.AreEqual(0, bed.Breaker.Signals.Count, "One error is an empty page, not a signal.");
}
[TestMethod]
public async Task ThreeEmptyAnswersInARowAreAThrottle()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.ServerError500, ScriptedReply.ServerError500, ScriptedReply.ServerError500);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var third = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, third.Status, third.Message);
Assert.AreEqual(SignalLevel.Throttle, bed.Breaker.Signals.Single().Level);
}
[TestMethod]
public async Task AnAnswerNoReaderKnowsIsAnUnrecognizedFormat()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.UnknownShape);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, outcome.Status, outcome.Message);
Assert.IsTrue((await bed.EventCodesAsync()).Contains("formato-non-riconosciuto"));
}
[TestMethod]
public async Task ARefusedPermitSendsNothing()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Governor.Limit(ActionKind.ProfileOpen, 0);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Denied, outcome.Status);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
}
[TestMethod]
public async Task TheGapWaitsWhenThePermitOfItsPageIsRefused()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
bed.Governor.Limit(ActionKind.BackfillPage, 0);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, "The check itself is done.");
Assert.AreEqual(1, bed.Scripted!.Sent.Count);
Assert.AreEqual("n17", await bed.Db.Settings.GetAsync($"raccolta.lacuna.{Id(account)}.cursore"));
}
[TestMethod]
public async Task WithoutTheSiteClientEveryRecipeGoesByThePage()
{
await using var bed = await RequestBed.CreateAsync(requests: false);
var account = await bed.AddSampleAccountAsync();
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.IsTrue(bed.Page.Touched > 0);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.AreEqual(RecipeStatus.Failed, outcome.Status);
}
[TestMethod]
public async Task TheFollowingSweepNeverGoesByRequests()
{
await using var bed = await RequestBed.CreateAsync();
Assert.IsFalse(bed.Runner.HasRequestRoute(RecipeKind.FollowingSweep));
Assert.IsNull(RecipeRunner.RequestOperations(RequestCatalog.LoadTestSite(), RecipeKind.FollowingSweep));
}
[TestMethod]
public async Task TheDiagnosticReportSeesTheRequestsByShapeOnly()
{
var clock = new VirtualClock(new DateTimeOffset(2026, 10, 13, 16, 0, 0, TimeSpan.Zero));
long? current = null;
using var diagnostics = new CollectionDiagnostics(clock, () => current) { SiteMap = SiteMap.LoadTestSite() };
await using var bed = await RequestBed.CreateAsync(diagnostics: diagnostics, clock: clock);
current = bed.Session.SessionId;
diagnostics.SessionStarted(bed.Session.SessionId, clock.Now, 1.0);
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
await bed.RunAsync(RecipeKind.Highlight, account.Id, highlightId: "3688348931");
diagnostics.SessionEnded(bed.Session.SessionId, clock.Now, SessionOutcome.Completed, SessionStopCause.PlannedEnd, RecipeStatus.Completed);
using var stream = new MemoryStream();
DiagnosticReport.Write(stream, diagnostics.Collect(), new DiagnosticReportHeader("0.0.0-prove", "docker", clock.Now, TestZones.Rome));
var text = System.Text.Encoding.UTF8.GetString(stream.ToArray());
Assert.AreEqual(0, diagnostics.Faults);
StringAssert.Contains(text, "/api/graphql", "The request is there, by the shape of its path.");
StringAssert.Contains(text, "/api/{testo}/{testo}/{testo}", "The other requests too, by the shapes of their paths.");
foreach (var value in new[] { "ndkwq.shzgd", "3688348931", "n17", "c40", "5555", "TqwwCvG" })
{
Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), $"«{value}» is in the report.");
}
}
[TestMethod]
public async Task StoriesNotFoundAskTheProfileAndArePlainlyNoStoriesForAPublicOne()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
for (var i = 0; i < 3; i++)
{
bed.Scripted!.Then(ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
}
CollectionAssert.AreEqual(new[] { "storie", "ProvaProfiloQuery", "storie", "ProvaProfiloQuery", "storie", "ProvaProfiloQuery" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.StoryView, ActionKind.ProfileOpen }, bed.Governor.Requests.Take(2).Select(r => r.Kind).ToArray(), "The profile says why, as by the page.");
Assert.AreEqual(0, bed.Breaker.Signals.Count, "Three «not found» of the stories are not three empty pages.");
var stored = (await bed.Db.Accounts.GetAsync(account.Id))!;
Assert.AreNotEqual(AccountState.Unreachable, stored.State);
Assert.IsNotNull(stored.LastStoriesCheckAt);
}
[TestMethod]
public async Task StoriesNotFoundOfAProfileNotFoundMakeTheAccountUnreachable()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.NotFoundJson, ScriptedReply.NotFoundJson);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
Assert.AreEqual(UnreachableReason.NotFound, (await bed.Db.Accounts.GetAsync(account.Id))!.UnreachableReason);
}
[TestMethod]
public async Task AStoriesAnswerStartsTheCountOfEmptyPagesAgain()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.ServerError500, ScriptedReply.ServerError500);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var stories = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
bed.Scripted.Then(ScriptedReply.ServerError500);
var third = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, stories.Status, stories.Message);
Assert.AreEqual(RecipeStatus.Failed, third.Status, third.Message);
Assert.AreEqual(0, bed.Breaker.Signals.Count, "The stories in between were data: the count of empty pages started again.");
}
[TestMethod]
public async Task ASignalOnTheSecondPageOfTheHistoryKeepsThePointOfTheFirst()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { State = AccountState.Backfilling });
bed.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.TooManyRequests);
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 3);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(2, bed.Scripted.Sent.Count, "Nothing after the signal.");
Assert.AreEqual(SignalLevel.Throttle, bed.Breaker.Signals.Single().Level);
Assert.AreEqual("n17", (await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCursor, "The point of the last page saved.");
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count);
}
[TestMethod]
public async Task ASignalOnThePageOfTheGapKeepsTheGapPoint()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { BackfillCursor = "c40", State = AccountState.Backfilling });
bed.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.RedirectToLogin);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.StoppedBySignal, outcome.Status, outcome.Message);
Assert.AreEqual(2, bed.Scripted.Sent.Count);
Assert.AreEqual(SignalLevel.Challenge, bed.Breaker.Signals.Single().Level);
Assert.AreEqual("n17", await bed.Db.Settings.GetAsync($"raccolta.lacuna.{Id(account)}.cursore"));
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count, "The first page was saved before.");
}
[TestMethod]
public async Task ATrayOfItsOwnIsAskedOnceADayAfterTheFirstPage()
{
await using var bed = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var account = await bed.AddSampleAccountAsync();
var first = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
var second = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo", "ProvaProfiloQuery" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray());
CollectionAssert.AreEqual(new[] { ActionKind.ProfileOpen, ActionKind.ProfileOpen, ActionKind.ProfileOpen }, bed.Governor.Requests.Select(r => r.Kind).ToArray());
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count);
}
[TestMethod]
public async Task AManualCheckAsksNoTrayForAnAccountThatDoesNotWantItsCollections()
{
await using var bed = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var account = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes & ~ContentTypes.Highlights });
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id, manual: true);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual("ProvaProfiloQuery", bed.Scripted!.Sent.Single().Operation);
}
[TestMethod]
public async Task ATrayRefusedOrFailedLosesNotTheFirstPage()
{
await using var refused = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var one = await refused.AddSampleAccountAsync();
refused.Governor.Limit(ActionKind.ProfileOpen, 1);
var denied = await refused.RunAsync(RecipeKind.ProfileCheck, one.Id);
await using var failing = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var two = await failing.AddSampleAccountAsync();
failing.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.ServerError503);
var failed = await failing.RunAsync(RecipeKind.ProfileCheck, two.Id);
Assert.AreEqual(RecipeStatus.Completed, denied.Status, "The check is done; the list waits for the next one.");
Assert.IsNull(await refused.Db.Settings.GetAsync($"raccolte.vassoio.{Id(one)}"));
Assert.AreEqual(RecipeStatus.Failed, failed.Status, failed.Message);
foreach (var (bed, account) in new[] { (refused, one), (failing, two) })
{
Assert.AreEqual(12, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count, "The first page was saved before the list.");
}
}
[TestMethod]
public async Task ATrayTheReadersDoNotKnowIsAnUnrecognizedFormat()
{
await using var bed = await RequestBed.CreateAsync(catalog: TrayOfItsOwn());
var account = await bed.AddSampleAccountAsync();
bed.Scripted!.Then(ScriptedReply.Sample, ScriptedReply.UnknownShape);
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, outcome.Status, outcome.Message);
}
[TestMethod]
public async Task AStoredPointWithoutItsNextPageGoesByThePagesWhenTheyCanRun()
{
await using var bed = await RequestBed.CreateAsync();
var account = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
await bed.Db.Settings.SetAsync($"raccolta.taggati.{Id(account)}.cursore", "t12");
await bed.RunAsync(RecipeKind.Tagged, account.Id);
Assert.AreEqual(0, bed.Scripted!.Sent.Count);
Assert.IsTrue(bed.Page.Touched > 0, "The pages go on from the stored point.");
Assert.IsTrue((await bed.EventCodesAsync()).Contains("richieste-pagine-successive"));
}
[TestMethod]
public async Task AStoredPointWithoutItsNextPageStillReadsTheFirstPage()
{
var map = new SiteMap("prova", new Dictionary<string, string?> { [SitePages.Profile] = "/profilo/{username}/" }, [], SiteTargets.All);
await using var bed = await RequestBed.CreateAsync(map);
var account = await bed.AddSampleAccountAsync(a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
await bed.Db.Settings.SetAsync($"raccolta.taggati.{Id(account)}.cursore", "t12");
var outcome = await bed.RunAsync(RecipeKind.Tagged, account.Id);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.AreEqual(0, bed.Page.Touched);
var sent = bed.Scripted!.Sent.Single();
Assert.AreEqual("taggati", sent.Operation, "What is new on top is read.");
Assert.IsFalse(sent.Values.ContainsKey(CaseValues.Cursor));
Assert.AreEqual(3, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count);
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{Id(account)}.completo"), "The whole tab fits in its first page: it is complete.");
}
/// <summary>The test site's catalog with the list of collections asked by an operation of its own (the shape of Instagram's).</summary>
private static RequestCatalog TrayOfItsOwn()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
foreach (var operation in file["operations"]!.AsArray())
{
switch (operation!["name"]!.GetValue<string>())
{
case "ProvaProfiloQuery":
operation["roles"] = new JsonArray("profile", "posts");
break;
case "profilo":
operation["roles"] = new JsonArray("highlights");
break;
}
}
return RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json");
}
private static async Task<long> AddPostAsync(RequestBed bed, Account account, string instagramId, string? code)
{
var result = await bed.Db.Entries.AddAsync(
new Entry
{
AccountId = account.Id,
Kind = EntryKind.Post,
InstagramId = instagramId,
Code = code,
PublishedAt = bed.Clock.Now.AddDays(-3),
DiscoveredAt = bed.Clock.Now.AddDays(-3),
},
[]);
return result.Stored.Entry.Id;
}
private static string Id(Account account) => account.Id.ToString(CultureInfo.InvariantCulture);
}
@@ -0,0 +1,220 @@
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Engine;
using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// Which recipe goes by requests (issue #36, S3): the roles of the catalog, checked when it loads; on Instagram none,
/// so nothing changes there; the configuration tells which recipes go by requests and a new role changes its fingerprint.
/// </summary>
[TestClass]
public sealed class RequestRoutingTests
{
[TestMethod]
public void OnInstagramNoRecipeGoesByRequests()
{
var instagram = RequestCatalog.LoadInstagram();
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.IsNull(RecipeRunner.RequestOperations(instagram, kind), $"{kind}: every operation of Instagram is still not configured.");
}
// The roles are written all the same, waiting for S4.
Assert.AreEqual("PolarisProfilePageContentQuery", instagram.HolderOf(RequestRole.Profile)?.Name);
Assert.AreEqual("PolarisProfilePostsQuery", instagram.HolderOf(RequestRole.Posts)?.Name);
Assert.IsNull(instagram.HolderOf(RequestRole.PostsNext), "The posts query of the HAR has no cursor.");
Assert.AreEqual(ActionKind.ProfileOpen, instagram.HolderOf(RequestRole.Posts)!.FirstPageCategory);
Assert.IsNull(instagram.HolderOf(RequestRole.Following), "No shapes of the following list yet.");
}
[TestMethod]
public async Task OnInstagramTheRunnerRefusesAsBefore()
{
var instagram = RequestCatalog.LoadInstagram();
var map = InstagramMap();
await using var withClient = await RequestBed.CreateAsync(map, instagram);
await using var without = await RequestBed.CreateAsync(map, instagram, requests: false);
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.IsFalse(withClient.Runner.HasRequestRoute(kind), kind.ToString());
Assert.AreEqual(without.Runner.NotConfiguredReason(kind), withClient.Runner.NotConfiguredReason(kind), kind.ToString());
}
}
[TestMethod]
public async Task TheEngineChecksTheBudgetOfTheFirstRequestOfTheRoute()
{
await using var byRequests = await RequestBed.CreateAsync();
await using var byPages = await RequestBed.CreateAsync(requests: false);
await using var instagram = await RequestBed.CreateAsync(InstagramMap(), RequestCatalog.LoadInstagram());
// Taggati and Reel by requests start with a page of the tab, not with the profile.
Assert.AreEqual(ActionKind.BackfillPage, byRequests.Runner.FirstCategory(RecipeKind.Tagged));
Assert.AreEqual(ActionKind.BackfillPage, byRequests.Runner.FirstCategory(RecipeKind.Reels));
foreach (var kind in Enum.GetValues<RecipeKind>())
{
Assert.AreEqual(CheckPolicy.CategoryOf(kind), byPages.Runner.FirstCategory(kind), kind.ToString());
Assert.AreEqual(CheckPolicy.CategoryOf(kind), instagram.Runner.FirstCategory(kind), $"{kind}: Instagram as before.");
if (kind is not (RecipeKind.Tagged or RecipeKind.Reels))
{
Assert.AreEqual(CheckPolicy.CategoryOf(kind), byRequests.Runner.FirstCategory(kind), kind.ToString());
}
}
}
[TestMethod]
public async Task ARecipeByRequestsNeedsNoPageOfTheMap()
{
var empty = new SiteMap("prova", new Dictionary<string, string?>(), [], SiteTargets.All);
await using var bed = await RequestBed.CreateAsync(empty);
Assert.IsNull(bed.Runner.NotConfiguredReason(RecipeKind.ProfileCheck));
Assert.IsNull(bed.Runner.NotConfiguredReason(RecipeKind.AccountStories));
Assert.IsNotNull(bed.Runner.NotConfiguredReason(RecipeKind.FollowingSweep), "The sweep needs the home page.");
}
[TestMethod]
public void OnTheTestSiteEveryRecipeButTheSweepGoesByRequests()
{
var prova = RequestCatalog.LoadTestSite();
string[]? Names(RecipeKind kind) => RecipeRunner.RequestOperations(prova, kind)?.Select(o => o.Name).ToArray();
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, Names(RecipeKind.ProfileCheck));
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery", "profilo-altri" }, Names(RecipeKind.Backfill));
CollectionAssert.AreEqual(new[] { "taggati" }, Names(RecipeKind.Tagged), "No next pages of the tagged posts: their answer has them all.");
CollectionAssert.AreEqual(new[] { "reel" }, Names(RecipeKind.Reels));
CollectionAssert.AreEqual(new[] { "storie" }, Names(RecipeKind.AccountStories));
CollectionAssert.AreEqual(new[] { "evidenza" }, Names(RecipeKind.Highlight));
CollectionAssert.AreEqual(new[] { "post" }, Names(RecipeKind.SinglePost));
CollectionAssert.AreEqual(new[] { "seguiti" }, Names(RecipeKind.FollowingList), "One operation, the first page and the next.");
Assert.IsNull(Names(RecipeKind.FollowingSweep));
}
[TestMethod]
public void TheFirstPageOfTheGridCountsAsTheProfile()
{
var instagram = RequestCatalog.LoadInstagram();
var posts = instagram.HolderOf(RequestRole.Posts)!;
Assert.AreEqual(ActionKind.BackfillPage, posts.Category);
Assert.AreEqual(ActionKind.ProfileOpen, posts.CategoryFor(new SiteRequest(posts.Name, new Dictionary<string, string> { [CaseValues.AccountId] = "5555" })));
}
[TestMethod]
public void TheGuardWantsThePermitOfTheCategoryOfTheRequest()
{
// ProvaProfiloQuery counts as a profile; profilo-altri, with its cursor, as a page of history.
var prova = RequestCatalog.LoadTestSite();
var spent = new SpentPermits();
var next = new SiteRequest("profilo-altri", new Dictionary<string, string> { [CaseValues.Username] = "marta.prova", [CaseValues.Cursor] = "c12" });
var refusal = Assert.ThrowsExactly<SiteRequestRefusedException>(() => SiteRequestGuard.Check(prova, next, Permit.Grant(ActionKind.ProfileOpen, null), spent));
StringAssert.Contains(refusal.Message, "conta come");
Assert.AreEqual("profilo-altri", SiteRequestGuard.Check(prova, next, Permit.Grant(ActionKind.BackfillPage, null), spent).Name);
}
[TestMethod]
[DataRow("[\"seguiti-di-qualcuno\"]", "sconosciuto")]
[DataRow("[\"posts-next\"]", "va da una pagina alla successiva")]
[DataRow("[null]", "sconosciuto")]
public void ARoleThatCannotBeIsRefusedWhenTheCatalogLoads(string roles, string said)
{
var operation = Rest("post-in-piu", "/api/dati/post-in-piu/{code}");
operation["roles"] = JsonNode.Parse(roles);
StringAssert.Contains(Refuse(Alone(operation)), said);
}
[TestMethod]
public void AFirstPageRoleOnAnOperationThatAlwaysWantsACursorIsRefused()
{
var operation = Rest("altri-in-piu", "/api/dati/altri-in-piu");
operation["parameters"] = new JsonObject { ["dopo"] = "{cursor}" };
operation["roles"] = new JsonArray("posts");
StringAssert.Contains(Refuse(Alone(operation)), "prima pagina");
}
[TestMethod]
public void ARoleOfTwoOperationsIsRefused()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
var second = Rest("post-due", "/api/dati/post-due/{code}");
second["roles"] = new JsonArray("post");
file["operations"]!.AsArray().Add(second);
StringAssert.Contains(Refuse(file.ToJsonString()), "un ruolo appartiene a una sola operazione");
}
[TestMethod]
public void ASearchHasNoRoleAndTheFirstPageCategoryIsOnlyForTheHistory()
{
var search = Rest("cerca-in-piu", "/api/dati/cerca-in-piu");
search["category"] = "ricerca";
search["parameters"] = new JsonObject { ["testo"] = "{search_text}" };
search["roles"] = new JsonArray("profile");
StringAssert.Contains(Refuse(Alone(search)), "una ricerca non ha ruoli");
var post = Rest("post-in-piu", "/api/dati/post-in-piu/{code}");
post["firstPageCategory"] = "profilo";
StringAssert.Contains(Refuse(Alone(post)), "solo per un'operazione della categoria «storico»");
var history = Rest("storico-in-piu", "/api/dati/storico-in-piu/{username}");
history["category"] = "storico";
history["firstPageCategory"] = "post";
StringAssert.Contains(Refuse(Alone(history)), "ammette solo «profilo»");
}
[TestMethod]
public void ARoleOfAnOperationNotConfiguredGivesNoRoute()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
var stories = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == "storie")!.AsObject();
stories["configured"] = false;
stories["reason"] = "prova";
var catalog = RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json");
Assert.IsNull(catalog.ForRole(RequestRole.Stories));
Assert.AreEqual("storie", catalog.HolderOf(RequestRole.Stories)?.Name);
Assert.IsNull(RecipeRunner.RequestOperations(catalog, RecipeKind.AccountStories));
}
[TestMethod]
public void TheConfigurationSaysWhichRecipesGoByRequests()
{
var vocabulary = ReaderVocabulary.LoadTestSite();
var empty = new SiteMap("prova", new Dictionary<string, string?>(), [], SiteTargets.All);
var without = CollectionConfiguration.Describe("prova", vocabulary, empty);
var with = CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadTestSite());
Assert.AreEqual(Enum.GetValues<RecipeKind>().Length, without.Blocked.Count, "Without pages nothing runs by the browser.");
CollectionAssert.AreEqual(new[] { RecipeKind.FollowingSweep }, with.Blocked.ToArray(), "Only the sweep needs the pages.");
CollectionAssert.Contains(with.Lines.ToList(), "Controllo del profilo: per richieste (ProvaProfiloQuery, profilo-altri).");
Assert.IsFalse(without.Lines.Any(l => l.Contains("per richieste", StringComparison.Ordinal)));
Assert.AreNotEqual(without.Fingerprint, with.Fingerprint, "A new route clears the suspensions too.");
Assert.AreEqual(without.Fingerprint, CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadInstagram()).Fingerprint, "No route: the fingerprint of before.");
Assert.AreEqual(0, CollectionConfiguration.Describe("prova", vocabulary, empty, RequestCatalog.LoadInstagram()).ByRequests.Count);
}
private static SiteMap InstagramMap() => SiteMap.LoadEmbedded("bersagli.instagram.json");
private static string Refuse(string json) =>
Assert.ThrowsExactly<InvalidDataException>(() => RequestCatalog.Parse(json, "richieste.prova.json")).Message;
private static string Alone(JsonObject operation) =>
new JsonObject { ["site"] = "prova", ["operations"] = new JsonArray(operation) }.ToJsonString();
private static JsonObject Rest(string name, string path) => new()
{
["name"] = name,
["kind"] = "rest",
["method"] = "GET",
["path"] = path,
["category"] = "post",
["configured"] = true,
["headers"] = new JsonObject { ["user-agent"] = "session:user_agent" },
["rootFields"] = new JsonArray("contenuto"),
["sample"] = "000005-post-serie",
};
}
@@ -0,0 +1,176 @@
using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Data;
using Febe.Tests.Support;
using RecordingBreaker = Febe.Tests.Browser.TestSupport.RecordingBreaker;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection.Support;
/// <summary>
/// A page that must never be touched: the recipes by requests do not use it (issue #36, S3). Every call is counted
/// and fails.
/// </summary>
public sealed class NoPageDriver : IPageDriver
{
private int _touched;
/// <summary>Calls received (each one failed).</summary>
public int Touched => Volatile.Read(ref _touched);
public double WaitMultiplier => 1.0;
/// <summary>Counted, not failed: it comes before the run, where a failure would not be the run's.</summary>
public void BeginSession(double mood) => Interlocked.Increment(ref _touched);
public Task<PageLoad> OpenAsync(string path, CancellationToken ct) => Touch<PageLoad>();
public Task<string> CurrentPathAsync(CancellationToken ct) => Touch<string>();
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Touch<bool>();
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => Touch<TargetCheck>();
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => Touch<TargetCheck>();
public Task ScrollBurstAsync(CancellationToken ct) => Touch<bool>();
public Task WaitAfterLoadAsync(CancellationToken ct) => Touch<bool>();
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Touch<bool>();
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Touch<bool>();
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Touch<bool?>();
public Task RestAsync(CancellationToken ct) => Touch<bool>();
private void Touch()
{
Interlocked.Increment(ref _touched);
throw new InvalidOperationException("La pagina è stata toccata da una ricetta per richieste.");
}
private Task<T> Touch<T>()
{
Touch();
return Task.FromResult<T>(default!);
}
}
/// <summary>
/// The recipes by requests without a browser (issue #36, S3): the runner of the test site's readers and map, with a
/// site client (<see cref="ScriptedRequester"/> by default) and a page that must never be touched.
/// </summary>
internal sealed class RequestBed : IAsyncDisposable
{
private readonly ConcurrentQueue<string> _warnings = new();
private RequestBed(TempFolder temp, FebeDatabase db, VirtualClock clock, NoPageDriver page, ISiteRequester requester, PermissiveGovernor governor, RecordingBreaker breaker, RecipeRunner runner, TestSession session)
{
Temp = temp;
Db = db;
Clock = clock;
Page = page;
Requester = requester;
Governor = governor;
Breaker = breaker;
Runner = runner;
Session = session;
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; }
public VirtualClock Clock { get; }
public NoPageDriver Page { get; }
public ISiteRequester Requester { get; }
/// <summary>The scripted site client (null when the bed runs on another one).</summary>
public ScriptedRequester? Scripted => Requester as ScriptedRequester;
public PermissiveGovernor Governor { get; }
public RecordingBreaker Breaker { get; }
public RecipeRunner Runner { get; }
public TestSession Session { get; }
public IReadOnlyList<string> Warnings => [.. _warnings];
/// <param name="map">The map of the site; the test site's by default (every recipe could also go by the pages).</param>
/// <param name="catalog">The catalog; the test site's by default.</param>
/// <param name="requester">The site client; a <see cref="ScriptedRequester"/> on the cleaned samples by default.</param>
/// <param name="diagnostics">The recorder of the diagnostic report, when the test reads it.</param>
/// <param name="requests">False: no site client at all (every recipe by the page).</param>
public static async Task<RequestBed> CreateAsync(SiteMap? map = null, RequestCatalog? catalog = null, ISiteRequester? requester = null, CollectionDiagnostics? diagnostics = null, bool requests = true, VirtualClock? clock = null)
{
var temp = new TempFolder("ricette-richieste");
var db = await TestDatabase.OpenAsync(temp);
clock ??= new VirtualClock(new DateTimeOffset(2026, 10, 13, 16, 0, 0, TimeSpan.Zero));
catalog ??= RequestCatalog.LoadTestSite();
requester ??= new ScriptedRequester(catalog) { SessionCookie = "sessione_prova" };
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock) { Diagnostics = diagnostics };
var page = new NoPageDriver();
var breaker = new RecordingBreaker();
var governor = new PermissiveGovernor();
RequestBed? bed = null;
var runner = new RecipeRunner(new RecipeEnvironment
{
Driver = page,
Capture = capture,
Governor = governor,
Budget = governor,
Signals = new SignalDetector(SignalRules.LoadTestSite(), breaker, clock),
Storage = db,
SiteMap = map ?? SiteMap.LoadTestSite(),
Clock = clock,
Random = new SeededRandom(7),
Breaker = breaker,
Diagnostics = diagnostics,
Requests = requests
? new SiteRequestEnvironment(requester, catalog, new SiteAnswerSignals(SignalRules.LoadTestSite(), "sessione_prova"), Warn: m => bed?._warnings.Enqueue(m))
: null,
});
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
bed = new RequestBed(temp, db, clock, page, requester, governor, breaker, runner, session);
return bed;
}
/// <summary>The account of the samples: «numero» 5555 (marta.prova on the site, a fake name in the samples).</summary>
public Task<Account> AddSampleAccountAsync(Func<Account, Account>? change = null) => AddAccountAsync("5555", "ndkwq.shzgd", change);
public Task<Account> AddAccountAsync(string? instagramId, string username, Func<Account, Account>? change = null, bool isMine = false)
{
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome, isMine: isMine) with
{
InstagramId = instagramId,
IsFollowed = !isMine,
};
return Db.Accounts.AddAsync(change is null ? account : change(account));
}
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, long? entryId = null, string? highlightId = null, int? maxPages = null, bool manual = false) =>
Runner.RunAsync(new RecipeRequest(kind, accountId, entryId, highlightId, maxPages, manual), Session, CancellationToken.None);
public async Task<IReadOnlyList<string>> EventCodesAsync() =>
[.. (await Db.Events.ListAsync(new Febe.Core.Storage.EventQuery())).Select(e => e.Code)];
public async ValueTask DisposeAsync()
{
(Requester as IDisposable)?.Dispose();
await Db.DisposeAsync();
Temp.Dispose();
}
}
@@ -29,6 +29,33 @@ public enum ScriptedReply
/// <summary>The sample, with the session cookie deleted by the site.</summary>
SessionCookieDeleted,
/// <summary>A 404 with the JSON of the test site («non-trovato»): the resource is not there (H19).</summary>
NotFoundJson,
/// <summary>A 500 with JSON: an error of the site.</summary>
ServerError500,
/// <summary>A 503 with JSON: the site is not available.</summary>
ServerError503,
/// <summary>No answer in time (<see cref="SiteUnreachableReason.Timeout"/>).</summary>
Timeout,
/// <summary>No connection (<see cref="SiteUnreachableReason.Unreachable"/>).</summary>
Unreachable,
/// <summary>An answer larger than allowed (<see cref="SiteUnreachableReason.TooLarge"/>).</summary>
TooLarge,
/// <summary>A body that cannot be decoded (<see cref="SiteUnreachableReason.Broken"/>).</summary>
Broken,
/// <summary>
/// A 200 with JSON that no reader recognizes (the body of the sample «forma-sconosciuta»), said to have the expected
/// fields: what a site that changed its format inside the same fields would send.
/// </summary>
UnknownShape,
}
/// <summary>
@@ -140,6 +167,23 @@ public sealed class ScriptedRequester : ISiteRequester
return new SiteAnswer(operation, 302, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: ChallengeLocation);
case ScriptedReply.HtmlInsteadOfJson:
return new SiteAnswer(operation, 200, "text/html; charset=utf-8", Encoding.UTF8.GetBytes("<!DOCTYPE html><html><head><title>Pagina</title></head><body></body></html>"));
case ScriptedReply.NotFoundJson:
return new SiteAnswer(operation, 404, "application/json", Encoding.UTF8.GetBytes("{\"errore\":\"non-trovato\"}"), rootFieldsPresent: false);
case ScriptedReply.ServerError500 or ScriptedReply.ServerError503:
return new SiteAnswer(operation, reply == ScriptedReply.ServerError500 ? 500 : 503, "application/json", Encoding.UTF8.GetBytes("{\"errore\":\"interno\"}"), rootFieldsPresent: false);
case ScriptedReply.Timeout or ScriptedReply.Unreachable or ScriptedReply.TooLarge or ScriptedReply.Broken:
var reason = reply switch
{
ScriptedReply.Timeout => SiteUnreachableReason.Timeout,
ScriptedReply.TooLarge => SiteUnreachableReason.TooLarge,
ScriptedReply.Broken => SiteUnreachableReason.Broken,
_ => SiteUnreachableReason.Unreachable,
};
throw new SiteUnreachableException($"«{operation.Name}» ({operation.PathShape}): nessuna risposta (prova).", reason);
case ScriptedReply.UnknownShape:
var unknown = Directory.EnumerateFiles(_samples, "*-forma-sconosciuta.json").Single();
var corpo = JsonNode.Parse(File.ReadAllText(unknown))!["corpo"]!;
return new SiteAnswer(operation, 200, "application/json", Encoding.UTF8.GetBytes(corpo.ToJsonString()), rootFieldsPresent: true);
}
var (mime, body) = Sample(operation);
@@ -41,6 +41,19 @@ public sealed class EngineSettingsTests
Assert.AreEqual(GesturePace.Slow, effective.Pace);
}
[TestMethod]
public void AStoryViewIsARequestOrAStoryShownAndItsBudgetsStayAsTheyWere()
{
// Issue #36, S3: by requests one StoryView brings every story of an account. The budgets do not change in S3,
// so that Instagram (still by the pages) and a saved «Su misura» behave as before; halving them is a question
// for Alberto when Instagram goes by requests (S4).
Assert.AreEqual(new Budget(50, 300), CautionProfile.Prudent.Budgets[ActionKind.StoryView]);
Assert.AreEqual(new Budget(80, 500), CautionProfile.Balanced.Budgets[ActionKind.StoryView]);
Assert.AreEqual(new Budget(120, 800), CautionProfile.Fast.Budgets[ActionKind.StoryView]);
Assert.AreEqual(new Budget(240, 1600), CautionProfile.Limits.MaxBudget(ActionKind.StoryView), "«Su misura» stays within twice «Rapido».");
Assert.IsTrue(CautionProfile.Prudent.Budgets[ActionKind.StoryView].PerHour >= new Febe.Core.Collection.Recipes.RecipeOptions().MinStoryBudget, "The viewer still has room for its minimum of stories.");
}
[TestMethod]
public void TheLimitsOfTheInterfaceAreEnforced()
{
@@ -37,6 +37,7 @@ public sealed class EngineSimulationTests
Assert.IsTrue(report.FollowedPosts.Count > 0 && report.Stories.Count > 0);
var text = report.ToText();
StringAssert.Contains(text, "Raccolta: per pagine");
StringAssert.Contains(text, "Sessioni");
StringAssert.Contains(text, "superamenti dei tetti: 0");
StringAssert.Contains(text, "Storico di 2.000 post");
@@ -159,6 +160,29 @@ public sealed class EngineSimulationTests
StringAssert.Contains(problem, "Durata non valida");
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--profilo", "spericolato"], out _, out _, out problem));
StringAssert.Contains(problem, "Profilo sconosciuto");
Assert.AreEqual(SimulatedCollection.Pages, options.Collection, "By the pages unless asked.");
Assert.IsTrue(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta", "richieste"], out options, out _, out _));
Assert.AreEqual(SimulatedCollection.Requests, options.Collection);
Assert.IsTrue(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta", "PAGINE"], out options, out _, out _));
Assert.AreEqual(SimulatedCollection.Pages, options.Collection);
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta", "browser"], out _, out _, out problem));
StringAssert.Contains(problem, "Raccolta sconosciuta");
Assert.IsFalse(Febe.Server.SimulateCommand.TryParse(["--simula", "7g", "--raccolta"], out _, out _, out problem));
StringAssert.Contains(problem, "pagine o richieste");
}
[TestMethod]
[DataRow(CautionProfileKind.Prudent)]
[DataRow(CautionProfileKind.Fast)]
public async Task ByRequestsEveryProfileRunsAWeekWithoutExceedingAnyBudget(CautionProfileKind profile)
{
var report = await SimulateAsync(new SimulationOptions { Days = 7, Profile = profile, Seed = 3, Collection = SimulatedCollection.Requests });
Assert.AreEqual(0, report.Overruns, string.Join('\n', report.OverrunDetails));
Assert.AreEqual(0, report.OverrunsOfFullBudgets);
Assert.AreEqual(SimulatedCollection.Requests, report.Collection);
Assert.IsTrue(report.Stories.Count > 0);
StringAssert.Contains(report.ToText(), "Raccolta: per richieste");
}
[TestMethod]
@@ -0,0 +1,303 @@
{
"descrittore": {
"indirizzo": "https://sito.esempio/v04262087535s0f2",
"host": "sito",
"stato": 200,
"tipo": "application/json",
"risorsa": "Fetch",
"nome": "jjrv"
},
"corpo": {
"profilo": {
"numero": "6104",
"nome": "lmxm.bgwrl",
"nome_visibile": "Cjtw dm vcgnm",
"riservato": false,
"seguito": true,
"pubblicazioni": 40,
"ritratto": [
{
"indirizzo": "https://cdn.esempio/p8855g33lq2s9v52.jpg",
"larghezza": 160,
"altezza": 160
},
{
"indirizzo": "https://cdn.esempio/nlq76dk085829116.jpg",
"larghezza": 320,
"altezza": 320
}
],
"ultima_storia": "2026-11-17T06:20:50Z"
},
"contenuti": [
{
"numero": "3307625433",
"sigla": "NwpTxtz",
"pubblicato": "2026-11-10T06:13:50Z",
"testo": "Bdx djbkzfsr hpm ktdf p ntrhtlsz (jlfwr 011)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/1wd611jk1xg90749.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/d8079rp6gf80595g.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/84631st7z73l008q.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/4f795888602n3h07.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/3z5fh589r44m47zz.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "7636047358",
"sigla": "ggjzj36",
"pubblicato": "2026-10-27T21:53:50Z",
"testo": "Dkv xgbrknvm xdd ftdjs j ljmmhnwv (cvcpx 007)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/224tf439x5s4c59k.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/69t401224hm89m1l.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/44293bx83x1dw7f6.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/1mn2311sdc76p87h.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/2f867265k4p5l0v5.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "9348053577",
"sigla": "Gwbqppb",
"pubblicato": "2026-10-14T10:49:50Z",
"testo": "Ztd nkjswztq xls zdhwt t gmbfq (sxsqw 417)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/35704l4g0559r58q.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/1b587kf45j81gk4f.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/g79397sdpfn50x0r.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/x4n2dx8673g342x1.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/8985j1wr34x84849.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "4035845102",
"sigla": "M5H2bQT",
"pubblicato": "2026-10-01T00:35:50Z",
"testo": "Jwn kdfkwwfm lmr zpqbfcvm h bjktt (nlqnl 255)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/8zh874cdcx04tff8.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/bfrk6607ldvk32n2.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/55k9nq42k31jr893.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/16w43gtnlzm0q58x.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/14vl6121g262v1nd.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "9155303648",
"sigla": "GzsddRB",
"pubblicato": "2026-09-17T15:37:50Z",
"testo": "Wjc pdhmvhnq tck zpnck l mbrnvzl (tqzsl 788)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/6802c23jp6p19484.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/q0838jr29lq3lts4.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/7n25023gxnh73rr6.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/838x1873s39ms1b6.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/9002037p2f62b9f2.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
},
{
"numero": "2197000011",
"sigla": "rNXQsSw",
"pubblicato": "2026-09-04T06:04:50Z",
"testo": "Bdr nkwchshs fxz mbcksz m vjcrnjtvj (zkmxc 371)",
"fissato": false,
"autore": {
"numero": "6104",
"nome": "lmxm.bgwrl"
},
"filmati": [
{
"indirizzo": "https://cdn.esempio/p3sg00r501w85896.mp4",
"larghezza": 360,
"altezza": 640,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/87dn2d97x928m441.mp4",
"larghezza": 720,
"altezza": 1280,
"audio": true
},
{
"indirizzo": "https://cdn.esempio/9w92bz978k9r919t.mp4",
"larghezza": 1080,
"altezza": 1920,
"audio": false
}
],
"foto": [
{
"indirizzo": "https://cdn.esempio/1b8xkqt7l4jq0s70.jpg",
"larghezza": 360,
"altezza": 640
},
{
"indirizzo": "https://cdn.esempio/2r5c33rw538h5460.jpg",
"larghezza": 720,
"altezza": 1280
}
],
"durata": 2
}
],
"pagina": {
"altro": false,
"dopo": null
}
}
}
@@ -26,3 +26,7 @@ controllano forme, dimensioni, date e conteggi, non i valori.
| `000009-taggati` | scheda «Taggati» di un profilo |
| `000010-pagina-vuota` | pagina di dati vuota |
| `000011-forma-sconosciuta` | risposta di forma sconosciuta |
| `000012-reel` | scheda «Reel» di un profilo (tappa S3 di #36), scritto dopo gli altri con lo stesso percorso: i suoi valori finti non sono quelli degli altri campioni |
Del Reel non c'è la pagina successiva: nel sito di prova i reel di ogni account (al più 6) stanno nella prima pagina,
che ne porta 12, e `altro` è sempre falso. Per questo `richieste.prova.json` non ha un'operazione `reel-altri`.
+6 -1
View File
@@ -75,7 +75,12 @@ static async Task<int> DumpSamplesAsync(string[] args)
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}.");
site.Control.Set(StopMode.Normal);
// 000011 is «forma-sconosciuta», written by hand. The reels of every account fit in one page (12): no next page.
number++;
await WriteSampleAsync(folder, ++number, "reel", site.Url($"/dati/profilo/{luca}?scheda=reel"), 200, JsonNode.Parse(await site.GetDataAsync($"/dati/profilo/{luca}?scheda=reel")));
Console.WriteLine($"Scritti {(number - 1).ToString(CultureInfo.InvariantCulture)} campioni grezzi in {folder} (il numero 11 si scrive a mano).");
return 0;
}