Instagram: Febe legge le risposte vere (campioni dal HAR del 21 ottobre) #11
No files matched your search
@@ -2,8 +2,36 @@
|
||||
|
||||
## 0.1.2 (in preparazione)
|
||||
|
||||
Correzioni:
|
||||
|
||||
- **Febe legge le risposte vere di Instagram.** Instagram manda i dati di storie e raccolte come `text/javascript`, e
|
||||
Febe leggeva solo le risposte dichiarate JSON: le scartava tutte. Ora legge anche quelle (mai i file di script) e il
|
||||
JSON che la pagina porta con sé. I lettori sono scritti sulle risposte che il browser di Alberto ha ricevuto il 21
|
||||
ottobre, ripulite, e il vocabolario di Instagram è «confermato».
|
||||
- La mappa di Instagram ha le pagine viste nel traffico vero (home, profilo, post, storie, raccolte): girano giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Storie, raccolte e schede Taggati e Reel aspettano i bersagli
|
||||
dei comandi, che si raccolgono con la nuova procedura «A bis» di `docs/prove-dal-vivo.md`.
|
||||
- Le risposte che non parlano di contenuti (promozioni, «storia vista», registri) non fermano più le ricette come
|
||||
«formato non riconosciuto».
|
||||
- Le ricette del profilo prendono intestazione, griglia e raccolte anche quando arrivano in risposte diverse, e uno
|
||||
storico non si chiude più per il «non ce n'è altro» di una risposta che parla d'altro. L'elenco dei seguiti non salva
|
||||
i profili suggeriti.
|
||||
- Il visualizzatore delle raccolte funziona anche se l'indirizzo non dice quale contenuto è a video, e si chiude
|
||||
sempre, anche dopo un errore imprevisto.
|
||||
- Una ricetta che la configurazione non lascia girare risulta «Da configurare»: non conta più come guasto, non viene
|
||||
sospesa e non si ripianifica. Al primo avvio con i file nuovi le ricette sospese per colpa dei file vecchi ripartono
|
||||
da sole, con una riga in Attività.
|
||||
- Barra laterale: dice «Collegato» quando il cookie di sessione c'è, anche se il nome dell'account non è ancora noto.
|
||||
- «Post singolo»: i controlli accodati per recuperare un indirizzo scaduto o completare una serie non vengono più
|
||||
annullati dalla coda prima di partire.
|
||||
|
||||
Sviluppo e qualità:
|
||||
|
||||
- `febe-sonda da-har`: un HAR esportato dal browser diventa campioni grezzi da ripulire con `ripulisci` e
|
||||
`verifica`; `tools/bersagli/raccogli-bersagli.js` raccoglie in sola lettura ruolo e nome dei comandi.
|
||||
- La ripulitura tiene `latest_reel_media` come data e mette un riempitivo neutro sotto le chiavi che sembrano segreti,
|
||||
così gitleaks non scambia i dati finti per segreti veri.
|
||||
|
||||
- Prove dell'interfaccia senza attese a tempo fisso (#8): le risposte in ritardo si trattengono finché la prova non le
|
||||
rilascia, e ciò che non deve succedere si controlla quando la pagina ha finito le sue richieste. Restano verdi anche
|
||||
con Chrome rallentato 20 volte.
|
||||
|
||||
@@ -6,7 +6,7 @@ Febe non costruisce richieste verso Instagram: usa un browser vero, in cui Alber
|
||||
|
||||
> Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il rischio per l'account, ma non può azzerarlo.
|
||||
|
||||
**Stato: versione 0.1.1, anteprima.** Il programma è completo e provato contro un sito di prova locale; prima di usarlo su Instagram serve la sonda di M0 (vedi [docs/stato.md](docs/stato.md)).
|
||||
**Stato: versione 0.1.1, anteprima.** Il programma è completo e provato contro un sito di prova locale. Dal 25 ottobre 2026 legge le risposte vere di Instagram (lettori scritti su risposte reali ripulite); storie e raccolte aspettano i bersagli dei comandi, e nulla è ancora stato provato dal vivo (vedi [docs/stato.md](docs/stato.md)).
|
||||
|
||||
## Documenti
|
||||
|
||||
|
||||
@@ -293,3 +293,23 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-10-21 | Il lavoro «controlli» legge anche gli script Node della CI (`node --check .gitea/scripts/*.js`) | Come `bash -n` per gli script di shell: un errore di sintassi in `versioni-registro.js` si vede in pochi secondi, non alla pulizia del lunedì |
|
||||
| 2026-10-21 | Nei modi «settimanale» e «completa» la pulizia legge lo store delle immagini del demone (`docker info --format '{{json .DriverStatus}}'`: con `io.containerd.snapshotter.v1` è quello di containerd, altrimenti il classico) e lo scrive all'inizio; con containerd, o se non lo sa, la prova avverte che le età che elenca sono solo indicative | Da quando contano le 24 ore di `image prune --filter until` dipende dallo store (rilievo della revisione). Con quello classico Docker confronta il `Created` della configurazione, cioè la costruzione (moby, `daemon/images/image_prune.go`: `img.Created.After(until)`); con quello di containerd il `CreatedAt` del record dell'immagine sul demone (`daemon/containerd/image_list.go`: `image.CreatedAt.Before(until)`), che containerd conserva quando lo stesso nome viene riscaricato. Nessun comando mostra quel `CreatedAt` (`docker image ls` dà il `Created` della configurazione anche con containerd), quindi la prova resta sull'età dalla costruzione e lo dice. Lo store di containerd è il predefinito nelle installazioni nuove di Docker Engine dalla 29; su Unraid è più probabile quello classico. `docker info` solo legge |
|
||||
| 2026-10-21 | Della pulizia del lunedì si dice anche che cosa `image prune -a` toglie alle immagini che un contenitore usa: i nomi in più. La pulizia vera confronta i nomi prima e dopo e scrive, nome per nome, quelli tolti a un'immagine che resta; la prova li stima secondo lo store (classico: tutti tranne l'ultimo in ordine alfabetico del nome completo, `docker.io/library/…` per Docker Hub; containerd: tutti tranne quelli da cui i contenitori sono stati creati, e l'ultimo se un contenitore la usa per identificativo). Il comando resta quello chiesto | Rilievo della revisione: la prova saltava ogni immagine in uso, e i documenti dicevano che un'immagine usata da un contenitore non si tocca. Docker non toglie l'immagine, ma con lo store classico `ImagesPrune` non guarda i contenitori e chiama `ImageDelete` senza forza su ogni riferimento, in ordine alfabetico (`daemon/images/image_prune.go`, uguale in moby v24.0.9, v27.5.1 e master; `reference/store.go`, `lexicalRefs`); `ImageDelete` rifiuta solo l'ultimo riferimento di un'immagine in uso (`image_delete.go`, `isSingleReference`), quindi può sparire proprio il nome da cui il contenitore è stato creato (un'applicazione di Unraid creata da `app:1.2` che si chiama anche `app:latest`). Con containerd `filterImagesUsedByContainers` protegge solo il nome di `Config.Image` e, se il contenitore usa l'immagine per identificativo o digest, l'ultimo nome (`daemon/containerd/image_prune.go`). Il demone finto delle prove fa lo stesso con l'uno e con l'altro store |
|
||||
| 2026-10-25 | I primi campioni reali di Instagram vengono dal file HAR che Alberto ha esportato dal suo browser il 21 ottobre (DevTools, filtro Fetch/XHR), non dalla sonda: le sole risposte utili sono state convertite nel formato grezzo della sonda in una cartella temporanea fuori dal repository, accorciate dal lato grezzo (raccolte: 2 per 4 contenuti, scelti fra foto, video con audio e video senza; pagina successiva: 1 per 3; profili suggeriti: i primi 3), ripulite con `febe-sonda ripulisci` e controllate con `febe-sonda verifica` («Verifica superata»). Del HAR si è letta solo la forma (percorsi, tipi, chiavi), mai valori, intestazioni o cookie; i grezzi convertiti si cancellano a fine lavoro | Richiesta di Alberto del 25 ottobre («vedi tu quale ti risulta più utile»: HAR o guida). La guida descrive richieste costruite a mano verso l'API, con intestazioni copiate, vietate dalle regole 2–4 di §2, e un formato (`GraphImage`, `edge_sidecar_to_children`) che nel HAR non compare: non si usa. Il HAR invece è ciò che la pagina riceve davvero, cioè il campione reale che chiede la regola 10. Accorciare dal lato grezzo tiene i campioni piccoli senza cambiarne la forma; la ripulitura costruisce l'elenco dei frammenti sensibili da tutto il grezzo, quindi accorciare dopo non servirebbe |
|
||||
| 2026-10-25 | La cattura legge come dati anche le risposte `text/javascript` (e ogni tipo che contiene «javascript») che la pagina chiede da sé (risorsa XHR o Fetch), oltre a quelle dichiarate JSON; i file di script non si leggono mai. Una sola regola, `DataResponses.IsData`, per `ResponseTap` e `CaptureCollector` | Nel HAR tutte le risposte GraphQL (`/graphql/query`, `/api/graphql`: storie, raccolte, ricerca) sono `text/javascript`; solo le REST (`/api/v1/…`) sono `application/json`. Con la regola di prima Febe scartava proprio i dati di storie e raccolte: è il motivo per cui non leggeva nulla. Le risposte con il prefisso `for (;;);` (`/ajax/…`: definizioni delle pagine, registri di navigazione) non sono JSON e non portano contenuti: restano scartate |
|
||||
| 2026-10-25 | Del documento principale di una pagina del sito (`text/html`, cornice principale) si leggono i blocchi `<script type="application/json">`: ogni blocco arriva ai lettori come una risposta a sé, con il descrittore del documento, letto mentre si scorre e uno solo in memoria alla volta (`DataResponses.EmbeddedJsonBlocks`); un documento senza blocchi validi si segnala scartato una volta; `febe-sonda da-har` scrive un campione per blocco. Il corpo del documento si chiede con `Network.getResponseBody`, già nell'elenco ammesso | Una pagina aperta per indirizzo (`Page.navigate`, come fanno tutte le ricette) riceve i dati del primo schermo dentro il documento e chiede con XHR solo le pagine successive: senza, la prima pagina di un profilo arriverebbe «vuota». **Da confermare dal vivo**: il HAR del 21 ottobre non conteneva documenti. Se i dati arrivano invece con XHR, la lettura del documento non trova nulla e non cambia niente. Blocco per blocco e non riuniti in un array (rilievo della revisione): riuniti davano una sola lettura con una sola paginazione, la prima del documento, e il «has_next_page» delle raccolte o il «more_available: false» di un post finiva sugli elementi di un altro blocco. Da confermare dal vivo: le regole di testo di `segnali.json` ora vedono anche i blocchi piccoli uno per uno. L'arrivo del documento non cancella più la sua stessa richiesta in corso (la cornice cambia documento prima che il corpo sia finito: si tiene la richiesta con l'identificativo del caricatore nuovo) |
|
||||
| 2026-10-25 | Nel vocabolario dei lettori, `relevance.keys`: se una risposta non contiene nessuna di quelle chiavi è «non pertinente» (`ReadShape.Unrelated`) e si ignora, invece di contare come forma sconosciuta; `CaptureCollector` non la conserva nemmeno, così una pagina che continua a mandare registri si assesta lo stesso. Per Instagram: `image_versions2`, `video_versions`, `carousel_media`, `taken_at`, `username`; per il sito di prova l'elenco è vuoto e tutto resta come prima | Instagram manda molte risposte JSON che non c'entrano con i contenuti (promozioni, il segno «storia vista», registri). Con le risposte `text/javascript` lette, ognuna di queste avrebbe fermato una ricetta come «formato non riconosciuto» ogni volta che il dato atteso tardava. Una risposta che ha le chiavi dei contenuti ma una forma che il vocabolario non descrive resta «formato non riconosciuto» (§6.4). L'elenco non si ricava dal vocabolario: sul sito di prova la forma sconosciuta di prova non ha nessuna sua chiave e deve restare sconosciuta |
|
||||
| 2026-10-25 | `IResponseObserver.OnBodyDropped`: la cattura avvisa quando il corpo di una risposta annunciata non arriverà (troppo grande, caricamento fallito, non JSON, pagina cambiata, browser riavviato), e `CaptureCollector` smette di aspettarlo | Prima un corpo scartato restava «in arrivo» per 15 secondi e `SettleAsync` non si assestava: con le risposte `/ajax/…` di Instagram, che arrivano a ogni scorrimento e cambio di pagina, ogni raffica avrebbe aspettato fino al limite |
|
||||
| 2026-10-25 | `lettori.instagram.json` è «confermato» e compilato soltanto con chiavi che compaiono nei campioni ripuliti (una prova lo controlla chiave per chiave): contenuto `pk`, `code`, `taken_at`, `caption.text`, `image_versions2.candidates`, `video_versions`, `carousel_media` e `carousel_media_count` (chiavi viste ma sempre vuote: nessuna serie nei campioni), `user`/`owner`, `expiring_at`, `video_duration`; versione `url`, `width`, `height`; profilo `pk`/`id`, `username`, `full_name`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`/`hd_profile_pic_versions`/`profile_pic_url`, `latest_reel_media`; raccolta `id`, `title`, `user`, `items`; pagina `has_next_page`/`more_available`, `end_cursor`; account collegato `xdt_viewer.user`. Restano vuoti `pinned`, `postCount` e `version.hasAudio` | Regola 10. `has_audio` sta sul contenuto, non sulla versione: ogni versione di `video_versions` conta come file completo (H5 si conferma scaricando). Le versioni video delle storie non hanno dimensioni: si prende la prima (101), che nei post ha le stesse dimensioni e la stessa banda delle altre due. `xdt_viewer.user` ha solo l'identificativo: il lettore lo tiene (`ReadResult.ViewerId`) per riconoscere l'account collegato quando il suo profilo compare altrove (H10 resta aperta) |
|
||||
| 2026-10-25 | L'identificativo di una raccolta si tiene nella forma dell'indirizzo: dal `highlight:17841…` dei dati il lettore toglie un prefisso fatto di sole lettere e due punti. Un oggetto con `id` e `title` è una raccolta solo se ha anche il proprietario o i contenuti (quando il vocabolario li nomina) | Nel HAR i dati dicono `highlight:<17 cifre>` e l'indirizzo del visualizzatore `/stories/highlights/<17 cifre>/`: senza normalizzare, ricetta e visualizzatore non si sarebbero mai riconosciuti. Senza il secondo vincolo una promozione o una sezione di pagina con `id` e `title` diventava una raccolta finta, e quelle vere sarebbero risultate tolte |
|
||||
| 2026-10-25 | Ripulitura: `latest_reel_media` è una data (si tiene); i valori sotto chiavi che hanno l'aspetto di un segreto (`token`, `key`, `secret`, `session`, `cookie`, `auth`, …) diventano un riempitivo neutro della stessa forma (lettere `x`, cifre `7`) invece di un valore finto vario | `latest_reel_media` è la data dell'ultima storia, della stessa natura di `taken_at`. Un valore finto estratto lettera per lettera da un `organic_tracking_token` di 340 caratteri sembra un segreto vero a gitleaks, che nella CI avrebbe fermato il lavoro «controlli» su dati finti; il riempitivo ha la stessa forma e nessuna entropia |
|
||||
| 2026-10-25 | Senza l'identificativo del contenuto nell'indirizzo del visualizzatore (Instagram: `/stories/highlights/{highlight}/`, uguale per tutti i contenuti della raccolta) i contenuti si contano sull'elenco ricevuto: il primo mostrato è il primo dell'elenco e ogni clic su «avanti» ne sposta uno; il conteggio non va mai avanti senza un clic. Un video si lascia entro l'inizio del clic + la sua durata − 1,5 s × umore·ritmo; se non si fa più in tempo, si chiude senza «avanti» e i contenuti dopo non si salvano (evento «visualizzatore-chiuso-prima»). Con l'identificativo nell'indirizzo (le storie, `/stories/{username}/{id}/`) si segue l'indirizzo come prima. In entrambi i modi il permesso StoryView per il contenuto successivo si chiede appena quello attuale è a video, prima dell'attesa di §7.7 (che si conta da quando è comparso); un contenuto comparso da solo dopo l'ultimo dell'elenco non si salva e il visualizzatore si chiude | Nel HAR quattro richieste fatte guardando contenuti diversi di una raccolta hanno lo stesso Referer: l'indirizzo non dice quale contenuto è a video. Regola 7 e §6.3: nella prima versione il permesso arrivava dopo che il contenuto era già comparso, e con umore o ritmo oltre 1 il clic cadeva dopo la fine del video, saltava un contenuto e portava nella raccolta successiva (rilievi della revisione). Meglio perdere contenuti che salvarne di non mostrati. Restano da misurare dal vivo il clic che la pagina ignora (il conteggio andrebbe avanti) e quanto il sito tiene una foto; con la spaziatura di 4 s del Governatore i video più brevi di 4–6 s si chiudono prima |
|
||||
| 2026-10-25 | Anche dopo un errore imprevisto (non dopo un segnale di arresto) la ricetta chiude il visualizzatore e salva ciò che è stato mostrato fin lì. Un visualizzatore che non si chiude con «viewer-close» ferma la ricetta come «bersaglio non trovato», anche dopo un altro arresto (tetto, errore); dopo un annullamento si salva ciò che è stato mostrato e la pagina resta com'è; ciò che un clic apre a un indirizzo che la mappa non riconosce si chiude prima di fermarsi | Un visualizzatore lasciato aperto passa da solo alle storie degli account successivi (§6.3), e solo «bersaglio non trovato» ferma la sessione e mette la pagina a riposo. Prima un indirizzo senza identificativo del contenuto faceva fallire la ricetta con il visualizzatore aperto, e un annullamento (pausa, segnale), che arriva quasi sempre durante l'attesa su una storia, faceva perdere storie già segnate come viste |
|
||||
| 2026-10-25 | Il bersaglio `profile-not-found` è facoltativo per Controllo del profilo, Storico, Taggati e Reel: si cerca solo se la mappa lo imposta; senza, un profilo che non c'è non dà dati ed è giudicato come una pagina vuota | Per Instagram non c'è ancora un segno verificato (H11) e le ricette del profilo devono poter girare con le sole pagine. Con il segno impostato l'account si segna «Non raggiungibile» come prima |
|
||||
| 2026-10-25 | Dopo aver aperto profilo, home ed elenco dei seguiti (e dopo il clic su una scheda) le ricette aspettano il dato atteso, lasciano assestare la pagina e prendono tutto ciò che è arrivato dal segno in poi; Controllo e Storico aspettano anche la prima pagina della griglia (fino a 20 s). La paginazione di un cammino viene solo dalle risposte che portano i suoi elementi, o da una pagina vuota; l'elenco dei seguiti non salva mai un profilo con `IsFollowed` falso (i profili suggeriti), né l'account collegato; la home «è arrivata» con contenuti, una voce della barra delle storie o una pagina, non con soli profili. «Tu» nasce anche da `ViewerId` più un profilo con lo stesso identificativo in una risposta qualunque del giro | Su Instagram intestazione del profilo, griglia, raccolte e home arrivano in risposte diverse, anche dopo la prima; risposte su altro (un post con `more_available:false`, le raccolte con `has_next_page:false`) dicono «non ce n'è altro» di sé stesse e avrebbero chiuso uno storico; i 30 profili suggeriti hanno `friendship_status.following:false`. Sul sito di prova, dove tutto arriva insieme, il comportamento resta quello di prima |
|
||||
| 2026-10-25 | Una ricetta che la mappa dei bersagli o il vocabolario dei lettori non lasciano girare finisce in `NotConfigured` («Da configurare»), non più in «bersaglio non trovato» o «formato non riconosciuto»: non conta per la sospensione, il motore non la pianifica, lo dice una volta per ricetta e per avvio, e annulla con un evento un comando di Alberto che non può partire. Senza il giro dei seguiti le storie dei seguiti si controllano account per account | I rifiuti dei primi file di Instagram, che erano scheletri, contavano come guasti: dopo tre sessioni il motore sospendeva le ricette come se Instagram fosse cambiato, e le sospensioni restavano anche con file nuovi |
|
||||
| 2026-10-25 | All'avvio Febe calcola un'impronta SHA-256 di `lettori.<sito>.json` e `bersagli.<sito>.json` come caricati (incorporati o copia nella cartella Dati, fine riga ignorati) e la conserva in `motore.configurazione-raccolta`; quando cambia, e al primo avvio che la calcola, azzera una volta sospensioni ed errori consecutivi delle ricette, con una riga in Attività se c'era qualcosa da azzerare. Il registro (fonte «raccolta») dice da dove vengono i due file e com'è il vocabolario, quali ricette non possono girare, e avvisa se una copia nella cartella Dati è ancora «ipotesi» mentre quella incorporata è «confermato» o ferma ricette che quella incorporata lascerebbe girare. Mai il contenuto dei file | Le sospensioni contate con i file vecchi non devono sopravvivere a quelli nuovi, e nel database di Alberto con ogni probabilità ce ne sono. Una copia vecchia nella cartella Dati vince sempre su quella incorporata: senza il registro resterebbe invisibile. La cartella `config/` accanto al programma non si legge mai (la riga del 13 ottobre lo dava per vero) |
|
||||
| 2026-10-25 | Lo stato del collegamento nella barra laterale viene dal cookie di sessione (dal modo del motore, o dal servizio di collegamento quando il motore non gira), non dal fatto che l'account «Tu» sia già noto | Su Instagram «Tu» può arrivare molto dopo il collegamento (H10: i dati danno solo l'identificativo dell'account collegato) e la barra diceva «Da collegare» mentre Febe raccoglieva |
|
||||
| 2026-10-25 | `bersagli.instagram.json`: compilate solo le pagine con una prova reale nel HAR del 21 ottobre (i modelli che Instagram stesso manda in `/ajax/bulk-route-definitions/` e i Referer delle richieste della pagina): home `/`, profilo `/{username}/`, post `/p/{code}/`, storie `/stories/{username}/{id}/`, raccolte `/stories/highlights/{highlight}/` senza identificativo del contenuto. Vuoti l'elenco dei seguiti, le pagine di ripresa e tutti i bersagli (H11). La forma delle storie coincide anche con l'indirizzo delle raccolte (nome utente «highlights»): accettato, perché per le storie è «un altro account» e il visualizzatore si chiude, e la ricetta delle raccolte legge solo la sua pagina | Regola 10: niente di inventato. Il HAR non aveva documenti né attributi degli elementi, quindi nessun ruolo né nome accessibile. Girano le ricette che aprono solo pagine (giro dei seguiti, controllo del profilo, storico, post singolo); storie, raccolte, Taggati e Reel aspettano i bersagli |
|
||||
| 2026-10-25 | `febe-sonda da-har --har <file> --a <cartella>`: un HAR esportato dagli strumenti per sviluppatori diventa una cartella di campioni grezzi nel formato della sonda: solo le risposte di dati del sito (`DataResponses.IsData`) e il JSON incorporato nei documenti, mai intestazioni, cookie, query o corpi delle richieste; il nome del file viene dall'operazione GraphQL solo se ha la forma di un nome del codice (finisce con Query, Mutation o Subscription, senza cifre ripetute), altrimenti «risposta» o «documento». Rifiuta un HAR o una cartella dentro un repository e una cartella non vuota | Alberto raccoglie più volentieri dal suo browser di tutti i giorni che con la sonda: così può ripulire e verificare da sé, sulla sua macchina, e mandare solo la copia ripulita (§14.5) |
|
||||
| 2026-10-25 | `tools/bersagli/raccogli-bersagli.js`: i bersagli si raccolgono con uno script in sola lettura che Alberto incolla nella Console del suo browser: un solo ascoltatore dei clic, nessuna modifica alla pagina, niente rete, cookie o archivi; calcola ruolo e nome accessibile come `TargetResolver`, registra la forma degli indirizzi prima e dopo il clic, sostituisce i nomi con NOME e prepara per ogni clic le voci `role`, `name`, `href` e `index` della mappa | Il HAR non porta gli attributi degli elementi; la sonda li registrerebbe, ma chiede di avviare un Chromium a parte. La forma dell'indirizzo dopo il clic dice anche se l'indirizzo delle storie segue ogni storia |
|
||||
| 2026-10-25 | La paginazione di una pagina (griglia, schede, giro dei seguiti, elenco dei seguiti) viene dalla risposta che porta più elementi non ancora incontrati, l'ultima a pari merito; una risposta che riporta solo elementi già letti non conta come pagina successiva né per la sua paginazione. Una risposta vuota senza profilo è la pagina vuota di un cammino solo quando risponde a un suo gesto (pagina di ripresa, scheda, scorrimento), mai all'apertura del profilo; con il profilo dell'account è la griglia vuota anche accanto alle raccolte, se il profilo dice «0 pubblicazioni» | Rilievi della revisione: su Instagram la pagina di un post del profilo stesso («more_available: false») e le raccolte di un account che non ne ha (connessione vuota con «has_next_page: false», forma identica a una griglia vuota) chiudevano lo storico dopo la prima pagina o senza post; sul sito di prova un profilo con raccolte e senza post aspettava 20 s a ogni controllo. Un account Instagram senza post resta così con lo storico aperto: costa un'attesa e una pagina a sessione, mai post persi |
|
||||
| 2026-10-25 | Mentre «Storie di un account» non può girare con la configurazione del sito, la visita di un profilo non seguito non serve le storie: si pianifica all'intervallo del profilo, non conta come lavoro di storie, e il giro dei seguiti non accoda «Storie segnalate dalla barra» (ogni giro segnala di nuovo l'account finché le storie non si vedono). `SyncQueue` non annulla più i «Post singolo» accodati dalla raccolta: li toglie solo per un account che non si contatta, e mentre la ricetta non può girare aspettano | Con i file di Instagram di oggi un profilo non seguito si sarebbe aperto fino a 24 volte più spesso del dovuto senza raccogliere nulla, e la Coda si sarebbe riempita a ogni sessione di storie che non sarebbero mai partite. Un «Post singolo» annullato non tornava più in coda (nessuno ricontrolla gli indirizzi scaduti), mentre §6.5 punto 5 vuole che il recupero passi da lì: difetto precedente a questo lavoro (commit `aff81df`), trovato dalla revisione. Effetto: su Instagram queste ricette ora girano davvero, dentro il loro tetto (Prudente: 10 l'ora, 60 al giorno) |
|
||||
+4
-3
@@ -37,9 +37,10 @@ seguire; passa al tuo account solo quando hai visto come si comporta.
|
||||
Questa guida descrive ciò che c'è nel programma, non ciò che si spera. Alcune cose dipendono da prove che si possono
|
||||
fare solo con Instagram o su Windows:
|
||||
|
||||
- **Raccolta da Instagram: non ancora attiva.** Le ricette, il motore, la libreria e gli scaricamenti funzionano e sono
|
||||
provati contro un sito di prova locale. Su Instagram le ricette si rifiutano di girare («la mappa dei bersagli non è
|
||||
ancora compilata») finché la sonda passiva non ha confermato le ipotesi H1–H11. Vedi
|
||||
- **Raccolta da Instagram: in parte attiva (25 ottobre 2026).** Febe legge le risposte vere di Instagram (lettori
|
||||
scritti su risposte reali, ripulite). Girano giro dei seguiti, controllo del profilo, storico e post singolo: foto e
|
||||
video dei post e dei reel. Storie, raccolte in evidenza e schede Taggati e Reel aspettano i bersagli dei comandi
|
||||
(ipotesi H11) e rispondono «la mappa dei bersagli non è ancora compilata». Non è ancora stato provato dal vivo. Vedi
|
||||
[Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
- **Versione per Windows: pronta, non ancora provata su un Windows vero.** Programma di installazione e versione
|
||||
portabile ci sono; le prove che si fanno solo su Windows (S1–S3) sono aperte. Vedi
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
# Ipotesi da verificare
|
||||
|
||||
Febe è costruito su alcune ipotesi che non si possono provare senza Instagram (voci **H**) o senza i due browser veri
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra: per questo la raccolta da Instagram non è
|
||||
ancora attiva. Lo stato aggiornato e i dettagli tecnici sono in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md`
|
||||
nel repository; i passi precisi delle prove in `docs/prove-dal-vivo.md`.
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra. Lo stato aggiornato e i dettagli tecnici sono
|
||||
in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md` nel repository; i passi precisi delle prove in
|
||||
`docs/prove-dal-vivo.md`.
|
||||
|
||||
**Dal 25 ottobre 2026** Febe legge le risposte vere di Instagram: i lettori sono scritti sulle risposte che il tuo
|
||||
browser ha ricevuto il 21 ottobre (un file HAR), ripulite. Girano le ricette che aprono solo pagine (giro dei seguiti,
|
||||
controllo del profilo, storico, post singolo). Storie, raccolte in evidenza e schede Taggati e Reel aspettano i
|
||||
**bersagli** (H11): i nomi e i ruoli di pulsanti come l'anello delle storie, «avanti» e la X, che nel HAR non c'erano.
|
||||
|
||||
Le prove dal vivo le fai **tu**, con l'**account di prova**, mai con l'account principale prima di aver visto Febe
|
||||
all'opera. Se in qualunque momento compare una verifica, un CAPTCHA o un avviso dell'account: fermati, risolvi a mano,
|
||||
@@ -14,28 +19,32 @@ locali, mai Instagram; **da provare** = serve una prova tua.
|
||||
|
||||
## Voci H: Instagram
|
||||
|
||||
Si provano tutte con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi
|
||||
tu in Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una
|
||||
raccolta, le schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
Si provano con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi tu in
|
||||
Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una raccolta, le
|
||||
schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
`febe-sonda ripulisci` e `febe-sonda verifica` sulla tua macchina, e mandi solo la cartella **ripulita**. La sonda non
|
||||
compie gesti e non apre pagine da sola.
|
||||
|
||||
Più semplice, con il **browser di tutti i giorni** (parte A bis): registri un HAR con il filtro «Tutti», incolli nella
|
||||
Console lo script `tools/bersagli/raccogli-bersagli.js` per i bersagli, poi `febe-sonda da-har`, `ripulisci` e
|
||||
`verifica`, e mandi solo la copia ripulita e il testo dei bersagli.
|
||||
|
||||
| | Ipotesi | Stato | Come la provi |
|
||||
|---|---|---|---|
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare (il HAR non conteneva la pagina iniziale) | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H2 | La barra delle storie dice quali profili seguiti hanno storie attive e a quando risale l'ultima | Da provare | Sonda, pagina iniziale caricata: passa sopra la prima voce della barra |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | Da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | Da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | Da provare | Sonda: un post video e una storia video |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | In parte: forma dell'indirizzo e del profilo viste nel HAR; le risposte della pagina profilo da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | In parte: il visualizzatore delle raccolte riceve l'elenco completo con gli indirizzi; quello delle storie di un account da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | In parte: tre versioni `.mp4` per video, «ha l'audio» detto dal contenuto; da confermare scaricando | Sonda: un post video e una storia video |
|
||||
| H6 | Le schede «Taggati» e «Reel» si comportano come la griglia | Da provare | Sonda: apri le due schede di un profilo e scorri |
|
||||
| H7 | I file del CDN si scaricano dal browser (`Network.loadNetworkResource`) | Provato in locale (24 MB integri); da provare con il CDN vero | Prima sessione dal vivo (parte B): i file arrivano in Libreria, stato «scaricato» |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | Da provare (non provocarli di proposito) | Se durante la sonda compare una verifica, annota l'ora e manda la riga ripulita di `navigazioni.jsonl` |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Da provare | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Da provare | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare; lo scheletro `bersagli.instagram.json` è pronto | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Indizio: i contenuti delle raccolte hanno identificativo e scadenza come le storie | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Non basta: i dati danno solo l'identificativo dell'account collegato; Febe lo riconosce quando compare il suo profilo | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare: il HAR non aveva gli attributi dei comandi. Pagine compilate, bersagli vuoti | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
|
||||
Finché H1–H11 non sono provate e la mappa dei bersagli e il vocabolario dei lettori non sono compilati sui campioni
|
||||
ripuliti, le ricette su Instagram rispondono «la mappa dei bersagli non è ancora compilata» senza aprire pagine.
|
||||
Finché i bersagli non sono compilati, le ricette che ne hanno bisogno rispondono «la mappa dei bersagli non è ancora
|
||||
compilata» senza aprire pagine; in Attività risultano «Da configurare» e il motore non le pianifica.
|
||||
|
||||
## Voci S: i due browser
|
||||
|
||||
|
||||
@@ -55,7 +55,9 @@ una sua copia, ha la sessione di Instagram.**
|
||||
- Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione
|
||||
chiusa.
|
||||
- Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i
|
||||
post in cui sei taggato. (Riconoscere il tuo account dai dati della pagina è l'ipotesi H10, ancora da confermare.)
|
||||
post in cui sei taggato. Su Instagram i dati della pagina danno solo l'identificativo del tuo account: Febe ti
|
||||
riconosce quando compare anche il tuo profilo (per esempio la tua voce nella barra delle storie); fino ad allora la
|
||||
barra laterale dice «Collegato» e «Nome non ancora noto». È l'ipotesi H10, ancora da confermare dal vivo.
|
||||
|
||||
Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostazioni).
|
||||
|
||||
|
||||
@@ -33,9 +33,10 @@ dati.
|
||||
|
||||
Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
||||
|
||||
1. **Raccolta da Instagram non ancora attiva.** Se in «Appena fatto» vedi «non può girare su instagram: la mappa dei
|
||||
bersagli non è ancora compilata», è lo stato attuale del progetto: le ricette su Instagram aspettano i risultati
|
||||
della sonda (ipotesi H1–H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto.
|
||||
1. **Ricetta «Da configurare».** Se in Attività vedi «non può girare su instagram: la mappa dei bersagli non è ancora
|
||||
compilata», è lo stato attuale del progetto per storie, raccolte e schede Taggati e Reel: aspettano i bersagli dei
|
||||
comandi (ipotesi H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto, e quelle ricette non
|
||||
vengono sospese.
|
||||
2. **Non collegato**, **verifica richiesta** o **sessione chiusa**: la barra laterale lo dice. Vedi
|
||||
[Primo collegamento](Primo-collegamento) e [Attività e arresti](Attivita-e-arresti).
|
||||
3. **Fuori fascia** o **giorno non attivo**: Attività dice «Fuori fascia» e quando riprende.
|
||||
|
||||
@@ -86,6 +86,110 @@ Quando i lettori e la mappa sono stati scritti sui campioni ripuliti, **cancella
|
||||
|
||||
---
|
||||
|
||||
## A bis. Bersagli e campioni dal browser di tutti i giorni (25 ottobre 2026)
|
||||
|
||||
Scopo: completare ciò che il file HAR del 21 ottobre non poteva dare. Quel file aveva solo le risposte **Fetch/XHR**
|
||||
(il filtro del pannello Rete era su «Fetch/XHR»): nessun documento, quindi nessun dato incorporato nelle pagine, e
|
||||
nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Da lì sono venuti i lettori
|
||||
(`lettori.instagram.json`) e le pagine della mappa (`bersagli.instagram.json`), ma i **bersagli** sono ancora vuoti:
|
||||
«Storie di un account», «Raccolta in evidenza», «Taggati» e «Reel» si rifiutano di girare finché non ci sono (H11).
|
||||
Mancano anche le risposte della home, del profilo e della sua griglia, delle storie, delle schede, dell'elenco dei
|
||||
seguiti e di un post con più foto.
|
||||
|
||||
Si raccolgono le due cose nello stesso giro, dal browser che usi tutti i giorni, senza la sonda: un file HAR completo
|
||||
e i bersagli dei comandi che clicchi. **Navighi solo tu**: nessun programma clicca o apre pagine.
|
||||
|
||||
### A bis 1. Prima di cominciare
|
||||
|
||||
- Chrome su Windows, con Instagram aperto e l'accesso già fatto, come il 21 ottobre.
|
||||
- Una cartella **fuori da qualunque repository git**, per esempio `C:\febe-har\2026-10-25` (qui sotto
|
||||
`<cartella>`): lì vanno il file HAR, i campioni grezzi e il testo dei bersagli. Il file HAR contiene i cookie della
|
||||
sessione e i dati di altre persone: **non si invia mai** e non va nel repository (`febe-sonda da-har` rifiuta un
|
||||
file o una cartella dentro un repository).
|
||||
- Il file `tools/bersagli/raccogli-bersagli.js` del repository, aperto in un editor per copiarlo
|
||||
(`tools/bersagli/LEGGIMI.md` dice che cosa registra).
|
||||
- Come in tutta questa guida: se compare una verifica, un CAPTCHA o un avviso dell'account, **fermati**, risolvi a
|
||||
mano, annota l'ora e riferisci.
|
||||
|
||||
### A bis 2. Strumenti per sviluppatori
|
||||
|
||||
1. Con Instagram aperto premi **F12** (oppure Ctrl+Maiusc+I).
|
||||
2. Scheda **Rete**: spunta **Conserva log** e nel filtro dei tipi scegli **Tutti**, **non** «Fetch/XHR»: servono
|
||||
anche i documenti.
|
||||
3. Ricarica la pagina (**F5**) con il pannello aperto: così anche il primo documento della home finisce nel registro.
|
||||
4. Scheda **Console**: incolla tutto il contenuto di `raccogli-bersagli.js` e premi Invio. La prima volta Chrome può
|
||||
chiedere di scrivere una frase di conferma prima di accettare un incolla: scrivila come indica e incolla di nuovo.
|
||||
Deve comparire «Febe: raccolta dei bersagli attiva (sola lettura)».
|
||||
|
||||
Lo script legge soltanto: non clicca, non cambia la pagina, non manda nulla a nessuno, non legge cookie né le memorie
|
||||
del browser. A ogni clic la Console scrive «Febe: clic N registrato». Se la pagina si ricarica del tutto (F5, un
|
||||
indirizzo scritto a mano) la raccolta si perde: **incolla di nuovo lo script**.
|
||||
|
||||
### A bis 3. Che cosa fare, nell'ordine
|
||||
|
||||
Muoviti con calma, come al solito, e annota l'ora d'inizio di ogni passo. I comandi in **grassetto** sono quelli da
|
||||
cliccare: è il clic che registra ruolo e nome accessibile.
|
||||
|
||||
1. **Home.** Attendi il caricamento e scorri piano per una decina di post.
|
||||
2. **Un profilo.** Scrivi nella barra l'indirizzo di un profilo pubblico (è un caricamento completo, come quando Febe
|
||||
apre un profilo), poi **incolla di nuovo lo script** nella Console. Scorri la griglia per 3–4 schermate.
|
||||
3. **Le storie di un seguito.** Dal suo profilo clicca la **foto con l'anello**. Vai avanti di **due** storie
|
||||
cliccando la **zona a destra**. Prima che finiscano, chiudi con la **X**: non lasciare che il visualizzatore passi da
|
||||
solo all'account successivo.
|
||||
4. **Una raccolta in evidenza.** Da un profilo clicca una **raccolta**, vai avanti **una volta** con la zona a destra,
|
||||
chiudi con la **X**.
|
||||
5. **Le schede «Reel» e «Taggati»** di un profilo: clicca la **scheda** e scorri un poco, per ognuna.
|
||||
6. **I tuoi seguiti.** Dal tuo profilo clicca **«Seguiti»** e scorri l'elenco per 3–4 schermate.
|
||||
7. **Un post con più foto** (una serie): aprilo dalla griglia e passa alla foto successiva con la **freccia**.
|
||||
|
||||
Ci si aspetta: nessuna verifica, nessun avviso.
|
||||
|
||||
### A bis 4. Il testo dei bersagli
|
||||
|
||||
1. Nella Console scrivi `febeBersagli()` e premi Invio: i clic registrati vanno negli appunti e la Console dice
|
||||
quanti sono (se la copia non riesce, li scrive nella Console: copiali da lì).
|
||||
2. Incollali in un file di testo nuovo, per esempio `<cartella>\bersagli.txt`. Nei testi i nomi visti negli
|
||||
indirizzi e le `@parole` sono già diventati `NOME`, e negli indirizzi resta solo la forma (`/stories/<x>/<x>/`).
|
||||
**Leggi il file e sostituisci con `NOME` ogni nome di persona rimasto** (nomi scritti per esteso, frasi delle
|
||||
didascalie).
|
||||
|
||||
### A bis 5. Il file HAR
|
||||
|
||||
1. Scheda **Rete**: pulsante per **esportare il HAR** (la freccia verso il basso nella barra del pannello) e salva in
|
||||
`<cartella>\instagram.har`. Se Chrome offre due voci, scegli quella senza dati sensibili; se poi la conversione
|
||||
dice che le risposte sono «senza corpo», esporta di nuovo con l'altra voce.
|
||||
2. Chiudi gli strumenti per sviluppatori.
|
||||
|
||||
### A bis 6. Conversione, ripulitura e verifica (sulla tua macchina)
|
||||
|
||||
```sh
|
||||
febe-sonda da-har --har <cartella>\instagram.har --a <cartella>\grezzi
|
||||
febe-sonda ripulisci --da <cartella>\grezzi --a <cartella>\ripuliti
|
||||
febe-sonda verifica --grezzi <cartella>\grezzi --ripuliti <cartella>\ripuliti
|
||||
```
|
||||
|
||||
Dal repository: `dotnet run --project tools/Febe.Sonda -- da-har …`, e così per gli altri due.
|
||||
|
||||
- `da-har` scrive i campioni grezzi nello stesso formato della sonda, in una cartella **nuova** (rifiuta una cartella
|
||||
già usata). Tiene solo le risposte di dati del sito e i dati incorporati nei documenti; lascia fuori file, immagini,
|
||||
script e ogni altro sito; **non copia mai** intestazioni, cookie, parametri degli indirizzi o corpi delle richieste.
|
||||
Ogni file prende il nome dell'operazione GraphQL quando c'è (per esempio `000012-PolarisStoriesV3HighlightsPageQuery.json`),
|
||||
altrimenti `risposta` o `documento`: mai un pezzo di indirizzo, che può contenere un nome. Stampa solo conteggi.
|
||||
- `ripulisci` va lanciato **una volta sola su tutta la cartella**: i valori finti cambiano a ogni esecuzione.
|
||||
- La verifica deve dire **«Verifica superata»**. Se no, dice in quale file sopravvive un frammento (mai il frammento
|
||||
stesso): **cancella la cartella `ripuliti`**, non inviare nulla e riferisci il messaggio.
|
||||
|
||||
### A bis 7. Che cosa mandare
|
||||
|
||||
1. La cartella **ripulita** (compressa) e il testo della verifica.
|
||||
2. Il file `bersagli.txt`, con i nomi sostituiti.
|
||||
3. Le note: a che ora hai fatto ogni passo, che cosa è andato diversamente da come descritto.
|
||||
|
||||
Mai: il file HAR, la cartella `grezzi`, schermate con nomi di altre persone. Quando lettori e mappa sono stati scritti
|
||||
sui campioni ripuliti, **cancella il file HAR e la cartella `grezzi`** (§14.5).
|
||||
|
||||
---
|
||||
|
||||
## B. Prima sessione dal vivo, dopo M3
|
||||
|
||||
Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, e i file arrivare in libreria.
|
||||
|
||||
+30
-20
@@ -1,24 +1,30 @@
|
||||
# Esito delle ipotesi di M0 (specifica §6.6)
|
||||
|
||||
Stato al 13 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**: per questo i
|
||||
file di Instagram sono ancora scheletri e le ricette si rifiutano di girare su Instagram (vedi in fondo).
|
||||
Stato al 25 ottobre 2026. Finché una voce non ha un esito con le prove, **non ci si costruisce sopra**.
|
||||
|
||||
**25 ottobre 2026: i primi campioni reali.** Alberto ha mandato un file HAR esportato dal suo browser il 21 ottobre
|
||||
(DevTools, filtro Fetch/XHR: niente documenti, immagini né script). Le risposte utili sono state convertite nel formato
|
||||
della sonda fuori dal repository, ripulite e verificate («Verifica superata»): sono in `tests/Febe.Tests/campioni/instagram`
|
||||
(vedi il suo `LEGGIMI.md`). Con quelle `lettori.instagram.json` è compilato e «confermato», e di
|
||||
`bersagli.instagram.json` sono compilate le pagine con una prova reale (vedi in fondo). Le colonne «Stato» qui sotto
|
||||
dicono che cosa il HAR ha provato e che cosa no.
|
||||
|
||||
Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvfb e pagine locali, mai Instagram;
|
||||
**da provare dal vivo** = serve Alberto, con l'account di prova e la sonda (`docs/prove-dal-vivo.md`, parte A).
|
||||
|
||||
| | Ipotesi | Stato | Come si prova (procedura esatta) | Che cosa ne dipende |
|
||||
|---|---|---|---|---|
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo** | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo** | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **Da provare dal vivo** | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **Da provare dal vivo** | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **Da provare dal vivo** | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo** | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H1 | La home consegna i post recenti dei seguiti con i dati completi dei file | **Da provare dal vivo**. Il HAR non contiene la home: nessuna risposta del feed | Sonda, passo A3.1: aprire la home, attendere il caricamento, scorrere piano per una decina di post. Nei campioni ripuliti cercare risposte con elenchi di contenuti (identificativo, data, versioni delle immagini con dimensioni, figli delle serie) | Giro dei seguiti; `pages.home` di `bersagli.instagram.json`; concetti `content.*` e `version.*` di `lettori.instagram.json` |
|
||||
| H2 | La barra delle storie dice quali seguiti hanno storie attive e a quando risale l'ultima | **Da provare dal vivo**. Il HAR non contiene la barra delle storie. La data dell'ultima storia di un profilo esiste come `latest_reel_media` (vista nell'autore di un post e nel proprietario di una raccolta) | Passo A3.1: con la home caricata, la sonda registra le risposte della barra; nei ripuliti cercare elenchi di profili con un campo data dell'ultima storia | `profile.latestStoryAt`; bersaglio `home-story` |
|
||||
| H3 | Il profilo consegna identificativo, pubblico/privato, se è seguito, prima pagina dei post con serie e video, elenco delle raccolte; lo scorrimento carica le pagine successive | **In parte**. Forma dell'indirizzo confermata (`/{username}/{?tab}/…`, dalle definizioni delle pagine che Instagram stesso manda); forma del nodo profilo confermata (`pk`, `username`, `is_private`, `friendship_status.following`, `hd_profile_pic_url_info`, `latest_reel_media`). Le risposte della pagina profilo (intestazione, griglia, raccolte, pagine successive) **non** sono nel HAR: da provare dal vivo | Passi A3.2 e A3.3: profilo pubblico non seguito e profilo privato seguito, scorrendo 3–4 schermate. Nei ripuliti: un nodo profilo con i campi di stato, pagine di contenuti successive con un punto di ripresa | Controllo del profilo, Storico; `profile.*`, `highlight.*`, `page.*`; `pages.profile`, `pages.profileFrom` (facoltativa: se il sito non riparte da un cursore, lo storico riprende scorrendo) |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | **In parte**. Il visualizzatore delle raccolte riceve l'elenco completo dei contenuti con indirizzi, `taken_at` ed `expiring_at` (`xdt_api__v1__feed__reels_media__connection`, `text/javascript`); la forma dell'indirizzo delle storie è `/stories/{username}/{?initial_media_id}/`. La risposta delle storie di un account (non di una raccolta) e se l'indirizzo segue ogni storia: da provare dal vivo | Passo A3.4: aprire le storie di un seguito dall'anello del profilo, guardarne 2–3, chiudere con la X **prima** che passi all'account successivo. Nei ripuliti: un elenco di contenuti con data di scadenza; in `navigazioni.jsonl` la forma dell'indirizzo del visualizzatore | Storie di un account; `content.expiresAt`; `pages.storyViewer`; bersagli `profile-story-ring`, `viewer-next`, `viewer-close` |
|
||||
| H5 | Per i video arriva almeno un indirizzo unico con audio e video insieme | **In parte**. `video_versions` dà tre versioni `.mp4` (tipi 101, 102, 103: nei post stesse dimensioni e banda); se c'è l'audio lo dice il contenuto (`has_audio`), non la versione. Che il file abbia davvero audio e video insieme si conferma scaricando (prima sessione dal vivo) | Passi A3.2 e A3.4 su un post video e su una storia video. Nei ripuliti: le versioni del video e un campo che dica se hanno l'audio | `version.hasAudio`; scelta della versione di §6.5 punto 1 (se nessuna versione ha audio e video insieme, va riletta §4.9: l'unione delle tracce è fuori dalla versione 1) |
|
||||
| H6 | Le schede «taggati» e «reel» si comportano come la griglia | **Da provare dal vivo**. Nessuna risposta delle schede nel HAR | Passo A3.6: aprire le due schede di un profilo e scorrere | Taggati, Reel; bersagli `profile-tab-tagged`, `profile-tab-reels`; `pages.taggedFrom`, `pages.reelsFrom` |
|
||||
| H7 | I file del CDN si scaricano con `Network.loadNetworkResource`; se no, con la via di riserva di §6.5 | **Da provare dal vivo**. In locale: scaricati integri (24 MB in 2,2 s; foto e video del sito di prova byte per byte) | Dopo la sonda, con la prima sessione dal vivo (parte B): file arrivati in Libreria, stato «scaricato». **Osservazione locale**: dalla pagina di riposo `about:blank` Chromium rifiuta gli indirizzi locali del CDN di prova (`net::ERR_BLOCKED_BY_PRIVATE_NETWORK_ACCESS_CHECKS`); dalle pagine del sito funziona. Con il CDN pubblico va misurato se lo scaricamento regge anche dalla pagina di riposo | `BrowserFileFetcher`; la via `HttpClient` di §6.5 punto 3 **non è scritta**: resta dietro `IFileFetcher` finché H7 non dice che serve. Codici HTTP di «indirizzo scaduto» (in locale 403 e 410) |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito) | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Da provare dal vivo** | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Da provare dal vivo** | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Scheletro pronto: `bersagli.instagram.json` | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | **Da provare dal vivo** (non provocare segnali di proposito). Nessun segnale nel HAR | Se durante la sonda compare una verifica o un avviso, annotare l'ora e mandare la riga corrispondente di `navigazioni.jsonl` ripulita. Sul sito di prova i casi 429, `/verifica`, sessione terminata e pagine vuote fermano le ricette (prove `StopAndDownloadIntegrationTests`) | `segnali.json` (le regole su Instagram restano ipotesi segnate H8) |
|
||||
| H9 | Un contenuto di una raccolta ha lo stesso identificativo che aveva come storia | **Indizio**. I contenuti di una raccolta hanno `pk` ed `expiring_at` come le storie; che il `pk` sia lo stesso della storia originale va visto con una storia ancora attiva | Passo A3.5: aprire una raccolta che contenga una storia ancora attiva (o pubblicata e poi messa in evidenza dall'account di prova). Confrontare gli identificativi nei ripuliti: la ripulitura dà a valori uguali lo stesso valore finto | Raccolta in evidenza (collegamento senza riscaricare); sul sito di prova funziona così per costruzione |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati, senza leggere i cookie | **Non basta**. `xdt_viewer.user` descrive l'account collegato con il solo identificativo, senza nome: Febe lo tiene (`ReadResult.ViewerId`) e riconosce «Tu» quando il suo profilo compare in un'altra risposta. Da provare dal vivo | Passo A3.1: nei ripuliti della home cercare un nodo che descriva l'account collegato | `viewer` di `lettori.instagram.json`; il profilo «Tu» |
|
||||
| H11 | I bersagli si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | **Da provare dal vivo**. Il HAR non ha documenti né attributi degli elementi: i bersagli restano vuoti. Procedura semplificata in `docs/prove-dal-vivo.md`, parte A bis | Durante tutta la sonda: passare col puntatore e cliccare i comandi elencati al passo A3; la sonda registra ruolo, nome accessibile e forma del collegamento in `interazioni.jsonl`. Alberto manda le righe dei soli comandi dell'interfaccia (passo A6) | Tutte le ricette |
|
||||
| S1 | In WebView2 funzionano corpo delle risposte, gesti e fotogrammi | **Da provare** su Windows. Pronto: `WebView2Browser` (Febe.Desktop) con l'adattatore `WebView2CdpSession` (stesso elenco ammesso del client Chromium, provato su Linux con un finto WebView2) | `docs/prove-dal-vivo.md`, parte C3: Febe per Windows con `--sito-di-prova`, una sessione intera (`Network.getResponseBody`, `Input.dispatchMouseEvent`, `Network.loadNetworkResource`/`IO.read`) e l'anteprima di Attività (`Page.captureScreenshot`). `Page.startScreencast` su Windows non serve (la vista remota è solo di Docker) | `WebView2Browser`, `WebView2CdpSession` |
|
||||
| S2 | Su Windows la pagina carica e scorre con la finestra fuori vista | **Da provare** su Windows. Pronti i tre modi di §6.6, scelti con `Febe.exe --browser finestra\|composizione\|edge` (predefinito `finestra`: fuori dallo schermo, `IsVisible` sempre vero, `--disable-features=CalculateNativeWinOcclusion --disable-backgrounding-occluded-windows`) | `docs/prove-dal-vivo.md`, parte C4: sessione sul sito di prova con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; se non regge, `composizione` e poi `edge` | `WebView2Browser`, `CompositionHost`, `EdgeBrowser` |
|
||||
| S3 | L'accesso a mano sopravvive al riavvio | **Provato in locale per Docker/Chromium** (cookie scritto con arresto SIGINT, 3 esecuzioni su 3; vedi `esito-locale.md`); **da provare** su Windows (all'arresto Febe chiude WebView2 e ne aspetta l'uscita prima di finire) e nel contenitore vero | Docker: accedere, riavviare il contenitore, controllare il collegamento. Windows: `docs/prove-dal-vivo.md`, parti C3.7 (sito di prova) e C5 (Instagram, account di prova: Esci e riapri, riavvio di Windows, avvio con il computer) | Profilo del browser nella cartella dei dati |
|
||||
@@ -28,14 +34,18 @@ Legenda: **provato in locale** = misurato su questa macchina con Chromium su Xvf
|
||||
|
||||
## Che cosa è pronto per ricevere gli esiti
|
||||
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json` (copiato in `config/`): **scheletro**. Elenca le pagine e i bersagli
|
||||
di cui le ricette hanno bisogno, tutti vuoti e segnati con l'ipotesi da cui dipendono. Finché una voce necessaria è
|
||||
vuota, la ricetta risponde «non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano …)»
|
||||
senza aprire pagine e senza chiedere permessi.
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **ipotesi**. Contiene solo gli indizi di §6.4 (`pk`, `code`,
|
||||
`taken_at`, `image_versions2.candidates`, `video_versions`, `carousel_media`); ogni altro concetto è vuoto. Con lo
|
||||
stato «ipotesi» le ricette non girano. Va riempito sui campioni ripuliti e portato a «confermato».
|
||||
- `src/Febe.Core/Config/lettori.instagram.json`: **confermato** il 25 ottobre sui campioni reali ripuliti; ogni sua
|
||||
chiave compare in quei campioni (lo controlla `InstagramReaderTests`). Le risposte che non parlano di contenuti
|
||||
(promozioni, «storia vista») si ignorano (`relevance`). Senza riscontro restano vuoti `pinned`, `postCount` e
|
||||
`version.hasAudio`; le serie (`carousel_media`) sono una chiave vista ma sempre vuota nei campioni.
|
||||
- `src/Febe.Core/Config/bersagli.instagram.json`: compilate le **pagine** con una prova reale (home, profilo, post,
|
||||
visualizzatore delle storie e delle raccolte, dalle definizioni delle pagine e dai Referer del HAR); i **bersagli**
|
||||
sono vuoti (H11). Le ricette che non ne hanno bisogno girano; quelle che li usano (storie, raccolte, schede Taggati e
|
||||
Reel) rispondono «la mappa dei bersagli non è ancora compilata (mancano …)» senza aprire pagine e senza chiedere
|
||||
permessi. Questi file si possono sostituire con una copia nella cartella Dati, che vince su quella incorporata.
|
||||
- La cattura legge anche le risposte `text/javascript` chieste dalla pagina (così Instagram manda i dati GraphQL) e il
|
||||
JSON incorporato nel documento della pagina (da confermare dal vivo: il HAR non aveva documenti).
|
||||
- `segnali.json`: regole di partenza, ancora ipotesi H8.
|
||||
- Sonda: `febe-sonda registra`, `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Sonda: `febe-sonda registra`, `da-har` (da un HAR del browser), `ripulisci`, `verifica` (procedura in `docs/prove-dal-vivo.md`).
|
||||
- Il sito di prova fa girare tutte le ricette con un browser vero (`tests/Febe.Tests/Collection/`): è la prova che la
|
||||
raccolta funziona **quando** mappa e vocabolario saranno compilati, non che Instagram si comporti allo stesso modo.
|
||||
+53
-5
@@ -1,10 +1,38 @@
|
||||
# Stato
|
||||
|
||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||
Aggiornato il 21 ottobre 2026, versione 0.1.1 (anteprima).
|
||||
Aggiornato il 25 ottobre 2026, versione 0.1.1 (anteprima), 0.1.2 in preparazione.
|
||||
|
||||
## In breve
|
||||
|
||||
**25 ottobre 2026: Febe legge le risposte vere di Instagram** (ramo `correzione/lettura-instagram`).
|
||||
|
||||
- **Il guasto**: Instagram manda i dati di storie e raccolte (GraphQL) come `text/javascript`, e la cattura leggeva
|
||||
solo le risposte dichiarate JSON: le scartava tutte. In più `lettori.instagram.json` e `bersagli.instagram.json` erano
|
||||
scheletri e le ricette si rifiutavano di girare.
|
||||
- **I campioni**: Alberto ha mandato un HAR del suo browser (21/10, filtro Fetch/XHR) e una guida. La guida descrive
|
||||
richieste costruite a mano, vietate dalle regole 2–4, e un formato che nel HAR non compare: non si è usata. Del HAR si
|
||||
è letta solo la forma; le 8 risposte utili, accorciate dal lato grezzo, ripulite e verificate («Verifica superata»),
|
||||
sono in `tests/Febe.Tests/campioni/instagram` (vedi il suo `LEGGIMI.md`). I grezzi convertiti sono stati cancellati.
|
||||
- **Che cosa cambia**: la cattura legge le risposte `text/javascript` chieste dalla pagina e il JSON incorporato nel
|
||||
documento (questo da confermare: il HAR non aveva documenti); le risposte che non parlano di contenuti si ignorano;
|
||||
il vocabolario di Instagram è «confermato» e ogni sua chiave compare nei campioni; la mappa ha le pagine viste nel
|
||||
traffico vero, i bersagli no. Le ricette del profilo reggono dati che arrivano in risposte diverse; il visualizzatore
|
||||
delle raccolte conta i contenuti (l'indirizzo non cambia); le ricette che la configurazione non lascia girare sono
|
||||
«Da configurare», non guasti, e le sospensioni dovute ai file vecchi si azzerano da sole al primo avvio.
|
||||
- **Che cosa gira su Instagram**: giro dei seguiti, controllo del profilo, storico, post singolo. **Non ancora**:
|
||||
storie, raccolte, Taggati, Reel (mancano i bersagli, H11) ed elenco dei seguiti (manca l'indirizzo). Nulla è stato
|
||||
provato dal vivo.
|
||||
- **Strumenti per Alberto**: `febe-sonda da-har` (HAR → campioni grezzi, poi `ripulisci` e `verifica`) e
|
||||
`tools/bersagli/raccogli-bersagli.js` (bersagli in sola lettura dalla Console); procedura in
|
||||
`docs/prove-dal-vivo.md`, parte A bis.
|
||||
- **Cancellazione automatica delle immagini delle Actions**: era già attiva dal 21/10 (ogni lavoro «immagine» toglie la
|
||||
sua immagine e le penzolanti; ogni lunedì la pulizia completa, la prima vera lunedì 26/10 alle 4:17). Nulla da
|
||||
cambiare. L'immagine si pubblica sul registro solo con `REGISTRY_TOKEN`, che manca ancora.
|
||||
- Lavoro fatto da più agenti in parallelo, ciascuno su un ramo di lavoro, poi revisione avversaria: 21 rilievi, 17
|
||||
confermati e corretti (uno solo in parte, vedi sotto), e un solo commit. Prove: 783 superate, 76 saltate su Windows
|
||||
(Chromium e Xvfb), da rivedere nella CI.
|
||||
|
||||
**21 ottobre 2026.**
|
||||
|
||||
- **0.1.1 rilasciata**: tag `v0.1.1`, release con installatore, zip portabile, modello Unraid e archivio per Compose.
|
||||
@@ -66,10 +94,14 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Da fare (di Alberto)
|
||||
|
||||
1. **Sonda di M0** con l'account di prova (domanda 2 di §16): `docs/prove-dal-vivo.md`, parte A. Poi mandare i
|
||||
campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano
|
||||
`bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito.
|
||||
2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B).
|
||||
1. **Bersagli e campioni dal browser di tutti i giorni** (`docs/prove-dal-vivo.md`, parte A bis, una decina di
|
||||
minuti): HAR con il filtro «Tutti» e «Conserva log», lo script `tools/bersagli/raccogli-bersagli.js` nella Console,
|
||||
poi `febe-sonda da-har`, `ripulisci`, `verifica`. Mandare solo la cartella ripulita e il testo dei bersagli: con
|
||||
quelli si compilano i bersagli di storie, raccolte, Taggati e Reel e si confermano la home, il profilo e le storie
|
||||
di un account (H1–H4, H6, H11). In alternativa la sonda (parte A).
|
||||
2. **Prima sessione dal vivo** con il profilo Prudente su un profilo pubblico (parte B): già possibile per giro dei
|
||||
seguiti, controllo del profilo, storico e post singolo. Da guardare: i file in Libreria (H5, H7), «Tu» riconosciuto
|
||||
(H10), nessun «formato non riconosciuto» in Attività.
|
||||
3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.1 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
vero.
|
||||
@@ -105,6 +137,22 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
(vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha
|
||||
appena collegato Febe aspetta.
|
||||
|
||||
## Rilievi aperti (25 ottobre)
|
||||
|
||||
- Nessuna di queste modifiche è stata provata con Instagram: la prima sessione dal vivo (parte B) dirà se i dati del
|
||||
primo schermo arrivano nel documento o con XHR, se i file video hanno l'audio (H5) e se si scaricano (H7).
|
||||
- I blocchi JSON dei documenti di Instagram non si sono mai visti (il HAR non aveva documenti): forma e ordine ignoti.
|
||||
Le regole di testo di `segnali.json` ora li guardano uno per uno; un falso segnale si vedrebbe in Attività.
|
||||
- Visualizzatore senza identificativo nell'indirizzo (le raccolte): un clic «avanti» che la pagina ignora non si vede,
|
||||
e il conteggio salverebbe un contenuto non mostrato; una foto che il sito lascia da sola fa restare indietro il
|
||||
conteggio. Da misurare quando i bersagli ci saranno. Con le storie l'indirizzo dice quale storia è a video, se
|
||||
Instagram lo aggiorna (da confermare con lo script dei bersagli).
|
||||
- Un account Instagram senza post resta con lo storico aperto: a ogni sessione costa un'attesa di 20 s e una pagina.
|
||||
- Il pannello «Con queste impostazioni» di un profilo non seguito conta le visite all'intervallo delle storie anche
|
||||
mentre le storie non possono girare (sovrastima).
|
||||
- «Post singolo» accodati per gli indirizzi scaduti ora girano davvero (prima la coda li annullava): dentro il loro
|
||||
tetto, ma sono azioni in più su Instagram.
|
||||
|
||||
## Rilievi aperti (21 ottobre)
|
||||
|
||||
- Le note della release scritte da `rilascio.yml` senza immagine dicono «`:latest` resta sulla versione precedente», ma
|
||||
|
||||
@@ -24,4 +24,7 @@ public sealed class DeferredRecipeRunner : IRecipeRunner
|
||||
: Task.FromResult(new RecipeOutcome(RecipeStatus.Cancelled, 0, 0, "Il browser non è ancora pronto."));
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => _target?.RestAsync(ct) ?? Task.CompletedTask;
|
||||
|
||||
/// <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);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -372,6 +373,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
runner.Target = Pipeline.Runner;
|
||||
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
|
||||
var changes = Web.Services.GetRequiredService<LibraryChanges>();
|
||||
_disposables.Add(changes.Attach(Pipeline.Downloads, Clock));
|
||||
_background.Add(Task.Run(() => DownloadLoopAsync(Pipeline.Downloads, ct), CancellationToken.None));
|
||||
@@ -412,6 +414,39 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which reader vocabulary and target map the collection uses, in the log: where each came from (embedded in Febe or
|
||||
/// the copy in the Data folder) and in what state, never what is in them; a warning when a copy in the Data folder
|
||||
/// hides a better embedded file. Then the engine clears, once, the suspensions and failures of the recipes counted
|
||||
/// against other files (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Before the engine loop starts.
|
||||
/// </summary>
|
||||
private async Task CheckCollectionConfigurationAsync(CollectionPipeline pipeline, EngineHost engine, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var configuration = CollectionConfiguration.Describe(_options.Site.Name, pipeline.Vocabulary, pipeline.SiteMap);
|
||||
foreach (var line in configuration.Lines)
|
||||
{
|
||||
Log.Info("raccolta", line);
|
||||
}
|
||||
|
||||
foreach (var warning in configuration.Warnings)
|
||||
{
|
||||
Log.Warn("raccolta", warning);
|
||||
}
|
||||
|
||||
if (await engine.ApplyCollectionConfigurationAsync(configuration.Fingerprint, ct).ConfigureAwait(false))
|
||||
{
|
||||
Log.Info("raccolta", $"Configurazione della raccolta diversa dall'ultimo avvio (impronta {configuration.Fingerprint[..12]}): sospensioni ed errori contati delle ricette azzerati.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Never a reason not to collect: the suspensions stay as they are, «Riattiva» still clears them.
|
||||
Log.Warn("raccolta", "Non riesco a confrontare la configurazione della raccolta con quella dell'ultimo avvio: le ricette sospese restano come sono.", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
|
||||
/// the site once, so that its session cookie exists — then back to the rest page.
|
||||
|
||||
@@ -19,8 +19,17 @@ public sealed record ResponseTapOptions
|
||||
/// <summary>How long to wait for one body before giving up on it (one stuck request must not block the others).</summary>
|
||||
public TimeSpan BodyTimeout { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>Decides from the declared MIME type whether a body is worth parsing as JSON.</summary>
|
||||
public Func<string, bool> IsJsonMimeType { get; init; } = static mime => mime.Contains("json", StringComparison.OrdinalIgnoreCase);
|
||||
/// <summary>
|
||||
/// Decides from the declared MIME type and the resource type whether a body is worth parsing as JSON
|
||||
/// (<see cref="DataResponses.IsData"/>: JSON, and JavaScript the page fetched itself).
|
||||
/// </summary>
|
||||
public Func<string, string?, bool> IsDataResponse { get; init; } = DataResponses.IsData;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the main document of a site page is read too, for the JSON blocks it embeds
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>).
|
||||
/// </summary>
|
||||
public bool ReadPageDocuments { get; init; } = true;
|
||||
|
||||
/// <summary>Per-resource buffer of the browser (<c>Network.enable</c> maxResourceBufferSize).</summary>
|
||||
public int BrowserResourceBufferBytes { get; init; } = 32 * 1024 * 1024;
|
||||
@@ -37,22 +46,26 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
|
||||
/// and the metadata of every response and main-frame navigation to <see cref="IResponseObserver"/>s.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It does not filter by address: readers recognise data by its shape (spec §6.4). Bodies stay in memory for the
|
||||
/// time of the reading, are never written to disk and never logged. Event handlers only queue work; bodies are
|
||||
/// fetched and parsed on a background worker, one at a time.
|
||||
/// It does not filter by address: readers recognise data by its shape (spec §6.4). A body is read when the browser
|
||||
/// declares it as JSON, or as JavaScript fetched by the page (Instagram's GraphQL answers), and the main document of a
|
||||
/// site page is read for the JSON blocks it embeds, each handed to consumers as an answer of its own with the
|
||||
/// document's descriptor. Bodies stay in memory for the time of the reading, are never written to disk and never
|
||||
/// logged. Event handlers only queue work; bodies are fetched and parsed on a background worker, one at a time.
|
||||
/// </remarks>
|
||||
public sealed class ResponseTap : IAsyncDisposable
|
||||
{
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly HostClassifier _hosts;
|
||||
private readonly IClock _clock;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly ResponseTapOptions _options;
|
||||
private readonly ConcurrentDictionary<string, ResponseDescriptor> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, PendingBody> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<IResponseConsumer> _consumers = [];
|
||||
private readonly List<IResponseObserver> _observers = [];
|
||||
private readonly Channel<ResponseDescriptor> _queue = Channel.CreateUnbounded<ResponseDescriptor>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
private Task? _worker;
|
||||
@@ -181,7 +194,14 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private void OnReconnected(object? sender, EventArgs e)
|
||||
{
|
||||
_inFlight.Clear();
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (_inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key);
|
||||
}
|
||||
}
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
@@ -240,16 +260,21 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (_options.IsJsonMimeType(mime) && status is >= 200 and < 600 && status != 204)
|
||||
if (_options.IsDataResponse(mime, type) && status is >= 200 and < 600 && status != 204)
|
||||
{
|
||||
_inFlight[requestId] = descriptor;
|
||||
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: false);
|
||||
}
|
||||
else if (_options.ReadPageDocuments && descriptor.HostKind == HostKind.Site && status is >= 200 and < 300
|
||||
&& DataResponses.IsPageDocument(mime, isMainDocument))
|
||||
{
|
||||
_inFlight[requestId] = new PendingBody(descriptor, IsPageDocument: true);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnLoadingFinished(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|
||||
|| !_inFlight.TryRemove(requestId, out var descriptor))
|
||||
|| !_inFlight.TryRemove(requestId, out var pending))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -258,17 +283,19 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
if (length > _options.MaxBodyBytes)
|
||||
{
|
||||
Interlocked.Increment(ref _skipped);
|
||||
NotifyDropped(requestId);
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.Writer.TryWrite(descriptor);
|
||||
_queue.Writer.TryWrite(pending);
|
||||
}
|
||||
|
||||
private void OnLoadingFailed(JsonElement p)
|
||||
{
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId)
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
|
||||
&& _inFlight.TryRemove(requestId, out _))
|
||||
{
|
||||
_inFlight.TryRemove(requestId, out _);
|
||||
NotifyDropped(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,8 +311,16 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
_mainFrameId = frame.TryGetProperty("id", out var id) ? id.GetString() : _mainFrameId;
|
||||
|
||||
// Requests of the previous document that never finished (e.g. a body the page did not read: Chromium then
|
||||
// sends no loadingFinished) will not finish any more: forget them.
|
||||
_inFlight.Clear();
|
||||
// sends no loadingFinished) will not finish any more: forget them. The new document itself is kept: the frame
|
||||
// commits it before its body has finished loading (its request id is the frame's loader id).
|
||||
var loader = frame.TryGetProperty("loaderId", out var l) ? l.GetString() : null;
|
||||
foreach (var key in _inFlight.Keys)
|
||||
{
|
||||
if (key != loader && _inFlight.TryRemove(key, out _))
|
||||
{
|
||||
NotifyDropped(key);
|
||||
}
|
||||
}
|
||||
Publish(frame.TryGetProperty("url", out var u) ? u.GetString() : null, sameDocument: false);
|
||||
}
|
||||
|
||||
@@ -325,64 +360,128 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private async Task WorkAsync(CancellationToken ct)
|
||||
{
|
||||
await foreach (var descriptor in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
try
|
||||
{
|
||||
IResponseConsumer[] consumers;
|
||||
lock (_gate)
|
||||
await foreach (var pending in _queue.Reader.ReadAllAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
consumers = [.. _consumers];
|
||||
try
|
||||
{
|
||||
await HandleAsync(pending, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
// One unexpected body must not stop the capture of the following ones. Only the type: the message
|
||||
// of a parsing error may quote the body.
|
||||
_log.Warn($"Cattura: errore imprevisto nella lettura di una risposta ({ex.GetType().Name}).");
|
||||
NotifyDropped(pending.Descriptor.RequestId);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
/// <summary>Fetches one body and hands it to the consumers; tells the observers once when nothing reached them.</summary>
|
||||
private async Task HandleAsync(PendingBody pending, CancellationToken ct)
|
||||
{
|
||||
var descriptor = pending.Descriptor;
|
||||
IResponseConsumer[] consumers;
|
||||
lock (_gate)
|
||||
{
|
||||
consumers = [.. _consumers];
|
||||
}
|
||||
|
||||
if (consumers.Length == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
return;
|
||||
}
|
||||
|
||||
byte[]? bytes;
|
||||
try
|
||||
{
|
||||
bytes = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
return;
|
||||
}
|
||||
|
||||
var delivered = bytes is null ? 0
|
||||
: pending.IsPageDocument ? await ConsumeDocumentAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false)
|
||||
: await ConsumeBodyAsync(descriptor, bytes, consumers, ct).ConfigureAwait(false);
|
||||
if (delivered == 0)
|
||||
{
|
||||
NotifyDropped(descriptor.RequestId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The body of a data response, as one answer. Returns how many answers reached the consumers (0 or 1).</summary>
|
||||
private async Task<int> ConsumeBodyAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(bytes, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Not JSON after all (e.g. Instagram's «for (;;);» answers of /ajax/, which carry no contents): skipped.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return 0;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
await DeliverAsync(descriptor, document, consumers, ct).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page document embeds, each handed to the consumers as an answer of its own with the document's
|
||||
/// descriptor, so that a pagination stays with the block that carries it
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). One block at a time: each is disposed before the next is parsed.
|
||||
/// Returns how many blocks reached the consumers; a document without any is not data, and not a parse error.
|
||||
/// </summary>
|
||||
private async Task<int> ConsumeDocumentAsync(ResponseDescriptor descriptor, byte[] bytes, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
var delivered = 0;
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
continue;
|
||||
delivered++;
|
||||
await DeliverAsync(descriptor, block, consumers, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
JsonDocument? document;
|
||||
return delivered;
|
||||
}
|
||||
|
||||
private async Task DeliverAsync(ResponseDescriptor descriptor, JsonDocument body, IResponseConsumer[] consumers, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
document = await FetchBodyAsync(descriptor.RequestId, ct).ConfigureAwait(false);
|
||||
await consumer.ConsumeAsync(descriptor, body, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or CdpDisconnectedException or BrowserUnavailableException or TimeoutException)
|
||||
{
|
||||
// The body may already be evicted from the browser's buffer, or the page navigated away.
|
||||
Interlocked.Increment(ref _bodyErrors);
|
||||
_log.Debug($"Cattura: corpo non disponibile ({ex.GetType().Name}).");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (document is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
Interlocked.Increment(ref _jsonBodies);
|
||||
foreach (var consumer in consumers)
|
||||
{
|
||||
try
|
||||
{
|
||||
await consumer.ConsumeAsync(descriptor, document, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
_log.Warn($"Cattura: errore in un lettore ({consumer.GetType().Name}).", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<JsonDocument?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
/// <summary>The decoded bytes of a body, or null when the browser gives none or it cannot be decoded.</summary>
|
||||
private async Task<byte[]?> FetchBodyAsync(string requestId, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(_options.BodyTimeout);
|
||||
@@ -402,34 +501,39 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
|
||||
var encoded = result.TryGetProperty("base64Encoded", out var b) && b.ValueKind == JsonValueKind.True;
|
||||
byte[] bytes;
|
||||
if (encoded)
|
||||
if (!encoded)
|
||||
{
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
bytes = decoded;
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes = Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
return Encoding.UTF8.GetBytes(body.GetString() ?? string.Empty);
|
||||
}
|
||||
|
||||
try
|
||||
if (!body.TryGetBytesFromBase64(out var decoded))
|
||||
{
|
||||
return JsonDocument.Parse(bytes, new JsonDocumentOptions { MaxDepth = 256 });
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Declared as JSON but it is not (or has a prefix): readers will be told by the probe in M0.
|
||||
Interlocked.Increment(ref _parseErrors);
|
||||
return null;
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/// <summary>Tells the observers that a body they may be waiting for will not come.</summary>
|
||||
private void NotifyDropped(string requestId)
|
||||
{
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnBodyDropped(requestId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle risposte.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A body to fetch once its loading has finished.</summary>
|
||||
private sealed record PendingBody(ResponseDescriptor Descriptor, bool IsPageDocument);
|
||||
|
||||
private IResponseObserver[] SnapshotObservers()
|
||||
{
|
||||
lock (_gate)
|
||||
|
||||
@@ -23,8 +23,8 @@ namespace Febe.Browser.Recipes;
|
||||
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
|
||||
{
|
||||
/// <summary>
|
||||
/// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and
|
||||
/// says why, without touching the site.
|
||||
/// Instagram. Its reader vocabulary is confirmed on real cleaned samples and its map has the pages seen in real
|
||||
/// traffic, not yet the targets: a recipe that needs a target refuses to run and says why, without touching the site.
|
||||
/// </summary>
|
||||
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>One configuration file of the collection as it was loaded.</summary>
|
||||
/// <param name="Name">File name: <c>lettori.instagram.json</c>, <c>bersagli.instagram.json</c>.</param>
|
||||
/// <param name="OverridePath">The editable copy in the Data folder that was loaded; null for the copy embedded in Febe.</param>
|
||||
/// <param name="Text">Its content (for the fingerprint only: never logged).</param>
|
||||
public sealed record CollectionConfigurationFile(string Name, string? OverridePath, string Text)
|
||||
{
|
||||
public bool IsOverride => OverridePath is not null;
|
||||
|
||||
/// <summary>Where it came from, in Italian, for the log: never what is in it.</summary>
|
||||
public string Origin => OverridePath is { } path
|
||||
? $"la copia nella cartella dei dati ({path})"
|
||||
: $"il file incorporato in Febe ({Name})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reader vocabulary and target map one site runs on, as the collection pipeline loaded them: where each came from
|
||||
/// (the copy embedded in Febe, or an editable copy in the Data folder, which always wins), its state, the recipes they
|
||||
/// leave unable to run, and a fingerprint of their content. The engine clears the suspensions of the recipes when the
|
||||
/// fingerprint changes (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>). Nothing here comes from the site.
|
||||
/// </summary>
|
||||
public sealed class CollectionConfiguration
|
||||
{
|
||||
private CollectionConfiguration(
|
||||
string site,
|
||||
ReaderVocabulary vocabulary,
|
||||
SiteMap map,
|
||||
CollectionConfigurationFile vocabularyFile,
|
||||
CollectionConfigurationFile mapFile,
|
||||
ReaderVocabulary? embeddedVocabulary,
|
||||
SiteMap? embeddedMap)
|
||||
{
|
||||
Site = site;
|
||||
Vocabulary = vocabulary;
|
||||
Map = map;
|
||||
VocabularyFile = vocabularyFile;
|
||||
MapFile = mapFile;
|
||||
EmbeddedVocabulary = embeddedVocabulary;
|
||||
EmbeddedMap = embeddedMap;
|
||||
Blocked = BlockedBy(map, vocabulary);
|
||||
Fingerprint = FingerprintOf(site, vocabularyFile, mapFile);
|
||||
}
|
||||
|
||||
/// <summary>The site name of the files (<c>instagram</c>, <c>prova</c>).</summary>
|
||||
public string Site { get; }
|
||||
|
||||
public ReaderVocabulary Vocabulary { get; }
|
||||
|
||||
public SiteMap Map { get; }
|
||||
|
||||
public CollectionConfigurationFile VocabularyFile { get; }
|
||||
|
||||
public CollectionConfigurationFile MapFile { get; }
|
||||
|
||||
/// <summary>The vocabulary embedded in Febe, when there is one (the same as <see cref="Vocabulary"/> without a copy).</summary>
|
||||
public ReaderVocabulary? EmbeddedVocabulary { get; }
|
||||
|
||||
/// <summary>The map embedded in Febe, when there is one (the same as <see cref="Map"/> without a copy).</summary>
|
||||
public SiteMap? EmbeddedMap { get; }
|
||||
|
||||
/// <summary>Recipes these files do not let run (<see cref="RecipeStatus.NotConfigured"/>), in the order of <see cref="RecipeKind"/>.</summary>
|
||||
public IReadOnlyList<RecipeKind> Blocked { get; }
|
||||
|
||||
/// <summary>SHA-256 of the two files as loaded (lower-case hexadecimal), line endings aside.</summary>
|
||||
public string Fingerprint { get; }
|
||||
|
||||
/// <summary>What the log says at start-up: where each file came from and in what state, and what cannot run.</summary>
|
||||
public IReadOnlyList<string> Lines
|
||||
{
|
||||
get
|
||||
{
|
||||
var all = Enum.GetValues<RecipeKind>().Length;
|
||||
var vocabularyState = Vocabulary.Status == VocabularyStatus.Confirmed ? "confermato" : "ipotesi";
|
||||
if (Vocabulary.MissingConcepts.Count > 0)
|
||||
{
|
||||
vocabularyState += $", {Vocabulary.MissingConcepts.Count.ToString(CultureInfo.InvariantCulture)} concetti ancora senza chiavi";
|
||||
}
|
||||
|
||||
var missing = Map.Missing(SitePages.All, SiteTargets.All).Count;
|
||||
var mapState = missing == 0 ? "tutte le voci compilate" : $"{missing.ToString(CultureInfo.InvariantCulture)} voci vuote o assenti";
|
||||
return
|
||||
[
|
||||
$"Vocabolario dei lettori per «{Site}»: {VocabularyFile.Origin}, {vocabularyState}.",
|
||||
$"Mappa dei bersagli per «{Site}»: {MapFile.Origin}, {mapState}.",
|
||||
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)}.",
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy in the Data folder that hides a better embedded file: a vocabulary still «ipotesi» while the embedded one
|
||||
/// is «confermato», or a map that leaves recipes unable to run that the embedded one lets run. A stale copy would
|
||||
/// otherwise keep the new files of an update from ever being used.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Warnings
|
||||
{
|
||||
get
|
||||
{
|
||||
var warnings = new List<string>();
|
||||
if (VocabularyFile.IsOverride && EmbeddedVocabulary is { } embedded
|
||||
&& Vocabulary.Status == VocabularyStatus.Hypothesis && embedded.Status == VocabularyStatus.Confirmed)
|
||||
{
|
||||
warnings.Add($"Il vocabolario dei lettori in {VocabularyFile.OverridePath} è ancora un'ipotesi, mentre quello incorporato in Febe è confermato: la copia nella cartella dei dati nasconde quello nuovo. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
|
||||
if (MapFile.IsOverride && EmbeddedMap is { } embeddedMap)
|
||||
{
|
||||
var hidden = MissingFrom(Map).Except(MissingFrom(embeddedMap)).ToList();
|
||||
if (hidden.Count > 0)
|
||||
{
|
||||
warnings.Add($"La mappa dei bersagli in {MapFile.OverridePath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare ({Names(hidden)}): la copia nella cartella dei dati nasconde quella nuova. Toglila (o aggiornala) e riavvia Febe.");
|
||||
}
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes what was loaded for <paramref name="site"/>: <paramref name="vocabulary"/> and <paramref name="map"/>
|
||||
/// 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>
|
||||
/// <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)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(site);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
var vocabularyFile = LoadedFile($"lettori.{site}.json", vocabulary.Source);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
ArgumentNullException.ThrowIfNull(vocabulary);
|
||||
return vocabulary.IsUsable ? MissingFrom(map) : Enum.GetValues<RecipeKind>();
|
||||
}
|
||||
|
||||
/// <summary>The recipes whose pages or targets the map lacks, whatever the vocabulary.</summary>
|
||||
private static RecipeKind[] MissingFrom(SiteMap map) =>
|
||||
[.. Enum.GetValues<RecipeKind>().Where(kind =>
|
||||
{
|
||||
var (pages, targets) = RecipeRunner.Requirements(kind);
|
||||
return map.Missing(pages, targets).Count > 0;
|
||||
})];
|
||||
|
||||
private static CollectionConfigurationFile LoadedFile(string name, string? source)
|
||||
{
|
||||
if (source is { Length: > 0 } path && !string.Equals(path, name, StringComparison.Ordinal))
|
||||
{
|
||||
return new CollectionConfigurationFile(name, path, File.ReadAllText(path));
|
||||
}
|
||||
|
||||
return new CollectionConfigurationFile(name, null, SiteMap.ReadEmbeddedText(name));
|
||||
}
|
||||
|
||||
private static T? Try<T>(Func<T> load)
|
||||
where T : class
|
||||
{
|
||||
try
|
||||
{
|
||||
return load();
|
||||
}
|
||||
catch (Exception ex) when (ex is FileNotFoundException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string FingerprintOf(string site, CollectionConfigurationFile vocabulary, CollectionConfigurationFile map)
|
||||
{
|
||||
static string Normalized(string text) => text.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
var text = string.Join('\n', site, vocabulary.Name, Normalized(vocabulary.Text), map.Name, Normalized(map.Text));
|
||||
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
|
||||
}
|
||||
|
||||
private static string Names(IEnumerable<RecipeKind> kinds) => string.Join(", ", kinds.Select(RecipeRunner.Name));
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// Which responses of the page carry data worth reading (spec §6.2), decided from what the browser declares about
|
||||
/// them, never from the address.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Instagram serves its GraphQL data (<c>/graphql/query</c>, <c>/api/graphql</c>) as <c>text/javascript</c>, and only
|
||||
/// the REST answers (<c>/api/v1/...</c>) as <c>application/json</c> (HAR of Alberto's browser, 21 October 2026). A
|
||||
/// JavaScript type counts only when the page itself fetched it (XHR, Fetch): script files are never parsed.
|
||||
/// </remarks>
|
||||
public static partial class DataResponses
|
||||
{
|
||||
/// <summary>Largest page document whose embedded data is read.</summary>
|
||||
public const int MaxDocumentChars = 16 * 1024 * 1024;
|
||||
|
||||
private static readonly JsonDocumentOptions BlockOptions = new() { MaxDepth = 256 };
|
||||
|
||||
/// <summary>True for a body worth parsing as JSON data.</summary>
|
||||
/// <param name="mimeType">Declared MIME type, without parameters.</param>
|
||||
/// <param name="resourceType">Browser resource type (Document, XHR, Fetch, Script...), when known.</param>
|
||||
public static bool IsData(string mimeType, string? resourceType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(mimeType);
|
||||
if (mimeType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return mimeType.Contains("javascript", StringComparison.OrdinalIgnoreCase)
|
||||
&& resourceType is not null
|
||||
&& (resourceType.Equals("XHR", StringComparison.OrdinalIgnoreCase) || resourceType.Equals("Fetch", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>True for an HTML document of the main frame: the data it embeds is read too (<see cref="EmbeddedJsonBlocks"/>).</summary>
|
||||
public static bool IsPageDocument(string mimeType, bool isMainFrameDocument) =>
|
||||
isMainFrameDocument && mimeType.Equals("text/html", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// The JSON blocks a page embeds in <c><script type="application/json"></c> elements, one parsed document per
|
||||
/// block, in document order; none when there is none. Blocks that are not valid JSON are left out.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Single-page sites put the data of the first screen in the document itself and fetch only the following pages:
|
||||
/// without this, the first page of a profile opened by address would arrive «empty». The reader recognizes the data by
|
||||
/// shape wherever it sits inside a block (spec §6.4).
|
||||
/// <para>
|
||||
/// Every block is an answer of its own and is read on its own, like a response: joined to the others, the
|
||||
/// pagination of one block (collections that say «has_next_page» of themselves, a post that says
|
||||
/// «more_available: false» of itself) would end up on the items of another and end a walk early. The blocks are
|
||||
/// parsed lazily, one per step of the enumeration: the caller disposes each before taking the next, so a large
|
||||
/// document never has all its blocks in memory at once.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IEnumerable<JsonDocument> EmbeddedJsonBlocks(string html)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(html);
|
||||
return html.Length > MaxDocumentChars ? [] : Blocks(html);
|
||||
}
|
||||
|
||||
private static IEnumerable<JsonDocument> Blocks(string html)
|
||||
{
|
||||
for (var match = NextBlock(html, previous: null); match is not null; match = NextBlock(html, match))
|
||||
{
|
||||
var body = match.Groups["body"];
|
||||
if (TryParse(html.AsMemory(body.Index, body.Length)) is { } block)
|
||||
{
|
||||
yield return block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The block element after <paramref name="previous"/> (the first one when null), or null at the end.</summary>
|
||||
private static Match? NextBlock(string html, Match? previous)
|
||||
{
|
||||
try
|
||||
{
|
||||
var match = previous is null ? JsonScript().Match(html) : previous.NextMatch();
|
||||
return match.Success ? match : null;
|
||||
}
|
||||
catch (RegexMatchTimeoutException)
|
||||
{
|
||||
// A pathological document: the blocks found so far have been given, the rest is left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonDocument? TryParse(ReadOnlyMemory<char> text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonDocument.Parse(text, BlockOptions);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or ArgumentException)
|
||||
{
|
||||
// Not JSON, or too deep; ArgumentException: text that is not valid UTF-16 (a lone surrogate). Left out.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex("""<script\b[^>]*?\btype\s*=\s*["']?application/json["']?[^>]*>(?<body>.*?)</script\s*>""", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 5000)]
|
||||
private static partial Regex JsonScript();
|
||||
}
|
||||
@@ -73,8 +73,9 @@ public sealed class HostClassifier
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from.
|
||||
/// Public knowledge, not response formats; still to be confirmed by the M0 probe.
|
||||
/// Instagram's public host names: the site and the two CDN families its pages load files from. In the HAR of
|
||||
/// 21 October 2026 the data came from www.instagram.com (logging from graph.instagram.com), the video files from
|
||||
/// scontent-*.cdninstagram.com and the scripts from static.cdninstagram.com; fbcdn.net is public knowledge.
|
||||
/// </summary>
|
||||
public static HostClassifier Instagram { get; } = new(
|
||||
["instagram.com"],
|
||||
|
||||
@@ -69,4 +69,13 @@ public interface IResponseObserver
|
||||
void OnResponse(ResponseDescriptor response);
|
||||
|
||||
void OnNavigation(NavigationDescriptor navigation);
|
||||
|
||||
/// <summary>
|
||||
/// The body of a data response announced by <see cref="OnResponse"/> will not reach the consumers: it failed to
|
||||
/// load, was too large, was not JSON after all (Instagram's «for (;;);» answers), or the page moved on. Observers
|
||||
/// that wait for bodies stop waiting for this one.
|
||||
/// </summary>
|
||||
void OnBodyDropped(string requestId)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,12 @@ public enum ReadShape
|
||||
|
||||
/// <summary>A shape the vocabulary does not describe: event «formato non riconosciuto» (spec §6.4).</summary>
|
||||
Unrecognized,
|
||||
|
||||
/// <summary>
|
||||
/// Nothing the vocabulary speaks about: none of its relevance keys appears anywhere (promotions, logging, a search
|
||||
/// box). Ignored: neither data, nor an empty page, nor an unknown shape (<see cref="ReaderVocabulary.Relevance"/>).
|
||||
/// </summary>
|
||||
Unrelated,
|
||||
}
|
||||
|
||||
/// <summary>Everything one response gave, detached from the JSON document (which is disposed right after).</summary>
|
||||
@@ -146,6 +152,12 @@ public sealed record ReadResult
|
||||
|
||||
public ProfileInfo? Viewer { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account, also when the answer describes it with nothing else (Instagram's
|
||||
/// <c>xdt_viewer.user</c>): a profile with this identifier in another answer is the connected account (H10).
|
||||
/// </summary>
|
||||
public string? ViewerId { get; init; }
|
||||
|
||||
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
|
||||
public string? KeyStructure { get; init; }
|
||||
}
|
||||
@@ -185,6 +185,15 @@ public sealed record ReaderVocabulary
|
||||
/// <summary>The key under which the response describes the connected account (H10).</summary>
|
||||
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>
|
||||
/// Keys at least one of which, anywhere in a response, makes it «about contents or profiles». A response that has
|
||||
/// none of them is <see cref="ReadShape.Unrelated"/> and ignored, instead of counting as an unknown shape: a real site
|
||||
/// sends many JSON answers that have nothing to do with contents (Instagram: promotions, logging, «seen» marks).
|
||||
/// Plain key names, not paths. Empty: every response counts (the test site, where any unknown answer is a format
|
||||
/// change).
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Relevance { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Concepts the collection pipeline cannot work without, still unset. While this is not empty, or the status is
|
||||
/// a hypothesis, recipes refuse to run on the site.
|
||||
@@ -319,6 +328,7 @@ public sealed record ReaderVocabulary
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Viewer = K(file.Viewer),
|
||||
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -342,6 +352,15 @@ internal sealed class VocabularyFile
|
||||
public PageDto? Page { get; set; }
|
||||
|
||||
public List<string>? Viewer { get; set; }
|
||||
|
||||
public RelevanceDto? Relevance { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class RelevanceDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Keys { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class ContentDto
|
||||
|
||||
@@ -20,10 +20,12 @@ public sealed class ShapeReader
|
||||
private const int MaxDepth = 64;
|
||||
|
||||
private readonly ReaderVocabulary _v;
|
||||
private readonly HashSet<string> _relevance;
|
||||
|
||||
public ShapeReader(ReaderVocabulary vocabulary)
|
||||
{
|
||||
_v = vocabulary ?? throw new ArgumentNullException(nameof(vocabulary));
|
||||
_relevance = new HashSet<string>(vocabulary.Relevance, StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
public ReaderVocabulary Vocabulary => _v;
|
||||
@@ -34,6 +36,12 @@ public sealed class ShapeReader
|
||||
var walk = new Walk();
|
||||
Visit(root, walk, owner: null, highlightId: null, depth: 0);
|
||||
|
||||
if (walk.ViewerId is { } viewerId && walk.Profiles.TryGetValue(viewerId, out var own))
|
||||
{
|
||||
// The connected account described by its identifier only, and its profile elsewhere in the same answer.
|
||||
walk.Profiles[viewerId] = own with { IsViewer = true };
|
||||
}
|
||||
|
||||
var profiles = walk.Profiles.Values.ToList();
|
||||
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
|
||||
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
|
||||
@@ -46,12 +54,18 @@ public sealed class ShapeReader
|
||||
Highlights = walk.Highlights,
|
||||
Page = walk.Page,
|
||||
Viewer = viewer,
|
||||
ViewerId = viewer?.Id ?? walk.ViewerId,
|
||||
};
|
||||
}
|
||||
|
||||
if (IsEmptyShape(root, walk.Page is not null))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page };
|
||||
return new ReadResult { Shape = ReadShape.Empty, Page = walk.Page, ViewerId = walk.ViewerId };
|
||||
}
|
||||
|
||||
if (_relevance.Count > 0 && !HasAnyKey(root, 0))
|
||||
{
|
||||
return new ReadResult { Shape = ReadShape.Unrelated, ViewerId = walk.ViewerId };
|
||||
}
|
||||
|
||||
return new ReadResult { Shape = ReadShape.Unrecognized, Page = walk.Page, KeyStructure = KeyStructure.Describe(root) };
|
||||
@@ -93,9 +107,18 @@ public sealed class ShapeReader
|
||||
_v.Page.Cursor.TryGet(node, out var cursor) ? AsText(cursor) : null);
|
||||
}
|
||||
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode) && ReadProfile(viewerNode) is { } viewer)
|
||||
if (_v.Viewer.TryGet(node, out var viewerNode))
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
if (ReadProfile(viewerNode) is { } viewer)
|
||||
{
|
||||
walk.AddProfile(viewer with { IsViewer = true });
|
||||
}
|
||||
else if (viewerNode.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
// Instagram describes the connected account with its identifier only (xdt_viewer.user): kept, so a
|
||||
// profile with the same identifier can be recognized as the connected account (H10).
|
||||
walk.ViewerId ??= AsText(Get(_v.Profile.Id, viewerNode));
|
||||
}
|
||||
}
|
||||
|
||||
if (IsContent(node))
|
||||
@@ -116,7 +139,7 @@ public sealed class ShapeReader
|
||||
walk.AddProfile(highlightOwner);
|
||||
}
|
||||
|
||||
var id = AsText(Get(_v.Highlight.Id, node))!;
|
||||
var id = HighlightId(AsText(Get(_v.Highlight.Id, node))!);
|
||||
var before = walk.Contents.Count;
|
||||
if (_v.Highlight.Items.TryGet(node, out var items))
|
||||
{
|
||||
@@ -160,8 +183,26 @@ public sealed class ShapeReader
|
||||
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
|
||||
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
|
||||
|
||||
/// <summary>
|
||||
/// A highlight collection: identifier and title, and — when the vocabulary names them — an owner or its items, so
|
||||
/// that any other object with an «id» and a «title» (a promotion, a section of a page) is not taken for one.
|
||||
/// </summary>
|
||||
private bool IsHighlight(JsonElement node) =>
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null;
|
||||
_v.Highlight.Id.Has(node) && _v.Highlight.Title.Has(node) && AsText(Get(_v.Highlight.Id, node)) is not null
|
||||
&& ((!_v.Highlight.Owner.IsSet && !_v.Highlight.Items.IsSet) || _v.Highlight.Owner.Has(node) || _v.Highlight.Items.Has(node));
|
||||
|
||||
/// <summary>
|
||||
/// The identifier of a collection as its address carries it: Instagram writes «highlight:17841…» in the data and
|
||||
/// «/stories/highlights/17841…/» in the address (HAR of 21/10/2026), so a «kind:» prefix made of letters is dropped.
|
||||
/// </summary>
|
||||
internal static string HighlightId(string id)
|
||||
{
|
||||
var colon = id.IndexOf(':', StringComparison.Ordinal);
|
||||
return colon > 0 && colon < id.Length - 1 && id.AsSpan(0, colon).IndexOfAnyExcept(Letters) < 0 ? id[(colon + 1)..] : id;
|
||||
}
|
||||
|
||||
private static readonly System.Buffers.SearchValues<char> Letters =
|
||||
System.Buffers.SearchValues.Create("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_");
|
||||
|
||||
private ContentItem? ReadContent(JsonElement node, Walk walk, ProfileInfo? inheritedOwner, string? highlightId)
|
||||
{
|
||||
@@ -322,6 +363,41 @@ public sealed class ShapeReader
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when one of the relevance keys of the vocabulary is a property name anywhere under <paramref name="element"/>.</summary>
|
||||
private bool HasAnyKey(JsonElement element, int depth)
|
||||
{
|
||||
if (depth > MaxDepth)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (_relevance.Contains(property.Name) || HasAnyKey(property.Value, depth + 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (HasAnyKey(item, depth + 1))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Empty»: no list with elements anywhere, and either a recognized pagination or only plain values at the top
|
||||
/// (a bare status or error). Anything richer that nothing recognized is an unknown shape.
|
||||
@@ -464,6 +540,9 @@ public sealed class ShapeReader
|
||||
|
||||
public PageInfo? Page { get; set; }
|
||||
|
||||
/// <summary>Identifier of the connected account when the answer gives no more than that.</summary>
|
||||
public string? ViewerId { get; set; }
|
||||
|
||||
/// <summary>Merges what different parts of a response say about the same profile.</summary>
|
||||
public void AddProfile(ProfileInfo profile)
|
||||
{
|
||||
|
||||
@@ -29,6 +29,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
private readonly List<CapturedRead> _reads = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
||||
private long _sequence;
|
||||
private string? _viewerId;
|
||||
|
||||
public CaptureCollector(ShapeReader reader, IClock clock)
|
||||
{
|
||||
@@ -41,6 +42,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
/// <summary>How long a data response may stay «on its way» before it is forgotten (its body may never come).</summary>
|
||||
public TimeSpan PendingLifetime { get; init; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>
|
||||
/// Identifier of the connected account in the latest site answer that gave one (<see cref="ReadResult.ViewerId"/>),
|
||||
/// also an answer that is otherwise <see cref="ReadShape.Unrelated"/> and not kept.
|
||||
/// </summary>
|
||||
public string? ViewerId
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _viewerId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sequence number of the last read: pass it to <see cref="Since"/> to get what arrives after now.</summary>
|
||||
public long Mark()
|
||||
{
|
||||
@@ -135,7 +151,10 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Reads one body (also used by tests and the probe samples).</summary>
|
||||
/// <summary>
|
||||
/// Reads one body (also used by tests and the probe samples). Returns null, and keeps nothing, for responses that
|
||||
/// are not the site's or that are <see cref="ReadShape.Unrelated"/>.
|
||||
/// </summary>
|
||||
public CapturedRead? Accept(ResponseDescriptor response, JsonElement body)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
@@ -150,6 +169,21 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
|
||||
var result = _reader.Read(body);
|
||||
if (result.ViewerId is { } viewerId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_viewerId = viewerId;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.Shape == ReadShape.Unrelated)
|
||||
{
|
||||
// Not about contents (promotions, logging): neither data nor an empty page, and not «something new
|
||||
// arrived» for SettleAsync, or a page that keeps logging would never look settled.
|
||||
return null;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
var read = new CapturedRead(++_sequence, response, result);
|
||||
@@ -166,7 +200,7 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
void IResponseObserver.OnResponse(ResponseDescriptor response)
|
||||
{
|
||||
if (response.HostKind == HostKind.Site
|
||||
&& response.MimeType.Contains("json", StringComparison.OrdinalIgnoreCase)
|
||||
&& DataResponses.IsData(response.MimeType, response.ResourceType)
|
||||
&& response.Status is >= 200 and < 600 && response.Status != 204)
|
||||
{
|
||||
lock (_gate)
|
||||
@@ -176,6 +210,14 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnBodyDropped(string requestId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_pending.Remove(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnNavigation(NavigationDescriptor navigation)
|
||||
{
|
||||
if (!navigation.SameDocument)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -98,8 +99,12 @@ public sealed partial class RecipeRunner
|
||||
await run.OpenAsync(
|
||||
byPage ? SitePages.FollowingFrom : SitePages.Following,
|
||||
byPage ? Values(("username", mine.Username), ("cursor", stored!)) : Values(("username", mine.Username))).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Profiles.Count > 0, null))
|
||||
|
||||
// Only followed profiles say the list came: the page also receives suggested profiles (not followed) and
|
||||
// Alberto's own profile, which would pass for a list that is not there.
|
||||
bool Listed(ReadResult r) => r.Profiles.Any(p => IsListed(p, mine));
|
||||
var reads = await WaitAndSettleAsync(run, mark, Listed).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, Listed, null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -109,7 +114,9 @@ public sealed partial class RecipeRunner
|
||||
while (true)
|
||||
{
|
||||
read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false);
|
||||
var page = LastPage(reads);
|
||||
|
||||
// The pagination of the list, never that of another answer (the suggestions, a post, the collections).
|
||||
var page = PageOf(reads, r => r.Profiles.Where(p => IsListed(p, mine)).Select(p => p.Id), r => r.Shape == ReadShape.Empty);
|
||||
if (catchingUp && ((page?.Cursor is { } c && string.Equals(c, stored, StringComparison.Ordinal)) || read >= readBefore))
|
||||
{
|
||||
catchingUp = false; // back where the last run stopped
|
||||
@@ -133,7 +140,7 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
var counted = !catchingUp;
|
||||
reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
reads = await ScrollForPageAsync(run, Listed).ConfigureAwait(false);
|
||||
if (counted)
|
||||
{
|
||||
pages++;
|
||||
@@ -175,12 +182,20 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, progress);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A profile of the following list: not Alberto himself, and not one the answer says he does not follow (Instagram
|
||||
/// sends suggested profiles with «friendship_status.following: false», HAR of 21/10/2026). A profile that does not
|
||||
/// say is taken as listed: it came with the list.
|
||||
/// </summary>
|
||||
private static bool IsListed(ProfileInfo profile, Account mine) =>
|
||||
profile.IsFollowed != false && !profile.IsViewer && profile.Id != mine.InstagramId;
|
||||
|
||||
/// <summary>Stores one page of the following list in reading order; renamed followed accounts are recognized.</summary>
|
||||
private async Task<int> SaveFollowingPageAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, Account mine, int offset)
|
||||
{
|
||||
var now = Env.Clock.Now;
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => !p.IsViewer && p.Id != mine.InstagramId && seen.Add(p.Id)).ToList();
|
||||
var profiles = reads.SelectMany(r => r.Result.Profiles).Where(p => IsListed(p, mine) && seen.Add(p.Id)).ToList();
|
||||
var records = new List<FollowingRecord>(profiles.Count);
|
||||
for (var i = 0; i < profiles.Count; i++)
|
||||
{
|
||||
|
||||
@@ -122,6 +122,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>Items already saved by the caller (they are not saved again).</summary>
|
||||
public HashSet<string> Processed { get; init; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// The reads the walk starts from answer a gesture of the walk itself (a resume page, a tab): a bare empty answer
|
||||
/// among them is its empty page. After opening the profile it is not: an empty answer there may be about
|
||||
/// something else (the collections of an account that has none).
|
||||
/// </summary>
|
||||
public bool StartsFromOwnAnswer { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -134,9 +141,9 @@ public sealed partial class RecipeRunner
|
||||
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
var (current, reads) = await OpenProfileAsync(run, account, waitForGrid: true).ConfigureAwait(false);
|
||||
account = current;
|
||||
var profile = FindProfile(reads, account)!;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
|
||||
if (profile.LatestStoryAt is { } latest && latest > (account.LastStoriesCheckAt ?? DateTimeOffset.MinValue)
|
||||
&& account.ContentTypes.HasFlag(ContentTypes.Stories))
|
||||
@@ -174,7 +181,7 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
var page = LastPage(reads);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer: false);
|
||||
if (!sawKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
|
||||
{
|
||||
if (page?.HasMore == true && page.Cursor is { } cursor)
|
||||
@@ -218,7 +225,7 @@ public sealed partial class RecipeRunner
|
||||
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);
|
||||
|
||||
if (LastPage(reads)?.HasMore == false)
|
||||
if (WalkPage(reads, account, walk, ownAnswer: false)?.HasMore == false)
|
||||
{
|
||||
if (stored is not null || before is not null)
|
||||
{
|
||||
@@ -234,6 +241,7 @@ public sealed partial class RecipeRunner
|
||||
IReadOnlyList<CapturedRead> start = reads;
|
||||
ResumePoint? catchUpTo = null;
|
||||
var pages = 0;
|
||||
var ownStart = false;
|
||||
if (!tailIsNew)
|
||||
{
|
||||
if (stored is null)
|
||||
@@ -246,13 +254,14 @@ public sealed partial class RecipeRunner
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
|
||||
start = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(start, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
start = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(start, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
return; // an empty page, counted: the gap stays for the next check
|
||||
}
|
||||
|
||||
pages = 1;
|
||||
ownStart = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -266,6 +275,7 @@ public sealed partial class RecipeRunner
|
||||
{
|
||||
CatchUpTo = catchUpTo,
|
||||
PagesRead = pages,
|
||||
StartsFromOwnAnswer = ownStart,
|
||||
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
|
||||
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
|
||||
CheckDownloads = true,
|
||||
@@ -345,14 +355,15 @@ public sealed partial class RecipeRunner
|
||||
IReadOnlyList<CapturedRead> reads;
|
||||
var pages = 0;
|
||||
ResumePoint? catchUpTo = null;
|
||||
var ownStart = true; // a resume page or a tab; not the profile as opened
|
||||
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
// Resume where the last run stopped: the page of the site that starts after the stored point.
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -361,15 +372,16 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
else
|
||||
{
|
||||
(account, reads) = await OpenProfileAsync(run, account).ConfigureAwait(false);
|
||||
(account, reads) = await OpenProfileAsync(run, account, waitForGrid: walk.IsGrid).ConfigureAwait(false);
|
||||
ownStart = walk.TabTarget is not null;
|
||||
if (walk.TabTarget is { } tab)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.ClickAsync(tab, parameters).ConfigureAwait(false);
|
||||
await Env.Driver.WaitAfterLoadAsync(run.Ct).ConfigureAwait(false);
|
||||
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, null))
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => IsWalkPage(r, account, walk), null))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
@@ -387,6 +399,7 @@ public sealed partial class RecipeRunner
|
||||
{
|
||||
CatchUpTo = catchUpTo,
|
||||
PagesRead = pages,
|
||||
StartsFromOwnAnswer = ownStart,
|
||||
MaxPages = maxPages,
|
||||
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
|
||||
CheckDownloads = !checkOnly,
|
||||
@@ -441,10 +454,12 @@ public sealed partial class RecipeRunner
|
||||
var pending = rules.CatchUpTo;
|
||||
var pages = rules.PagesRead;
|
||||
var catchUp = 0;
|
||||
var ownAnswer = rules.StartsFromOwnAnswer;
|
||||
IReadOnlySet<string>? seen = null; // the first page: only what its own answers bring
|
||||
while (true)
|
||||
{
|
||||
var items = PageItems(reads, account, walk);
|
||||
var page = LastPage(reads);
|
||||
var page = WalkPage(reads, account, walk, ownAnswer, seen);
|
||||
if (pending is not null && pending.IsReachedBy(page, items, i => walk.IsChronological && !IsPinned(i, items, walk)))
|
||||
{
|
||||
pending = null; // this page holds the stored point: from here on the walk goes on as usual
|
||||
@@ -483,7 +498,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
var counted = pending is null;
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
|
||||
|
||||
// Only items of the walk not read yet say the next page came: an answer about something else that arrives
|
||||
// meanwhile (a post of another account, the collections), or one that brings again a post already read
|
||||
// (the page of that post), neither counts as it nor ends the walk with its pagination.
|
||||
reads = await ScrollForPageAsync(run, r => r.Contents.Any(c => IsWalkItem(c, account, walk) && !rules.Processed.Contains(c.Id))).ConfigureAwait(false);
|
||||
ownAnswer = true;
|
||||
seen = rules.Processed;
|
||||
if (counted)
|
||||
{
|
||||
pages++;
|
||||
@@ -561,7 +582,124 @@ public sealed partial class RecipeRunner
|
||||
|
||||
/// <summary>The posts of a walk page: of the account (tagged: of others), never a story or a collection item.</summary>
|
||||
private static IReadOnlyList<ContentItem> PageItems(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk) =>
|
||||
Contents(reads, c => IsPostLike(c) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account)));
|
||||
Contents(reads, c => IsWalkItem(c, account, walk));
|
||||
|
||||
/// <summary>An item of a walk: a post of the account (tagged: of another account), never a story or a collection item.</summary>
|
||||
private static bool IsWalkItem(ContentItem item, Account account, ProfileWalk walk) =>
|
||||
IsPostLike(item) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(item, account) : IsOwnedBy(item, account));
|
||||
|
||||
/// <summary>An answer that brings items of the walk.</summary>
|
||||
private static bool CarriesWalk(ReadResult result, Account account, ProfileWalk walk) =>
|
||||
result.Contents.Any(c => IsWalkItem(c, account, walk));
|
||||
|
||||
/// <summary>
|
||||
/// An answer to a gesture of the walk (a resume page, a tab) that is a page of it on its own: it brings items of the
|
||||
/// walk, or it is an empty page of it (<see cref="IsEmptyWalkPage"/>).
|
||||
/// </summary>
|
||||
private static bool IsWalkPage(ReadResult result, Account account, ProfileWalk walk) =>
|
||||
CarriesWalk(result, account, walk) || IsEmptyWalkPage(result, account, walk, ownAnswer: true);
|
||||
|
||||
/// <summary>
|
||||
/// The end of a tab with nothing in it: a pagination and no item. With the profile of the account (the test site
|
||||
/// sends it with every page of the tab), when nothing else comes with it, or — on the grid — when that profile says
|
||||
/// it has no posts (the test site sends the collections with the first page of the grid). A bare empty answer only
|
||||
/// when it answers a gesture of the walk (<paramref name="ownAnswer"/>): on Instagram the collections of an account
|
||||
/// that has none are an empty connection with «has_next_page: false», as an empty grid would be, and they come
|
||||
/// with the profile too.
|
||||
/// </summary>
|
||||
private static bool IsEmptyWalkPage(ReadResult result, Account account, ProfileWalk walk, bool ownAnswer) =>
|
||||
result.Page is not null && result.Shape switch
|
||||
{
|
||||
ReadShape.Empty => ownAnswer,
|
||||
ReadShape.Recognized => ProfileIn(result, account) is { } profile
|
||||
&& ((result.Contents.Count == 0 && result.Highlights.Count == 0)
|
||||
|| (walk.IsGrid && profile.PostCount == 0 && !result.Contents.Any(IsPostLike))),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of a walk page: from the answer that brought the most items of the walk not read before
|
||||
/// (<paramref name="seen"/>: the pages already read); when none did, from the last empty page of the walk
|
||||
/// (<paramref name="ownAnswer"/>: the reads answer a gesture of the walk, <see cref="IsEmptyWalkPage"/>). Never from
|
||||
/// an answer about something else, nor from one that only brings again a post already read: on Instagram the page
|
||||
/// of a post says «more_available: false» of its single post and the collections say «has_next_page» of
|
||||
/// themselves (HAR of 21/10/2026), and either would end the walk, or mark the history complete, where the grid
|
||||
/// goes on.
|
||||
/// </summary>
|
||||
private static PageInfo? WalkPage(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk, bool ownAnswer, IReadOnlySet<string>? seen = null) =>
|
||||
PageOf(reads, r => r.Contents.Where(c => IsWalkItem(c, account, walk)).Select(c => c.Id), r => IsEmptyWalkPage(r, account, walk, ownAnswer), seen);
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of a page of a list (a profile tab, the feed, the following list): from the answer that brings
|
||||
/// the most items of the list not met before — in <paramref name="seen"/>, or in an earlier answer of the same page
|
||||
/// with a pagination of its own — the last one on a tie; when none brings any, from the last empty page. An answer
|
||||
/// that only brings again items already met, or fewer new ones than another (the page of a single post next to the
|
||||
/// grid), never gives it.
|
||||
/// </summary>
|
||||
private static PageInfo? PageOf(IEnumerable<CapturedRead> reads, Func<ReadResult, IEnumerable<string>> itemIds, Func<ReadResult, bool> isEmptyPage, IReadOnlySet<string>? seen = null)
|
||||
{
|
||||
var met = new HashSet<string>(StringComparer.Ordinal);
|
||||
PageInfo? withItems = null;
|
||||
var most = 0;
|
||||
PageInfo? empty = null;
|
||||
foreach (var result in reads.Select(r => r.Result).Where(r => r.Page is not null))
|
||||
{
|
||||
var carried = 0;
|
||||
var fresh = 0;
|
||||
foreach (var id in itemIds(result))
|
||||
{
|
||||
carried++;
|
||||
if (met.Add(id) && seen?.Contains(id) != true)
|
||||
{
|
||||
fresh++;
|
||||
}
|
||||
}
|
||||
|
||||
if (fresh > 0)
|
||||
{
|
||||
if (fresh >= most)
|
||||
{
|
||||
most = fresh;
|
||||
withItems = result.Page;
|
||||
}
|
||||
}
|
||||
else if (carried == 0 && isEmptyPage(result))
|
||||
{
|
||||
empty = result.Page;
|
||||
}
|
||||
}
|
||||
|
||||
return withItems ?? empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The profile of the account as all the answers of the page describe it: the same profile can come in several
|
||||
/// of them (the profile itself, the author of the posts, the owner of the collections), each with part of its
|
||||
/// facts. The best described one is completed with what the others say; of the pictures, the largest.
|
||||
/// </summary>
|
||||
private static ProfileInfo? AccountProfile(IReadOnlyList<CapturedRead> reads, Account account)
|
||||
{
|
||||
if (FindProfile(reads, account) is not { } best)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var other in reads.SelectMany(r => r.Result.Profiles).Where(p => p.Id == best.Id).ToList())
|
||||
{
|
||||
best = best with
|
||||
{
|
||||
DisplayName = best.DisplayName ?? other.DisplayName,
|
||||
IsPrivate = best.IsPrivate ?? other.IsPrivate,
|
||||
IsFollowed = best.IsFollowed ?? other.IsFollowed,
|
||||
PostCount = best.PostCount ?? other.PostCount,
|
||||
Picture = other.Picture is { } picture && (best.Picture is null || picture.Area > best.Picture.Area) ? picture : best.Picture,
|
||||
LatestStoryAt = best.LatestStoryAt ?? other.LatestStoryAt,
|
||||
IsViewer = best.IsViewer || other.IsViewer,
|
||||
};
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
/// <summary>Pinned on top of the profile: the vocabulary says so, or (newest first) the order of the page does.</summary>
|
||||
private bool IsPinned(ContentItem item, IReadOnlyList<ContentItem> page, ProfileWalk walk) =>
|
||||
@@ -591,28 +729,32 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile, a name now used by another
|
||||
/// account, private profile not followed (rule 6: not touched). Returns the updated account and the reads.
|
||||
/// Opens the profile page (1 counted action) and reads its state: missing profile (when the map has its marker), a
|
||||
/// name now used by another account, private profile not followed (rule 6: not touched). The profile, the posts
|
||||
/// and the collections may come in different answers, and not together: after the profile the page is left to
|
||||
/// settle, and with <paramref name="waitForGrid"/> the first page of posts is waited for too. Returns the updated
|
||||
/// account and everything the page received.
|
||||
/// </summary>
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account)
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account, bool waitForGrid = false)
|
||||
{
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
if ((await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
if (Env.SiteMap.IsTargetConfigured(SiteTargets.ProfileNotFound)
|
||||
&& (await run.FindAsync(SiteTargets.ProfileNotFound, parameters).ConfigureAwait(false)).Found)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.NotFound).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"Il profilo {account.Username} non esiste o non è più disponibile.");
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
var reads = await WaitAndSettleAsync(run, mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => ProfileIn(r, account) is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
var profile = FindProfile(reads, account)!;
|
||||
var profile = AccountProfile(reads, account)!;
|
||||
if (account.InstagramId is { } known && profile.Id != known)
|
||||
{
|
||||
await MarkUnreachableAsync(run, account, UnreachableReason.Renamed).ConfigureAwait(false);
|
||||
@@ -634,9 +776,58 @@ 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for <paramref name="expected"/> after <paramref name="mark"/>, then lets the page settle and returns
|
||||
/// everything that arrived since the mark: what one page shows can come in several answers, the expected one not
|
||||
/// always last, and stopping at the first that matches would lose the others. When the expected data does not
|
||||
/// come, returns what came, to be judged.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> WaitAndSettleAsync(RecipeRun run, long mark, Func<ReadResult, bool> expected)
|
||||
{
|
||||
var reads = await run.WaitForDataAsync(mark, expected).ConfigureAwait(false);
|
||||
if (!reads.Any(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)))
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
return Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first page of the grid, when it did not come with the profile: the page may ask for it only after drawing
|
||||
/// the profile, later than it takes to settle. Waits for posts of the account or an empty grid that is surely its
|
||||
/// own (<see cref="IsEmptyWalkPage"/>: a bare empty answer may be the collections), then lets the page settle again.
|
||||
/// Nothing is judged here (the profile came): a profile without posts that does not say so only costs the wait.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<CapturedRead>> WaitForGridAsync(RecipeRun run, long mark, Account account, IReadOnlyList<CapturedRead> reads)
|
||||
{
|
||||
var walk = ProfileWalk.Posts;
|
||||
bool Arrived(IReadOnlyList<CapturedRead> list) => PageItems(list, account, walk).Count > 0 || WalkPage(list, account, walk, ownAnswer: false) is not null;
|
||||
if (Arrived(reads))
|
||||
{
|
||||
return reads;
|
||||
}
|
||||
|
||||
var arrived = await Env.Capture.WaitAsync(mark, list => run.Signal is not null || Arrived(list), Env.Options.DataTimeout, Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
if (!Arrived(arrived))
|
||||
{
|
||||
return arrived;
|
||||
}
|
||||
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
return Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
|
||||
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Only the expected data ends the bursts: a response the page
|
||||
@@ -674,9 +865,6 @@ public sealed partial class RecipeRunner
|
||||
/// <summary>Outcome message of a page that arrived without data (three in a row raise a throttle signal).</summary>
|
||||
private const string EmptyPageMessage = "La pagina è arrivata vuota: nessun dato da leggere.";
|
||||
|
||||
private static PageInfo? LastPage(IEnumerable<CapturedRead> reads) =>
|
||||
reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault();
|
||||
|
||||
private static DateTimeOffset? ParseTime(string? value) =>
|
||||
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var time) ? time : null;
|
||||
|
||||
|
||||
@@ -17,34 +17,61 @@ public sealed partial class RecipeRunner
|
||||
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Profiles.Count > 0).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
// The feed and the stories bar may come in different answers: after the first, the page is left to settle.
|
||||
var reads = await WaitAndSettleAsync(run, mark, HomeArrived).ConfigureAwait(false);
|
||||
run.Judge(reads, HomeArrived, Env.SiteMap.BuildPath(SitePages.Home));
|
||||
|
||||
var processed = 0;
|
||||
var sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
var hasMore = reads.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? true;
|
||||
var hasMore = FeedPage(reads)?.HasMore ?? true;
|
||||
|
||||
// Everything after the last read taken, so that nothing arriving while the posts are saved is missed.
|
||||
var seen = reads.Count > 0 ? reads[^1].Sequence : mark;
|
||||
for (var burst = 0; burst < Env.Options.SweepMaxBursts && !sawKnown && hasMore; burst++)
|
||||
{
|
||||
var before = Env.Capture.Mark();
|
||||
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
var more = Env.Capture.Since(before);
|
||||
var more = Env.Capture.Since(seen);
|
||||
if (more.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
seen = more[^1].Sequence;
|
||||
var met = Contents(reads, IsPostLike).Select(c => c.Id).ToHashSet(StringComparer.Ordinal);
|
||||
reads = [.. reads, .. more];
|
||||
sawKnown = await ProcessSweepReadsAsync(run, reads, ref processed).ConfigureAwait(false);
|
||||
hasMore = more.Select(r => r.Result.Page).LastOrDefault(p => p is not null)?.HasMore ?? hasMore;
|
||||
hasMore = FeedPage(more, met)?.HasMore ?? hasMore;
|
||||
}
|
||||
|
||||
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The home arrived: posts, an account of the stories bar (it says when its latest story was published) or a page
|
||||
/// of the feed. Profiles alone do not say it: Instagram also sends suggested profiles, not followed (HAR of
|
||||
/// 21/10/2026), and they would pass for a home that is not there.
|
||||
/// </summary>
|
||||
private static bool HomeArrived(ReadResult result) =>
|
||||
result.Contents.Count > 0 || result.Profiles.Any(p => p.LatestStoryAt is not null) || result.Page is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The pagination of the feed: from the answer that brought the most posts not met before (<paramref name="met"/>:
|
||||
/// the earlier answers of the run); when none did, from an answer that brought no contents nor collections (an
|
||||
/// empty feed). Never from an answer that brought only stories or collection items (the collections say
|
||||
/// «has_next_page» of themselves), nor from one that only brings again a post already met (the page of that post
|
||||
/// says «more_available: false» of itself).
|
||||
/// </summary>
|
||||
private static PageInfo? FeedPage(IReadOnlyList<CapturedRead> reads, IReadOnlySet<string>? met = null) =>
|
||||
PageOf(
|
||||
reads,
|
||||
r => r.Contents.Where(IsPostLike).Select(c => c.Id),
|
||||
r => (r.Shape is ReadShape.Empty or ReadShape.Recognized) && r.Contents.Count == 0 && r.Highlights.Count == 0,
|
||||
met);
|
||||
|
||||
/// <summary>Saves the posts not processed yet; returns true once known content has been met.</summary>
|
||||
private Task<bool> ProcessSweepReadsAsync(RecipeRun run, IReadOnlyList<CapturedRead> reads, ref int processed)
|
||||
{
|
||||
@@ -101,11 +128,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen.
|
||||
/// Alberto's own profile («Tu») from the data the page receives (H10), the first time it is seen: an answer that
|
||||
/// presents it with its name, or — Instagram's way, whose «xdt_viewer.user» gives only an identifier (HAR of
|
||||
/// 21/10/2026) — the identifier from one answer of the run and the profile with that identifier, name included,
|
||||
/// from any answer of the run (his own entry in the stories bar, for instance).
|
||||
/// </summary>
|
||||
private async Task EnsureMineAsync(IReadOnlyList<CapturedRead> reads, RecipeRun run)
|
||||
{
|
||||
if (reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null) is not { } viewer)
|
||||
var viewer = reads.Select(r => r.Result.Viewer).FirstOrDefault(v => v is not null);
|
||||
if (viewer is null && (reads.Select(r => r.Result.ViewerId).FirstOrDefault(id => id is not null) ?? Env.Capture.ViewerId) is { } viewerId)
|
||||
{
|
||||
viewer = reads.SelectMany(r => r.Result.Profiles).FirstOrDefault(p => p.Id == viewerId);
|
||||
}
|
||||
|
||||
if (viewer is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
@@ -11,6 +12,17 @@ public sealed partial class RecipeRunner
|
||||
/// <summary>A story stays on offer for a day (spec §4.3: «storie attive nelle 24 ore»).</summary>
|
||||
private static readonly TimeSpan StoryLifetime = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>
|
||||
/// Without the item in the address, how long before a video ends the gesture that leaves it («next», or close) starts
|
||||
/// at the latest: the pointer travel and the pause on the target of §7.7 (up to 1.2 s) with room to spare, multiplied
|
||||
/// by mood and pace like the gesture. The viewer moves on by itself when the video ends, and the address would not
|
||||
/// say so: a «next» pressed after that would skip an item.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan VideoClickLead = TimeSpan.FromSeconds(1.5);
|
||||
|
||||
/// <summary>The placeholder of a viewer address that names the item shown; optional (Instagram's highlight viewer has none).</summary>
|
||||
private const string ItemKey = "id";
|
||||
|
||||
/// <summary>
|
||||
/// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the
|
||||
/// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of
|
||||
@@ -66,7 +78,7 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{ring.Message} Il profilo di {account.Username} dice però che c'è una storia attiva: la mappa dei bersagli va controllata.");
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
await StoriesCheckedAsync(account, run.Ct).ConfigureAwait(false);
|
||||
return RecipeStatus.Completed; // no active stories: nothing to open
|
||||
}
|
||||
}
|
||||
@@ -77,13 +89,14 @@ public sealed partial class RecipeRunner
|
||||
var opened = await OpenViewerAsync(run, target, parameters, SitePages.StoryViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.StoryViewer, "username", account.Username, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
var ct = watched.StoreToken(run);
|
||||
|
||||
var stories = Contents(Env.Capture.Since(viewerMark), c => IsOwnedBy(c, account));
|
||||
foreach (var id in shown)
|
||||
{
|
||||
if (stories.FirstOrDefault(s => s.Id == id) is { } story)
|
||||
{
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
var saved = await Writer.SaveAsync(account, story, EntryKind.Story, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
@@ -91,12 +104,8 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
|
||||
await StoriesCheckedAsync(account, ct).ConfigureAwait(false);
|
||||
watched.ThrowIfStopped();
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
@@ -105,10 +114,15 @@ public sealed partial class RecipeRunner
|
||||
/// StoryView permit per content shown) and closes the viewer after the last one. A content that is a story already
|
||||
/// saved is referenced, not downloaded again (H9).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Collections are compared in the form of their address: Instagram writes «highlight:1790…» in its data and
|
||||
/// «/stories/highlights/1790…/» in the address (HAR of 21/10/2026); the reader keeps the second, and the requested
|
||||
/// identifier is taken in either form.
|
||||
/// </remarks>
|
||||
private async Task<RecipeStatus> HighlightAsync(RecipeRun run)
|
||||
{
|
||||
var account = await LoadAccountAsync(run).ConfigureAwait(false);
|
||||
if (run.Request.HighlightId is not { Length: > 0 } highlightId)
|
||||
if (run.Request.HighlightId is not { Length: > 0 } requested)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "«Raccolta in evidenza» ha bisogno dell'identificativo della raccolta.");
|
||||
}
|
||||
@@ -118,26 +132,38 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, $"«Storie in evidenza» è spento per {account.Username}.");
|
||||
}
|
||||
|
||||
var highlightId = ShapeReader.HighlightId(requested);
|
||||
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Highlights.Count > 0 || ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
if (!run.Judge(reads, r => r.Highlights.Count > 0 || r.Profiles.Count > 0, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
|
||||
// Only this account's profile or collections say the page arrived: profiles suggested beside it do not.
|
||||
var reads = await run.WaitForDataAsync(mark, r => OwnProfileOrCollectionsIn(r, account)).ConfigureAwait(false);
|
||||
if (!reads.Any(r => r.Result.Highlights.Any(h => h.Id == highlightId && IsHighlightOf(h, account))))
|
||||
{
|
||||
// The collections may come in an answer of their own, after the profile: let the page settle first.
|
||||
await run.SettleAsync().ConfigureAwait(false);
|
||||
reads = Env.Capture.Since(mark);
|
||||
}
|
||||
|
||||
if (!run.Judge(reads, r => OwnProfileOrCollectionsIn(r, account), Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
|
||||
}
|
||||
|
||||
if (FindProfile(reads, account) is { } profile)
|
||||
{
|
||||
account = await Writer.ApplyProfileAsync(account, profile, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => h.Owner is null || h.Owner.Id == account.InstagramId).ToList();
|
||||
var listed = reads.SelectMany(r => r.Result.Highlights).Where(h => IsHighlightOf(h, account)).ToList();
|
||||
var collections = await Writer.UpsertHighlightsAsync(account, listed, run.Ct).ConfigureAwait(false);
|
||||
if (!collections.TryGetValue(highlightId, out var highlight))
|
||||
{
|
||||
var known = await Env.Storage.Highlights.FindAsync(account.Id, highlightId, run.Ct).ConfigureAwait(false);
|
||||
var known = 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, known is null
|
||||
? "La raccolta non è nel profilo."
|
||||
: $"La raccolta «{known.Title}» non è più nel profilo: i suoi file restano.");
|
||||
@@ -145,11 +171,13 @@ public sealed partial class RecipeRunner
|
||||
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
var viewerMark = Env.Capture.Mark();
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, Values(("id", highlightId), ("username", account.Username)), SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var target = Values(("id", highlightId), ("username", account.Username), ("title", highlight.Title));
|
||||
var opened = await OpenViewerAsync(run, SiteTargets.ProfileHighlight, target, SitePages.HighlightViewer).ConfigureAwait(false);
|
||||
var watched = await WatchViewerAsync(run, SitePages.HighlightViewer, "highlight", highlightId, account, viewerMark, opened).ConfigureAwait(false);
|
||||
var shown = watched.Shown;
|
||||
var ct = watched.StoreToken(run);
|
||||
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => c.HighlightId == highlightId);
|
||||
var items = Contents(Env.Capture.Since(viewerMark), c => InCollection(c, highlightId));
|
||||
var ordered = new List<long>();
|
||||
foreach (var id in shown)
|
||||
{
|
||||
@@ -158,7 +186,7 @@ public sealed partial class RecipeRunner
|
||||
continue;
|
||||
}
|
||||
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
var (entry, created) = await Writer.LinkHighlightItemAsync(account, highlight, item, run.Session.SessionId, ct).ConfigureAwait(false);
|
||||
if (created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
@@ -172,15 +200,11 @@ public sealed partial class RecipeRunner
|
||||
|
||||
if (items.Count > 0 && items.All(i => shown.Contains(i.Id)) && ordered.Count == items.Count)
|
||||
{
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
if (watched.Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
await Env.Storage.Highlights.SetItemsAsync(highlight.Id, ordered, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Env.Storage.Highlights.UpsertAsync(highlight with { LastCheckedAt = Env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
watched.ThrowIfStopped();
|
||||
return RecipeStatus.Completed;
|
||||
}
|
||||
|
||||
@@ -196,15 +220,29 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed.</summary>
|
||||
private async Task<IReadOnlyDictionary<string, string>> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
/// <summary>
|
||||
/// Clicks what opens a viewer and waits for it; one more click if the first one went unnoticed. Returns the address
|
||||
/// shown and when the first click started (the first item cannot have come on screen before). When the click takes
|
||||
/// the page to an address the map does not take for the viewer (its shape in the map may be wrong), what opened is
|
||||
/// closed like a viewer before the recipe stops: left open, it would move on by itself to other accounts.
|
||||
/// </summary>
|
||||
private async Task<ViewerOpening> OpenViewerAsync(RecipeRun run, string target, IReadOnlyDictionary<string, string> parameters, string viewerPage)
|
||||
{
|
||||
var before = await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false);
|
||||
var clickedAt = Env.Clock.Now;
|
||||
for (var attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
await run.ClickAsync(target, parameters).ConfigureAwait(false);
|
||||
if (await WaitForViewerAsync(run, viewerPage, previous: null).ConfigureAwait(false) is { } opened)
|
||||
{
|
||||
return opened;
|
||||
return new ViewerOpening(opened, clickedAt);
|
||||
}
|
||||
|
||||
if (!string.Equals(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false), before, StringComparison.Ordinal))
|
||||
{
|
||||
// The click was noticed, but what opened has not the shape of the viewer: no second click on it.
|
||||
await CloseAsync(run, path => !string.Equals(path, before, StringComparison.Ordinal)).ConfigureAwait(false);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"Dopo il clic l'indirizzo non ha la forma «{viewerPage}» della mappa {Env.SiteMap.Source ?? Env.SiteMap.Site}: ciò che si è aperto è stato chiuso. La forma va controllata.");
|
||||
}
|
||||
|
||||
if (!(await run.FindAsync(target, parameters).ConfigureAwait(false)).Found)
|
||||
@@ -217,141 +255,383 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: reads the item shown from the address of the page, waits
|
||||
/// the time of §7.7, asks a StoryView permit before each «next» (and after the fact when the viewer moved on by
|
||||
/// itself) and closes the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something
|
||||
/// else. On any stop other than a signal the viewer is closed first. Returns the identifiers shown, in order.
|
||||
/// Watches a viewer that shows <paramref name="opened"/>: on each item it first asks the StoryView permit for the
|
||||
/// item after it (before it can come on screen, by a click or by itself), then waits the time of §7.7, and closes
|
||||
/// the viewer after the last item of <paramref name="owner"/>, or as soon as it shows something else. The item
|
||||
/// shown is read from the address when the address carries it (<see cref="FollowAddressAsync"/>), otherwise counted
|
||||
/// (<see cref="FollowCountAsync"/>). On any stop other than a signal, an unexpected error included, the viewer is
|
||||
/// closed first; a viewer that stays open stops the run as a target not found. A cancellation leaves the page as it
|
||||
/// is. Returns the identifiers shown, in order, each under its permit.
|
||||
/// </summary>
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, IReadOnlyDictionary<string, string> opened)
|
||||
private async Task<ViewerResult> WatchViewerAsync(RecipeRun run, string viewerPage, string ownerKey, string owner, Account account, long mark, ViewerOpening opened)
|
||||
{
|
||||
var shown = new List<string>();
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var pendingPermit = true; // asked before the click that opened the viewer
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
var viewer = new ViewerWatch(viewerPage, ownerKey, owner, account, mark);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!string.Equals(position[ownerKey], owner, StringComparison.OrdinalIgnoreCase))
|
||||
if (!opened.Position.ContainsKey(ownerKey))
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewerPage == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, $"La forma dell'indirizzo «{viewerPage}» nella mappa {Env.SiteMap.Source ?? Env.SiteMap.Site} non dice di chi è il visualizzatore: manca «{{{ownerKey}}}».");
|
||||
}
|
||||
|
||||
var id = position["id"];
|
||||
if (counted.Add(id))
|
||||
if (opened.Position.ContainsKey(ItemKey))
|
||||
{
|
||||
if (!pendingPermit)
|
||||
{
|
||||
// The viewer moved on by itself: this item was shown without asking first; ask now.
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
pendingPermit = false;
|
||||
shown.Add(id);
|
||||
await FollowAddressAsync(run, viewer, opened.Position, shown).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await FollowCountAsync(run, viewer, opened, shown).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, mark, viewerPage, owner, account).ConfigureAwait(false);
|
||||
var item = list.FirstOrDefault(i => i.Id == id);
|
||||
var video = item?.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
await Env.Driver.WaitAsync(StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier), run.Ct).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
if (list.Count > 0 && index == list.Count - 1)
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
|
||||
if (!pendingPermit)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, account.Id).ConfigureAwait(false);
|
||||
pendingPermit = true;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewerPage, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return new ViewerResult(shown, null); // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
return new ViewerResult(shown, null);
|
||||
}
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
if (stop.Status != RecipeStatus.StoppedBySignal)
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// Leave no viewer open: it would move on by itself to other accounts. After a signal the page stays as it is.
|
||||
try
|
||||
{
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
}
|
||||
catch (RecipeStopException)
|
||||
{
|
||||
}
|
||||
var stillOpen = stop.Status == RecipeStatus.StoppedBySignal ? null : await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, Worse(stop, stillOpen));
|
||||
}
|
||||
|
||||
return new ViewerResult(shown, stop);
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Not even an unexpected error leaves the viewer open; what was shown until then is saved all the same.
|
||||
var stillOpen = await TryCloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return new ViewerResult(shown, Worse(RecipeRun.Stop(RecipeStatus.Failed, $"Errore imprevisto in «{Name(run.Request.Kind)}» ({ex.GetType().Name}): {ex.Message}"), stillOpen));
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException cancelled)
|
||||
{
|
||||
// A pause, the session closed by a signal, Alberto taking the browser: the page is left as it is, what was
|
||||
// shown under its permit is saved all the same, then the cancellation goes on.
|
||||
return new ViewerResult(shown, null, ExceptionDispatchInfo.Capture(cancelled));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a viewer showed, and why it stopped early (the caller saves what was shown, then stops).</summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop);
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address carries the item shown (the test site: «/storie/{username}/{id}/»): every
|
||||
/// position is read from the address, so an item the viewer skipped or showed by itself is known for what it is.
|
||||
/// The permit asked on an item covers the next one, also when it comes by itself; an item that comes by itself
|
||||
/// after what the list gave as the last one had no permit: the viewer is closed and it is not saved.
|
||||
/// </summary>
|
||||
private async Task FollowAddressAsync(RecipeRun run, ViewerWatch viewer, IReadOnlyDictionary<string, string> opened, List<string> shown)
|
||||
{
|
||||
var counted = new HashSet<string>(StringComparer.Ordinal);
|
||||
var permitted = true; // asked before the click that opened the viewer: for the first item on screen
|
||||
var position = opened;
|
||||
var stuck = 0;
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var id = position[ItemKey];
|
||||
if (counted.Add(id))
|
||||
{
|
||||
if (!permitted)
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Il visualizzatore è andato avanti da solo dopo quella che per la pagina era l'ultima storia di {viewer.Account.Username}: chiuso, la storia in più non si salva."
|
||||
: $"Il visualizzatore è andato avanti da solo dopo quello che per la pagina era l'ultimo contenuto della raccolta di {viewer.Account.Username}: chiuso, il contenuto in più non si salva.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
permitted = false;
|
||||
shown.Add(id);
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
|
||||
// The list of the account arrives with the viewer (H4): it tells which item is the last one.
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
var index = list.FindIndex(i => i.Id == id);
|
||||
var last = list.Count > 0 && index == list.Count - 1;
|
||||
if (!last && !permitted)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen.
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
permitted = true;
|
||||
}
|
||||
|
||||
await WatchAsync(run, index < 0 ? null : VideoDuration(list[index]), since, latest: null).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!SamePosition(current, position))
|
||||
{
|
||||
position = current; // it moved on by itself while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
var next = await WaitForViewerAsync(run, viewer.Page, previous: current).ConfigureAwait(false);
|
||||
if (next is null)
|
||||
{
|
||||
return; // closed after the last item
|
||||
}
|
||||
|
||||
if (SamePosition(next, current))
|
||||
{
|
||||
if (++stuck >= 2)
|
||||
{
|
||||
throw RecipeRun.Stop(RecipeStatus.Failed, "Il visualizzatore non va avanti.");
|
||||
}
|
||||
|
||||
continue; // the click went unnoticed: watch a little more and try again
|
||||
}
|
||||
|
||||
stuck = 0;
|
||||
position = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows a viewer whose address does not say which item is shown: Instagram's highlight viewer stays on
|
||||
/// «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026). The items are counted against the
|
||||
/// list the page received for the owner: the first one shown is the first of the list, and each click on «next»
|
||||
/// moves one on. A move the viewer makes by itself cannot be seen, so it is never counted: a video, which moves the
|
||||
/// viewer on when it ends, is left before then (<see cref="VideoClickLead"/>), and when that is no longer possible
|
||||
/// (the Governor's wait for the permit took its time) the viewer is closed without clicking «next», the items after
|
||||
/// it not saved. A photo is never taken as over, because how long the site keeps it is not in the data: should the
|
||||
/// viewer leave one by itself, the count falls behind and its last «next» takes the viewer to another collection,
|
||||
/// where it is closed. A click the page ignores would put the count ahead: nothing in the address or in the data
|
||||
/// tells it yet (to be measured live).
|
||||
/// </summary>
|
||||
private async Task FollowCountAsync(RecipeRun run, ViewerWatch viewer, ViewerOpening opened, List<string> shown)
|
||||
{
|
||||
var position = opened.Position;
|
||||
var index = 0;
|
||||
var appearedAfter = opened.ClickedAt; // the item at «index» did not come on screen before this
|
||||
while (true)
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
if (!viewer.ShowsOwner(position))
|
||||
{
|
||||
await LeaveOtherOwnerAsync(run, viewer).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var since = Env.Clock.Now;
|
||||
var list = await ViewerListAsync(run, viewer).ConfigureAwait(false);
|
||||
if (index >= list.Count)
|
||||
{
|
||||
// The page described nothing (more) for this owner: which item is on screen cannot be told.
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// On screen under the permit asked before it could come: before opening, or on the item before it.
|
||||
var item = list[index];
|
||||
if (!shown.Contains(item.Id, StringComparer.Ordinal))
|
||||
{
|
||||
shown.Add(item.Id);
|
||||
}
|
||||
|
||||
var last = index == list.Count - 1;
|
||||
var video = VideoDuration(item);
|
||||
DateTimeOffset? leaveBy = video is { } duration && duration > TimeSpan.Zero
|
||||
? appearedAfter + duration - TimeSpan.FromTicks((long)(VideoClickLead.Ticks * Env.Driver.WaitMultiplier))
|
||||
: null;
|
||||
if (!last)
|
||||
{
|
||||
// The permit for the item after this one, before it can come on screen; asked only while the viewer
|
||||
// surely has not moved on by itself, and the item still has to be left in time once it is granted.
|
||||
if (!Passed(leaveBy))
|
||||
{
|
||||
await run.PermitAsync(ActionKind.StoryView, viewer.Account.Id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Passed(leaveBy))
|
||||
{
|
||||
await CloseEarlyAsync(run, viewer, viewer.Page == SitePages.StoryViewer
|
||||
? $"Una storia video di {viewer.Account.Username} poteva essere già finita, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», le storie successive non si salvano questa volta."
|
||||
: $"Un video della raccolta di {viewer.Account.Username} poteva essere già finito, con il visualizzatore andato avanti da solo: chiuso senza cliccare «avanti», i contenuti successivi non si salvano questa volta.").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
await WatchAsync(run, video, since, leaveBy).ConfigureAwait(false);
|
||||
run.ThrowIfSignal();
|
||||
|
||||
var current = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (current is null)
|
||||
{
|
||||
return; // the viewer closed by itself
|
||||
}
|
||||
|
||||
if (!viewer.ShowsOwner(current))
|
||||
{
|
||||
position = current; // it moved on by itself to another owner while we watched
|
||||
continue;
|
||||
}
|
||||
|
||||
if (last)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var pressedAfter = Env.Clock.Now;
|
||||
await run.ClickAsync(SiteTargets.ViewerNext).ConfigureAwait(false);
|
||||
index++;
|
||||
appearedAfter = pressedAfter;
|
||||
position = Env.SiteMap.Match(viewer.Page, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false));
|
||||
if (position is null)
|
||||
{
|
||||
return; // the viewer closed: the item after was not shown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True once <paramref name="moment"/> has come (never for none).</summary>
|
||||
private bool Passed(DateTimeOffset? moment) => moment is { } end && Env.Clock.Now >= end;
|
||||
|
||||
/// <summary>
|
||||
/// Waits the time of §7.7 on an item on screen since <paramref name="since"/>: what the recipe waited meanwhile (the
|
||||
/// Governor's spacing before the permit for the next item) is part of it. Never past <paramref name="latest"/>.
|
||||
/// </summary>
|
||||
private async Task WatchAsync(RecipeRun run, TimeSpan? video, DateTimeOffset since, DateTimeOffset? latest)
|
||||
{
|
||||
var until = since + StoryTimings.Watch(Env.Random, video, Env.Driver.WaitMultiplier);
|
||||
if (latest is { } end && end < until)
|
||||
{
|
||||
until = end;
|
||||
}
|
||||
|
||||
var wait = until - Env.Clock.Now;
|
||||
if (wait > TimeSpan.Zero)
|
||||
{
|
||||
await Env.Driver.WaitAsync(wait, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private static TimeSpan? VideoDuration(ContentItem item) => item.Files.FirstOrDefault(f => f.Kind == MediaKind.Video)?.Duration;
|
||||
|
||||
/// <summary>The viewer went on to another account or collection: closed, and the event recorded.</summary>
|
||||
private async Task LeaveOtherOwnerAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync(
|
||||
"visualizzatore-altro-account",
|
||||
viewer.Page == SitePages.StoryViewer
|
||||
? $"Dopo le storie di {viewer.Account.Username} il visualizzatore è passato a un altro account: chiuso, quelle storie non si salvano."
|
||||
: $"Il visualizzatore è passato a un'altra raccolta di {viewer.Account.Username}: chiuso senza salvarla.",
|
||||
EventSeverity.Warning,
|
||||
viewer.Account.Id,
|
||||
run.Session.SessionId,
|
||||
run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The viewer may be on an item not shown under a permit, or not known: closed before the end, without clicking
|
||||
/// «next», and the event recorded. What it may show now is not saved.
|
||||
/// </summary>
|
||||
private async Task CloseEarlyAsync(RecipeRun run, ViewerWatch viewer, string why)
|
||||
{
|
||||
await CloseViewerAsync(run, viewer.Page).ConfigureAwait(false);
|
||||
await Writer.EventAsync("visualizzatore-chiuso-prima", why, EventSeverity.Info, viewer.Account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the viewer on the way out of a stop, unless a signal says to leave the page as it is; never throws, but
|
||||
/// for a cancellation. Returns why the viewer may still be open (it did not close with its command), otherwise null.
|
||||
/// </summary>
|
||||
private async Task<RecipeStopException?> TryCloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
{
|
||||
try
|
||||
{
|
||||
run.ThrowIfSignal();
|
||||
await CloseViewerAsync(run, viewerPage).ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
catch (RecipeStopException stop)
|
||||
{
|
||||
// After a signal the page stays as it is; otherwise the command was not found or the viewer did not close.
|
||||
return stop.Status == RecipeStatus.TargetNotFound ? stop : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
// Whether it closed is not known (the browser may be gone): the stop being reported is the first one.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stop to report: a viewer left open outranks a milder first stop, as a target not found, which makes the
|
||||
/// session stop and put the page at rest.
|
||||
/// </summary>
|
||||
private static RecipeStopException Worse(RecipeStopException first, RecipeStopException? stillOpen) =>
|
||||
stillOpen is null || first.Status == RecipeStatus.TargetNotFound
|
||||
? first
|
||||
: RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{first.Message} {stillOpen.Message}");
|
||||
|
||||
/// <summary>The address a viewer opened on, and when the click that opened it started.</summary>
|
||||
private sealed record ViewerOpening(IReadOnlyDictionary<string, string> Position, DateTimeOffset ClickedAt);
|
||||
|
||||
/// <summary>
|
||||
/// What a viewer showed, and why it stopped early: a stop, or a cancellation. The caller saves what was shown, then
|
||||
/// goes on with the stop (<see cref="ThrowIfStopped"/>).
|
||||
/// </summary>
|
||||
private sealed record ViewerResult(List<string> Shown, RecipeStopException? Stop, ExceptionDispatchInfo? Cancelled = null)
|
||||
{
|
||||
/// <summary>The token to store what was shown with: stopped early, the run's own may be cancelled already, or a moment later (storage only).</summary>
|
||||
public CancellationToken StoreToken(RecipeRun run) => Stop is null && Cancelled is null ? run.Ct : CancellationToken.None;
|
||||
|
||||
/// <summary>Goes on with the cancellation or the stop, once what was shown is stored.</summary>
|
||||
public void ThrowIfStopped()
|
||||
{
|
||||
Cancelled?.Throw();
|
||||
if (Stop is { } stop)
|
||||
{
|
||||
throw stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A viewer being watched: its page, the placeholder of its owner in the address, the owner, the account, the mark of its data.</summary>
|
||||
private sealed record ViewerWatch(string Page, string OwnerKey, string Owner, Account Account, long Mark)
|
||||
{
|
||||
/// <summary>True when the address still shows the owner watched (an account, or a collection).</summary>
|
||||
public bool ShowsOwner(IReadOnlyDictionary<string, string> position) =>
|
||||
position.TryGetValue(OwnerKey, out var shown) && string.Equals(shown, Owner, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static bool SamePosition(IReadOnlyDictionary<string, string> a, IReadOnlyDictionary<string, string> b) =>
|
||||
a.Count == b.Count && a.All(p => b.TryGetValue(p.Key, out var v) && string.Equals(v, p.Value, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The items of the viewer for the owner, as received (waits for them the first time).</summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, long mark, string viewerPage, string owner, Account account)
|
||||
/// <summary>
|
||||
/// The items of the viewer for the owner, as received (waits for them the first time). The stories of an account are
|
||||
/// only what looks like a story (it expires and is in no collection): a post of the account arriving meanwhile (the
|
||||
/// grid comes in an answer of its own, also after the viewer opened) would hide which story is the last one, or,
|
||||
/// counted by position, move every position after it.
|
||||
/// </summary>
|
||||
private async Task<List<ContentItem>> ViewerListAsync(RecipeRun run, ViewerWatch viewer)
|
||||
{
|
||||
Func<ContentItem, bool> belongs = viewerPage == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, account)
|
||||
: c => c.HighlightId == owner;
|
||||
var present = Contents(Env.Capture.Since(mark), belongs);
|
||||
Func<ContentItem, bool> belongs = viewer.Page == SitePages.StoryViewer
|
||||
? c => IsOwnedBy(c, viewer.Account) && c.ExpiresAt is not null && c.HighlightId is null
|
||||
: c => InCollection(c, viewer.Owner);
|
||||
var present = Contents(Env.Capture.Since(viewer.Mark), belongs);
|
||||
if (present.Count > 0)
|
||||
{
|
||||
return present;
|
||||
}
|
||||
|
||||
var reads = await run.WaitForDataAsync(mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(viewer.Mark, r => r.Contents.Any(belongs)).ConfigureAwait(false);
|
||||
run.Judge(reads, r => r.Contents.Any(belongs), null);
|
||||
return Contents(reads, belongs);
|
||||
}
|
||||
@@ -383,10 +663,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone.</summary>
|
||||
private async Task CloseViewerAsync(RecipeRun run, string viewerPage)
|
||||
/// <summary>Closes the viewer with its command and waits until it is gone; stops the run when it stays open.</summary>
|
||||
private Task CloseViewerAsync(RecipeRun run, string viewerPage) =>
|
||||
CloseAsync(run, path => Env.SiteMap.Match(viewerPage, path) is not null);
|
||||
|
||||
/// <summary>
|
||||
/// Clicks «viewer-close» while the address says something is open (<paramref name="isOpen"/>) and waits until it is
|
||||
/// gone. Never after a signal (the page stays as it is). A command that is not found, or a viewer still open after
|
||||
/// <see cref="RecipeOptions.ViewerTimeout"/>, stops the run as a target not found: the session then stops and the
|
||||
/// page is put at rest.
|
||||
/// </summary>
|
||||
private async Task CloseAsync(RecipeRun run, Func<string, bool> isOpen)
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
run.ThrowIfSignal();
|
||||
if (!isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -399,19 +689,20 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var deadline = Env.Clock.Now + Env.Options.ViewerTimeout;
|
||||
while (Env.Clock.Now < deadline)
|
||||
while (isOpen(await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)))
|
||||
{
|
||||
if (Env.SiteMap.Match(viewerPage, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is null)
|
||||
if (Env.Clock.Now >= deadline)
|
||||
{
|
||||
return;
|
||||
run.ThrowIfSignal();
|
||||
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"Il visualizzatore non si è chiuso con «{SiteTargets.ViewerClose}»: il bersaglio della mappa va controllato.");
|
||||
}
|
||||
|
||||
await Env.Clock.Delay(Env.Options.Poll, run.Ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StoriesCheckedAsync(Account account, RecipeRun run) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, run.Ct).ConfigureAwait(false);
|
||||
private async Task StoriesCheckedAsync(Account account, CancellationToken ct) =>
|
||||
await Env.Storage.Accounts.UpdateChecksAsync(account.Id, new AccountCheckTimes { LastStoriesCheckAt = Env.Clock.Now }, ct).ConfigureAwait(false);
|
||||
|
||||
private async Task MarkUnreachableAsync(RecipeRun run, Account account, UnreachableReason reason)
|
||||
{
|
||||
@@ -433,4 +724,18 @@ public sealed partial class RecipeRunner
|
||||
|
||||
private static ProfileInfo? ProfileIn(ReadResult result, Account account) =>
|
||||
result.Profiles.FirstOrDefault(p => (account.InstagramId is { } id && p.Id == id) || string.Equals(p.Username, account.Username, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>The profile of the account, or one of its collections: what says that its profile page arrived.</summary>
|
||||
private static bool OwnProfileOrCollectionsIn(ReadResult result, Account account) =>
|
||||
ProfileIn(result, account) is not null || result.Highlights.Any(h => IsHighlightOf(h, account));
|
||||
|
||||
/// <summary>A collection of the account: its owner is the account, or the answer does not say whose it is.</summary>
|
||||
private static bool IsHighlightOf(HighlightInfo highlight, Account account) =>
|
||||
highlight.Owner is not { } owner
|
||||
|| (account.InstagramId is { } id && owner.Id == id)
|
||||
|| string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>An item received inside collection <paramref name="highlightId"/> (both in the form of the address).</summary>
|
||||
private static bool InCollection(ContentItem item, string highlightId) =>
|
||||
item.HighlightId is { } id && string.Equals(ShapeReader.HighlightId(id), highlightId, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -50,11 +50,13 @@ public sealed record RecipeEnvironment
|
||||
/// Common rules: the Governor is asked before every counted action and a refusal stops the recipe in order; a stop
|
||||
/// signal stops it where it is and leaves the page as it is; a missing target stops it with a report, never with
|
||||
/// coordinates; an unknown response shape stops it with <see cref="RecipeStatus.UnrecognizedFormat"/> and an event
|
||||
/// that carries only the key structure. Recipes refuse to run on a site whose map or reader vocabulary is still a
|
||||
/// skeleton (the first Instagram files, to be filled after M0).
|
||||
/// that carries only the key structure. A recipe refuses to run, as <see cref="RecipeStatus.NotConfigured"/>, while the
|
||||
/// site's map lacks a page or target it needs or the reader vocabulary is not usable (Instagram's targets, H11).
|
||||
/// </remarks>
|
||||
public sealed partial class RecipeRunner : IRecipeRunner
|
||||
{
|
||||
private readonly Lock _refusalsGate = new();
|
||||
private readonly HashSet<RecipeKind> _refusalsReported = [];
|
||||
private long? _sessionId;
|
||||
private RecipeKind? _lastKind;
|
||||
|
||||
@@ -83,15 +85,19 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Pages and targets a recipe cannot work without.</summary>
|
||||
/// <summary>
|
||||
/// Pages and targets a recipe cannot work without. «profile-not-found» is not among them: it is looked up only when
|
||||
/// the map sets it, and without it a profile that does not exist gives no data, judged like any page that arrives
|
||||
/// empty.
|
||||
/// </summary>
|
||||
public static (IReadOnlyList<string> Pages, IReadOnlyList<string> Targets) Requirements(RecipeKind kind) => kind switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => ([SitePages.Home], []),
|
||||
RecipeKind.AccountStories => ([SitePages.Profile, SitePages.StoryViewer], [SiteTargets.ProfileStoryRing, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], [SiteTargets.ProfileNotFound]),
|
||||
RecipeKind.ProfileCheck or RecipeKind.Backfill => ([SitePages.Profile], []),
|
||||
RecipeKind.Highlight => ([SitePages.Profile, SitePages.HighlightViewer], [SiteTargets.ProfileHighlight, SiteTargets.ViewerNext, SiteTargets.ViewerClose]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileNotFound, SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.Tagged => ([SitePages.Profile], [SiteTargets.ProfileTabTagged]),
|
||||
RecipeKind.Reels => ([SitePages.Profile], [SiteTargets.ProfileTabReels]),
|
||||
RecipeKind.SinglePost => ([SitePages.Post], []),
|
||||
RecipeKind.FollowingList => ([SitePages.Following], []),
|
||||
_ => ([], []),
|
||||
@@ -112,20 +118,23 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
ArgumentNullException.ThrowIfNull(session);
|
||||
var name = Name(request.Kind);
|
||||
|
||||
var (pages, targets) = Requirements(request.Kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
// 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)
|
||||
{
|
||||
var message = $"«{name}» non può girare su {Env.SiteMap.Site}: la mappa dei bersagli non è ancora compilata (mancano {string.Join(", ", missing)}). Va completata con i campioni della sonda di M0 (ipotesi H11).";
|
||||
await Writer.EventAsync("mappa-incompleta", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.TargetNotFound, 0, 0, message);
|
||||
}
|
||||
bool first;
|
||||
lock (_refusalsGate)
|
||||
{
|
||||
first = _refusalsReported.Add(request.Kind);
|
||||
}
|
||||
|
||||
if (Env.Capture.Reader.Vocabulary.UnusableReason is { } unusable)
|
||||
{
|
||||
var message = $"«{name}» non può girare: {unusable}";
|
||||
await Writer.EventAsync("lettori-incompleti", message, EventSeverity.Error, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
return new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 0, 0, message);
|
||||
if (first)
|
||||
{
|
||||
await Writer.EventAsync(refusal.Code, refusal.Message + SessionComposer.NotConfiguredTail, EventSeverity.Warning, null, session.SessionId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, refusal.Message);
|
||||
}
|
||||
|
||||
if (Env.Breaker is { } breaker && !breaker.State.AllowsSiteActions)
|
||||
@@ -206,6 +215,28 @@ public sealed partial class RecipeRunner : IRecipeRunner
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string? NotConfiguredReason(RecipeKind kind) => Refusal(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.
|
||||
/// </summary>
|
||||
private (string Code, string Message)? Refusal(RecipeKind kind)
|
||||
{
|
||||
var name = Name(kind);
|
||||
var (pages, targets) = Requirements(kind);
|
||||
var missing = Env.SiteMap.Missing(pages, targets);
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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.
|
||||
|
||||
@@ -31,10 +31,13 @@ public static class SitePages
|
||||
/// <summary>The same list resuming after {cursor} (optional).</summary>
|
||||
public const string FollowingFrom = "followingFrom";
|
||||
|
||||
/// <summary>Shape of the address of the story viewer: {username} and {id} of the story shown.</summary>
|
||||
/// <summary>Shape of the address of the story viewer: {username}, and {id} of the story shown when the address carries it.</summary>
|
||||
public const string StoryViewer = "storyViewer";
|
||||
|
||||
/// <summary>Shape of the address of the highlight viewer: {highlight} and {id} of the item shown.</summary>
|
||||
/// <summary>
|
||||
/// Shape of the address of the highlight viewer: {highlight}, and {id} of the item shown when the address carries it
|
||||
/// (Instagram's does not: «/stories/highlights/{highlight}/» stays the same from item to item).
|
||||
/// </summary>
|
||||
public const string HighlightViewer = "highlightViewer";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
@@ -178,7 +181,7 @@ public sealed partial class SiteMap
|
||||
/// <summary>The target map of the local test site (embedded <c>bersagli.prova.json</c>).</summary>
|
||||
public static SiteMap LoadTestSite() => LoadEmbedded("bersagli.prova.json");
|
||||
|
||||
/// <summary>The Instagram skeleton (embedded <c>bersagli.instagram.json</c>): every entry is still unset (H11).</summary>
|
||||
/// <summary>The Instagram map (embedded <c>bersagli.instagram.json</c>): the pages seen in real traffic, targets still unset (H11).</summary>
|
||||
public static SiteMap LoadInstagram() => LoadEmbedded("bersagli.instagram.json");
|
||||
|
||||
public static SiteMap LoadOrEmbedded(string? path, string embeddedName) =>
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"note": "SCHELETRO della prima versione (specifica §6.3, ipotesi H11). Elenca solo le pagine e i bersagli di cui le ricette hanno bisogno, tutti VUOTI: si compilano con i campioni della sonda di M0 (docs/prove-dal-vivo.md, docs/sonda/esito.md). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"note": "Mappa di Instagram, aggiornata il 25 ottobre 2026 (specifica §6.3). PAGINE: compilate solo quelle che hanno una prova reale nel file HAR del browser di Alberto del 21 ottobre 2026, cioè i modelli di indirizzo che Instagram stesso manda al browser (/ajax/bulk-route-definitions/) e i percorsi del Referer delle richieste fatte dalla pagina: home, profile, post, storyViewer, highlightViewer. Restano vuote, senza prove: following e followingFrom (quindi «Elenco dei seguiti» non gira), profileFrom, reelsFrom e taggedFrom (facoltative). Le parti facoltative dei modelli di Instagram ({?tab}, {?initial_media_id}) non si scrivono: qui ogni segnaposto vale esattamente un segmento. BERSAGLI: tutti ancora VUOTI (ipotesi H11). Il HAR aveva solo risposte Fetch/XHR: nessun documento e nessun attributo degli elementi (ruoli, nomi accessibili, collegamenti). Si compilano con docs/prove-dal-vivo.md, parte A bis (tools/bersagli/raccogli-bersagli.js). Finché una voce necessaria è vuota, la ricetta che la usa si rifiuta di girare su Instagram e lo dice. Mai coordinate, mai nomi di classi generate: solo ruolo, nome accessibile e forma del collegamento.",
|
||||
"pages": {
|
||||
"home": { "path": "", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti." },
|
||||
"profile": { "path": "", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Se resta vuota lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati." },
|
||||
"post": { "path": "", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code}." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa." },
|
||||
"storyViewer": { "path": "", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata." },
|
||||
"highlightViewer": { "path": "", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} e {id}." }
|
||||
"home": { "path": "/", "hypothesis": "H1", "note": "Pagina iniziale con barra delle storie e post recenti dei seguiti. Prova: modello «/» (PolarisFeedRoute) nelle definizioni delle pagine. Che cosa arrivi caricandola (H1) non è nel HAR e resta da provare." },
|
||||
"profile": { "path": "/{username}/", "hypothesis": "H3", "note": "Pagina di un profilo; segnaposto {username}. Prova: modello /{username}/{?tab}/{?view_type}/{?igshid}/ (PolarisProfilePostsTabRoute), senza le parti facoltative. I valori di {?tab} non si vedono nel campione." },
|
||||
"profileFrom": { "path": "", "hypothesis": "H3", "note": "Facoltativa: profilo che riparte da un punto di ripresa ({cursor}). Nessuna prova di un indirizzo del genere: resta vuota e lo storico riprende scorrendo." },
|
||||
"reelsFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Reel. Nessuna prova: la scheda non è nel campione." },
|
||||
"taggedFrom": { "path": "", "hypothesis": "H6", "note": "Facoltativa, come profileFrom per la scheda Taggati. Nessuna prova: la scheda non è nel campione." },
|
||||
"post": { "path": "/p/{code}/", "hypothesis": "H3", "note": "Pagina di un post; segnaposto {code} (11 caratteri). Prova: il percorso /p/{code}/ nel Referer delle richieste della pagina di un post. Instagram usa anche /{username}/reel/{code}/ (modello /{username}/{permalink_key}/{shortcode}/): Febe apre la forma /p/." },
|
||||
"following": { "path": "", "hypothesis": "H11", "note": "Elenco dei profili seguiti da Alberto; segnaposto {username}. Nessuna prova nel campione: resta vuota e «Elenco dei seguiti» non gira finché non arriva (parte A bis)." },
|
||||
"followingFrom": { "path": "", "hypothesis": "H11", "note": "Facoltativa: elenco dei seguiti da un punto di ripresa. Nessuna prova." },
|
||||
"storyViewer": { "path": "/stories/{username}/{id}/", "hypothesis": "H4", "note": "Forma dell'indirizzo del visualizzatore: {username} e {id} della storia mostrata. Prova: modello /stories/{username}/{?initial_media_id}/ (PolarisStoriesV3Route). DA CONFERMARE che l'indirizzo segua ogni storia (l'{id} cambia a ogni avanzamento) e che porti l'{id} fin dall'apertura: senza {id} questa forma non corrisponde e la ricetta si ferma dicendo che il visualizzatore non si è aperto. Anche /stories/highlights/<cifre>/ ha questa forma, con username «highlights»: per le Storie di un account è «un altro account» e il visualizzatore si chiude; la ricetta delle raccolte legge solo highlightViewer." },
|
||||
"highlightViewer": { "path": "/stories/highlights/{highlight}/", "hypothesis": "H9", "note": "Forma dell'indirizzo del visualizzatore delle raccolte: {highlight} sono le 17 cifre dell'identificativo (nei dati «highlight:<cifre>», ridotto alle cifre dal lettore). Prova: il Referer delle richieste fatte guardando una raccolta e il modello /stories/highlights/{highlight_reel_id}/ (PolarisStoriesV3HighlightsRoute). Non c'è l'{id} del contenuto mostrato: l'indirizzo resta lo stesso mentre si guarda, quindi la posizione nella raccolta non si legge dall'indirizzo." }
|
||||
},
|
||||
"targets": {
|
||||
"home-story": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Voce della barra delle storie per un account ({username})." },
|
||||
|
||||
@@ -1,51 +1,55 @@
|
||||
{
|
||||
"site": "instagram",
|
||||
"status": "ipotesi",
|
||||
"note": "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0 (specifica §6.4, regola 10). Contiene solo gli indizi che la specifica stessa elenca in §6.4 (pk, code, taken_at, image_versions2.candidates, video_versions, carousel_media); ogni altro concetto è vuoto e si compila sui campioni ripuliti della sonda. Finché lo stato è «ipotesi» o manca un concetto necessario, le ricette si rifiutano di girare su Instagram.",
|
||||
"status": "confermato",
|
||||
"note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome, quindi da solo non basta a riconoscerlo (H10 resta aperta).",
|
||||
"content": {
|
||||
"note": "Indizi di §6.4: chiavi viste in passato, non uno schema. Ipotesi, da confermare con i campioni di M0.",
|
||||
"note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza e raccolta-pagina-successiva. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media): chiave vista ma sempre vuota nei campioni, il formato dei figli è un indizio di §6.4 da confermare con un campione di un post con più file.",
|
||||
"id": ["pk"],
|
||||
"code": ["code"],
|
||||
"takenAt": ["taken_at"],
|
||||
"caption": [],
|
||||
"caption": ["caption.text"],
|
||||
"images": ["image_versions2.candidates"],
|
||||
"videos": ["video_versions"],
|
||||
"children": ["carousel_media"],
|
||||
"childCount": [],
|
||||
"owner": [],
|
||||
"childCount": ["carousel_media_count"],
|
||||
"owner": ["user", "owner"],
|
||||
"pinned": [],
|
||||
"expiresAt": [],
|
||||
"duration": []
|
||||
"expiresAt": ["expiring_at"],
|
||||
"duration": ["video_duration"]
|
||||
},
|
||||
"version": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H5).",
|
||||
"url": [],
|
||||
"width": [],
|
||||
"height": [],
|
||||
"note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).",
|
||||
"url": ["url"],
|
||||
"width": ["width"],
|
||||
"height": ["height"],
|
||||
"hasAudio": []
|
||||
},
|
||||
"profile": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H10).",
|
||||
"id": [],
|
||||
"username": [],
|
||||
"displayName": [],
|
||||
"isPrivate": [],
|
||||
"isFollowed": [],
|
||||
"note": "Un profilo (XDTUserDict): visto come autore di un post (user, owner), come proprietario di una raccolta, nella ricerca e nei profili suggeriti. friendship_status.following dice se Alberto lo segue; latest_reel_media è la data dell'ultima storia. Il numero dei post non compare in nessun campione: resta vuoto.",
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"isPrivate": ["is_private"],
|
||||
"isFollowed": ["friendship_status.following"],
|
||||
"postCount": [],
|
||||
"picture": [],
|
||||
"latestStoryAt": []
|
||||
"picture": ["hd_profile_pic_url_info", "hd_profile_pic_versions", "profile_pic_url"],
|
||||
"latestStoryAt": ["latest_reel_media"]
|
||||
},
|
||||
"highlight": {
|
||||
"note": "Da compilare con i campioni di M0 (H3, H9).",
|
||||
"id": [],
|
||||
"title": [],
|
||||
"owner": [],
|
||||
"items": []
|
||||
"note": "Una raccolta in evidenza (XDTReelDict con reel_type highlight_reel): id «highlight:<numero>», title, user e i contenuti in items. Vista in raccolta-in-evidenza e raccolta-pagina-successiva.",
|
||||
"id": ["id"],
|
||||
"title": ["title"],
|
||||
"owner": ["user"],
|
||||
"items": ["items"]
|
||||
},
|
||||
"page": {
|
||||
"note": "Da compilare con i campioni di M0 (H3).",
|
||||
"hasMore": [],
|
||||
"cursor": []
|
||||
"note": "page_info delle connessioni GraphQL (has_next_page, end_cursor) e more_available delle risposte REST. Visti in raccolta-in-evidenza e post-video.",
|
||||
"hasMore": ["has_next_page", "more_available"],
|
||||
"cursor": ["end_cursor"]
|
||||
},
|
||||
"viewer": []
|
||||
"relevance": {
|
||||
"note": "Una risposta che non contiene nessuna di queste chiavi non parla di contenuti né di profili e si ignora: promozioni, registri, il segno «storia vista», le definizioni delle pagine. Senza questo elenco ognuna conterebbe come «formato non riconosciuto».",
|
||||
"keys": ["image_versions2", "video_versions", "carousel_media", "taken_at", "username"]
|
||||
},
|
||||
"viewer": ["xdt_viewer.user"]
|
||||
}
|
||||
@@ -403,6 +403,8 @@ public static class EngineEventCodes
|
||||
public const string ManualCheck = "controlla-ora";
|
||||
public const string RecipeFailed = "ricetta-fallita";
|
||||
public const string SettingsChanged = "impostazioni-motore";
|
||||
public const string RecipeNotConfigured = "configurazione-incompleta";
|
||||
public const string CollectionConfigurationChanged = "configurazione-raccolta";
|
||||
|
||||
/// <summary>Prefix of the per-recipe lines («Appena fatto»): "ricetta." + recipe kind.</summary>
|
||||
public const string RecipePrefix = "ricetta.";
|
||||
|
||||
@@ -74,6 +74,12 @@ public enum RecipeStatus
|
||||
|
||||
/// <summary>Unexpected error; message says what happened.</summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>
|
||||
/// Refused before anything was done: the target map or the reader vocabulary of the site does not have what the
|
||||
/// recipe needs yet. A state of the configuration, not a failure of the recipe: it never counts towards suspension.
|
||||
/// </summary>
|
||||
NotConfigured,
|
||||
}
|
||||
|
||||
/// <summary>Result of a recipe run, used by the scheduler to plan what comes next.</summary>
|
||||
@@ -115,6 +121,13 @@ public interface IRecipeRunner
|
||||
|
||||
/// <summary>Puts the browser on the empty rest page (end of session, pauses, night).</summary>
|
||||
Task RestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="kind"/> cannot run on the configuration of the site in use (target map, reader vocabulary),
|
||||
/// in Italian; null when it can, or when the runner cannot tell. The engine does not plan such a recipe: running it
|
||||
/// would only end in <see cref="RecipeStatus.NotConfigured"/>.
|
||||
/// </summary>
|
||||
string? NotConfiguredReason(RecipeKind kind) => null;
|
||||
}
|
||||
|
||||
/// <summary>Daily byte budget for CDN downloads (category «dati scaricati», spec §7.4).</summary>
|
||||
|
||||
@@ -259,6 +259,11 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
}
|
||||
|
||||
var kind = CheckPolicy.WantsProfileChecks(account) ? EngineTaskKind.ProfileCheck : EngineTaskKind.AccountStories;
|
||||
if (_composer.NotConfiguredReason(CheckPolicy.RecipeOf(kind)) is { } notConfigured)
|
||||
{
|
||||
return new CheckNowResult(CheckNowStatus.Refused, notConfigured + " Il controllo non parte.");
|
||||
}
|
||||
|
||||
var category = kind == EngineTaskKind.ProfileCheck ? ActionKind.ProfileOpen : ActionKind.StoryView;
|
||||
var budget = await _s.Governor.EvaluateBudgetAsync(category, accountId, ct).ConfigureAwait(false);
|
||||
if (!budget.Granted && budget.Reason != DenialReason.AccountNotContactable)
|
||||
@@ -397,6 +402,49 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
return resumed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration in use: <paramref name="fingerprint"/> of the reader vocabulary and target map of the
|
||||
/// site as loaded. When it differs from the stored one — or none is stored yet, the first start that knows it —
|
||||
/// every suspension and consecutive failure of the recipes is cleared once, since they were counted against other
|
||||
/// files, with one line in the timeline when there was something to clear; then the fingerprint is stored. Called at
|
||||
/// start-up, before <see cref="StartAsync"/>. True when the configuration had changed.
|
||||
/// </summary>
|
||||
public async Task<bool> ApplyCollectionConfigurationAsync(string fingerprint, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(fingerprint);
|
||||
var settings = _s.Storage.Settings;
|
||||
if (string.Equals(await settings.GetAsync(EngineSettingKeys.CollectionConfiguration, ct).ConfigureAwait(false), fingerprint, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await _health.LoadAsync(ct).ConfigureAwait(false);
|
||||
var (suspended, hadFailures) = await _health.ResetAllAsync(ct).ConfigureAwait(false);
|
||||
if (suspended.Count > 0)
|
||||
{
|
||||
var names = string.Join(", ", suspended.Select(k => "«" + ItalianText.Capitalize(SessionComposer.RecipeName(k)) + "»"));
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
EngineEventCodes.CollectionConfigurationChanged,
|
||||
$"La configurazione della raccolta è cambiata: le ricette sospese ripartono ({names}).",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (hadFailures)
|
||||
{
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Info,
|
||||
EngineEventCodes.CollectionConfigurationChanged,
|
||||
"La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.",
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Stored last: if Febe stops in between, the next start clears again, which changes nothing.
|
||||
await settings.SetAsync(EngineSettingKeys.CollectionConfiguration, fingerprint, ct).ConfigureAwait(false);
|
||||
Wake();
|
||||
_s.Events.Publish(EngineNotificationKind.StateChanged);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Stores and applies new engine settings, then replans.</summary>
|
||||
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -45,6 +45,12 @@ public static class EngineSettingKeys
|
||||
|
||||
/// <summary>Last completed Giro dei seguiti, Unix milliseconds (it read the stories bar of every followed account).</summary>
|
||||
public const string LastSweep = "motore.ultimo-giro";
|
||||
|
||||
/// <summary>
|
||||
/// Fingerprint of the collection configuration the suspensions and failure counts refer to (reader vocabulary and
|
||||
/// target map of the site, as loaded): when it changes they are cleared once.
|
||||
/// </summary>
|
||||
public const string CollectionConfiguration = "motore.configurazione-raccolta";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -28,6 +28,7 @@ public sealed record RecentAction(
|
||||
RecipeStatus.AccountUnreachable => "Non raggiungibile",
|
||||
RecipeStatus.Cancelled => "Interrotto",
|
||||
RecipeStatus.Failed => "Errore",
|
||||
RecipeStatus.NotConfigured => "Da configurare",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Consecutive failures per recipe and suspended recipes (spec §6.4: after three «formato non riconosciuto» in a row
|
||||
/// the recipe is suspended and the interface says so). Persisted in the settings table.
|
||||
/// the recipe is suspended and the interface says so). Persisted in the settings table. A refusal because the
|
||||
/// configuration of the site is incomplete (<see cref="RecipeStatus.NotConfigured"/>) is not a failure and never
|
||||
/// reaches it; a change of that configuration clears it (<see cref="ResetAllAsync"/>).
|
||||
/// </summary>
|
||||
internal sealed class RecipeHealth
|
||||
{
|
||||
@@ -110,6 +112,26 @@ internal sealed class RecipeHealth
|
||||
return removed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration changed: every suspension and every consecutive failure goes, since they were
|
||||
/// counted against other files. Returns the recipes that were suspended and whether any failure was counted.
|
||||
/// </summary>
|
||||
public async Task<(IReadOnlyList<RecipeKind> Suspended, bool HadFailures)> ResetAllAsync(CancellationToken ct)
|
||||
{
|
||||
RecipeKind[] suspended;
|
||||
bool hadFailures;
|
||||
lock (_gate)
|
||||
{
|
||||
suspended = [.. _suspended.Keys.Order()];
|
||||
hadFailures = _failures.Count > 0;
|
||||
_suspended.Clear();
|
||||
_failures.Clear();
|
||||
}
|
||||
|
||||
await SaveAsync(ct).ConfigureAwait(false);
|
||||
return (suspended, hadFailures);
|
||||
}
|
||||
|
||||
private Task SaveAsync(CancellationToken ct)
|
||||
{
|
||||
string failures;
|
||||
|
||||
@@ -14,6 +14,9 @@ namespace Febe.Core.Engine;
|
||||
/// </summary>
|
||||
internal sealed class SessionComposer
|
||||
{
|
||||
/// <summary>What every line about a recipe the configuration does not let run adds (the runner's included).</summary>
|
||||
internal const string NotConfiguredTail = " Febe non la avvia finché la configurazione non è completa, e non la conta fra i problemi della ricetta.";
|
||||
|
||||
private static readonly TimeSpan DefaultWindow = TimeSpan.FromHours(16);
|
||||
|
||||
private readonly EngineServices _s;
|
||||
@@ -24,6 +27,13 @@ internal sealed class SessionComposer
|
||||
private readonly Lock _noticeGate = new();
|
||||
private readonly HashSet<(string Code, long? Account, DateOnly Day)> _notices = [];
|
||||
|
||||
// Recipes the configuration of the site does not let run. The configuration is loaded once per process, so what a
|
||||
// run learned holds until the end, and each recipe is said once (_notConfiguredSaid), not at every session.
|
||||
private readonly Lock _configurationGate = new();
|
||||
private readonly Dictionary<RecipeKind, string> _notConfigured = [];
|
||||
private readonly HashSet<RecipeKind> _notConfiguredSaid = [];
|
||||
private readonly List<string> _notConfiguredToSay = [];
|
||||
|
||||
// The interface calls SyncQueueAsync while a session may be running. A recipe's task is Running in the database
|
||||
// between its start and its bookkeeping, and then has its successor: under this gate the queue is looked at only
|
||||
// when every task is pending, in flight (_inFlight) or already replaced by its successor, never in between.
|
||||
@@ -102,6 +112,7 @@ internal sealed class SessionComposer
|
||||
|
||||
// Normally the next sweep will cover them: explicit checks only when no sweep can run, or after a long gap.
|
||||
var sweepUnavailable = _health.IsSuspended(RecipeKind.FollowingSweep)
|
||||
|| NotConfiguredReason(RecipeKind.FollowingSweep) is not null
|
||||
|| !(await _s.Governor.EvaluateBudgetAsync(ActionKind.Home, null, ct).ConfigureAwait(false)).Granted;
|
||||
var factor = sweepUnavailable ? 1 : 2;
|
||||
var uncovered = accounts.Values
|
||||
@@ -184,9 +195,9 @@ internal sealed class SessionComposer
|
||||
/// <summary>
|
||||
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
|
||||
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks of accounts that may not be
|
||||
/// contacted are cancelled. Commands of Alberto are left alone, and so is the task of the recipe in progress: its
|
||||
/// own bookkeeping plans the next one.
|
||||
/// «Storico in corso», a Giro dei seguiti when someone is followed; pending planned tasks the account no longer wants,
|
||||
/// or of accounts that may not be contacted, are cancelled (a «Post singolo» only in the second case). Commands of
|
||||
/// Alberto are left alone, and so is the task of the recipe in progress: its own bookkeeping plans the next one.
|
||||
/// </summary>
|
||||
public async Task<Dictionary<long, Account>> SyncQueueAsync(CancellationToken ct)
|
||||
{
|
||||
@@ -212,7 +223,14 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var tasks = byAccount[account.Id].Where(t => !t.IsManual).ToList();
|
||||
var wanted = WantedKinds(account);
|
||||
foreach (var task in tasks.Where(t => t.Kind != EngineTaskKind.HighlightCheck && !wanted.ContainsKey(t.Kind) && !(t.Kind == EngineTaskKind.AccountStories && t.Priority >= Options.FlaggedStoriesPriority && CheckPolicy.IsContactable(account))))
|
||||
|
||||
// Nothing is planned that the configuration of the site does not let run: it would only be refused.
|
||||
foreach (var kind in wanted.Keys.Where(k => !CanRun(CheckPolicy.RecipeOf(k))).ToList())
|
||||
{
|
||||
wanted.Remove(kind);
|
||||
}
|
||||
|
||||
foreach (var task in tasks.Where(t => !Keeps(t, account, wanted)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
}
|
||||
@@ -233,12 +251,13 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
var anyFollowed = accounts.Values.Any(a => a.IsFollowed && CheckPolicy.IsContactable(a));
|
||||
var sweepWanted = anyFollowed && CanRun(RecipeKind.FollowingSweep);
|
||||
var sweeps = pending.Where(t => t.Kind == EngineTaskKind.FollowingSweep && !t.IsManual).ToList();
|
||||
if (anyFollowed && sweeps.Count == 0)
|
||||
if (sweepWanted && sweeps.Count == 0)
|
||||
{
|
||||
await EnsureSweepTaskAsync(_s.Runtime.NextSessionAt ?? now, ct).ConfigureAwait(false);
|
||||
}
|
||||
else if (!anyFollowed)
|
||||
else if (!sweepWanted)
|
||||
{
|
||||
foreach (var sweep in sweeps)
|
||||
{
|
||||
@@ -246,9 +265,28 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return accounts;
|
||||
}
|
||||
|
||||
/// <summary>Whether <see cref="SyncQueueLockedAsync"/> leaves a pending planned task of the account where it is.</summary>
|
||||
private bool Keeps(EngineTask task, Account account, Dictionary<EngineTaskKind, DateTimeOffset?> wanted) => task.Kind switch
|
||||
{
|
||||
// One per collection: SyncHighlightsAsync.
|
||||
EngineTaskKind.HighlightCheck => true,
|
||||
|
||||
// Queued by the collection, not by the settings of the account: a series the grid did not give whole, an
|
||||
// address that expired (spec §6.5 point 5). Nothing would queue it again, so it waits while the recipe cannot
|
||||
// run, and goes only with an account that may not be contacted.
|
||||
EngineTaskKind.SinglePost => CheckPolicy.IsContactable(account),
|
||||
|
||||
// Flagged by the stories bar: kept until it runs, when it can.
|
||||
EngineTaskKind.AccountStories when task.Priority >= Options.FlaggedStoriesPriority =>
|
||||
wanted.ContainsKey(task.Kind) || (CheckPolicy.IsContactable(account) && CanRun(RecipeKind.AccountStories)),
|
||||
|
||||
_ => wanted.ContainsKey(task.Kind),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// «Raccolta in evidenza» (spec §6.3) for an account that wants «Storie in evidenza»: one task per collection the
|
||||
/// profile check found (payload: its Instagram identifier), due at once for a collection never looked at, then
|
||||
@@ -270,6 +308,11 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
if (collections.Count > 0 && !CanRun(RecipeKind.Highlight))
|
||||
{
|
||||
collections.Clear();
|
||||
}
|
||||
|
||||
foreach (var task in planned.Where(t => t.Payload is null || !collections.ContainsKey(t.Payload)))
|
||||
{
|
||||
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
|
||||
@@ -295,11 +338,73 @@ internal sealed class SessionComposer
|
||||
private bool InFlight(long accountId, EngineTaskKind kind, string? payload) =>
|
||||
_inFlight is { } task && task.AccountId == accountId && task.Kind == kind && (payload is null || task.Payload == payload);
|
||||
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session.</summary>
|
||||
public Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct) =>
|
||||
Store.Tasks.EnqueueAsync(
|
||||
/// <summary>The Giro dei seguiti shown in the queue at the next session (when the configuration lets it run).</summary>
|
||||
public async Task EnsureSweepTaskAsync(DateTimeOffset dueAt, CancellationToken ct)
|
||||
{
|
||||
if (!CanRun(RecipeKind.FollowingSweep))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await Store.Tasks.EnqueueAsync(
|
||||
new EngineTask { Kind = EngineTaskKind.FollowingSweep, DueAt = dueAt, CreatedAt = Clock.Now },
|
||||
ct);
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the configuration of the site in use (target map, reader vocabulary) does not let <paramref name="kind"/>
|
||||
/// run, as the runner says or as a run of it said; null when it can.
|
||||
/// </summary>
|
||||
internal string? NotConfiguredReason(RecipeKind kind)
|
||||
{
|
||||
lock (_configurationGate)
|
||||
{
|
||||
if (_notConfigured.TryGetValue(kind, out var known))
|
||||
{
|
||||
return known;
|
||||
}
|
||||
}
|
||||
|
||||
return _runner.NotConfiguredReason(kind);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// False when the configuration does not let <paramref name="kind"/> run. The first time, its reason is kept to be
|
||||
/// said in the timeline (<see cref="SayNotConfiguredAsync"/>): once per recipe and process, not at every session.
|
||||
/// </summary>
|
||||
private bool CanRun(RecipeKind kind)
|
||||
{
|
||||
if (NotConfiguredReason(kind) is not { } reason)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
lock (_configurationGate)
|
||||
{
|
||||
if (_notConfiguredSaid.Add(kind))
|
||||
{
|
||||
_notConfiguredToSay.Add(reason);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task SayNotConfiguredAsync()
|
||||
{
|
||||
string[] reasons;
|
||||
lock (_configurationGate)
|
||||
{
|
||||
reasons = [.. _notConfiguredToSay];
|
||||
_notConfiguredToSay.Clear();
|
||||
}
|
||||
|
||||
foreach (var reason in reasons)
|
||||
{
|
||||
await _s.Events.WriteAsync(EventSeverity.Warning, EngineEventCodes.RecipeNotConfigured, reason + NotConfiguredTail, ct: CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<EngineTaskKind, DateTimeOffset?> WantedKinds(Account account)
|
||||
{
|
||||
@@ -314,7 +419,7 @@ internal sealed class SessionComposer
|
||||
if (profile)
|
||||
{
|
||||
// A profile that is not followed shows its stories only on its page: one visit serves both checks.
|
||||
wanted[EngineTaskKind.ProfileCheck] = !account.IsFollowed && stories
|
||||
wanted[EngineTaskKind.ProfileCheck] = VisitServesStories(account)
|
||||
? Earliest(account.NextProfileCheckAt, account.NextStoriesCheckAt)
|
||||
: account.NextProfileCheckAt;
|
||||
}
|
||||
@@ -336,7 +441,21 @@ internal sealed class SessionComposer
|
||||
private static DateTimeOffset? Earliest(DateTimeOffset? a, DateTimeOffset? b) =>
|
||||
a is null || b is null ? null : a < b ? a : b;
|
||||
|
||||
private static bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
|
||||
/// <summary>
|
||||
/// Whether a visit of the profile also checks its stories, so that it comes at the shorter of the two intervals: a
|
||||
/// profile that is not followed, with «Storie» on, while the configuration lets «Storie di un account» run. Without
|
||||
/// it the visit is a plain profile check (story times are left as they are, for when the stories can run).
|
||||
/// </summary>
|
||||
private bool VisitServesStories(Account account) =>
|
||||
!account.IsFollowed && CheckPolicy.WantsStories(account) && CanRun(RecipeKind.AccountStories);
|
||||
|
||||
/// <summary>Interval of a visit of the profile (<see cref="CheckPolicy.VisitInterval"/> only when it serves the stories).</summary>
|
||||
private TimeSpan VisitInterval(Account account, TimeSpan window) =>
|
||||
VisitServesStories(account)
|
||||
? CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay)
|
||||
: CheckPolicy.ProfileCheckInterval(account);
|
||||
|
||||
private bool IsStoryWork(EngineTask task, Dictionary<long, Account> accounts, DateTimeOffset now)
|
||||
{
|
||||
if (task.Kind == EngineTaskKind.AccountStories)
|
||||
{
|
||||
@@ -347,8 +466,7 @@ internal sealed class SessionComposer
|
||||
return task.Kind == EngineTaskKind.ProfileCheck
|
||||
&& task.AccountId is { } id
|
||||
&& accounts.TryGetValue(id, out var account)
|
||||
&& !account.IsFollowed
|
||||
&& CheckPolicy.WantsStories(account)
|
||||
&& VisitServesStories(account)
|
||||
&& (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now);
|
||||
}
|
||||
|
||||
@@ -361,7 +479,7 @@ internal sealed class SessionComposer
|
||||
{
|
||||
var interval = task.Kind == EngineTaskKind.AccountStories
|
||||
? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay)
|
||||
: CheckPolicy.VisitInterval(account, window, Options.MinimumStoryChecksPerDay);
|
||||
: VisitInterval(account, window);
|
||||
items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval)));
|
||||
}
|
||||
else
|
||||
@@ -545,6 +663,15 @@ internal sealed class SessionComposer
|
||||
|
||||
var now = Clock.Now;
|
||||
var flagged = new HashSet<long>(outcome.AccountsWithStories);
|
||||
|
||||
// No check is queued that the configuration does not let run: it would only wait, and go at the next session.
|
||||
// Nothing is lost: until their stories are checked, every sweep flags these accounts again.
|
||||
if (flagged.Count > 0 && !CanRun(RecipeKind.AccountStories))
|
||||
{
|
||||
flagged.Clear();
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
foreach (var id in flagged)
|
||||
{
|
||||
if (accounts.TryGetValue(id, out var account) && CheckPolicy.IsContactable(account) && CheckPolicy.WantsStories(account))
|
||||
@@ -615,6 +742,12 @@ internal sealed class SessionComposer
|
||||
return;
|
||||
}
|
||||
|
||||
if (!CanRun(RecipeKind.Backfill))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var now = Clock.Now;
|
||||
var zone = Clock.LocalZone;
|
||||
var today = LocalCalendar.Today(now, zone);
|
||||
@@ -683,6 +816,25 @@ internal sealed class SessionComposer
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!CanRun(request.Kind))
|
||||
{
|
||||
await SayNotConfiguredAsync().ConfigureAwait(false);
|
||||
if (task is { IsManual: true })
|
||||
{
|
||||
// A command of Alberto that cannot be carried out with these files: dropped, and he is told why.
|
||||
await Store.Tasks.CancelAsync(task.Id, Clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
await _s.Events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
EngineEventCodes.RecipeNotConfigured,
|
||||
$"La tua richiesta ({RecipeName(request.Kind)}{Of(account)}) è annullata: {NotConfiguredReason(request.Kind)}",
|
||||
account?.Id,
|
||||
state.Context.SessionId,
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var category = CheckPolicy.CategoryOf(request.Kind);
|
||||
if (state.Exhausted.Contains(category))
|
||||
{
|
||||
@@ -875,6 +1027,26 @@ internal sealed class SessionComposer
|
||||
$"Formato non riconosciuto durante {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
case RecipeStatus.NotConfigured:
|
||||
// Not a failure: the files of the site do not let it run. Never counted towards suspension, not tried
|
||||
// again in this process (the runner has said why); a command of Alberto is dropped, planned work waits.
|
||||
lock (_configurationGate)
|
||||
{
|
||||
_notConfigured.TryAdd(kind, outcome.Message ?? $"«{ItalianText.Capitalize(RecipeName(kind))}» non può girare con la configurazione attuale.");
|
||||
_notConfiguredSaid.Add(kind);
|
||||
}
|
||||
|
||||
if (task is { IsManual: true })
|
||||
{
|
||||
writes.Add(Store.Tasks.CancelAsync(task.Id, now, ct));
|
||||
}
|
||||
else if (task is not null)
|
||||
{
|
||||
await RequeueAsync(task, "Configurazione incompleta", now).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case RecipeStatus.AccountUnreachable:
|
||||
if (task is not null)
|
||||
{
|
||||
@@ -955,9 +1127,10 @@ internal sealed class SessionComposer
|
||||
{
|
||||
case RecipeKind.ProfileCheck:
|
||||
{
|
||||
// A profile not followed is visited at the earlier of its post check and its story check.
|
||||
// A profile not followed is visited at the earlier of its post check and its story check (while the
|
||||
// stories can run: otherwise only for its posts).
|
||||
var next = now + CheckPolicy.NextCheckDelay(_s.Random, CheckPolicy.ProfileCheckInterval(account));
|
||||
DateTimeOffset? storiesNext = !account.IsFollowed && CheckPolicy.WantsStories(account)
|
||||
DateTimeOffset? storiesNext = VisitServesStories(account)
|
||||
? now + CheckPolicy.NextStoryCheckDelay(_s.Random, CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay))
|
||||
: null;
|
||||
state.LastVisitNext = storiesNext;
|
||||
@@ -1164,6 +1337,7 @@ internal sealed class SessionComposer
|
||||
RecipeStatus.UnrecognizedFormat => "Formato non riconosciuto",
|
||||
RecipeStatus.AccountUnreachable => "Non raggiungibile",
|
||||
RecipeStatus.Cancelled => "Interrotto",
|
||||
RecipeStatus.NotConfigured => "Configurazione della raccolta incompleta",
|
||||
_ => "Non riuscito",
|
||||
};
|
||||
return (title, detail);
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Threading.Channels;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
@@ -24,8 +25,8 @@ public static class EngineApi
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) =>
|
||||
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
|
||||
|
||||
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
@@ -78,13 +79,19 @@ public static class EngineApi
|
||||
endpoints.MapGet("/api/eventi", StreamAsync);
|
||||
}
|
||||
|
||||
/// <summary>The engine as the interface needs it.</summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
|
||||
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
|
||||
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
|
||||
/// (or there is none in this process) the connection is asked.
|
||||
/// </summary>
|
||||
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(monitor);
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(tracker);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
|
||||
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
|
||||
var state = snapshot.Mode switch
|
||||
@@ -92,9 +99,10 @@ public static class EngineApi
|
||||
EngineMode.NotConnected => "notConnected",
|
||||
EngineMode.StoppedForVerification => "verification",
|
||||
EngineMode.Disconnected => "disconnected",
|
||||
_ => mine is null ? "notConnected" : "connected",
|
||||
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
|
||||
_ => "connected",
|
||||
};
|
||||
var connection = state == "notConnected"
|
||||
var link = state == "notConnected"
|
||||
? new ConnectionDto(state, null, null, null)
|
||||
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
|
||||
|
||||
@@ -109,7 +117,7 @@ public static class EngineApi
|
||||
canResume = snapshot.Mode == EngineMode.Paused;
|
||||
}
|
||||
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, connection, canResume);
|
||||
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, link, canResume);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -123,7 +131,8 @@ public static class EngineApi
|
||||
IFebeStorage storage,
|
||||
BrowserUseTracker tracker,
|
||||
LibraryChanges library,
|
||||
IClock clock)
|
||||
IClock clock,
|
||||
IConnectionService connection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var response = context.Response;
|
||||
@@ -235,7 +244,7 @@ public static class EngineApi
|
||||
|
||||
async Task SendEngineAsync()
|
||||
{
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, ct).ConfigureAwait(false);
|
||||
var dto = await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false);
|
||||
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ using Febe.Browser.Download;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
@@ -59,6 +61,174 @@ public sealed class CaptureUnitTests
|
||||
Assert.AreEqual(2, cdp.Sent.Count(c => c.Method == "Network.getResponseBody"), "Only JSON bodies are fetched.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task JavaScriptAnswersOfThePageAreDataButScriptFilesAreNot()
|
||||
{
|
||||
// Instagram serves its GraphQL data as «text/javascript» (HAR of 21/10/2026).
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "g1" => new JsonObject { ["body"] = """{"data":{"x":[1]}}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "a1" => new JsonObject { ["body"] = """for (;;);{"payload":{}}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = "var x = 1;", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var consumer = new CollectingConsumer();
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(consumer);
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Received("g1", "http://127.0.0.1:5000/graphql/query", 200, "text/javascript; charset=utf-8", "XHR"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "g1", ["encodedDataLength"] = 20 });
|
||||
cdp.Raise("Network.responseReceived", Received("s1", "http://127.0.0.1:5001/bundle.js", 200, "text/javascript", "Script"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "s1", ["encodedDataLength"] = 10 });
|
||||
cdp.Raise("Network.responseReceived", Received("a1", "http://127.0.0.1:5000/ajax/navigation/", 200, "text/javascript", "XHR"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "a1", ["encodedDataLength"] = 24 });
|
||||
|
||||
await WaitUntilAsync(() => consumer.Items.Count == 1 && observer.Dropped.Contains("a1"));
|
||||
Assert.AreEqual("""{"data":{"x":[1]}}""", consumer.Items.Single().Json);
|
||||
Assert.AreEqual("XHR", consumer.Items.Single().Descriptor.ResourceType);
|
||||
Assert.IsFalse(cdp.Sent.Any(c => c.Method == "Network.getResponseBody" && c.Parameters?["requestId"]?.GetValue<string>() == "s1"), "A script file is never fetched.");
|
||||
Assert.AreEqual(1, tap.Stats.ParseErrors, "«for (;;);» is not JSON: skipped, and its waiters are told.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryJsonBlockOfThePageDocumentIsAnAnswerOfItsOwn()
|
||||
{
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
var tooDeep = new string('[', 300) + new string(']', 300);
|
||||
var html = $$"""
|
||||
<html><head><script type="application/json" data-sjs>{"a":1}</script><script>var b = 2;</script>
|
||||
<script type="application/json">{ non è json </script><script type="application/json">{{tooDeep}}</script>
|
||||
<script type="application/json"> </script></head>
|
||||
<body><script type="application/json">{"c":[3]}</script></body></html>
|
||||
""";
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "L7" => new JsonObject { ["body"] = html, ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "r10" => new JsonObject { ["body"] = """{"d":4}""", ["base64Encoded"] = false },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = "<html><body>niente</body></html>", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var failing = new FailingConsumer();
|
||||
var consumer = new CollectingConsumer();
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(failing);
|
||||
tap.AddConsumer(consumer);
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
// The frame commits the new document before its body has finished loading: the body is still read.
|
||||
cdp.Raise("Network.responseReceived", Document("L7", "http://127.0.0.1:5000/marta.prova/"));
|
||||
cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["loaderId"] = "L7", ["url"] = "http://127.0.0.1:5000/marta.prova/" } });
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L7", ["encodedDataLength"] = html.Length });
|
||||
|
||||
// A document without embedded JSON gives nothing; one of another host is not even fetched. A data answer after
|
||||
// them: the worker reads in order, so once it has arrived the documents have been dealt with.
|
||||
cdp.Raise("Network.responseReceived", Document("L8", "http://127.0.0.1:5000/vuota/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L8", ["encodedDataLength"] = 30 });
|
||||
cdp.Raise("Network.responseReceived", Document("L9", "https://esterno.example/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L9", ["encodedDataLength"] = 30 });
|
||||
cdp.Raise("Network.responseReceived", Received("r10", "http://127.0.0.1:5000/api/dopo", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r10", ["encodedDataLength"] = 7 });
|
||||
await WaitUntilAsync(() => consumer.Items.Any(i => i.Descriptor.RequestId == "r10"));
|
||||
|
||||
// One answer per valid block, in the order of the document, each with the document's descriptor: a block that
|
||||
// is not JSON, is too deep or is blank is left out without being a parse error.
|
||||
var blocks = consumer.Items.Where(i => i.Descriptor.RequestId == "L7").ToList();
|
||||
CollectionAssert.AreEqual(new[] { """{"a":1}""", """{"c":[3]}""" }, blocks.Select(b => b.Json).ToArray());
|
||||
Assert.IsTrue(blocks.All(b => b.Descriptor.IsMainFrameDocument && b.Descriptor.MimeType == "text/html" && b.Descriptor.Path == "/marta.prova/"));
|
||||
Assert.AreEqual(0, tap.Stats.ParseErrors);
|
||||
Assert.AreEqual(3, tap.Stats.JsonBodies, "Two blocks and the answer after them.");
|
||||
|
||||
// A reader that fails on a block stops neither the other readers, nor the next block, nor the next answer.
|
||||
Assert.AreEqual(3, failing.Calls);
|
||||
|
||||
// Those who wait for a body are told once when nothing reached the readers, never when blocks did.
|
||||
Assert.IsFalse(observer.Dropped.Contains("L7"));
|
||||
Assert.AreEqual(1, observer.Dropped.Count(id => id == "L8"));
|
||||
Assert.IsFalse(cdp.Sent.Any(c => c.Method == "Network.getResponseBody" && c.Parameters?["requestId"]?.GetValue<string>() == "L9"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePaginationOfAnEmbeddedBlockStaysWithTheBlockThatCarriesIt()
|
||||
{
|
||||
// Two real answers (cleaned samples of the HAR of 21/10/2026) embedded in one page document: first the
|
||||
// collections, which say «has_next_page: true» of themselves, then a post, which says «more_available: false»
|
||||
// of itself. Read as one answer, the post took the first pagination of the document, the collections'.
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
var html = $"""
|
||||
<!DOCTYPE html><html><head><script type="application/json">{SampleBody("raccolta-in-evidenza")}</script></head>
|
||||
<body><script type="application/json">{SampleBody("post-video")}</script></body></html>
|
||||
""";
|
||||
cdp.Responder = (method, p) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
|
||||
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "L7" => new JsonObject { ["body"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(html)), ["base64Encoded"] = true },
|
||||
"Network.getResponseBody" => new JsonObject { ["body"] = """{"segni":[1]}""", ["base64Encoded"] = false },
|
||||
_ => null,
|
||||
};
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
|
||||
var after = new CollectingConsumer();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock);
|
||||
tap.AddConsumer(capture);
|
||||
tap.AddObserver(capture);
|
||||
tap.AddConsumer(after);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Document("L7", "http://127.0.0.1:5000/marta.prova/"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "L7", ["encodedDataLength"] = html.Length });
|
||||
cdp.Raise("Network.responseReceived", Received("r2", "http://127.0.0.1:5000/api/dopo", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r2", ["encodedDataLength"] = 7 });
|
||||
await WaitUntilAsync(() => after.Items.Any(i => i.Descriptor.RequestId == "r2"));
|
||||
|
||||
var reads = capture.Since(0);
|
||||
Assert.AreEqual(2, reads.Count, "One read per block (the answer after them is not about contents).");
|
||||
Assert.IsTrue(reads.All(r => r.Response.RequestId == "L7" && r.Response.IsMainFrameDocument));
|
||||
var collections = reads[0].Result;
|
||||
Assert.AreEqual(2, collections.Highlights.Count);
|
||||
Assert.AreEqual(true, collections.Page?.HasMore);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(collections.Page?.Cursor));
|
||||
var post = reads[1].Result;
|
||||
Assert.AreEqual(0, post.Highlights.Count);
|
||||
Assert.AreEqual(1, post.Contents.Count);
|
||||
Assert.AreEqual(false, post.Page?.HasMore, "The post's own pagination, not the collections'.");
|
||||
Assert.IsNull(post.Page?.Cursor);
|
||||
Assert.AreEqual(0, capture.Pending, "Nothing is left on its way.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BodiesThatWillNotComeAreReportedToObservers()
|
||||
{
|
||||
var clock = new VirtualClock();
|
||||
var cdp = new FakeCdpSession(clock);
|
||||
cdp.Responder = (method, _) => method == "Page.getFrameTree"
|
||||
? new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } }
|
||||
: null;
|
||||
var observer = new CollectingObserver();
|
||||
await using var tap = new ResponseTap(cdp, Hosts, clock, options: new ResponseTapOptions { MaxBodyBytes = 100 });
|
||||
tap.AddConsumer(new CollectingConsumer());
|
||||
tap.AddObserver(observer);
|
||||
await tap.StartAsync();
|
||||
|
||||
cdp.Raise("Network.responseReceived", Received("big", "http://127.0.0.1:5000/a", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "big", ["encodedDataLength"] = 1000 });
|
||||
cdp.Raise("Network.responseReceived", Received("fail", "http://127.0.0.1:5000/b", 200, "application/json"));
|
||||
cdp.Raise("Network.loadingFailed", new JsonObject { ["requestId"] = "fail" });
|
||||
cdp.Raise("Network.responseReceived", Received("old", "http://127.0.0.1:5000/c", 200, "application/json"));
|
||||
cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["loaderId"] = "L2", ["url"] = "http://127.0.0.1:5000/altra/" } });
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { "big", "fail", "old" }, observer.Dropped.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task MainFrameNavigationsAreReported()
|
||||
{
|
||||
@@ -229,15 +399,25 @@ public sealed class CaptureUnitTests
|
||||
Assert.IsFalse(gate.IsDriving);
|
||||
}
|
||||
|
||||
private static JsonObject Received(string id, string url, int status, string mime) => new()
|
||||
private static JsonObject Received(string id, string url, int status, string mime, string type = "Fetch") => new()
|
||||
{
|
||||
["requestId"] = id,
|
||||
["loaderId"] = "L1",
|
||||
["frameId"] = "F1",
|
||||
["type"] = "Fetch",
|
||||
["type"] = type,
|
||||
["response"] = new JsonObject { ["url"] = url, ["status"] = status, ["mimeType"] = mime },
|
||||
};
|
||||
|
||||
/// <summary>The response of a main-frame navigation: its request id is the loader id.</summary>
|
||||
private static JsonObject Document(string loader, string url) => new()
|
||||
{
|
||||
["requestId"] = loader,
|
||||
["loaderId"] = loader,
|
||||
["frameId"] = "F1",
|
||||
["type"] = "Document",
|
||||
["response"] = new JsonObject { ["url"] = url, ["status"] = 200, ["mimeType"] = "text/html; charset=utf-8" },
|
||||
};
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
for (var i = 0; i < 300 && !condition(); i++)
|
||||
@@ -248,17 +428,39 @@ public sealed class CaptureUnitTests
|
||||
Assert.IsTrue(condition(), "Condition not reached in time.");
|
||||
}
|
||||
|
||||
/// <summary>The body of a cleaned Instagram sample (<c>tests/campioni/instagram</c>), as JSON text.</summary>
|
||||
private static string SampleBody(string name)
|
||||
{
|
||||
var file = Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
using var sample = JsonDocument.Parse(File.ReadAllText(file));
|
||||
return sample.RootElement.GetProperty("corpo").GetRawText();
|
||||
}
|
||||
|
||||
private sealed class CollectingConsumer : IResponseConsumer
|
||||
{
|
||||
public ConcurrentBag<(ResponseDescriptor Descriptor, string Json)> Items { get; } = [];
|
||||
/// <summary>In arrival order.</summary>
|
||||
public ConcurrentQueue<(ResponseDescriptor Descriptor, string Json)> Items { get; } = new();
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Items.Add((response, body.RootElement.GetRawText()));
|
||||
Items.Enqueue((response, body.RootElement.GetRawText()));
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailingConsumer : IResponseConsumer
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
|
||||
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
throw new InvalidOperationException("Lettore di prova che fallisce sempre.");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CollectingObserver : IResponseObserver
|
||||
{
|
||||
public ConcurrentQueue<ResponseDescriptor> Responses { get; } = new();
|
||||
@@ -267,7 +469,11 @@ public sealed class CaptureUnitTests
|
||||
|
||||
public void OnResponse(ResponseDescriptor response) => Responses.Enqueue(response);
|
||||
|
||||
public ConcurrentQueue<string> Dropped { get; } = new();
|
||||
|
||||
public void OnNavigation(NavigationDescriptor navigation) => Navigations.Enqueue(navigation);
|
||||
|
||||
public void OnBodyDropped(string requestId) => Dropped.Enqueue(requestId);
|
||||
}
|
||||
|
||||
private sealed class SyncProgress(List<long> values) : IProgress<long>
|
||||
|
||||
@@ -34,11 +34,46 @@ public sealed class CollectionUnitTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramMapIsASkeletonWithEveryEntryEmpty()
|
||||
public void TheInstagramMapHasThePagesSeenInRealTrafficAndNoTargetYet()
|
||||
{
|
||||
var map = SiteMap.LoadInstagram();
|
||||
Assert.AreEqual("instagram", map.Site);
|
||||
Assert.AreEqual(SitePages.All.Count + SiteTargets.All.Count, map.Missing(SitePages.All, SiteTargets.All).Count, "Nothing is filled in before M0.");
|
||||
|
||||
// Pages: only those with evidence in the HAR of 21 October 2026 (Instagram's own route templates and the
|
||||
// Referer of the page's requests). The others have none and stay empty.
|
||||
string[] filled = [SitePages.Home, SitePages.Profile, SitePages.Post, SitePages.StoryViewer, SitePages.HighlightViewer];
|
||||
string[] empty = [SitePages.ProfileFrom, SitePages.ReelsFrom, SitePages.TaggedFrom, SitePages.Following, SitePages.FollowingFrom];
|
||||
CollectionAssert.AreEquivalent(SitePages.All.ToArray(), filled.Concat(empty).ToArray(), "Every page is decided.");
|
||||
Assert.IsTrue(filled.All(map.HasPage));
|
||||
CollectionAssert.AreEquivalent(empty.Select(p => $"pagina «{p}»").ToArray(), map.Missing(SitePages.All, []).ToArray());
|
||||
|
||||
Assert.AreEqual("/", map.BuildPath(SitePages.Home));
|
||||
Assert.AreEqual("/mario.rossi/", map.BuildPath(SitePages.Profile, new Dictionary<string, string> { ["username"] = "mario.rossi" }));
|
||||
Assert.AreEqual("/p/Abc_12-xYz9/", map.BuildPath(SitePages.Post, new Dictionary<string, string> { ["code"] = "Abc_12-xYz9" }));
|
||||
Assert.IsNotNull(map.Match(SitePages.Home, "/"));
|
||||
Assert.IsNull(map.Match(SitePages.Home, "/mario.rossi/"));
|
||||
Assert.AreEqual("mario.rossi", map.Match(SitePages.Profile, "/mario.rossi/")!["username"]);
|
||||
|
||||
// Viewers: matched only, never opened. The story viewer carries the account and the story shown.
|
||||
var story = map.Match(SitePages.StoryViewer, "/stories/mario/3456789012345678901/");
|
||||
Assert.AreEqual("mario", story!["username"]);
|
||||
Assert.AreEqual("3456789012345678901", story["id"]);
|
||||
Assert.IsNull(map.Match(SitePages.StoryViewer, "/stories/mario/"), "Without the story id the shape does not match (to be confirmed live).");
|
||||
Assert.IsNull(map.Match(SitePages.HighlightViewer, "/stories/mario/3456789012345678901/"));
|
||||
|
||||
// The highlight viewer: the 17 digits of the collection and no item id (the address stays the same while watching).
|
||||
var highlight = map.Match(SitePages.HighlightViewer, "/stories/highlights/17841400000000000/");
|
||||
CollectionAssert.AreEquivalent(new[] { "highlight" }, highlight!.Keys.ToArray());
|
||||
Assert.AreEqual("17841400000000000", highlight["highlight"]);
|
||||
|
||||
// Overlap: a highlight address also has the story viewer's shape, with «highlights» as user name. The story
|
||||
// recipe then sees «another account» and closes; the highlight recipe reads only its own page.
|
||||
Assert.AreEqual("highlights", map.Match(SitePages.StoryViewer, "/stories/highlights/17841400000000000/")!["username"]);
|
||||
|
||||
// Targets: none has evidence yet (the HAR had no documents and no element attributes).
|
||||
var missingTargets = map.Missing([], SiteTargets.All);
|
||||
Assert.AreEqual(SiteTargets.All.Count, missingTargets.Count);
|
||||
Assert.IsTrue(missingTargets.All(m => m.EndsWith("(vuoto)", StringComparison.Ordinal)), "Every target is listed, still empty.");
|
||||
|
||||
// The browser layer reads the same file: every target is a placeholder and is never looked up in the page.
|
||||
var targets = TargetMap.LoadEmbedded("bersagli.instagram.json");
|
||||
@@ -49,47 +84,77 @@ public sealed class CollectionUnitTests
|
||||
Assert.AreEqual(TargetStatus.NotConfigured, lookup.Status);
|
||||
Assert.AreEqual(0, cdp.Sent.Count, "A placeholder never reaches the page.");
|
||||
StringAssert.Contains(lookup.Message, "H11");
|
||||
|
||||
// The copy next to the executable is the same map.
|
||||
var copy = SiteMap.Load(Path.Combine(AppContext.BaseDirectory, "config", "bersagli.instagram.json"));
|
||||
CollectionAssert.AreEquivalent(map.Missing(SitePages.All, SiteTargets.All).ToArray(), copy.Missing(SitePages.All, SiteTargets.All).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecipesRefuseToRunOnInstagramWhileTheMapOrTheReadersAreSkeletons()
|
||||
public async Task OnInstagramOnlyRecipesThatNeedNoTargetGetPastTheMap()
|
||||
{
|
||||
using var temp = new TempFolder("ricette");
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new VirtualClock();
|
||||
var governor = new PermissiveGovernor();
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
RecipeEnvironment Environment(SiteMap map, ReaderVocabulary vocabulary) => new()
|
||||
|
||||
// The Instagram vocabulary is confirmed on real samples. To see which recipes get past the map without letting
|
||||
// any of them reach the page, the runs use a copy marked as a hypothesis: the readers' gate comes right after
|
||||
// the map's and stops them there.
|
||||
Assert.IsTrue(ReaderVocabulary.LoadInstagram().IsUsable, ReaderVocabulary.LoadInstagram().UnusableReason);
|
||||
var stopper = ReaderVocabulary.LoadInstagram() with { Status = VocabularyStatus.Hypothesis };
|
||||
Task<RecipeOutcome> RunAsync(RecipeKind kind) => new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = new UntouchableDriver(),
|
||||
Capture = new CaptureCollector(new ShapeReader(vocabulary), clock),
|
||||
Capture = new CaptureCollector(new ShapeReader(stopper), clock),
|
||||
Governor = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock),
|
||||
Storage = db,
|
||||
SiteMap = map,
|
||||
SiteMap = SiteMap.LoadInstagram(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(1),
|
||||
};
|
||||
}).RunAsync(new RecipeRequest(kind, 1), session, CancellationToken.None);
|
||||
|
||||
foreach (var kind in Enum.GetValues<RecipeKind>().Where(k => k != RecipeKind.FollowingSweep))
|
||||
static void Refused(RecipeKind kind, RecipeOutcome outcome, string missing)
|
||||
{
|
||||
var outcome = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite()))
|
||||
.RunAsync(new RecipeRequest(kind, 1), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, kind.ToString());
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, outcome.Status, kind.ToString());
|
||||
StringAssert.Contains(outcome.Message, "mappa dei bersagli non è ancora compilata");
|
||||
StringAssert.Contains(outcome.Message, missing, kind.ToString());
|
||||
}
|
||||
|
||||
var sweep = await new RecipeRunner(Environment(SiteMap.LoadInstagram(), ReaderVocabulary.LoadTestSite()))
|
||||
.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
StringAssert.Contains(sweep.Message, "pagina «home»");
|
||||
static void Passed(RecipeKind kind, RecipeOutcome outcome)
|
||||
{
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, outcome.Status, $"{kind}: {outcome.Message}");
|
||||
StringAssert.Contains(outcome.Message, "ipotesi", kind.ToString());
|
||||
}
|
||||
|
||||
var readers = await new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadInstagram()))
|
||||
.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, readers.Status);
|
||||
StringAssert.Contains(readers.Message, "ipotesi");
|
||||
// Recipes that click something: every target is still empty (H11), while their pages are all there.
|
||||
foreach (var kind in new[] { RecipeKind.AccountStories, RecipeKind.Highlight, RecipeKind.Tagged, RecipeKind.Reels })
|
||||
{
|
||||
var outcome = await RunAsync(kind);
|
||||
Refused(kind, outcome, "(vuoto)");
|
||||
Assert.IsFalse(outcome.Message!.Contains("pagina «", StringComparison.Ordinal), $"{kind}: {outcome.Message}");
|
||||
}
|
||||
|
||||
// Recipes that only open pages.
|
||||
Passed(RecipeKind.FollowingSweep, await RunAsync(RecipeKind.FollowingSweep));
|
||||
Passed(RecipeKind.SinglePost, await RunAsync(RecipeKind.SinglePost));
|
||||
|
||||
// The profile check and the backfill need no target: the «not found» marker is looked up only when configured.
|
||||
foreach (var kind in new[] { RecipeKind.ProfileCheck, RecipeKind.Backfill })
|
||||
{
|
||||
Assert.IsFalse(RecipeRunner.Requirements(kind).Targets.Contains(SiteTargets.ProfileNotFound), kind.ToString());
|
||||
Passed(kind, await RunAsync(kind));
|
||||
}
|
||||
|
||||
// No evidence of the address of the following list.
|
||||
Refused(RecipeKind.FollowingList, await RunAsync(RecipeKind.FollowingList), $"pagina «{SitePages.Following}»");
|
||||
|
||||
Assert.AreEqual(0, governor.Requests.Count, "No permit asked, no gesture, no page.");
|
||||
Assert.IsTrue((await db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "mappa-incompleta"));
|
||||
var events = await db.Events.ListAsync(new EventQuery());
|
||||
Assert.IsTrue(events.Any(e => e.Code == "mappa-incompleta"));
|
||||
Assert.IsTrue(events.Any(e => e.Code == "lettori-incompleti"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Sonda;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The tools with which Alberto provides evidence from his own browser: the conversion of a HAR into the probe's raw
|
||||
/// format (<c>febe-sonda da-har</c>) and the targets snippet for the DevTools console. The HAR is synthetic, written by
|
||||
/// the test: invented generic values, nothing that claims to be Instagram's format.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class HarImportTests
|
||||
{
|
||||
private const string FirstBody = """{"dati":{"elementi":[{"numero":"5512345678","nome":"mario.rossi","larghezza":1080}]}}""";
|
||||
private const string SecondBody = """{"stato":"ok","persone":[{"nome":"lucia.bianchi"}]}""";
|
||||
private const string EmbeddedBlock = """{"profilo":{"nome":"mario.rossi","privato":false}}""";
|
||||
private const string SecondEmbeddedBlock = """{"pagina":{"altre":false},"elementi":[]}""";
|
||||
|
||||
/// <summary>The request parameter that names a GraphQL operation (the only part of a request body ever read).</summary>
|
||||
private const string Operation = HarImporter.OperationParameter;
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyDataAnswersOfTheSiteAndEmbeddedDataAreKeptWithoutHeadersCookiesOrQueries()
|
||||
{
|
||||
using var temp = new TempFolder("har");
|
||||
var har = temp.Combine("prova.har");
|
||||
File.WriteAllText(har, SyntheticHar().ToJsonString());
|
||||
var raw = temp.Combine("grezzi");
|
||||
|
||||
var report = HarImporter.Import(har, raw);
|
||||
Assert.AreEqual(new HarImportReport(Entries: 12, DataResponses: 4, Documents: 1, DocumentBlocks: 2, OtherHosts: 2, NotData: 2, WithoutBody: 1, NotJson: 1, DocumentsWithoutData: 1), report);
|
||||
Assert.AreEqual(6, report.Written);
|
||||
|
||||
// Flat files named by number and kind: a GraphQL operation name only when it is one, never a path.
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "000001-ProvaElencoQuery.json", "000002-risposta.json", "000003-ProvaPaginaSuccessivaQuery.json", "000004-risposta.json", "000005-documento.json", "000006-documento.json", "LEGGIMI.txt" },
|
||||
Directory.GetFiles(raw).Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray());
|
||||
|
||||
// Headers, cookies, query strings and request bodies never reach the output.
|
||||
foreach (var file in Directory.GetFiles(raw))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (var secret in new[] { "segreto", "sessionid", "cookie", "igsh", "variables", "pacchetto", "nascosto", "payload", "esterno" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(secret, StringComparison.OrdinalIgnoreCase), $"{Path.GetFileName(file)}: {secret}");
|
||||
}
|
||||
}
|
||||
|
||||
var first = Sample(raw, "000001-ProvaElencoQuery.json");
|
||||
var descriptor = first["descrittore"]!;
|
||||
Assert.AreEqual("https://www.instagram.com/graphql/query", descriptor["indirizzo"]!.GetValue<string>());
|
||||
Assert.AreEqual("sito", descriptor["host"]!.GetValue<string>());
|
||||
Assert.AreEqual(200, descriptor["stato"]!.GetValue<int>());
|
||||
Assert.AreEqual("text/javascript", descriptor["tipo"]!.GetValue<string>(), "Lower case, no parameters.");
|
||||
Assert.AreEqual("XHR", descriptor["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("2026-10-21T15:35:04Z", descriptor["quando"]!.GetValue<string>(), "UTC, to the second.");
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(FirstBody), first["corpo"]), "The base64 body, decoded and parsed.");
|
||||
CollectionAssert.AreEquivalent(new[] { "descrittore", "corpo" }, first.AsObject().Select(p => p.Key).ToArray());
|
||||
|
||||
var second = Sample(raw, "000002-risposta.json");
|
||||
Assert.AreEqual("https://www.instagram.com/api/v1/prova/mario.rossi/info/", second["descrittore"]!["indirizzo"]!.GetValue<string>());
|
||||
Assert.AreEqual("Fetch", second["descrittore"]!["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("application/json", second["descrittore"]!["tipo"]!.GetValue<string>());
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(SecondBody), second["corpo"]));
|
||||
|
||||
// A page document: one sample per valid JSON block it embeds, in order and with the document's descriptor, as
|
||||
// Febe's capture hands them to the readers; nothing of its scripts.
|
||||
var page = Sample(raw, "000005-documento.json");
|
||||
Assert.AreEqual("Document", page["descrittore"]!["risorsa"]!.GetValue<string>());
|
||||
Assert.AreEqual("text/html", page["descrittore"]!["tipo"]!.GetValue<string>());
|
||||
Assert.AreEqual("https://www.instagram.com/mario.rossi/", page["descrittore"]!["indirizzo"]!.GetValue<string>());
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(EmbeddedBlock), page["corpo"]));
|
||||
var nextBlock = Sample(raw, "000006-documento.json");
|
||||
Assert.IsTrue(JsonNode.DeepEquals(page["descrittore"], nextBlock["descrittore"]));
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(SecondEmbeddedBlock), nextBlock["corpo"]));
|
||||
|
||||
// The folder is a raw folder like the probe's: «ripulisci» and «verifica» work on it unchanged.
|
||||
var clean = temp.Combine("ripuliti");
|
||||
var cleaned = new SampleSanitizer(key: new byte[32]).SanitizeFolder(raw, clean);
|
||||
Assert.AreEqual(6, cleaned.Files);
|
||||
var verify = SampleVerifier.Verify(raw, clean);
|
||||
Assert.IsTrue(verify.Passed, string.Join("; ", verify.Leaks.Select(l => $"{l.CleanFile} {l.Length} {l.Kind}")));
|
||||
Assert.IsFalse(File.ReadAllText(Path.Combine(clean, "000001-ProvaElencoQuery.json")).Contains("mario", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheConversionRefusesRepositoriesUsedFoldersAndFilesThatAreNotAHar()
|
||||
{
|
||||
using var temp = new TempFolder("har");
|
||||
var har = temp.Combine("prova.har");
|
||||
File.WriteAllText(har, SyntheticHar().ToJsonString());
|
||||
|
||||
// Raw output inside a repository: refused before anything is written.
|
||||
Directory.CreateDirectory(temp.Combine("progetto", ".git"));
|
||||
var inside = temp.Combine("progetto", "grezzi");
|
||||
StringAssert.Contains(Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(har, inside)).Message, "fuori dal repository");
|
||||
Assert.IsFalse(Directory.Exists(inside));
|
||||
|
||||
// The HAR itself holds cookies: it is not read from inside a repository either.
|
||||
var harInside = temp.Combine("progetto", "prova.har");
|
||||
File.Copy(har, harInside);
|
||||
Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(harInside, temp.Combine("altrove")));
|
||||
|
||||
// A folder that is already in use: refused, nothing is mixed or overwritten.
|
||||
var used = Directory.CreateDirectory(temp.Combine("usata")).FullName;
|
||||
File.WriteAllText(Path.Combine(used, "000001-risposta.json"), "{}");
|
||||
StringAssert.Contains(Assert.ThrowsExactly<InvalidOperationException>(() => HarImporter.Import(har, used)).Message, "non è vuota");
|
||||
Assert.AreEqual("{}", File.ReadAllText(Path.Combine(used, "000001-risposta.json")));
|
||||
|
||||
Assert.ThrowsExactly<FileNotFoundException>(() => HarImporter.Import(temp.Combine("manca.har"), temp.Combine("nuova1")));
|
||||
File.WriteAllText(temp.Combine("non-har.har"), """{"altro":[]}""");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("non-har.har"), temp.Combine("nuova2")));
|
||||
File.WriteAllText(temp.Combine("rotto.har"), "{\"log\":");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("rotto.har"), temp.Combine("nuova3")));
|
||||
File.WriteAllText(temp.Combine("elenco.har"), "[1,2]");
|
||||
Assert.ThrowsExactly<InvalidDataException>(() => HarImporter.Import(temp.Combine("elenco.har"), temp.Combine("nuova4")));
|
||||
Assert.IsFalse(Directory.Exists(temp.Combine("nuova4")), "Nothing is created for a file that is not a HAR.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnlyNamesOfTheSiteCodeNameAFile()
|
||||
{
|
||||
Assert.AreEqual("PolarisStoriesV3HighlightsPageQuery", HarImporter.OperationName("PolarisStoriesV3HighlightsPageQuery"));
|
||||
Assert.AreEqual("usePolarisRegisterInRecentSearchesMutation", HarImporter.OperationName(" usePolarisRegisterInRecentSearchesMutation "));
|
||||
Assert.AreEqual("ProvaAggiornamentiSubscription", HarImporter.OperationName("ProvaAggiornamentiSubscription"));
|
||||
foreach (var value in new[] { null, "", "Query", "mario.rossi", "mario_rossi", "Pagina di mario Query", "Profilo12345Query", "/mario.rossi/Query", "ProvaElenco" })
|
||||
{
|
||||
Assert.IsNull(HarImporter.OperationName(value), value ?? "null");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTargetsSnippetOnlyListensAndReads()
|
||||
{
|
||||
var path = Febe.Tests.Desktop.Support.Repository.PathOf("tools", "bersagli", "raccogli-bersagli.js");
|
||||
var script = File.ReadAllText(path);
|
||||
|
||||
// The same deny-list as Febe's own page scripts: no gesture, no DOM change, no request, no cookie or storage.
|
||||
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(script);
|
||||
foreach (var word in new[] { "preventDefault", "stopPropagation", "stopImmediatePropagation", "postMessage", "document.cookie", "cookieStore", "Storage", "indexedDB", "fetch(", "XMLHttpRequest", "sendBeacon", "WebSocket", "new Image", "innerHTML", "outerHTML", "classList", ".style", "setAttribute", "removeAttribute", "eval(", "Function(", "open(" })
|
||||
{
|
||||
Assert.IsFalse(script.Contains(word, StringComparison.Ordinal), word);
|
||||
}
|
||||
|
||||
// One capturing click listener, and the function that copies the records.
|
||||
foreach (var part in new[] { "addEventListener('click', onClick, { capture: true, passive: true })", "globalThis.febeBersagli = ", "copy(text)" })
|
||||
{
|
||||
Assert.IsTrue(script.Contains(part, StringComparison.Ordinal), part);
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, script.Split("addEventListener").Length - 1, "A single listener.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(Path.GetDirectoryName(path)!, "LEGGIMI.md")));
|
||||
}
|
||||
|
||||
private static JsonNode Sample(string folder, string name) => JsonNode.Parse(File.ReadAllText(Path.Combine(folder, name)))!;
|
||||
|
||||
private static string Base64(string text) => Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
|
||||
|
||||
private static JsonObject SyntheticHar()
|
||||
{
|
||||
static JsonArray Headers(params (string Name, string Value)[] headers) =>
|
||||
[.. headers.Select(h => (JsonNode)new JsonObject { ["name"] = h.Name, ["value"] = h.Value })];
|
||||
|
||||
static JsonObject Entry(string resourceType, string method, string url, int status, JsonObject content, JsonObject? postData = null, string started = "2026-10-21T17:35:04.512+02:00")
|
||||
{
|
||||
var request = new JsonObject
|
||||
{
|
||||
["method"] = method,
|
||||
["url"] = url,
|
||||
["httpVersion"] = "h3",
|
||||
["headers"] = Headers(("Cookie", "sessionid=segreto-cookie; ds_user_id=segreto-cookie"), ("X-Prova", "segreto-intestazione")),
|
||||
["queryString"] = new JsonArray(new JsonObject { ["name"] = "variables", ["value"] = "segreto-indirizzo" }),
|
||||
["cookies"] = new JsonArray(new JsonObject { ["name"] = "sessionid", ["value"] = "segreto-cookie" }),
|
||||
["headersSize"] = -1,
|
||||
["bodySize"] = 0,
|
||||
};
|
||||
if (postData is not null)
|
||||
{
|
||||
request["postData"] = postData;
|
||||
}
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["_resourceType"] = resourceType,
|
||||
["startedDateTime"] = started,
|
||||
["time"] = 123.4,
|
||||
["request"] = request,
|
||||
["response"] = new JsonObject
|
||||
{
|
||||
["status"] = status,
|
||||
["statusText"] = "",
|
||||
["httpVersion"] = "h3",
|
||||
["headers"] = Headers(("Set-Cookie", "prova=segreto-risposta"), ("Content-Type", "text/plain; segreto-intestazione")),
|
||||
["cookies"] = new JsonArray(new JsonObject { ["name"] = "prova", ["value"] = "segreto-risposta" }),
|
||||
["content"] = content,
|
||||
["redirectURL"] = "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
static JsonObject Content(string mime, string? text, bool base64 = false)
|
||||
{
|
||||
var content = new JsonObject { ["size"] = text?.Length ?? 0, ["mimeType"] = mime };
|
||||
if (text is not null)
|
||||
{
|
||||
content["text"] = base64 ? Base64(text) : text;
|
||||
if (base64)
|
||||
{
|
||||
content["encoding"] = "base64";
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
static JsonObject Form(string text, params (string Name, string Value)[] parameters)
|
||||
{
|
||||
var form = new JsonObject { ["mimeType"] = "application/x-www-form-urlencoded", ["text"] = text };
|
||||
if (parameters.Length > 0)
|
||||
{
|
||||
form["params"] = Headers(parameters);
|
||||
}
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
var page = $$"""
|
||||
<!DOCTYPE html><html><head>
|
||||
<script>var nascosto = "segreto-script";</script>
|
||||
<script type="application/json" data-prova="1">{{EmbeddedBlock}}</script>
|
||||
<script type="application/json">{ "rotto": </script>
|
||||
</head><body><p>segreto-testo-della-pagina</p><script type="application/json">{{SecondEmbeddedBlock}}</script></body></html>
|
||||
""";
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["log"] = new JsonObject
|
||||
{
|
||||
["version"] = "1.2",
|
||||
["creator"] = new JsonObject { ["name"] = "WebInspector", ["version"] = "537.36" },
|
||||
["pages"] = new JsonArray(),
|
||||
["entries"] = new JsonArray(
|
||||
Entry("xhr", "POST", "https://www.instagram.com/graphql/query?variables=segreto-indirizzo", 200, Content("text/javascript; charset=utf-8", FirstBody, base64: true),
|
||||
Form($"av=segreto-corpo&{Operation}=ProvaElencoQuery&variables=segreto-corpo", ("av", "segreto-corpo"), (Operation, "ProvaElencoQuery"), ("variables", "segreto-corpo"))),
|
||||
Entry("fetch", "GET", "https://www.instagram.com/api/v1/prova/mario.rossi/info/?segreto=1", 200, Content("application/json", SecondBody)),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/graphql/query", 200, Content("application/json", """{"pagina":{"cursore":"QVFIUjBz","altre":true}}"""),
|
||||
Form($"{Operation}=ProvaPaginaSuccessivaQuery&x=segreto-corpo")),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/api/graphql", 200, Content("text/javascript", """{"dati":{"vuoto":null}}"""),
|
||||
Form($"{Operation}=mario.rossi", (Operation, "mario.rossi"))),
|
||||
Entry("script", "GET", "https://www.instagram.com/static/pacchetto.js", 200, Content("text/javascript", "console.log('segreto-script')")),
|
||||
Entry("image", "GET", "https://scontent.cdninstagram.com/v/foto.jpg?firma=segreto-indirizzo", 200, Content("image/jpeg", "segreto-immagine", base64: true)),
|
||||
Entry("document", "GET", "https://www.instagram.com/mario.rossi/?igsh=segreto-indirizzo", 200, Content("text/html; charset=utf-8", page)),
|
||||
Entry("xhr", "POST", "https://www.instagram.com/ajax/prova/", 200, Content("text/javascript", """for (;;);{"payload":{"segreto":1}}""")),
|
||||
Entry("document", "GET", "https://www.instagram.com/altro/", 200, Content("text/html", "<html><body>segreto-senza-dati</body></html>")),
|
||||
Entry("xhr", "GET", "https://www.instagram.com/api/v1/vuota/", 200, Content("application/json", null)),
|
||||
Entry("fetch", "GET", "https://esterno.example/api/?segreto=1", 200, Content("application/json", """{"segreto":1}""")),
|
||||
Entry("fetch", "GET", "https://scontent.cdninstagram.com/v/dati.json", 200, Content("application/json", """{"segreto":1}"""))),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The reader with the Instagram vocabulary on the cleaned real samples of <c>tests/campioni/instagram</c>: answers
|
||||
/// Alberto's browser received on 21 October 2026 (HAR), cleaned with «febe-sonda ripulisci» and checked with
|
||||
/// «febe-sonda verifica» (spec §14.5, rule 10). Values are fakes of the same shape: the tests check shapes, sizes,
|
||||
/// dates and counts.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class InstagramReaderTests
|
||||
{
|
||||
private static readonly ReaderVocabulary Vocabulary = ReaderVocabulary.LoadInstagram();
|
||||
private static readonly ShapeReader Reader = new(Vocabulary);
|
||||
|
||||
private static string SampleFile(string name) =>
|
||||
Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
|
||||
private static ReadResult ReadSample(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return Reader.Read(document.RootElement.GetProperty("corpo"));
|
||||
}
|
||||
|
||||
private static string SampleBody(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return document.RootElement.GetProperty("corpo").GetRawText();
|
||||
}
|
||||
|
||||
private static string MimeOf(string name)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(SampleFile(name)));
|
||||
return document.RootElement.GetProperty("descrittore").GetProperty("tipo").GetString()!;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramVocabularyIsConfirmedAndUsable()
|
||||
{
|
||||
Assert.AreEqual(VocabularyStatus.Confirmed, Vocabulary.Status);
|
||||
Assert.IsTrue(Vocabulary.IsUsable, Vocabulary.UnusableReason);
|
||||
Assert.AreEqual(0, Vocabulary.MissingConcepts.Count);
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.instagram.json")), "Editable without recompiling.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryKeyOfTheVocabularyComesFromTheRealSamples()
|
||||
{
|
||||
// Rule 10: the format is not invented. Every path of lettori.instagram.json exists, as nested keys, somewhere in
|
||||
// the cleaned samples; every relevance key is a key of the samples.
|
||||
var paths = new HashSet<string>(StringComparer.Ordinal);
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json"))
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(file));
|
||||
Collect(document.RootElement.GetProperty("corpo"), paths, names);
|
||||
}
|
||||
|
||||
var concepts = new[]
|
||||
{
|
||||
Vocabulary.Content.Id, Vocabulary.Content.Code, Vocabulary.Content.TakenAt, Vocabulary.Content.Caption, Vocabulary.Content.Images,
|
||||
Vocabulary.Content.Videos, Vocabulary.Content.Children, Vocabulary.Content.ChildCount, Vocabulary.Content.Owner, Vocabulary.Content.Pinned,
|
||||
Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height,
|
||||
Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate,
|
||||
Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt,
|
||||
Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items,
|
||||
Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer,
|
||||
};
|
||||
foreach (var path in concepts.SelectMany(c => c.Paths))
|
||||
{
|
||||
Assert.IsTrue(paths.Contains(path), $"«{path}» non compare in nessun campione ripulito di Instagram.");
|
||||
}
|
||||
|
||||
foreach (var key in Vocabulary.Relevance)
|
||||
{
|
||||
Assert.IsTrue(names.Contains(key), $"«{key}» non compare in nessun campione ripulito di Instagram.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GraphQlAnswersComeAsJavaScriptAndAreReadAsData()
|
||||
{
|
||||
// Why the capture reads «text/javascript»: the stories and highlights data of the samples was served that way.
|
||||
Assert.AreEqual("text/javascript", MimeOf("raccolta-in-evidenza"));
|
||||
Assert.AreEqual("application/json", MimeOf("post-video"));
|
||||
Assert.IsTrue(DataResponses.IsData("text/javascript", "XHR"));
|
||||
Assert.IsTrue(DataResponses.IsData("text/javascript", "Fetch"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/x-javascript", "XHR"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/json", "Fetch"));
|
||||
Assert.IsTrue(DataResponses.IsData("application/json", null));
|
||||
Assert.IsFalse(DataResponses.IsData("text/javascript", "Script"), "Script files are never parsed.");
|
||||
Assert.IsFalse(DataResponses.IsData("text/javascript", null));
|
||||
Assert.IsFalse(DataResponses.IsData("text/html", "Document"));
|
||||
Assert.IsFalse(DataResponses.IsData("video/mp4", "Fetch"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AHighlightPageGivesTheCollectionsTheirStoriesAndTheirOwner()
|
||||
{
|
||||
var result = ReadSample("raccolta-in-evidenza");
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
Assert.AreEqual(2, result.Highlights.Count);
|
||||
foreach (var highlight in result.Highlights)
|
||||
{
|
||||
// «highlight:<17 digits>» in the data, «/stories/highlights/<17 digits>/» in the address: the reader keeps
|
||||
// the address form (the cleaned samples fake the letters of the prefix, not its shape).
|
||||
StringAssert.Matches(highlight.Id, new System.Text.RegularExpressions.Regex("^[0-9]{17}$"));
|
||||
Assert.AreEqual(4, highlight.Items.Count);
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(highlight.Title));
|
||||
Assert.IsNotNull(highlight.Owner);
|
||||
Assert.IsTrue(highlight.Items.All(i => i.HighlightId == highlight.Id));
|
||||
|
||||
// The «user» of each item has only an identifier: the author is the owner of the collection.
|
||||
Assert.IsTrue(highlight.Items.All(i => i.Owner?.Id == highlight.Owner.Id && i.Owner.Username == highlight.Owner.Username));
|
||||
Assert.IsTrue(highlight.Items.All(i => i.ExpiresAt > i.TakenAt), "Highlight items keep the expiry they had as stories.");
|
||||
Assert.IsTrue(highlight.Items.All(i => i.Code is { Length: 11 }));
|
||||
Assert.IsTrue(highlight.Items.All(i => i.IsComplete && i.Files.Count == 1));
|
||||
}
|
||||
|
||||
Assert.AreEqual(result.Highlights.Sum(h => h.Items.Count), result.Contents.Count);
|
||||
Assert.IsFalse(result.Contents.Any(c => c.ExpiresAt is null && c.HighlightId is null), "Nothing here looks like a post.");
|
||||
Assert.AreEqual(true, result.Page?.HasMore);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(result.Page?.Cursor));
|
||||
Assert.IsTrue(result.Profiles.Any(p => p.Id == result.Highlights[0].Owner!.Id && p.IsPrivate == false));
|
||||
Assert.IsNull(result.Viewer, "xdt_viewer.user has no user name: the connected account is not recognized from it alone (H10).");
|
||||
Assert.IsNotNull(result.ViewerId, "Its identifier is kept, to recognize its profile in other answers.");
|
||||
Assert.IsFalse(result.Profiles.Any(p => p.Id == result.ViewerId), "In this answer the connected account has no profile.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void StoryFilesTakeTheLargestImageAndTheFirstVideoVersion()
|
||||
{
|
||||
var items = ReadSample("raccolta-in-evidenza").Contents;
|
||||
var photos = items.Where(i => i.Files[0].Kind == MediaKind.Photo).ToList();
|
||||
var videos = items.Where(i => i.Files[0].Kind == MediaKind.Video).ToList();
|
||||
Assert.IsTrue(photos.Count > 0 && videos.Count > 0);
|
||||
|
||||
// The largest of the 10–14 candidates: 1206×2144 or 640×1136 in the samples.
|
||||
Assert.IsTrue(items.All(i => i.Files[0].Kind == MediaKind.Video || i.Files[0].Best.Area >= 640 * 1136));
|
||||
Assert.IsTrue(photos.All(p => p.Files[0].Best.Url.EndsWith(".jpg", StringComparison.Ordinal)));
|
||||
|
||||
// Story video versions (type 101, 102, 103) carry no size: the first one is taken, with the cover image.
|
||||
foreach (var video in videos.Select(v => v.Files[0]))
|
||||
{
|
||||
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
|
||||
Assert.IsNull(video.Best.Width);
|
||||
Assert.IsNotNull(video.Cover);
|
||||
Assert.IsTrue(video.Duration > TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheNextPageOfHighlightsIsReadLikeTheFirst()
|
||||
{
|
||||
var result = ReadSample("raccolta-pagina-successiva");
|
||||
var highlight = result.Highlights.Single();
|
||||
Assert.AreEqual(3, highlight.Items.Count);
|
||||
Assert.IsNotNull(highlight.Owner);
|
||||
Assert.IsNotNull(result.Page);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void APostPageGivesTheVideoItsCoverTheCaptionAndTheAuthor()
|
||||
{
|
||||
var result = ReadSample("post-video");
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
var post = result.Contents.Single();
|
||||
Assert.AreEqual(11, post.Code?.Length);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(post.Caption), "The caption is an object: its text is in caption.text.");
|
||||
Assert.IsNull(post.ExpiresAt);
|
||||
Assert.IsNull(post.HighlightId);
|
||||
Assert.IsTrue(post.IsComplete);
|
||||
Assert.IsNotNull(post.Owner);
|
||||
Assert.AreEqual(false, post.Owner.IsFollowed, "friendship_status.following of the author.");
|
||||
Assert.AreEqual(false, post.Owner.IsPrivate);
|
||||
Assert.IsNotNull(post.Owner.Picture);
|
||||
Assert.AreEqual(960, post.Owner.Picture.Width, "hd_profile_pic_url_info, the largest picture.");
|
||||
Assert.IsNotNull(post.Owner.LatestStoryAt);
|
||||
|
||||
var video = post.Files.Single();
|
||||
Assert.AreEqual(MediaKind.Video, video.Kind);
|
||||
Assert.AreEqual((720, 1280), (video.Best.Width, video.Best.Height));
|
||||
Assert.IsTrue(video.Best.Url.EndsWith(".mp4", StringComparison.Ordinal));
|
||||
Assert.AreEqual((720, 1280), (video.Cover?.Width, video.Cover?.Height), "The largest of the 12 candidates.");
|
||||
Assert.AreEqual(5.919, video.Duration!.Value.TotalSeconds, 0.001);
|
||||
Assert.AreEqual(false, result.Page?.HasMore, "more_available of the REST answer.");
|
||||
|
||||
var now = new DateTimeOffset(2026, 10, 25, 12, 0, 0, TimeSpan.Zero);
|
||||
var media = ReadMapping.ToMedia(post, now).Single();
|
||||
Assert.AreEqual(MediaKind.Video, media.Kind);
|
||||
Assert.AreEqual(video.Best.Url, media.SourceUrl);
|
||||
Assert.AreEqual(video.Cover!.Url, media.CoverUrl);
|
||||
Assert.AreEqual(post.TakenAt, ReadMapping.ToEntry(post, 1, EntryKind.Post, now).PublishedAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProfilesOfSearchSuggestionsAndCommentsAreProfilesOnly()
|
||||
{
|
||||
var search = ReadSample("ricerca-profili");
|
||||
Assert.AreEqual(ReadShape.Recognized, search.Shape);
|
||||
Assert.AreEqual(5, search.Profiles.Count);
|
||||
Assert.AreEqual(0, search.Contents.Count);
|
||||
|
||||
var suggested = ReadSample("profili-suggeriti");
|
||||
Assert.AreEqual(3, suggested.Profiles.Count);
|
||||
Assert.IsTrue(suggested.Profiles.All(p => p.IsFollowed == false), "Suggested profiles are not followed.");
|
||||
Assert.AreEqual(0, suggested.Contents.Count);
|
||||
|
||||
var comments = ReadSample("commenti");
|
||||
Assert.AreEqual(0, comments.Contents.Count);
|
||||
Assert.IsTrue(comments.Profiles.Count > 0);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnswersAboutOtherThingsAreUnrelatedNotAnUnknownFormat()
|
||||
{
|
||||
foreach (var name in new[] { "promozioni", "storia-vista" })
|
||||
{
|
||||
var result = ReadSample(name);
|
||||
Assert.AreEqual(ReadShape.Unrelated, result.Shape, name);
|
||||
Assert.IsNull(result.KeyStructure, name);
|
||||
}
|
||||
|
||||
// A response that speaks of contents but in keys nobody knows is still an unknown format (spec §6.4).
|
||||
var changed = Reader.Read("""{"data":{"feed":{"items":[{"pk":"1","taken_at":1777663535,"image_versions3":{"candidates":[]}}]}}}""");
|
||||
Assert.AreEqual(ReadShape.Unrecognized, changed.Shape);
|
||||
Assert.IsNotNull(changed.KeyStructure);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCollectorKeepsNothingOfUnrelatedAnswers()
|
||||
{
|
||||
var clock = new Febe.Tests.Browser.TestSupport.VirtualClock();
|
||||
var collector = new CaptureCollector(Reader, clock);
|
||||
var observer = (IResponseObserver)collector;
|
||||
var descriptor = new ResponseDescriptor("r1", HostKind.Site, "https://www.instagram.com/api/graphql", "www.instagram.com", "/api/graphql", 200, "text/javascript", "XHR", false, clock.Now);
|
||||
observer.OnResponse(descriptor);
|
||||
Assert.AreEqual(1, collector.Pending, "A JavaScript data answer is awaited like a JSON one.");
|
||||
var mark = collector.Mark();
|
||||
using (var promo = JsonDocument.Parse(File.ReadAllText(SampleFile("promozioni"))))
|
||||
{
|
||||
Assert.IsNull(collector.Accept(descriptor, promo.RootElement.GetProperty("corpo")));
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, collector.Pending);
|
||||
Assert.AreEqual(mark, collector.Mark(), "An unrelated answer is not «something new arrived».");
|
||||
using var highlights = JsonDocument.Parse(File.ReadAllText(SampleFile("raccolta-in-evidenza")));
|
||||
Assert.IsNotNull(collector.Accept(descriptor with { RequestId = "r2" }, highlights.RootElement.GetProperty("corpo")));
|
||||
Assert.AreEqual(ReadShape.Recognized, collector.Since(mark).Single().Result.Shape);
|
||||
|
||||
observer.OnResponse(descriptor with { RequestId = "r3", ResourceType = "Script" });
|
||||
Assert.AreEqual(0, collector.Pending, "A script file is not data.");
|
||||
|
||||
// The connected account's identifier is remembered even from an answer that is otherwise not kept.
|
||||
using var unrelated = JsonDocument.Parse("""{"data":{"xdt_viewer":{"user":{"id":"5512345","pk":"5512345"}},"segni":[1]}}""");
|
||||
var before = collector.Mark();
|
||||
Assert.IsNull(collector.Accept(descriptor with { RequestId = "r4" }, unrelated.RootElement));
|
||||
Assert.AreEqual(before, collector.Mark());
|
||||
Assert.AreEqual("5512345", collector.ViewerId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDataEmbeddedInAPageDocumentIsReadLikeAnAnswer()
|
||||
{
|
||||
// Each valid block is an answer of its own, as the capture hands it to the readers: the collections (which say
|
||||
// «has_next_page: true» of themselves) and the post (which says «more_available: false» of itself) keep each
|
||||
// their own pagination, whatever their order in the document.
|
||||
var head = $$"""
|
||||
<!DOCTYPE html><html><head>
|
||||
<script type="application/json" data-sjs>{"require":[["Bootloader","handle",null,[{"x":1}]]]}</script>
|
||||
<script>var notData = {"a":1};</script>
|
||||
<script type="application/json">{ not json </script>
|
||||
<script type="application/json">{{SampleBody("raccolta-in-evidenza")}}</script>
|
||||
</head><body>
|
||||
<script type="application/json" data-content-len="9" data-sjs>{"require":[["ScheduledServerJS","handle",null,[{"__bbox":{"result":{"data":
|
||||
""";
|
||||
var html = head + SampleBody("post-video") + """}}}]]]}</script></body></html>""";
|
||||
var reads = new List<ReadResult>();
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(html))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
reads.Add(Reader.Read(block.RootElement));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(3, reads.Count, "Only the valid application/json blocks, in order.");
|
||||
Assert.AreEqual(ReadShape.Unrelated, reads[0].Shape, "The loader's block is not about contents.");
|
||||
Assert.AreEqual(2, reads[1].Highlights.Count);
|
||||
Assert.AreEqual(true, reads[1].Page?.HasMore);
|
||||
Assert.AreEqual(ReadShape.Recognized, reads[2].Shape);
|
||||
Assert.AreEqual(1, reads[2].Contents.Count);
|
||||
Assert.AreEqual(0, reads[2].Highlights.Count);
|
||||
Assert.AreEqual(false, reads[2].Page?.HasMore, "The post's own pagination, not the collections'.");
|
||||
|
||||
Assert.IsFalse(DataResponses.EmbeddedJsonBlocks("<html><script>var a = 1;</script></html>").Any());
|
||||
Assert.IsTrue(DataResponses.IsPageDocument("text/html", isMainFrameDocument: true));
|
||||
Assert.IsFalse(DataResponses.IsPageDocument("text/html", isMainFrameDocument: false));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ABadBlockOfAPageDocumentIsLeftOutAndTheNextOnesAreStillRead()
|
||||
{
|
||||
// Text that is not valid UTF-16 (a lone surrogate: JsonDocument throws ArgumentException, not JsonException),
|
||||
// a block nested deeper than any body may be, a blank one: none of them stops the reading of the document.
|
||||
const string Open = """<script type="application/json">""";
|
||||
var html = Open + "{\"a\":\"\ud800\"}</script>" + Open + new string('[', 300) + new string(']', 300) + "</script>"
|
||||
+ Open + " </script>" + Open + """{"b":[2]}</script>""";
|
||||
var blocks = new List<string>();
|
||||
foreach (var block in DataResponses.EmbeddedJsonBlocks(html))
|
||||
{
|
||||
using (block)
|
||||
{
|
||||
blocks.Add(block.RootElement.GetRawText());
|
||||
}
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { """{"b":[2]}""" }, blocks);
|
||||
}
|
||||
|
||||
private static void Collect(JsonElement element, HashSet<string> paths, HashSet<string> names)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
names.Add(property.Name);
|
||||
paths.Add(property.Name);
|
||||
foreach (var below in NestedPaths(property.Value))
|
||||
{
|
||||
paths.Add(property.Name + "." + below);
|
||||
}
|
||||
|
||||
Collect(property.Value, paths, names);
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
Collect(item, paths, names);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Dotted paths of object keys directly below <paramref name="element"/> (two levels are enough here).</summary>
|
||||
private static IEnumerable<string> NestedPaths(JsonElement element)
|
||||
{
|
||||
if (element.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
yield return property.Name;
|
||||
if (property.Value.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
foreach (var deeper in property.Value.EnumerateObject())
|
||||
{
|
||||
yield return property.Name + "." + deeper.Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,820 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The recipes of the profile, the history, the sweep and the following list over answers shaped like Instagram's,
|
||||
/// without a browser: the cleaned real samples of <c>tests/campioni/instagram</c> (HAR of 21 October 2026), and
|
||||
/// variants built here from them where Instagram's answer is not in the samples (the profile, the grid, the feed, the
|
||||
/// stories bar, the following list: REPERTI «Not in the sample»). The variants use only keys of the samples and move
|
||||
/// their parts around; they say nothing new about Instagram's format. Unlike the test site, the page receives what it
|
||||
/// shows in several answers, one after the other, and answers about something else in between.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class InstagramRecipeTests
|
||||
{
|
||||
private const string AlbertoId = "1000";
|
||||
|
||||
[TestMethod]
|
||||
public void TheNotFoundMarkerIsOptionalAndTheTabsStillNeedTheirTargets()
|
||||
{
|
||||
foreach (var kind in new[] { RecipeKind.ProfileCheck, RecipeKind.Backfill })
|
||||
{
|
||||
Assert.AreEqual(0, RecipeRunner.Requirements(kind).Targets.Count, kind.ToString());
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.ProfileTabTagged }, RecipeRunner.Requirements(RecipeKind.Tagged).Targets.ToArray());
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.ProfileTabReels }, RecipeRunner.Requirements(RecipeKind.Reels).Targets.ToArray());
|
||||
|
||||
var map = InstagramBed.Map();
|
||||
var (pages, targets) = RecipeRunner.Requirements(RecipeKind.ProfileCheck);
|
||||
Assert.AreEqual(0, map.Missing(pages, targets).Count, "The profile page is enough for the check.");
|
||||
var tagged = RecipeRunner.Requirements(RecipeKind.Tagged);
|
||||
CollectionAssert.AreEqual(new[] { $"bersaglio «{SiteTargets.ProfileTabTagged}» (vuoto)" }, map.Missing(tagged.Pages, tagged.Targets).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheProfileCheckKeepsTheGridAndTheCollectionsThatComeAfterTheProfile()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2002", "marta.prova");
|
||||
var marta = Author("2002", "marta.prova");
|
||||
|
||||
// The profile first; the grid asked for only after the page has settled on it; then the collections and a
|
||||
// post of another account, both saying there is nothing more of themselves.
|
||||
bed.Page.OnOpen["/marta.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(marta), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(Grid(Posts(marta, 0, 12, bed.Clock.Now.AddDays(-1)), "griglia-12", hasNext: true), TimeSpan.FromSeconds(1.5), TimeSpan.FromSeconds(1.9)),
|
||||
new(Highlights("2002", "marta.prova", hasNext: false), TimeSpan.FromSeconds(1.9), TimeSpan.FromSeconds(2.3)),
|
||||
new(Sample("post-video"), TimeSpan.FromSeconds(2.0), TimeSpan.FromSeconds(2.5)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The grid came after the profile and was read.");
|
||||
Assert.AreEqual(2, (await bed.Db.Highlights.ListAsync(account.Id)).Count, "So were the collections, after the grid.");
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor, "The history goes on from the grid's own page.");
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "Neither «more_available: false» of the post nor «has_next_page: false» of the collections ends it.");
|
||||
Assert.IsFalse(bed.Page.Looked.Contains(SiteTargets.ProfileNotFound), "The marker is not in the map: it is not looked for.");
|
||||
Assert.IsFalse((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code is "mappa-incompleta" or "formato-non-riconosciuto"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheMarkerAMissingProfileIsAnEmptyPageAndWithItTheAccountIsUnreachable()
|
||||
{
|
||||
await using (var bed = await InstagramBed.CreateAsync())
|
||||
{
|
||||
var account = await bed.AddAccountAsync("2004", "sparito.prova");
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message);
|
||||
Assert.AreNotEqual(AccountState.Unreachable, (await bed.Db.Accounts.GetAsync(account.Id))!.State, "Nothing says the profile is gone.");
|
||||
Assert.IsFalse(bed.Page.Looked.Contains(SiteTargets.ProfileNotFound));
|
||||
}
|
||||
|
||||
await using (var bed = await InstagramBed.CreateAsync(InstagramBed.Map(SiteTargets.ProfileNotFound)))
|
||||
{
|
||||
var account = await bed.AddAccountAsync("2004", "sparito.prova");
|
||||
bed.Page.Present.Add(SiteTargets.ProfileNotFound);
|
||||
var outcome = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.AccountUnreachable, outcome.Status, outcome.Message);
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual(AccountState.Unreachable, stored!.State);
|
||||
Assert.AreEqual(UnreachableReason.NotFound, stored.UnreachableReason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnAnswerWithoutMorePagesOfSomethingElseDoesNotEndTheHistory()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova");
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-2);
|
||||
bed.Page.OnOpen["/luca.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(Grid(Posts(luca, 0, 12, newest), "griglia-12", hasNext: true), TimeSpan.Zero, TimeSpan.Zero),
|
||||
];
|
||||
|
||||
// The first burst brings only answers about something else, each saying it has no more: a post of another
|
||||
// account and the collections. The next page of the grid comes with the second burst.
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[Sample("post-video"), Highlights("2001", "luca.prova", hasNext: false)],
|
||||
[Grid(Posts(luca, 12, 24, newest), "griglia-24", hasNext: true)],
|
||||
[Grid(Posts(luca, 24, 30, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the grid, not of the post.");
|
||||
Assert.AreEqual(30, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The answers about something else did not count as a page.");
|
||||
Assert.AreEqual(3, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageOfAPostOfTheAccountNeitherEndsTheHistoryNorCountsAsItsNextPage()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova");
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-2);
|
||||
|
||||
// After the grid, the page of one of its posts: the REST answer of the samples, «more_available: false».
|
||||
bed.Page.OnOpen["/luca.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(Grid(Posts(luca, 0, 12, newest), "griglia-12", hasNext: true), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(PostPage(Posts(luca, 3, 4, newest)[0]), TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(400)),
|
||||
];
|
||||
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor, "The history goes on from the grid's own page.");
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "«more_available: false» of the page of one of its posts does not complete it.");
|
||||
|
||||
// The first burst brings only the page of another post already read; the next page of the grid comes with the second.
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(luca, 5, 6, newest)[0])],
|
||||
[Grid(Posts(luca, 12, 24, newest), "griglia-24", hasNext: true)],
|
||||
[Grid(Posts(luca, 24, 30, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the grid, not of the post.");
|
||||
Assert.AreEqual(30, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The page of a post already read did not count as a page.");
|
||||
Assert.AreEqual(3, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnTheTaggedTabThePageOfAPostAlreadyReadDoesNotEndTheWalk()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync(InstagramBed.Map(SiteTargets.ProfileTabTagged));
|
||||
bed.Page.Present.Add(SiteTargets.ProfileTabTagged);
|
||||
var account = await bed.AddAccountAsync("2001", "luca.prova", change: a => a with { ContentTypes = a.ContentTypes | ContentTypes.Tagged });
|
||||
var luca = Author("2001", "luca.prova");
|
||||
var other = Author("2005", "altro.prova");
|
||||
var newest = bed.Clock.Now.AddDays(-3);
|
||||
|
||||
// On the tab every post of another account is an item of the walk, the page of one of them too.
|
||||
bed.Page.OnOpen["/luca.prova/"] = [new(ProfileAnswer(luca), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
bed.Page.OnClick[SiteTargets.ProfileTabTagged] =
|
||||
[
|
||||
new(Grid(Posts(other, 0, 12, newest), "taggati-12", hasNext: true), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(PostPage(Posts(other, 4, 5, newest)[0]), TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(600)),
|
||||
];
|
||||
bed.Page.OnScroll["/luca.prova/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(other, 7, 8, newest)[0])],
|
||||
[Grid(Posts(other, 12, 20, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.Tagged, account.Id, maxPages: 5);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, "The end of the tab, not of the post.");
|
||||
Assert.AreEqual(20, (await bed.PostIdsAsync(account.Id, EntryKind.Tagged)).Count);
|
||||
Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{account.Id.ToString(CultureInfo.InvariantCulture)}.completo"));
|
||||
Assert.AreEqual(2, bed.Governor.Granted(ActionKind.BackfillPage), "The tab and its second page; the page of a post is not one.");
|
||||
Assert.AreEqual(2, bed.Page.Scrolls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThePageOfAPostAlreadyInTheFeedDoesNotEndTheSweep()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
var nadia = Author("2003", "nadia.prova");
|
||||
var newest = bed.Clock.Now.AddHours(-1);
|
||||
bed.Page.OnOpen["/"] = [new(Grid(Posts(nadia, 0, 6, newest), "feed-6", hasNext: true), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
bed.Page.OnScroll["/"] = new Queue<IReadOnlyList<JsonNode>>(
|
||||
[
|
||||
[PostPage(Posts(nadia, 2, 3, newest)[0])],
|
||||
[Grid(Posts(nadia, 6, 12, newest), null, hasNext: false)],
|
||||
]);
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "«more_available: false» of the page of a post read already is not the end of the feed.");
|
||||
Assert.AreEqual(2, bed.Page.Scrolls, "The feed's own end stops the sweep.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEmptyCollectionsOfAnAccountWithoutAnyAreNotAnEmptyGrid()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2002", "marta.prova");
|
||||
var marta = Author("2002", "marta.prova");
|
||||
|
||||
// No collections: their answer, an empty connection saying there are no more, comes before the grid, which
|
||||
// the page asks for only after it has settled on the profile.
|
||||
bed.Page.OnOpen["/marta.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(marta), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(NoHighlights(), TimeSpan.FromMilliseconds(400), TimeSpan.FromMilliseconds(800)),
|
||||
new(Grid(Posts(marta, 0, 12, bed.Clock.Now.AddDays(-1)), "griglia-12", hasNext: true), TimeSpan.FromSeconds(1.6), TimeSpan.FromSeconds(2.0)),
|
||||
];
|
||||
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The grid was still waited for.");
|
||||
var stored = await bed.Db.Accounts.GetAsync(account.Id);
|
||||
Assert.AreEqual("griglia-12", stored!.BackfillCursor);
|
||||
Assert.IsNull(stored.BackfillCompletedAt, "«has_next_page: false» of the empty collections does not complete the history.");
|
||||
|
||||
// When the grid does not come, the empty collections do not stand for it either.
|
||||
var other = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
bed.Page.OnOpen["/nadia.prova/"] =
|
||||
[
|
||||
new(ProfileAnswer(Author("2003", "nadia.prova")), TimeSpan.Zero, TimeSpan.FromMilliseconds(300)),
|
||||
new(NoHighlights(), TimeSpan.FromMilliseconds(400), TimeSpan.FromMilliseconds(800)),
|
||||
];
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, other.Id)).Status);
|
||||
stored = await bed.Db.Accounts.GetAsync(other.Id);
|
||||
Assert.IsNull(stored!.BackfillCompletedAt, "Nothing said the grid is empty.");
|
||||
Assert.IsNull(stored.BackfillCursor);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestedProfilesAreNeverSavedAsFollowed()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
await bed.AddMineAsync();
|
||||
|
||||
// A profile Febe keeps that Alberto does not follow, among the suggestions of the sample.
|
||||
var suggestions = Sample("profili-suggeriti");
|
||||
var suggested = suggestions["data"]!["xdt_api__v1__discover__chaining"]!["users"]!.AsArray().Select(u => u!["username"]!.GetValue<string>()).ToList();
|
||||
var kept = await bed.AddAccountAsync(suggestions["data"]!["xdt_api__v1__discover__chaining"]!["users"]![0]!["pk"]!.GetValue<string>(), suggested[0], followed: false);
|
||||
|
||||
var followed = Enumerable.Range(0, 4).Select(i => Author((3000 + i).ToString(CultureInfo.InvariantCulture), $"seguito{i}.prova")).ToList();
|
||||
bed.Page.OnOpen["/alberto.prova/seguiti-di-prova/"] =
|
||||
[
|
||||
new(suggestions, TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(ProfileAnswer(Author(AlbertoId, "alberto.prova", following: null)), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(FollowingList(followed), TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(700)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingList);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.IsTrue(outcome.BackfillFinished, outcome.Message);
|
||||
var list = (await bed.Db.Following.ListAsync()).Select(f => f.Username).ToList();
|
||||
CollectionAssert.AreEquivalent(new[] { "seguito0.prova", "seguito1.prova", "seguito2.prova", "seguito3.prova" }, list, "Neither the suggestions nor Alberto himself.");
|
||||
Assert.IsFalse((await bed.Db.Accounts.GetAsync(kept.Id))!.IsFollowed, "A suggested profile is not followed.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestionsAndAlbertoAloneAreNotTheFollowingList()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
await bed.AddMineAsync();
|
||||
bed.Page.OnOpen["/alberto.prova/seguiti-di-prova/"] =
|
||||
[
|
||||
new(Sample("profili-suggeriti"), TimeSpan.Zero, TimeSpan.Zero),
|
||||
new(ProfileAnswer(Author(AlbertoId, "alberto.prova", following: null)), TimeSpan.Zero, TimeSpan.Zero),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingList);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message);
|
||||
Assert.AreEqual(0, await bed.Db.Following.CountAsync());
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(RecipeRunner.FollowingKeys.Cursor));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheConnectedAccountIsRecognizedFromItsIdentifierAndItsEntryInTheStoriesBar()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
var account = await bed.AddAccountAsync("2003", "nadia.prova");
|
||||
var nadia = Author("2003", "nadia.prova", latestStoryAt: bed.Clock.Now.AddHours(-2));
|
||||
|
||||
// The feed says who the connected account is by its identifier only (xdt_viewer.user, as in the samples);
|
||||
// its name comes later, with its own entry in the stories bar.
|
||||
bed.Page.OnOpen["/"] =
|
||||
[
|
||||
new(Grid(Posts(nadia, 0, 2, bed.Clock.Now.AddHours(-5)), "feed-2", hasNext: false, viewerId: AlbertoId), TimeSpan.Zero, TimeSpan.FromMilliseconds(200)),
|
||||
new(StoriesBar(Author(AlbertoId, "alberto.prova", following: null, latestStoryAt: bed.Clock.Now.AddHours(-1)), nadia), TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(900)),
|
||||
];
|
||||
|
||||
var outcome = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
var mine = await bed.Db.Accounts.GetMineAsync();
|
||||
Assert.IsNotNull(mine, "«Tu» from the identifier of one answer and the profile of another.");
|
||||
Assert.AreEqual("alberto.prova", mine.Username);
|
||||
Assert.AreEqual(AlbertoId, mine.InstagramId);
|
||||
Assert.AreEqual(2, (await bed.PostIdsAsync(account.Id)).Count);
|
||||
Assert.IsTrue(outcome.AccountsWithStories.Contains(account.Id), "The stories bar came after the feed and was read.");
|
||||
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "account-collegato"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SuggestedProfilesAloneAreNotTheHome()
|
||||
{
|
||||
await using var bed = await InstagramBed.CreateAsync();
|
||||
bed.Page.OnOpen["/"] = [new(Sample("profili-suggeriti"), TimeSpan.Zero, TimeSpan.Zero)];
|
||||
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.FollowingSweep)).Status);
|
||||
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.FollowingSweep)).Status);
|
||||
Assert.AreEqual(0, bed.Breaker.Signals.Count);
|
||||
var third = await bed.RunAsync(RecipeKind.FollowingSweep);
|
||||
Assert.AreEqual(RecipeStatus.StoppedBySignal, third.Status, "Three homes with nothing but suggestions are three empty pages: " + third.Message);
|
||||
Assert.AreEqual("empty-pages", bed.Breaker.Signals.Single().Code);
|
||||
Assert.IsNull(await bed.Db.Accounts.GetMineAsync());
|
||||
}
|
||||
|
||||
// ----- Answers: the cleaned samples, and variants built from them -----
|
||||
|
||||
private static string SampleFile(string name) =>
|
||||
Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), $"*-{name}.json").Single();
|
||||
|
||||
/// <summary>The body of a cleaned sample, as the page received it.</summary>
|
||||
private static JsonObject Sample(string name) =>
|
||||
JsonNode.Parse(File.ReadAllText(SampleFile(name)))!["corpo"]!.DeepClone().AsObject();
|
||||
|
||||
/// <summary>
|
||||
/// A profile as the post of the samples describes its author (pk, username, friendship_status, latest_reel_media,
|
||||
/// the pictures), with another identity. <paramref name="following"/> null: without friendship_status.
|
||||
/// </summary>
|
||||
private static JsonObject Author(string pk, string username, bool? following = true, DateTimeOffset? latestStoryAt = null)
|
||||
{
|
||||
var user = Sample("post-video")["items"]![0]!["user"]!.DeepClone().AsObject();
|
||||
user["pk"] = pk;
|
||||
user["pk_id"] = pk;
|
||||
user["id"] = pk;
|
||||
user["strong_id__"] = pk;
|
||||
user["username"] = username;
|
||||
user["full_name"] = username;
|
||||
if (following is { } value)
|
||||
{
|
||||
user["friendship_status"]!["following"] = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Remove("friendship_status");
|
||||
}
|
||||
|
||||
if (latestStoryAt is { } latest)
|
||||
{
|
||||
user["latest_reel_media"] = latest.ToUnixTimeSeconds();
|
||||
}
|
||||
else
|
||||
{
|
||||
user.Remove("latest_reel_media");
|
||||
}
|
||||
|
||||
Retag(user, "a" + pk);
|
||||
return user;
|
||||
}
|
||||
|
||||
/// <summary>Posts of <paramref name="author"/>, one hour apart going back from <paramref name="newest"/>: the post of the samples, renumbered.</summary>
|
||||
private static List<JsonObject> Posts(JsonObject author, int from, int to, DateTimeOffset newest)
|
||||
{
|
||||
var template = Sample("post-video")["items"]![0]!;
|
||||
var authorPk = author["pk"]!.GetValue<string>();
|
||||
var posts = new List<JsonObject>();
|
||||
for (var i = from; i < to; i++)
|
||||
{
|
||||
var pk = authorPk + "9" + i.ToString("D4", CultureInfo.InvariantCulture);
|
||||
var post = template.DeepClone().AsObject();
|
||||
post["pk"] = pk;
|
||||
post["id"] = $"{pk}_{authorPk}";
|
||||
post["code"] = ("C" + pk).PadRight(11, 'x')[..11];
|
||||
post["taken_at"] = newest.AddHours(-i).ToUnixTimeSeconds();
|
||||
Retag(post, "p" + pk);
|
||||
post["user"] = author.DeepClone();
|
||||
post["owner"] = author.DeepClone();
|
||||
posts.Add(post);
|
||||
}
|
||||
|
||||
return posts;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A page of posts: Instagram's grid and feed are not in the samples, so the posts go into the GraphQL connection
|
||||
/// the samples show (data.…connection.edges[].node, page_info), with xdt_viewer.user when given.
|
||||
/// </summary>
|
||||
private static JsonObject Grid(IEnumerable<JsonObject> posts, string? cursor, bool hasNext, string? viewerId = null)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var data = body["data"]!.AsObject();
|
||||
var connection = data["xdt_api__v1__feed__reels_media__connection"]!.AsObject();
|
||||
connection["edges"] = new JsonArray([.. posts.Select(p => (JsonNode)new JsonObject { ["node"] = p, ["cursor"] = null })]);
|
||||
connection["page_info"]!["end_cursor"] = cursor;
|
||||
connection["page_info"]!["has_next_page"] = hasNext;
|
||||
if (viewerId is null)
|
||||
{
|
||||
data.Remove("xdt_viewer");
|
||||
}
|
||||
else
|
||||
{
|
||||
var user = data["xdt_viewer"]!["user"]!;
|
||||
user["pk"] = viewerId;
|
||||
user["id"] = viewerId;
|
||||
user["user_id"] = viewerId;
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The collections of the samples, as if of another account, saying whether there are more of them.</summary>
|
||||
private static JsonObject Highlights(string pk, string username, bool hasNext)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var connection = body["data"]!["xdt_api__v1__feed__reels_media__connection"]!;
|
||||
foreach (var node in connection["edges"]!.AsArray().Select(e => e!["node"]!))
|
||||
{
|
||||
var owner = node["user"]!;
|
||||
owner["pk"] = pk;
|
||||
owner["id"] = pk;
|
||||
owner["user_id"] = pk;
|
||||
owner["username"] = username;
|
||||
foreach (var item in node["items"]!.AsArray())
|
||||
{
|
||||
item!["user"]!["pk"] = pk;
|
||||
item["user"]!["id"] = pk;
|
||||
item["user"]!["instagram_pk"] = pk;
|
||||
}
|
||||
}
|
||||
|
||||
connection["page_info"]!["has_next_page"] = hasNext;
|
||||
body["data"]!.AsObject().Remove("xdt_viewer");
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The collections of an account that has none: the connection of the samples without edges, saying there are no more.</summary>
|
||||
private static JsonObject NoHighlights()
|
||||
{
|
||||
var body = Highlights("0", "nessuno.prova", hasNext: false);
|
||||
body["data"]!["xdt_api__v1__feed__reels_media__connection"]!["edges"] = new JsonArray();
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The page of one post: the REST answer of the samples («more_available: false») with <paramref name="post"/> as its item.</summary>
|
||||
private static JsonObject PostPage(JsonObject post)
|
||||
{
|
||||
var body = Sample("post-video");
|
||||
body["items"] = new JsonArray(post);
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>A profile on its own (data.user): Instagram's profile answer is not in the samples.</summary>
|
||||
private static JsonObject ProfileAnswer(JsonObject profile) => new() { ["data"] = new JsonObject { ["user"] = profile.DeepClone() } };
|
||||
|
||||
/// <summary>
|
||||
/// The stories bar of the home, not in the samples: the reels of the samples (XDTReelDict) without what makes them a
|
||||
/// collection (title, items), one per account, its author in «user».
|
||||
/// </summary>
|
||||
private static JsonObject StoriesBar(params JsonObject[] authors)
|
||||
{
|
||||
var body = Sample("raccolta-in-evidenza");
|
||||
var data = body["data"]!.AsObject();
|
||||
var connection = data["xdt_api__v1__feed__reels_media__connection"]!.AsObject();
|
||||
var template = connection["edges"]![0]!["node"]!;
|
||||
connection["edges"] = new JsonArray([.. authors.Select(author =>
|
||||
{
|
||||
var reel = template.DeepClone().AsObject();
|
||||
reel.Remove("title");
|
||||
reel.Remove("items");
|
||||
reel.Remove("cover_media");
|
||||
reel["id"] = author["pk"]!.GetValue<string>();
|
||||
reel["user"] = author.DeepClone();
|
||||
reel["latest_reel_media"] = author["latest_reel_media"]?.DeepClone();
|
||||
return (JsonNode)new JsonObject { ["node"] = reel, ["cursor"] = null };
|
||||
})]);
|
||||
connection.Remove("page_info");
|
||||
data.Remove("xdt_viewer");
|
||||
return body;
|
||||
}
|
||||
|
||||
/// <summary>The following list, not in the samples: its profiles in «users», as the suggestions of the samples have them, and «more_available».</summary>
|
||||
private static JsonObject FollowingList(IEnumerable<JsonObject> profiles) => new()
|
||||
{
|
||||
["users"] = new JsonArray([.. profiles.Select(p => (JsonNode)p.DeepClone())]),
|
||||
["more_available"] = false,
|
||||
};
|
||||
|
||||
/// <summary>Gives the file addresses of a copied part their own name, so that copies are different files.</summary>
|
||||
private static void Retag(JsonNode node, string tag)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case JsonObject obj:
|
||||
foreach (var (key, value) in obj.ToList())
|
||||
{
|
||||
if (value is JsonValue v && v.TryGetValue<string>(out var text) && text.StartsWith("https://cdn.esempio/", StringComparison.Ordinal))
|
||||
{
|
||||
obj[key] = "https://cdn.esempio/" + tag + "-" + text["https://cdn.esempio/".Length..];
|
||||
}
|
||||
else if (value is not null)
|
||||
{
|
||||
Retag(value, tag);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case JsonArray array:
|
||||
foreach (var item in array.Where(i => i is not null))
|
||||
{
|
||||
Retag(item!, tag);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ----- The bed: a page driver that hands the capture Instagram-shaped answers over time -----
|
||||
|
||||
/// <summary>An answer of a page: its response seen at <paramref name="Announced"/>, its body read at <paramref name="Delivered"/>.</summary>
|
||||
private sealed record Answer(JsonNode Body, TimeSpan Announced, TimeSpan Delivered);
|
||||
|
||||
/// <summary>A virtual clock that also runs what is due when time passes: bodies arrive while the recipe waits.</summary>
|
||||
private sealed class StepClock(DateTimeOffset start) : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<(DateTimeOffset At, long Order, Action Action)> _due = [];
|
||||
private DateTimeOffset _now = start;
|
||||
private long _order;
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
||||
|
||||
public void After(TimeSpan delay, Action action)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_due.Add((_now + delay, _order++, action));
|
||||
}
|
||||
}
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
List<Action> due;
|
||||
lock (_gate)
|
||||
{
|
||||
if (time > TimeSpan.Zero)
|
||||
{
|
||||
_now += time;
|
||||
}
|
||||
|
||||
due = [.. _due.Where(d => d.At <= _now).OrderBy(d => d.At).ThenBy(d => d.Order).Select(d => d.Action)];
|
||||
_due.RemoveAll(d => d.At <= _now);
|
||||
}
|
||||
|
||||
foreach (var action in due)
|
||||
{
|
||||
action();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page: opening a path hands the capture its answers (each seen as a response first, its body read later, as
|
||||
/// the browser does), and so does a click on a target; a burst hands it the next answers queued for the path.
|
||||
/// Targets are found only when present.
|
||||
/// </summary>
|
||||
private sealed class InstagramPage(CaptureCollector capture, StepClock clock) : IPageDriver
|
||||
{
|
||||
private int _requests;
|
||||
|
||||
public Dictionary<string, List<Answer>> OnOpen { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, List<Answer>> OnClick { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, Queue<IReadOnlyList<JsonNode>>> OnScroll { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public HashSet<string> Present { get; } = [];
|
||||
|
||||
public List<string> Looked { get; } = [];
|
||||
|
||||
public int Scrolls { get; private set; }
|
||||
|
||||
public string CurrentPath { get; private set; } = "about:blank";
|
||||
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public void BeginSession(double mood)
|
||||
{
|
||||
}
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
CurrentPath = path;
|
||||
foreach (var answer in OnOpen.GetValueOrDefault(path) ?? [])
|
||||
{
|
||||
Send(answer.Body, answer.Announced, answer.Delivered);
|
||||
}
|
||||
|
||||
return Task.FromResult(new PageLoad(true, path, null));
|
||||
}
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => Task.FromResult(CurrentPath);
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
Looked.Add(target);
|
||||
return Task.FromResult(Present.Contains(target)
|
||||
? new TargetCheck(target, TargetCheckStatus.Found, 1, "Trovato.")
|
||||
: new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
|
||||
}
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
if (!Present.Contains(target))
|
||||
{
|
||||
return Task.FromResult(new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
|
||||
}
|
||||
|
||||
foreach (var answer in OnClick.GetValueOrDefault(target) ?? [])
|
||||
{
|
||||
Send(answer.Body, answer.Announced, answer.Delivered);
|
||||
}
|
||||
|
||||
return Task.FromResult(new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato."));
|
||||
}
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct)
|
||||
{
|
||||
Scrolls++;
|
||||
if (OnScroll.TryGetValue(CurrentPath, out var queue) && queue.Count > 0)
|
||||
{
|
||||
foreach (var body in queue.Dequeue())
|
||||
{
|
||||
Send(body, TimeSpan.Zero, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(true);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
CurrentPath = "about:blank";
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void Send(JsonNode body, TimeSpan announced, TimeSpan delivered)
|
||||
{
|
||||
var id = "r" + Interlocked.Increment(ref _requests).ToString(CultureInfo.InvariantCulture);
|
||||
var descriptor = new ResponseDescriptor(id, HostKind.Site, "https://sito.esempio/graphql/query", "sito.esempio", "/graphql/query", 200, "text/javascript", "XHR", false, clock.Now);
|
||||
var text = body.ToJsonString();
|
||||
void Announce() => ((IResponseObserver)capture).OnResponse(descriptor);
|
||||
void Deliver()
|
||||
{
|
||||
using var document = JsonDocument.Parse(text);
|
||||
capture.Accept(descriptor, document.RootElement);
|
||||
}
|
||||
|
||||
if (delivered <= TimeSpan.Zero)
|
||||
{
|
||||
Announce();
|
||||
Deliver();
|
||||
return;
|
||||
}
|
||||
|
||||
clock.After(announced, Announce);
|
||||
clock.After(delivered, Deliver);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Database, clock, Governor, signals and runner over <see cref="InstagramPage"/> and the Instagram vocabulary.</summary>
|
||||
private sealed class InstagramBed : IAsyncDisposable
|
||||
{
|
||||
private InstagramBed(TempFolder temp, FebeDatabase db, StepClock clock, InstagramPage page, RecipeRunner runner, TestSession session)
|
||||
{
|
||||
Temp = temp;
|
||||
Db = db;
|
||||
Clock = clock;
|
||||
Page = page;
|
||||
Runner = runner;
|
||||
Session = session;
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public FebeDatabase Db { get; }
|
||||
|
||||
public StepClock Clock { get; }
|
||||
|
||||
public InstagramPage Page { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
public TestSession Session { get; }
|
||||
|
||||
public PermissiveGovernor Governor => (PermissiveGovernor)Runner.Env.Governor;
|
||||
|
||||
public RecordingBreaker Breaker => (RecordingBreaker)Runner.Env.Breaker!;
|
||||
|
||||
/// <summary>
|
||||
/// Pages with Instagram's addresses where the samples show them (home, profile, post: route definitions of the
|
||||
/// HAR); the following list has an address of the test, Instagram's is not in the samples. Targets: only
|
||||
/// <paramref name="configured"/>.
|
||||
/// </summary>
|
||||
public static SiteMap Map(params string[] configured) => new(
|
||||
"instagram",
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[SitePages.Home] = "/",
|
||||
[SitePages.Profile] = "/{username}/",
|
||||
[SitePages.Post] = "/p/{code}/",
|
||||
[SitePages.Following] = "/{username}/seguiti-di-prova/",
|
||||
},
|
||||
configured,
|
||||
SiteTargets.All);
|
||||
|
||||
public static async Task<InstagramBed> CreateAsync(SiteMap? map = null)
|
||||
{
|
||||
var temp = new TempFolder("ricette-instagram");
|
||||
var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new StepClock(new DateTimeOffset(2026, 10, 25, 9, 0, 0, TimeSpan.Zero));
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
|
||||
var page = new InstagramPage(capture, clock);
|
||||
var breaker = new RecordingBreaker();
|
||||
var governor = new PermissiveGovernor();
|
||||
var runner = new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = page,
|
||||
Capture = capture,
|
||||
Governor = governor,
|
||||
Budget = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), breaker, clock),
|
||||
Storage = db,
|
||||
SiteMap = map ?? Map(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(7),
|
||||
Breaker = breaker,
|
||||
});
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
return new InstagramBed(temp, db, clock, page, runner, session);
|
||||
}
|
||||
|
||||
public Task<Account> AddAccountAsync(string instagramId, string username, bool followed = true, Func<Account, Account>? change = null)
|
||||
{
|
||||
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome) with
|
||||
{
|
||||
InstagramId = instagramId,
|
||||
IsFollowed = followed,
|
||||
};
|
||||
return Db.Accounts.AddAsync(change is null ? account : change(account));
|
||||
}
|
||||
|
||||
public Task<Account> AddMineAsync() =>
|
||||
Db.Accounts.AddAsync(Account.Create("alberto.prova", StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome, isMine: true) with { InstagramId = AlbertoId });
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, int? maxPages = null) =>
|
||||
Runner.RunAsync(new RecipeRequest(kind, accountId, MaxPages: maxPages), Session, CancellationToken.None);
|
||||
|
||||
public async Task<IReadOnlyList<string>> PostIdsAsync(long accountId, EntryKind kind = EntryKind.Post) =>
|
||||
[.. (await Db.Entries.ListByAccountAsync(accountId, new EntryListOptions { Kind = kind, Limit = 1000 })).Select(e => e.InstagramId!)];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await Db.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The generic reader (spec §6.4) on the cleaned samples of <c>tests/campioni/prova</c>: captured from the test site,
|
||||
/// cleaned with «febe-sonda ripulisci» and checked with «febe-sonda verifica». Never real Instagram samples: there
|
||||
/// are none yet (rule 10).
|
||||
/// cleaned with «febe-sonda ripulisci» and checked with «febe-sonda verifica». The real Instagram samples have their
|
||||
/// own tests (<see cref="InstagramReaderTests"/>).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ReaderTests
|
||||
@@ -199,31 +199,16 @@ public sealed class ReaderTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheShippedVocabulariesLoadAndInstagramsIsOnlyAHypothesis()
|
||||
public void TheShippedVocabulariesLoad()
|
||||
{
|
||||
var test = ReaderVocabulary.LoadTestSite();
|
||||
Assert.IsTrue(test.IsUsable, test.UnusableReason);
|
||||
Assert.AreEqual(0, test.Relevance.Count, "On the test site every unknown answer is a format change.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.prova.json")), "Editable without recompiling.");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "lettori.instagram.json")));
|
||||
|
||||
var instagram = ReaderVocabulary.LoadInstagram();
|
||||
Assert.AreEqual(VocabularyStatus.Hypothesis, instagram.Status);
|
||||
Assert.IsFalse(instagram.IsUsable);
|
||||
StringAssert.Contains(instagram.UnusableReason, "ipotesi");
|
||||
StringAssert.Contains(instagram.Note, "IPOTESI, DA CONFERMARE CON I CAMPIONI DI M0");
|
||||
|
||||
// Only the hint keys of spec §6.4: nothing invented (rule 10).
|
||||
var keys = new[]
|
||||
{
|
||||
instagram.Content.Id, instagram.Content.Code, instagram.Content.TakenAt, instagram.Content.Caption, instagram.Content.Images,
|
||||
instagram.Content.Videos, instagram.Content.Children, instagram.Content.ChildCount, instagram.Content.Owner, instagram.Content.Pinned,
|
||||
instagram.Content.ExpiresAt, instagram.Content.Duration, instagram.Version.Url, instagram.Version.Width, instagram.Version.Height,
|
||||
instagram.Version.HasAudio, instagram.Profile.Id, instagram.Profile.Username, instagram.Profile.DisplayName, instagram.Profile.IsPrivate,
|
||||
instagram.Profile.IsFollowed, instagram.Profile.PostCount, instagram.Profile.Picture, instagram.Profile.LatestStoryAt,
|
||||
instagram.Highlight.Id, instagram.Highlight.Title, instagram.Highlight.Owner, instagram.Highlight.Items,
|
||||
instagram.Page.HasMore, instagram.Page.Cursor, instagram.Viewer,
|
||||
}.SelectMany(k => k.Paths).Order().ToArray();
|
||||
CollectionAssert.AreEqual(new[] { "carousel_media", "code", "image_versions2.candidates", "pk", "taken_at", "video_versions" }, keys);
|
||||
// Instagram's vocabulary has its own tests on the real cleaned samples (InstagramReaderTests).
|
||||
Assert.IsTrue(ReaderVocabulary.LoadInstagram().IsUsable);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -134,6 +134,39 @@ public sealed class RecipeRuleTests
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{account.Id}.cursore"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AProfileWithCollectionsAndNoPostsHasItsWholeHistoryInTheFirstAnswer()
|
||||
{
|
||||
// The test site sends the collections with the first page of the grid, here empty: the profile in the same
|
||||
// answer says there are no posts.
|
||||
await using var bed = await ScriptedBed.CreateAsync();
|
||||
var timeout = new RecipeOptions().DataTimeout;
|
||||
var vera = bed.Site.Add(new ScriptedAccount("2006", "vera.prova"));
|
||||
vera.HighlightsWithItems.Add(("h1", "Estate", []));
|
||||
var account = await bed.AddAccountAsync(vera, a => a with { State = AccountState.Backfilling });
|
||||
|
||||
var start = bed.Clock.Now;
|
||||
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.IsTrue(bed.Clock.Now - start < timeout, "The empty grid came with the profile: no wait for another one.");
|
||||
Assert.AreEqual(1, (await bed.Db.Highlights.ListAsync(account.Id)).Count);
|
||||
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
|
||||
Assert.IsTrue(check.BackfillFinished, "Its history is complete, with nothing in it.");
|
||||
|
||||
// The history of an account like it, not marked complete yet, ends at the profile without a page of its own.
|
||||
var lia = bed.Site.Add(new ScriptedAccount("2007", "lia.prova"));
|
||||
lia.HighlightsWithItems.Add(("h2", "Inverno", []));
|
||||
var other = await bed.AddAccountAsync(lia, a => a with { State = AccountState.Backfilling });
|
||||
start = bed.Clock.Now;
|
||||
var backfill = await bed.RunAsync(RecipeKind.Backfill, other.Id);
|
||||
Assert.AreEqual(RecipeStatus.Completed, backfill.Status, backfill.Message);
|
||||
Assert.IsTrue(backfill.BackfillFinished, backfill.Message);
|
||||
Assert.IsTrue(bed.Clock.Now - start < timeout);
|
||||
Assert.AreEqual(0, bed.Governor.Granted(ActionKind.BackfillPage), "No page asked for after the profile.");
|
||||
Assert.AreEqual(0, bed.Site.Scrolls);
|
||||
Assert.AreEqual(0, bed.Breaker.Signals.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AResponseUnrelatedToThePageNeitherEndsTheWalkNorStopsTheRecipe()
|
||||
{
|
||||
|
||||
@@ -193,6 +193,24 @@ public sealed class SanitizerTests
|
||||
StringAssert.EndsWith(node["c"]!.GetValue<string>(), ".webp");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ValuesUnderSecretLikeKeysBecomeANeutralFillerOfTheSameShape()
|
||||
{
|
||||
// A fake drawn letter by letter from a long token still looks like a token to a secret scanner (gitleaks).
|
||||
var sanitizer = new SampleSanitizer(key: new byte[32]);
|
||||
// Built at run time, so the source itself holds no token-like literal next to a token-like key (gitleaks).
|
||||
var tracked = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("""{"version":5,"payload":{"is_analytics_tracked":true"""));
|
||||
var ranked = new Guid(0x18f2c1b0, 0xaa77, 0x4c2e, 0x9e, 0x1d, 0x0c, 0x6a, 0x1b, 0x2c, 0x3d, 0x4e).ToString();
|
||||
var node = sanitizer.Sanitize(JsonNode.Parse(new JsonObject { ["organic_tracking_token"] = tracked, ["rank_token"] = ranked, ["nome"] = "Lucia" }.ToJsonString()))!;
|
||||
Assert.AreEqual("xxx7xxxx", node["organic_tracking_token"]!.GetValue<string>()[..8]);
|
||||
Assert.IsTrue(node["organic_tracking_token"]!.GetValue<string>().All(c => c is 'x' or '7'));
|
||||
Assert.AreEqual("77x7x7x7-xx77-7x7x-7x7x-7x7x7x7x7x7x", node["rank_token"]!.GetValue<string>());
|
||||
Assert.AreNotEqual("Lucia", node["nome"]!.GetValue<string>());
|
||||
Assert.IsFalse(node["nome"]!.GetValue<string>().All(c => c == 'x'), "Ordinary values keep their varied fakes.");
|
||||
Assert.IsTrue(SampleSanitizer.LooksLikeSecretKey("client_cache_key"));
|
||||
Assert.IsFalse(SampleSanitizer.LooksLikeSecretKey("username"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProbeReadsOnlyThroughAReadOnlyScript() =>
|
||||
Febe.Browser.Cdp.ReadOnlyScriptGuard.EnsureReadOnly(ProbeRecorder.InteractionScript);
|
||||
@@ -209,5 +227,31 @@ public sealed class SanitizerTests
|
||||
using var document = JsonDocument.Parse(text);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _));
|
||||
}
|
||||
|
||||
// The same for tests/campioni/instagram: no address of Instagram or of its CDN, every address a fake one.
|
||||
foreach (var file in Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json"))
|
||||
{
|
||||
var text = File.ReadAllText(file);
|
||||
foreach (var host in new[] { "instagram.com", "cdninstagram", "fbcdn" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(host, StringComparison.OrdinalIgnoreCase), $"{file}: {host}");
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(text);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("descrittore", out _), file);
|
||||
Assert.IsTrue(document.RootElement.TryGetProperty("corpo", out _), file);
|
||||
foreach (var address in Strings(document.RootElement).Where(v => v.StartsWith("http", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
Assert.IsTrue(System.Text.RegularExpressions.Regex.IsMatch(address, @"^https://(sito|cdn|altro)\.esempio/"), $"{file}: indirizzo non ripulito");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> Strings(JsonElement element) => element.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => [element.GetString()!],
|
||||
JsonValueKind.Object => element.EnumerateObject().SelectMany(p => Strings(p.Value)),
|
||||
JsonValueKind.Array => element.EnumerateArray().SelectMany(Strings),
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The story and highlight viewers on the scripted site, with and without the item shown in the address. Instagram's
|
||||
/// highlight viewer stays on «/stories/highlights/{id}/» from one item to the next (HAR of 21/10/2026): the recipe
|
||||
/// counts the items against the list the page received. The test site writes the item in the address
|
||||
/// («/storie/{username}/{id}/»): the recipe keeps reading it from there.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ViewerAddressTests
|
||||
{
|
||||
private const string SummerId = "17900000000000001";
|
||||
private const string TravelId = "17900000000000002";
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(SummerId)]
|
||||
[DataRow("highlight:" + SummerId)]
|
||||
public async Task AHighlightViewerWithoutTheItemInTheAddressSavesTheItemsShownAndClosesAfterTheLast(string requested)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, requested);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(4, outcome.NewEntries);
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, bed.Viewer.Seen, "Closed after the last item: never on to the next collection.");
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "Every item shown, in order.");
|
||||
Assert.AreEqual(0, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Highlight })).Count(e => e.InstagramId!.StartsWith('v')), "The other collection received with it is not saved.");
|
||||
Assert.AreEqual(3, bed.Viewer.NextClicks);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual(4, bed.Bed.Governor.Granted(ActionKind.StoryView), "One permit per item shown.");
|
||||
bed.AssertNoItemCameOnScreenBeforeItsPermit();
|
||||
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None), "Back on the profile.");
|
||||
Assert.AreEqual("/evidenza/" + SummerId + "/", bed.Viewer.OpenedAt, "The collection is clicked by the identifier of its address.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheItemInTheAddressAVideoIsLeftBeforeItEndsAlsoWhenTheWatchWouldLastLonger()
|
||||
{
|
||||
// Mood × pace 1.2 and a draw near the top: the watch of a ten-second video would last 11.3 s, past its end but
|
||||
// short of the old three-second margin. Clicked then, «next» would have skipped «p1».
|
||||
var random = new FixedRandom(0.9);
|
||||
var watch = StoryTimings.Watch(random, TimeSpan.FromSeconds(10), 1.2);
|
||||
Assert.IsTrue(watch > TimeSpan.FromSeconds(10) && watch < TimeSpan.FromSeconds(13), $"Watch of {watch}.");
|
||||
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, waitMultiplier: 1.2, random: random);
|
||||
var (_, account) = await bed.AddCollectionsAsync([new("v0", Video: TimeSpan.FromSeconds(10)), new("p1"), new("p2")]);
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "v0", "p1", "p2" }, bed.Viewer.Seen, "Never on to the next collection.");
|
||||
CollectionAssert.AreEqual(new[] { "v0", "p1", "p2" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "Every item shown, in order.");
|
||||
Assert.AreEqual(2, bed.Viewer.NextClicks, "«next» on the video before it ended, then on «p1».");
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
bed.AssertNoItemCameOnScreenBeforeItsPermit();
|
||||
Assert.IsFalse((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-altro-account"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task AnUnexpectedErrorInTheViewerClosesItAndKeepsWhatWasShown(bool itemInAddress)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
bed.Viewer.FailAtNextClick = 2;
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Failed, outcome.Status, outcome.Message);
|
||||
StringAssert.Contains(outcome.Message, "Errore imprevisto");
|
||||
StringAssert.Contains(outcome.Message, nameof(InvalidOperationException));
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks, "The viewer is closed: left open it would move on by itself.");
|
||||
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "The two items shown before the error are saved.");
|
||||
Assert.IsTrue((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "ricetta-fallita"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(2, DisplayName = "The video ended: the viewer moved on by itself")]
|
||||
[DataRow(30, DisplayName = "The video stalled: the viewer is still on it")]
|
||||
public async Task WithoutTheItemInTheAddressAVideoThatMayHaveEndedIsNeverClickedPastNorCountedAsOver(int onScreenSeconds)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, spacing: TimeSpan.FromSeconds(6));
|
||||
var nadia = bed.Bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
|
||||
var account = await bed.Bed.AddAccountAsync(nadia);
|
||||
nadia.HighlightsWithItems.Add(("highlight:" + SummerId, "Estate", []));
|
||||
var video = new ViewerItem("v0", TimeSpan.FromSeconds(onScreenSeconds), Video: TimeSpan.FromSeconds(2));
|
||||
bed.Viewer.Add(ViewerAnswers.Highlight(nadia, SummerId, "Estate", [video, new ViewerItem("p1"), new ViewerItem("p2")]));
|
||||
|
||||
// The Governor makes the permit for «p1» wait 6 s: the two-second video may be over by then, with the viewer on
|
||||
// «p1» by itself, or it may have stalled. The address does not say which: closed, without clicking «next».
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
var saved = (await bed.ItemsOfAsync(account, SummerId)).ToArray();
|
||||
CollectionAssert.AreEqual(new[] { "v0" }, saved, "Only what was surely shown under its permit.");
|
||||
CollectionAssert.IsSubsetOf(saved, bed.Viewer.Seen, "Nothing saved that was not on screen.");
|
||||
Assert.AreEqual(0, bed.Viewer.NextClicks, "No click on a video that may have ended: it would have skipped «p1».");
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual(2, bed.Bed.Governor.Granted(ActionKind.StoryView), "For «v0», and for «p1» before it could come on screen.");
|
||||
Assert.IsTrue((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-chiuso-prima"), "The early close is recorded.");
|
||||
Assert.AreEqual("/profilo/nadia.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheItemInTheAddressOnlyStoriesAreCountedAsStories()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
|
||||
// A post of the account arrives with the stories, ahead of them: counted by position it would take the place of «s0».
|
||||
var post = ScriptedSite.Post(marta, new ScriptedPost("post1", bed.Bed.Clock.Now.AddDays(-1)));
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1")], post));
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
|
||||
Assert.AreEqual(0, (await bed.Bed.PostIdsAsync(account.Id)).Count, "The post received with the viewer is not saved by it.");
|
||||
Assert.AreEqual(1, bed.Viewer.NextClicks);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual("/profilo/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheItemInTheAddressStoriesAreFollowedByTheAddressAsBefore()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
await bed.Bed.AddAccountAsync(bed.Bed.Site.Add(new ScriptedAccount("2001", "luca.prova")));
|
||||
|
||||
// «s1» stays on screen half a second: the viewer moves on to «s2» by itself while the recipe watches.
|
||||
var stories = ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1", TimeSpan.FromMilliseconds(500)), new ViewerItem("s2")]);
|
||||
bed.Viewer.Add(stories with { Next = "luca.prova" });
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(bed.Bed.Site.Accounts["luca.prova"], [new ViewerItem("l0")]));
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual(3, outcome.NewEntries);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, bed.Viewer.Seen, "Closed after the last story, before the next account.");
|
||||
Assert.AreEqual(1, bed.Viewer.NextClicks, "From «s0» to «s1»; «s2» came by itself, and the address said so.");
|
||||
Assert.AreEqual(3, bed.Bed.Governor.Granted(ActionKind.StoryView), "One permit per story shown.");
|
||||
bed.AssertNoItemCameOnScreenBeforeItsPermit(); // «s2» too, that came by itself: its permit was asked on «s1»
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual("/profilo/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheItemInTheAddressAPostArrivingAfterTheStoriesDoesNotHideTheLastOne()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
await bed.Bed.AddAccountAsync(bed.Bed.Site.Add(new ScriptedAccount("2001", "luca.prova")));
|
||||
|
||||
// The grid of the profile comes in an answer of its own, after the viewer opened: a post of the account.
|
||||
var post = ScriptedSite.Post(marta, new ScriptedPost("post1", bed.Bed.Clock.Now.AddDays(-1)));
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]) with
|
||||
{
|
||||
Next = "luca.prova",
|
||||
Then = new JsonObject { ["contenuti"] = new JsonArray(post) },
|
||||
});
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(bed.Bed.Site.Accounts["luca.prova"], [new ViewerItem("l0")]));
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, bed.Viewer.Seen, "Closed after «s2», the last story: never on to the next account.");
|
||||
Assert.AreEqual(2, bed.Viewer.NextClicks);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
Assert.AreEqual(3, bed.Bed.Governor.Granted(ActionKind.StoryView), "No permit for a story after the last one.");
|
||||
Assert.IsFalse((await bed.Bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "visualizzatore-altro-account"));
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1", "s2" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task AViewerThatDoesNotCloseStopsTheRunAsATargetNotFoundAndKeepsWhatWasShown(bool itemInAddress)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
bed.Viewer.IgnoresClose = true; // «viewer-close» is found, and the viewer stays open
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
|
||||
StringAssert.Contains(outcome.Message, SiteTargets.ViewerClose);
|
||||
Assert.AreEqual(2, bed.Viewer.CloseClicks, "One more try on the way out.");
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2", "e3" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "What was shown is saved all the same.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARefusedPermitWithAViewerThatDoesNotCloseStopsAsATargetNotFound()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false, storyGrants: 2);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
bed.Viewer.IgnoresClose = true;
|
||||
|
||||
// Refused on «e1», the viewer is closed at once, but it stays open: the run says so, as a target not found
|
||||
// (the session stops and puts the page at rest), not as a refusal (it would go on with the viewer open).
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
|
||||
StringAssert.Contains(outcome.Message, "Tetto delle storie raggiunto (prova).");
|
||||
StringAssert.Contains(outcome.Message, SiteTargets.ViewerClose);
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks);
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public async Task ACancellationWhileWatchingKeepsWhatWasShownAndThenGoesOn(bool itemInAddress)
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress);
|
||||
var (_, account) = await bed.AddCollectionsAsync();
|
||||
using var cancel = new CancellationTokenSource();
|
||||
bed.Viewer.CancelAtWait = (3, cancel); // while watching «e2», as a pause or a signal that closes the session would
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: SummerId), cancel.Token);
|
||||
Assert.AreEqual(RecipeStatus.Cancelled, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "e0", "e1", "e2" }, (await bed.ItemsOfAsync(account, SummerId)).ToArray(), "The three items shown are saved.");
|
||||
Assert.AreEqual(0, bed.Viewer.CloseClicks, "A cancelled run leaves the page as it is.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACancellationWhileWatchingStoriesKeepsTheStoriesShown()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]));
|
||||
using var cancel = new CancellationTokenSource();
|
||||
bed.Viewer.CancelAtWait = (2, cancel); // while watching «s1»
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id), cancel.Token);
|
||||
Assert.AreEqual(RecipeStatus.Cancelled, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0", "s1" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray());
|
||||
Assert.AreEqual(0, bed.Viewer.CloseClicks);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(true)]
|
||||
[DataRow(false)]
|
||||
public async Task AClickThatOpensAnAddressTheMapDoesNotTakeForTheViewerIsClosedBeforeTheRecipeStops(bool closes)
|
||||
{
|
||||
// The map wants the story in the address; the site opens the viewer without it.
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true, siteWritesItem: false);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1")]));
|
||||
bed.Viewer.IgnoresClose = !closes;
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(closes ? RecipeStatus.Failed : RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s0" }, bed.Viewer.Seen, "No second click on what opened.");
|
||||
Assert.AreEqual(1, bed.Viewer.CloseClicks, "What opened is closed like a viewer.");
|
||||
Assert.AreEqual(closes ? "/profilo/marta.prova/" : "/storie/marta.prova/", await bed.Viewer.CurrentPathAsync(CancellationToken.None));
|
||||
Assert.AreEqual(0, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheItemInTheAddressTheViewerIsFollowedFromTheItemItOpensOn()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: true);
|
||||
var marta = bed.Bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Bed.Clock.Now.AddHours(-1) });
|
||||
var account = await bed.Bed.AddAccountAsync(marta);
|
||||
bed.Viewer.Add(ViewerAnswers.Stories(marta, [new ViewerItem("s0"), new ViewerItem("s1"), new ViewerItem("s2")]));
|
||||
bed.Viewer.StartAt = 1; // a site that opens on the first story not seen yet
|
||||
|
||||
var outcome = await bed.RunAsync(new RecipeRequest(RecipeKind.AccountStories, account.Id));
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
CollectionAssert.AreEqual(new[] { "s1", "s2" }, (await bed.Bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Select(e => e.InstagramId).Order(StringComparer.Ordinal).ToArray(), "«s0» was received, never shown.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ProfilesSuggestedBesideTheProfileAreNotItsPage()
|
||||
{
|
||||
await using var bed = await ViewerBed.CreateAsync(itemInAddress: false);
|
||||
var account = await bed.Bed.AddAccountAsync(new ScriptedAccount("2003", "nadia.prova")); // its profile never arrives
|
||||
bed.Viewer.AlongsideEveryPage = new JsonObject
|
||||
{
|
||||
["suggeriti"] = new JsonArray(ScriptedSite.Profile(new ScriptedAccount("4001", "altro.prova")), ScriptedSite.Profile(new ScriptedAccount("4002", "ancora.prova"))),
|
||||
};
|
||||
|
||||
var outcome = await bed.RunHighlightAsync(account, SummerId);
|
||||
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
|
||||
Assert.AreEqual("La pagina è arrivata vuota: nessun dato da leggere.", outcome.Message, "An empty page, not «the collection is not on the profile».");
|
||||
Assert.AreEqual(0, bed.Bed.Governor.Granted(ActionKind.StoryView));
|
||||
Assert.IsNull(bed.Viewer.OpenedAt);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the viewer of the scripted site receives, in the format of the test site (<c>lettori.prova.json</c>).</summary>
|
||||
internal static class ViewerAnswers
|
||||
{
|
||||
/// <summary>A collection of <paramref name="owner"/> as the viewer receives it: «highlight:» before the identifier, as Instagram writes it.</summary>
|
||||
public static Viewable Highlight(ScriptedAccount owner, string id, string title, IReadOnlyList<ViewerItem> items, params Viewable[] alsoReceived)
|
||||
{
|
||||
var node = HighlightNode(owner, id, title, items);
|
||||
var all = new JsonArray(node);
|
||||
foreach (var other in alsoReceived)
|
||||
{
|
||||
all.Add(HighlightNode(owner, other.Key, other.Title, other.Items));
|
||||
}
|
||||
|
||||
return new Viewable("evidenza", id, title, items, new JsonObject { ["raccolte"] = all });
|
||||
}
|
||||
|
||||
private static JsonObject HighlightNode(ScriptedAccount owner, string id, string title, IReadOnlyList<ViewerItem> items) => new()
|
||||
{
|
||||
["numero"] = "highlight:" + id,
|
||||
["titolo"] = title,
|
||||
["autore"] = ScriptedSite.Lite(owner),
|
||||
["contenuti"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: false))]),
|
||||
};
|
||||
|
||||
/// <summary>The stories of <paramref name="owner"/> as the viewer receives them, after <paramref name="before"/> when given.</summary>
|
||||
public static Viewable Stories(ScriptedAccount owner, IReadOnlyList<ViewerItem> items, JsonObject? before = null)
|
||||
{
|
||||
var body = new JsonObject();
|
||||
if (before is not null)
|
||||
{
|
||||
body["contenuti"] = new JsonArray(before);
|
||||
}
|
||||
|
||||
body["storie"] = new JsonArray([.. items.Select(i => (JsonNode)Item(owner, i, expires: true))]);
|
||||
body["autore"] = ScriptedSite.Lite(owner);
|
||||
return new Viewable("storie", owner.Username, owner.Username, items, body);
|
||||
}
|
||||
|
||||
private static JsonObject Item(ScriptedAccount owner, ViewerItem item, bool expires)
|
||||
{
|
||||
var takenAt = new DateTimeOffset(2026, 10, 13, 6, 0, 0, TimeSpan.Zero);
|
||||
var node = ScriptedSite.Post(owner, new ScriptedPost(item.Id, takenAt)
|
||||
{
|
||||
ExpiresAt = expires ? takenAt.AddHours(24) : null,
|
||||
Url = $"https://cdn.prova/m/{item.Id}.jpg",
|
||||
});
|
||||
if (item.Video is { } duration)
|
||||
{
|
||||
node["filmati"] = new JsonArray(new JsonObject { ["indirizzo"] = $"https://cdn.prova/m/{item.Id}.mp4", ["larghezza"] = 720, ["altezza"] = 1280, ["audio"] = true });
|
||||
node["durata"] = duration.TotalSeconds;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An item of a viewer: how long it stays on screen before the viewer moves on by itself, and its video length.</summary>
|
||||
internal sealed record ViewerItem(string Id, TimeSpan? OnScreen = null, TimeSpan? Video = null);
|
||||
|
||||
/// <summary>What a viewer shows for one owner (an account, or a collection), and what the page receives when it opens.</summary>
|
||||
/// <param name="Kind">«storie» or «evidenza», the first segment of its address.</param>
|
||||
/// <param name="Key">The owner in the address: user name, or identifier of the collection.</param>
|
||||
internal sealed record Viewable(string Kind, string Key, string Title, IReadOnlyList<ViewerItem> Items, JsonObject Body)
|
||||
{
|
||||
/// <summary>The owner the viewer moves on to by itself after the last item (another account, another collection).</summary>
|
||||
public string? Next { get; init; }
|
||||
|
||||
/// <summary>An answer of its own the page receives right after <see cref="Body"/> (the grid of the profile, say).</summary>
|
||||
public JsonObject? Then { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The scripted site with a viewer, as a decorator: clicking a story ring or a collection opens its viewer on the first
|
||||
/// item (or on <see cref="StartAt"/>) and hands the capture what the page receives; «viewer-next» moves one item on; an
|
||||
/// item moves on by itself after its time on screen (time is the virtual clock, which the waits move on); after the last
|
||||
/// item the viewer goes on to <see cref="Viewable.Next"/> or closes; «viewer-close» goes back to the page it was opened
|
||||
/// from. The address carries the item shown only with <see cref="AddressWithItem"/>.
|
||||
/// </summary>
|
||||
internal sealed class ViewerSite(ScriptedSite site, CaptureCollector capture, VirtualClock clock) : IPageDriver
|
||||
{
|
||||
private static readonly TimeSpan PhotoOnScreen = TimeSpan.FromMinutes(1); // long: only clicks move a photo on, unless a test says so
|
||||
|
||||
private readonly Dictionary<string, Viewable> _viewables = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Viewable? _open;
|
||||
private int _index;
|
||||
private DateTimeOffset _since;
|
||||
private int _responses;
|
||||
private int _waits;
|
||||
|
||||
public bool AddressWithItem { get; init; }
|
||||
|
||||
/// <summary>The item the viewer opens on (a site that resumes from the first item not seen).</summary>
|
||||
public int StartAt { get; set; }
|
||||
|
||||
/// <summary>The click on «next» (from 1) that throws, as a broken connection with the browser would.</summary>
|
||||
public int? FailAtNextClick { get; set; }
|
||||
|
||||
/// <summary>«viewer-close» is found, but the viewer stays open (a click that lands on the wrong element).</summary>
|
||||
public bool IgnoresClose { get; set; }
|
||||
|
||||
/// <summary>The wait (from 1) during which the source is cancelled: the wait then throws, as <see cref="Task.Delay(TimeSpan, CancellationToken)"/> would.</summary>
|
||||
public (int Wait, CancellationTokenSource Source)? CancelAtWait { get; set; }
|
||||
|
||||
/// <summary>An answer unrelated to the account (suggested profiles) that arrives with every page opened.</summary>
|
||||
public JsonObject? AlongsideEveryPage { get; set; }
|
||||
|
||||
/// <summary>The items that came on screen, in order.</summary>
|
||||
public List<string> Seen { get; } = [];
|
||||
|
||||
public int NextClicks { get; private set; }
|
||||
|
||||
public int CloseClicks { get; private set; }
|
||||
|
||||
/// <summary>The address of the first viewer opened.</summary>
|
||||
public string? OpenedAt { get; private set; }
|
||||
|
||||
public double WaitMultiplier { get; init; } = 1;
|
||||
|
||||
public void Add(Viewable viewable) => _viewables[viewable.Kind + "/" + viewable.Key] = viewable;
|
||||
|
||||
/// <summary>How many items have come on screen until now.</summary>
|
||||
public int OnScreenSoFar()
|
||||
{
|
||||
Tick();
|
||||
return Seen.Count;
|
||||
}
|
||||
|
||||
public void BeginSession(double mood) => site.BeginSession(mood);
|
||||
|
||||
public async Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
_open = null;
|
||||
var load = await site.OpenAsync(path, ct);
|
||||
if (AlongsideEveryPage is { } other)
|
||||
{
|
||||
Deliver(other);
|
||||
}
|
||||
|
||||
return load;
|
||||
}
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct)
|
||||
{
|
||||
Tick();
|
||||
if (_open is not { } open)
|
||||
{
|
||||
return Task.FromResult(site.CurrentPath);
|
||||
}
|
||||
|
||||
var path = "/" + open.Kind + "/" + Uri.EscapeDataString(open.Key) + "/";
|
||||
return Task.FromResult(AddressWithItem ? path + Uri.EscapeDataString(open.Items[_index].Id) + "/" : path);
|
||||
}
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => site.FindAsync(target, parameters, ct);
|
||||
|
||||
public async Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
Tick();
|
||||
var check = await site.FindAsync(target, parameters, ct);
|
||||
if (!check.Found)
|
||||
{
|
||||
return check;
|
||||
}
|
||||
|
||||
var clicked = new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato.");
|
||||
switch (target)
|
||||
{
|
||||
case SiteTargets.ProfileHighlight:
|
||||
return Show("evidenza/" + parameters!["id"]) ? clicked : NotFound(target);
|
||||
case SiteTargets.ProfileStoryRing or SiteTargets.HomeStory:
|
||||
return Show("storie/" + parameters!["username"]) ? clicked : NotFound(target);
|
||||
case SiteTargets.ViewerNext when _open is not null:
|
||||
if (++NextClicks == FailAtNextClick)
|
||||
{
|
||||
throw new InvalidOperationException("Il collegamento con il navigatore si è interrotto (prova).");
|
||||
}
|
||||
|
||||
MoveOn(clock.Now);
|
||||
return clicked;
|
||||
case SiteTargets.ViewerClose when _open is not null:
|
||||
CloseClicks++;
|
||||
if (!IgnoresClose)
|
||||
{
|
||||
_open = null;
|
||||
}
|
||||
|
||||
return clicked;
|
||||
default:
|
||||
return clicked;
|
||||
}
|
||||
}
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct) => site.ScrollBurstAsync(ct);
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => site.WaitAfterLoadAsync(ct);
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct)
|
||||
{
|
||||
clock.Advance(duration);
|
||||
if (CancelAtWait is { } cancel && ++_waits == cancel.Wait)
|
||||
{
|
||||
cancel.Source.Cancel();
|
||||
}
|
||||
|
||||
return ct.IsCancellationRequested ? Task.FromCanceled(ct) : Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(true);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
_open = null;
|
||||
return site.RestAsync(ct);
|
||||
}
|
||||
|
||||
private static TargetCheck NotFound(string target) => new(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato.");
|
||||
|
||||
private static TimeSpan OnScreen(ViewerItem item) => item.OnScreen ?? item.Video ?? PhotoOnScreen;
|
||||
|
||||
private bool Show(string key)
|
||||
{
|
||||
if (!_viewables.TryGetValue(key, out var viewable))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Open(viewable, StartAt, clock.Now);
|
||||
OpenedAt ??= "/" + viewable.Kind + "/" + viewable.Key + "/";
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Open(Viewable viewable, int index, DateTimeOffset since)
|
||||
{
|
||||
_open = viewable;
|
||||
_index = index;
|
||||
_since = since;
|
||||
Seen.Add(viewable.Items[index].Id);
|
||||
Deliver(viewable.Body);
|
||||
if (viewable.Then is { } then)
|
||||
{
|
||||
Deliver(then);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The viewer moves on by itself when an item has been on screen for its time.</summary>
|
||||
private void Tick()
|
||||
{
|
||||
while (_open is { } open && clock.Now - _since >= OnScreen(open.Items[_index]))
|
||||
{
|
||||
MoveOn(_since + OnScreen(open.Items[_index]));
|
||||
}
|
||||
}
|
||||
|
||||
private void MoveOn(DateTimeOffset at)
|
||||
{
|
||||
var open = _open!;
|
||||
if (_index + 1 < open.Items.Count)
|
||||
{
|
||||
_index++;
|
||||
_since = at;
|
||||
Seen.Add(open.Items[_index].Id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (open.Next is { } next && _viewables.TryGetValue(open.Kind + "/" + next, out var following))
|
||||
{
|
||||
Open(following, 0, at);
|
||||
return;
|
||||
}
|
||||
|
||||
_open = null; // after the last item, with nothing after it, the viewer closes by itself
|
||||
}
|
||||
|
||||
private void Deliver(JsonObject body)
|
||||
{
|
||||
var id = "v" + Interlocked.Increment(ref _responses).ToString(CultureInfo.InvariantCulture);
|
||||
using var document = JsonDocument.Parse(body.ToJsonString());
|
||||
capture.Accept(new ResponseDescriptor(id, HostKind.Site, "http://prova.local/dati", "prova.local", "/dati", 200, "application/json", "Fetch", false, clock.Now), document.RootElement);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A scripted bed whose page has a viewer; the Governor can make every story permit wait, like its minimum spacing.</summary>
|
||||
internal sealed class ViewerBed : IAsyncDisposable
|
||||
{
|
||||
private ViewerBed(ScriptedBed bed, ViewerSite viewer, PermitWatcher permits, RecipeRunner runner)
|
||||
{
|
||||
Bed = bed;
|
||||
Viewer = viewer;
|
||||
Permits = permits;
|
||||
Runner = runner;
|
||||
}
|
||||
|
||||
public ScriptedBed Bed { get; }
|
||||
|
||||
public ViewerSite Viewer { get; }
|
||||
|
||||
/// <summary>What was on screen at each story permit granted.</summary>
|
||||
public PermitWatcher Permits { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
/// <param name="itemInAddress">Whether the map's viewer addresses carry the item shown.</param>
|
||||
/// <param name="spacing">Every story permit first waits this long (the Governor's minimum spacing).</param>
|
||||
/// <param name="waitMultiplier">Mood × pace of the page driver.</param>
|
||||
/// <param name="random">The random source of the recipes (a seeded one by default).</param>
|
||||
/// <param name="siteWritesItem">Whether the site writes the item in the address (as the map says, by default).</param>
|
||||
/// <param name="storyGrants">After this many story permits the Governor refuses, while the budget says there is room.</param>
|
||||
public static async Task<ViewerBed> CreateAsync(bool itemInAddress, TimeSpan? spacing = null, double waitMultiplier = 1, IRandomSource? random = null, bool? siteWritesItem = null, int? storyGrants = null)
|
||||
{
|
||||
var pages = ScriptedBed.TestSitePages.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
|
||||
if (!itemInAddress)
|
||||
{
|
||||
pages[SitePages.StoryViewer] = "/storie/{username}/";
|
||||
pages[SitePages.HighlightViewer] = "/evidenza/{highlight}/";
|
||||
}
|
||||
|
||||
var bed = await ScriptedBed.CreateAsync(new SiteMap("prova", pages, SiteTargets.All, SiteTargets.All));
|
||||
var viewer = new ViewerSite(bed.Site, bed.Runner.Env.Capture, bed.Clock) { AddressWithItem = siteWritesItem ?? itemInAddress, WaitMultiplier = waitMultiplier };
|
||||
IGovernor governor = storyGrants is { } grants ? new StoryGrantsGovernor(bed.Governor, grants) : bed.Governor;
|
||||
governor = spacing is { } wait ? new SpacedGovernor(governor, bed.Clock, wait) : governor;
|
||||
var permits = new PermitWatcher(governor, viewer);
|
||||
return new ViewerBed(bed, viewer, permits, new RecipeRunner(bed.Runner.Env with { Driver = viewer, Governor = permits, Random = random ?? bed.Runner.Env.Random }));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «nadia.prova» with two collections on her profile, «Estate» (e0–e3, or <paramref name="summer"/>) and «Viaggi»
|
||||
/// (v0–v1): the viewer of «Estate» receives both, as Instagram's did, and goes on to «Viaggi» by itself after the last item.
|
||||
/// </summary>
|
||||
public async Task<(ScriptedAccount Scripted, Account Account)> AddCollectionsAsync(IReadOnlyList<ViewerItem>? summer = null)
|
||||
{
|
||||
var nadia = Bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
|
||||
var account = await Bed.AddAccountAsync(nadia);
|
||||
nadia.HighlightsWithItems.Add(("highlight:17900000000000001", "Estate", []));
|
||||
nadia.HighlightsWithItems.Add(("highlight:17900000000000002", "Viaggi", []));
|
||||
summer ??= [new("e0"), new("e1"), new("e2"), new("e3")];
|
||||
IReadOnlyList<ViewerItem> travel = [new("v0"), new("v1")];
|
||||
var travelView = ViewerAnswers.Highlight(nadia, "17900000000000002", "Viaggi", travel);
|
||||
Viewer.Add(ViewerAnswers.Highlight(nadia, "17900000000000001", "Estate", summer, travelView) with { Next = "17900000000000002" });
|
||||
Viewer.Add(travelView);
|
||||
return (nadia, account);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every item that came on screen had its story permit before (rule 7, §6.3): the n-th permit was granted before
|
||||
/// the n-th item came, and no item came without one.
|
||||
/// </summary>
|
||||
public void AssertNoItemCameOnScreenBeforeItsPermit()
|
||||
{
|
||||
var atPermit = Permits.OnScreenAtStoryPermit;
|
||||
for (var i = 0; i < atPermit.Count; i++)
|
||||
{
|
||||
Assert.IsTrue(atPermit[i] <= i, $"Story permit {i + 1} granted when {atPermit[i]} items had already come on screen ({string.Join(", ", Viewer.Seen)}).");
|
||||
}
|
||||
|
||||
Assert.IsTrue(Viewer.Seen.Count <= atPermit.Count, $"{Viewer.Seen.Count} items came on screen ({string.Join(", ", Viewer.Seen)}) with {atPermit.Count} story permits.");
|
||||
}
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeRequest request, CancellationToken ct = default) => Runner.RunAsync(request, Bed.Session, ct);
|
||||
|
||||
public Task<RecipeOutcome> RunHighlightAsync(Account account, string highlightId) =>
|
||||
RunAsync(new RecipeRequest(RecipeKind.Highlight, account.Id, HighlightId: highlightId));
|
||||
|
||||
/// <summary>Instagram identifiers of the items of a collection, in their order.</summary>
|
||||
public async Task<IReadOnlyList<string>> ItemsOfAsync(Account account, string highlightId)
|
||||
{
|
||||
var highlight = await Bed.Db.Highlights.FindAsync(account.Id, highlightId) ?? throw new AssertFailedException($"Raccolta {highlightId} non salvata.");
|
||||
var ids = new List<string>();
|
||||
foreach (var item in (await Bed.Db.Highlights.ListItemsAsync(highlight.Id)).OrderBy(i => i.Position))
|
||||
{
|
||||
ids.Add((await Bed.Db.Entries.GetAsync(item.EntryId))!.InstagramId!);
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => Bed.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Grants what the inner Governor grants, but every story permit first waits <paramref name="spacing"/> (its minimum spacing).</summary>
|
||||
internal sealed class SpacedGovernor(IGovernor inner, VirtualClock clock, TimeSpan spacing) : IGovernor
|
||||
{
|
||||
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
|
||||
{
|
||||
if (kind == ActionKind.StoryView)
|
||||
{
|
||||
clock.Advance(spacing);
|
||||
}
|
||||
|
||||
return inner.RequestAsync(kind, accountId, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Grants what the inner Governor grants, but refuses story permits after <paramref name="grants"/> (the budget view still says there is room).</summary>
|
||||
internal sealed class StoryGrantsGovernor(IGovernor inner, int grants) : IGovernor
|
||||
{
|
||||
private int _granted;
|
||||
|
||||
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct) =>
|
||||
kind == ActionKind.StoryView && Interlocked.Increment(ref _granted) > grants
|
||||
? Task.FromResult(Permit.Deny(kind, accountId, DenialReason.HourlyBudgetReached, "Tetto delle storie raggiunto (prova)."))
|
||||
: inner.RequestAsync(kind, accountId, ct);
|
||||
}
|
||||
|
||||
/// <summary>Passes every request on and records, at each story permit granted, how many items had come on screen.</summary>
|
||||
internal sealed class PermitWatcher(IGovernor inner, ViewerSite viewer) : IGovernor
|
||||
{
|
||||
public List<int> OnScreenAtStoryPermit { get; } = [];
|
||||
|
||||
public async Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
|
||||
{
|
||||
var permit = await inner.RequestAsync(kind, accountId, ct);
|
||||
if (kind == ActionKind.StoryView && permit.Granted)
|
||||
{
|
||||
OnScreenAtStoryPermit.Add(viewer.OnScreenSoFar());
|
||||
}
|
||||
|
||||
return permit;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A degenerate random source: always the same value (the draws of §7.2 come out the same every time).</summary>
|
||||
internal sealed class FixedRandom(double value) : IRandomSource
|
||||
{
|
||||
public double NextDouble() => value;
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// The collection configuration in use (reader vocabulary and target map of the site, as loaded): what the log says of
|
||||
/// it, the copies in the Data folder that hide newer embedded files, and the suspensions counted against other files,
|
||||
/// cleared once when it changes.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class CollectionConfigurationTests
|
||||
{
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
[TestMethod]
|
||||
public async Task AChangedCollectionConfigurationLiftsTheSuspensionsOfTheOldFilesOnce()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
|
||||
// What the first Instagram files left in Alberto's database: suspended recipes and failures counted.
|
||||
var since = Morning.AddDays(-3).ToUnixTimeMilliseconds();
|
||||
await bed.Db.Settings.SetAsync(EngineSettingKeys.SuspendedRecipes, $"AccountStories={since};ProfileCheck={since}");
|
||||
await bed.Db.Settings.SetAsync(EngineSettingKeys.RecipeFailures, "AccountStories=3;Backfill=2;ProfileCheck=3");
|
||||
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
|
||||
var changed = false;
|
||||
var host = await bed.StartAsync(runner, async h => changed = await h.ApplyCollectionConfigurationAsync("impronta-1"));
|
||||
Assert.IsTrue(changed, "The first start that knows the configuration counts as a change.");
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.SuspendedRecipes));
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
|
||||
Assert.AreEqual("impronta-1", await bed.Db.Settings.GetAsync(EngineSettingKeys.CollectionConfiguration));
|
||||
|
||||
var line = (await bed.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == EngineEventCodes.CollectionConfigurationChanged);
|
||||
Assert.AreEqual("La configurazione della raccolta è cambiata: le ricette sospese ripartono («Le storie», «Il controllo del profilo»).", line.Message);
|
||||
Assert.AreEqual(EventSeverity.Info, line.Severity);
|
||||
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed), "The recipe runs again.");
|
||||
Assert.IsFalse(await host.ApplyCollectionConfigurationAsync("impronta-1"), "Same files: nothing to do.");
|
||||
|
||||
// A restart with the same files changes nothing; new files with nothing to clear say nothing.
|
||||
await bed.ReopenAsync(8);
|
||||
var again = true;
|
||||
var reopened = await bed.StartAsync(new ScriptedRunner(bed.Governor, bed.Clock), async h => again = await h.ApplyCollectionConfigurationAsync("impronta-1"));
|
||||
Assert.IsFalse(again);
|
||||
Assert.IsTrue(await reopened.ApplyCollectionConfigurationAsync("impronta-2"));
|
||||
Assert.AreEqual("impronta-2", await bed.Db.Settings.GetAsync(EngineSettingKeys.CollectionConfiguration));
|
||||
Assert.AreEqual(1, (await bed.Db.Events.ListAsync(new EventQuery())).Count(e => e.Code == EngineEventCodes.CollectionConfigurationChanged));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task FailuresAloneAreClearedWithTheirOwnLine()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.Db.Settings.SetAsync(EngineSettingKeys.RecipeFailures, "ProfileCheck=2");
|
||||
var host = new EngineHost(bed.Services, new ScriptedRunner(bed.Governor, bed.Clock));
|
||||
await using (host)
|
||||
{
|
||||
Assert.IsTrue(await host.ApplyCollectionConfigurationAsync("impronta"));
|
||||
}
|
||||
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
|
||||
var line = (await bed.Db.Events.ListAsync(new EventQuery())).Single(e => e.Code == EngineEventCodes.CollectionConfigurationChanged);
|
||||
Assert.AreEqual("La configurazione della raccolta è cambiata: i problemi delle ricette contati finora non valgono più.", line.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheEmbeddedFilesAreDescribedWithoutTheirContentAndFingerprinted()
|
||||
{
|
||||
var configuration = CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite());
|
||||
Assert.IsFalse(configuration.VocabularyFile.IsOverride);
|
||||
Assert.IsFalse(configuration.MapFile.IsOverride);
|
||||
Assert.IsEmpty(configuration.Blocked);
|
||||
Assert.IsEmpty(configuration.Warnings);
|
||||
CollectionAssert.AreEqual(
|
||||
new[]
|
||||
{
|
||||
"Vocabolario dei lettori per «prova»: il file incorporato in Febe (lettori.prova.json), confermato.",
|
||||
"Mappa dei bersagli per «prova»: il file incorporato in Febe (bersagli.prova.json), tutte le voci compilate.",
|
||||
"Con questa configurazione tutte le ricette possono girare.",
|
||||
},
|
||||
configuration.Lines.ToArray());
|
||||
Assert.MatchesRegex("^[0-9a-f]{64}$", configuration.Fingerprint);
|
||||
Assert.AreEqual(configuration.Fingerprint, CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite()).Fingerprint);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ACopyInTheDataFolderIsNamedAndOneThatHidesABetterEmbeddedFileIsAWarning()
|
||||
{
|
||||
using var folder = new TempFolder("configurazione");
|
||||
var vocabularyText = SiteMap.ReadEmbeddedText("lettori.prova.json");
|
||||
var mapText = SiteMap.ReadEmbeddedText("bersagli.prova.json");
|
||||
var embedded = CollectionConfiguration.Describe("prova", ReaderVocabulary.LoadTestSite(), SiteMap.LoadTestSite());
|
||||
|
||||
// The same map with other line endings is the same configuration.
|
||||
var mapPath = folder.Combine("bersagli.prova.json");
|
||||
File.WriteAllText(mapPath, mapText.Contains("\r\n", StringComparison.Ordinal) ? mapText.Replace("\r\n", "\n", StringComparison.Ordinal) : mapText.Replace("\n", "\r\n", StringComparison.Ordinal));
|
||||
var sameMap = Loaded(folder, "prova");
|
||||
Assert.IsTrue(sameMap.MapFile.IsOverride);
|
||||
Assert.AreEqual(mapPath, sameMap.MapFile.OverridePath);
|
||||
Assert.AreEqual(embedded.Fingerprint, sameMap.Fingerprint);
|
||||
Assert.IsEmpty(sameMap.Warnings);
|
||||
StringAssert.Contains(sameMap.Lines[1], $"la copia nella cartella dei dati ({mapPath})");
|
||||
|
||||
// A stale vocabulary, still a hypothesis, hides the confirmed embedded one: every recipe would be refused.
|
||||
var vocabularyPath = folder.Combine("lettori.prova.json");
|
||||
File.WriteAllText(vocabularyPath, vocabularyText.Replace("\"confermato\"", "\"ipotesi\"", StringComparison.Ordinal));
|
||||
var stale = Loaded(folder, "prova");
|
||||
Assert.AreNotEqual(embedded.Fingerprint, stale.Fingerprint);
|
||||
CollectionAssert.AreEqual(Enum.GetValues<RecipeKind>(), stale.Blocked.ToArray());
|
||||
Assert.HasCount(1, stale.Warnings);
|
||||
StringAssert.Contains(stale.Warnings[0], vocabularyPath);
|
||||
StringAssert.Contains(stale.Warnings[0], "è ancora un'ipotesi, mentre quello incorporato in Febe è confermato");
|
||||
StringAssert.EndsWith(stale.Lines[0], ", ipotesi.");
|
||||
StringAssert.StartsWith(stale.Lines[2], "Con questa configurazione non possono girare 9 ricette su 9: Giro dei seguiti, ");
|
||||
|
||||
// A map that lacks what the embedded one has leaves recipes still that could run.
|
||||
File.Delete(vocabularyPath);
|
||||
File.WriteAllText(mapPath, """{ "site": "prova", "pages": { "home": "/" } }""");
|
||||
var poor = Loaded(folder, "prova");
|
||||
CollectionAssert.Contains(poor.Blocked.ToArray(), RecipeKind.ProfileCheck);
|
||||
CollectionAssert.DoesNotContain(poor.Blocked.ToArray(), RecipeKind.FollowingSweep);
|
||||
Assert.HasCount(1, poor.Warnings);
|
||||
StringAssert.Contains(poor.Warnings[0], $"La mappa dei bersagli in {mapPath} lascia ferme ricette che con quella incorporata in Febe potrebbero girare (");
|
||||
StringAssert.Contains(poor.Warnings[0], "Controllo del profilo");
|
||||
|
||||
// Never what is in the files.
|
||||
var note = ReaderVocabulary.LoadTestSite().Note!;
|
||||
foreach (var text in stale.Lines.Concat(stale.Warnings).Concat(poor.Lines).Concat(poor.Warnings))
|
||||
{
|
||||
Assert.IsFalse(text.Contains(note, StringComparison.Ordinal), text);
|
||||
Assert.IsFalse(text.Contains("/profilo/", StringComparison.Ordinal), text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The files loaded as the collection pipeline loads them: the Data-folder copy when it exists.</summary>
|
||||
private static CollectionConfiguration Loaded(TempFolder folder, string site)
|
||||
{
|
||||
var vocabulary = ReaderVocabulary.LoadOrEmbedded(folder.Combine($"lettori.{site}.json"), $"lettori.{site}.json");
|
||||
var map = SiteMap.LoadOrEmbedded(folder.Combine($"bersagli.{site}.json"), $"bersagli.{site}.json");
|
||||
return CollectionConfiguration.Describe(site, vocabulary, map);
|
||||
}
|
||||
}
|
||||
@@ -607,4 +607,28 @@ public sealed class EngineHostTests
|
||||
Assert.HasCount(foodLooks, Looks("17900000002"));
|
||||
Assert.IsTrue(Looks("17900000001").Count > travelLooks);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASinglePostQueuedByTheCollectionRunsInsteadOfBeingCancelledByTheQueue()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("uno.demo", followed: true);
|
||||
var paused = await bed.AddAccountAsync("due.demo", followed: true, state: AccountState.Paused);
|
||||
|
||||
// As CollectionWriter.QueueSinglePostAsync queues it for an address that expired (spec §6.5 point 5).
|
||||
EngineTask SinglePost(Account a, string entryId) =>
|
||||
new() { Kind = EngineTaskKind.SinglePost, AccountId = a.Id, Payload = entryId, DueAt = Morning, CreatedAt = Morning };
|
||||
var refresh = await bed.Db.Tasks.EnqueueAsync(SinglePost(account, "41"));
|
||||
var held = await bed.Db.Tasks.EnqueueAsync(SinglePost(paused, "42"));
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock);
|
||||
bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
|
||||
var runs = runner.Runs.Where(r => r.Request.Kind == RecipeKind.SinglePost).ToList();
|
||||
Assert.HasCount(1, runs, "The expired address is refreshed once, on the account that may be contacted.");
|
||||
Assert.AreEqual(41L, runs[0].Request.EntryId);
|
||||
Assert.AreEqual(account.Id, runs[0].Request.AccountId);
|
||||
Assert.AreEqual(EngineTaskState.Done, (await bed.Db.Tasks.GetAsync(refresh.Id))!.State);
|
||||
Assert.AreEqual(EngineTaskState.Cancelled, (await bed.Db.Tasks.GetAsync(held.Id))!.State, "«In pausa»: not contacted.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// A recipe the files of the site do not let run (target map or reader vocabulary incomplete) is a state of the
|
||||
/// configuration, not a failure (spec §6.4): never counted towards suspension, not planned, said once per process.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class NotConfiguredRecipeTests
|
||||
{
|
||||
private const string ProfileReason = "«Controllo del profilo» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «profile»).";
|
||||
private const string SweepReason = "«Giro dei seguiti» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «home»).";
|
||||
private const string ListReason = "«Elenco dei seguiti» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano pagina «following»).";
|
||||
private const string StoriesReason = "«Storie di un account» non può girare su instagram: la mappa dei bersagli non è ancora compilata (mancano bersaglio «profile-story-ring»).";
|
||||
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARecipeTheConfigurationDoesNotLetRunIsNotPlannedNotCountedAndSaidOnce()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("lontano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock) { NotConfigured = k => k == RecipeKind.ProfileCheck ? ProfileReason : null };
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(2));
|
||||
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "Never run: it would only be refused.");
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.ProfileCheck), "Nor planned.");
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures), "No failure counted.");
|
||||
|
||||
var events = await bed.Db.Events.ListAsync(new EventQuery());
|
||||
var said = events.Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
|
||||
Assert.HasCount(1, said, "Once per recipe and process, not at every session.");
|
||||
Assert.AreEqual(ProfileReason + SessionComposer.NotConfiguredTail, said[0].Message);
|
||||
Assert.AreEqual(EventSeverity.Warning, said[0].Severity);
|
||||
Assert.IsFalse(events.Any(e => e.Code is EngineEventCodes.RecipeSuspended or EngineEventCodes.TargetNotFound or EngineEventCodes.FormatUnrecognized));
|
||||
Assert.IsGreaterThan(1, events.Count(e => e.Code == EngineEventCodes.SessionEnded), "Several sessions went by.");
|
||||
|
||||
// «Controlla ora» says why at once instead of queueing a check that cannot run.
|
||||
var check = await host.CheckNowAsync(account.Id);
|
||||
Assert.AreEqual(CheckNowStatus.Refused, check.Status);
|
||||
Assert.AreEqual(ProfileReason + " Il controllo non parte.", check.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheSweepFollowedStoriesAreCheckedOneByOneAndACommandThatCannotRunIsDropped()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.AddAccountAsync("vicina.demo", followed: true);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
NotConfigured = k => k switch
|
||||
{
|
||||
RecipeKind.FollowingSweep => SweepReason,
|
||||
RecipeKind.FollowingList => ListReason,
|
||||
_ => null,
|
||||
},
|
||||
};
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.FollowingSweep));
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.FollowingSweep), "The sweep is not shown in the queue.");
|
||||
Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories), "No sweep covers the stories bar: they are checked explicitly.");
|
||||
|
||||
await host.RequestFollowingListAsync();
|
||||
await bed.RunForAsync(TimeSpan.FromHours(8));
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.FollowingList));
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.FollowingList), "Alberto's command is dropped, not left waiting for ever.");
|
||||
|
||||
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).Select(e => e.Message).ToList();
|
||||
Assert.AreEqual(1, said.Count(m => m.StartsWith(SweepReason, StringComparison.Ordinal)));
|
||||
Assert.AreEqual(1, said.Count(m => m.StartsWith(ListReason, StringComparison.Ordinal)));
|
||||
Assert.AreEqual(1, said.Count(m => m == $"La tua richiesta (l'elenco dei profili che segui) è annullata: {ListReason}"));
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WhileTheStoriesCannotRunAProfileNotFollowedIsVisitedOnlyForItsPosts()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("lontana.demo", followed: false, Frequency.Low);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock) { NotConfigured = k => k == RecipeKind.AccountStories ? StoriesReason : null };
|
||||
bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(4));
|
||||
|
||||
// «Bassa»: the profile every 12 hours or so, never sooner than 0.6 × 12 h. A visit that also served the stories
|
||||
// would come at the story interval instead (a third of the window, about 5 hours), and collect nothing more.
|
||||
var visits = runner.Runs.Where(r => r.Request.Kind == RecipeKind.ProfileCheck && r.Status == RecipeStatus.Completed).Select(r => r.At).ToList();
|
||||
Assert.IsGreaterThan(2, visits.Count, "The profile is still checked for its posts.");
|
||||
for (var i = 1; i < visits.Count; i++)
|
||||
{
|
||||
Assert.IsTrue(visits[i] - visits[i - 1] >= TimeSpan.FromHours(7), $"Visit after {visits[i] - visits[i - 1]}.");
|
||||
}
|
||||
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories));
|
||||
Assert.IsNull((await bed.Db.Accounts.GetAsync(account.Id))!.NextStoriesCheckAt, "Story times stay as they are, for when the stories can run.");
|
||||
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
|
||||
Assert.HasCount(1, said);
|
||||
Assert.AreEqual(StoriesReason + SessionComposer.NotConfiguredTail, said[0].Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStoriesBarQueuesNoStoryCheckTheConfigurationDoesNotLetRun()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
var account = await bed.AddAccountAsync("vicina.demo", followed: true);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
FlaggedStories = [account.Id],
|
||||
NotConfigured = k => k == RecipeKind.AccountStories ? StoriesReason : null,
|
||||
};
|
||||
bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(1));
|
||||
|
||||
Assert.IsGreaterThan(1, runner.Runs.Count(r => r.Request.Kind == RecipeKind.FollowingSweep && r.Status == RecipeStatus.Completed), "Several sweeps flagged the account.");
|
||||
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.AccountStories));
|
||||
Assert.AreEqual(0L, await TasksAsync(bed, EngineTaskKind.AccountStories), "No story check queued: none waits in the Coda, none is cancelled at the next session.");
|
||||
var said = (await bed.Db.Events.ListAsync(new EventQuery())).Where(e => e.Code == EngineEventCodes.RecipeNotConfigured).ToList();
|
||||
Assert.HasCount(1, said, "Said once, not at every sweep.");
|
||||
Assert.AreEqual(StoriesReason + SessionComposer.NotConfiguredTail, said[0].Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARefusalOfTheRunnerIsNotAFailureAndIsNotTriedAgainInTheProcess()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(Morning);
|
||||
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.NotConfigured, 0, 0, ProfileReason) : null,
|
||||
};
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(Morning.AddDays(3));
|
||||
|
||||
// Three unrecognized formats suspend the recipe in two days (EngineHostTests); a refusal never does.
|
||||
Assert.AreEqual(1, runner.Runs.Count(r => r.Request.Kind == RecipeKind.ProfileCheck));
|
||||
Assert.IsEmpty(host.SuspendedRecipes);
|
||||
Assert.IsNull(await bed.Db.Settings.GetAsync(EngineSettingKeys.RecipeFailures));
|
||||
Assert.IsFalse((await bed.Db.Tasks.ListPendingAsync(1000)).Any(t => t.Kind == EngineTaskKind.ProfileCheck));
|
||||
|
||||
var events = await bed.Db.Events.ListAsync(new EventQuery());
|
||||
Assert.IsFalse(events.Any(e => e.Code is EngineEventCodes.RecipeSuspended or EngineEventCodes.FormatUnrecognized or EngineEventCodes.TargetNotFound or EngineEventCodes.RecipeFailed));
|
||||
Assert.AreEqual(0, events.Count(e => e.Code == EngineEventCodes.RecipeNotConfigured), "The runner said it; the engine does not say it again.");
|
||||
var line = events.Single(e => e.Code == EngineEventCodes.RecipePrefix + RecipeKind.ProfileCheck);
|
||||
StringAssert.EndsWith(line.Message, "Configurazione della raccolta incompleta");
|
||||
var snapshot = await host.Monitor.GetSnapshotAsync();
|
||||
Assert.IsTrue(snapshot.RecentActions.Any(a => a.Badge == "Da configurare"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheRunnerRefusesBeforeDoingAnythingAndSaysItOncePerRecipe()
|
||||
{
|
||||
using var temp = new TempFolder("non-configurata");
|
||||
await using var db = await TestDatabase.OpenAsync(temp);
|
||||
var clock = new VirtualClock();
|
||||
var governor = new PermissiveGovernor();
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
RecipeEnvironment Environment(SiteMap map, ReaderVocabulary vocabulary) => new()
|
||||
{
|
||||
Driver = new UntouchedDriver(),
|
||||
Capture = new CaptureCollector(new ShapeReader(vocabulary), clock),
|
||||
Governor = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadDefault(), new RecordingBreaker(), clock),
|
||||
Storage = db,
|
||||
SiteMap = map,
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(1),
|
||||
};
|
||||
|
||||
var empty = SiteMap.Parse("""{ "site": "vuoto", "pages": { "home": "" } }""", "bersagli.vuoto.json");
|
||||
var runner = new RecipeRunner(Environment(empty, ReaderVocabulary.LoadTestSite()));
|
||||
StringAssert.Contains(runner.NotConfiguredReason(RecipeKind.FollowingSweep), "pagina «home»");
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var sweep = await runner.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, sweep.Status);
|
||||
Assert.AreEqual(runner.NotConfiguredReason(RecipeKind.FollowingSweep), sweep.Message);
|
||||
Assert.AreEqual(0, sweep.CountedActions);
|
||||
}
|
||||
|
||||
var profile = await runner.RunAsync(new RecipeRequest(RecipeKind.ProfileCheck, 1), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, profile.Status);
|
||||
StringAssert.Contains(profile.Message, "la mappa dei bersagli non è ancora compilata");
|
||||
|
||||
var lines = (await db.Events.ListAsync(new EventQuery())).Where(e => e.Code == "mappa-incompleta").ToList();
|
||||
Assert.HasCount(2, lines, "One line per recipe, not one per run.");
|
||||
Assert.IsTrue(lines.All(e => e.Severity == EventSeverity.Warning && e.Message.EndsWith(SessionComposer.NotConfiguredTail, StringComparison.Ordinal)));
|
||||
|
||||
// A vocabulary that is only a hypothesis refuses every recipe the same way.
|
||||
var hypothesis = new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadTestSite() with { Status = VocabularyStatus.Hypothesis }));
|
||||
var readers = await hypothesis.RunAsync(new RecipeRequest(RecipeKind.FollowingSweep), session, CancellationToken.None);
|
||||
Assert.AreEqual(RecipeStatus.NotConfigured, readers.Status);
|
||||
Assert.IsTrue((await db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "lettori-incompleti"));
|
||||
Assert.AreEqual(0, governor.Requests.Count, "No permit asked, no gesture, no page.");
|
||||
|
||||
// The test site's own files let every recipe run.
|
||||
var full = new RecipeRunner(Environment(SiteMap.LoadTestSite(), ReaderVocabulary.LoadTestSite()));
|
||||
foreach (var kind in Enum.GetValues<RecipeKind>())
|
||||
{
|
||||
Assert.IsNull(full.NotConfiguredReason(kind), kind.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tasks of a kind in the queue, whatever their state (cancelled ones included).</summary>
|
||||
private static Task<long> TasksAsync(EngineTestBed bed, EngineTaskKind kind) =>
|
||||
bed.Db.ReadAsync(c => c.Command("SELECT COUNT(*) FROM task WHERE kind = @k").With("@k", kind.ToString()).ScalarInt64(), default);
|
||||
|
||||
/// <summary>A driver that fails the test if a refused recipe touches it.</summary>
|
||||
private sealed class UntouchedDriver : IPageDriver
|
||||
{
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public void BeginSession(double mood) => throw Touched();
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => throw Touched();
|
||||
|
||||
private static AssertFailedException Touched() => new("Una ricetta rifiutata ha toccato la pagina.");
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,19 @@ internal sealed class EngineTestBed : IAsyncDisposable
|
||||
return _host;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Like <see cref="Start"/>, with <paramref name="beforeLoop"/> run on the host before its loop, as the composition
|
||||
/// does at start-up (<see cref="EngineHost.ApplyCollectionConfigurationAsync"/>).
|
||||
/// </summary>
|
||||
public async Task<EngineHost> StartAsync(IRecipeRunner runner, Func<EngineHost, Task> beforeLoop)
|
||||
{
|
||||
_host = new EngineHost(Services, runner);
|
||||
await beforeLoop(_host);
|
||||
_loopCts = new CancellationTokenSource();
|
||||
_loop = _host.RunAsync(_loopCts.Token);
|
||||
return _host;
|
||||
}
|
||||
|
||||
public EngineHost Host => _host ?? throw new InvalidOperationException("Engine not started.");
|
||||
|
||||
/// <summary>Advances virtual time to <paramref name="target"/>, letting the engine run.</summary>
|
||||
|
||||
@@ -31,6 +31,9 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
|
||||
/// <summary>Accounts the stories bar flags in every sweep.</summary>
|
||||
public IReadOnlyList<long> FlaggedStories { get; set; } = [];
|
||||
|
||||
/// <summary>What the runner says of the configuration of the site (null: every recipe can run).</summary>
|
||||
public Func<RecipeKind, string?>? NotConfigured { get; set; }
|
||||
|
||||
public int Rests { get; private set; }
|
||||
|
||||
public IReadOnlyList<RunRecord> Runs
|
||||
@@ -74,6 +77,8 @@ internal sealed class ScriptedRunner(IGovernor governor, IClock clock) : IRecipe
|
||||
return outcome;
|
||||
}
|
||||
|
||||
public string? NotConfiguredReason(RecipeKind kind) => NotConfigured?.Invoke(kind);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
Rests++;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Part2Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The link to Instagram in the sidebar (<c>/api/engine</c>, «connection»): it comes from the session cookie, as the
|
||||
/// engine's mode or the connection says, never from whether the account «Tu» is already known (H10: its name may come
|
||||
/// much later, and meanwhile the sidebar says «Collegato» with «Nome non ancora noto»).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class EngineConnectionStateTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task TheSidebarSaysConnectedFromTheSessionCookieEvenBeforeTuIsKnown()
|
||||
{
|
||||
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null) };
|
||||
await using var server = await Part2.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton<IEngineMonitor>(sp => new FixedModeMonitor(sp.GetRequiredService<IClock>()));
|
||||
s.AddSingleton<IConnectionService>(connection);
|
||||
});
|
||||
var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService<IEngineMonitor>();
|
||||
async Task<JsonElement> LinkAsync(EngineMode mode)
|
||||
{
|
||||
monitor.Mode = mode;
|
||||
return (await server.GetJsonAsync("/api/engine")).GetProperty("connection");
|
||||
}
|
||||
|
||||
// Collecting (or about to), with the cookie and without «Tu»: connected, no name yet.
|
||||
foreach (var mode in new[] { EngineMode.Starting, EngineMode.InSession, EngineMode.Resting, EngineMode.OutsideWindow, EngineMode.Paused, EngineMode.Throttled, EngineMode.UserDriving })
|
||||
{
|
||||
var link = await LinkAsync(mode);
|
||||
Assert.AreEqual("connected", link.Str("state"), mode.ToString());
|
||||
Assert.AreEqual(JsonValueKind.Null, link.GetProperty("username").ValueKind, mode.ToString());
|
||||
}
|
||||
|
||||
Assert.AreEqual("notConnected", (await LinkAsync(EngineMode.NotConnected)).Str("state"));
|
||||
Assert.AreEqual("disconnected", (await LinkAsync(EngineMode.Disconnected)).Str("state"));
|
||||
Assert.AreEqual("verification", (await LinkAsync(EngineMode.StoppedForVerification)).Str("state"));
|
||||
|
||||
// The engine loop does not run: the connection itself is asked.
|
||||
Assert.AreEqual("connected", (await LinkAsync(EngineMode.Off)).Str("state"));
|
||||
connection.Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null);
|
||||
Assert.AreEqual("notConnected", (await LinkAsync(EngineMode.Off)).Str("state"));
|
||||
|
||||
// Once «Tu» is known, its name comes along.
|
||||
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
||||
var named = await LinkAsync(EngineMode.Resting);
|
||||
Assert.AreEqual("connected", named.Str("state"));
|
||||
Assert.AreEqual("tuo.profilo", named.Str("username"));
|
||||
Assert.AreEqual(JsonValueKind.Null, (await LinkAsync(EngineMode.NotConnected)).GetProperty("username").ValueKind, "Not connected: no name.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutEngineAndBrowserTheSidebarSaysNotConnectedEvenIfTuIsKnown()
|
||||
{
|
||||
await using var server = await Part2.StartAsync();
|
||||
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
||||
var engine = await server.GetJsonAsync("/api/engine");
|
||||
Assert.AreEqual("Off", engine.GetProperty("snapshot").Str("mode"));
|
||||
Assert.AreEqual("notConnected", engine.GetProperty("connection").Str("state"), "No engine has looked at the cookie and the browser is not there.");
|
||||
}
|
||||
|
||||
/// <summary>An engine that reports the mode the test sets.</summary>
|
||||
private sealed class FixedModeMonitor(IClock clock) : IEngineMonitor
|
||||
{
|
||||
public EngineMode Mode { get; set; } = EngineMode.Resting;
|
||||
|
||||
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
|
||||
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent));
|
||||
|
||||
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -467,7 +467,9 @@ public sealed class InterfaceTests
|
||||
[TestMethod]
|
||||
public async Task TheEmptyLibraryFollowsTheConnectionAlsoWhenTheEngineAnswersLate()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
// No engine loop here (mode Off): the link in /api/engine is the connection's, from the session cookie.
|
||||
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null) };
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IConnectionService>(connection));
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(HoldEngine);
|
||||
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
|
||||
@@ -479,12 +481,12 @@ public sealed class InterfaceTests
|
||||
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto, main .mosaico') === null")).GetBoolean(), "no empty state is guessed " + ui.Report());
|
||||
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "0 ");
|
||||
|
||||
// Not connected (no own account): the first start with its two ways to begin (spec §10.3).
|
||||
// Not connected (no session cookie): the first start with its two ways to begin (spec §10.3).
|
||||
await ui.EvalAsync("window.__releaseEngine()");
|
||||
await ui.WaitAsync("document.querySelector('main .benvenuto') !== null && document.querySelector('main [aria-busy=true]') === null", "primo avvio dopo la risposta del motore");
|
||||
|
||||
// Connected now (the own account is known): the welcome gives way to the empty library.
|
||||
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
|
||||
// Connected now (the session cookie is there; «Tu» is not known yet, H10): the welcome gives way to the empty library.
|
||||
connection.Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null);
|
||||
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
|
||||
await ui.WaitAsync("document.querySelector('main .benvenuto') === null && document.querySelector('main .vuoto-pagina h2') !== null", "libreria vuota da collegato");
|
||||
Assert.AreEqual("La libreria è ancora vuota", (await ui.EvalAsync("document.querySelector('main .vuoto-pagina h2').textContent")).GetString());
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:35:04Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"ig_quick_promotion_batch_fetch_root": [
|
||||
{
|
||||
"surface_nux_id": "TRZWJXPWP_SCR_STFPZDBBB",
|
||||
"eligible_promotions": {
|
||||
"edges": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"surface_nux_id": "FZGHXFCSS_KHW_RJF_RWSQVJQZKMRP_ND",
|
||||
"eligible_promotions": {
|
||||
"edges": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"surface_nux_id": "QQJKWMDPD_MGG_LDB_PRRTGPN_JR",
|
||||
"eligible_promotions": {
|
||||
"edges": []
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 6491170198676,
|
||||
"time_at_flush_ms": 6962160759946
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:35:57Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_api__v1__fbsearch__topsearch_connection": {
|
||||
"see_more": null,
|
||||
"inform_module": null,
|
||||
"hashtags": [],
|
||||
"places": [],
|
||||
"users": [
|
||||
{
|
||||
"position": 0,
|
||||
"user": {
|
||||
"username": "dwvqbrgcjf",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"search_social_context": "Dddfhhp fp mgfkpgntpndkm \u00B7 hvsfq 5",
|
||||
"search_social_context_snippet_type": "typeahead_mutual_followers",
|
||||
"unseen_count": 0,
|
||||
"pk": "215081405",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/07030bdh2v0xr6k5.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/647n30r26f451997.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "215081405"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 1,
|
||||
"user": {
|
||||
"username": "_knkrcbq",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "51077241323",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/52323983k4g85lf2.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/0r67762f9b08cs29.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "51077241323"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 2,
|
||||
"user": {
|
||||
"username": "tpmzvqmgq",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Gfvfds Cvwlsxb\u00B7\u00B7\u00B7\u00B7\u00B7\u00B7",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "1878810562",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/50q0271sh117xmkh.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/95424rmcv4b31999.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "1878810562"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 3,
|
||||
"user": {
|
||||
"username": "ldrcdvnhrhzz",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Xpdcsvzwfqvm Qkvnk-gftsqrqmpk",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "3162721231",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/305401nc89mc40qs.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/5256037mb91hp50k.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "3162721231"
|
||||
}
|
||||
},
|
||||
{
|
||||
"position": 4,
|
||||
"user": {
|
||||
"username": "hkngtchnglsv",
|
||||
"is_verified": false,
|
||||
"ai_agent_owner_username": null,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_enabled": false
|
||||
},
|
||||
"full_name": "Wmjqb",
|
||||
"search_social_context": null,
|
||||
"search_social_context_snippet_type": null,
|
||||
"unseen_count": 0,
|
||||
"pk": "0388923287",
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"profile_pic_url": "https://cdn.esempio/514p2980v17438q8.jpg",
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/72zh4k37vr72lr9f.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "0388923287"
|
||||
}
|
||||
}
|
||||
],
|
||||
"rank_token": "7777777777777\u00B7xx77777xxx7x7x7x7x777xx7777x77777777777x7x777xx7x7x77777xxxx7x77"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 5319299593604,
|
||||
"time_at_flush_ms": 7904759334510
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:36:00Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_api__v1__discover__chaining": {
|
||||
"users": [
|
||||
{
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"blocking": false,
|
||||
"is_feed_favorite": false,
|
||||
"outgoing_request": false,
|
||||
"followed_by": false,
|
||||
"incoming_request": false,
|
||||
"is_restricted": false,
|
||||
"is_bestie": false
|
||||
},
|
||||
"full_name": "sgdcmwkjqgwmhg",
|
||||
"is_verified": false,
|
||||
"pk": "1575951745",
|
||||
"profile_pic_url": "https://cdn.esempio/1981r1hc98hsp8b6.jpg",
|
||||
"username": "vxpclbv_bkvgmvq",
|
||||
"is_private": false,
|
||||
"supervision_info": null,
|
||||
"social_context": null,
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/2v973665034n8123.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "1575951745"
|
||||
},
|
||||
{
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"blocking": false,
|
||||
"is_feed_favorite": false,
|
||||
"outgoing_request": false,
|
||||
"followed_by": false,
|
||||
"incoming_request": false,
|
||||
"is_restricted": false,
|
||||
"is_bestie": false
|
||||
},
|
||||
"full_name": "KZ6Q - Tpkqftnb Dlhlc 3Qjwm",
|
||||
"is_verified": false,
|
||||
"pk": "6092958043",
|
||||
"profile_pic_url": "https://cdn.esempio/s62m19s6181q16rm.jpg",
|
||||
"username": "hndphqqhdvktn6dnpj",
|
||||
"is_private": false,
|
||||
"supervision_info": null,
|
||||
"social_context": null,
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/9zh0q9f43861n513.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "6092958043"
|
||||
},
|
||||
{
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"blocking": false,
|
||||
"is_feed_favorite": false,
|
||||
"outgoing_request": false,
|
||||
"followed_by": false,
|
||||
"incoming_request": false,
|
||||
"is_restricted": false,
|
||||
"is_bestie": false
|
||||
},
|
||||
"full_name": "PNQHC HXGBF VTMHJTV",
|
||||
"is_verified": false,
|
||||
"pk": "24973134344",
|
||||
"profile_pic_url": "https://cdn.esempio/f092k9mj8664rdc9.jpg",
|
||||
"username": "hwjfbsgqhdqhmkcgs_",
|
||||
"is_private": false,
|
||||
"supervision_info": null,
|
||||
"social_context": null,
|
||||
"live_broadcast_visibility": null,
|
||||
"live_broadcast_id": null,
|
||||
"hd_profile_pic_url_info": {
|
||||
"url": "https://cdn.esempio/j7c0c9m17ztg64xg.jpg"
|
||||
},
|
||||
"is_unpublished": false,
|
||||
"id": "24973134344"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 4070744587334,
|
||||
"time_at_flush_ms": 7911613436243
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/tb3199751p061262",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "application/json",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:38:56Z"
|
||||
},
|
||||
"corpo": {
|
||||
"can_view_more_preview_comments": false,
|
||||
"caption": {
|
||||
"bit_flags": 0,
|
||||
"content_type": "comment",
|
||||
"created_at": 1788817267,
|
||||
"created_at_for_fb_app": 7133613899,
|
||||
"created_at_utc": 7133613899,
|
||||
"did_report_as_spam": false,
|
||||
"is_covered": false,
|
||||
"is_created_by_media_owner": true,
|
||||
"is_ranked_comment": false,
|
||||
"media_id": "9222129690324603277",
|
||||
"pk": "40021847552872166",
|
||||
"private_reply_status": 0,
|
||||
"share_enabled": true,
|
||||
"status": "Active",
|
||||
"strong_id__": "40021847552872166",
|
||||
"text": "Qwqwpb \u00B7\u00B7",
|
||||
"type": 1,
|
||||
"user": {
|
||||
"fbid_v2": "55370645405178029",
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"id": "215081405",
|
||||
"is_private": false,
|
||||
"is_unpublished": false,
|
||||
"is_verified": false,
|
||||
"pk": 681057818,
|
||||
"pk_id": "215081405",
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/07030bdh2v0xr6k5.jpg",
|
||||
"strong_id__": "215081405",
|
||||
"username": "dwvqbrgcjf"
|
||||
},
|
||||
"user_id": 681057818
|
||||
},
|
||||
"caption_is_edited": false,
|
||||
"comment_count": 2,
|
||||
"comment_cover_pos": "nrfkbf",
|
||||
"comment_filter_param": "pv_mbxxnt",
|
||||
"comment_likes_enabled": true,
|
||||
"comments": [],
|
||||
"has_more_comments": false,
|
||||
"has_more_headload_comments": false,
|
||||
"initiate_at_top": true,
|
||||
"insert_new_comment_to_top": true,
|
||||
"liked_by_media_owner_badge_enabled": true,
|
||||
"media_header_display": "lwrc",
|
||||
"quick_response_emojis": [
|
||||
{
|
||||
"unicode": "\u00B7\uFE0F"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
},
|
||||
{
|
||||
"unicode": "\u00B7\u00B7"
|
||||
}
|
||||
],
|
||||
"scroll_behavior": 1,
|
||||
"threading_enabled": true,
|
||||
"filter_options": [],
|
||||
"sort_options": [],
|
||||
"should_render_upsell": false,
|
||||
"foundation_improvements_enabled": true,
|
||||
"geoblocked_comment_notices": [],
|
||||
"has_more_headload_fb_comments": false,
|
||||
"fb_comments": [],
|
||||
"ai_topic_filters": [],
|
||||
"status": "ok"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/81jg128fq9rkr95q",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "application/json",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:38:56Z"
|
||||
},
|
||||
"corpo": {
|
||||
"num_results": 1,
|
||||
"more_available": false,
|
||||
"items": [
|
||||
{
|
||||
"strong_id__": "7909533858063387797_250912751",
|
||||
"id": "7909533858063387797_250912751",
|
||||
"disable_caption_and_comment": false,
|
||||
"fbid": "16246906758569910",
|
||||
"deleted_reason": 0,
|
||||
"client_cache_key": "xxx7xxxxxxx7xxx7xxxxxxx7xx\u00B7\u00B7.7",
|
||||
"integrity_review_decision": "xnmfgvb",
|
||||
"is_awaiting_distribution": false,
|
||||
"has_delayed_metadata": false,
|
||||
"mezql_token": "",
|
||||
"should_request_ads": false,
|
||||
"has_privately_liked": false,
|
||||
"share_count_disabled": false,
|
||||
"is_reshare_of_text_post_app_media_in_ig": false,
|
||||
"is_visual_reply_commenter_notice_enabled": true,
|
||||
"subtype_name_for_REST__": "RZJRtmmpMsqnt",
|
||||
"is_quiet_post": false,
|
||||
"is_third_party_downloads_eligible": true,
|
||||
"is_short_drama": false,
|
||||
"media_type": 2,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxxxxxx7xxx7xxx7xxxxxxx7xxxxxxx7xxx7xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxx7xxxxxxx7xxx7xxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxx7xxx7xxx7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx7xxxxxxx7xxxxxxxxxxxxxxxxxxx7xxx7xxx7xxxxxxxxxxxxxx7xxxxxx77xxxxxxxx7xxx7",
|
||||
"music_metadata": null,
|
||||
"clips_tab_pinned_user_ids": [],
|
||||
"is_open_to_public_submission": false,
|
||||
"is_social_ufi_disabled": false,
|
||||
"timeline_pinned_user_ids": [],
|
||||
"taken_at": 1788817278,
|
||||
"pk": "9222129690324603277",
|
||||
"can_see_insights_as_brand": false,
|
||||
"is_affiliate_commission_eligible": false,
|
||||
"is_in_profile_grid": false,
|
||||
"profile_grid_control_enabled": false,
|
||||
"product_type": "clips",
|
||||
"subscribe_cta_visible": false,
|
||||
"is_cutout_sticker_allowed": true,
|
||||
"cutout_sticker_info": [],
|
||||
"should_show_author_pog_for_tagged_media_shared_to_profile_grid": false,
|
||||
"is_eligible_content_for_post_roll_ad": false,
|
||||
"related_ads_pivots_media_info": "LRNPHZQ_DT_GZRCR_LCH_LQSPKFSMNZM",
|
||||
"eligible_insights_entrypoints": "XJMH",
|
||||
"basel_encoding_timeout": 60,
|
||||
"media_attributions_data": [],
|
||||
"media_ui_attributions_data": [],
|
||||
"media_ui_attributions_data_v2": [],
|
||||
"is_eligible_for_poe": false,
|
||||
"is_eligible_for_organic_eager_refresh": true,
|
||||
"commerce_integrity_review_decision": "",
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"boost_unavailable_reason_v2": null,
|
||||
"coauthor_producers": [],
|
||||
"coauthor_producer_can_see_organic_insights": false,
|
||||
"invited_coauthor_producers": [],
|
||||
"is_paid_partnership": false,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"comment_inform_treatment": {
|
||||
"action_type": null,
|
||||
"should_have_inform_treatment": false,
|
||||
"text": "",
|
||||
"url": null
|
||||
},
|
||||
"is_photo_comments_composer_enabled_for_author": true,
|
||||
"fb_comment_count": 2,
|
||||
"hide_view_all_comment_entrypoint": true,
|
||||
"locations": [],
|
||||
"are_remixes_crosspostable": true,
|
||||
"crosspost_metadata": {
|
||||
"is_feedback_aggregated": true,
|
||||
"unified_feedback_enabled": true,
|
||||
"fb_downstream_use_xpost_metadata": {
|
||||
"downstream_use_xpost_deny_reason": "XJMH"
|
||||
}
|
||||
},
|
||||
"is_eligible_for_autodub": false,
|
||||
"is_eligible_for_autodub_upsell": false,
|
||||
"video_sticker_locales": [],
|
||||
"has_audio": true,
|
||||
"video_versions": [
|
||||
{
|
||||
"bandwidth": 7488206,
|
||||
"height": 1280,
|
||||
"id": "6329013574175521c",
|
||||
"progressive_identifier": "FL\u00B7\u00B7",
|
||||
"type": 101,
|
||||
"url": "https://cdn.esempio/09m2z2jjrhj04846.mp4",
|
||||
"url_expiration_timestamp_us": null,
|
||||
"width": 720,
|
||||
"fallback": null
|
||||
},
|
||||
{
|
||||
"bandwidth": 7488206,
|
||||
"height": 1280,
|
||||
"id": "6329013574175521c",
|
||||
"progressive_identifier": "FL\u00B7\u00B7",
|
||||
"type": 102,
|
||||
"url": "https://cdn.esempio/09m2z2jjrhj04846.mp4",
|
||||
"url_expiration_timestamp_us": null,
|
||||
"width": 720,
|
||||
"fallback": null
|
||||
},
|
||||
{
|
||||
"bandwidth": 7488206,
|
||||
"height": 1280,
|
||||
"id": "6329013574175521c",
|
||||
"progressive_identifier": "FL\u00B7\u00B7",
|
||||
"type": 103,
|
||||
"url": "https://cdn.esempio/09m2z2jjrhj04846.mp4",
|
||||
"url_expiration_timestamp_us": null,
|
||||
"width": 720,
|
||||
"fallback": null
|
||||
}
|
||||
],
|
||||
"number_of_qualities": 5,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null,
|
||||
"sharing_friction_payload": null
|
||||
},
|
||||
"gen_ai_detection_method": {
|
||||
"detection_method": "XJMH"
|
||||
},
|
||||
"tappable_elements": [],
|
||||
"premium_reaction_count": 0,
|
||||
"viewer_premium_reaction_asset_id": null,
|
||||
"creator_is_in_premium_reactions_alpha": false,
|
||||
"image_versions2": {
|
||||
"additional_candidates": {
|
||||
"first_frame": {
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1136,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/34217235931q327b.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
"igtv_first_frame": {
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1136,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/34217235931q327b.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
"smart_frame": null
|
||||
},
|
||||
"candidates": [
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1280,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/kx13rmfs3p38w278.jpg",
|
||||
"width": 720,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 1138,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/33m7013129286664.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 853,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/vkzpk03019d4p6l9.jpg",
|
||||
"width": 480,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 569,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/h459gzh05hqwdp7q.jpg",
|
||||
"width": 320,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 427,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/4p4s1v897755d261.jpg",
|
||||
"width": 240,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 720,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/w2sq4q2jmczmk8rv.jpg",
|
||||
"width": 720,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 720,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/w2sq4q2jmczmk8rv.jpg",
|
||||
"width": 720,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 640,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/7794f286mv847mpk.jpg",
|
||||
"width": 640,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 480,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/6cbl44591025c4gt.jpg",
|
||||
"width": 480,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 320,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/20zvr63s211lt69k.jpg",
|
||||
"width": 320,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 240,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/l4xq85tt02lk907c.jpg",
|
||||
"width": 240,
|
||||
"is_spatial_image": false
|
||||
},
|
||||
{
|
||||
"estimated_scans_sizes": [],
|
||||
"height": 150,
|
||||
"scans_profile": null,
|
||||
"url": "https://cdn.esempio/9fpxtl37s22c73v1.jpg",
|
||||
"width": 150,
|
||||
"is_spatial_image": false
|
||||
}
|
||||
],
|
||||
"scrubber_spritesheet_info_candidates": {
|
||||
"default": {
|
||||
"file_size_kb": 681,
|
||||
"max_thumbnails_per_sprite": 105,
|
||||
"rendered_width": 96,
|
||||
"sprite_height": 1232,
|
||||
"sprite_urls": [
|
||||
"https://cdn.esempio/b9h31456q6z1k694.jpg"
|
||||
],
|
||||
"sprite_width": 1500,
|
||||
"thumbnail_duration": 0.05619047619047619,
|
||||
"thumbnail_height": 176,
|
||||
"thumbnail_width": 100,
|
||||
"thumbnails_per_row": 15,
|
||||
"total_thumbnail_num_per_sprite": 105,
|
||||
"video_length": 5.9
|
||||
}
|
||||
}
|
||||
},
|
||||
"original_width": 1440,
|
||||
"original_height": 2560,
|
||||
"has_tagged_users": false,
|
||||
"fb_user_tags": {
|
||||
"in": []
|
||||
},
|
||||
"media_overlay_info": null,
|
||||
"media_notes": {
|
||||
"items": []
|
||||
},
|
||||
"social_context": [],
|
||||
"creative_config": {
|
||||
"capture_type": "clips_v2",
|
||||
"face_effect_id": null,
|
||||
"failure_reason": null,
|
||||
"attribution_user": null,
|
||||
"creation_tool_info": [
|
||||
{
|
||||
"camera_tool": 434,
|
||||
"duration_selector_seconds": 0.0,
|
||||
"speed_selector": 0.0,
|
||||
"color_filters": "",
|
||||
"appearance_effect": 0,
|
||||
"timer_selector_seconds": 0.0,
|
||||
"magic_cut_start_time": 0.0,
|
||||
"magic_cut_end_time": 0.0,
|
||||
"effect_filter_name": ""
|
||||
}
|
||||
],
|
||||
"effect_configs": null,
|
||||
"effect_preview": null,
|
||||
"gen_ai_tool_info": null
|
||||
},
|
||||
"floating_context_items": [],
|
||||
"is_reuse_allowed": true,
|
||||
"igbio_product": null,
|
||||
"clips_metadata": {
|
||||
"clips_creation_entry_point": "gmzkv",
|
||||
"featured_label": null,
|
||||
"is_public_chat_welcome_video": false,
|
||||
"professional_clips_upsell_type": 0,
|
||||
"show_tips": null,
|
||||
"achievements_info": {
|
||||
"num_earned_achievements": null,
|
||||
"show_achievements": false
|
||||
},
|
||||
"additional_audio_info": {
|
||||
"additional_audio_username": null,
|
||||
"audio_reattribution_info": {
|
||||
"should_allow_restore": false
|
||||
}
|
||||
},
|
||||
"asset_recommendation_info": null,
|
||||
"audio_ranking_info": {
|
||||
"best_audio_cluster_id": "887740111386887"
|
||||
},
|
||||
"audio_type": "original_sounds",
|
||||
"branded_content_tag_info": {
|
||||
"can_add_tag": false
|
||||
},
|
||||
"breaking_content_info": null,
|
||||
"breaking_creator_info": null,
|
||||
"challenge_info": null,
|
||||
"content_appreciation_info": {
|
||||
"enabled": false,
|
||||
"entry_point_container": null
|
||||
},
|
||||
"contextual_highlight_info": null,
|
||||
"cutout_sticker_info": [],
|
||||
"disable_use_in_clips_client_cache": false,
|
||||
"external_media_info": null,
|
||||
"is_fan_club_promo_video": false,
|
||||
"is_shared_to_fb": false,
|
||||
"mashup_info": {
|
||||
"can_toggle_mashups_allowed": false,
|
||||
"formatted_mashups_count": null,
|
||||
"has_been_mashed_up": false,
|
||||
"has_nonmimicable_additional_audio": false,
|
||||
"is_creator_requesting_mashup": false,
|
||||
"is_light_weight_check": true,
|
||||
"is_light_weight_reuse_allowed_check": false,
|
||||
"is_pivot_page_available": false,
|
||||
"is_reuse_allowed": true,
|
||||
"mashup_type": null,
|
||||
"mashups_allowed": true,
|
||||
"mashups_allowed_for_carousel": false,
|
||||
"non_privacy_filtered_mashups_media_count": 0,
|
||||
"privacy_filtered_mashups_media_count": null,
|
||||
"original_media": null
|
||||
},
|
||||
"merchandising_pill_info": null,
|
||||
"music_canonical_id": "91113504822483696",
|
||||
"music_info": null,
|
||||
"nux_info": null,
|
||||
"original_sound_info": {
|
||||
"allow_creator_to_rename": true,
|
||||
"audio_asset_id": "12471162636763090",
|
||||
"attributed_custom_audio_asset_id": null,
|
||||
"can_remix_be_shared_to_fb": true,
|
||||
"can_remix_be_shared_to_fb_expansion": true,
|
||||
"dash_manifest": "\u00B7?fgw hcmrvts\u00B7\u00227.5\u0022 czvtdjch\u00B7\u0022JWZ-0\u0022?\u00B7\n\u00B7KKJ dsqwq\u00B7\u0022rsh:hrqr:dfxm:sndnsc:ctw:3176\u0022 sgggq:mkf\u00B7\u0022dbgs://dmh.q5.gvj/0496/QXXJhftxf-mfjjjlmb\u0022 lck:dznkzgWmtbzbdc\u00B7\u0022pxb:rttk:pptt:ksrnzr:twz:1853 CLQN-MJT.mhg\u0022 hdpgpbvz\u00B7\u0022qkh:ppvf:ncwf:kdspllk:qmfbk-jn-kdxszp:3300\u0022 llvNzcbcdCnrg\u00B7\u0022TR0F\u0022 vxpv\u00B7\u0022xjvrrh\u0022 klmhnDhkggrvgzmjrKwkknxlg\u00B7\u0022ZM2.541945N\u0022 RXNnkhcsrmLbwlwcmmk\u00B7\u00222221857858\u0022 JWWhsmmtksVvtfdvvgbr\u00B7\u0022DtVcj16XPDtZ//LtsdWsGzPCFKM2TDlxZ3KbK19rbz66TpTdNPLR\u0022\u00B7\u00B7Zmqtcs zv\u00B7\u00220\u0022 xrxlkzmg\u00B7\u0022PS7.526638D\u0022\u00B7\u00B7SmhvzlzspnHpr gl\u00B7\u00221\u0022 qzllhrxTzfb\u00B7\u0022bdqdh\u0022 dhzccrszrlNqptxbHbvgZPR\u00B7\u00221\u0022 qqhgzppzjdLlqlrjlqk\u00B7\u0022mvcp\u0022\u00B7\u00B7Gsppwhdkqwzfwg gd\u00B7\u00223454055608463982k\u0022 rtqfglzdz\u00B7\u002214114\u0022 rcvhdj\u00B7\u0022pn8d.44.9\u0022 pcfkPdmb\u00B7\u0022gzjgv/xg2\u0022 MCQgcLfqqmnp\u00B7\u002256757\u0022 cpthjDkfxrxndZqjs\u00B7\u002293511\u0022\u00B7\u00B7RbvvvBlvwvwkPtqfsgvsvwwzx krtcgmFhQjz\u00B7\u0022zsb:gtwm:crjv:19112:3:swpbc_sdnlcnw_spzcltkfmkvzp:5596\u0022 lnmgs\u00B7\u00221\u0022/\u00B7\u00B7JlwjHRG\u00B7pqqqk://zhphpxdp-zdw7-1.whkmjdjxmdsh.vcd/b6/w/m6/s0/c96/ZKVd5xnMnvrpG8sJGFCH486Z1ljbM1N2gCmhgFNS8pHTbSSHTG95C7KhKsLMrxQLz7nzVCB441PWTHqjzgLdCKsDt7FWkCWChScQPkx.lb0?_hj_wzg\u00B75\u0026thc;_rr_sbm\u00B78qr563\u0026jnh;_vb_dv\u00B7sxjnwqrf-rsf1-2.wdqwxrwjxlpp.zjx\u0026rzg;_np_dfm\u00B7FBcvc9cBtPMM1wHdqHnjqlf\u0026gwk;kwc\u00B7jzR6DX4bl0VcK9PgJpK6LrMhz6tlwJ9ljCGwNLXnlhLtR99qhQTdxdBpNrDmBBGhM2hhCgdstFmsCDGppRzgvNMsJ7FvK3XbkD0cNLF1ZfW9XxlrXPHgNHQ0QZHmxDgkczFnlqZvLQK0VzPxj21hm42hCPW2hLFnJPSrJVBkdKFcGcDsSGt8JMLbLkS5JDf1WHGnZmJpr6V5T8GzRN7zLMpdVxzmVSCxJzShQ2ZbXGPwd9TxbCGrGgPkZCz3FKMbpVLxnZkvzt6nQgh0CDWclWDfRHLkSbk4WkN9PPzzvXFhL4GgM8CczLLcDFB8Bgh6wbL5\u0026mcw;hwt\u00B746-2\u0026mnq;_bd_wgc\u00B7xNZ-cG63JpqFxw2L3j3ZxN\u0026wqj;_jk_rz\u00B75k86f\u0026fvx;_mv_sf\u00B745\u0026rqg;nr\u00B790_VNFj_ZnbnTk9sL-MsGWng01vWhN_pkB6KvDhmbTrVfWKgQ\u0026dvd;fr\u00B79CSWT4Z9\u00B7/QdqlGTS\u00B7\u00B7CzqgsvzRmpm hdddqKknjd\u00B7\u0022700-263\u0022 bpqxltqtq\u00B7\u002255460\u0022\u00B7\u00B7Vgmznbtxjpxskh xrmhv\u00B7\u00221-933\u0022/\u00B7\u00B7/LpvglhtZzsn\u00B7\u00B7/Lfbjfktxgrbgdf\u00B7\u00B7/VbgtkkljtpVxx\u00B7\u00B7/Tbdrnw\u00B7\u00B7/RPJ\u00B7\n",
|
||||
"duration_in_ms": 5900,
|
||||
"formatted_clips_media_count": null,
|
||||
"hide_remixing": false,
|
||||
"is_audio_automatically_attributed": false,
|
||||
"is_eligible_for_audio_effects": false,
|
||||
"is_eligible_for_vinyl_sticker": true,
|
||||
"is_explicit": false,
|
||||
"is_original_audio_download_eligible": false,
|
||||
"is_reuse_disabled": false,
|
||||
"is_xpost_from_fb": false,
|
||||
"music_canonical_id": null,
|
||||
"oa_owner_is_music_artist": false,
|
||||
"original_audio_subtype": "spvmmvm",
|
||||
"original_audio_title": "Nvskk dtcpxknbk",
|
||||
"original_media_id": "7211154431180240139",
|
||||
"progressive_download_url": "https://cdn.esempio/kk33cnh1t9rwwd57.mp4",
|
||||
"should_mute_audio": false,
|
||||
"time_created": 2618720927,
|
||||
"trend_rank": null,
|
||||
"previous_trend_rank": null,
|
||||
"overlap_duration_in_ms": 5900,
|
||||
"audio_asset_start_time_in_ms": 0,
|
||||
"derived_content_start_time_in_composition_in_ms": 0,
|
||||
"should_allow_audio_editing": false,
|
||||
"ig_artist": {
|
||||
"strong_id__": "3615921134",
|
||||
"pk": "3615921134",
|
||||
"pk_id": "3615921134",
|
||||
"id": "3615921134",
|
||||
"username": "zhlnznghsvglgmmh",
|
||||
"full_name": "Xrrwgthgj Gpfprwb",
|
||||
"is_private": false,
|
||||
"is_verified": true,
|
||||
"profile_pic_id": "4387790421367093288_3487371757",
|
||||
"profile_pic_url": "https://cdn.esempio/f728qmjp637n0647.jpg"
|
||||
},
|
||||
"audio_filter_infos": null,
|
||||
"audio_parts": [],
|
||||
"audio_parts_by_filter": [],
|
||||
"consumption_info": {
|
||||
"display_media_id": null,
|
||||
"is_bookmarked": false,
|
||||
"is_trending_in_clips": false,
|
||||
"should_mute_audio_reason": "",
|
||||
"should_mute_audio_reason_type": null,
|
||||
"inline_audio_label": null,
|
||||
"display_labels": null,
|
||||
"display_labels_with_translations": null,
|
||||
"user_notes": null
|
||||
},
|
||||
"xpost_fb_creator_info": null,
|
||||
"fb_downstream_use_xpost_metadata": {
|
||||
"downstream_use_xpost_deny_reason": "XJMH"
|
||||
}
|
||||
},
|
||||
"originality_info": null,
|
||||
"reels_on_the_rise_info": null,
|
||||
"reusable_text_attribute_string": null,
|
||||
"reusable_text_info": null,
|
||||
"show_achievements": false,
|
||||
"may_have_template_info": null,
|
||||
"viewer_interaction_settings": null,
|
||||
"shopping_info": null,
|
||||
"template_info": null
|
||||
},
|
||||
"hide_stickers_for_original_language": false,
|
||||
"like_count": 64,
|
||||
"fb_like_count": 13,
|
||||
"has_liked": false,
|
||||
"top_likers": [
|
||||
"dvtgnfcmcjq"
|
||||
],
|
||||
"facepile_top_likers": [
|
||||
{
|
||||
"strong_id__": "3851043056",
|
||||
"pk": "3851043056",
|
||||
"pk_id": "3851043056",
|
||||
"id": "3851043056",
|
||||
"username": "dvtgnfcmcjq",
|
||||
"full_name": "Jtfgfd Bkkmw",
|
||||
"is_private": false,
|
||||
"is_verified": false,
|
||||
"profile_pic_id": "6174566419957196250_8710701751",
|
||||
"profile_pic_url": "https://cdn.esempio/57n1d16w4k1j353f.jpg"
|
||||
}
|
||||
],
|
||||
"hidden_likes_string_variant": -1,
|
||||
"caption": {
|
||||
"strong_id__": "40021847552872166",
|
||||
"bit_flags": 0,
|
||||
"created_at": 1788817267,
|
||||
"created_at_utc": 7133613899,
|
||||
"did_report_as_spam": false,
|
||||
"is_ranked_comment": false,
|
||||
"pk": "40021847552872166",
|
||||
"share_enabled": false,
|
||||
"content_type": "comment",
|
||||
"media_id": "9222129690324603277",
|
||||
"status": "Active",
|
||||
"type": 1,
|
||||
"user_id": "215081405",
|
||||
"text": "Qwqwpb \u00B7\u00B7",
|
||||
"user": {
|
||||
"strong_id__": "215081405",
|
||||
"pk": "215081405",
|
||||
"pk_id": "215081405",
|
||||
"id": "215081405",
|
||||
"is_unpublished": false,
|
||||
"fbid_v2": "55370645405178029",
|
||||
"username": "dwvqbrgcjf",
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"is_private": false,
|
||||
"is_verified": false,
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/l77dd7l0fd384l17.jpg"
|
||||
},
|
||||
"is_covered": false,
|
||||
"private_reply_status": 0
|
||||
},
|
||||
"comment_count": 2,
|
||||
"can_view_more_preview_comments": false,
|
||||
"preview_comments": [],
|
||||
"comment_likes_enabled": true,
|
||||
"play_count": 1547,
|
||||
"ig_play_count": 929,
|
||||
"fb_play_count": 618,
|
||||
"shop_routing_user_id": null,
|
||||
"featured_products": [],
|
||||
"video_duration": 5.919000148773193,
|
||||
"is_dash_eligible": 1,
|
||||
"video_dash_manifest": "\u00B7?bxp fgdhnhx\u00B7\u00223.2\u0022 nqvdpphx\u00B7\u0022RCW-4\u0022?\u00B7\n\u00B7JRP kcldb\u00B7\u0022mnl:tkbn:slxv:dzzklk:xsp:5071\u0022 xhjbh:mrc\u00B7\u0022pfgz://gbl.w1.nbs/9401/DRCHjbsnh-rljkspqs\u0022 hnc:fcsswcVctjvxbk\u00B7\u0022qgc:zhwc:vggr:wbxfkx:srh:0506 BNZH-KFR.rvb\u0022 tzthfssh\u00B7\u0022mpx:chqr:zrfv:nwrbzpp:znrtp-mv-bhnngp:4898\u0022 jkbLhwxjkDsdz\u00B7\u0022QC7Q\u0022 mwqj\u00B7\u0022wrtpmp\u0022 zlcntXtlvfwkrfjwvHnchpssp\u00B7\u0022PR2.066339S\u0022 PWGdmhbgbsVkgjkqnks\u00B7\u00222790501876\u0022 PTXtlphwmvGgbjsjmffb\u00B7\u0022TlSvf25KMHFvV02kPXTmK1Bps0khP3QlJGrm2p2M9hzb1bV3t3xVxX7qB\u00B7ZN2KbzgbRWmGbZcXkg1xXw5PHFlZ3jM2vXb3lrqrWZVfnSFGMjmH5pjq4qJMWqF068ZfJvJ1Z9VQmwXhpSQZnnmFVmDW8hzDqmqGBBBmQJRsRVFT\u00B7\u00B7\u0022\u00B7\u00B7Kxnftp dd\u00B7\u00225\u0022 fpkcvxsb\u00B7\u0022XT6.568319G\u0022\u00B7\u00B7FfwzgmjljtQrd nw\u00B7\u00226\u0022 xdvwwqjVjsc\u00B7\u0022cznms\u0022 jcqgwgflhmNxgzgrnmx\u00B7\u0022rqrb\u0022 mfh\u00B7\u00223:32\u0022 QFCwccmvpGljvcpDplrjnmbzwHqn\u00B7\u0022391:23.1\u0022\u00B7\u00B7Lgmxfmdblgtsxz mg\u00B7\u00222072495724225125w\u0022 wwbqvpfbf\u00B7\u0022068578\u0022 dcddzm\u00B7\u0022sr39.23.94.78.63.68.85.94.54\u0022 rgffJclm\u00B7\u0022jxxdr/ws3\u0022 qgr\u00B7\u00228:7\u0022 RJGlfjwmfcFfs\u00B7\u0022qgtd_lm4-tndjk-vxl2_338j\u0022 QDBbpkdjzPnfjtw\u00B7\u0022388834\u0022 HFRbprjjznNppvhwtgzdVvc\u00B7\u00227:899,087:77.8,698:08.6,509:11.8,0173:52.3,2389:62.2\u0022 XTNnnpbcgvRpbdnrflmlWlrFkdrlmpqgkPwrrq\u00B7\u0022dfjd\u0022 FHBzwwbdtgQzmsqghhtxQjzrm\u00B7\u00227:037,999:82.3,127:93.1,733:56.5,4575:00.3,6844:12.9\u0022 RKLfnTjrsqsHlbn\u00B7\u0022\u0022 vkzcw\u00B7\u0022116\u0022 rjbjmg\u00B7\u0022378\u0022 xrnbxLwtl\u00B7\u002200691/004\u0022 BZQrpvgwcHjlms\u00B7\u0022rk\u0022 QCBvjljlsHwlzm\u00B7\u0022105p\u0022\u00B7\u00B7LqfhTHL\u00B7wmkjc://nxnfbkvk-xfr1-6.bfrgzgmjcfms.fhz/h8/j/x7/m2/q467/QNFSlPCwVmr3t5q_NjwjGLFzkwcKNC6CBz2X6b-gfc1dmzVdcLL17N8Qz0MfP2wGqscPNBMVmst5XDzV6QGxGm1QkPtMwMbJzXMJjzdfpH7D7s.xb9?_xl_wqh\u00B7579\u0026vlt;_ln_jqm\u00B75ld419\u0026wcr;_cj_wn\u00B7hbtqmtbb-fbz5-0.cgsglvthksxb.xpz\u0026fbt;_pd_zvs\u00B7TldglJzWhxNF8lTtnMXgJ4v\u0026bwr;lgl\u00B7cgT5MH3wh9HjT9SxNrG0FvjnTWrdvtKnBdPbrRJfGdNtFPGcKqBtw0zsjdR4QKSlk1klVRfmrqPzKgGltLQxJpBvBBZlL1kfTzvldShsSVCkrBkghGZdJ6NnS9TmxV8gSWP8LCQ7HqS6SrLrLgqsSKZ8NLXlhTqqxhNcbtFqPZD9ZzvpFvgprLJ6N2Pqx8H4S5zdFgxwTJr8DmHfDVp0DSP6JpS7VLVvx0KkfP4pM3TsCNK8tlV5XSVbCbKmD3BdNWBqw0QlhHGfJgQsBWM8LFWgmXMrxZnwhf8bRzw4DLFbzPDqGJMhWzs3TvQ5HLKsXnRshSmzmv7ht3QqR4PsQsQ7n4ndpH%3W%5D\u0026fpv;knf\u00B719-5\u0026qlt;_pk_vjf\u00B7vRZ-xW72WhlFrx7N9c3LxH\u0026ppg;_fx_jj\u00B71b38z\u0026nzd;_mz_qs\u00B735\u0026vmg;hs\u00B770_GKXfPFBBzvNRBKkhVn2-wbGF0wnQ8fwdQVBtqlVsNHDVDN\u0026fch;hj\u00B72KBMHS36\u00B7/ZcxpXGN\u00B7\u00B7ZjcrvsjRvjr xqptjPtttr\u00B7\u0022579-154\u0022 gfjzjbkvj\u00B7\u002296708\u0022 ZHBdqstjlZbxpnbsdZtxjj\u00B7\u0022712-44180\u0022 LVPrzlrxnKbvzcgdqFghclhfn\u00B7\u00220076\u0022 ZKCfwmmdbHrsnqnkfNgsxx\u00B7\u0022317-065318\u0022 QTJrjkpDsnlnmgThcmd\u00B7\u0022553-680009\u0022 TPGxgnxHgjzswxSppwfpmn\u00B7\u00223152\u0022 SFZnnhqbLzccqxlFqqzn\u00B7\u0022303182-344504\u0022 GKTljbfxhgDgqjpwfGlqnk\u00B7\u0022118-472377\u0022 ZPVtsbhdzxGcfbwjbNvjbvnpk\u00B7\u00227004\u0022\u00B7\u00B7Nxvkfqvhjmqwzw mcxsl\u00B7\u00227-580\u0022/\u00B7\u00B7/DxzggthWvpr\u00B7\u00B7/Cwkgtrwwtwfrrx\u00B7\u00B7Djzcbnsxxpbscf wp\u00B7\u00224559668956075875r\u0022 lfkdlrspk\u00B7\u00224840764\u0022 cqbhnv\u00B7\u0022rc95.04.95.89.72.91.09.82.99\u0022 pztxTvjz\u00B7\u0022dtstp/jp3\u0022 nqq\u00B7\u00227:9\u0022 MHWstfgbxrZcr\u00B7\u0022qxpp_qv6-zgzmj-gtq6_932c\u0022 VHSzcsrgfNpgqwm\u00B7\u00221305635\u0022 ZLNczfntftJwpxzflrdxPmk\u00B7\u00225:496,146:11,187:35.5,716:49.8,5177:64.4,6062:57.6\u0022 WFHcmqqdqkBxrpnhbkrtLjbKwhqvdqmcfZbktf\u00B7\u0022jcjj\u0022 GTStrpmxbkKxlcwsmccnSnzfz\u00B7\u00222:328,067:94,839:60.4,071:34.8,7745:31.1,6322:63.8\u0022 WZQzcQgsxwqSplx\u00B7\u0022\u0022 xxlws\u00B7\u0022783\u0022 fwfkvh\u00B7\u0022380\u0022 hdvkwTsmh\u00B7\u002245054/163\u0022 XHCxzjwxkQnxzf\u00B7\u0022mf\u0022 PKNtcgnndBhzxd\u00B7\u0022471j\u0022\u00B7\u00B7XctbPMS\u00B7psskz://snjmzxxw-fkm7-7.drtbrbzrfrxs.hjh/q2/x/b9/d6/b419/RGC5Zbt9NPsrz9Gt2FggsDmPdw78stTMzkRTNkb6V4mNGkhmG53Zd2JPfhg8vlvB5RVwLTSdSSHhBlCVwNP3840vTzp8ZkZHDNTncrHBSddrSf.vp3?_xs_kmd\u00B7672\u0026pfj;_dk_nws\u00B72qm860\u0026wsp;_vx_cr\u00B7bwsjvsvv-bjj8-2.zgvpmlwzmxqk.cgb\u0026jdq;_gk_ngh\u00B7BS5zmjwbmcRM3cBbhWddGlr\u0026ngj;klj\u00B7snB5FB9dz4BvM1WtCnK8NmjmWLdvsjHcPtRssSJzPjFwTZBfKtXns5bfshF9KMGmq2gdQPhcvgTtFWVnvHRmFzFlQKRwW7kmVfmdpDxpMFPsrKgnvRLbK2WmK7PttK2xVKR3XTW0HrW1ZnPpFnfpZBN4SCGbfQgdnrLvmpQjMDH0QvfnJxpcwWX6N5Lht0R1K6tzGjxrKBc7NrSqCFr5HVJ4SqQ3TZGfk0BhrB2fK4LbTVS0dsG9MBHnZvHdJ9PsHFGnn9NzbGQjFbJvBSL7FJHnrMMckQlnmp3zPnx5XGNmtGZjHJBnWmbzDDZ9HMn1STD2scrjGN4hz095pmFnJgkgx8c7Nt7%1F\u0026pxs;qsp\u00B773-0\u0026bfh;_cd_nkl\u00B7fQV-rK63GtpRsm6S1l2BcR\u0026wgr;_mh_bw\u00B78h40c\u0026dbr;_jr_tf\u00B740\u0026gbt;sd\u00B784_FTDcl1ZTzZXgpWFhSHhb_drClZNQrLine truncated
|
||||
"user": {
|
||||
"strong_id__": "215081405",
|
||||
"fbid_v2": "55370645405178029",
|
||||
"feed_post_reshare_disabled": false,
|
||||
"id": "215081405",
|
||||
"is_unpublished": false,
|
||||
"pk": "215081405",
|
||||
"pk_id": "215081405",
|
||||
"third_party_downloads_enabled": 1,
|
||||
"account_type": 2,
|
||||
"can_see_quiet_post_attribution": true,
|
||||
"account_badges": [],
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"has_anonymous_profile_picture": false,
|
||||
"is_favorite": false,
|
||||
"is_private": false,
|
||||
"is_ring_creator": false,
|
||||
"show_ring_award": false,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false,
|
||||
"is_auto_detected": false,
|
||||
"is_manually_enabled": false
|
||||
},
|
||||
"is_verified": false,
|
||||
"show_account_transparency_details": true,
|
||||
"transparency_product_enabled": false,
|
||||
"username": "dwvqbrgcjf",
|
||||
"eligible_for_text_app_activation_badge": false,
|
||||
"user_activation_info": {},
|
||||
"fan_club_info": {
|
||||
"autosave_to_exclusive_highlight": null,
|
||||
"connected_member_count": null,
|
||||
"fan_club_id": null,
|
||||
"fan_club_name": null,
|
||||
"has_created_ssc": null,
|
||||
"has_enough_subscribers_for_ssc": null,
|
||||
"is_fan_club_gifting_eligible": null,
|
||||
"is_fan_club_referral_eligible": null,
|
||||
"is_free_trial_eligible": null,
|
||||
"largest_public_bc_id": null,
|
||||
"subscriber_count": null,
|
||||
"should_show_playlists_in_profile_tab": null,
|
||||
"fan_consideration_page_revamp_eligiblity": null
|
||||
},
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"is_bestie": false,
|
||||
"is_feed_favorite": false,
|
||||
"is_private": false,
|
||||
"is_restricted": false,
|
||||
"followed_by": false,
|
||||
"is_muting_reel": false
|
||||
},
|
||||
"hd_profile_pic_url_info": {
|
||||
"height": 960,
|
||||
"url": "https://cdn.esempio/4c74479rv6zw0pp5.jpg",
|
||||
"width": 960
|
||||
},
|
||||
"hd_profile_pic_versions": [
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/q5pz0293nmsd9nz9.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/2b806015288zl984.jpg",
|
||||
"width": 640
|
||||
}
|
||||
],
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/l77dd7l0fd384l17.jpg",
|
||||
"is_embeds_disabled": false,
|
||||
"text_post_app_is_private": false,
|
||||
"is_active_on_text_post_app": true,
|
||||
"latest_reel_media": 1792602930
|
||||
},
|
||||
"owner": {
|
||||
"strong_id__": "215081405",
|
||||
"fbid_v2": "55370645405178029",
|
||||
"feed_post_reshare_disabled": false,
|
||||
"id": "215081405",
|
||||
"is_unpublished": false,
|
||||
"pk": "215081405",
|
||||
"pk_id": "215081405",
|
||||
"third_party_downloads_enabled": 1,
|
||||
"account_type": 2,
|
||||
"can_see_quiet_post_attribution": true,
|
||||
"account_badges": [],
|
||||
"full_name": "Gqqdcr Vkrmp",
|
||||
"has_anonymous_profile_picture": false,
|
||||
"is_favorite": false,
|
||||
"is_private": false,
|
||||
"is_ring_creator": false,
|
||||
"show_ring_award": false,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false,
|
||||
"is_auto_detected": false,
|
||||
"is_manually_enabled": false
|
||||
},
|
||||
"is_verified": false,
|
||||
"show_account_transparency_details": true,
|
||||
"transparency_product_enabled": false,
|
||||
"username": "dwvqbrgcjf",
|
||||
"eligible_for_text_app_activation_badge": false,
|
||||
"user_activation_info": {},
|
||||
"fan_club_info": {
|
||||
"autosave_to_exclusive_highlight": null,
|
||||
"connected_member_count": null,
|
||||
"fan_club_id": null,
|
||||
"fan_club_name": null,
|
||||
"has_created_ssc": null,
|
||||
"has_enough_subscribers_for_ssc": null,
|
||||
"is_fan_club_gifting_eligible": null,
|
||||
"is_fan_club_referral_eligible": null,
|
||||
"is_free_trial_eligible": null,
|
||||
"largest_public_bc_id": null,
|
||||
"subscriber_count": null,
|
||||
"should_show_playlists_in_profile_tab": null,
|
||||
"fan_consideration_page_revamp_eligiblity": null
|
||||
},
|
||||
"friendship_status": {
|
||||
"following": false,
|
||||
"is_bestie": false,
|
||||
"is_feed_favorite": false,
|
||||
"is_private": false,
|
||||
"is_restricted": false,
|
||||
"followed_by": false,
|
||||
"is_muting_reel": false
|
||||
},
|
||||
"hd_profile_pic_url_info": {
|
||||
"height": 960,
|
||||
"url": "https://cdn.esempio/4c74479rv6zw0pp5.jpg",
|
||||
"width": 960
|
||||
},
|
||||
"hd_profile_pic_versions": [
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/q5pz0293nmsd9nz9.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/2b806015288zl984.jpg",
|
||||
"width": 640
|
||||
}
|
||||
],
|
||||
"profile_pic_id": "6460827721051748069_181896617",
|
||||
"profile_pic_url": "https://cdn.esempio/l77dd7l0fd384l17.jpg",
|
||||
"is_embeds_disabled": false,
|
||||
"text_post_app_is_private": false,
|
||||
"is_active_on_text_post_app": true,
|
||||
"latest_reel_media": 1792602930
|
||||
},
|
||||
"community_notes_info": {
|
||||
"has_viewer_submitted_note": false,
|
||||
"note_submission_disabled": false,
|
||||
"enable_submission_friction": false,
|
||||
"is_eligible_for_request_a_note": true
|
||||
},
|
||||
"has_high_risk_gen_ai_inform_treatment": false,
|
||||
"caption_is_edited": false,
|
||||
"code": "NkNCTkwnbp8",
|
||||
"device_timestamp": 1868754255900570,
|
||||
"enable_media_notes_production": true,
|
||||
"filter_type": 0,
|
||||
"has_views_fetching": true,
|
||||
"is_post_live_clips_media": false,
|
||||
"is_eligible_for_rta": false,
|
||||
"like_and_view_counts_disabled": false,
|
||||
"is_meta_ai_invocation_blocked_by_author": false,
|
||||
"tya_media_related_topics": [],
|
||||
"teen_project_info": null,
|
||||
"is_educational": null,
|
||||
"meta_ai_suggested_prompts": [],
|
||||
"is_eligible_for_poe_premium": false,
|
||||
"is_longform_player_eligible": false,
|
||||
"collaborator_edit_eligibility": false,
|
||||
"is_organic_product_tagging_eligible": true,
|
||||
"can_viewer_reshare": true,
|
||||
"has_shared_to_fb": 0,
|
||||
"media_reposter_bottomsheet_enabled": false,
|
||||
"can_viewer_save": true,
|
||||
"is_comments_gif_composer_enabled": true,
|
||||
"translated_langs_for_autodub": []
|
||||
}
|
||||
],
|
||||
"auto_load_more_enabled": false,
|
||||
"status": "ok"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,607 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/34m6543g18c0k202",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:39:03Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_api__v1__feed__reels_media__connection": {
|
||||
"edges": [
|
||||
{
|
||||
"node": {
|
||||
"id": "mtmlprbdv:62008803167428297",
|
||||
"items": [
|
||||
{
|
||||
"pk": "9704657468886935049",
|
||||
"id": "0224021262026182334_702528115",
|
||||
"has_audio": false,
|
||||
"story_music_stickers": null,
|
||||
"ai_label_info": null,
|
||||
"carousel_media": null,
|
||||
"code": "RzZX1JHhJNG",
|
||||
"image_versions2": {
|
||||
"candidates": [
|
||||
{
|
||||
"height": 1276,
|
||||
"url": "https://cdn.esempio/3m6x3548q708c84w.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 1134,
|
||||
"url": "https://cdn.esempio/324647f1l7pt1n80.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 851,
|
||||
"url": "https://cdn.esempio/329m6914172rf1kp.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 567,
|
||||
"url": "https://cdn.esempio/hc4g542p6d2s1t19.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 425,
|
||||
"url": "https://cdn.esempio/p88051bs2w1412mc.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/154sg73t10wnj81f.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/154sg73t10wnj81f.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/s864785cwb5gkm08.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/hbgq9m2wt9x946p5.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/b5l52zm8f2k79z34.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 240,
|
||||
"url": "https://cdn.esempio/l04w59br24162l62.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 150,
|
||||
"url": "https://cdn.esempio/d53475r2kg9z9jg3.jpg",
|
||||
"width": 150
|
||||
}
|
||||
]
|
||||
},
|
||||
"original_width": 640,
|
||||
"original_height": 1136,
|
||||
"taken_at": 1535615772,
|
||||
"is_dash_eligible": 1,
|
||||
"number_of_qualities": 2,
|
||||
"video_dash_manifest": "\u00B7?wwb qkkqkwc\u00B7\u00223.8\u0022?\u00B7\n\u00B7VSF vnnzs\u00B7\u0022bjz:ltmg:xqfv:tfslbk:wqt:7521\u0022 ndhGptpdcKlwb\u00B7\u0022PH0.101P\u0022 xgqg\u00B7\u0022nqmwjc\u0022 tjxfpWfdxgrpxjtzdWnqhrbpd\u00B7\u0022PD5W0G3.607P\u0022 tfmQcxvznrDqxcxxgc\u00B7\u0022SR3Q3C8.137N\u0022 kfmqnvxp\u00B7\u0022xwk:nznw:wkld:flzhklb:knmqj-dv-chwsmj:7373,pwzd://mmvvfp.pvj/wsckzctcxb/fpcb905\u0022 HNNnxkcgqsHnscssspr\u00B7\u00224162876904\u0022 PHPljrrqtjCzmdkqcnwk\u00B7\u0022Qn7wm54JZTTfD11mCQFdP2Dxt0TgvF3hXPfJdW\u00B7QhKjQZpWFd2XSjmVTNknhJLRxvKlcrTDch9B1C4Dlfj0bDKfjHdBbx40phSB2QbgJDBpwrTDhXJ7lgMlfpVQMzKQGZRVCHMqCKx3ZW1JGQKQLRSPPDHLD\u0022\u00B7\u00B7Mbdsvw wmpcbspc\u00B7\u0022DS8D5C1.713C\u0022\u00B7\u00B7WqpndndcmjZzc hnfgwjqQwmwslndf\u00B7\u0022cjmp\u0022 ltzVzkvn\u00B7\u0022099\u0022 jdqMbdtlr\u00B7\u00229292\u0022 cfqSchlcBspk\u00B7\u002297\u0022 dzs\u00B7\u00229:89\u0022 ljlh\u00B7\u0022hcl\u0022 gxqjmmclrnJqxlqcgbj\u00B7\u0022zsfc\u0022 sfwgtgxsvtXcbzlzKksxJWR\u00B7\u00223\u0022 mf\u00B7\u00225\u0022\u00B7\u00B7Nkrfrcdpkntgrq gg\u00B7\u0022482151444703656c\u0022 pfdtZrsv\u00B7\u0022kptzp/fj2\u0022 ncljpw\u00B7\u0022ggt7.5V806Z\u0022 mkntl\u00B7\u0022124\u0022 ndzmsd\u00B7\u00229577\u0022 drzjlGzss\u00B7\u002242\u0022 tkl\u00B7\u00227:1\u0022 vjfpcHghrNHR\u00B7\u00228\u0022 xlfsdcffb\u00B7\u0022091868\u0022 ZJKpgphhjgTcc\u00B7\u0022lvhw_vflmtbcz_9_r6\u0022 WKNhjcrljBglkms\u00B7\u0022078865\u0022 QLLftNwmggsJkbj\u00B7\u0022\u0022 CPHdsvbgnQhphm\u00B7\u0022rd\u0022 FJHmshfqrJlnfl\u00B7\u0022648k\u0022\u00B7\u00B7KjzwNHH\u00B7xcbmp://bzmhpgpz-kws4-4.dfwcpflnwjwm.lhz/c9/j/c21/q1/h08/LWRQCv4JT9WSTdZvcTTmKdCD_XtqxgVfwgp26mfkDF_pTdXG8T23gBf43RZtPv9H9CMsKjXv9Pz5SXnJc8-ZqFPHZKV6Td3ZsFGrnMb.fq2?_rv_kts\u00B7608\u0026mqz;_qf_mrz\u00B78kd078\u0026wdj;_mw_gg\u00B7zhbcmdgb-nml3-9.cfnkflsntnxc.jbx\u0026qqf;_vs_wmm\u00B7DtCLQ3bgm-ZL9jXwzXLN2kX\u0026ffx;xlv\u00B7xzB9VG3qf6KkH6VwBgZ5HgdqVZrsnkSbHwR3c8F3Xxwsl0n3MCSqPkPqn7ngMsQxCXfpzdSgDV39JRNbFcFlKSQxC2wkHwrzlBqrBVLmgCkbkCZcB2DfL0QhlN4fRPN5QPZ4XxJ5MtJhLwdvGQZ2MGVbtQwqsxSdqhRrBVP9BmthVptfhJD1Z4Xmx2G7M5czZjt6CFLrMMB7HDD2MTD2XJQxJwKjc1R9D8QmPS4sSBthKtglGBtsTGD2tJ82p4JtMRVtB2xnCgtrHXwkCzplNCLdRPScx99tzgD7LLbmZmr6blQ8CWK5FlD7GTG9NPX9wktpJB6hd764vfFmXjlph2r6Tk8%2Z\u0026wkt;bjz\u00B739-8\u0026hcx;_zv_klp\u00B70V8ndm4BsRzTv4LT4MWJpw\u0026tpt;_hx_lt\u00B75fsgx\u0026chb;_fq_tn\u00B723\u0026bhg;ls\u00B742_SHGczhCzFRp5Nvrk2VpPffQ9QkQwNGHqlkG7cBPzsHHrqX\u0026djp;sd\u00B73QNLR7Q2\u00B7/VlfhDZR\u00B7\u00B7MlcvxhnDllb jtwvhFmtpcQptwp\u00B7\u0022fsln\u0022 qsvjmWknpc\u00B7\u0022737-351\u0022 DZXwcdwDjnlfrdLmxnd\u00B7\u0022887-144580\u0022 JZQwqjdTndwkngRgwmgbkx\u00B7\u00229653\u0022 MGSwctrghbGljmlqfCsfgb\u00B7\u0022062-392591\u0022 WTGfwtgsxnGvclxnvRmxgpplc\u00B7\u00225055\u0022\u00B7\u00B7Fmtgdrkcmmrmrv fbppn\u00B7\u00229-710\u0022/\u00B7\u00B7/PsrwkmlSlfw\u00B7\u00B7/Ngrgknqmkblkpl\u00B7\u00B7Zvqcjchcztfxdx zh\u00B7\u0022666047318082679m\u0022 gscxrrrxz\u00B7\u002250080\u0022 mjmhgx\u00B7\u0022xfx1.4t787g\u0022 wpwbDkjg\u00B7\u0022pzlfh/rq1\u0022 bjm\u00B7\u0022536:139\u0022 SQLqjvlkxvMkc\u00B7\u0022whgj_cpfrqhcd_5_n5\u0022 GNRqcbqkfPjcrrx\u00B7\u002237317\u0022 JRQpvmbgmkZgdjcdwsbwQxp\u00B7\u00224:656,651:61.2,275:70,786:13.2\u0022 VVXrmljbdhLrwchgjsjsZzxRsgggwzgfkMqwfj\u00B7\u0022zgmd\u0022 KNKddbwddbPnlwpjzfbvLlmqf\u00B7\u00224:530,971:07.5,097:38.7,285:46.6\u0022 DSCbmTlxgczPbbf\u00B7\u0022\u0022 rfrvw\u00B7\u0022094\u0022 xcwnmz\u00B7\u0022289\u0022 nlgngJjwn\u00B7\u002273760/418\u0022 PFMtbjxplMdnrj\u00B7\u0022wc\u0022 CZMndlnlzXmhnt\u00B7\u0022294l\u0022\u00B7\u00B7RtprJZQ\u00B7spknw://vmprdgtb-cvh4-9.ccmtfshfkcbw.zhw/s3/h/m22/j3/g82/KZZHsDth05NvXL5JgKqFvrn4V7mhChzkqLgxpq5Rkjp0lBVmcgsTqRxf8GqWrK2N9QxVsqSSw9Wt6k2q0KKZkhSSfP-Lm2r4vdl2FL9.pd8?_tr_hgl\u00B7217\u0026zdx;_hv_jlg\u00B73tz091\u0026vtd;_pm_tc\u00B7bhdzljjm-dml0-2.jjbhktwdwmrk.gdj\u0026zlc;_qm_nwk\u00B7rJ-9VVf8F3vD8sFxrSsZdMh\u0026knt;vtn\u00B7vqL7FG7pr8KzL4ZwLdD5RtsmFHcsxbJhBhP9z2H4Qvxzd1l6KBQfFlHbx8zwVmHsPNdlptSkRf45LDTvLwMbRMKtS5hwNlwbgRhnSCThjRrrsHJmV8KmL3RnxW7gPXK9QWT9NpK4MnLqHsmvSTS2LWKsvQtdzbHstmChFCC5XsvqBrpmvHQ2P9Djv0G6D3mnSfx7HQWrWVQ8FBQ4QJC2RVQlLjVcw8W9J0ZsVC5lVCwgQpqlXFxdSWR2qQ30s0SsXJDzM8xfZjwtVTlrKfbmPCMrSHNbt92bqvN5ZZjmMzl9ntK9BMZ7Tds4JhhbXsQgdWjrbx8dq1KpM3LfFvF4x5zwbH%7D%1K\u0026nmp;bzz\u00B762-0\u0026rqq;_zl_mdm\u00B79J0dch0NtMdWf5BT7XNDng\u0026zvt;_cz_wh\u00B71xtnf\u0026lgg;_qn_kf\u00B735\u0026pnc;zb\u00B734_PJWgPv8hBCWMDpZN2W8M2DV6NTZqVMgXP15g95Jx0qjsLm\u0026nnf;rq\u00B74PJPB5J8\u00B7/BrgnGCG\u00B7\u00B7WqzkppfDhtx vdgcdMpjnn\u00B7\u0022031-464\u0022 qpncssclq\u00B7\u002294893\u0022 JRKjwspmdKzhzvqdgJvsqx\u00B7\u0022779-76519\u0022 ZDFfphjKtmzhnqKndxp\u00B7\u0022787-34921\u0022 JDQxcwpNvqqwwcSgrxrzcb\u00B7\u00226974\u0022 NSRjvrjzpjKwgqrflQxhsw\u00B7\u0022725-70931\u0022 HQNjnmctswKqdhzglSxkdqlrl\u00B7\u00221843\u0022\u00B7\u00B7Mbxqhlgpsqjrsp vvnrc\u00B7\u00223-428\u0022/\u00B7\u00B7/XdxwztmGpxk\u00B7\u00B7/Lgmnbcsmvnfxtc\u00B7\u00B7/VcljpsfcgnWtb\u00B7\u00B7/Fnsgxc\Line truncated
|
||||
"video_versions": [
|
||||
{
|
||||
"type": 101,
|
||||
"url": "https://cdn.esempio/w6plz52z5749r9g8.mp4"
|
||||
},
|
||||
{
|
||||
"type": 102,
|
||||
"url": "https://cdn.esempio/w6plz52z5749r9g8.mp4"
|
||||
},
|
||||
{
|
||||
"type": 103,
|
||||
"url": "https://cdn.esempio/w6plz52z5749r9g8.mp4"
|
||||
}
|
||||
],
|
||||
"media_type": 2,
|
||||
"visual_comment_reply_sticker_info": null,
|
||||
"story_bloks_stickers": null,
|
||||
"story_hashtags": null,
|
||||
"story_locations": null,
|
||||
"text_post_share_to_ig_story_stickers": null,
|
||||
"story_countdowns": null,
|
||||
"story_questions": null,
|
||||
"story_sliders": null,
|
||||
"link": null,
|
||||
"reel_media_background": null,
|
||||
"video_duration": 5,
|
||||
"custom_list_info": null,
|
||||
"is_story_edited": false,
|
||||
"product_type": "story",
|
||||
"reshared_story_media_author": null,
|
||||
"story_app_attribution": null,
|
||||
"audience": null,
|
||||
"has_liked": false,
|
||||
"viewer_count": null,
|
||||
"viewers": [],
|
||||
"can_reshare": true,
|
||||
"user": {
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"is_ai_user": null,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false
|
||||
},
|
||||
"instagram_pk": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642"
|
||||
},
|
||||
"inventory_source": null,
|
||||
"carousel_media_count": null,
|
||||
"media_overlay_info": null,
|
||||
"caption": null,
|
||||
"accessibility_caption": null,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxxxxxx7xxx7xxx7xxx7xxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxx7xxx7xxxxxxxxxxx7xxxxxxxxxxx7xxx7xxxxxxxxxxxxxxxxxxxxxxx7xxxxx7xxx7x7xxx7xxxxxxx7xxxxxxx7xxx7xxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxx\u00B7\u00B7",
|
||||
"story_link_stickers": null,
|
||||
"story_bloks_tappables": null,
|
||||
"story_feed_media": null,
|
||||
"story_cta": null,
|
||||
"preview": null,
|
||||
"is_paid_partnership": false,
|
||||
"sponsor_tags": null,
|
||||
"wearable_attribution_info": null,
|
||||
"has_translation": false,
|
||||
"boosted_status": null,
|
||||
"can_see_insights_as_brand": false,
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"can_viewer_reshare": null,
|
||||
"expiring_at": 1535702172,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null
|
||||
},
|
||||
"can_reply": true,
|
||||
"__typename": "JGPZxtzzMglf"
|
||||
},
|
||||
{
|
||||
"pk": "0136776105441301518",
|
||||
"id": "1919041622766888881_764140925",
|
||||
"has_audio": null,
|
||||
"story_music_stickers": null,
|
||||
"ai_label_info": null,
|
||||
"carousel_media": null,
|
||||
"code": "Pf_jnh4jjGx",
|
||||
"image_versions2": {
|
||||
"candidates": [
|
||||
{
|
||||
"height": 1278,
|
||||
"url": "https://cdn.esempio/64277767bs4g22l3.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 1136,
|
||||
"url": "https://cdn.esempio/1l76q9n05v433q8z.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 852,
|
||||
"url": "https://cdn.esempio/tv49354p66z3fb11.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 568,
|
||||
"url": "https://cdn.esempio/h4576h51s0k2qg8c.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 426,
|
||||
"url": "https://cdn.esempio/568w418p1jmzlxr9.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/8f89j8p2b9109j5t.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 720,
|
||||
"url": "https://cdn.esempio/8f89j8p2b9109j5t.jpg",
|
||||
"width": 720
|
||||
},
|
||||
{
|
||||
"height": 640,
|
||||
"url": "https://cdn.esempio/q046570l2m6860j3.jpg",
|
||||
"width": 640
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/458xvr038d7nr57d.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/lmjkwb9v6qq0xnpc.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 240,
|
||||
"url": "https://cdn.esempio/785x3klnzc3l6240.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 150,
|
||||
"url": "https://cdn.esempio/p8018t8149r793v6.jpg",
|
||||
"width": 150
|
||||
}
|
||||
]
|
||||
},
|
||||
"original_width": 720,
|
||||
"original_height": 1278,
|
||||
"taken_at": 1537547068,
|
||||
"is_dash_eligible": null,
|
||||
"number_of_qualities": null,
|
||||
"video_dash_manifest": null,
|
||||
"video_versions": null,
|
||||
"media_type": 1,
|
||||
"visual_comment_reply_sticker_info": null,
|
||||
"story_bloks_stickers": null,
|
||||
"story_hashtags": null,
|
||||
"story_locations": [
|
||||
{
|
||||
"x": 0.5,
|
||||
"y": 9.78327953178594,
|
||||
"width": 0.875,
|
||||
"height": 0.097790492957746,
|
||||
"rotation": 0,
|
||||
"location": {
|
||||
"pk": 348843475
|
||||
},
|
||||
"id": "08921590880713343"
|
||||
}
|
||||
],
|
||||
"text_post_share_to_ig_story_stickers": null,
|
||||
"story_countdowns": null,
|
||||
"story_questions": null,
|
||||
"story_sliders": null,
|
||||
"link": null,
|
||||
"reel_media_background": null,
|
||||
"video_duration": null,
|
||||
"custom_list_info": null,
|
||||
"is_story_edited": false,
|
||||
"product_type": "story",
|
||||
"reshared_story_media_author": null,
|
||||
"story_app_attribution": null,
|
||||
"audience": null,
|
||||
"has_liked": false,
|
||||
"viewer_count": null,
|
||||
"viewers": [],
|
||||
"can_reshare": true,
|
||||
"user": {
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"is_ai_user": null,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false
|
||||
},
|
||||
"instagram_pk": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642"
|
||||
},
|
||||
"inventory_source": null,
|
||||
"carousel_media_count": null,
|
||||
"media_overlay_info": null,
|
||||
"caption": null,
|
||||
"accessibility_caption": null,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxxxxxx7xxx7xxx7xxx7xxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxx7xxx7xxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxxx7xxx7xxx7xxxxxxxxx7x7xxxxxxx7xxxxxxx7xxxxxxx7xxx7xxxxxxxxxxx7xxxxxxxxxx\u00B7\u00B7",
|
||||
"story_link_stickers": null,
|
||||
"story_bloks_tappables": null,
|
||||
"story_feed_media": null,
|
||||
"story_cta": null,
|
||||
"preview": null,
|
||||
"is_paid_partnership": false,
|
||||
"sponsor_tags": null,
|
||||
"wearable_attribution_info": null,
|
||||
"has_translation": false,
|
||||
"boosted_status": null,
|
||||
"can_see_insights_as_brand": false,
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"can_viewer_reshare": null,
|
||||
"expiring_at": 1537633468,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null
|
||||
},
|
||||
"can_reply": true,
|
||||
"__typename": "JGPZxtzzMglf"
|
||||
},
|
||||
{
|
||||
"pk": "3134868844340144332",
|
||||
"id": "7652716589938419222_411682419",
|
||||
"has_audio": true,
|
||||
"story_music_stickers": null,
|
||||
"ai_label_info": null,
|
||||
"carousel_media": null,
|
||||
"code": "G-NPTmQzpkD",
|
||||
"image_versions2": {
|
||||
"candidates": [
|
||||
{
|
||||
"height": 916,
|
||||
"url": "https://cdn.esempio/fs6632cb872701wc.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 611,
|
||||
"url": "https://cdn.esempio/b5244m81x5d26316.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 458,
|
||||
"url": "https://cdn.esempio/p41f04n0vt13070h.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 480,
|
||||
"url": "https://cdn.esempio/65912pv25ms50257.jpg",
|
||||
"width": 480
|
||||
},
|
||||
{
|
||||
"height": 320,
|
||||
"url": "https://cdn.esempio/n246l4s386791637.jpg",
|
||||
"width": 320
|
||||
},
|
||||
{
|
||||
"height": 240,
|
||||
"url": "https://cdn.esempio/r7010z76j203fm48.jpg",
|
||||
"width": 240
|
||||
},
|
||||
{
|
||||
"height": 150,
|
||||
"url": "https://cdn.esempio/p20352l4w88k9715.jpg",
|
||||
"width": 150
|
||||
}
|
||||
]
|
||||
},
|
||||
"original_width": 480,
|
||||
"original_height": 916,
|
||||
"taken_at": 1585040589,
|
||||
"is_dash_eligible": 1,
|
||||
"number_of_qualities": 2,
|
||||
"video_dash_manifest": "\u00B7?tdn rjmxjmk\u00B7\u00225.8\u0022?\u00B7\n\u00B7RPJ mfzdh\u00B7\u0022rgh:qrhp:szsl:bdspdk:wll:1069\u0022 rvkKgkznjHkpq\u00B7\u0022KR9.413B\u0022 tpvl\u00B7\u0022gltczb\u0022 frvmtQnmxpgxmmwfbWgcbdmhv\u00B7\u0022FQ6W8B9.433T\u0022 jpvWxlhhshXkmtwhdk\u00B7\u0022HR9L9S8.805C\u0022 dltcmrdt\u00B7\u0022kzq:dvjf:lkpx:bngkmjb:wbzjb-dc-wwztzh:7351,qzdw://bgvkrp.dbd/pmdhkrfvss/jpkl074\u0022 BVKnhnbnqqDdmvhkjpg\u00B7\u00226467737323\u0022 PJQqgwkgrlFcjprltgkn\u00B7\u0022Fs7gr87DHWCsS96rBLGnT3Skv3PwvK6dLJl5dbxP2/0SNKLx2/8mxt8Djqlkb2Gf/DXqBFDlFQQfG7Ncq9SmvD9nJ2V3LDbbVsqSTHcsdKWwGZ3ndWmpnKMDmDHTBCPXBQbDBm1QX4KNKRQHMDTNNPKL\u0022\u00B7\u00B7Bxkvcr dmppbgwb\u00B7\u0022GJ2D4B8.614P\u0022\u00B7\u00B7MbwnfglwxgLmz cmdqqmrTxkjrmkjv\u00B7\u0022pfzd\u0022 ttjSjbbf\u00B7\u0022426\u0022 fjgQpksll\u00B7\u0022586\u0022 hqsDjnjbNqgg\u00B7\u002279\u0022 swd\u00B7\u002233:94\u0022 qrfz\u00B7\u0022rkh\u0022 nnhtsdkzmfVftwmmwbw\u00B7\u0022khtp\u0022 vvjfbrshnrWhqscqHnccVJS\u00B7\u00221\u0022 nk\u00B7\u00221\u0022\u00B7\u00B7Klvxfjdpgmkcbm nf\u00B7\u00222105064258901257c\u0022 bjfpTfmh\u00B7\u0022mnmgp/xx2\u0022 drjhtt\u00B7\u0022mbv3.34S28P\u0022 xmnfx\u00B7\u0022015\u0022 dnrjpl\u00B7\u0022783\u0022 svvnbWbgr\u00B7\u002290\u0022 pzn\u00B7\u00225:0\u0022 cshnzKjbcNTH\u00B7\u00224\u0022 htkdvtxss\u00B7\u0022535086\u0022 TXPpnsrrttRdh\u00B7\u0022phjf_mtjggqnp_9_t9\u0022 TQFsjbkdsDjfzmc\u00B7\u0022682788\u0022 WBTfxqfdsNdpfd\u00B7\u0022tr\u0022 QHZvvdrzqZrzlt\u00B7\u0022388c\u0022\u00B7\u00B7BzkpHTX\u00B7ptzrd://djtpgnnr-gdm7-5.chqjnggtxcnw.hbz/t6/n/g77/v0/s85/LNFcTLDTPwFs5rG45zQ5GcpTbPW51VgxS-gxLbBrX7Lp1_ZBpHqw1f1jkk7FVH68Kt05rqw71q5tDxmLK0dPK_MlpwGWDfRxDktFw4j.pc0?_fg_fvr\u00B7091\u0026bmt;_vr_dln\u00B70kq244\u0026npf;_pf_qj\u00B7nxxhgmjb-dgx1-4.vcjhbjhtqdzf.ncv\u0026zkx;_tg_kwp\u00B74zJPs9rxLb7H7jTqsLRtxCD\u0026rrl;jwr\u00B7skR7CK9xh7FmL4ZjJgZ8JcswKFsdsbXhRxC2v8T2Xnkvd4h8LSLlWdQdb6llSfFvDPtbzdKqCS36RXCtDdRcXMTrW7rgLlzbgHjwGSRjgLbfnTXwM6HmT3SrdT7qWJP9HLT9QxG6ZdNxKcllJQD7WCSmsQdstzWzrqTgTWZ9GpmcFmdltBX7S2Rrb3N0T1gbLbbjJTS5JgPcSNxlRKW1FDB7VJXrj3MlpL8zR1PxXXR2tsT6ZnClGtpwlwtlpSXzF9PtSH4jHPV6GFStSMFdPvZ0dmR5gN1vD1JlDjCmJpTtlZKprWTbZzN0FCCsCWxhzXCrH4LxR9MvkJHwLDF7Gsm4jnC5\u0026bcw;gxx\u00B721-3\u0026chn;_lt_rxw\u00B79C2pdx6LfVwGh9LB9KDJdl\u0026lzm;_jl_ql\u00B79mrrb\u0026xbh;_jk_ws\u00B775\u0026rqd;mt\u00B743_LXLnvSpHs_MGXGZtM6P_RZ3f3DJVBvwjDkKn0j9sSQM3KS\u0026dsx;kz\u00B75LFCZH01\u00B7/PshwFDJ\u00B7\u00B7PljvwwlKxmh xmgssFmqtxKtswx\u00B7\u0022cstc\u0022 cjmzhNzkrl\u00B7\u0022760-044\u0022 ZXDksrdZbgdnmnHpcvz\u00B7\u0022675-807615\u0022 DFKrwnnFdrcgdjPzslkxlv\u00B7\u00225006\u0022 VGQpmtnkjcSghrjssGttpl\u00B7\u0022707-284425\u0022 CGZxgqfzkqSkxvlbjKmjzrsjk\u00B7\u00225995\u0022\u00B7\u00B7Zdlpbbqjtddvbg kqzhj\u00B7\u00223-022\u0022/\u00B7\u00B7/HxjhswmXlsw\u00B7\u00B7/Dmkhtdjvmngqqg\u00B7\u00B7Hgvgkntcpkcgkh ww\u00B7\u00223087880308574554p\u0022 rqtpsnxbh\u00B7\u0022793589\u0022 fbzqqw\u00B7\u0022lzb3.3h343v\u0022 hgppCzjz\u00B7\u0022vbhhh/ql9\u0022 ssp\u00B7\u00226:6\u0022 QQRlrvxmndPjp\u00B7\u0022pzsj_qlvsscnr_7_c8\u0022 GFVgrlhtbLbmvkg\u00B7\u0022692823\u0022 DGKtwshdvjJjtvhhstbzWgk\u00B7\u00228:856,840:89.5,372:06.2,171:03.2\u0022 NJXksjglbzVbphmkfgkdRlvCqprcdlxlxWbptk\u00B7\u0022tvpb\u0022 KDZkdktghlKxshktthrjCsfmh\u00B7\u00221:122,024:36.6,698:71.9,996:34.4,334:39.9\u0022 zpxbk\u00B7\u0022208\u0022 kgzpwj\u00B7\u0022751\u0022 bbzmnRcbf\u00B7\u002243632/639\u0022 TLGlmkljzHslsm\u00B7\u0022pn\u0022 TNZcdvtncBbntg\u00B7\u0022249m\u0022\u00B7\u00B7HpccTXS\u00B7vdctg://qdbdqbfr-gls5-9.wptvrlzzwrdq.xhr/f4/d/g09/l5/m45/TQWbq6b-TbVwMtc2T7fdQq0gCPhvTw-HHRbBGTwPF6QCNRSS8cBkmsZs7bJ4Rbd9tDbhthVPZ0fGBRhfTCwXJdQcM6LsTvhPNtwWQcC.hm3?_mn_cdz\u00B7262\u0026nfj;_gh_xxg\u00B73th305\u0026cpl;_gj_nj\u00B7wzgkczvp-htk6-2.dhsxnxbbvrgx.jrx\u0026ndz;_ld_qts\u00B7S0S6pQvmrsJS8mPjmRwr3Pk\u0026wqf;wkl\u00B7ncD2MS8qc8RlT9VfGvD2GbkqTGlgmdZvNrL4r3P7Qmqgg2g4DDKdSpJtd1wvQgDcRCdkbzTkQc59HLTsKzXkZPSbL3hgJvpdzWtrGGMkgLdxgDKqR0JvD9WwbD2nLTC7RBX1QkX4JlRpDqlzQNX6RHPzcCjcjsDsltGnTKR4CwddKrxdkSH7X2Vvc3R8L7qlWgmkMTD1QnLfXNpnXSP3ZCB0HQZks8BbgM0tL4ZmBGW5xxV1NgThXwqgwlwsxKKpB6MkQW1tNDH8GXCzTKJhXcZ1qsD6dQ9cJ5KxLbCjVmZcmQJcgPVfLfJzQFDzKMbmgFGgW6QbC5DcmRHgVBJ2Dpj9ckQ8\u0026mkw;rdf\u00B749-5\u0026mhg;_wk_bdg\u00B74J7hdl2WnBxJl2JJ5NPWmt\u0026zvk;_lp_qv\u00B78bmwr\u0026nps;_lp_fh\u00B786\u0026jxf;nj\u00B735_NFP0BKLchBzPn1jtBGHkSMpN-dflLnZgVfjfW7Xm_sbBjb\u0026mmc;lj\u00B76XQGV2N8\u00B7/MqwgKTB\u00B7\u00B7XphkckcQldx kqtrmHhwkx\u00B7\u0022107-805\u0022 hrfknnnxx\u00B7\u002234837\u0022 SKLzqgxchJpxbmflwGhgjb\u00B7\u0022859-42393\u0022 NBGlwkfKzdfhlqXsslg\u00B7\u0022538-083992\u0022 LSGpkhpQmdpmqqRwljmfgw\u00B7\u00228653\u0022 HHBhxxzxftXclxhktNsdxg\u00B7\u0022602-948251\u0022 RQDrchdbdsSxjwkgsNgrskjpz\u00B7\u00224931\u0022\u00B7\u00B7Rmhlcfxvznqjsb wbdjc\u00B7\u00223-460\u0022/\u00B7\u00B7/MdthlrsFlhg\u00B7\u00B7/Xxpndlrwkszvnj\u00B7\u00B7/DvfzgjfshsHrg\u00B7\u00B7ShfdrnhlnwSnh pdjkrcrGkfsgdmbm\u00B7\u0022ddpq\u0022 pkdqqqngkdFxntwmcch\u00B7\Line truncated
|
||||
"video_versions": [
|
||||
{
|
||||
"type": 101,
|
||||
"url": "https://cdn.esempio/q81g83s37b162509.mp4"
|
||||
},
|
||||
{
|
||||
"type": 102,
|
||||
"url": "https://cdn.esempio/q81g83s37b162509.mp4"
|
||||
},
|
||||
{
|
||||
"type": 103,
|
||||
"url": "https://cdn.esempio/q81g83s37b162509.mp4"
|
||||
}
|
||||
],
|
||||
"media_type": 2,
|
||||
"visual_comment_reply_sticker_info": null,
|
||||
"story_bloks_stickers": [
|
||||
{
|
||||
"x": 6.0729408,
|
||||
"y": 5.1558897,
|
||||
"width": 0.15614899,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Jkft",
|
||||
"username": "ltgb_llltjlq"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "77352604007748140"
|
||||
},
|
||||
{
|
||||
"x": 0.2172182,
|
||||
"y": 4.0015787,
|
||||
"width": 0.10810314,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Qlhxtpjrt Fdkxddh",
|
||||
"username": "pvcbbkcm"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "84808036527115787"
|
||||
},
|
||||
{
|
||||
"x": 3.9762111,
|
||||
"y": 8.20447074,
|
||||
"width": 0.15614899,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Bwxrlz Fktpv",
|
||||
"username": "vqkkjw_xlpmd"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "59768694316706370"
|
||||
},
|
||||
{
|
||||
"x": 0.505518,
|
||||
"y": 9.11380160,
|
||||
"width": 0.14413752,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Gdwjmhmqf Hbvkbkff",
|
||||
"username": "dxvmxzdcwrv"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "79509364456252542"
|
||||
},
|
||||
{
|
||||
"x": 0.3920282,
|
||||
"y": 9.52808700,
|
||||
"width": 0.19218336,
|
||||
"height": 0.01749242,
|
||||
"rotation": -4.0158431704,
|
||||
"bloks_sticker": {
|
||||
"sticker_data": {
|
||||
"ig_mention": {
|
||||
"full_name": "Rtdrq ZvpBksknl",
|
||||
"username": "mtdqqpdwvndhnbv"
|
||||
}
|
||||
},
|
||||
"id": "dxtrs_nzwbbld_pf"
|
||||
},
|
||||
"id": "20963016712538816"
|
||||
}
|
||||
],
|
||||
"story_hashtags": null,
|
||||
"story_locations": null,
|
||||
"text_post_share_to_ig_story_stickers": null,
|
||||
"story_countdowns": null,
|
||||
"story_questions": null,
|
||||
"story_sliders": null,
|
||||
"link": null,
|
||||
"reel_media_background": null,
|
||||
"video_duration": 6.06,
|
||||
"custom_list_info": null,
|
||||
"is_story_edited": false,
|
||||
"product_type": "story",
|
||||
"reshared_story_media_author": null,
|
||||
"story_app_attribution": null,
|
||||
"audience": null,
|
||||
"has_liked": false,
|
||||
"viewer_count": null,
|
||||
"viewers": [],
|
||||
"can_reshare": true,
|
||||
"user": {
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"is_ai_user": null,
|
||||
"aigm_account_label_info": {
|
||||
"is_enabled": false
|
||||
},
|
||||
"instagram_pk": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642"
|
||||
},
|
||||
"inventory_source": null,
|
||||
"carousel_media_count": null,
|
||||
"media_overlay_info": null,
|
||||
"caption": null,
|
||||
"accessibility_caption": null,
|
||||
"organic_tracking_token": "xxx7xxxxxx7xxxx7xxxxxxxxx7xxxxx7xxxxx7xxxxx7xxxxx777xxxxx7xxxxx7xxxxxxx7xxxxxxxxxxx7xxxxxxxxxxxxxx77xxxxxxxxxxxxxxx7xxx7xxxxxxx7xxx7xxxxxxxxxxx7xxxxxxxxxxxxxxxxxxxxxx77x7xxxxx7xxx7xxx7xxxxxxx7xxx7xxx7xxxxxxxxxxx7xxxxxxxxxxx7xxxxxxxxxxx7xxxxxxx7x7xxxxxxxxxxxxx7xxx7xxxxxxx7xxxxxxxxx7x7xxxxxxx7xxx7xxx7x7x7xxxxxxxxxxxxxxx7xxx7xxxxxxxxxxx7xxxxxxxxxx\u00B7\u00B7",
|
||||
"story_link_stickers": null,
|
||||
"story_bloks_tappables": null,
|
||||
"story_feed_media": null,
|
||||
"story_cta": null,
|
||||
"preview": null,
|
||||
"is_paid_partnership": false,
|
||||
"sponsor_tags": null,
|
||||
"wearable_attribution_info": null,
|
||||
"has_translation": false,
|
||||
"boosted_status": null,
|
||||
"can_see_insights_as_brand": false,
|
||||
"boost_unavailable_identifier": null,
|
||||
"boost_unavailable_reason": null,
|
||||
"can_viewer_reshare": null,
|
||||
"expiring_at": 1585126989,
|
||||
"ig_media_sharing_disabled": false,
|
||||
"sharing_friction_info": {
|
||||
"should_have_sharing_friction": false,
|
||||
"bloks_app_url": null
|
||||
},
|
||||
"can_reply": true,
|
||||
"__typename": "JGPZxtzzMglf"
|
||||
}
|
||||
],
|
||||
"unviewable_authors_infos": [],
|
||||
"user": {
|
||||
"__typename": "KGTWcdxBfxp",
|
||||
"pk": "215081405",
|
||||
"id": "215081405",
|
||||
"interop_messaging_user_fbid": "068866421413642",
|
||||
"username": "dwvqbrgcjf",
|
||||
"profile_pic_url": "https://cdn.esempio/w8282f33028f3207.jpg",
|
||||
"is_private": false,
|
||||
"user_id": "215081405",
|
||||
"is_verified": false,
|
||||
"aigm_account_label_info": {
|
||||
"attribution_label_text": null,
|
||||
"is_auto_detected": false,
|
||||
"is_enabled": false,
|
||||
"is_manually_enabled": false
|
||||
},
|
||||
"transparency_label": null,
|
||||
"transparency_product": null,
|
||||
"transparency_product_enabled": false
|
||||
},
|
||||
"seen": null,
|
||||
"reel_type": "highlight_reel",
|
||||
"cover_media": {
|
||||
"cropped_image_version": {
|
||||
"url": "https://cdn.esempio/149tj2dp394sl651.jpg"
|
||||
},
|
||||
"full_image_version": null
|
||||
},
|
||||
"title": "Ggwgm \u00B7\u00B7",
|
||||
"can_reshare": true,
|
||||
"latest_reel_media": 1772734155,
|
||||
"muted": null,
|
||||
"__typename": "DWVDlmdMnfr"
|
||||
},
|
||||
"cursor": null
|
||||
}
|
||||
],
|
||||
"page_info": {
|
||||
"end_cursor": "vjbwtfskq:72329892632403300",
|
||||
"has_next_page": true,
|
||||
"has_previous_page": true,
|
||||
"start_cursor": "mtmlprbdv:62008803167428297"
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 5400924782018,
|
||||
"time_at_flush_ms": 9344386158027
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"descrittore": {
|
||||
"indirizzo": "https://sito.esempio/vgw3tpjgl1868811",
|
||||
"host": "sito",
|
||||
"stato": 200,
|
||||
"tipo": "text/javascript",
|
||||
"risorsa": "XHR",
|
||||
"quando": "2026-10-21T17:39:03Z"
|
||||
},
|
||||
"corpo": {
|
||||
"data": {
|
||||
"xdt_mark_story_reel_seen": {
|
||||
"__typename": "HZKNvqbMqjwNgsxngwm"
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"server_metadata": {
|
||||
"request_start_time_ms": 9970054667900,
|
||||
"time_at_flush_ms": 1713075827507
|
||||
},
|
||||
"is_final": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Campioni ripuliti di Instagram
|
||||
|
||||
Risposte **reali** di Instagram, ripulite. Servono alle prove dei lettori di Instagram
|
||||
(`tests/Febe.Tests/Collection/InstagramReaderTests.cs`) e al controllo dei campioni del repository
|
||||
(`SanitizerTests`), e sono la fonte di `src/Febe.Core/Config/lettori.instagram.json` (regola 9: i lettori si
|
||||
scrivono solo su campioni reali ripuliti).
|
||||
|
||||
## Da dove vengono
|
||||
|
||||
Da un file HAR esportato da Alberto dal suo browser il **21 ottobre 2026**, mentre navigava a mano su Instagram con
|
||||
l'accesso fatto. Il pannello Rete era filtrato su **Fetch/XHR**: nel file ci sono solo le risposte che la pagina ha
|
||||
chiesto da sé, nessun documento, nessuna immagine, nessuno script (per questo i bersagli e i dati incorporati nelle
|
||||
pagine mancano: `docs/prove-dal-vivo.md`, parte A bis).
|
||||
|
||||
Il percorso è quello di specifica §14.5:
|
||||
|
||||
1. campioni grezzi scritti **fuori dal repository**, nel formato della sonda (descrittore + corpo), con le sole
|
||||
risposte che interessano; i corpi più lunghi sono stati accorciati **sul lato grezzo**, prima della ripulitura,
|
||||
tenendo l'ordine e le chiavi originali:
|
||||
- pagina delle raccolte in evidenza: 2 raccolte × 4 contenuti, scelti in modo da avere una foto, un video con
|
||||
l'audio e un video senza;
|
||||
- pagina successiva delle raccolte: 1 raccolta × 3 contenuti;
|
||||
- profili suggeriti: i primi 3;
|
||||
- tutte le altre risposte intere;
|
||||
2. ripulitura, in una sola esecuzione per tutti i file (i valori finti cambiano a ogni esecuzione):
|
||||
`febe-sonda ripulisci --da <grezzi> --a tests/Febe.Tests/campioni/instagram`;
|
||||
3. verifica: `febe-sonda verifica --grezzi <grezzi> --ripuliti tests/Febe.Tests/campioni/instagram` →
|
||||
«Verifica superata».
|
||||
|
||||
Da un nuovo file HAR i grezzi si ricavano con `febe-sonda da-har` (stesso formato, stessi nomi dei file), poi si
|
||||
procede dal punto 2.
|
||||
|
||||
## Che cosa resta e che cosa no
|
||||
|
||||
Struttura, chiavi, booleani, `null`, dimensioni, durate, conteggi, codici di tipo e date restano come sono (elenco
|
||||
`tools/Febe.Sonda/ripulitura.json`). Nomi, didascalie, identificativi, cursori e indirizzi sono valori finti della
|
||||
stessa forma: valori uguali hanno lo stesso valore finto in tutti i file, quindi i collegamenti fra le risposte
|
||||
restano. Gli indirizzi diventano `https://sito.esempio/…` o `https://cdn.esempio/…` con la sola estensione del file.
|
||||
I valori sotto chiavi che sembrano chiavi segrete (`organic_tracking_token`, `rank_token` e simili) sono un
|
||||
riempitivo neutro di `x` e `7` della stessa forma, perché gitleaks non li scambi per segreti. Le prove controllano
|
||||
forme, dimensioni, date e conteggi, mai i valori.
|
||||
|
||||
## I file
|
||||
|
||||
| File | Operazione o indirizzo | Tipo | Che cosa contiene |
|
||||
|---|---|---|---|
|
||||
| `000001-promozioni` | `QuickPromotionSupportIGSchemaBatchFetchQuery` | `text/javascript` | promozioni dell'interfaccia: nessun contenuto né profilo (risposta estranea, ignorata) |
|
||||
| `000002-ricerca-profili` | `PolarisSearchBoxRefetchableQuery` | `text/javascript` | profili trovati dalla casella di ricerca (5) |
|
||||
| `000003-profili-suggeriti` | `PolarisProfileSuggestedUsersWithPreloadableQuery` | `text/javascript` | profili suggeriti, non seguiti (i primi 3) |
|
||||
| `000004-commenti` | `/api/v1/media/…/comments/` | `application/json` | commenti di un post, con la didascalia |
|
||||
| `000005-post-video` | `/api/v1/media/…/info/` | `application/json` | un post video (reel) con autore, didascalia e versioni |
|
||||
| `000006-raccolta-in-evidenza` | `PolarisStoriesV3HighlightsPageQuery` | `text/javascript` | pagina delle raccolte in evidenza (2 × 4) e l'account collegato, con il solo identificativo |
|
||||
| `000007-raccolta-pagina-successiva` | `PolarisStoriesV3HighlightsPagePaginationQuery` | `text/javascript` | pagina successiva delle raccolte (1 × 3) |
|
||||
| `000008-storia-vista` | `PolarisStoriesV3SeenMutation` | `text/javascript` | la pagina segna una storia come vista: nessun dato (risposta estranea, ignorata) |
|
||||
|
||||
Le operazioni GraphQL (le righe con un nome) arrivano con il tipo `text/javascript`, non `application/json`: la
|
||||
cattura le legge lo stesso (`src/Febe.Core/Collection/DataResponses.cs`).
|
||||
@@ -0,0 +1,365 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
|
||||
namespace Febe.Sonda;
|
||||
|
||||
/// <summary>What a HAR conversion did: counts only, never a value.</summary>
|
||||
/// <param name="Entries">Entries of the HAR.</param>
|
||||
/// <param name="DataResponses">Site answers written because their body is data (<see cref="DataResponses.IsData"/>).</param>
|
||||
/// <param name="Documents">Page documents that embed JSON: each of their blocks is written as a sample of its own.</param>
|
||||
/// <param name="DocumentBlocks">Samples written from page documents: one per JSON block they embed, the way Febe's capture
|
||||
/// hands the blocks to the readers.</param>
|
||||
/// <param name="OtherHosts">Left out: not an answer of the site (CDN, other sites).</param>
|
||||
/// <param name="NotData">Left out: files, images, scripts, styles, or a type or status that is not data.</param>
|
||||
/// <param name="WithoutBody">Left out: the HAR does not hold the body.</param>
|
||||
/// <param name="NotJson">Left out: a body that is not valid JSON (for example one that starts with <c>for (;;);</c>).</param>
|
||||
/// <param name="DocumentsWithoutData">Left out: page documents that embed no JSON.</param>
|
||||
public sealed record HarImportReport(int Entries, int DataResponses, int Documents, int DocumentBlocks, int OtherHosts, int NotData, int WithoutBody, int NotJson, int DocumentsWithoutData)
|
||||
{
|
||||
public int Written => DataResponses + DocumentBlocks;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a HAR exported from the browser's DevTools (Chrome, Edge) into the probe's RAW format (spec §14.5), so that
|
||||
/// <c>ripulisci</c> and <c>verifica</c> work on it as on a recording of the probe: flat files <c>NNNNNN-<kind>.json</c>,
|
||||
/// each <c>{"descrittore":{indirizzo, host, stato, tipo, risorsa, quando}, "corpo": <body>}</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It keeps what Febe's own capture keeps (<c>ResponseTap</c>), in the same pieces: site answers whose body is data, and
|
||||
/// the JSON blocks embedded in page documents, one sample per block with the document's descriptor
|
||||
/// (<see cref="DataResponses.EmbeddedJsonBlocks"/>). Everything else is left out. Headers, cookies, query strings and
|
||||
/// request bodies are never copied: the address keeps scheme, host and path only, and of the request body only the
|
||||
/// GraphQL operation name is read, to name the file, when it has the shape of a name in the site's code (never a path:
|
||||
/// paths contain user names).
|
||||
/// The output is still RAW (bodies hold other people's data): it must stay outside any repository.
|
||||
/// </remarks>
|
||||
public static partial class HarImporter
|
||||
{
|
||||
/// <summary>Request parameter that names the GraphQL operation of a POST (a fixed name in the site's code).</summary>
|
||||
public const string OperationParameter = "fb_api_req_friendly_name";
|
||||
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
||||
|
||||
/// <summary>Converts <paramref name="harPath"/> into the new, empty folder <paramref name="rawFolder"/>.</summary>
|
||||
/// <exception cref="InvalidOperationException">A folder is inside a git repository, or the output folder is not empty.</exception>
|
||||
/// <exception cref="InvalidDataException">The file is not a HAR.</exception>
|
||||
public static HarImportReport Import(string harPath, string rawFolder, HostClassifier? hosts = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(harPath);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(rawFolder);
|
||||
hosts ??= HostClassifier.Instagram;
|
||||
var har = Path.GetFullPath(harPath);
|
||||
if (!File.Exists(har))
|
||||
{
|
||||
throw new FileNotFoundException($"Il file HAR non esiste: {har}", har);
|
||||
}
|
||||
|
||||
// The HAR holds cookies and other people's data, and so does the output: neither belongs in a repository.
|
||||
RepositoryGuard.EnsureOutside(Path.GetDirectoryName(har)!);
|
||||
var folder = Path.GetFullPath(rawFolder);
|
||||
RepositoryGuard.EnsureOutside(folder);
|
||||
if (Directory.Exists(folder) && Directory.EnumerateFileSystemEntries(folder).Any())
|
||||
{
|
||||
throw new InvalidOperationException($"La cartella «{folder}» non è vuota: indica una cartella nuova, solo per questa conversione.");
|
||||
}
|
||||
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
using var stream = File.OpenRead(har);
|
||||
document = JsonDocument.Parse(stream);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR valido (riga {ex.LineNumber + 1}).", ex);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Object
|
||||
|| !document.RootElement.TryGetProperty("log", out var log) || log.ValueKind != JsonValueKind.Object
|
||||
|| !log.TryGetProperty("entries", out var entries) || entries.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
throw new InvalidDataException($"{Path.GetFileName(har)}: non è un file HAR (manca «log.entries»).");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(folder);
|
||||
File.WriteAllText(
|
||||
Path.Combine(folder, "LEGGIMI.txt"),
|
||||
"Campioni GREZZI convertiti da un file HAR con «febe-sonda da-har»: contengono dati personali di Alberto e di altre persone.\n"
|
||||
+ "Non vanno nel repository e non si inviano: si ripuliscono con «febe-sonda ripulisci», si controllano con «febe-sonda verifica»\n"
|
||||
+ "e si cancellano, insieme al file HAR, quando lettori e mappa sono scritti (specifica §14.5).\n");
|
||||
|
||||
int count = 0, written = 0, data = 0, documents = 0, blocks = 0, otherHosts = 0, notData = 0, withoutBody = 0, notJson = 0, documentsWithoutData = 0;
|
||||
foreach (var entry in entries.EnumerateArray())
|
||||
{
|
||||
count++;
|
||||
var outcome = ConvertEntry(entry, hosts, out var sample);
|
||||
if (sample is not null)
|
||||
{
|
||||
// One block at a time: each is written and disposed before the next one is parsed.
|
||||
var bodies = 0;
|
||||
foreach (var body in sample.Bodies)
|
||||
{
|
||||
using (body)
|
||||
{
|
||||
written++;
|
||||
Write(Path.Combine(folder, $"{written.ToString("000000", CultureInfo.InvariantCulture)}-{sample.Kind}.json"), sample, body);
|
||||
}
|
||||
|
||||
bodies++;
|
||||
}
|
||||
|
||||
if (outcome == EntryOutcome.Document)
|
||||
{
|
||||
blocks += bodies;
|
||||
outcome = bodies > 0 ? EntryOutcome.Document : EntryOutcome.DocumentWithoutData;
|
||||
}
|
||||
}
|
||||
|
||||
switch (outcome)
|
||||
{
|
||||
case EntryOutcome.Data:
|
||||
data++;
|
||||
break;
|
||||
case EntryOutcome.Document:
|
||||
documents++;
|
||||
break;
|
||||
case EntryOutcome.OtherHost:
|
||||
otherHosts++;
|
||||
break;
|
||||
case EntryOutcome.WithoutBody:
|
||||
withoutBody++;
|
||||
break;
|
||||
case EntryOutcome.NotJson:
|
||||
notJson++;
|
||||
break;
|
||||
case EntryOutcome.DocumentWithoutData:
|
||||
documentsWithoutData++;
|
||||
break;
|
||||
default:
|
||||
notData++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new HarImportReport(count, data, documents, blocks, otherHosts, notData, withoutBody, notJson, documentsWithoutData);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name of the GraphQL operation of a request, when it is one: a word of the site's code (letters and digits,
|
||||
/// ending in Query, Mutation or Subscription, no run of three digits), the same for everyone. Otherwise null.
|
||||
/// </summary>
|
||||
public static string? OperationName(string? value)
|
||||
{
|
||||
var name = value?.Trim();
|
||||
return name is not null && OperationShape().IsMatch(name) && !DigitRun().IsMatch(name) ? name : null;
|
||||
}
|
||||
|
||||
private static EntryOutcome ConvertEntry(JsonElement entry, HostClassifier hosts, out RawSample? sample)
|
||||
{
|
||||
sample = null;
|
||||
if (entry.ValueKind != JsonValueKind.Object
|
||||
|| !entry.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object
|
||||
|| !entry.TryGetProperty("response", out var response) || response.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return EntryOutcome.NotData;
|
||||
}
|
||||
|
||||
// Chrome's resource types, written as the browser's protocol names them (what ResponseTap sees).
|
||||
var resource = Text(entry, "_resourceType")?.ToLowerInvariant() switch
|
||||
{
|
||||
"xhr" => "XHR",
|
||||
"fetch" => "Fetch",
|
||||
"document" => "Document",
|
||||
_ => null,
|
||||
};
|
||||
if (resource is null)
|
||||
{
|
||||
return EntryOutcome.NotData;
|
||||
}
|
||||
|
||||
var url = Text(request, "url");
|
||||
var host = hosts.Classify(url);
|
||||
if (host != HostKind.Site)
|
||||
{
|
||||
return EntryOutcome.OtherHost;
|
||||
}
|
||||
|
||||
var status = response.TryGetProperty("status", out var s) && s.TryGetInt32(out var code) ? code : 0;
|
||||
var content = response.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.Object ? c : default;
|
||||
var mime = (content.ValueKind == JsonValueKind.Object ? Text(content, "mimeType") : null)?.Split(';')[0].Trim().ToLowerInvariant() ?? string.Empty;
|
||||
var isData = DataResponses.IsData(mime, resource) && status is >= 200 and < 600 && status != 204;
|
||||
var isDocument = !isData && resource == "Document" && status is >= 200 and < 300 && DataResponses.IsPageDocument(mime, isMainFrameDocument: true);
|
||||
if (!isData && !isDocument)
|
||||
{
|
||||
return EntryOutcome.NotData;
|
||||
}
|
||||
|
||||
var bytes = Body(content);
|
||||
if (bytes is null)
|
||||
{
|
||||
return EntryOutcome.WithoutBody;
|
||||
}
|
||||
|
||||
var address = UrlSanitizer.Sanitize(url).Url;
|
||||
var at = When(Text(entry, "startedDateTime"));
|
||||
if (isDocument)
|
||||
{
|
||||
// Only the JSON the page embeds, one block per sample, as Febe's capture hands it to the readers: parsed
|
||||
// while the samples are written (a document without any becomes DocumentWithoutData there).
|
||||
sample = new RawSample("documento", address, host, status, mime, resource, at, DataResponses.EmbeddedJsonBlocks(Encoding.UTF8.GetString(bytes)));
|
||||
return EntryOutcome.Document;
|
||||
}
|
||||
|
||||
JsonDocument body;
|
||||
try
|
||||
{
|
||||
body = JsonDocument.Parse(bytes, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return EntryOutcome.NotJson;
|
||||
}
|
||||
|
||||
var kind = resource == "Document" ? "documento" : OperationName(Operation(request)) ?? "risposta";
|
||||
sample = new RawSample(kind, address, host, status, mime, resource, at, [body]);
|
||||
return EntryOutcome.Data;
|
||||
}
|
||||
|
||||
/// <summary>The value of <see cref="OperationParameter"/> in a form-encoded request body; nothing else is read.</summary>
|
||||
private static string? Operation(JsonElement request)
|
||||
{
|
||||
if (!request.TryGetProperty("postData", out var post) || post.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (post.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var parameter in parameters.EnumerateArray())
|
||||
{
|
||||
if (parameter.ValueKind == JsonValueKind.Object && Text(parameter, "name") == OperationParameter)
|
||||
{
|
||||
return Unescape(Text(parameter, "value"));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((Text(post, "mimeType") ?? string.Empty).Contains("x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Text(post, "text") is { } text)
|
||||
{
|
||||
foreach (var pair in text.Split('&'))
|
||||
{
|
||||
var equals = pair.IndexOf('=', StringComparison.Ordinal);
|
||||
if (equals > 0 && Unescape(pair[..equals]) == OperationParameter)
|
||||
{
|
||||
return Unescape(pair[(equals + 1)..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? Unescape(string? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Uri.UnescapeDataString(value.Replace('+', ' '));
|
||||
}
|
||||
catch (UriFormatException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[]? Body(JsonElement content)
|
||||
{
|
||||
if (content.ValueKind != JsonValueKind.Object || Text(content, "text") is not { Length: > 0 } text)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!string.Equals(Text(content, "encoding"), "base64", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(text);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Convert.FromBase64String(text);
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? When(string? value) =>
|
||||
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var at)
|
||||
? at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture)
|
||||
: null;
|
||||
|
||||
private static string? Text(JsonElement element, string property) =>
|
||||
element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
|
||||
|
||||
/// <summary>The same descriptor the probe writes (<see cref="ProbeRecorder"/>), then the body as it arrived.</summary>
|
||||
private static void Write(string path, RawSample sample, JsonDocument body)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write);
|
||||
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { MaxDepth = 300 });
|
||||
writer.WriteStartObject();
|
||||
writer.WriteStartObject("descrittore");
|
||||
writer.WriteString("indirizzo", sample.Url);
|
||||
writer.WriteString("host", sample.Host switch { HostKind.Site => "sito", HostKind.Cdn => "cdn", _ => "altro" });
|
||||
writer.WriteNumber("stato", sample.Status);
|
||||
writer.WriteString("tipo", sample.MimeType);
|
||||
writer.WriteString("risorsa", sample.ResourceType);
|
||||
if (sample.At is { } at)
|
||||
{
|
||||
writer.WriteString("quando", at);
|
||||
}
|
||||
else
|
||||
{
|
||||
writer.WriteNull("quando");
|
||||
}
|
||||
|
||||
writer.WriteEndObject();
|
||||
writer.WritePropertyName("corpo");
|
||||
body.RootElement.WriteTo(writer);
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
// A GraphQL operation name: an identifier of the site's code (e.g. a «...PageQuery»), never free text.
|
||||
[GeneratedRegex("^[A-Za-z][A-Za-z0-9_]{1,96}(Query|Mutation|Subscription)$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex OperationShape();
|
||||
|
||||
[GeneratedRegex("[0-9]{3}", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex DigitRun();
|
||||
|
||||
private enum EntryOutcome
|
||||
{
|
||||
Data,
|
||||
Document,
|
||||
OtherHost,
|
||||
NotData,
|
||||
WithoutBody,
|
||||
NotJson,
|
||||
DocumentWithoutData,
|
||||
}
|
||||
|
||||
/// <summary>What is written of one entry: its descriptor, and its body (a data answer) or the JSON blocks it embeds (a page document).</summary>
|
||||
private sealed record RawSample(string Kind, string Url, HostKind Host, int Status, string MimeType, string ResourceType, string? At, IEnumerable<JsonDocument> Bodies);
|
||||
}
|
||||
@@ -10,9 +10,11 @@ using Febe.Sonda;
|
||||
// [--sito <host> --cdn <host>] (solo per provarla sul sito di prova)
|
||||
// febe-sonda ripulisci --da <grezzi> --a <ripuliti> [--ammessi <ripulitura.json>] [--sito <host> --cdn <host>]
|
||||
// febe-sonda verifica --grezzi <grezzi> --ripuliti <ripuliti> [--ammessi <ripulitura.json>]
|
||||
// febe-sonda da-har --har <file .har> --a <cartella nuova fuori dal repository> [--sito <host> --cdn <host>]
|
||||
return args.Length == 0 ? Usage() : args[0] switch
|
||||
{
|
||||
"registra" => await RecordAsync(args[1..]),
|
||||
"da-har" => FromHar(args[1..]),
|
||||
"ripulisci" => Sanitize(args[1..]),
|
||||
"verifica" => Verify(args[1..]),
|
||||
_ => Usage(),
|
||||
@@ -25,7 +27,11 @@ static int Usage()
|
||||
febe-sonda registra --cartella <cartella fuori dal repository> [--display :0 | --xvfb] [--porta 9333] [--chromium <file>] [--no-sandbox]
|
||||
febe-sonda ripulisci --da <campioni grezzi> --a <campioni ripuliti> [--ammessi <ripulitura.json>]
|
||||
febe-sonda verifica --grezzi <campioni grezzi> --ripuliti <campioni ripuliti> [--ammessi <ripulitura.json>]
|
||||
febe-sonda da-har --har <file .har esportato dal browser> --a <cartella nuova fuori dal repository>
|
||||
La sonda è passiva: apre il browser e registra ciò che la pagina riceve mentre navighi tu. Non compie gesti.
|
||||
«da-har» converte nello stesso formato grezzo un file HAR esportato dagli strumenti per sviluppatori del browser:
|
||||
tiene le sole risposte di dati del sito e i dati incorporati nelle pagine; mai intestazioni, cookie, parametri
|
||||
degli indirizzi o corpi delle richieste. Poi si usano «ripulisci» e «verifica» come per la sonda.
|
||||
""");
|
||||
return 2;
|
||||
}
|
||||
@@ -109,6 +115,40 @@ static async Task<int> RecordAsync(string[] args)
|
||||
}
|
||||
}
|
||||
|
||||
static int FromHar(string[] args)
|
||||
{
|
||||
var har = Option(args, "--har");
|
||||
var to = Option(args, "--a");
|
||||
if (string.IsNullOrWhiteSpace(har) || string.IsNullOrWhiteSpace(to))
|
||||
{
|
||||
Console.Error.WriteLine("Indicare --har <file .har> e --a <cartella nuova fuori dal repository>.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
HarImportReport report;
|
||||
try
|
||||
{
|
||||
report = HarImporter.Import(har, to, Hosts(args));
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or InvalidDataException or FileNotFoundException)
|
||||
{
|
||||
Console.Error.WriteLine(ex.Message);
|
||||
return 3;
|
||||
}
|
||||
|
||||
// Counts only: what the answers contain stays on this machine.
|
||||
Console.WriteLine($"Lette {report.Entries} voci del file HAR; scritti {report.Written} campioni grezzi: {report.DataResponses} risposte di dati del sito, {report.DocumentBlocks} blocchi di dati incorporati in {report.Documents} pagine.");
|
||||
Console.WriteLine($"Lasciate fuori: {report.OtherHosts} di altri indirizzi (CDN, altri siti), {report.NotData} che non sono dati (file, immagini, script...), {report.WithoutBody} senza corpo, {report.NotJson} non JSON, {report.DocumentsWithoutData} pagine senza dati incorporati.");
|
||||
if (report.Written == 0 && report.WithoutBody > 0)
|
||||
{
|
||||
Console.WriteLine("Il file HAR non contiene i corpi delle risposte: esportalo di nuovo dal pannello Rete con le risposte incluse.");
|
||||
}
|
||||
|
||||
Console.WriteLine($"Campioni grezzi in: {Path.GetFullPath(to)}");
|
||||
Console.WriteLine("Ora: febe-sonda ripulisci --da <cartella> --a <copia ripulita>, poi febe-sonda verifica.");
|
||||
return report.Written > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static int Sanitize(string[] args)
|
||||
{
|
||||
var from = Option(args, "--da");
|
||||
|
||||
@@ -21,7 +21,7 @@ public sealed record SanitizeReport(int Files, int Lines, int ReplacedStrings, i
|
||||
/// sensitive run of any raw sample (it is drawn again). Fake letters are consonants only, so they cannot spell the
|
||||
/// words of a caption. The browser profile folder of the probe is never read.
|
||||
/// </remarks>
|
||||
public sealed class SampleSanitizer
|
||||
public sealed partial class SampleSanitizer
|
||||
{
|
||||
/// <summary>The probe's browser profile: holds the session, never part of the samples.</summary>
|
||||
public const string BrowserProfileFolder = "profilo-browser";
|
||||
@@ -188,12 +188,26 @@ public sealed class SampleSanitizer
|
||||
}
|
||||
|
||||
_strings++;
|
||||
return JsonValue.Create(Fake(text, "s"));
|
||||
return JsonValue.Create(LooksLikeSecretKey(key) ? Filler(text) : Fake(text, "s"));
|
||||
default:
|
||||
return JsonValue.Create(element);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True for the keys under which a site keeps tokens and keys of its own (Instagram: «organic_tracking_token»,
|
||||
/// «rank_token», «client_cache_key»). Their fakes would look like real secrets to a secret scanner (gitleaks in the
|
||||
/// CI): they get a neutral filler of the same shape instead.
|
||||
/// </summary>
|
||||
internal static bool LooksLikeSecretKey(string? key) => key is not null && SecretKey().IsMatch(key);
|
||||
|
||||
/// <summary>Letters become «x», digits «7», symbols «·»: the shape stays, nothing of the value and no entropy.</summary>
|
||||
private static string Filler(string text) =>
|
||||
new([.. text.Select(c => char.IsLetter(c) ? 'x' : char.IsDigit(c) ? '7' : char.IsSurrogate(c) || char.IsSymbol(c) ? '·' : c)]);
|
||||
|
||||
[System.Text.RegularExpressions.GeneratedRegex("token|secret|passw|credential|cookie|csrf|session|signature|auth|key", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant)]
|
||||
private static partial System.Text.RegularExpressions.Regex SecretKey();
|
||||
|
||||
private string FakeKey(string key)
|
||||
{
|
||||
_keys++;
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
"keys": ["type", "*_type", "status", "tipo", "stato", "risorsa", "host", "role", "tag", "evento"]
|
||||
},
|
||||
"date": {
|
||||
"note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4.",
|
||||
"keys": ["taken_at", "*_at", "pubblicato", "scade", "ultima_storia", "quando"]
|
||||
"note": "Date: si tengono i numeri e i testi che hanno la forma di una data. taken_at è uno degli indizi di §6.4; latest_reel_media è la data dell'ultima storia di un profilo (campioni del 21/10/2026).",
|
||||
"keys": ["taken_at", "*_at", "latest_reel_media", "pubblicato", "scade", "ultima_storia", "quando"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# Raccolta dei bersagli dal browser di tutti i giorni
|
||||
|
||||
`raccogli-bersagli.js` serve a compilare i **bersagli** di `src/Febe.Core/Config/bersagli.instagram.json` (ipotesi
|
||||
H11): l'anello delle storie, la zona «avanti» e la X del visualizzatore, le schede del profilo, le raccolte in evidenza.
|
||||
Si usa come spiegato in `docs/prove-dal-vivo.md`, parte **A bis**.
|
||||
|
||||
## Come si usa
|
||||
|
||||
1. Nel browser con cui navighi di solito, già entrato nel sito, apri gli strumenti per sviluppatori (F12) e la scheda
|
||||
**Console**.
|
||||
2. Incolla tutto il contenuto di `raccogli-bersagli.js` e premi Invio. Compare «Febe: raccolta dei bersagli attiva».
|
||||
Se la pagina si ricarica del tutto, la raccolta si perde: incollalo di nuovo.
|
||||
3. Naviga e clicca come al solito. A ogni clic la Console scrive «Febe: clic N registrato».
|
||||
4. Alla fine scrivi `febeBersagli()` nella Console: copia negli appunti i clic registrati (se la copia non riesce, li
|
||||
scrive nella Console e li copi da lì).
|
||||
|
||||
## Che cosa fa e che cosa non fa
|
||||
|
||||
- **Sola lettura.** Aggiunge un solo ascoltatore dei clic, che non blocca e non cambia il clic, e legge attributi.
|
||||
Non modifica la pagina, non manda nulla a nessuno, non legge cookie né le memorie del browser. I dati restano nella
|
||||
memoria della scheda finché non chiami `febeBersagli()`.
|
||||
- Per ogni clic registra la forma dell'indirizzo prima e circa 1,5 secondi dopo, e del comando cliccato (il più vicino
|
||||
fra collegamento, pulsante, elemento con un ruolo o con `tabindex`): elemento, ruolo, `aria-label`, `alt`, `title`, il
|
||||
testo (solo per pulsanti, collegamenti, schede e simili), il **nome accessibile calcolato come lo calcola Febe**
|
||||
(`src/Febe.Browser/Targets/TargetResolver.cs`), se il nome viene da un'icona `svg` con `aria-label`, la forma del
|
||||
collegamento, e quanti elementi visibili hanno lo stesso ruolo e lo stesso nome (con la posizione di quello cliccato).
|
||||
- La voce `perLaMappa` è già nella forma dei campi `role`, `name`, `href` e `index` della mappa.
|
||||
- **Nomi.** Negli indirizzi restano solo le parole fisse (`stories`, `highlights`, `p`, `reel`, `reels`, `tagged`,
|
||||
`following`, `followers`, `explore`); ogni altro pezzo diventa `<x>`. Nei testi registrati, i nomi visti negli
|
||||
indirizzi e ogni `@parola` diventano `NOME`. I nomi scritti per esteso (per esempio «Mario Rossi») **non** si
|
||||
riconoscono: prima di inviare il testo, sostituisci a mano con `NOME` ogni nome di persona rimasto.
|
||||
- Un nome utente che è anche una parola dell'interfaccia può far diventare `NOME` anche quella parola: va bene così,
|
||||
meglio un nome di comando in meno che un nome di persona in più.
|
||||
@@ -0,0 +1,258 @@
|
||||
// Febe: targets from the everyday browser (docs/prove-dal-vivo.md, part «A bis»; hypothesis H11).
|
||||
//
|
||||
// Paste it in the Console of the browser's DevTools, with the site open and already logged in, then browse by hand.
|
||||
// For every click it records the shape of the address before and about 1.5 s after, and the attributes of the clicked
|
||||
// command that Febe's target map uses (src/Febe.Core/Config/bersagli.<sito>.json): role, accessible name computed as
|
||||
// src/Febe.Browser/Targets/TargetResolver.cs computes it, link shape. At the end, febeBersagli() copies the records.
|
||||
//
|
||||
// READ-ONLY with respect to the page: one capturing click listener that never blocks or changes the click, and
|
||||
// attribute reads. It never changes the DOM, never sends anything anywhere, never reads cookies or the browser's
|
||||
// storage. Records stay in this tab's memory; reloading the page drops them (paste it again after a reload).
|
||||
// Address segments that are not fixed words become «<x>»; user names seen in the addresses and @words become «NOME».
|
||||
(() => {
|
||||
'use strict';
|
||||
if (typeof globalThis.febeBersagli === 'function') {
|
||||
console.log('Febe: la raccolta dei bersagli è già attiva. febeBersagli() copia ciò che è stato registrato.');
|
||||
return;
|
||||
}
|
||||
|
||||
const FIXED = new Set(['stories', 'highlights', 'p', 'reel', 'reels', 'tagged', 'following', 'followers', 'explore']);
|
||||
const MAX_TEXT = 80;
|
||||
const records = [];
|
||||
const names = new Set();
|
||||
|
||||
// Same as TargetResolver.cs: collapsed whitespace.
|
||||
const clean = (s) => (s || '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
// The shape of a path: fixed words stay, every other segment becomes «<x>». The segments that are not fixed words
|
||||
// are kept aside (in memory only) to mask them in the recorded texts.
|
||||
const shapeOf = (path) => {
|
||||
if (typeof path !== 'string') return null;
|
||||
return path.split('/').map((segment) => {
|
||||
if (segment === '' || FIXED.has(segment.toLowerCase())) return segment;
|
||||
let decoded = segment;
|
||||
try { decoded = decodeURIComponent(segment); } catch { /* keep it as it is */ }
|
||||
if (decoded.length >= 2) names.add(decoded.toLowerCase());
|
||||
return '<x>';
|
||||
}).join('/');
|
||||
};
|
||||
|
||||
// Same as TargetResolver.cs roleOf: explicit role first, then the implicit role of the tag.
|
||||
const roleOf = (el) => {
|
||||
const explicit = clean(el.getAttribute('role')).split(' ')[0];
|
||||
if (explicit) return explicit.toLowerCase();
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const type = (el.getAttribute('type') || '').toLowerCase();
|
||||
switch (tag) {
|
||||
case 'a': case 'area': return el.hasAttribute('href') ? 'link' : '';
|
||||
case 'button': return 'button';
|
||||
case 'input':
|
||||
if (['button', 'submit', 'reset', 'image'].includes(type)) return 'button';
|
||||
if (type === 'checkbox') return 'checkbox';
|
||||
if (type === 'radio') return 'radio';
|
||||
if (type === 'search') return 'searchbox';
|
||||
if (['', 'text', 'email', 'tel', 'url', 'password'].includes(type)) return 'textbox';
|
||||
return '';
|
||||
case 'textarea': return 'textbox';
|
||||
case 'select': return 'combobox';
|
||||
case 'img': return el.getAttribute('alt') === '' ? 'presentation' : 'img';
|
||||
case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return 'heading';
|
||||
case 'nav': return 'navigation';
|
||||
case 'main': return 'main';
|
||||
case 'dialog': return 'dialog';
|
||||
case 'article': return 'article';
|
||||
case 'ul': case 'ol': return 'list';
|
||||
case 'li': return 'listitem';
|
||||
case 'section': return (el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby')) ? 'region' : '';
|
||||
default: return '';
|
||||
}
|
||||
};
|
||||
|
||||
// Same as TargetResolver.cs textOf: a child's aria-label stands for its subtree, aria-hidden children are skipped.
|
||||
const textOf = (node, depth) => {
|
||||
if (depth > 25) return '';
|
||||
let out = '';
|
||||
for (const child of node.childNodes) {
|
||||
if (child.nodeType === 3) { out += child.nodeValue + ' '; continue; }
|
||||
if (child.nodeType !== 1) continue;
|
||||
if (child.getAttribute('aria-hidden') === 'true') continue;
|
||||
const label = clean(child.getAttribute('aria-label'));
|
||||
if (label) { out += label + ' '; continue; }
|
||||
const tag = child.tagName.toLowerCase();
|
||||
if (tag === 'img') { out += (child.getAttribute('alt') || '') + ' '; continue; }
|
||||
if (tag === 'script' || tag === 'style' || tag === 'template') continue;
|
||||
out += textOf(child, depth + 1) + ' ';
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// Roles named from their content (TargetResolver.cs fromContent): only these get their text recorded.
|
||||
const fromContent = new Set(['button', 'link', 'tab', 'menuitem', 'heading', 'cell', 'gridcell', 'option',
|
||||
'checkbox', 'radio', 'switch', 'listitem', 'treeitem', 'columnheader', 'rowheader', 'tooltip']);
|
||||
|
||||
// Same as TargetResolver.cs nameOf: the accessible name the «name» field of the map is matched against.
|
||||
const nameOf = (el, role) => {
|
||||
const ids = clean(el.getAttribute('aria-labelledby'));
|
||||
if (ids) {
|
||||
const joined = clean(ids.split(' ').map((id) => document.getElementById(id)).filter(Boolean).map((e) => e.textContent).join(' '));
|
||||
if (joined) return joined;
|
||||
}
|
||||
const aria = clean(el.getAttribute('aria-label'));
|
||||
if (aria) return aria;
|
||||
const tag = el.tagName.toLowerCase();
|
||||
const type = (el.getAttribute('type') || '').toLowerCase();
|
||||
if (tag === 'img' || (tag === 'input' && type === 'image')) {
|
||||
const alt = clean(el.getAttribute('alt'));
|
||||
if (alt) return alt;
|
||||
}
|
||||
if (tag === 'input' && ['button', 'submit', 'reset'].includes(type)) {
|
||||
const label = clean(el.getAttribute('value'));
|
||||
if (label) return label;
|
||||
}
|
||||
if (fromContent.has(role)) {
|
||||
const text = clean(textOf(el, 0));
|
||||
if (text) return text;
|
||||
}
|
||||
return clean(el.getAttribute('title') || el.getAttribute('placeholder'));
|
||||
};
|
||||
|
||||
const visible = (el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!(r.width > 0 && r.height > 0)) return false;
|
||||
return typeof el.checkVisibility === 'function' ? el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) : true;
|
||||
};
|
||||
|
||||
// Like ProbeRecorder.cs: the path of a link and whether it stays on the site, never the host of another site.
|
||||
const linkOf = (el) => {
|
||||
const href = el.getAttribute('href');
|
||||
if (!href) return null;
|
||||
try {
|
||||
const u = new URL(href, document.baseURI);
|
||||
return { sito: u.origin === location.origin, path: shapeOf(u.pathname) };
|
||||
} catch { return null; }
|
||||
};
|
||||
|
||||
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
// User names seen in any recorded address, and every @word, become «NOME»; texts are cut to 80 characters.
|
||||
const mask = (text) => {
|
||||
if (text === null || text === undefined) return null;
|
||||
let out = clean(String(text)).replace(/@[\p{L}\p{N}._]+/gu, 'NOME');
|
||||
for (const name of names) {
|
||||
out = out.replace(new RegExp('(^|[^\\p{L}\\p{N}_])' + escapeRegex(name) + '(?![\\p{L}\\p{N}_])', 'giu'), '$1NOME');
|
||||
}
|
||||
return out.length > MAX_TEXT ? out.slice(0, MAX_TEXT) : out;
|
||||
};
|
||||
|
||||
const describe = (el, inner) => {
|
||||
const role = roleOf(el);
|
||||
const name = nameOf(el, role);
|
||||
const svg = el.querySelector('svg[aria-label]');
|
||||
const svgLabel = svg ? clean(svg.getAttribute('aria-label')) : '';
|
||||
let same = null;
|
||||
let position = null;
|
||||
if (role) {
|
||||
// How many visible elements share role and name, and which one this is: the «index» field of the map.
|
||||
same = 0;
|
||||
for (const other of document.querySelectorAll('*')) {
|
||||
if (roleOf(other) !== role || nameOf(other, role) !== name || !visible(other)) continue;
|
||||
if (other === el) position = same;
|
||||
same++;
|
||||
}
|
||||
}
|
||||
return {
|
||||
tag: el.tagName.toLowerCase(),
|
||||
interno: inner && inner !== el && inner.tagName ? inner.tagName.toLowerCase() : null,
|
||||
roleAttributo: el.getAttribute('role'),
|
||||
ruolo: role,
|
||||
ariaLabel: el.getAttribute('aria-label'),
|
||||
alt: el.getAttribute('alt'),
|
||||
titolo: el.getAttribute('title'),
|
||||
testo: fromContent.has(role) ? clean(el.textContent) : null,
|
||||
nome: name,
|
||||
svg: svgLabel || null,
|
||||
nomeDaSvg: !!svgLabel && !clean(el.getAttribute('aria-label')) && name === clean(textOf(el, 0)) && name.includes(svgLabel),
|
||||
collegamento: linkOf(el),
|
||||
tabindex: el.getAttribute('tabindex'),
|
||||
uguali: same,
|
||||
posizione: position,
|
||||
};
|
||||
};
|
||||
|
||||
const onClick = (event) => {
|
||||
try {
|
||||
const inner = event.target && event.target.nodeType === 1 ? event.target : null;
|
||||
const el = inner && inner.closest ? inner.closest('a[href], button, [role], [tabindex]') : null;
|
||||
const record = {
|
||||
n: records.length + 1,
|
||||
ora: new Date().toTimeString().slice(0, 8),
|
||||
prima: shapeOf(location.pathname),
|
||||
dopo: null,
|
||||
elemento: el ? describe(el, inner) : null,
|
||||
};
|
||||
records.push(record);
|
||||
setTimeout(() => {
|
||||
try { record.dopo = shapeOf(location.pathname); } catch { /* the record stays without it */ }
|
||||
}, 1500);
|
||||
console.log(`Febe: clic ${record.n} registrato${el ? '' : ' (nessun comando sotto il puntatore)'}.`);
|
||||
} catch {
|
||||
// Never disturb the page: a click that cannot be described is just not recorded.
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('click', onClick, { capture: true, passive: true });
|
||||
|
||||
// The records, masked, ready for bersagli.<sito>.json: «<x>» becomes «*» (one segment), «NOME» becomes «.+».
|
||||
const output = () => records.map((r) => {
|
||||
const e = r.elemento;
|
||||
if (!e) return { n: r.n, ora: r.ora, prima: r.prima, dopo: r.dopo, elemento: null };
|
||||
const element = {
|
||||
...e,
|
||||
roleAttributo: mask(e.roleAttributo),
|
||||
ariaLabel: mask(e.ariaLabel),
|
||||
alt: mask(e.alt),
|
||||
titolo: mask(e.titolo),
|
||||
testo: mask(e.testo),
|
||||
nome: mask(e.nome),
|
||||
svg: mask(e.svg),
|
||||
};
|
||||
const name = element.nome ? '^' + escapeRegex(element.nome).replace(/NOME/g, '.+') + '$' : '';
|
||||
return {
|
||||
n: r.n,
|
||||
ora: r.ora,
|
||||
prima: r.prima,
|
||||
dopo: r.dopo,
|
||||
elemento: element,
|
||||
perLaMappa: {
|
||||
role: e.ruolo,
|
||||
name,
|
||||
href: e.collegamento && e.collegamento.sito ? e.collegamento.path.replace(/<x>/g, '*') : '',
|
||||
index: e.posizione,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// copy() is a utility of the DevTools Console, there while the Console runs a command: kept from the paste too.
|
||||
const copier = typeof copy === 'function' ? copy : null;
|
||||
globalThis.febeBersagli = () => {
|
||||
const text = JSON.stringify(output(), null, 2);
|
||||
let copied = true;
|
||||
if (typeof copy === 'function') {
|
||||
copy(text);
|
||||
} else if (copier) {
|
||||
copier(text);
|
||||
} else {
|
||||
copied = false;
|
||||
}
|
||||
|
||||
if (copied) {
|
||||
console.log(`Febe: copiati negli appunti ${records.length} clic registrati. Incollali in un file di testo e controlla che non resti nessun nome.`);
|
||||
} else {
|
||||
console.log(text);
|
||||
console.log(`Febe: ${records.length} clic registrati, scritti qui sopra: copiali da qui.`);
|
||||
}
|
||||
return records.length;
|
||||
};
|
||||
|
||||
console.log('Febe: raccolta dei bersagli attiva (sola lettura). Naviga come al solito; alla fine scrivi febeBersagli().');
|
||||
})();
|
||||
Reference in new issue
Block a user