Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce9691fe1c | ||
|
|
e10c25d12d | ||
|
|
c4c035d61f | ||
|
|
129ca22449 | ||
|
|
2625eb0f70 | ||
|
|
2bbad2e9b7 | ||
|
|
654076d280 | ||
|
|
c49df4ca7b |
No files matched your search
@@ -361,3 +361,31 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-11-16 | I rifiuti del catalogo delle richieste (`RequestCatalog`) stanno nel codice, non nel JSON: ogni nome che contiene `Mutation`, le famiglie GraphQL di chat, messaggi, presenza, promozioni, pubblicità e telemetria, i percorsi di telemetria e navigazione (`/logging_client_events`, `/ajax/…`, `/ws/`, `/api/v1/web/`, `/api/v1/discover/web/`…), ogni percorso con un host, una query o un valore come primo segmento; GraphQL solo verso `/api/graphql` e `/graphql/query` con POST, gli indirizzi semplici solo con GET; niente intestazione `cookie` nel modello | Una copia di `richieste.<sito>.json` modificata nella cartella dei dati non deve poter togliere un divieto (regole 3, 6) |
|
||||
| 2026-11-16 | `richieste.<sito>.json` ha chiavi in inglese come gli altri file di configurazione; per ogni intestazione e campo dice la fonte del valore (`constant:`, `cookie:csrftoken`, `session:` user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id, `operation`, `variables`, `computed`, `pending` se ancora da stabilire nella tappa S4). Un'operazione con un nome o un valore tolto dalla sonda nelle variabili resta «non configurata» e il client la rifiuta; nessun `doc_id` nel repository. Le categorie del Governatore sono quelle che ci sono già, fino ai tetti per richiesta della tappa S3 | Regola 9: le forme non mostrano tutto, e ciò che manca non si indovina |
|
||||
| 2026-11-16 | Il contratto del client del sito (S1 di #36) si chiude nel codice: un'operazione con un'intestazione o un campo `pending` (o col nome tolto dalla sonda) non può essere configurata, quindi oggi nessuna operazione di Instagram lo è; un permesso vale per una sola richiesta, contato per riferimento (`SpentPermits`) e speso anche se la richiesta è poi rifiutata; i valori del caso hanno una forma (cifre per gli identificativi, i caratteri di un nome utente, di un codice o di una raccolta) e quelli che finiscono nel percorso non portano `/ ? # %` né punti soli; i percorsi del catalogo non hanno segmenti vuoti, `.` o `..` né caratteri fuori da lettere, cifre e `/_.-{}`; un indirizzo semplice non può puntare a GraphQL; la categoria «ricerca» è solo di un'operazione che porta `{search_text}` e nessun account o contenuto, e viceversa; `SiteAnswer` prende l'operazione del catalogo, non un percorso | Revisione della tappa S1: altrimenti una copia modificata nella cartella dei dati (`/./ajax/bz`, che `System.Uri` riduce a `/ajax/bz`), un valore come `..` o un permesso riusato aggirerebbero i divieti delle regole 4, 8, 9 e 10; il tetto della ricerca è fuori dalle sessioni (§7.4) |
|
||||
| 2026-11-16 | Vista remota: watchdog dei fotogrammi facoltativo (`ScreencastOptions.Watchdog`, default dell'host 2 s / 250 ms / 30 s), con riavvio stop+start dopo silenzio o `loadEventFired` senza fotogrammi e attesa che raddoppia fino a 30 s; immagine ferma con `Page.captureScreenshot` se il riavvio non porta nulla | Un ack perso o un cambio di renderer lasciavano la vista bianca per sempre; il raddoppio evita un riavvio ogni 2 s sulle pagine ferme. Nessun comando CDP nuovo |
|
||||
| 2026-11-16 | Dopo un riavvio dei fotogrammi la vista aspetta il primo fotogramma per mezzo secondo (`ScreencastWatchdog.FirstFrameWait`, sull'orologio) prima di mandare l'immagine ferma, e la scarta se durante la cattura arriva un fotogramma vero; il silenzio si conta dall'avvio e l'attesa raddoppia prima dell'avvio | Chromium manda il primo fotogramma solo dopo aver risposto a `Page.startScreencast`: il controllo subito dopo la risposta mandava una cattura a quasi ogni riavvio, e l'immagine ferma poteva sostituire un fotogramma più recente |
|
||||
| 2026-11-16 | Finestra «Browser di Febe» troppo grande per lo schermo: si restringe all'area di lavoro e la pagina si mostra con `ZoomFactor` uguale al rapporto (minimo 0,4) | La pagina tiene le stesse misure CSS (1280×900) per Instagram e per le ricette |
|
||||
| 2026-11-16 | Fuori vista la finestra torna sempre a `Fit` 1 (pagina e `ZoomFactor` al 100%); il rapporto si ricalcola solo quando viene sullo schermo | Su uno schermo piccolo il rapporto restava per le sessioni del motore: le pagine vedevano un `devicePixelRatio` e media query diversi, un browser diverso da quello di sempre (regola 4) |
|
||||
| 2026-11-16 | Su Windows lasciare una pagina di Febe non nasconde né mette a riposo la finestra del browser (cancel con `pageLeft` → `IConnectionService.ReleaseAsync`); resta finché Alberto non la chiude o preme «Ho finito» | La finestra spariva sotto gli occhi di Alberto quando cambiava pagina in Febe |
|
||||
| 2026-11-16 | Finestra ridotta a icona: non vale più come «ho finito»; ha il pulsante nella barra delle applicazioni e dopo 2 minuti torna fuori vista | Ridurla la faceva sparire; S2 vieta di lasciarla ridotta a lungo |
|
||||
| 2026-11-16 | Il pulsante della barra delle applicazioni cambia solo mentre la finestra è fuori vista (aggiunto prima di portarla sullo schermo, tolto dopo averla spostata); sullo schermo la finestra chiede di ridisegnarsi (`RedrawWindow` con i figli, niente che la pagina veda) | WPF cambia `ShowInTaskbar` di una finestra mostrata nascondendola e mostrandola di nuovo (visto con un aggancio a `WM_WINDOWPOSCHANGED`: `SWP_HIDEWINDOW`, poi `SWP_SHOWWINDOW`); S2 vieta di nasconderla sotto gli occhi di Alberto. `ITaskbarList` avrebbe evitato il nascondere, ma il suo comportamento con la finestra fuori vista non si può provare qui |
|
||||
| 2026-11-16 | Ridotta a icona troppo a lungo, la finestra si ripristina coperta (`DWMWA_CLOAK`) e senza fuoco (`SW_SHOWNOACTIVATE`), si sposta fuori vista e solo allora si scopre | Windows ripristina una finestra dove stava sullo schermo: spostare prima la posizione di ripristino non basta, Windows la riporta su uno schermo (provato); senza copertura la finestra appariva e prendeva il fuoco per un attimo |
|
||||
| 2026-11-16 | Dopo un riavvio del processo GPU la finestra riceve bordi di un pixel più bassi e poi quelli veri, e una richiesta di ridisegno | Gli stessi bordi di nuovo possono non essere un cambiamento per WebView2; il ridisegno senza cambio di misura non è provato con un arresto vero della GPU |
|
||||
| 2026-11-16 | «Pagina iniziale» della finestra di Windows e della vista remota passa da `BrowserConnectionService.OpenStartPageAsync`: aspetta la fine della sessione del motore e il turno della pagina, e agisce solo mentre Alberto guida | Come l'apertura dal riposo: un passo di una sessione che finisce o della ricerca dei profili (#37) non deve trovarsi la pagina cambiata a metà |
|
||||
| 2026-11-16 | I corpi facoltativi delle richieste (`begin`, `cancel`, `browser/show`) si leggono con `ApiHttp.OptionalBodyAsync`: senza lunghezza dichiarata, un byte dice se il corpo c'è | Un POST vuoto a pezzi (o in HTTP/2) arriva senza `Content-Length` e finiva in 400 «Richiesta non leggibile» |
|
||||
| 2026-11-16 | La pagina Browser toglie `?accesso=1` dall'indirizzo appena l'ha usato | Ricaricare la pagina, o riaprire la scheda, riapriva la pagina di accesso anche da collegati |
|
||||
| 2026-11-16 | `IBrowserWindow.ShowAsync` tolto: «Apri il browser» passa da `IConnectionService.ShowBrowserAsync(openLogin)` | Aprire la pagina iniziale richiede il permesso di guida e il turno della pagina, che tiene il servizio di collegamento |
|
||||
| 2026-11-16 | Con `--accesso-di-prova` il primo controllo della sessione all'avvio non segnala nulla (`RefreshAsync` con `mayReport: false`) | La sessione mancante è quella che l'accesso automatico sta per aprire, non una disconnessione |
|
||||
| 2026-11-16 | «Pagina iniziale» vale finché dura il permesso di chi l'ha premuta: la finestra di Windows e la vista remota passano un gettone che si annulla con il loro permesso, e la connessione guarda di nuovo, con il turno della pagina in mano, che Alberto guidi ancora; senza turno rinuncia invece di prendere la pagina. Nella vista remota la pressione corre a parte, una per volta, e intanto clic e tasti si scartano | L'attesa (fine della sessione, turno della pagina) può durare mezzo minuto: Alberto poteva aver chiuso la finestra e Febe navigava senza permesso e fuori dal Governatore (regole 7 e 8); nella vista l'attesa nel ciclo di ricezione bloccava i comandi e poi li riversava sulla pagina nuova |
|
||||
| 2026-11-16 | `Repaint` della finestra «Browser di Febe» chiede solo di ridisegnare (`RDW_INVALIDATE \| RDW_ALLCHILDREN`), senza `RDW_UPDATENOW` | Le finestre figlie sono del processo del browser di WebView2: un processo bloccato avrebbe fermato il thread dell'interfaccia in un ridisegno sincrono |
|
||||
| 2026-11-16 | Le porte libere delle prove (`LocalTestSite.FreePort`) vengono da 20000–29999, ciascuna una volta sola per processo e provata prima di darla, non più dalla porta 0 del sistema | Nella CI 350 (#52) Chromium non è partito perché la porta di debug, presa dall'intervallo effimero di Linux e chiusa prima di usarla, era stata nel frattempo occupata (come per #46: la causa, non un tempo più lungo) |
|
||||
| 2026-11-16 | Il client del sito (`HttpSiteRequester`, tappa S2 di #36) sta in Febe.Core accanto ai suoi contratti, come il client di Telegram: `SocketsHttpHandler` senza rinvii (`AllowAutoRedirect = false`), senza cookie propri (`UseCookies = false`, i cookie della sessione in una sola riga `Cookie` nel loro ordine), gzip, deflate e brotli, HTTP/2 con ripiego su 1.1 (`RequestVersionOrLower`), una connessione, nessun `traceparent` (`ActivityHeadersPropagator = null`); una richiesta per volta: una seconda chiamata mentre la prima è in volo si rifiuta (`SiteRequestRefusedException`), non si mette in coda, come fa già `ScriptedRequester`; tempo massimo e attesa della connessione nelle opzioni; un corpo che non si decomprime (gzip o deflate rovinati: `InvalidDataException`, brotli: `InvalidOperationException`) è `SiteUnreachableReason.Broken`, non «troppo grande»; `Dispose` interrompe la richiesta in volo come annullamento e il semaforo non si chiude sotto chi lo usa | Nessun pacchetto nuovo; un'attività di ASP.NET Core avrebbe aggiunto `traceparent` a ciò che parte, che il modello non elenca (regola 4). Le sole intestazioni fuori dal modello sono `Host`, `Content-Length` e l'`Accept-Encoding: gzip, deflate, br` che la decompressione scrive da sé: è ciò che §6.0 chiede, non un'intestazione del browser copiata. Una richiesta in coda sarebbe partita appena finita la precedente, prima che chi l'aveva mandata leggesse un 429 o un rinvio in quella risposta (regola 8) e più vicina del ritmo del Governatore (§7.7) |
|
||||
| 2026-11-16 | Il client del sito va solo a `https://www.instagram.com/` con il catalogo di Instagram e solo a un indirizzo IP di loopback (127.0.0.0/8, ::1; non il nome `localhost`) con ogni altro catalogo; ogni indirizzo costruito si ricontrolla prima di partire. Proxy di sistema per Instagram, nessun proxy per il loopback | Regola 3: un indirizzo sbagliato si rifiuta alla costruzione, senza aprire connessioni. Un nome si può far puntare altrove (file hosts), un indirizzo IP di loopback no; nessun browser raggiunge il loopback attraverso un proxy |
|
||||
| 2026-11-16 | Sessione salvata come interfaccia `ISiteSession` in Febe.Core: istantanea in sola lettura (`SiteSessionValues`: cookie in ordine, user agent, valori della pagina, `doc_id` per operazione) e un aggiornamento per risposta (`SiteSessionUpdate`: cookie rinnovati e cancellati, claim) in una sola scrittura; `InMemorySiteSession` per prove e sito di prova fino al file cifrato della tappa S4. `Set-Cookie` letto come un browser (RFC 6265: il valore tale e quale, virgolette comprese; valore vuoto o `""`, `Max-Age` ≤ 0 o `Expires` passato cancellano; `Max-Age` vince su `Expires`; un altro dominio si ignora) con la scadenza: un cookie scaduto non si manda, il cookie di sessione scaduto è una sessione mancante; i cookie nuovi in fondo nell'ordine delle righe `Set-Cookie`, quelli rinnovati al loro posto. L'aggiornamento si scrive appena arrivano le intestazioni, senza il gettone di annullamento di chi chiama, e solo sulla stessa copia dal browser (`SiteSessionValues.Capture`, uguale attraverso i rinnovi e nuovo a ogni accesso): la risposta tardiva di una sessione sostituita non tocca la nuova. Il cookie di sessione cancellato si applica, si scrive nel registro e la risposta lo riporta. Dominio e percorso non si tengono: S4 copia con `Network.getCookies` i soli cookie che il browser manderebbe all'indirizzo del sito | Il file cifrato deve scrivere in modo atomico: un aggiornamento per risposta, mai mezzo. Il sito cambia i valori quando manda le intestazioni: un corpo troppo grande, interrotto o annullato non deve lasciare nella sessione un cookie che il sito ha già tolto. Tolte le virgolette, `rur` tornava al sito diverso da come lo manda il browser (regola 4). Un nuovo accesso ricopia tutto e vince (§6.0). Il cookie cancellato si toglie come farebbe il browser: la richiesta successiva non parte (sessione mancante), e la risposta che l'ha cancellato è già un segnale |
|
||||
| 2026-11-16 | Su Windows il client del sito non si costruisce (per Instagram, non per il sito di prova sul loopback) se è impostata una fra `HTTP_PROXY`, `HTTPS_PROXY` e `ALL_PROXY`: il messaggio dice quali, mai il loro valore | `HttpClient.DefaultProxy` su Windows legge quelle variabili prima delle impostazioni di sistema, che sono le sole che WebView2 usa: la stessa sessione sarebbe uscita da due strade (§6.0, «su Windows le impostazioni proxy del sistema, come WebView2»). In Docker Chromium legge le stesse variabili di .NET, e lì valgono |
|
||||
| 2026-11-16 | Senza un claim nella sessione salvata il client del sito manda `x-ig-www-claim: 0` (`SiteSessionValues.InitialClaim`), poi quello che il sito dà con `x-ig-set-www-claim`. Da confermare con i campioni (H13) | È il valore che la pagina manda finché il sito non ne ha dato uno; senza, una sessione appena copiata non avrebbe mandato nessuna richiesta, e quindi non avrebbe mai ricevuto un claim |
|
||||
| 2026-11-16 | Il catalogo rifiuta un'operazione configurata senza `user-agent: session:user_agent`, e il client del sito ricontrolla prima di costruire la richiesta | Lo stack HTTP non aggiunge un user agent: una copia modificata di `richieste.instagram.json` avrebbe fatto partire richieste senza, che non sono quelle del browser (regola 4) |
|
||||
| 2026-11-16 | Senza sessione salvata, senza il cookie di sessione o senza un valore che il modello chiede (`cookie:csrftoken`, `session:…`, il `doc_id` dell'operazione) la richiesta non parte: `SiteSessionMissingException` (un `SiteRequestRefusedException`) con il solo nome del valore, che `SiteAnswerSignals.ForMissingSession` legge come Disconnessione | §7.6: «la sessione salvata manca» è una Disconnessione; una richiesta senza un'intestazione del modello non è quella del browser (regola 4) |
|
||||
| 2026-11-16 | Le variabili GraphQL si scrivono dal modello nell'ordine e con i tipi del file (numeri e vero/falso come sono, `"{nome}"` sostituito dal valore come testo), compatte e con un serializzatore proprio identico a `JSON.stringify` (lettere non ASCII, `< > &`, emoji, U+2028, U+2029 e DEL così come sono; controlli e surrogati soli come `\u` con cifre minuscole); il modulo con il serializzatore della pagina (`URLSearchParams`: spazio come `+`); i parametri e i campi nell'ordine del file (`SiteOperation.ParameterOrder`, `HeaderOrder`, `BodyOrder`) | La richiesta deve essere quella della pagina; il dizionario congelato del catalogo non teneva l'ordine; `Utf8JsonWriter` sostituiva emoji, U+2028 e DEL anche con `UnsafeRelaxedJsonEscaping` |
|
||||
| 2026-11-16 | `SiteAnswerSignals` (Febe.Core) legge i segnali di §7.6 da una `SiteAnswer`, qualunque cosa l'abbia portata: prima le regole di stato di `segnali.json` (429), poi il cookie di sessione cancellato, un rinvio, 401 e 403, poi con qualunque stato HTML al posto del JSON, un corpo che non è JSON (anche vuoto) e le regole di testo, infine, esclusi 404 e 5xx con un JSON (risposta, decide la ricetta o la tappa S3), i campi attesi mancanti; questi casi sono Verifica marcata H16. Non è ancora collegato al motore (S3). `SiteAnswer.RootFieldsPresent` dice se il client ha trovato i campi attesi | Decisione del 16 novembre (H16: Verifica finché le forme vere non sono note); un «attendi qualche minuto» in un JSON breve resta un Rallentamento anche senza i campi attesi. §6.0 ferma su una risposta che non è JSON senza eccezioni di stato: una pagina d'accesso o d'errore HTML servita con 404 o 5xx non è un «non trovato» |
|
||||
| 2026-11-16 | Il sito di prova risponde al client del sito sotto `/api/` (`/api/dati/…` come `/dati/…`, e `POST /api/graphql` con la query `ProvaProfiloQuery`), controllando cookie `sessione_prova`, `x-csrftoken` uguale al cookie `csrftoken`, `x-app-id`, `doc_id`, gettoni e tipi delle variabili, con risposte generiche marcate H16 (302 all'accesso, 401, 403 HTML, 400); le pagine restano su `/dati/`, che non controlla nulla. `richieste.prova.json` passa a `/api/` e aggiunge `x-app-id`, `x-csrftoken` e la query GraphQL; `SiteControl.ReplyToDirect` gioca 429, rinvii, HTML, JSON senza campi, cookie rinnovato o cancellato, nuovo claim; i modi armati «dopo N richieste di dati» contano anche le richieste del client, e `sessione-scaduta` chiude la sessione anche sul sito | Le pagine del sito di prova non mandano `x-csrftoken`: controllare `/dati/` avrebbe cambiato le prove con il browser. Il sito non dà ancora alle pagine nessuno dei valori che controlla (cookie `csrftoken`, `app_id`, `lsd`, `fb_dtsg`, il `doc_id` di `ProvaProfiloQuery`, un claim): li mettono le prove nella sessione; li deve esporre la tappa S4, con la copia della sessione. Con le ricette sul client del sito (S3) un arresto «dopo N richieste» non sarebbe mai scattato |
|
||||
| 2026-11-16 | Il sito di prova apre una sessione nuova (`aperta-N`, mai riusata) a ogni visita senza sessione viva, e chiude la sessione dalla stessa parte sia per le pagine sia per `/api/`; `attiva` resta solo come sessione iniziale per le prove senza browser | Dopo una sessione scaduta un nuovo accesso deve dare una sessione che anche il client del sito accetta, altrimenti le prove di «nuovo accesso e Riprendi» (S3, S4) non possono passare |
|
||||
@@ -101,7 +101,8 @@ riprendere: lascia Febe in pausa.
|
||||
|
||||
## Che cosa fare dopo una disconnessione
|
||||
|
||||
1. «Apri il browser»: la pagina mostra l'accesso di Instagram.
|
||||
1. «Apri il browser» nella striscia rossa: il browser apre la pagina di accesso di Instagram (anche se era a riposo
|
||||
sulla pagina vuota).
|
||||
2. Accedi a mano (nome utente, password, eventuale codice), aspetta la pagina iniziale, «Ho finito».
|
||||
3. «Riprendi». Anche qui riparte l'avvio graduale.
|
||||
|
||||
|
||||
@@ -19,6 +19,14 @@
|
||||
automatica sono spenti.
|
||||
- Ciò che scrivi nella finestra del browser va direttamente alla pagina di Instagram: Febe non riceve la password.
|
||||
Mentre usi il browser il motore resta fermo; quando hai finito chiudi la finestra (o «Ho finito»): torna fuori vista.
|
||||
Lasciare la pagina di Febe da cui l'hai aperta non la chiude: resta sullo schermo finché non la chiudi tu.
|
||||
- Sullo schermo la finestra ha il suo pulsante nella barra delle applicazioni, così ridurla a icona non la fa sparire.
|
||||
Ridotta a icona però non può restare a lungo (S2): dopo due minuti Febe la rimette fuori vista, come se l'avessi
|
||||
chiusa. Se lo schermo è troppo piccolo per la pagina e la sua barra, la finestra si restringe e mostra la pagina
|
||||
rimpicciolita, sempre della stessa misura per Instagram; fuori vista, quando la usa il motore, la pagina torna al
|
||||
100%. Nella barra in basso: «Indietro», «Ricarica», «Pagina
|
||||
iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) e l'indirizzo; sulla pagina
|
||||
vuota di riposo la barra dice «Il browser è a riposo su una pagina vuota».
|
||||
- Funzioni di Windows offerte all'interfaccia: scelta di una cartella, «Mostra nella cartella», indirizzi aperti nel
|
||||
tuo browser predefinito (mai nel browser di Febe), notifiche di Windows, avvio con il computer.
|
||||
|
||||
|
||||
@@ -64,10 +64,23 @@ Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostaz
|
||||
## Usare il browser a mano
|
||||
|
||||
Da collegato, **«Usa il browser»** apre il browser di Febe (in Docker la pagina «Browser», con la vista remota e i
|
||||
comandi «Indietro» e «Ricarica»; su Windows la finestra). Serve per controllare qualcosa a mano. Mentre lo usi il
|
||||
motore resta fermo; quando hai finito premi «Ho finito». Se lasci la pagina Browser, o la pagina Collegamento mentre
|
||||
accedi, senza premere «Ho finito» (un'altra pagina, la scheda chiusa o ricaricata), vale come «Annulla»: il browser
|
||||
torna sulla pagina vuota e il motore può lavorare di nuovo.
|
||||
comandi «Indietro», «Ricarica» e «Pagina iniziale»; su Windows la finestra, con gli stessi tre pulsanti nella barra in
|
||||
basso). Serve per controllare qualcosa a mano. Mentre lo usi il motore resta fermo; quando hai finito premi «Ho finito».
|
||||
|
||||
Quando Febe non lo usa, il browser resta **a riposo su una pagina vuota**. Se lo apri mentre è a riposo, Febe apre per
|
||||
te la **pagina iniziale**: la home di Instagram se sei collegato, la pagina di accesso se non lo sei (o se Instagram ti
|
||||
ha scollegato). Se invece c'è già una pagina (per esempio quella di una verifica), la lascia com'è. «Pagina iniziale»
|
||||
ci torna quando vuoi; se la barra dice «Il browser è a riposo su una pagina vuota», premilo. Se Febe sta finendo un
|
||||
lavoro nel browser, «Pagina iniziale» aspetta che finisca: può volerci qualche secondo (nella vista remota, intanto,
|
||||
clic e tasti non arrivano al browser). Se nel frattempo chiudi il browser, o se il lavoro dura troppo, non succede
|
||||
nulla: premilo di nuovo.
|
||||
|
||||
Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la
|
||||
scheda chiusa o ricaricata):
|
||||
|
||||
- **in Docker** vale come «Annulla»: il browser torna sulla pagina vuota e il motore può lavorare di nuovo;
|
||||
- **su Windows** la finestra «Browser di Febe» resta com'è, sullo schermo e con la sua pagina, finché non la chiudi (o
|
||||
premi «Ho finito»); finché è sullo schermo il motore resta fermo.
|
||||
|
||||
## Scollegarsi
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@ dati.
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| La vista remota è lenta o non risponde | La vista è un'immagine della pagina inviata dal server: aspetta qualche secondo dopo ogni clic. Se dice «La vista remota non risponde», premi «Riprova»; se si apre in un'altra finestra, la precedente si chiude da sola (una vista alla volta) |
|
||||
| La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso |
|
||||
| Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) |
|
||||
| «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» |
|
||||
| Dopo un riavvio Febe chiede di nuovo l'accesso | Non dovrebbe: la sessione è nel profilo del browser in `/dati/browser`. Controlla che `/dati` sia un volume persistente e non sia stato cancellato; riferisci il caso (è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)) |
|
||||
|
||||
|
||||
+43
-2
@@ -7,7 +7,7 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
|
||||
## In breve
|
||||
|
||||
**16 novembre 2026: richieste dirette con la sessione copiata dal browser** (#36, tappe S0 e S1; #52).
|
||||
**16 novembre 2026: richieste dirette con la sessione copiata dal browser** (#36, tappe S0, S1 e S2; #52).
|
||||
|
||||
- Il HAR nuovo di Alberto (home, due ricerche, due profili) è stato letto solo in forma aggregata, senza stampare
|
||||
valori: 487 voci complete, troncato a 55,5 MB, **nessun corpo delle risposte del sito** (va rifatto più corto, #35).
|
||||
@@ -23,7 +23,22 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
viste. Le tappe S0–S7 stanno in #36.
|
||||
- **Il browser che a volte restava vuoto** (#52): nove cause trovate e ordinate (la pagina di riposo `about:blank`
|
||||
mostrata all'apertura, «Apri il browser» dopo una disconnessione, la finestra nascosta su Windows quando si lascia
|
||||
la pagina, lo schermo remoto senza controllo dei fotogrammi in Docker, e altre); correzione su un ramo a parte.
|
||||
la pagina, lo schermo remoto senza controllo dei fotogrammi in Docker, e altre). Corretto:
|
||||
- aperto dal riposo, il browser va alla home se collegato, altrimenti all'accesso, come azione di Alberto; pulsante
|
||||
«Pagina iniziale» nella finestra e nella vista remota, che aspetta la fine della sessione del motore e il turno
|
||||
della pagina e vale solo finché dura il permesso di guida di chi l'ha premuto; avviso «a riposo su una pagina
|
||||
vuota»; «Indietro» salta la pagina di riposo;
|
||||
- «Apri il browser» della striscia rossa apre l'accesso; con `--accesso-di-prova` niente falso allarme all'avvio;
|
||||
- Windows: lasciare una pagina di Febe non nasconde più la finestra; pulsante nella barra delle applicazioni solo
|
||||
mentre è sullo schermo (cambiarlo con la finestra visibile la nasconde per un attimo); ridotta a icona non vale
|
||||
più «Ho finito» e dopo 2 minuti torna fuori vista senza lampeggiare (DWM cloak); su uno schermo piccolo la finestra
|
||||
si restringe con lo zoom della pagina, che torna a 1 fuori vista; ridisegno dopo il riavvio del processo GPU;
|
||||
- Docker: controllo dei fotogrammi della vista remota (riavvio dopo 2 s di silenzio o un caricamento senza
|
||||
fotogrammi, attesa che raddoppia fino a 30 s, immagine ferma con `Page.captureScreenshot` se il riavvio non porta
|
||||
nulla in 500 ms), «Nessuna immagine dal browser» con «Riprova» dopo 8 s, registro della vista; nessun comando CDP
|
||||
nuovo. 16 righe in `docs/decisioni.md`, due giri di revisione indipendente (14 punti, tutti chiusi).
|
||||
- **Non verificato**: il disegno vero dopo un crash della GPU, uno schermo piccolo vero, la vista remota con Chromium
|
||||
vero (solo nella CI Linux), le schermate nuove contro il mockup.
|
||||
- **Tappa S1, il giunto senza cambiare comportamento**: `ResponseDelivery` (in Core) consegna ai lettori le risposte
|
||||
catturate e, da S2, quelle chieste, nello stesso modo; `ResponseTap` la usa con gli stessi conteggi e messaggi.
|
||||
Contratti `SiteRequest`, `SiteAnswer` (che non stampa mai corpi, cookie o percorsi concreti) e `ISiteRequester`,
|
||||
@@ -39,6 +54,32 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
catalogo di prova ne ha 8 configurate su 11. Prove nuove: 87 (`RequestCatalogTests`, `SiteRequesterTests`,
|
||||
`ResponseDeliveryTests`, con `ScriptedRequester` sui campioni ripuliti). Il campione 000016 viene da
|
||||
`PolarisProfilePostsQuery`, non da `media/{numero}/info`.
|
||||
- **Tappa S2, il client del sito contro il sito di prova** (ancora non collegato al motore):
|
||||
- `HttpSiteRequester` (Core) è l'unica classe che parla col sito. Va solo a `https://www.instagram.com/` (porta
|
||||
443) o, per il sito di prova, a un indirizzo di loopback. Non segue i rinvii, non tiene cookie propri e manda
|
||||
i cookie della sessione in una sola intestazione. Decomprime gzip, deflate e brotli; usa HTTP/2 con ripiego su
|
||||
1.1, mai HTTP/3.
|
||||
- Una richiesta per volta: una seconda richiesta mentre ce n'è una in corso è rifiutata, mai messa in coda.
|
||||
- Manda solo le intestazioni del catalogo, nell'ordine del file, con l'user agent tale e quale; niente
|
||||
`traceparent`. Su Windows rifiuta di partire se è impostata una variabile `HTTP_PROXY`, `HTTPS_PROXY` o
|
||||
`ALL_PROXY`, che WebView2 non userebbe.
|
||||
- Applica alla sessione i cookie rinnovati e `x-ig-set-www-claim` appena arrivano le intestazioni, anche se poi
|
||||
il corpo fallisce. I cookie scaduti non si mandano; una risposta di una sessione già sostituita si ignora.
|
||||
- Registra solo operazione, forma del percorso e stato.
|
||||
- `ISiteSession` con `InMemorySiteSession`; S4 aggiunge la copia cifrata.
|
||||
- `SiteAnswerSignals` traduce le risposte nei segnali di §7.6, non ancora collegato al motore:
|
||||
- 429 → Rallentamento, dalle regole di `segnali.json`;
|
||||
- rinvio, 401, 403, cookie di sessione cancellato, HTML o testo dove si aspetta JSON, campi attesi
|
||||
mancanti → Verifica, con forme generiche segnate H16 (un 5xx vuoto o HTML compreso);
|
||||
- sessione mancante o scaduta → Disconnessione.
|
||||
- Il sito di prova risponde a `/api/dati/…` e `POST /api/graphql` come dice `richieste.prova.json` (9
|
||||
operazioni configurate). Controlla il cookie di sessione, `x-csrftoken` e gli altri gettoni. Con
|
||||
`/_controllo/diretto` simula 429, i rinvii all'accesso e alla verifica, HTML, campi mancanti, cookie rinnovati
|
||||
o cancellati e il claim.
|
||||
- Prove nuove: 72 (`HttpSiteRequesterTests` col sito di prova vero, `HttpSiteRequesterShapeTests` con un
|
||||
ascoltatore TCP che legge i byte, `SiteAnswerSignalsTests`, `SiteSessionTests`).
|
||||
- Revisione su tre lenti: 20 punti, 18 reali, corretti; il dominio e il percorso dei cookie passano a S4. Più un
|
||||
difetto del sito di prova, corretto: le sessioni chiuse non tornavano valide dopo un nuovo accesso.
|
||||
- **Domande per Alberto** (anche su #36): la sonda può tenere i nomi di campo che oggi toglie («(nome tolto)»: sono
|
||||
nomi di codice, non valori) e il tipo JSON dei valori (numero o testo)? Le corrispondenze `__user`/`av` →
|
||||
identificativo dell'account e `reel_ids_arr` → account sono dedotte, non confermate.
|
||||
|
||||
@@ -17,9 +17,10 @@ namespace Febe.App;
|
||||
/// means that the session cookie exists in the browser profile: only its existence is checked
|
||||
/// (<c>Network.getCookies</c>, names only), never its value. Opening the login page is Alberto's action, not the
|
||||
/// engine's (rule 7, last sentence): it happens only while he holds the «driving» lease and the engine is still.
|
||||
/// On Windows the browser is the window «Browser di Febe»: «Accedi» and «Portalo in primo piano» bring it to the front,
|
||||
/// «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the profile. In Docker
|
||||
/// showing and hiding do nothing (the remote view shows the browser).
|
||||
/// On Windows the browser is the window «Browser di Febe»: «Accedi», «Apri il browser» and «Portalo in primo piano»
|
||||
/// bring it to the front, «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the
|
||||
/// profile; leaving a page of Febe leaves it as it is. In Docker showing and hiding do nothing (the remote view shows
|
||||
/// the browser).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
@@ -29,6 +30,11 @@ namespace Febe.App;
|
||||
/// must not stay still for ever.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Alberto never meets the empty rest page (issue #52): when he takes the browser while it rests there, his own first
|
||||
/// navigation (rule 7, like the login page) opens <see cref="StartPageUrl"/> — the site's home when connected, the login
|
||||
/// page when not connected or after a disconnection.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A session cookie that disappears outside a session (or is missing at start-up after a connection) is a disconnection
|
||||
/// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only
|
||||
/// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega».
|
||||
@@ -54,6 +60,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
private readonly IClock _clock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly string _loginUrl;
|
||||
private readonly string _homeUrl;
|
||||
private readonly SessionCookieOptions _cookie;
|
||||
private readonly SemaphoreSlim _commands = new(1, 1);
|
||||
private readonly Lock _gate = new();
|
||||
@@ -65,7 +72,15 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
private bool? _disconnectedByUser;
|
||||
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
|
||||
|
||||
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, SessionCookieOptions cookie)
|
||||
/// <param name="browser">The browser of Febe.</param>
|
||||
/// <param name="storage">The database (first connection, «Scollega»).</param>
|
||||
/// <param name="tracker">When Alberto last used the browser.</param>
|
||||
/// <param name="clock">The composition's clock.</param>
|
||||
/// <param name="log">Febe's log.</param>
|
||||
/// <param name="loginUrl">The page «Accedi a Instagram» opens.</param>
|
||||
/// <param name="homeUrl">The site's home, the start page once connected.</param>
|
||||
/// <param name="cookie">The session cookie looked for (its name only).</param>
|
||||
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
||||
@@ -73,6 +88,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
|
||||
_homeUrl = homeUrl ?? throw new ArgumentNullException(nameof(homeUrl));
|
||||
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
|
||||
}
|
||||
|
||||
@@ -91,6 +107,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the
|
||||
/// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection
|
||||
/// (spec §7.6), when Instagram's home would only send him there.
|
||||
/// </summary>
|
||||
public string StartPageUrl =>
|
||||
IsConnected == true && _engine?.Services.Breaker.State.Status != BreakerStatus.Disconnected ? _homeUrl : _loginUrl;
|
||||
|
||||
/// <summary>
|
||||
/// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition
|
||||
/// marks it as «Tu» (<see cref="Account.IsMine"/>); the status shows that account. Raised after every change of the
|
||||
@@ -104,6 +128,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// </summary>
|
||||
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>
|
||||
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
|
||||
/// wait; tests shorten it.
|
||||
/// </summary>
|
||||
public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>The engine, once it exists (it is built after the browser).</summary>
|
||||
public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine));
|
||||
|
||||
@@ -150,21 +180,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
if (openLogin)
|
||||
{
|
||||
// The engine ends its session when the lease starts; wait for it before taking the page. A search step
|
||||
// in progress (issue #37) stops at its next check of the lease: the login page waits for its turn.
|
||||
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
||||
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
||||
var result = await _browser.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", result.Succeeded
|
||||
? "Alberto usa il browser: pagina di accesso aperta."
|
||||
: "Alberto usa il browser: la pagina di accesso non si è aperta (errore di rete del browser).");
|
||||
}
|
||||
else
|
||||
{
|
||||
_log.Info("collegamento", "Alberto usa il browser.");
|
||||
}
|
||||
await OpenForAlbertoAsync(openLogin, ct).ConfigureAwait(false);
|
||||
|
||||
// Windows: the window «Browser di Febe» comes to the front (Docker: nothing, the remote view shows it).
|
||||
await ShowQuietlyAsync(ct).ConfigureAwait(false);
|
||||
@@ -175,6 +191,116 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ShowBrowserAsync(bool openLogin, CancellationToken ct)
|
||||
{
|
||||
EnsureBrowser();
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
|
||||
// Alberto's hold while his page opens: the window takes its own lease when it comes on screen, and holds the
|
||||
// engine still for as long as it stays there (closing it ends it, as before).
|
||||
var hold = _browser.UserDriving.Begin();
|
||||
try
|
||||
{
|
||||
_tracker.MarkUsed(_clock.Now);
|
||||
await OpenForAlbertoAsync(openLogin, ct).ConfigureAwait(false);
|
||||
await _browser.ShowToUserAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
hold.Dispose();
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Pagina iniziale» of the window's bar and of the remote view (issue #52): Alberto's own navigation (rule 7) to
|
||||
/// <see cref="StartPageUrl"/>, as when he takes the browser from the rest page — after the engine's session ended and
|
||||
/// with the page's turn, so that no step of a session or of the profile search has its page swapped under it. Only
|
||||
/// while he is at the browser: otherwise the page is the engine's and nothing happens.
|
||||
/// </summary>
|
||||
/// <param name="ct">
|
||||
/// Cancelled when the lease of whoever pressed the button ends (the window closed, the remote view closed): the press
|
||||
/// is then forgotten, whatever it was waiting for.
|
||||
/// </param>
|
||||
/// <remarks>
|
||||
/// The waits can last up to <see cref="PageTurnWait"/> and more: Alberto may have let go of the browser meanwhile, and
|
||||
/// then the page is the engine's again (rules 7 and 8: no navigation without his lease, outside the Governor). So
|
||||
/// right before navigating, with the page's turn in hand, it looks again: he still drives and the caller's lease still
|
||||
/// holds. Without the page's turn (a step of the search kept it) nothing happens either: the page is not taken from
|
||||
/// under the step.
|
||||
/// </remarks>
|
||||
public async Task OpenStartPageAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!_browser.UserIsDriving)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
||||
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
||||
if (_engine is not null && turn is null)
|
||||
{
|
||||
_log.Info("collegamento", "«Pagina iniziale» non aperta: la pagina è ancora occupata dalla ricerca dei profili. Riprova fra poco.");
|
||||
return;
|
||||
}
|
||||
|
||||
// The last look, with the page's turn in hand (no recipe and no search step can open a page until it is given
|
||||
// back): Alberto still drives and the caller's lease still holds.
|
||||
if (ct.IsCancellationRequested || !_browser.UserIsDriving)
|
||||
{
|
||||
_log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser.");
|
||||
return;
|
||||
}
|
||||
|
||||
var target = StartPageUrl;
|
||||
var what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito";
|
||||
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", result.Succeeded
|
||||
? $"«Pagina iniziale»: {what} aperta."
|
||||
: $"«Pagina iniziale»: {what} non aperta (errore di rete del browser).");
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
_log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ReleaseAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (ReleaseLease())
|
||||
{
|
||||
_log.Info("collegamento", "Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_commands.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<FinishResult> FinishAsync(CancellationToken ct)
|
||||
{
|
||||
await _commands.WaitAsync(ct).ConfigureAwait(false);
|
||||
@@ -305,16 +431,18 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// <summary>
|
||||
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
|
||||
/// and after the test site's automatic login. A session that went away (or is missing at start-up after a
|
||||
/// connection) while Alberto is not at the browser is reported to the breaker as a disconnection (spec §7.6).
|
||||
/// connection) while Alberto is not at the browser is reported to the breaker as a disconnection (spec §7.6) —
|
||||
/// unless <paramref name="mayReport"/> is false: the first look of a start with the test site's automatic login,
|
||||
/// which is about to open the session itself (issue #52: a false disconnection at every development start).
|
||||
/// </summary>
|
||||
public async Task<bool?> RefreshAsync(CancellationToken ct)
|
||||
public async Task<bool?> RefreshAsync(CancellationToken ct, bool mayReport = true)
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
{
|
||||
return IsConnected;
|
||||
}
|
||||
|
||||
var connected = await CheckAsync(force: true, mayReport: true, ct).ConfigureAwait(false);
|
||||
var connected = await CheckAsync(force: true, mayReport, ct).ConfigureAwait(false);
|
||||
if (connected == true)
|
||||
{
|
||||
await MarkConnectedAsync(ct).ConfigureAwait(false);
|
||||
@@ -528,6 +656,64 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Alberto's own first navigation (rule 7: not an engine action, no Governor), under his lease: the login page when
|
||||
/// asked for, and the start page when the browser rests on the empty page (issue #52). Any other page stays as it is
|
||||
/// — the one he was using, or the verification page of a stop.
|
||||
/// </summary>
|
||||
private async Task OpenForAlbertoAsync(bool openLogin, CancellationToken ct)
|
||||
{
|
||||
if (!openLogin && !IsRest(await FullUrlAsync(ct).ConfigureAwait(false)))
|
||||
{
|
||||
_log.Info("collegamento", "Alberto usa il browser.");
|
||||
return;
|
||||
}
|
||||
|
||||
// The engine ends its session when the lease starts; wait for it before taking the page. A search step in
|
||||
// progress (issue #37) stops at its next check of the lease: Alberto's page waits for its turn.
|
||||
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
|
||||
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
|
||||
string target;
|
||||
string what;
|
||||
if (openLogin)
|
||||
{
|
||||
target = _loginUrl;
|
||||
what = "pagina di accesso";
|
||||
}
|
||||
else if (IsRest(await FullUrlAsync(ct).ConfigureAwait(false)))
|
||||
{
|
||||
target = StartPageUrl;
|
||||
what = target == _loginUrl ? "era a riposo, pagina di accesso" : "era a riposo, pagina iniziale del sito";
|
||||
}
|
||||
else
|
||||
{
|
||||
// The session that just ended left its page: his to look at.
|
||||
_log.Info("collegamento", "Alberto usa il browser.");
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
|
||||
_log.Info("collegamento", result.Succeeded
|
||||
? $"Alberto usa il browser: {what} aperta."
|
||||
: $"Alberto usa il browser: {what} non aperta (errore di rete del browser).");
|
||||
}
|
||||
|
||||
/// <summary>The empty rest page (or no document at all): never what Alberto should be shown.</summary>
|
||||
private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl;
|
||||
|
||||
/// <summary>The address of the main frame, in full (never logged); null when the browser does not answer.</summary>
|
||||
private async Task<string?> FullUrlAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _browser.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WaitForSessionEndAsync(CancellationToken ct)
|
||||
{
|
||||
if (_engine is not { } engine)
|
||||
@@ -543,8 +729,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page turn for Alberto's login page, so that no step of the profile search runs under it; after 15 seconds
|
||||
/// the page is taken anyway (Alberto asked for it), and null comes back.
|
||||
/// The page turn for Alberto's own navigation, so that no step of the profile search runs under it; null after
|
||||
/// <see cref="PageTurnWait"/> (and always without an engine). The login and the start page from the rest page then
|
||||
/// take the page anyway (Alberto asked for it, under his lease); «Pagina iniziale» gives up.
|
||||
/// </summary>
|
||||
private async Task<PageTurn?> TakePageAsync(CancellationToken ct)
|
||||
{
|
||||
@@ -554,7 +741,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
}
|
||||
|
||||
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
limit.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
limit.CancelAfter(PageTurnWait);
|
||||
try
|
||||
{
|
||||
return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false);
|
||||
|
||||
+11
-3
@@ -245,9 +245,11 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
// Browser, connection, engine. The engine loop starts only once the browser is up.
|
||||
var browser = await _platform.CreateBrowserAsync(new FebePlatformContext(o, data, Database, Clock, Log, Tracker), ct).ConfigureAwait(false);
|
||||
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
|
||||
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
|
||||
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
|
||||
Browser = browser;
|
||||
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, o.Site.SessionCookie);
|
||||
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie);
|
||||
Connection = connection;
|
||||
var engineOptions = o.FirstSessionDelay is { } delay
|
||||
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
|
||||
@@ -458,7 +460,9 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
services.Events.Notified += WakeDownloads;
|
||||
OnStop(() => services.Events.Notified -= WakeDownloads);
|
||||
|
||||
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
|
||||
// With the test site's automatic login the first look reports nothing: the session it may not find yet is
|
||||
// the one the login below opens (issue #52), not a disconnection.
|
||||
await Connection!.RefreshAsync(ct, mayReport: !o.TestSiteAutoLogin).ConfigureAwait(false);
|
||||
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
|
||||
{
|
||||
await TestSiteLoginAsync(ct).ConfigureAwait(false);
|
||||
@@ -514,6 +518,10 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».</summary>
|
||||
private static string HomeUrl(string baseUrl) =>
|
||||
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
|
||||
|
||||
/// <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.
|
||||
|
||||
@@ -101,7 +101,8 @@ public sealed partial class FebeLog : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
|
||||
public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write(
|
||||
/// <param name="category">The category of the lines (the remote view writes as «vista»).</param>
|
||||
public IBrowserLog ForBrowser(string category = "browser") => new DelegateBrowserLog((level, message, exception) => Write(
|
||||
level switch
|
||||
{
|
||||
BrowserLogLevel.Error => LogLevel.Error,
|
||||
@@ -109,7 +110,7 @@ public sealed partial class FebeLog : IDisposable
|
||||
BrowserLogLevel.Information => LogLevel.Information,
|
||||
_ => LogLevel.Debug,
|
||||
},
|
||||
"browser",
|
||||
category,
|
||||
message,
|
||||
exception));
|
||||
|
||||
|
||||
@@ -55,7 +55,12 @@ public interface IFebePlatform
|
||||
/// <param name="Clock">The clock of the engine.</param>
|
||||
/// <param name="Log">The log.</param>
|
||||
/// <param name="Tracker">When Alberto last used the browser: the desktop window marks it when he uses and closes it.</param>
|
||||
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker);
|
||||
/// <param name="OpenStartPage">
|
||||
/// What «Pagina iniziale» of the browser window does (issue #52): the connection opens the site's home when connected,
|
||||
/// the login page otherwise, once the engine's session ended and with the page's turn
|
||||
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
|
||||
/// </param>
|
||||
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
|
||||
|
||||
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
|
||||
public sealed record FebeAppOptions
|
||||
|
||||
@@ -47,6 +47,10 @@ public sealed class ProblemConnectionService(IReadOnlyList<ConfigurationProblem>
|
||||
|
||||
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct) => throw Refused();
|
||||
|
||||
public Task ReleaseAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct) => throw Refused();
|
||||
|
||||
private Febe.Web.Api.BadRequestException Refused() =>
|
||||
|
||||
@@ -66,7 +66,7 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
|
||||
/// <param name="log">Where opening and closing are noted (never keys).</param>
|
||||
/// <param name="log">Where the frames' starts, restarts and silences are noted (never keys).</param>
|
||||
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
|
||||
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
@@ -100,7 +100,8 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
throw;
|
||||
}
|
||||
|
||||
_log.Info("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
|
||||
// The host notes the opening in its own words; here only for whoever uses the session alone.
|
||||
_log.Debug("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
|
||||
}
|
||||
|
||||
public async Task MouseAsync(RemoteMouseEvent e, CancellationToken ct = default)
|
||||
@@ -198,7 +199,7 @@ public sealed class RemoteViewSession : IAsyncDisposable
|
||||
_buttons = 0;
|
||||
}
|
||||
|
||||
_log.Info("Vista remota chiusa.");
|
||||
_log.Debug("Vista remota chiusa.");
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
@@ -13,7 +14,37 @@ namespace Febe.Browser.RemoteView;
|
||||
/// <param name="MaxWidth">Largest frame width in pixels.</param>
|
||||
/// <param name="MaxHeight">Largest frame height in pixels.</param>
|
||||
/// <param name="EveryNthFrame">Send one frame out of this many.</param>
|
||||
public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1);
|
||||
/// <param name="Watchdog">How missing frames are noticed and the frames started again; null: never (issue #52).</param>
|
||||
public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1, ScreencastWatchdog? Watchdog = null);
|
||||
|
||||
/// <summary>
|
||||
/// When the remote view starts its frames again (issue #52): Chromium sends a frame only when the page repaints, a
|
||||
/// lost acknowledgement stops the frames for good, and a change of renderer (another site, the rest page, a crash) may
|
||||
/// leave the screencast on the old one. After <see cref="Silence"/> without frames — measured from the start, from the
|
||||
/// last frame or from the last change of document of the main frame — the screencast is stopped and started again (a
|
||||
/// new screencast session), and one still picture of the page is sent when no frame came within
|
||||
/// <see cref="FirstFrameWait"/> of the start (Chromium sends the first frame only after answering the start). Each restart
|
||||
/// doubles the wait, up to <see cref="LongestSilence"/>: a page that does not move (Chromium sends nothing then) costs
|
||||
/// one restart every so often, not one every two seconds. Frames that flow again (<see cref="FlowingFrames"/> after a
|
||||
/// restart) or a new document bring the wait back to <see cref="Silence"/>.
|
||||
/// </summary>
|
||||
/// <param name="Silence">Time without frames before the first restart.</param>
|
||||
/// <param name="Tick">How often the watchdog looks.</param>
|
||||
/// <param name="LongestSilence">The longest wait between two restarts without frames.</param>
|
||||
public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpan LongestSilence)
|
||||
{
|
||||
/// <summary>
|
||||
/// Frames after a restart that show the page is moving: a start alone brings one frame even on a still page, which
|
||||
/// says that the screencast works, not that it keeps going.
|
||||
/// </summary>
|
||||
public const int FlowingFrames = 3;
|
||||
|
||||
/// <summary>How long a restart waits for its first frame before it sends a still picture instead.</summary>
|
||||
public static readonly TimeSpan FirstFrameWait = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
/// <summary>About two seconds, looked at four times a second, at most half a minute between restarts.</summary>
|
||||
public static ScreencastWatchdog Default { get; } = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
/// <summary>One frame of the remote view.</summary>
|
||||
/// <param name="Jpeg">The image.</param>
|
||||
@@ -24,6 +55,7 @@ public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, in
|
||||
/// <param name="ScrollOffsetX">Horizontal scroll position.</param>
|
||||
/// <param name="ScrollOffsetY">Vertical scroll position.</param>
|
||||
/// <param name="Timestamp">Browser timestamp (seconds), when given.</param>
|
||||
/// <param name="Still">True for a still picture (<c>Page.captureScreenshot</c>) sent because no frame came.</param>
|
||||
public sealed record ScreencastFrame(
|
||||
byte[] Jpeg,
|
||||
double DeviceWidth,
|
||||
@@ -32,7 +64,8 @@ public sealed record ScreencastFrame(
|
||||
double OffsetTop,
|
||||
double ScrollOffsetX,
|
||||
double ScrollOffsetY,
|
||||
double? Timestamp);
|
||||
double? Timestamp,
|
||||
bool Still = false);
|
||||
|
||||
/// <summary>
|
||||
/// The remote view's video (spec §4.1, §11): <c>Page.startScreencast</c> in JPEG, every frame acknowledged with
|
||||
@@ -40,9 +73,16 @@ public sealed record ScreencastFrame(
|
||||
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
|
||||
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
|
||||
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// With a <see cref="ScreencastWatchdog"/> the frames are started again when they stop coming (issue #52): after a
|
||||
/// silence, and when the main frame finished loading a new document (<c>Page.loadEventFired</c>) without a frame. Every
|
||||
/// restart, the start after a browser restart and the stop run one at a time, so the stop is never followed by a start.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class ScreencastSession : IAsyncDisposable
|
||||
{
|
||||
@@ -60,15 +100,33 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
|
||||
private readonly Channel<int> _acks = Channel.CreateUnbounded<int>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
|
||||
// Starts after the first one (watchdog, browser restart) and the stop: one at a time.
|
||||
private readonly SemaphoreSlim _starts = new(1, 1);
|
||||
private readonly Lock _watch = new();
|
||||
private readonly List<IDisposable> _pageEvents = [];
|
||||
private IDisposable? _subscription;
|
||||
private Task? _ackPump;
|
||||
private Task? _watchdog;
|
||||
private ScreencastOptions? _options;
|
||||
private int _stopped;
|
||||
private long _framesReceived;
|
||||
private long _restarts;
|
||||
|
||||
// Guarded by _watch: when silence is measured from, how long it may last, and what the page did meanwhile.
|
||||
private DateTimeOffset _lastFrameAt;
|
||||
private DateTimeOffset _watchFrom;
|
||||
private TimeSpan _silenceLimit;
|
||||
private long _framesAtNavigation;
|
||||
private int _framesSinceRestart;
|
||||
private bool _restartWanted;
|
||||
private bool _silent;
|
||||
private DateTimeOffset _silentSince;
|
||||
private TaskCompletionSource? _nextFrame;
|
||||
|
||||
/// <param name="cdp">The page session.</param>
|
||||
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
|
||||
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</param>
|
||||
/// <param name="log">Where starts, restarts and silences are noted (never parameters or frames).</param>
|
||||
/// <param name="clock">Wall-clock time for the pauses between start attempts and the watchdog; null: the system clock.</param>
|
||||
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
|
||||
{
|
||||
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
|
||||
@@ -79,11 +137,15 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
|
||||
public event EventHandler<ScreencastFrame>? FrameReceived;
|
||||
|
||||
/// <summary>The last frame received, for mapping input coordinates.</summary>
|
||||
/// <summary>The last frame received (or still picture sent), for mapping input coordinates.</summary>
|
||||
public ScreencastFrame? LastFrame { get; private set; }
|
||||
|
||||
/// <summary>Frames of the screencast received so far (still pictures not counted).</summary>
|
||||
public long FramesReceived => Interlocked.Read(ref _framesReceived);
|
||||
|
||||
/// <summary>How many times the watchdog started the frames again.</summary>
|
||||
public long Restarts => Interlocked.Read(ref _restarts);
|
||||
|
||||
public async Task StartAsync(ScreencastOptions? options = null, CancellationToken ct = default)
|
||||
{
|
||||
if (_subscription is not null)
|
||||
@@ -100,7 +162,20 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
|
||||
_ackPump = Task.Run(() => AckPumpAsync(_lifetime.Token), CancellationToken.None);
|
||||
await SendStartAsync(ct).ConfigureAwait(false);
|
||||
_log.Debug("Vista remota avviata.");
|
||||
if (_options.Watchdog is { } watchdog)
|
||||
{
|
||||
lock (_watch)
|
||||
{
|
||||
_watchFrom = _clock.Now;
|
||||
_silenceLimit = watchdog.Silence;
|
||||
}
|
||||
|
||||
_pageEvents.Add(_cdp.On("Page.frameNavigated", OnFrameNavigated));
|
||||
_pageEvents.Add(_cdp.On("Page.loadEventFired", OnLoadEventFired));
|
||||
_watchdog = Task.Run(() => WatchAsync(watchdog, _lifetime.Token), CancellationToken.None);
|
||||
}
|
||||
|
||||
_log.Info("Vista remota: fotogrammi avviati.");
|
||||
}
|
||||
|
||||
/// <summary>Frames as they arrive; the oldest are dropped if the reader falls behind. Ends when the session stops.</summary>
|
||||
@@ -124,31 +199,44 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
events.Reconnected -= OnReconnected;
|
||||
}
|
||||
|
||||
if (_subscription is not null)
|
||||
foreach (var subscription in _pageEvents)
|
||||
{
|
||||
_subscription.Dispose();
|
||||
try
|
||||
subscription.Dispose();
|
||||
}
|
||||
|
||||
// The watchdog and any start under way end first: no start may follow the stop below.
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
if (_watchdog is not null)
|
||||
{
|
||||
await Quietly(_watchdog).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _starts.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (_subscription is not null)
|
||||
{
|
||||
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException)
|
||||
{
|
||||
// The browser is gone: nothing to stop.
|
||||
_subscription.Dispose();
|
||||
try
|
||||
{
|
||||
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException)
|
||||
{
|
||||
// The browser is gone: nothing to stop.
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_starts.Release();
|
||||
}
|
||||
|
||||
_frames.Writer.TryComplete();
|
||||
_acks.Writer.TryComplete();
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
if (_ackPump is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _ackPump.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
await Quietly(_ackPump).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_log.Debug("Vista remota fermata.");
|
||||
@@ -158,6 +246,55 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
{
|
||||
await StopAsync().ConfigureAwait(false);
|
||||
_lifetime.Dispose();
|
||||
_starts.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>The width and height written in a JPEG's frame header (SOFn), or null when the data has none.</summary>
|
||||
internal static (int Width, int Height)? JpegSize(ReadOnlySpan<byte> jpeg)
|
||||
{
|
||||
if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var i = 2;
|
||||
while (i + 3 < jpeg.Length)
|
||||
{
|
||||
if (jpeg[i] != 0xFF)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var marker = jpeg[i + 1];
|
||||
if (marker == 0xFF)
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
var length = (jpeg[i + 2] << 8) | jpeg[i + 3];
|
||||
var isFrame = marker is >= 0xC0 and <= 0xCF && marker is not (0xC4 or 0xC8 or 0xCC);
|
||||
if (isFrame)
|
||||
{
|
||||
if (i + 8 >= jpeg.Length)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var height = (jpeg[i + 5] << 8) | jpeg[i + 6];
|
||||
var width = (jpeg[i + 7] << 8) | jpeg[i + 8];
|
||||
return width > 0 && height > 0 ? (width, height) : null;
|
||||
}
|
||||
|
||||
if (length < 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
i += 2 + length;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task SendStartAsync(CancellationToken ct)
|
||||
@@ -182,7 +319,7 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
ct).ConfigureAwait(false);
|
||||
if (attempt > 1)
|
||||
{
|
||||
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
_log.Info($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -206,16 +343,274 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
private void OnReconnected(object? sender, EventArgs e) =>
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
// Read inside the try: a browser restart that races the dispose finds the source disposed.
|
||||
var ct = CancellationToken.None;
|
||||
try
|
||||
{
|
||||
await SendStartAsync(_lifetime.Token).ConfigureAwait(false);
|
||||
ct = _lifetime.Token;
|
||||
await _starts.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
if (Volatile.Read(ref _stopped) == 0)
|
||||
{
|
||||
await SendStartAsync(ct).ConfigureAwait(false);
|
||||
_log.Info("Vista remota: fotogrammi avviati di nuovo dopo il riavvio del browser.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_starts.Release();
|
||||
}
|
||||
|
||||
lock (_watch)
|
||||
{
|
||||
_watchFrom = _clock.Now;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("Vista remota: non è ripartita dopo il riavvio del browser.", ex);
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The watchdog: every <see cref="ScreencastWatchdog.Tick"/> it looks how long no frame came; past the allowed
|
||||
/// silence (or when a new document loaded without frames) it starts the frames again.
|
||||
/// </summary>
|
||||
private async Task WatchAsync(ScreencastWatchdog watchdog, CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _clock.Delay(watchdog.Tick, ct).ConfigureAwait(false);
|
||||
bool due;
|
||||
bool afterLoad;
|
||||
TimeSpan silence;
|
||||
lock (_watch)
|
||||
{
|
||||
var now = _clock.Now;
|
||||
var since = _lastFrameAt > _watchFrom ? _lastFrameAt : _watchFrom;
|
||||
silence = now - since;
|
||||
afterLoad = _restartWanted;
|
||||
due = afterLoad || silence >= _silenceLimit;
|
||||
}
|
||||
|
||||
if (due && Volatile.Read(ref _stopped) == 0)
|
||||
{
|
||||
await RestartAsync(watchdog, silence, afterLoad, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Never the end of the watchdog: the next look tries again.
|
||||
_log.Debug($"Vista remota: controllo dei fotogrammi non riuscito ({ex.GetType().Name}).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stop and start again (a new screencast session), then one still picture when no frame came within
|
||||
/// <see cref="ScreencastWatchdog.FirstFrameWait"/>. The silence counts from the start; the wait for the next restart
|
||||
/// doubles here, before the start, so that frames flowing meanwhile bring it back to the short one.
|
||||
/// </summary>
|
||||
private async Task RestartAsync(ScreencastWatchdog watchdog, TimeSpan silence, bool afterLoad, CancellationToken ct)
|
||||
{
|
||||
await _starts.WaitAsync(ct).ConfigureAwait(false);
|
||||
var started = false;
|
||||
TaskCompletionSource? nextFrame = null;
|
||||
try
|
||||
{
|
||||
bool first;
|
||||
lock (_watch)
|
||||
{
|
||||
first = !_silent;
|
||||
if (first)
|
||||
{
|
||||
_silent = true;
|
||||
_silentSince = _clock.Now - silence;
|
||||
}
|
||||
|
||||
_restartWanted = false;
|
||||
_framesSinceRestart = 0;
|
||||
var longer = _silenceLimit + _silenceLimit;
|
||||
_silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence;
|
||||
}
|
||||
|
||||
var seconds = Math.Max(1, (int)Math.Round(silence.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
|
||||
var why = afterLoad
|
||||
? "pagina nuova caricata senza fotogrammi"
|
||||
: $"nessun fotogramma da {seconds} s";
|
||||
var line = $"Vista remota: {why}, riavvio dei fotogrammi.";
|
||||
if (first)
|
||||
{
|
||||
_log.Info(line);
|
||||
}
|
||||
else
|
||||
{
|
||||
_log.Debug(line);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpCommandException or TimeoutException)
|
||||
{
|
||||
// Nothing was running on the browser side: the start below is what matters.
|
||||
}
|
||||
|
||||
// Ready before the start: its first frame may come as soon as Chromium has answered.
|
||||
nextFrame = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
lock (_watch)
|
||||
{
|
||||
_nextFrame = nextFrame;
|
||||
}
|
||||
|
||||
await SendStartAsync(ct).ConfigureAwait(false);
|
||||
lock (_watch)
|
||||
{
|
||||
_watchFrom = _clock.Now;
|
||||
}
|
||||
|
||||
started = true;
|
||||
Interlocked.Increment(ref _restarts);
|
||||
if (!await FrameWithinAsync(nextFrame.Task, ScreencastWatchdog.FirstFrameWait, ct).ConfigureAwait(false))
|
||||
{
|
||||
await SendStillAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
// The browser is restarting or the page is between two documents for longer than the budget: next time.
|
||||
_log.Debug($"Vista remota: riavvio dei fotogrammi non riuscito ({ex.GetType().Name}).");
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_watch)
|
||||
{
|
||||
if (!started)
|
||||
{
|
||||
_watchFrom = _clock.Now; // a failed restart: the next one after a whole silence, not at the next look
|
||||
}
|
||||
|
||||
if (ReferenceEquals(_nextFrame, nextFrame))
|
||||
{
|
||||
_nextFrame = null;
|
||||
}
|
||||
}
|
||||
|
||||
_starts.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="frame"/> completes within <paramref name="wait"/> (on the clock).</summary>
|
||||
private async Task<bool> FrameWithinAsync(Task frame, TimeSpan wait, CancellationToken ct)
|
||||
{
|
||||
if (frame.IsCompleted)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
using var stopWaiting = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var delay = _clock.Delay(wait, stopWaiting.Token);
|
||||
await Task.WhenAny(frame, delay).ConfigureAwait(false);
|
||||
|
||||
// Asked of the frame itself, not of which task woke the wait: both may be done by now, and a frame is a frame.
|
||||
if (frame.IsCompleted)
|
||||
{
|
||||
// The pause ends here (a clock that moves only when asked keeps no sleeper behind).
|
||||
await stopWaiting.CancelAsync().ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
await delay.ConfigureAwait(false); // cancelled with ct: the restart ends there
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One picture of the page as it is (<c>Page.captureScreenshot</c>, already allowed for the preview): a page that
|
||||
/// does not repaint shows something, and the pointer can be placed on it.
|
||||
/// </summary>
|
||||
private async Task SendStillAsync(CancellationToken ct)
|
||||
{
|
||||
var before = FramesReceived;
|
||||
var jpeg = await PagePreview.CaptureAsync(_cdp, Math.Clamp((_options ?? new ScreencastOptions()).Quality, 0, 100), ct).ConfigureAwait(false);
|
||||
if (jpeg.Length == 0 || Volatile.Read(ref _stopped) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (FramesReceived != before)
|
||||
{
|
||||
// A real frame came during the capture: it is newer and carries the page's scroll and zoom.
|
||||
_log.Debug("Vista remota: immagine ferma scartata, è arrivato un fotogramma.");
|
||||
return;
|
||||
}
|
||||
|
||||
var last = LastFrame;
|
||||
double width;
|
||||
double height;
|
||||
if (last is { DeviceWidth: > 0, DeviceHeight: > 0 })
|
||||
{
|
||||
width = last.DeviceWidth;
|
||||
height = last.DeviceHeight;
|
||||
}
|
||||
else if (JpegSize(jpeg) is { } size)
|
||||
{
|
||||
// Docker's browser draws at one device pixel per CSS pixel.
|
||||
width = size.Width;
|
||||
height = size.Height;
|
||||
}
|
||||
else
|
||||
{
|
||||
var o = _options ?? new ScreencastOptions();
|
||||
width = o.MaxWidth;
|
||||
height = o.MaxHeight;
|
||||
}
|
||||
|
||||
Deliver(new ScreencastFrame(jpeg, width, height, 1, 0, 0, 0, null, Still: true));
|
||||
_log.Debug("Vista remota: immagine ferma della pagina inviata.");
|
||||
}
|
||||
|
||||
private void OnFrameNavigated(JsonElement e)
|
||||
{
|
||||
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// A new document in the main frame (perhaps in another renderer): the silence counts from here, short again.
|
||||
lock (_watch)
|
||||
{
|
||||
_watchFrom = _clock.Now;
|
||||
_framesAtNavigation = FramesReceived;
|
||||
_silenceLimit = _options?.Watchdog?.Silence ?? _silenceLimit;
|
||||
_silent = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnLoadEventFired(JsonElement e)
|
||||
{
|
||||
lock (_watch)
|
||||
{
|
||||
if (FramesReceived == _framesAtNavigation)
|
||||
{
|
||||
_restartWanted = true; // loaded and still no frame of it: the next look starts them again
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFrame(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("sessionId", out var sid) || !sid.TryGetInt32(out var sessionId))
|
||||
@@ -242,8 +637,37 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
Read(meta, "scrollOffsetY"),
|
||||
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty("timestamp", out var ts) && ts.TryGetDouble(out var t) ? t : null);
|
||||
|
||||
LastFrame = frame;
|
||||
Interlocked.Increment(ref _framesReceived);
|
||||
TimeSpan? resumedAfter = null;
|
||||
lock (_watch)
|
||||
{
|
||||
_lastFrameAt = _clock.Now;
|
||||
_restartWanted = false;
|
||||
_nextFrame?.TrySetResult();
|
||||
_nextFrame = null;
|
||||
if (++_framesSinceRestart >= ScreencastWatchdog.FlowingFrames && _options?.Watchdog is { } watchdog)
|
||||
{
|
||||
// The page moves: frames flow, and a silence from now on is worth a quick restart again.
|
||||
_silenceLimit = watchdog.Silence;
|
||||
if (_silent)
|
||||
{
|
||||
_silent = false;
|
||||
resumedAfter = _lastFrameAt - _silentSince;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (resumedAfter is { } after)
|
||||
{
|
||||
_log.Info($"Vista remota: fotogrammi di nuovo in arrivo, dopo {Math.Max(1, (int)Math.Round(after.TotalSeconds)).ToString(CultureInfo.InvariantCulture)} s di silenzio.");
|
||||
}
|
||||
|
||||
Deliver(frame);
|
||||
}
|
||||
|
||||
private void Deliver(ScreencastFrame frame)
|
||||
{
|
||||
LastFrame = frame;
|
||||
_frames.Writer.TryWrite(frame);
|
||||
FrameReceived?.Invoke(this, frame);
|
||||
}
|
||||
@@ -258,11 +682,22 @@ public sealed class ScreencastSession : IAsyncDisposable
|
||||
}
|
||||
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
|
||||
{
|
||||
// A lost ack only pauses frames until the next start.
|
||||
// A lost ack pauses the frames: the watchdog, when there is one, starts them again after the silence.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task Quietly(Task task)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static double Read(JsonElement meta, string name, double fallback = 0) =>
|
||||
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty(name, out var v) && v.TryGetDouble(out var d) ? d : fallback;
|
||||
}
|
||||
@@ -0,0 +1,866 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>Options of <see cref="HttpSiteRequester"/>.</summary>
|
||||
public sealed record HttpSiteRequesterOptions
|
||||
{
|
||||
/// <summary>The address of Instagram: the only one the Instagram catalog may be asked at (https, default port).</summary>
|
||||
public static Uri InstagramAddress { get; } = new("https://www.instagram.com/", UriKind.Absolute);
|
||||
|
||||
/// <summary>
|
||||
/// Scheme, host and port of the site, with the path «/» and nothing else. For the Instagram catalog exactly
|
||||
/// <see cref="InstagramAddress"/>; for any other catalog a loopback address (127.0.0.0/8 or ::1), http or https.
|
||||
/// </summary>
|
||||
public required Uri SiteAddress { get; init; }
|
||||
|
||||
/// <summary>Name of the session cookie of the site (<c>sessionid</c>, <c>sessione_prova</c>): without it nothing leaves.</summary>
|
||||
public required string SessionCookie { get; init; }
|
||||
|
||||
/// <summary>How long a request may take, answer read included.</summary>
|
||||
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>How long opening a connection may take.</summary>
|
||||
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>Largest body kept in memory; a larger answer is dropped (<see cref="SiteUnreachableReason.TooLarge"/>).</summary>
|
||||
public int MaxBodyBytes { get; init; } = 32 * 1024 * 1024;
|
||||
|
||||
/// <summary>The options for Instagram.</summary>
|
||||
public static HttpSiteRequesterOptions Instagram() => new() { SiteAddress = InstagramAddress, SessionCookie = "sessionid" };
|
||||
|
||||
/// <summary>The options for the local test site at <paramref name="address"/> (<c>http://127.0.0.1:port/</c>).</summary>
|
||||
public static HttpSiteRequesterOptions TestSite(Uri address, string sessionCookie = "sessione_prova") =>
|
||||
new() { SiteAddress = address, SessionCookie = sessionCookie };
|
||||
}
|
||||
|
||||
/// <summary>Why a request got no answer.</summary>
|
||||
public enum SiteUnreachableReason
|
||||
{
|
||||
/// <summary>No answer within <see cref="HttpSiteRequesterOptions.Timeout"/>.</summary>
|
||||
Timeout,
|
||||
|
||||
/// <summary>No connection, or the connection broke.</summary>
|
||||
Unreachable,
|
||||
|
||||
/// <summary>The answer was larger than <see cref="HttpSiteRequesterOptions.MaxBodyBytes"/>.</summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>The body could not be decoded (corrupt or truncated gzip, deflate or brotli).</summary>
|
||||
Broken,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The site gave no answer (time out, no connection, an answer too large). The message is in Italian and names only the
|
||||
/// operation and its path shape, never the address, a value or the text of the network error.
|
||||
/// </summary>
|
||||
public sealed class SiteUnreachableException : IOException
|
||||
{
|
||||
public SiteUnreachableException()
|
||||
{
|
||||
}
|
||||
|
||||
public SiteUnreachableException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public SiteUnreachableException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public SiteUnreachableException(string message, SiteUnreachableReason reason)
|
||||
: base(message) => Reason = reason;
|
||||
|
||||
public SiteUnreachableReason Reason { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A request that did not leave because the saved session is missing, has no session cookie, or lacks a value the
|
||||
/// catalog asks for (§7.6: «la sessione salvata manca», Disconnessione). Names only the missing value.
|
||||
/// </summary>
|
||||
public sealed class SiteSessionMissingException : SiteRequestRefusedException
|
||||
{
|
||||
public SiteSessionMissingException()
|
||||
{
|
||||
}
|
||||
|
||||
public SiteSessionMissingException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public SiteSessionMissingException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public SiteSessionMissingException(string message, string? missing)
|
||||
: base(message) => Missing = missing;
|
||||
|
||||
/// <summary>The header, field or cookie that has no value (its name), or null when the whole session is missing.</summary>
|
||||
public string? Missing { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The site client (issue #36, spec §6.0): the one class of Febe that asks the site for data without the browser
|
||||
/// (rule 3). It sends only the operations of the catalog, with the user agent, the cookies and the values of the saved
|
||||
/// session (<see cref="ISiteSession"/>), the headers of the catalog and nothing else, and keeps in the session what the
|
||||
/// site renews.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="SiteRequestGuard.Check"/> before anything, with one <see cref="SpentPermits"/> for its lifetime:
|
||||
/// a permit per request (rule 8).</item>
|
||||
/// <item>One request at a time: a second call while one is in flight is refused (<see cref="SiteRequestRefusedException"/>),
|
||||
/// never queued, so no request leaves before its caller has read the answer of the one before (rule 8: stop at the
|
||||
/// first signal) and the spacing of §7.7 stays the Governor's.</item>
|
||||
/// <item>What the site renews (<c>Set-Cookie</c>, <c>x-ig-set-www-claim</c>) is written to the session as soon as the
|
||||
/// headers arrive, as a browser does, whatever then happens to the body or to the caller's token; and only to the
|
||||
/// capture the request was sent with.</item>
|
||||
/// <item>Only to <see cref="HttpSiteRequesterOptions.SiteAddress"/>: https only for Instagram, http only for a loopback
|
||||
/// test site; every address it builds is checked again before it leaves.</item>
|
||||
/// <item>No redirect is followed (<c>AllowAutoRedirect = false</c>): a 3xx comes back as an answer, a signal (§7.6).</item>
|
||||
/// <item>Cookies are written by hand, as one <c>Cookie</c> header (<c>UseCookies = false</c>), in the session's order.</item>
|
||||
/// <item>HTTP/2 with fallback to HTTP/1.1 (<see cref="HttpVersionPolicy.RequestVersionOrLower"/>), never HTTP/3;
|
||||
/// gzip, deflate and brotli (the HTTP stack adds <c>Accept-Encoding: gzip, deflate, br</c> to say so: with
|
||||
/// <c>Host</c> and <c>Content-Length</c> the only headers not in the catalog, besides the <c>Cookie</c> line; no
|
||||
/// <c>traceparent</c> from an activity of the host); the system proxy, as WebView2 — except for a loopback test site,
|
||||
/// which no browser reaches through a proxy. On Windows .NET would read <c>HTTP_PROXY</c>, <c>HTTPS_PROXY</c> and
|
||||
/// <c>ALL_PROXY</c> before the system settings, which WebView2 ignores: with one of them set the client is not built.</item>
|
||||
/// <item>Logs name only the operation, its path shape and the status, in Italian (rule 10). Exceptions never carry the
|
||||
/// address, a value or a body.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public sealed class HttpSiteRequester : ISiteRequester, IDisposable
|
||||
{
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = ResponseDelivery.MaxDepth };
|
||||
|
||||
private readonly RequestCatalog _catalog;
|
||||
private readonly ISiteSession _session;
|
||||
private readonly HttpSiteRequesterOptions _options;
|
||||
private readonly IClock _clock;
|
||||
private readonly Action<string> _log;
|
||||
private readonly HttpClient _http;
|
||||
private readonly SpentPermits _spent = new();
|
||||
// Never disposed: no wait handle is ever asked of it, and a call still in flight at Dispose releases it.
|
||||
private readonly SemaphoreSlim _oneAtATime = new(1, 1);
|
||||
|
||||
// Cancelled by Dispose, so a request in flight ends as a cancellation; never disposed, for the same reason.
|
||||
private readonly CancellationTokenSource _closing = new();
|
||||
private readonly Uri _site;
|
||||
private int _disposed;
|
||||
|
||||
/// <param name="catalog">The operations it may ask.</param>
|
||||
/// <param name="session">The saved session: values read before each request, renewals written after.</param>
|
||||
/// <param name="options">Address of the site, session cookie, limits.</param>
|
||||
/// <param name="clock">Time for the expiry of cookies and for <c>Retry-After</c> dates.</param>
|
||||
/// <param name="log">Receives the Italian log lines (operation, path shape, status only); null discards them.</param>
|
||||
/// <exception cref="ArgumentException">An address that is not the catalog's site (see <see cref="HttpSiteRequesterOptions.SiteAddress"/>).</exception>
|
||||
public HttpSiteRequester(RequestCatalog catalog, ISiteSession session, HttpSiteRequesterOptions options, IClock clock, Action<string>? log = null)
|
||||
{
|
||||
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
|
||||
_session = session ?? throw new ArgumentNullException(nameof(session));
|
||||
_options = options ?? throw new ArgumentNullException(nameof(options));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? (_ => { });
|
||||
if (!SiteCookies.IsPlainName(options.SessionCookie))
|
||||
{
|
||||
throw new ArgumentException("Il nome del cookie di sessione non è un nome semplice.", nameof(options));
|
||||
}
|
||||
|
||||
if (options.Timeout <= TimeSpan.Zero || options.ConnectTimeout <= TimeSpan.Zero || options.MaxBodyBytes <= 0)
|
||||
{
|
||||
throw new ArgumentException("Tempi e dimensione massima del client del sito devono essere positivi.", nameof(options));
|
||||
}
|
||||
|
||||
_site = CheckAddress(catalog, options.SiteAddress);
|
||||
if (!IsLoopback(_site) && EnvironmentProxyRefusal(OperatingSystem.IsWindows(), Environment.GetEnvironmentVariable) is { } proxy)
|
||||
{
|
||||
throw new InvalidOperationException(proxy);
|
||||
}
|
||||
|
||||
_http = new HttpClient(CreateHandler(_options, IsLoopback(_site)), disposeHandler: true)
|
||||
{
|
||||
// The timeout is a token of our own, to tell it from a cancellation of the caller.
|
||||
Timeout = System.Threading.Timeout.InfiniteTimeSpan,
|
||||
DefaultRequestVersion = HttpVersion.Version20,
|
||||
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The site it talks to (scheme, host, port).</summary>
|
||||
public Uri Site => _site;
|
||||
|
||||
/// <summary>
|
||||
/// Why <paramref name="address"/> is not where <paramref name="catalog"/> may be asked, or null when it is: the
|
||||
/// Instagram catalog only at <see cref="HttpSiteRequesterOptions.InstagramAddress"/>, any other only on loopback.
|
||||
/// </summary>
|
||||
public static string? RefusalOfAddress(RequestCatalog catalog, Uri? address)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
if (address is null || !address.IsAbsoluteUri)
|
||||
{
|
||||
return "manca l'indirizzo del sito";
|
||||
}
|
||||
|
||||
if (address.UserInfo.Length > 0 || address.AbsolutePath != "/" || address.Query.Length > 0 || address.Fragment.Length > 0)
|
||||
{
|
||||
return "l'indirizzo del sito è solo schema, host e porta";
|
||||
}
|
||||
|
||||
if (catalog.Site == "instagram")
|
||||
{
|
||||
return address.Scheme == Uri.UriSchemeHttps && address.IdnHost == HttpSiteRequesterOptions.InstagramAddress.IdnHost && address.Port == 443
|
||||
? null
|
||||
: "il catalogo di Instagram si chiede solo a https://www.instagram.com/";
|
||||
}
|
||||
|
||||
if (address.Scheme != Uri.UriSchemeHttp && address.Scheme != Uri.UriSchemeHttps)
|
||||
{
|
||||
return "un sito di prova si chiede con http o https";
|
||||
}
|
||||
|
||||
return IsLoopback(address) ? null : "un sito di prova sta solo su un indirizzo locale (127.0.0.1 o ::1): Febe non chiede nulla ad altri host";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Why the system proxy of .NET would not be the browser's, or null when it is. On Windows <c>HttpClient.DefaultProxy</c>
|
||||
/// takes <c>HTTP_PROXY</c>, <c>HTTPS_PROXY</c> or <c>ALL_PROXY</c> before the system settings WebView2 uses: the same
|
||||
/// session would leave from two routes (§6.0, «su Windows le impostazioni proxy del sistema, come WebView2»). In
|
||||
/// Docker Chromium reads the same variables as .NET, so they are the browser's route. Names the variables, never
|
||||
/// their values (they may hold a password).
|
||||
/// </summary>
|
||||
internal static string? EnvironmentProxyRefusal(bool windows, Func<string, string?> variable)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(variable);
|
||||
if (!windows)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var set = new[] { "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY" }.Where(n => !string.IsNullOrWhiteSpace(variable(n))).ToList();
|
||||
return set.Count == 0
|
||||
? null
|
||||
: $"Client del sito non avviato: sono impostate le variabili {string.Join(", ", set)}, che WebView2 non usa. Il client del sito uscirebbe da una strada diversa da quella del browser: togli le variabili o imposta il proxy nelle impostazioni di Windows.";
|
||||
}
|
||||
|
||||
/// <summary>The handler of the site client: no redirect, no cookie jar, decompression, HTTP/2, system proxy.</summary>
|
||||
internal static SocketsHttpHandler CreateHandler(HttpSiteRequesterOptions options, bool loopback) => new()
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
UseCookies = false,
|
||||
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
|
||||
// The system proxy (null = HttpClient.DefaultProxy), the way WebView2 and Chromium go out (decision of 16
|
||||
// November 2026); a loopback test site is never reached through one.
|
||||
UseProxy = !loopback,
|
||||
ConnectTimeout = options.ConnectTimeout,
|
||||
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
|
||||
MaxConnectionsPerServer = 1,
|
||||
|
||||
// No «traceparent» or «Request-Id» from an activity of the host: nothing the catalog does not list (rule 4).
|
||||
ActivityHeadersPropagator = null,
|
||||
};
|
||||
|
||||
public async Task<SiteAnswer> SendAsync(SiteRequest request, Permit permit, CancellationToken ct)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
||||
var operation = SiteRequestGuard.Check(_catalog, request, permit, _spent);
|
||||
|
||||
// Refused, never queued: a queued request would leave as soon as the one before ends, before its caller could
|
||||
// read a stop signal in that answer (rule 8), and closer to it than the Governor spaced them (§7.7).
|
||||
if (!_oneAtATime.Wait(0, CancellationToken.None))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: un'altra richiesta è ancora in corso (una per volta, mai in coda).");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var values = _session.Read()
|
||||
?? throw new SiteSessionMissingException($"Richiesta «{operation.Name}» non inviata: non c'è una sessione salvata.", missing: null);
|
||||
if (values.CookieAt(_options.SessionCookie, _clock.Now) is null)
|
||||
{
|
||||
throw new SiteSessionMissingException($"Richiesta «{operation.Name}» non inviata: la sessione salvata non ha il cookie di sessione, o è scaduto.", _options.SessionCookie);
|
||||
}
|
||||
|
||||
using var message = Build(operation, request, values);
|
||||
return await ExchangeAsync(operation, message, values.Capture, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_oneAtATime.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Closes the client: a request in flight ends with <see cref="OperationCanceledException"/>, later calls with <see cref="ObjectDisposedException"/>.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_closing.Cancel();
|
||||
_http.Dispose();
|
||||
}
|
||||
|
||||
private async Task<SiteAnswer> ExchangeAsync(SiteOperation operation, HttpRequestMessage message, long capture, CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct, _closing.Token);
|
||||
timeout.CancelAfter(_options.Timeout);
|
||||
HttpResponseMessage response;
|
||||
byte[] body;
|
||||
try
|
||||
{
|
||||
response = await _http.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (IsStop(ex, ct))
|
||||
{
|
||||
throw Stopped(ex, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw Unreachable(operation, SiteUnreachableReason.Timeout);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
// The text of the network error may name the host and the address: it is not passed on.
|
||||
throw Unreachable(operation, SiteUnreachableReason.Unreachable);
|
||||
}
|
||||
|
||||
using (response)
|
||||
{
|
||||
// What the site renewed counts as soon as the headers are here, as for a browser: the site may already have
|
||||
// dropped the old values, whatever happens to the body or to the caller next. Never cancelled.
|
||||
var update = SessionUpdate(response, capture, out var set, out var deleted);
|
||||
if (!update.IsEmpty)
|
||||
{
|
||||
await _session.UpdateAsync(update, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var deletesSession = deleted.Contains(_options.SessionCookie, StringComparer.Ordinal);
|
||||
if (deletesSession)
|
||||
{
|
||||
_log(string.Create(CultureInfo.InvariantCulture, $"Client del sito: «{operation.Name}» {operation.PathShape}, il sito ha cancellato il cookie di sessione."));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
body = await ReadLimitedAsync(response.Content, _options.MaxBodyBytes, timeout.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (IsStop(ex, ct))
|
||||
{
|
||||
throw Stopped(ex, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw Unreachable(operation, SiteUnreachableReason.Timeout);
|
||||
}
|
||||
catch (BodyTooLargeException)
|
||||
{
|
||||
throw Unreachable(operation, SiteUnreachableReason.TooLarge);
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException)
|
||||
{
|
||||
// GZipStream and DeflateStream throw InvalidDataException on corrupt data, BrotliStream InvalidOperationException.
|
||||
throw Unreachable(operation, SiteUnreachableReason.Broken);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or IOException)
|
||||
{
|
||||
throw Unreachable(operation, SiteUnreachableReason.Unreachable);
|
||||
}
|
||||
|
||||
var status = (int)response.StatusCode;
|
||||
var mime = response.Content.Headers.ContentType?.MediaType;
|
||||
var answer = new SiteAnswer(
|
||||
operation,
|
||||
status,
|
||||
mime,
|
||||
body,
|
||||
redirectTo: response.Headers.Location?.OriginalString,
|
||||
cookiesSet: set,
|
||||
cookiesDeleted: deleted,
|
||||
setsClaim: update.Claim is not null,
|
||||
retryAfter: RetryAfter(response.Headers.RetryAfter),
|
||||
rootFieldsPresent: RootFields(operation, body));
|
||||
|
||||
_log(string.Create(CultureInfo.InvariantCulture, $"Client del sito: «{operation.Name}» {operation.PathShape}, stato {status}."));
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="error"/> comes from the caller's cancellation or from <see cref="Dispose"/>, not from the site.</summary>
|
||||
private bool IsStop(Exception error, CancellationToken ct) =>
|
||||
(ct.IsCancellationRequested && error is OperationCanceledException)
|
||||
|| (_closing.IsCancellationRequested && error is OperationCanceledException or HttpRequestException or IOException or ObjectDisposedException);
|
||||
|
||||
private OperationCanceledException Stopped(Exception error, CancellationToken ct) =>
|
||||
ct.IsCancellationRequested && error is OperationCanceledException cancelled
|
||||
? cancelled
|
||||
: new OperationCanceledException("Client del sito chiuso: la richiesta in corso è stata interrotta.", _closing.Token);
|
||||
|
||||
private HttpRequestMessage Build(SiteOperation operation, SiteRequest request, SiteSessionValues values)
|
||||
{
|
||||
// The catalog refuses a configured operation without it; checked again: no request leaves without the
|
||||
// browser's user agent (rule 4), and the HTTP stack would add none.
|
||||
if (!operation.Headers.TryGetValue("user-agent", out var agent) || agent != new ValueSource(ValueSourceKind.Session, "user_agent"))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: il modello non manda l'user agent del browser («user-agent»: «session:user_agent»).");
|
||||
}
|
||||
|
||||
var address = new Uri(_site, PathAndQuery(operation, request));
|
||||
|
||||
// Built from the site and a catalog path the catalog checked: checked again, so nothing leaves for another host.
|
||||
if (address.Scheme != _site.Scheme || address.IdnHost != _site.IdnHost || address.Port != _site.Port)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'indirizzo non è del sito.");
|
||||
}
|
||||
|
||||
var message = new HttpRequestMessage(new HttpMethod(operation.Method), address)
|
||||
{
|
||||
Version = HttpVersion.Version20,
|
||||
VersionPolicy = HttpVersionPolicy.RequestVersionOrLower,
|
||||
};
|
||||
try
|
||||
{
|
||||
var now = _clock.Now;
|
||||
string? contentType = null;
|
||||
foreach (var name in operation.HeaderOrder)
|
||||
{
|
||||
var source = operation.Headers[name];
|
||||
if (source.Kind == ValueSourceKind.Computed)
|
||||
{
|
||||
if (name != "content-length")
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'intestazione «{name}» non si può calcolare.");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = Resolve(operation, name, source, values, variables: null, now);
|
||||
if (name == "content-type")
|
||||
{
|
||||
contentType = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!message.Headers.TryAddWithoutValidation(name, value))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: l'intestazione «{name}» non si può scrivere.");
|
||||
}
|
||||
}
|
||||
|
||||
var cookies = string.Join("; ", values.CookiesAt(now).Select(c => $"{c.Key}={c.Value}"));
|
||||
message.Headers.TryAddWithoutValidation("cookie", cookies);
|
||||
|
||||
if (operation.Kind == OperationKind.GraphQl)
|
||||
{
|
||||
var variables = Variables(operation, request);
|
||||
var form = new StringBuilder();
|
||||
foreach (var field in operation.BodyOrder)
|
||||
{
|
||||
var value = Resolve(operation, field, operation.Body[field], values, variables, now);
|
||||
if (form.Length > 0)
|
||||
{
|
||||
form.Append('&');
|
||||
}
|
||||
|
||||
form.Append(FormEncode(field)).Append('=').Append(FormEncode(value));
|
||||
}
|
||||
|
||||
message.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(form.ToString()));
|
||||
if (contentType is not null && !message.Content.Headers.TryAddWithoutValidation("content-type", contentType))
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: «content-type» non si può scrivere.");
|
||||
}
|
||||
}
|
||||
else if (contentType is not null)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: una lettura con GET non ha «content-type».");
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
catch
|
||||
{
|
||||
message.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static string PathAndQuery(SiteOperation operation, SiteRequest request)
|
||||
{
|
||||
var path = operation.Path;
|
||||
foreach (var name in operation.PathValues)
|
||||
{
|
||||
path = path.Replace("{" + name + "}", Uri.EscapeDataString(request.Values[name]), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
var query = new StringBuilder();
|
||||
foreach (var key in operation.ParameterOrder)
|
||||
{
|
||||
var template = operation.Parameters[key];
|
||||
string value;
|
||||
if (template.StartsWith("constant:", StringComparison.Ordinal))
|
||||
{
|
||||
value = template["constant:".Length..];
|
||||
}
|
||||
else
|
||||
{
|
||||
var name = template.Trim('{', '}', '?');
|
||||
if (!request.Values.TryGetValue(name, out var given))
|
||||
{
|
||||
// Only an optional value can be missing here: the guard checked the required ones.
|
||||
continue;
|
||||
}
|
||||
|
||||
value = given;
|
||||
}
|
||||
|
||||
query.Append(query.Length == 0 ? '?' : '&').Append(Uri.EscapeDataString(key)).Append('=').Append(Uri.EscapeDataString(value));
|
||||
}
|
||||
|
||||
return path + query;
|
||||
}
|
||||
|
||||
private static string Resolve(SiteOperation operation, string name, ValueSource source, SiteSessionValues values, string? variables, DateTimeOffset now)
|
||||
{
|
||||
var value = source.Kind switch
|
||||
{
|
||||
ValueSourceKind.Constant => source.Argument,
|
||||
ValueSourceKind.Cookie => values.CookieAt(source.Argument!, now),
|
||||
ValueSourceKind.Session => values.Field(source.Argument!, operation.Name),
|
||||
ValueSourceKind.Operation => operation.Name,
|
||||
ValueSourceKind.Variables => variables,
|
||||
_ => throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: «{name}» non ha una fonte stabilita."),
|
||||
};
|
||||
|
||||
return value ?? throw new SiteSessionMissingException(
|
||||
$"Richiesta «{operation.Name}» non inviata: la sessione salvata non ha il valore di «{name}» ({source}).", name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The variables of a GraphQL operation: its template, in the order and with the types of the file, with every
|
||||
/// <c>"{name}"</c> replaced by the value of the case, as a JSON string.
|
||||
/// </summary>
|
||||
internal static string Variables(SiteOperation operation, SiteRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (operation.Variables is not { } template)
|
||||
{
|
||||
throw new SiteRequestRefusedException($"Richiesta «{operation.Name}» non inviata: mancano le variabili.");
|
||||
}
|
||||
|
||||
var text = new StringBuilder();
|
||||
WriteTemplate(text, template, request);
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static void WriteTemplate(StringBuilder text, JsonElement element, SiteRequest request)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
text.Append('{');
|
||||
var firstProperty = true;
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (!firstProperty)
|
||||
{
|
||||
text.Append(',');
|
||||
}
|
||||
|
||||
firstProperty = false;
|
||||
WriteString(text, property.Name);
|
||||
text.Append(':');
|
||||
WriteTemplate(text, property.Value, request);
|
||||
}
|
||||
|
||||
text.Append('}');
|
||||
break;
|
||||
case JsonValueKind.Array:
|
||||
text.Append('[');
|
||||
var firstItem = true;
|
||||
foreach (var item in element.EnumerateArray())
|
||||
{
|
||||
if (!firstItem)
|
||||
{
|
||||
text.Append(',');
|
||||
}
|
||||
|
||||
firstItem = false;
|
||||
WriteTemplate(text, item, request);
|
||||
}
|
||||
|
||||
text.Append(']');
|
||||
break;
|
||||
case JsonValueKind.String:
|
||||
var constant = element.GetString()!;
|
||||
WriteString(text, constant.Length > 2 && constant[0] == '{' && constant[^1] == '}' && request.Values.TryGetValue(constant[1..^1], out var value) ? value : constant);
|
||||
break;
|
||||
default:
|
||||
// Numbers, true, false and null as the file writes them (12 stays 12, never 12.0).
|
||||
text.Append(element.GetRawText());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A JSON string as the page's <c>JSON.stringify</c> writes it (ECMA-262 QuoteJSONString): <c>"</c> and <c>\</c>
|
||||
/// escaped, <c>\b \f \n \r \t</c> short, the other controls below U+0020 and lone surrogates as <c>\u</c> with
|
||||
/// lower-case hex; everything else as it is (letters, emoji, U+007F, U+2028 and U+2029 included).
|
||||
/// </summary>
|
||||
internal static void WriteString(StringBuilder text, string value)
|
||||
{
|
||||
text.Append('"');
|
||||
for (var i = 0; i < value.Length; i++)
|
||||
{
|
||||
var c = value[i];
|
||||
switch (c)
|
||||
{
|
||||
case '"':
|
||||
text.Append("\\\"");
|
||||
break;
|
||||
case '\\':
|
||||
text.Append("\\\\");
|
||||
break;
|
||||
case '\b':
|
||||
text.Append("\\b");
|
||||
break;
|
||||
case '\f':
|
||||
text.Append("\\f");
|
||||
break;
|
||||
case '\n':
|
||||
text.Append("\\n");
|
||||
break;
|
||||
case '\r':
|
||||
text.Append("\\r");
|
||||
break;
|
||||
case '\t':
|
||||
text.Append("\\t");
|
||||
break;
|
||||
default:
|
||||
if (char.IsHighSurrogate(c) && i + 1 < value.Length && char.IsLowSurrogate(value[i + 1]))
|
||||
{
|
||||
text.Append(c).Append(value[++i]);
|
||||
}
|
||||
else if (c < ' ' || char.IsSurrogate(c))
|
||||
{
|
||||
text.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
|
||||
}
|
||||
else
|
||||
{
|
||||
text.Append(c);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
text.Append('"');
|
||||
}
|
||||
|
||||
/// <summary>The <c>application/x-www-form-urlencoded</c> serializer of the page (URLSearchParams): space as «+».</summary>
|
||||
internal static string FormEncode(string value)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(value);
|
||||
var text = new StringBuilder(bytes.Length);
|
||||
foreach (var b in bytes)
|
||||
{
|
||||
var c = (char)b;
|
||||
if (char.IsAsciiLetterOrDigit(c) || c is '*' or '-' or '.' or '_')
|
||||
{
|
||||
text.Append(c);
|
||||
}
|
||||
else if (c == ' ')
|
||||
{
|
||||
text.Append('+');
|
||||
}
|
||||
else
|
||||
{
|
||||
text.Append('%').Append(b.ToString("X2", CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private SiteSessionUpdate SessionUpdate(HttpResponseMessage response, long capture, out List<string> set, out List<string> deleted)
|
||||
{
|
||||
set = [];
|
||||
deleted = [];
|
||||
|
||||
// In the order of the Set-Cookie lines: a cookie new to the session goes after the others in that order.
|
||||
var renewed = new List<KeyValuePair<string, string>>();
|
||||
var expires = new Dictionary<string, DateTimeOffset>(StringComparer.Ordinal);
|
||||
if (response.Headers.TryGetValues("set-cookie", out var lines))
|
||||
{
|
||||
var now = _clock.Now;
|
||||
foreach (var line in lines)
|
||||
{
|
||||
if (SiteCookies.Parse(line, _site.IdnHost, now) is not { } cookie)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var index = renewed.FindIndex(c => c.Key == cookie.Name);
|
||||
if (cookie.Deletes)
|
||||
{
|
||||
if (index >= 0)
|
||||
{
|
||||
renewed.RemoveAt(index);
|
||||
}
|
||||
|
||||
expires.Remove(cookie.Name);
|
||||
set.Remove(cookie.Name);
|
||||
if (!deleted.Contains(cookie.Name))
|
||||
{
|
||||
deleted.Add(cookie.Name);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (index >= 0)
|
||||
{
|
||||
renewed[index] = new(cookie.Name, cookie.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
renewed.Add(new(cookie.Name, cookie.Value));
|
||||
}
|
||||
|
||||
if (cookie.Expires is { } until)
|
||||
{
|
||||
expires[cookie.Name] = until;
|
||||
}
|
||||
else
|
||||
{
|
||||
expires.Remove(cookie.Name);
|
||||
}
|
||||
|
||||
deleted.Remove(cookie.Name);
|
||||
if (!set.Contains(cookie.Name))
|
||||
{
|
||||
set.Add(cookie.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string? claim = null;
|
||||
if (response.Headers.TryGetValues("x-ig-set-www-claim", out var claims))
|
||||
{
|
||||
claim = claims.LastOrDefault(c => !string.IsNullOrWhiteSpace(c))?.Trim();
|
||||
}
|
||||
|
||||
return new SiteSessionUpdate(renewed, deleted, claim, expires, capture);
|
||||
}
|
||||
|
||||
private TimeSpan? RetryAfter(RetryConditionHeaderValue? header)
|
||||
{
|
||||
if (header?.Delta is { } delta)
|
||||
{
|
||||
return delta < TimeSpan.Zero ? TimeSpan.Zero : delta;
|
||||
}
|
||||
|
||||
if (header?.Date is { } date)
|
||||
{
|
||||
var wait = date - _clock.Now;
|
||||
return wait < TimeSpan.Zero ? TimeSpan.Zero : wait;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool RootFields(SiteOperation operation, byte[] body)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(body, BodyOptions);
|
||||
return operation.HasRootFields(document.RootElement);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<byte[]> ReadLimitedAsync(HttpContent content, int limit, CancellationToken ct)
|
||||
{
|
||||
if (content.Headers.ContentLength is > 0 and var declared && declared > limit)
|
||||
{
|
||||
throw new BodyTooLargeException();
|
||||
}
|
||||
|
||||
await using var stream = await content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||||
using var buffer = new MemoryStream();
|
||||
var chunk = new byte[16 * 1024];
|
||||
int read;
|
||||
while ((read = await stream.ReadAsync(chunk, ct).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
if (buffer.Length + read > limit)
|
||||
{
|
||||
throw new BodyTooLargeException();
|
||||
}
|
||||
|
||||
buffer.Write(chunk, 0, read);
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The body went past <see cref="HttpSiteRequesterOptions.MaxBodyBytes"/>: a type of its own, so no decoder error is taken for it.</summary>
|
||||
private sealed class BodyTooLargeException : Exception
|
||||
{
|
||||
public BodyTooLargeException()
|
||||
: base("Risposta troppo grande.")
|
||||
{
|
||||
}
|
||||
|
||||
public BodyTooLargeException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public BodyTooLargeException(string message, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private SiteUnreachableException Unreachable(SiteOperation operation, SiteUnreachableReason reason)
|
||||
{
|
||||
var what = reason switch
|
||||
{
|
||||
SiteUnreachableReason.Timeout => string.Create(CultureInfo.InvariantCulture, $"nessuna risposta entro {(long)_options.Timeout.TotalSeconds} s"),
|
||||
SiteUnreachableReason.TooLarge => "risposta troppo grande, scartata",
|
||||
SiteUnreachableReason.Broken => "risposta interrotta o non decomprimibile, scartata",
|
||||
_ => "il sito non si raggiunge",
|
||||
};
|
||||
_log($"Client del sito: «{operation.Name}» {operation.PathShape}, {what}.");
|
||||
return new SiteUnreachableException($"Richiesta «{operation.Name}» ({operation.PathShape}): {what}.", reason);
|
||||
}
|
||||
|
||||
private static Uri CheckAddress(RequestCatalog catalog, Uri address)
|
||||
{
|
||||
if (RefusalOfAddress(catalog, address) is { } refusal)
|
||||
{
|
||||
throw new ArgumentException($"Client del sito di {catalog.Site}: {refusal}.", nameof(address));
|
||||
}
|
||||
|
||||
return new Uri(address.GetLeftPart(UriPartial.Authority) + "/", UriKind.Absolute);
|
||||
}
|
||||
|
||||
private static bool IsLoopback(Uri address) =>
|
||||
address.HostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6
|
||||
&& IPAddress.TryParse(address.IdnHost.Trim('[', ']'), out var ip)
|
||||
&& IPAddress.IsLoopback(ip);
|
||||
}
|
||||
@@ -36,7 +36,7 @@ public interface ISiteRequester
|
||||
/// the catalog or not configured, values that do not match. The message is in Italian and names only the operation and
|
||||
/// value names.
|
||||
/// </summary>
|
||||
public sealed class SiteRequestRefusedException : InvalidOperationException
|
||||
public class SiteRequestRefusedException : InvalidOperationException
|
||||
{
|
||||
public SiteRequestRefusedException()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,409 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// The saved session the site client reads its values from and writes the site's renewals to (issue #36, spec §6.0,
|
||||
/// §13.2): the cookies of the site with their values, the user agent of the browser as it is, the tokens and
|
||||
/// identifiers the page holds, the <c>doc_id</c> of each catalog operation and the <c>x-ig-www-claim</c>. Tappa S4 adds
|
||||
/// the encrypted file of <c>Dati/sessione</c>; <see cref="InMemorySiteSession"/> serves the tests and the test site.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only the site client and the copy from the browser («Ho finito», S4) touch it. Its values never reach a log, a
|
||||
/// message or an exception: what an implementation tells about them is counts and names (rule 10).
|
||||
/// </remarks>
|
||||
public interface ISiteSession
|
||||
{
|
||||
/// <summary>The values as they are now; null when there is no saved session (Disconnessione, §7.6).</summary>
|
||||
SiteSessionValues? Read();
|
||||
|
||||
/// <summary>
|
||||
/// Applies what the site sent with one answer (renewed or deleted cookies, a new claim) in one write, so a stored
|
||||
/// session never holds half an answer. Does nothing when there is no saved session, and nothing when
|
||||
/// <see cref="SiteSessionUpdate.Capture"/> names another capture than the stored one: the late answer of a session
|
||||
/// a new login replaced never touches the new one (§6.0: «un nuovo accesso ricopia tutto e sostituisce»).
|
||||
/// </summary>
|
||||
Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A snapshot of the saved session. Its text (<see cref="ToString"/>) shows counts only, never a name of the account,
|
||||
/// a value of a cookie or of a token.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Cookies are the ones the browser would send to the site's address (S4 copies them with <c>Network.getCookies</c>
|
||||
/// for that address, so domain and path are already resolved by the browser), each with its expiry when it has one: an
|
||||
/// expired cookie is not sent, an expired session cookie is a missing session (§7.6, Disconnessione).
|
||||
/// </remarks>
|
||||
public sealed class SiteSessionValues
|
||||
{
|
||||
/// <summary>The initial value of <c>x-ig-www-claim</c> the page sends until the site sets one (H13).</summary>
|
||||
public const string InitialClaim = "0";
|
||||
|
||||
private static long s_captures;
|
||||
|
||||
/// <param name="cookies">Cookies of the site, by name, in the order the browser had them, values as they are.</param>
|
||||
/// <param name="userAgent">The user agent of Febe's browser, copied as it is (rule 4).</param>
|
||||
/// <param name="fields">
|
||||
/// Values of the page by the names of <see cref="ValueSource.SessionFields"/> other than <c>user_agent</c> and
|
||||
/// <c>doc_id</c>: <c>lsd</c>, <c>fb_dtsg</c>, <c>app_id</c>, <c>claim</c>, <c>account_id</c>.
|
||||
/// </param>
|
||||
/// <param name="docIds">The <c>doc_id</c> of each GraphQL operation of the catalog, by operation name.</param>
|
||||
/// <param name="expires">When cookies expire, by name; a cookie not listed lasts as long as the session.</param>
|
||||
/// <exception cref="ArgumentException">A cookie name that is not a plain name, or a field that is not a session field.</exception>
|
||||
public SiteSessionValues(
|
||||
IEnumerable<KeyValuePair<string, string>> cookies,
|
||||
string userAgent,
|
||||
IReadOnlyDictionary<string, string>? fields = null,
|
||||
IReadOnlyDictionary<string, string>? docIds = null,
|
||||
IReadOnlyDictionary<string, DateTimeOffset>? expires = null)
|
||||
: this(cookies, userAgent, fields, docIds, expires, Interlocked.Increment(ref s_captures))
|
||||
{
|
||||
}
|
||||
|
||||
private SiteSessionValues(
|
||||
IEnumerable<KeyValuePair<string, string>> cookies,
|
||||
string userAgent,
|
||||
IReadOnlyDictionary<string, string>? fields,
|
||||
IReadOnlyDictionary<string, string>? docIds,
|
||||
IReadOnlyDictionary<string, DateTimeOffset>? expires,
|
||||
long capture)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cookies);
|
||||
ArgumentNullException.ThrowIfNull(userAgent);
|
||||
var list = new List<KeyValuePair<string, string>>();
|
||||
foreach (var (name, value) in cookies)
|
||||
{
|
||||
if (!SiteCookies.IsPlainName(name))
|
||||
{
|
||||
throw new ArgumentException("Un nome di cookie della sessione non è un nome semplice.", nameof(cookies));
|
||||
}
|
||||
|
||||
var index = list.FindIndex(c => c.Key == name);
|
||||
if (index >= 0)
|
||||
{
|
||||
list[index] = new(name, value ?? string.Empty);
|
||||
}
|
||||
else
|
||||
{
|
||||
list.Add(new(name, value ?? string.Empty));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var name in (fields ?? new Dictionary<string, string>()).Keys)
|
||||
{
|
||||
if (!ValueSource.SessionFields.Contains(name) || name is "user_agent" or "doc_id")
|
||||
{
|
||||
throw new ArgumentException($"«{name}» non è un valore della sessione (ammessi: lsd, fb_dtsg, app_id, claim, account_id).", nameof(fields));
|
||||
}
|
||||
}
|
||||
|
||||
Cookies = list;
|
||||
UserAgent = userAgent;
|
||||
Fields = (fields ?? new Dictionary<string, string>()).ToFrozenDictionary(StringComparer.Ordinal);
|
||||
DocIds = (docIds ?? new Dictionary<string, string>()).ToFrozenDictionary(StringComparer.Ordinal);
|
||||
Expires = (expires ?? new Dictionary<string, DateTimeOffset>())
|
||||
.Where(e => list.Exists(c => c.Key == e.Key))
|
||||
.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
Capture = capture;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which capture from the browser these values come from: the same through every renewal (<see cref="With"/>),
|
||||
/// another for a new login. Says nothing of the account.
|
||||
/// </summary>
|
||||
public long Capture { get; }
|
||||
|
||||
/// <summary>Cookies of the site, by name, in order (never logged).</summary>
|
||||
public IReadOnlyList<KeyValuePair<string, string>> Cookies { get; }
|
||||
|
||||
/// <summary>When cookies expire, by name; a cookie not listed lasts as long as the session.</summary>
|
||||
public IReadOnlyDictionary<string, DateTimeOffset> Expires { get; }
|
||||
|
||||
/// <summary>The user agent of Febe's browser, as it is.</summary>
|
||||
public string UserAgent { get; }
|
||||
|
||||
/// <summary>Values of the page (<c>lsd</c>, <c>fb_dtsg</c>, <c>app_id</c>, <c>claim</c>, <c>account_id</c>).</summary>
|
||||
public IReadOnlyDictionary<string, string> Fields { get; }
|
||||
|
||||
/// <summary>The <c>doc_id</c> of each GraphQL operation, by operation name.</summary>
|
||||
public IReadOnlyDictionary<string, string> DocIds { get; }
|
||||
|
||||
/// <summary>The value of the cookie <paramref name="name"/>, or null.</summary>
|
||||
public string? Cookie(string name)
|
||||
{
|
||||
foreach (var (key, value) in Cookies)
|
||||
{
|
||||
if (key == name)
|
||||
{
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The value of the cookie <paramref name="name"/> the browser would still send at <paramref name="now"/>: null when missing, empty or expired.</summary>
|
||||
public string? CookieAt(string name, DateTimeOffset now) =>
|
||||
Cookie(name) is { Length: > 0 } value && !IsExpired(name, now) ? value : null;
|
||||
|
||||
/// <summary>The cookies the browser would still send at <paramref name="now"/>, in order: no empty and no expired one.</summary>
|
||||
public IEnumerable<KeyValuePair<string, string>> CookiesAt(DateTimeOffset now) =>
|
||||
Cookies.Where(c => c.Value.Length > 0 && !IsExpired(c.Key, now));
|
||||
|
||||
/// <summary>
|
||||
/// The value of a session field of the catalog (<see cref="ValueSource.SessionFields"/>) for
|
||||
/// <paramref name="operation"/>: <c>user_agent</c>, the <c>doc_id</c> of the operation, or a value of the page. Null
|
||||
/// when the session does not have it, or it is empty; the claim the site has not set yet is
|
||||
/// <see cref="InitialClaim"/>, as the page sends it.
|
||||
/// </summary>
|
||||
public string? Field(string name, string operation) => name switch
|
||||
{
|
||||
"user_agent" => UserAgent.Length > 0 ? UserAgent : null,
|
||||
"doc_id" => DocIds.TryGetValue(operation, out var docId) && docId.Length > 0 ? docId : null,
|
||||
"claim" => Fields.TryGetValue(name, out var claim) && claim.Length > 0 ? claim : InitialClaim,
|
||||
_ => Fields.TryGetValue(name, out var value) && value.Length > 0 ? value : null,
|
||||
};
|
||||
|
||||
/// <summary>These values with <paramref name="update"/> applied (same <see cref="Capture"/>).</summary>
|
||||
public SiteSessionValues With(SiteSessionUpdate update)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update);
|
||||
var cookies = Cookies.Where(c => !update.CookiesDeleted.Contains(c.Key, StringComparer.Ordinal)).ToList();
|
||||
var expires = Expires.Where(e => !update.CookiesDeleted.Contains(e.Key, StringComparer.Ordinal)).ToDictionary(StringComparer.Ordinal);
|
||||
foreach (var (name, value) in update.CookiesSet)
|
||||
{
|
||||
var index = cookies.FindIndex(c => c.Key == name);
|
||||
if (index >= 0)
|
||||
{
|
||||
// Renewed in place: the browser keeps the creation time of a cookie it overwrites, so its place.
|
||||
cookies[index] = new(name, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
cookies.Add(new(name, value));
|
||||
}
|
||||
|
||||
if (update.Expires.TryGetValue(name, out var until))
|
||||
{
|
||||
expires[name] = until;
|
||||
}
|
||||
else
|
||||
{
|
||||
expires.Remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
var fields = Fields.ToDictionary(StringComparer.Ordinal);
|
||||
if (update.Claim is { } claim)
|
||||
{
|
||||
fields["claim"] = claim;
|
||||
}
|
||||
|
||||
return new SiteSessionValues(cookies, UserAgent, fields, DocIds, expires, Capture);
|
||||
}
|
||||
|
||||
private bool IsExpired(string name, DateTimeOffset now) => Expires.TryGetValue(name, out var until) && until <= now;
|
||||
|
||||
/// <summary>Counts only.</summary>
|
||||
public override string ToString() => string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"Sessione salvata: {Cookies.Count} cookie, {Fields.Count} valori della pagina, {DocIds.Count} doc_id.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the site sent with one answer for the saved session: cookies it renewed (with their values), cookies it
|
||||
/// deleted (names), a new <c>x-ig-www-claim</c>. Its text shows counts only.
|
||||
/// </summary>
|
||||
public sealed class SiteSessionUpdate
|
||||
{
|
||||
/// <param name="cookiesSet">Cookies set or renewed, in the order of the <c>Set-Cookie</c> lines (a name twice: the last value, the first place).</param>
|
||||
/// <param name="cookiesDeleted">Names of the cookies deleted.</param>
|
||||
/// <param name="claim">The new claim, or null.</param>
|
||||
/// <param name="expires">When the cookies set expire, by name; one not listed lasts as long as the session.</param>
|
||||
/// <param name="capture">The <see cref="SiteSessionValues.Capture"/> the request was sent with; null applies to any.</param>
|
||||
public SiteSessionUpdate(
|
||||
IEnumerable<KeyValuePair<string, string>>? cookiesSet = null,
|
||||
IEnumerable<string>? cookiesDeleted = null,
|
||||
string? claim = null,
|
||||
IReadOnlyDictionary<string, DateTimeOffset>? expires = null,
|
||||
long? capture = null)
|
||||
{
|
||||
var set = new List<KeyValuePair<string, string>>();
|
||||
foreach (var (name, value) in cookiesSet ?? [])
|
||||
{
|
||||
var index = set.FindIndex(c => c.Key == name);
|
||||
if (index >= 0)
|
||||
{
|
||||
set[index] = new(name, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
set.Add(new(name, value));
|
||||
}
|
||||
}
|
||||
|
||||
CookiesSet = set;
|
||||
CookiesDeleted = [.. (cookiesDeleted ?? []).Distinct(StringComparer.Ordinal)];
|
||||
Claim = string.IsNullOrEmpty(claim) ? null : claim;
|
||||
Expires = (expires ?? new Dictionary<string, DateTimeOffset>()).ToFrozenDictionary(StringComparer.Ordinal);
|
||||
Capture = capture;
|
||||
}
|
||||
|
||||
/// <summary>Cookies set or renewed, with their values, in the order the site set them (never logged).</summary>
|
||||
public IReadOnlyList<KeyValuePair<string, string>> CookiesSet { get; }
|
||||
|
||||
/// <summary>When the cookies set expire, by name.</summary>
|
||||
public IReadOnlyDictionary<string, DateTimeOffset> Expires { get; }
|
||||
|
||||
/// <summary>The capture the request was sent with: the update applies only to that one (null: to any).</summary>
|
||||
public long? Capture { get; }
|
||||
|
||||
/// <summary>Names of the cookies the site deleted.</summary>
|
||||
public IReadOnlyList<string> CookiesDeleted { get; }
|
||||
|
||||
/// <summary>The new claim (<c>x-ig-set-www-claim</c>), or null.</summary>
|
||||
public string? Claim { get; }
|
||||
|
||||
/// <summary>True when there is nothing to write.</summary>
|
||||
public bool IsEmpty => CookiesSet.Count == 0 && CookiesDeleted.Count == 0 && Claim is null;
|
||||
|
||||
/// <summary>Counts only.</summary>
|
||||
public override string ToString() => string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"Aggiornamento della sessione: {CookiesSet.Count} cookie rinnovati, {CookiesDeleted.Count} cancellati{(Claim is null ? string.Empty : ", nuovo claim")}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The saved session in memory (issue #36, S2): for the tests, the simulation and the test site, until tappa S4 adds the
|
||||
/// encrypted file. Thread-safe; every update replaces the snapshot at once.
|
||||
/// </summary>
|
||||
public sealed class InMemorySiteSession : ISiteSession
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private SiteSessionValues? _values;
|
||||
private int _updates;
|
||||
|
||||
/// <param name="values">The session; null for none (no saved session).</param>
|
||||
public InMemorySiteSession(SiteSessionValues? values) => _values = values;
|
||||
|
||||
/// <summary>How many non-empty updates were applied.</summary>
|
||||
public int Updates => Volatile.Read(ref _updates);
|
||||
|
||||
public SiteSessionValues? Read()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _values;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Replaces the whole session (a new login), or removes it with null («Scollega»).</summary>
|
||||
public void Replace(SiteSessionValues? values)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_values = values;
|
||||
}
|
||||
}
|
||||
|
||||
public Task UpdateAsync(SiteSessionUpdate update, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(update);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (update.IsEmpty)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
// No session, or the late answer of one a new login replaced: nothing to change.
|
||||
if (_values is null || (update.Capture is { } capture && capture != _values.Capture))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
_values = _values.With(update);
|
||||
_updates++;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Counts only.</summary>
|
||||
public override string ToString() => Read()?.ToString() ?? "Nessuna sessione salvata.";
|
||||
}
|
||||
|
||||
/// <summary>Cookie names and the <c>Set-Cookie</c> lines of the site, read the way a browser reads them (RFC 6265).</summary>
|
||||
public static class SiteCookies
|
||||
{
|
||||
/// <summary>True for a plain cookie name: no separator, space, quote or control character.</summary>
|
||||
public static bool IsPlainName(string? name) =>
|
||||
!string.IsNullOrEmpty(name) && name.Length <= 256
|
||||
&& !name.Any(c => c is '=' or ';' or ',' or '"' or '\\' || char.IsWhiteSpace(c) || char.IsControl(c) || c > '\x7e');
|
||||
|
||||
/// <summary>
|
||||
/// One <c>Set-Cookie</c> line: its name, its value as the browser keeps it (RFC 6265 §5.2: double quotes are part
|
||||
/// of the value), whether it deletes the cookie (an empty value or <c>""</c>, a <c>Max-Age</c> of zero or less, an
|
||||
/// <c>Expires</c> not after <paramref name="now"/>), and when it expires (null: with the session). Null for a line
|
||||
/// that is not a cookie, or one for another domain than <paramref name="host"/> (a browser would refuse it).
|
||||
/// </summary>
|
||||
public static (string Name, string Value, bool Deletes, DateTimeOffset? Expires)? Parse(string line, string host, DateTimeOffset now)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(line);
|
||||
ArgumentNullException.ThrowIfNull(host);
|
||||
var parts = line.Split(';');
|
||||
var pair = parts[0];
|
||||
var equals = pair.IndexOf('=', StringComparison.Ordinal);
|
||||
if (equals <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = pair[..equals].Trim();
|
||||
var value = pair[(equals + 1)..].Trim();
|
||||
if (!IsPlainName(name))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var empty = value.Length == 0 || value == "\"\"";
|
||||
DateTimeOffset? byAge = null;
|
||||
DateTimeOffset? byDate = null;
|
||||
foreach (var attribute in parts.Skip(1))
|
||||
{
|
||||
var cut = attribute.IndexOf('=', StringComparison.Ordinal);
|
||||
var key = (cut < 0 ? attribute : attribute[..cut]).Trim();
|
||||
var argument = cut < 0 ? string.Empty : attribute[(cut + 1)..].Trim();
|
||||
if (key.Equals("max-age", StringComparison.OrdinalIgnoreCase)
|
||||
&& long.TryParse(argument, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
|
||||
{
|
||||
// The last Max-Age counts (RFC 6265 §5.3: attributes are read in order).
|
||||
byAge = seconds <= 0 ? DateTimeOffset.MinValue
|
||||
: seconds >= (DateTimeOffset.MaxValue - now).TotalSeconds ? DateTimeOffset.MaxValue
|
||||
: now.AddSeconds(seconds);
|
||||
}
|
||||
else if (key.Equals("expires", StringComparison.OrdinalIgnoreCase)
|
||||
&& DateTimeOffset.TryParse(argument, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AllowWhiteSpaces, out var expires))
|
||||
{
|
||||
byDate = expires;
|
||||
}
|
||||
else if (key.Equals("domain", StringComparison.OrdinalIgnoreCase) && argument.Length > 0)
|
||||
{
|
||||
var domain = argument.TrimStart('.');
|
||||
if (!host.Equals(domain, StringComparison.OrdinalIgnoreCase)
|
||||
&& !host.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Max-Age wins over Expires (RFC 6265 §5.3 step 3).
|
||||
var until = byAge ?? byDate;
|
||||
var deletes = empty || until <= now;
|
||||
return (name, value, deletes, deletes ? null : until);
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,10 @@ public sealed partial class SiteOperation
|
||||
IReadOnlyList<string> rootFields,
|
||||
string? sample,
|
||||
IReadOnlySet<string> required,
|
||||
IReadOnlySet<string> optional)
|
||||
IReadOnlySet<string> optional,
|
||||
IReadOnlyList<string> parameterOrder,
|
||||
IReadOnlyList<string> headerOrder,
|
||||
IReadOnlyList<string> bodyOrder)
|
||||
{
|
||||
Name = name;
|
||||
Kind = kind;
|
||||
@@ -109,6 +112,9 @@ public sealed partial class SiteOperation
|
||||
Sample = sample;
|
||||
RequiredValues = required;
|
||||
OptionalValues = optional;
|
||||
ParameterOrder = parameterOrder;
|
||||
HeaderOrder = headerOrder;
|
||||
BodyOrder = bodyOrder;
|
||||
PathShape = Placeholder().Replace(path, m => CaseValues.ShapeOf(m.Groups[1].Value));
|
||||
PathValues = Placeholder().Matches(path).Select(m => m.Groups[1].Value).ToFrozenSet(StringComparer.Ordinal);
|
||||
PendingValues = [.. headers.Where(h => h.Value.Kind == ValueSourceKind.Pending).Select(h => h.Key)
|
||||
@@ -162,6 +168,15 @@ public sealed partial class SiteOperation
|
||||
/// <summary>The form fields of a GraphQL query and where each value comes from.</summary>
|
||||
public IReadOnlyDictionary<string, ValueSource> Body { get; }
|
||||
|
||||
/// <summary>The names of <see cref="Parameters"/> in the order of the file: the order the site client writes them in.</summary>
|
||||
public IReadOnlyList<string> ParameterOrder { get; }
|
||||
|
||||
/// <summary>The names of <see cref="Headers"/> in the order of the file (the request shapes keep the browser's order).</summary>
|
||||
public IReadOnlyList<string> HeaderOrder { get; }
|
||||
|
||||
/// <summary>The names of <see cref="Body"/> in the order of the file (the request shapes keep the page's order).</summary>
|
||||
public IReadOnlyList<string> BodyOrder { get; }
|
||||
|
||||
/// <summary>The template of the variables of a GraphQL query: constants as the shapes show them, <c>"{name}"</c> for a value of the case.</summary>
|
||||
public JsonElement? Variables { get; }
|
||||
|
||||
@@ -645,6 +660,12 @@ public sealed partial class RequestCatalog
|
||||
$"{where}: {pending.Count.ToString(CultureInfo.InvariantCulture)} intestazioni o campi hanno la fonte «pending» (come {string.Join(", ", pending.Take(3).Select(p => $"«{p}»"))}): non può essere configurata finché non si sa da dove vengono i valori (regola 9).");
|
||||
}
|
||||
|
||||
// The HTTP stack adds no user agent: without this line the request would leave without one (rule 4).
|
||||
if (!headers.ContainsKey("user-agent"))
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un'operazione configurata manda l'user agent del browser («user-agent»: «session:user_agent», regola 4).");
|
||||
}
|
||||
|
||||
if (sample is null || rootFields.Count == 0)
|
||||
{
|
||||
throw new InvalidDataException($"{where}: un'operazione configurata dice il campione della risposta («sample») e i campi attesi («rootFields»).");
|
||||
@@ -658,7 +679,8 @@ public sealed partial class RequestCatalog
|
||||
return new SiteOperation(
|
||||
name, kind, method!, path, category, configured, reason, parameters.ToFrozenDictionary(StringComparer.Ordinal),
|
||||
headers.ToFrozenDictionary(StringComparer.Ordinal), body.ToFrozenDictionary(StringComparer.Ordinal), variables,
|
||||
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal));
|
||||
rootFields, sample, required.ToFrozenSet(StringComparer.Ordinal), optional.ToFrozenSet(StringComparer.Ordinal),
|
||||
[.. parameters.Keys], [.. headers.Keys], [.. body.Keys]);
|
||||
}
|
||||
|
||||
private static Dictionary<string, ValueSource> Sources(Dictionary<string, string?>? entries, string where, string what, bool isBody)
|
||||
|
||||
@@ -30,6 +30,10 @@ public sealed class SiteAnswer
|
||||
/// <param name="cookiesDeleted">Names of the cookies the site deleted (<c>Set-Cookie</c> expired or empty).</param>
|
||||
/// <param name="setsClaim">True when the site sent a new <c>x-ig-www-claim</c> (<c>x-ig-set-www-claim</c>).</param>
|
||||
/// <param name="retryAfter">What a <c>Retry-After</c> asked to wait, when the site sent one.</param>
|
||||
/// <param name="rootFieldsPresent">
|
||||
/// Whether the body is JSON with every field of <see cref="SiteOperation.RootFields"/>: true or false when the site
|
||||
/// client looked (it does for every answer), null when nobody did (<see cref="SiteAnswerSignals"/> then looks itself).
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentException">A cookie name that is not a plain name (a value must never slip in).</exception>
|
||||
public SiteAnswer(
|
||||
SiteOperation operation,
|
||||
@@ -40,7 +44,8 @@ public sealed class SiteAnswer
|
||||
IEnumerable<string>? cookiesSet = null,
|
||||
IEnumerable<string>? cookiesDeleted = null,
|
||||
bool setsClaim = false,
|
||||
TimeSpan? retryAfter = null)
|
||||
TimeSpan? retryAfter = null,
|
||||
bool? rootFieldsPresent = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
Operation = operation.Name;
|
||||
@@ -54,6 +59,7 @@ public sealed class SiteAnswer
|
||||
CookiesDeleted = Names(cookiesDeleted, nameof(cookiesDeleted));
|
||||
SetsClaim = setsClaim;
|
||||
RetryAfter = retryAfter;
|
||||
RootFieldsPresent = rootFieldsPresent;
|
||||
}
|
||||
|
||||
/// <summary>Name of the catalog operation that was asked.</summary>
|
||||
@@ -92,6 +98,12 @@ public sealed class SiteAnswer
|
||||
/// <summary>What a <c>Retry-After</c> asked to wait (§7.6, Rallentamento).</summary>
|
||||
public TimeSpan? RetryAfter { get; }
|
||||
|
||||
/// <summary>
|
||||
/// True when the body is JSON with every expected field of the operation, false when it is not JSON or misses one
|
||||
/// (§6.0: stop and warn), null when it was not looked at.
|
||||
/// </summary>
|
||||
public bool? RootFieldsPresent { get; }
|
||||
|
||||
/// <summary>True when the declared type is JSON, or JavaScript as Instagram serves its GraphQL data (<see cref="DataResponses.IsData"/>).</summary>
|
||||
public bool IsDeclaredData => DataResponses.IsData(MimeType, "Fetch");
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Requests;
|
||||
|
||||
/// <summary>A stop signal read from an answer of the site client, with the Italian text the interface and the log show.</summary>
|
||||
/// <param name="Signal">The signal for the circuit breaker; its address is the path shape of the operation, never a value.</param>
|
||||
/// <param name="Message">What happened, in Italian: operation, status, path shapes, never a value or a body.</param>
|
||||
/// <param name="Hypothesis">The hypothesis of spec §6.6 the reading depends on (<c>H16</c>), when the true shapes are not known yet.</param>
|
||||
public sealed record SiteAnswerSignal(Signal Signal, string Message, string? Hypothesis);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the stop signals of spec §7.6 from a <see cref="SiteAnswer"/> (issue #36, S2), whatever brought it: the HTTP
|
||||
/// site client or its test double. Transport-neutral: status, type, redirect, cookies and body only.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// In order, the first that applies:
|
||||
/// <list type="number">
|
||||
/// <item>the status rules of <c>segnali.json</c> for the site (429 is a Rallentamento, as for the browser);</item>
|
||||
/// <item>the session cookie deleted by the site;</item>
|
||||
/// <item>a redirect (3xx, never followed), a 401 or a 403;</item>
|
||||
/// <item>then, whatever the status: an HTML document where the catalog expects JSON, a body that is not JSON (an empty
|
||||
/// one included), the text rules of <c>segnali.json</c> on a short JSON;</item>
|
||||
/// <item>last, for every status but 404 (a JSON «not found» is an answer, the recipe decides) and 5xx (a JSON error of
|
||||
/// the site, S3 decides whether to try again later): a JSON without the expected fields of the operation.</item>
|
||||
/// </list>
|
||||
/// Until the true shapes of an expired or challenged session are known (H16), the cases after the status rules are a
|
||||
/// <see cref="SignalLevel.Challenge"/> (Verifica): Febe stops, warns, and Alberto decides whether to log in again
|
||||
/// (decision of 16 November 2026). A JSON answer with its fields and nothing of the above gives no signal.
|
||||
/// </remarks>
|
||||
public sealed class SiteAnswerSignals
|
||||
{
|
||||
/// <summary>A 3xx: never followed.</summary>
|
||||
public const string RedirectCode = "site-redirect";
|
||||
|
||||
/// <summary>A 401.</summary>
|
||||
public const string UnauthorizedCode = "site-unauthorized";
|
||||
|
||||
/// <summary>A 403.</summary>
|
||||
public const string ForbiddenCode = "site-forbidden";
|
||||
|
||||
/// <summary>An HTML document where the catalog expects JSON.</summary>
|
||||
public const string HtmlCode = "site-html-instead-of-json";
|
||||
|
||||
/// <summary>A body that is not JSON.</summary>
|
||||
public const string NotJsonCode = "site-not-json";
|
||||
|
||||
/// <summary>A JSON without the expected fields of the operation.</summary>
|
||||
public const string MissingFieldsCode = "site-missing-fields";
|
||||
|
||||
/// <summary>A <c>Set-Cookie</c> that deletes the session cookie.</summary>
|
||||
public const string SessionCookieDeletedCode = "site-session-cookie-deleted";
|
||||
|
||||
/// <summary>No saved session, or one without the session cookie or a value the catalog asks for: nothing left.</summary>
|
||||
public const string SessionMissingCode = "saved-session-missing";
|
||||
|
||||
/// <summary>The hypothesis the H16 readings depend on.</summary>
|
||||
public const string H16 = "H16";
|
||||
|
||||
private const string Decides = "Febe si ferma e non rifà l'accesso da sola: decide Alberto.";
|
||||
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = ResponseDelivery.MaxDepth };
|
||||
|
||||
private readonly SignalRules _rules;
|
||||
private readonly string _sessionCookie;
|
||||
|
||||
/// <param name="rules">The rules of the site (<c>segnali.json</c>, <c>segnali.prova.json</c>).</param>
|
||||
/// <param name="sessionCookie">Name of the session cookie of the site (<c>sessionid</c>, <c>sessione_prova</c>).</param>
|
||||
public SiteAnswerSignals(SignalRules rules, string sessionCookie)
|
||||
{
|
||||
_rules = rules ?? throw new ArgumentNullException(nameof(rules));
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(sessionCookie);
|
||||
_sessionCookie = sessionCookie;
|
||||
}
|
||||
|
||||
/// <summary>The signal <paramref name="answer"/> carries, or null when it carries none.</summary>
|
||||
/// <param name="operation">The catalog operation that was asked (its expected fields).</param>
|
||||
/// <param name="answer">What the site answered.</param>
|
||||
/// <param name="at">When (the engine's clock).</param>
|
||||
/// <exception cref="ArgumentException"><paramref name="answer"/> is not an answer to <paramref name="operation"/>.</exception>
|
||||
public SiteAnswerSignal? Classify(SiteOperation operation, SiteAnswer answer, DateTimeOffset at)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
ArgumentNullException.ThrowIfNull(answer);
|
||||
if (answer.Operation != operation.Name)
|
||||
{
|
||||
throw new ArgumentException("La risposta non è di questa operazione.", nameof(answer));
|
||||
}
|
||||
|
||||
var what = $"«{operation.Name}» ({operation.PathShape})";
|
||||
var status = answer.Status.ToString(CultureInfo.InvariantCulture);
|
||||
foreach (var rule in _rules.Rules)
|
||||
{
|
||||
if (rule.Statuses.Contains(answer.Status) && rule.HostKinds.Contains(HostKind.Site) && (rule.Scope & SignalScope.Subresource) != 0)
|
||||
{
|
||||
var wait = answer.RetryAfter is { } retry ? string.Create(CultureInfo.InvariantCulture, $", chiede di attendere {(long)retry.TotalSeconds} s") : string.Empty;
|
||||
return Make(rule.Level, rule.Code, operation, at, $"{what}: il sito ha risposto con lo stato {status}{wait}.", rule.Hypothesis);
|
||||
}
|
||||
}
|
||||
|
||||
if (answer.Deletes(_sessionCookie))
|
||||
{
|
||||
return Challenge(SessionCookieDeletedCode, operation, at, $"{what}: il sito ha cancellato il cookie di sessione (stato {status}). {Decides}");
|
||||
}
|
||||
|
||||
if (answer.IsRedirect)
|
||||
{
|
||||
var to = answer.RedirectPathShape is { Length: > 0 } shape ? $" a {shape}" : " senza indirizzo";
|
||||
return Challenge(RedirectCode, operation, at, $"{what}: il sito ha risposto con un rinvio{to} (stato {status}), non seguito. {Decides}");
|
||||
}
|
||||
|
||||
if (answer.Status is 401 or 403)
|
||||
{
|
||||
return Challenge(answer.Status == 401 ? UnauthorizedCode : ForbiddenCode, operation, at, $"{what}: il sito ha rifiutato la richiesta (stato {status}). {Decides}");
|
||||
}
|
||||
|
||||
// A JSON «not found» or site error is an answer for the recipe (S3); an HTML or a body that is not JSON is not,
|
||||
// whatever the status (§6.0: «una risposta che non è JSON quando il modello si aspetta JSON ferma la sessione»).
|
||||
var jsonLeftToCaller = answer.Status == 404 || answer.Status >= 500;
|
||||
|
||||
if (answer.IsHtml || LooksLikeHtml(answer.Body.Span))
|
||||
{
|
||||
return Challenge(HtmlCode, operation, at, $"{what}: il sito ha mandato una pagina HTML al posto dei dati JSON (stato {status}). {Decides}");
|
||||
}
|
||||
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(answer.Body, BodyOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return Challenge(NotJsonCode, operation, at, $"{what}: la risposta non è JSON (stato {status}, {(answer.MimeType.Length == 0 ? "senza tipo" : answer.MimeType)}). {Decides}");
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
foreach (var rule in _rules.Rules)
|
||||
{
|
||||
if (rule.Text is not null && rule.HostKinds.Contains(HostKind.Site) && SignalDetector.ContainsText(document.RootElement, rule.Text, rule.MaxTextChars))
|
||||
{
|
||||
return Make(rule.Level, rule.Code, operation, at, $"{what}: la risposta chiede di fermarsi («{rule.Code}», stato {status}).", rule.Hypothesis);
|
||||
}
|
||||
}
|
||||
|
||||
if (jsonLeftToCaller)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var present = answer.RootFieldsPresent ?? operation.HasRootFields(document.RootElement);
|
||||
if (!present)
|
||||
{
|
||||
return Challenge(
|
||||
MissingFieldsCode,
|
||||
operation,
|
||||
at,
|
||||
$"{what}: nella risposta mancano i campi attesi ({string.Join(", ", operation.RootFields)}; stato {status}). Il formato può essere cambiato o la sessione non vale più. {Decides}");
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The signal of a request that did not leave because the saved session is missing or incomplete (§7.6,
|
||||
/// Disconnessione: «la sessione salvata manca»).
|
||||
/// </summary>
|
||||
public static SiteAnswerSignal ForMissingSession(SiteSessionMissingException refusal, DateTimeOffset at)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(refusal);
|
||||
var what = refusal.Missing is null ? "non c'è una sessione salvata" : $"nella sessione salvata manca «{refusal.Missing}»";
|
||||
return new SiteAnswerSignal(
|
||||
new Signal(SignalLevel.Disconnect, SessionMissingCode, null, at),
|
||||
$"Client del sito: {what}. Serve un nuovo accesso dal browser di Febe; Febe non rientra da sola.",
|
||||
null);
|
||||
}
|
||||
|
||||
private static SiteAnswerSignal Challenge(string code, SiteOperation operation, DateTimeOffset at, string message) =>
|
||||
Make(SignalLevel.Challenge, code, operation, at, message, H16);
|
||||
|
||||
private static SiteAnswerSignal Make(SignalLevel level, string code, SiteOperation operation, DateTimeOffset at, string message, string? hypothesis) =>
|
||||
new(new Signal(level, code, operation.PathShape, at), message, hypothesis);
|
||||
|
||||
/// <summary>A body that starts as an HTML document, whatever its declared type.</summary>
|
||||
private static bool LooksLikeHtml(ReadOnlySpan<byte> body)
|
||||
{
|
||||
var head = Encoding.UTF8.GetString(body[..Math.Min(body.Length, 512)]).TrimStart('', ' ', '\t', '\r', '\n');
|
||||
return head.StartsWith("<!doctype html", StringComparison.OrdinalIgnoreCase)
|
||||
|| head.StartsWith("<html", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,7 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
|
||||
}
|
||||
|
||||
/// <summary>Looks for <paramref name="regex"/> in the string values, giving up when they exceed <paramref name="maxChars"/>.</summary>
|
||||
private static bool ContainsText(JsonElement root, Regex regex, int maxChars)
|
||||
internal static bool ContainsText(JsonElement root, Regex regex, int maxChars)
|
||||
{
|
||||
var budget = maxChars;
|
||||
var strings = new List<string>();
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
{
|
||||
"site": "prova",
|
||||
"note": "Operazioni che il client del sito chiederà al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Il sito di prova non controlla le intestazioni; le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET.",
|
||||
"note": "Operazioni che il client del sito chiede al sito di prova locale (tools/Febe.SitoDiProva, specifica §14.2) dalla tappa S2 di #36: le stesse risposte JSON che la pagina chiede a /dati/, servite sotto /api/ dove il sito controlla ciò che controlla un sito vero (cookie sessione_prova, x-csrftoken uguale al cookie csrftoken, x-app-id e le altre intestazioni e i campi del modello), documentate dai campioni ripuliti di tests/Febe.Tests/campioni/prova. Le pagine continuano a chiedere /dati/, che non controlla nulla. ProvaProfiloQuery è una richiesta GraphQL (POST /api/graphql con doc_id, nome dell'operazione e variabili) che risponde con il JSON di /dati/profilo/{nome}. Le regole di rifiuto sono le stesse di Instagram (nel codice). La scrittura /dati/ricerche-recenti (POST) non c'è e non può esserci: un indirizzo semplice si legge solo con GET.",
|
||||
"operations": [
|
||||
{
|
||||
"name": "inizio",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/inizio",
|
||||
"path": "/api/dati/inizio",
|
||||
"category": "home",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti"
|
||||
@@ -22,7 +24,7 @@
|
||||
"name": "inizio-altri",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/inizio/altri",
|
||||
"path": "/api/dati/inizio/altri",
|
||||
"category": "home",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
@@ -31,14 +33,16 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "profilo",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}",
|
||||
"path": "/api/dati/profilo/{username}",
|
||||
"category": "profilo",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
@@ -46,7 +50,9 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"profilo"
|
||||
@@ -54,11 +60,49 @@
|
||||
"sample": "000002-profilo-pubblico",
|
||||
"note": "Anche 000004-profilo-privato-non-seguito: lo stato del profilo, senza contenuti."
|
||||
},
|
||||
{
|
||||
"name": "ProvaProfiloQuery",
|
||||
"kind": "graphql",
|
||||
"method": "POST",
|
||||
"path": "/api/graphql",
|
||||
"category": "profilo",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:*/*",
|
||||
"content-length": "computed",
|
||||
"content-type": "constant:application/x-www-form-urlencoded",
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken",
|
||||
"x-fb-friendly-name": "operation",
|
||||
"x-ig-www-claim": "session:claim"
|
||||
},
|
||||
"body": {
|
||||
"av": "session:account_id",
|
||||
"__a": "constant:1",
|
||||
"fb_dtsg": "session:fb_dtsg",
|
||||
"lsd": "session:lsd",
|
||||
"fb_api_req_friendly_name": "operation",
|
||||
"variables": "variables",
|
||||
"doc_id": "session:doc_id"
|
||||
},
|
||||
"variables": {
|
||||
"username": "{username}",
|
||||
"scheda": "post",
|
||||
"primi": 12,
|
||||
"raccolte": true
|
||||
},
|
||||
"rootFields": [
|
||||
"profilo"
|
||||
],
|
||||
"sample": "000002-profilo-pubblico",
|
||||
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso)."
|
||||
},
|
||||
{
|
||||
"name": "profilo-altri",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}/altri",
|
||||
"path": "/api/dati/profilo/{username}/altri",
|
||||
"category": "storico",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
@@ -67,7 +111,9 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti",
|
||||
@@ -80,7 +126,7 @@
|
||||
"name": "taggati",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}",
|
||||
"path": "/api/dati/profilo/{username}",
|
||||
"category": "storico",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
@@ -88,7 +134,9 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuti"
|
||||
@@ -99,7 +147,7 @@
|
||||
"name": "reel",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/profilo/{username}",
|
||||
"path": "/api/dati/profilo/{username}",
|
||||
"category": "storico",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
@@ -108,19 +156,23 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "post",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/post/{code}",
|
||||
"path": "/api/dati/post/{code}",
|
||||
"category": "post",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"contenuto"
|
||||
@@ -131,12 +183,14 @@
|
||||
"name": "storie",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/storie/{username}",
|
||||
"path": "/api/dati/storie/{username}",
|
||||
"category": "storia",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"storie"
|
||||
@@ -147,12 +201,14 @@
|
||||
"name": "evidenza",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/evidenza/{highlight_id}",
|
||||
"path": "/api/dati/evidenza/{highlight_id}",
|
||||
"category": "storia",
|
||||
"configured": true,
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"raccolta"
|
||||
@@ -163,7 +219,7 @@
|
||||
"name": "seguiti",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/seguiti",
|
||||
"path": "/api/dati/seguiti",
|
||||
"category": "seguiti",
|
||||
"configured": true,
|
||||
"parameters": {
|
||||
@@ -171,7 +227,9 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
},
|
||||
"rootFields": [
|
||||
"seguiti"
|
||||
@@ -183,7 +241,7 @@
|
||||
"name": "cerca",
|
||||
"kind": "rest",
|
||||
"method": "GET",
|
||||
"path": "/dati/cerca",
|
||||
"path": "/api/dati/cerca",
|
||||
"category": "ricerca",
|
||||
"configured": false,
|
||||
"reason": "manca il campione ripulito della risposta in tests/Febe.Tests/campioni/prova",
|
||||
@@ -192,7 +250,9 @@
|
||||
},
|
||||
"headers": {
|
||||
"accept": "constant:application/json",
|
||||
"user-agent": "session:user_agent"
|
||||
"user-agent": "session:user_agent",
|
||||
"x-app-id": "session:app_id",
|
||||
"x-csrftoken": "cookie:csrftoken"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -152,7 +152,7 @@ public sealed class DesktopPlatform : IFebePlatform
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
services.AddSingleton(_shell.Native);
|
||||
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow(() => app.Browser));
|
||||
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow());
|
||||
services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
|
||||
}
|
||||
|
||||
@@ -200,29 +200,14 @@ public sealed class DesktopPlatform : IFebePlatform
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Apri il browser» on Windows (spec §10.3): brings the window «Browser di Febe» to the front. While it is in front
|
||||
/// Alberto is driving and the engine is still; closing the window ends it.
|
||||
/// The browser of Windows is the window «Browser di Febe» (spec §10.3): «Apri il browser» brings it to the front through
|
||||
/// the connection (<c>IConnectionService.ShowBrowserAsync</c>, which opens the start page when it was at rest). While
|
||||
/// it is on screen Alberto is driving and the engine is still; closing the window ends it, leaving a page of Febe does
|
||||
/// not (issue #52).
|
||||
/// </summary>
|
||||
public sealed class DesktopBrowserWindow(Func<IFebeBrowser?> browser) : IBrowserWindow
|
||||
public sealed class DesktopBrowserWindow : IBrowserWindow
|
||||
{
|
||||
public bool IsSeparateWindow => true;
|
||||
|
||||
public async Task ShowAsync(CancellationToken ct)
|
||||
{
|
||||
if (browser() is not { } current)
|
||||
{
|
||||
throw new BadRequestException("Il browser di Febe non è in funzione in questo momento.");
|
||||
}
|
||||
|
||||
if (!current.IsAvailable)
|
||||
{
|
||||
throw new BadRequestException(current.LastError is { } error
|
||||
? "Il browser di Febe non è in funzione: " + error
|
||||
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
|
||||
}
|
||||
|
||||
await current.ShowToUserAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -3,21 +3,47 @@ using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Interop;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Febe.Desktop.Native;
|
||||
|
||||
namespace Febe.Desktop.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The window «Browser di Febe» (spec §4.1, §12): the page of Instagram at a fixed size, always the same, and below it a
|
||||
/// thin bar with «Indietro», «Ricarica» and the address without its query string. WebView2 draws into the upper area
|
||||
/// (as a child window, or as a DirectComposition visual for S2). When Alberto does not use it the window stays open
|
||||
/// but out of view, never hidden nor minimised: WebView2 would stop painting (S2). Closing it only puts it out of view.
|
||||
/// thin bar with «Indietro», «Ricarica», «Pagina iniziale» and the address without its query string. WebView2 draws
|
||||
/// into the upper area (as a child window, or as a DirectComposition visual for S2). When Alberto does not use it the
|
||||
/// window stays open but out of view, never hidden: WebView2 would stop painting (S2). Closing it only puts it out of
|
||||
/// view.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Issue #52. On screen it has a button in the taskbar, so that minimising it does not make it vanish; minimised it
|
||||
/// keeps Alberto at the wheel, but never for long (S2): after <see cref="MinimizedLimit"/> it is put out of view as if
|
||||
/// he had closed it, restored there without coming on screen. When the page and its bar do not fit in the work area of
|
||||
/// the screen (a small screen, a large text scale) the window shrinks to fit and the page is shown zoomed out
|
||||
/// (<see cref="Fit"/>), always with the same size in CSS pixels; out of view the page is at 100% again, so that the
|
||||
/// engine's pages always see the same browser. While the page is the empty rest page the bar says so.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// WPF changes the taskbar button of a shown window by hiding it and showing it again (seen in WM_WINDOWPOSCHANGED:
|
||||
/// SWP_HIDEWINDOW, then SWP_SHOWWINDOW). The button is therefore changed only while the window is out of view: before it
|
||||
/// comes on screen, after it left.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class BrowserWindow : Window
|
||||
{
|
||||
/// <summary>Height of the bar under the page, in device-independent pixels.</summary>
|
||||
public const double BarHeight = 40;
|
||||
|
||||
/// <summary>The smallest zoom the page is shown at when the screen is small.</summary>
|
||||
public const double SmallestFit = 0.4;
|
||||
|
||||
/// <summary>What the bar says while the page is the empty rest page.</summary>
|
||||
public const string RestNotice = "Il browser è a riposo su una pagina vuota: premi «Pagina iniziale».";
|
||||
|
||||
private readonly TextBlock _address;
|
||||
private readonly Border _page;
|
||||
private readonly DispatcherTimer _minimized;
|
||||
private bool _allowClose;
|
||||
|
||||
public BrowserWindow(int pageWidth, int pageHeight, ImageSource? icon)
|
||||
@@ -31,8 +57,9 @@ internal sealed class BrowserWindow : Window
|
||||
WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
ShowActivated = false;
|
||||
|
||||
// No taskbar button: out of view the window must not be reachable by accident (a click on a button that shows
|
||||
// Out of view no taskbar button: the window must not be reachable by accident (a click on a button that shows
|
||||
// nothing). It comes to the front from the interface: «Apri il browser», «Portalo in primo piano», the login.
|
||||
// On screen it has one (MoveOnScreen), so a minimised window can be brought back.
|
||||
ShowInTaskbar = false;
|
||||
Background = new SolidColorBrush(Color.FromRgb(0xF4, 0xF5, 0xF7));
|
||||
|
||||
@@ -40,6 +67,8 @@ internal sealed class BrowserWindow : Window
|
||||
back.Click += (_, _) => BackRequested?.Invoke(this, EventArgs.Empty);
|
||||
var reload = BarButton("Ricarica", "Ricarica la pagina");
|
||||
reload.Click += (_, _) => ReloadRequested?.Invoke(this, EventArgs.Empty);
|
||||
var home = BarButton("Pagina iniziale", "Apre la pagina iniziale del sito, o la pagina di accesso se non sei collegato");
|
||||
home.Click += (_, _) => HomeRequested?.Invoke(this, EventArgs.Empty);
|
||||
_address = new TextBlock
|
||||
{
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
@@ -57,24 +86,30 @@ internal sealed class BrowserWindow : Window
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(0x5B, 0x63, 0x6E)),
|
||||
FontFamily = new FontFamily("Segoe UI"),
|
||||
FontSize = 12,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||||
};
|
||||
|
||||
var bar = new DockPanel { Height = BarHeight, LastChildFill = true, Background = new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)) };
|
||||
DockPanel.SetDock(back, Dock.Left);
|
||||
DockPanel.SetDock(reload, Dock.Left);
|
||||
DockPanel.SetDock(home, Dock.Left);
|
||||
DockPanel.SetDock(hint, Dock.Right);
|
||||
bar.Children.Add(back);
|
||||
bar.Children.Add(reload);
|
||||
bar.Children.Add(home);
|
||||
bar.Children.Add(hint);
|
||||
bar.Children.Add(_address);
|
||||
|
||||
// The page area: WebView2 covers it (its bounds are computed from PageWidth/PageHeight and the DPI).
|
||||
var page = new Border { Width = pageWidth, Height = pageHeight, Background = Brushes.White };
|
||||
// The page area: WebView2 covers it (its bounds are computed from PageWidth/PageHeight, the fit and the DPI).
|
||||
_page = new Border { Width = pageWidth, Height = pageHeight, Background = Brushes.White };
|
||||
var layout = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(bar, Dock.Bottom);
|
||||
layout.Children.Add(bar);
|
||||
layout.Children.Add(page);
|
||||
layout.Children.Add(_page);
|
||||
Content = layout;
|
||||
|
||||
_minimized = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher);
|
||||
_minimized.Tick += (_, _) => MinimizedTooLong();
|
||||
}
|
||||
|
||||
/// <summary>Width of the page in device-independent pixels (CSS pixels of the page at zoom 100%).</summary>
|
||||
@@ -82,15 +117,30 @@ internal sealed class BrowserWindow : Window
|
||||
|
||||
public int PageHeight { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The zoom the page is shown at: 1, or less when the page and its bar do not fit in the work area of the screen.
|
||||
/// The page keeps its size in CSS pixels whatever the fit (the host zooms WebView2 out by the same factor).
|
||||
/// </summary>
|
||||
public double Fit { get; private set; } = 1;
|
||||
|
||||
/// <summary>How long the window may stay minimised before it is put out of view as «ho finito» (S2).</summary>
|
||||
public TimeSpan MinimizedLimit { get; set; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
/// <summary>Raised by «Indietro».</summary>
|
||||
public event EventHandler? BackRequested;
|
||||
|
||||
/// <summary>Raised by «Ricarica».</summary>
|
||||
public event EventHandler? ReloadRequested;
|
||||
|
||||
/// <summary>Raised when Alberto closes or minimises the window: the owner puts it out of view.</summary>
|
||||
/// <summary>Raised by «Pagina iniziale».</summary>
|
||||
public event EventHandler? HomeRequested;
|
||||
|
||||
/// <summary>Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view.</summary>
|
||||
public event EventHandler? DoneRequested;
|
||||
|
||||
/// <summary>Raised when the page area changed size (a new fit): the owner sizes WebView2 again.</summary>
|
||||
public event EventHandler? PageAreaChanged;
|
||||
|
||||
/// <summary>The window handle (created on first use).</summary>
|
||||
public IntPtr Handle => new WindowInteropHelper(this).EnsureHandle();
|
||||
|
||||
@@ -98,40 +148,102 @@ internal sealed class BrowserWindow : Window
|
||||
public double Scale => VisualTreeHelper.GetDpi(this).DpiScaleX;
|
||||
|
||||
/// <summary>Where WebView2 draws, in physical pixels of the client area.</summary>
|
||||
public System.Drawing.Rectangle PageBounds => new(0, 0, (int)Math.Round(PageWidth * Scale), (int)Math.Round(PageHeight * Scale));
|
||||
public System.Drawing.Rectangle PageBounds => new(0, 0, (int)Math.Round(PageWidth * Fit * Scale), (int)Math.Round(PageHeight * Fit * Scale));
|
||||
|
||||
/// <summary>True while the window is on a screen, false while it is parked out of view.</summary>
|
||||
public bool IsOnScreen =>
|
||||
Left < SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth
|
||||
&& Left + ActualWidth > SystemParameters.VirtualScreenLeft;
|
||||
|
||||
/// <summary>Shows the address of the page, without query string or fragment (they may carry tokens).</summary>
|
||||
public void ShowAddress(string? address) => _address.Text = address ?? string.Empty;
|
||||
/// <summary>The text the bar shows now (the address, or <see cref="RestNotice"/>).</summary>
|
||||
public string AddressText => _address.Text;
|
||||
|
||||
/// <summary>Centres the window on the work area of the primary screen.</summary>
|
||||
/// <summary>
|
||||
/// The zoom at which a page of <paramref name="pageWidth"/>×<paramref name="pageHeight"/> plus its bar and the
|
||||
/// window's frame fits in an area of <paramref name="areaWidth"/>×<paramref name="areaHeight"/> (all in
|
||||
/// device-independent pixels): 1 when it fits, never below <see cref="SmallestFit"/>.
|
||||
/// </summary>
|
||||
public static double FitFor(double areaWidth, double areaHeight, double pageWidth, double pageHeight, double frameWidth, double frameHeight)
|
||||
{
|
||||
if (pageWidth <= 0 || pageHeight <= 0)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
var byWidth = (areaWidth - frameWidth) / pageWidth;
|
||||
var byHeight = (areaHeight - frameHeight - BarHeight) / pageHeight;
|
||||
var fit = Math.Min(1, Math.Min(byWidth, byHeight));
|
||||
return Math.Max(SmallestFit, Math.Floor(fit * 100) / 100);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the address of the page, without query string or fragment (they may carry tokens); on the empty rest page,
|
||||
/// <see cref="RestNotice"/>.
|
||||
/// </summary>
|
||||
public void ShowAddress(string? address) =>
|
||||
_address.Text = address is null or "" or "about:blank" ? RestNotice : address;
|
||||
|
||||
/// <summary>
|
||||
/// Centres the window on the work area of the primary screen, shrunk to fit it when needed, with its taskbar button.
|
||||
/// </summary>
|
||||
public void MoveOnScreen()
|
||||
{
|
||||
var area = SystemParameters.WorkArea;
|
||||
var width = ActualWidth > 0 ? ActualWidth : PageWidth;
|
||||
var height = ActualHeight > 0 ? ActualHeight : PageHeight + BarHeight;
|
||||
FitTo(area);
|
||||
|
||||
// Still out of view: the hide and show with which WPF adds the button happen where nobody sees them.
|
||||
ShowInTaskbar = true;
|
||||
var width = ActualWidth > 0 ? ActualWidth : PageWidth * Fit;
|
||||
var height = ActualHeight > 0 ? ActualHeight : (PageHeight * Fit) + BarHeight;
|
||||
Left = area.Left + Math.Max(0, (area.Width - width) / 2);
|
||||
Top = area.Top + Math.Max(0, (area.Height - height) / 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view
|
||||
/// (S2). Never <c>Hide()</c> and never minimised.
|
||||
/// (S2), without its taskbar button and with the page at 100% (<see cref="Fit"/> 1). Never <c>Hide()</c>, never
|
||||
/// left minimised: a minimised window is restored without taking the focus and cloaked meanwhile, because Windows
|
||||
/// restores it where it was on screen (a restore position off every screen is moved back onto one).
|
||||
/// </summary>
|
||||
public void MoveOffScreen()
|
||||
{
|
||||
Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64;
|
||||
Top = SystemParameters.VirtualScreenTop;
|
||||
_minimized.Stop();
|
||||
var restoring = WindowState == WindowState.Minimized;
|
||||
var cloaked = restoring && Cloak(true);
|
||||
try
|
||||
{
|
||||
if (restoring)
|
||||
{
|
||||
Win32.ShowWindow(Handle, Win32.SwShowNoActivate);
|
||||
if (WindowState == WindowState.Minimized)
|
||||
{
|
||||
WindowState = WindowState.Normal;
|
||||
}
|
||||
}
|
||||
|
||||
Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64;
|
||||
Top = SystemParameters.VirtualScreenTop;
|
||||
|
||||
// Out of view first: the hide and show with which WPF removes the button happen where nobody sees them.
|
||||
ShowInTaskbar = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (cloaked)
|
||||
{
|
||||
Cloak(false);
|
||||
}
|
||||
}
|
||||
|
||||
// The engine's pages see the browser as it is, at 100%, whatever the size of Alberto's screen (rule 4).
|
||||
SetFit(1);
|
||||
}
|
||||
|
||||
/// <summary>Lets the window really close (Febe is stopping).</summary>
|
||||
public void CloseForGood()
|
||||
{
|
||||
_allowClose = true;
|
||||
_minimized.Stop();
|
||||
Close();
|
||||
}
|
||||
|
||||
@@ -151,14 +263,59 @@ internal sealed class BrowserWindow : Window
|
||||
{
|
||||
if (WindowState == WindowState.Minimized)
|
||||
{
|
||||
// A minimised window stops painting (S2): back to normal, out of view.
|
||||
WindowState = WindowState.Normal;
|
||||
DoneRequested?.Invoke(this, EventArgs.Empty);
|
||||
// Minimised Alberto still has it (its taskbar button brings it back), but WebView2 stops painting (S2):
|
||||
// left there too long it counts as closed.
|
||||
_minimized.Interval = MinimizedLimit;
|
||||
_minimized.Stop();
|
||||
_minimized.Start();
|
||||
}
|
||||
else
|
||||
{
|
||||
_minimized.Stop();
|
||||
}
|
||||
|
||||
base.OnStateChanged(e);
|
||||
}
|
||||
|
||||
private void MinimizedTooLong()
|
||||
{
|
||||
_minimized.Stop();
|
||||
if (WindowState == WindowState.Minimized)
|
||||
{
|
||||
// Restored out of view by the owner (MoveOffScreen), never first on screen where it was.
|
||||
DoneRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
private void FitTo(Rect area)
|
||||
{
|
||||
// The frame of the window (title bar and borders) around the page and its bar.
|
||||
var frame = SystemParameters.WindowNonClientFrameThickness;
|
||||
var resize = SystemParameters.WindowResizeBorderThickness;
|
||||
SetFit(FitFor(area.Width, area.Height, PageWidth, PageHeight, frame.Left + frame.Right + resize.Left + resize.Right, frame.Top + frame.Bottom + resize.Top + resize.Bottom));
|
||||
}
|
||||
|
||||
private void SetFit(double fit)
|
||||
{
|
||||
if (Math.Abs(fit - Fit) < 0.001)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Fit = fit;
|
||||
_page.Width = PageWidth * fit;
|
||||
_page.Height = PageHeight * fit;
|
||||
UpdateLayout();
|
||||
PageAreaChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>Cloaks or uncloaks the window (DWM); false when DWM refused.</summary>
|
||||
private bool Cloak(bool on)
|
||||
{
|
||||
var value = on ? 1 : 0;
|
||||
return Win32.DwmSetWindowAttribute(Handle, Win32.DwmCloak, ref value, sizeof(int)) == 0;
|
||||
}
|
||||
|
||||
private static Button BarButton(string text, string tip) => new()
|
||||
{
|
||||
Content = text,
|
||||
|
||||
@@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser
|
||||
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
|
||||
Host = new WebView2Host(
|
||||
ui,
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
|
||||
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage),
|
||||
context.Log);
|
||||
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ using Febe.Browser.Hosting;
|
||||
using Febe.Browser.WebView2;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Desktop.Native;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Desktop.Browser;
|
||||
@@ -18,7 +19,27 @@ namespace Febe.Desktop.Browser;
|
||||
/// <param name="AdditionalBrowserArguments">The switches of S2 (<see cref="BrowserArguments.ForWebView2"/>).</param>
|
||||
/// <param name="Icon">The icon of the window.</param>
|
||||
/// <param name="MarkUsed">Called when Alberto uses the browser and when he is done with it («Riprendi»).</param>
|
||||
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed);
|
||||
/// <param name="OpenStartPage">
|
||||
/// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise,
|
||||
/// once the engine's session ended and with the page's turn. Null: the button does nothing.
|
||||
/// </param>
|
||||
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
|
||||
|
||||
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
|
||||
internal enum ProcessFailureResponse
|
||||
{
|
||||
/// <summary>Nothing: WebView2 recovers by itself (an unresponsive page while Alberto looks at it, a helper process).</summary>
|
||||
None,
|
||||
|
||||
/// <summary>The whole browser is gone: the owner starts it again.</summary>
|
||||
Restart,
|
||||
|
||||
/// <summary>The page crashed (or hangs while nobody looks): back to the rest page (spec §6.1).</summary>
|
||||
Rest,
|
||||
|
||||
/// <summary>The GPU process restarted: the page is resized by a pixel and back, or the window may stay blank or black.</summary>
|
||||
Redraw,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The browser host of the Windows edition (spec §5, §6.1, §12): WebView2 in the window «Browser di Febe», with its own
|
||||
@@ -36,6 +57,9 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
|
||||
/// «Ho finito»; using and closing it marks the browser as used for «Riprendi».</item>
|
||||
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
|
||||
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
|
||||
/// <item>Issue #52: the bounds (and the zoom of a window shrunk to fit the screen) are given again, and WebView2 told of
|
||||
/// the window's new place, whenever the window moves on or off screen and after the GPU process restarted; a page that
|
||||
/// hangs while Alberto looks at it is left to recover instead of being replaced by the rest page.</item>
|
||||
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, its settings and DevTools
|
||||
/// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other
|
||||
/// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread
|
||||
@@ -71,6 +95,7 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
private CoreWebView2DevTools? _devTools;
|
||||
private TaskCompletionSource? _exited;
|
||||
private IDisposable? _lease;
|
||||
private CancellationTokenSource? _leaseEnded;
|
||||
private int _generation;
|
||||
private bool _starting;
|
||||
private bool _crashedWhileStarting;
|
||||
@@ -147,12 +172,22 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
}
|
||||
|
||||
window.MoveOnScreen();
|
||||
if (window.WindowState == System.Windows.WindowState.Minimized)
|
||||
{
|
||||
window.WindowState = System.Windows.WindowState.Normal;
|
||||
}
|
||||
|
||||
window.Activate();
|
||||
window.Topmost = true;
|
||||
window.Topmost = false;
|
||||
|
||||
// The lease first: once the window is on screen the engine must be still, whatever happens to the focus.
|
||||
TakeLease();
|
||||
|
||||
// On screen, perhaps shrunk to fit it: WebView2 gets its bounds again and learns where its window is now, and paints
|
||||
// again (WPF hid and showed the window, out of view, to give it its taskbar button).
|
||||
UpdateBounds();
|
||||
Repaint();
|
||||
try
|
||||
{
|
||||
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
@@ -169,9 +204,24 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
{
|
||||
_window?.MoveOffScreen();
|
||||
ReleaseLease();
|
||||
NotifyPositionChanged();
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// What a failed process of WebView2 asks of the host (issue #52). A page that does not answer while Alberto is at
|
||||
/// the window is his to wait for (WebView2 recovers, or he reloads): replacing it with the rest page would turn it
|
||||
/// white under his eyes. Nobody looking, it goes to rest as a crashed page does.
|
||||
/// </summary>
|
||||
internal static ProcessFailureResponse ResponseTo(CoreWebView2ProcessFailedKind kind, bool userIsDriving) => kind switch
|
||||
{
|
||||
CoreWebView2ProcessFailedKind.BrowserProcessExited => ProcessFailureResponse.Restart,
|
||||
CoreWebView2ProcessFailedKind.RenderProcessExited => ProcessFailureResponse.Rest,
|
||||
CoreWebView2ProcessFailedKind.RenderProcessUnresponsive => userIsDriving ? ProcessFailureResponse.None : ProcessFailureResponse.Rest,
|
||||
CoreWebView2ProcessFailedKind.GpuProcessExited => ProcessFailureResponse.Redraw,
|
||||
_ => ProcessFailureResponse.None,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
|
||||
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
|
||||
@@ -302,7 +352,14 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
window.DoneRequested += (_, _) => Done();
|
||||
window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack);
|
||||
window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true);
|
||||
window.HomeRequested += (_, _) => OpenStartPage();
|
||||
window.DpiChanged += (_, _) => UpdateBounds();
|
||||
window.PageAreaChanged += (_, _) => UpdateBounds();
|
||||
|
||||
// The raw controller does not follow its parent by itself: popups (lists of a <select>, menus, suggestions)
|
||||
// would open where the window was, out of view.
|
||||
window.LocationChanged += (_, _) => NotifyPositionChanged();
|
||||
window.ShowAddress(null);
|
||||
_window = window;
|
||||
}
|
||||
|
||||
@@ -336,6 +393,7 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
|
||||
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
|
||||
controller.Bounds = _window.PageBounds;
|
||||
controller.ZoomFactor = _window.Fit;
|
||||
|
||||
// WebView2 stops painting when IsVisible is false (S2): it stays true for the whole life of the browser.
|
||||
controller.IsVisible = true;
|
||||
@@ -436,24 +494,39 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
|
||||
switch (ResponseTo(kind, UserIsDriving))
|
||||
{
|
||||
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
|
||||
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
|
||||
_session.Detach();
|
||||
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
|
||||
}
|
||||
else if (kind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
||||
{
|
||||
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
|
||||
try
|
||||
{
|
||||
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser went with the page: its own ProcessFailed follows.
|
||||
}
|
||||
case ProcessFailureResponse.Restart:
|
||||
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
|
||||
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
|
||||
_session.Detach();
|
||||
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
|
||||
break;
|
||||
case ProcessFailureResponse.Rest:
|
||||
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
|
||||
try
|
||||
{
|
||||
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser went with the page: its own ProcessFailed follows.
|
||||
}
|
||||
|
||||
break;
|
||||
case ProcessFailureResponse.Redraw:
|
||||
// A windowed WebView can stay blank or black after the GPU process restarted until its size changes: the
|
||||
// same bounds again may be no change at all, so one pixel less and then the real ones (never
|
||||
// IsVisible = false, S2), once this handler has returned.
|
||||
_ = _ui.InvokeAsync(Redraw, DispatcherPriority.Background);
|
||||
break;
|
||||
default:
|
||||
if (kind == CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
|
||||
{
|
||||
_log.Info("browser", "WebView2: la pagina non risponde mentre usi il browser; Febe la lascia com'è (Ricarica, se non si riprende).");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,11 +554,12 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
TakeLease();
|
||||
}
|
||||
|
||||
/// <summary>Alberto closed or minimised the window: done, out of view.</summary>
|
||||
/// <summary>Alberto closed the window (or left it minimised too long): done, out of view.</summary>
|
||||
private void Done()
|
||||
{
|
||||
_window?.MoveOffScreen();
|
||||
ReleaseLease();
|
||||
NotifyPositionChanged();
|
||||
}
|
||||
|
||||
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
|
||||
@@ -510,6 +584,82 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection, which first waits for the engine's
|
||||
/// session to end and takes the page's turn (issue #52).
|
||||
/// </summary>
|
||||
private void OpenStartPage()
|
||||
{
|
||||
if (_settings.OpenStartPage is not { } open || _core is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TakeLease();
|
||||
|
||||
// The press lasts as long as this lease: closed meanwhile, the window gives the page back to the engine and the
|
||||
// connection forgets the press (rules 7 and 8).
|
||||
_ = OpenStartPageQuietlyAsync(open, _leaseEnded!.Token);
|
||||
}
|
||||
|
||||
private async Task OpenStartPageQuietlyAsync(Func<CancellationToken, Task> open, CancellationToken whileLeased)
|
||||
{
|
||||
try
|
||||
{
|
||||
await open(whileLeased).ConfigureAwait(true);
|
||||
}
|
||||
catch (OperationCanceledException) when (whileLeased.IsCancellationRequested)
|
||||
{
|
||||
// The window went out of view before the start page could open: nothing to say.
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Warn("browser", $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>After a GPU restart: a real change of size (one pixel less), then the real bounds and a repaint.</summary>
|
||||
private void Redraw()
|
||||
{
|
||||
if (_controller is not { } controller || _window is not { } window)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var bounds = window.PageBounds;
|
||||
if (bounds.Height > 1)
|
||||
{
|
||||
controller.Bounds = bounds with { Height = bounds.Height - 1 };
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone: the next start sizes the new WebView.
|
||||
return;
|
||||
}
|
||||
|
||||
_ = _ui.InvokeAsync(
|
||||
() =>
|
||||
{
|
||||
UpdateBounds();
|
||||
Repaint();
|
||||
},
|
||||
DispatcherPriority.Background);
|
||||
}
|
||||
|
||||
/// <summary>Asks the window and WebView2's child windows to paint again; nothing the page can see changes.</summary>
|
||||
private void Repaint()
|
||||
{
|
||||
if (_window is { } window)
|
||||
{
|
||||
// Only invalidated, never painted at once (RDW_UPDATENOW): the children belong to WebView2's browser process,
|
||||
// and a hung one would hold the UI thread in a synchronous paint.
|
||||
Win32.RedrawWindow(window.Handle, IntPtr.Zero, IntPtr.Zero, Win32.RdwInvalidate | Win32.RdwAllChildren);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateBounds()
|
||||
{
|
||||
if (_controller is not { } controller || _window is not { } window)
|
||||
@@ -520,6 +670,10 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
try
|
||||
{
|
||||
controller.Bounds = window.PageBounds;
|
||||
|
||||
// Shrunk to fit a small screen, the page is zoomed out by as much: its size in CSS pixels stays the same.
|
||||
controller.ZoomFactor = window.Fit;
|
||||
controller.NotifyParentWindowPositionChanged();
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
@@ -527,11 +681,24 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
}
|
||||
}
|
||||
|
||||
private void NotifyPositionChanged()
|
||||
{
|
||||
try
|
||||
{
|
||||
_controller?.NotifyParentWindowPositionChanged();
|
||||
}
|
||||
catch (Exception ex) when (ex is COMException or InvalidOperationException)
|
||||
{
|
||||
// The browser process is gone: the next start places the new WebView.
|
||||
}
|
||||
}
|
||||
|
||||
private void TakeLease()
|
||||
{
|
||||
if (_lease is null)
|
||||
{
|
||||
_lease = UserDriving.Begin();
|
||||
_leaseEnded = new CancellationTokenSource();
|
||||
_log.Info("browser", "Alberto usa il browser di Febe: il motore resta fermo.");
|
||||
}
|
||||
|
||||
@@ -545,6 +712,15 @@ internal sealed class WebView2Host : IBrowserHost
|
||||
_lease = null;
|
||||
_settings.MarkUsed();
|
||||
lease.Dispose();
|
||||
|
||||
// Off the UI thread: whatever waited on this lease (a «Pagina iniziale» in progress) gives up there. The source
|
||||
// has no timer and is never disposed, so a late look at its token is still safe.
|
||||
if (_leaseEnded is { } ended)
|
||||
{
|
||||
_leaseEnded = null;
|
||||
_ = ended.CancelAsync();
|
||||
}
|
||||
|
||||
_log.Info("browser", "Browser di Febe fuori vista.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,20 @@ internal static class Win32
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool IsIconic(IntPtr window);
|
||||
|
||||
public const uint RdwInvalidate = 0x0001;
|
||||
public const uint RdwAllChildren = 0x0080;
|
||||
|
||||
/// <summary>DWMWA_CLOAK: the window stays shown for Windows but DWM does not put it on screen.</summary>
|
||||
public const int DwmCloak = 13;
|
||||
|
||||
/// <summary>Asks a window and its children (WebView2's own) to paint again, without changing anything else.</summary>
|
||||
[DllImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool RedrawWindow(IntPtr window, IntPtr updateRect, IntPtr updateRegion, uint flags);
|
||||
|
||||
[DllImport("dwmapi.dll")]
|
||||
public static extern int DwmSetWindowAttribute(IntPtr window, int attribute, ref int value, int size);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern IntPtr SetCursor(IntPtr cursor);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Browser.Gestures;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
@@ -24,6 +25,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
||||
private readonly IClock _clock;
|
||||
private readonly IClock _browserClock;
|
||||
private readonly FebeLog _log;
|
||||
private readonly Func<CancellationToken, Task>? _openStartPage;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SemaphoreSlim _opening = new(1, 1);
|
||||
private BrowserRemoteViewConnection? _current;
|
||||
@@ -34,18 +36,29 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
||||
/// <param name="clock">The composition's clock (the time of that note).</param>
|
||||
/// <param name="log">Febe's log.</param>
|
||||
/// <param name="browserClock">
|
||||
/// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real
|
||||
/// time whatever clock the engine runs on (the tests compress it).
|
||||
/// Time for the waits on the browser itself and for the frames' watchdog; null: the wall clock, because the browser
|
||||
/// commits a navigation and paints in real time whatever clock the engine runs on (the tests compress it).
|
||||
/// </param>
|
||||
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null)
|
||||
/// <param name="openStartPage">
|
||||
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
|
||||
/// with the page's turn; null: the button does nothing.
|
||||
/// </param>
|
||||
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null)
|
||||
{
|
||||
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
|
||||
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
|
||||
_openStartPage = openStartPage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How an open view notices that frames stopped coming and starts them again (issue #52); null: never (tests whose
|
||||
/// clock moves only when asked).
|
||||
/// </summary>
|
||||
public ScreencastWatchdog? Watchdog { get; set; } = ScreencastWatchdog.Default;
|
||||
|
||||
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
|
||||
{
|
||||
if (!_browser.IsAvailable)
|
||||
@@ -83,7 +96,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
|
||||
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock);
|
||||
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _openStartPage, Watchdog);
|
||||
try
|
||||
{
|
||||
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
|
||||
@@ -167,6 +180,9 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
private readonly BrowserUseTracker _tracker;
|
||||
private readonly IClock _clock;
|
||||
private readonly RemoteViewSession _session;
|
||||
private readonly Func<CancellationToken, Task>? _openStartPage;
|
||||
private readonly ScreencastWatchdog? _watchdog;
|
||||
private readonly IBrowserLog _log;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Queue<RemoteViewMeta> _meta = new();
|
||||
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
|
||||
@@ -183,20 +199,42 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
private int _height;
|
||||
private int _disposed;
|
||||
private bool _used;
|
||||
private int _startPagePending;
|
||||
private Task _startPage = Task.CompletedTask;
|
||||
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock)
|
||||
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<CancellationToken, Task>? openStartPage, ScreencastWatchdog? watchdog)
|
||||
{
|
||||
_owner = owner;
|
||||
_browser = browser;
|
||||
_tracker = tracker;
|
||||
_clock = clock;
|
||||
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock);
|
||||
_openStartPage = openStartPage;
|
||||
_watchdog = watchdog;
|
||||
_log = log;
|
||||
|
||||
// A real log (issue #52): the starts, restarts and silences of the frames reach the registro.
|
||||
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, log, browserClock);
|
||||
}
|
||||
|
||||
public RemoteViewEnd? Ended { get; private set; }
|
||||
|
||||
private ICdpSession Cdp => _browser.Cdp;
|
||||
|
||||
/// <summary>True while a «Pagina iniziale» waits or loads: the input of the view is dropped meanwhile.</summary>
|
||||
internal bool StartPagePending => Volatile.Read(ref _startPagePending) != 0;
|
||||
|
||||
/// <summary>The last «Pagina iniziale» of this view (a completed task before the first): tests wait on it.</summary>
|
||||
internal Task StartPageOpening
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _startPage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StartAsync(int width, int height, CancellationToken ct)
|
||||
{
|
||||
_width = width;
|
||||
@@ -216,7 +254,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
|
||||
_signal.Release();
|
||||
_session.Screencast.FrameReceived += OnFrame;
|
||||
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height), ct).ConfigureAwait(false);
|
||||
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height, Watchdog: _watchdog), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
|
||||
@@ -262,9 +300,11 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
public Task MouseAsync(RemoteViewMouse input, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
if (_session.Screencast.LastFrame is null)
|
||||
if (_session.Screencast.LastFrame is null || StartPagePending)
|
||||
{
|
||||
return Task.CompletedTask; // no frame yet: nothing on screen to point at
|
||||
// No frame yet: nothing on screen to point at. «Pagina iniziale» in progress: a click would land on the page
|
||||
// about to go, or on the start page while it loads.
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
MarkUsed();
|
||||
@@ -288,6 +328,11 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
public Task KeyAsync(RemoteViewKey input, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
if (StartPagePending)
|
||||
{
|
||||
return Task.CompletedTask; // as for the mouse: not typed into a page about to change
|
||||
}
|
||||
|
||||
MarkUsed();
|
||||
if (input.Action == RemoteViewKeyAction.Char)
|
||||
{
|
||||
@@ -300,17 +345,35 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
|
||||
{
|
||||
MarkUsed();
|
||||
if (action == RemoteViewNavigation.Home)
|
||||
{
|
||||
OpenStartPage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (StartPagePending)
|
||||
{
|
||||
return; // the start page is about to replace the page anyway
|
||||
}
|
||||
|
||||
string? target;
|
||||
lock (_gate)
|
||||
{
|
||||
if (action == RemoteViewNavigation.Back)
|
||||
{
|
||||
if (_history.Count < 2)
|
||||
// Back never lands on the empty rest page (issue #52): it skips it, and with nothing before it stays.
|
||||
var previous = _history.Count - 2;
|
||||
while (previous >= 0 && IsRest(_history[previous]))
|
||||
{
|
||||
previous--;
|
||||
}
|
||||
|
||||
if (previous < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_history.RemoveAt(_history.Count - 1);
|
||||
_history.RemoveRange(previous + 1, _history.Count - previous - 1);
|
||||
target = _history[^1];
|
||||
}
|
||||
else
|
||||
@@ -328,6 +391,46 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
await _session.NavigateAsync(target, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection — like the start page opened from the
|
||||
/// rest page, it waits for the engine's session to end and takes the page's turn first, up to half a minute. So it runs
|
||||
/// beside the view, not in its receive loop (the view would freeze meanwhile), for as long as the view and its lease
|
||||
/// last; one at a time, and until it is done the view's input is dropped.
|
||||
/// </summary>
|
||||
private void OpenStartPage()
|
||||
{
|
||||
if (_openStartPage is not { } open || Interlocked.CompareExchange(ref _startPagePending, 1, 0) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var task = Task.Run(() => OpenStartPageAsync(open), CancellationToken.None);
|
||||
lock (_gate)
|
||||
{
|
||||
_startPage = task;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenStartPageAsync(Func<CancellationToken, Task> open)
|
||||
{
|
||||
try
|
||||
{
|
||||
await open(_ended.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (_ended.IsCancellationRequested)
|
||||
{
|
||||
// The view closed first: its lease is gone, the page is the engine's.
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
_log.Write(BrowserLogLevel.Warning, $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _startPagePending, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends the view from the server side (another tab, shutdown): the page is told why.</summary>
|
||||
public async Task EndAsync(RemoteViewEnd reason)
|
||||
{
|
||||
@@ -452,6 +555,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
|
||||
|
||||
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
|
||||
internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url);
|
||||
|
||||
private static bool IsRest(string url) => url is "" or CdpPageExtensions.RestUrl;
|
||||
}
|
||||
|
||||
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
|
||||
|
||||
@@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(app);
|
||||
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log);
|
||||
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
|
||||
services.AddSingleton<IRemoteViewHost>(RemoteView);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using Febe.Core.Storage;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.Web.Api;
|
||||
@@ -86,6 +87,40 @@ public static class ApiHttp
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an optional JSON body: <paramref name="empty"/> when there is none — no length and nothing to read, as an
|
||||
/// empty POST may come chunked or over HTTP/2 — and the body otherwise (a 400 when it is not readable).
|
||||
/// </summary>
|
||||
public static async Task<T> OptionalBodyAsync<T>(HttpContext context, JsonTypeInfo<T> type, T empty)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var request = context.Request;
|
||||
if (request.ContentLength == 0)
|
||||
{
|
||||
return empty;
|
||||
}
|
||||
|
||||
if (request.ContentLength is null)
|
||||
{
|
||||
if (context.Features.Get<IHttpRequestBodyDetectionFeature>() is { CanHaveBody: false })
|
||||
{
|
||||
return empty;
|
||||
}
|
||||
|
||||
// A body without a declared length may still be empty: one byte tells, then it is read from the start.
|
||||
request.EnableBuffering();
|
||||
var probe = new byte[1];
|
||||
if (await request.Body.ReadAsync(probe, context.RequestAborted).ConfigureAwait(false) == 0)
|
||||
{
|
||||
return empty;
|
||||
}
|
||||
|
||||
request.Body.Position = 0;
|
||||
}
|
||||
|
||||
return await BodyAsync(context, type).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>A JSON answer with its source-generated metadata.</summary>
|
||||
public static IResult Json<T>(T value, JsonTypeInfo<T> type, int status = StatusCodes.Status200OK) =>
|
||||
Results.Json(value, type, statusCode: status);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Native;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
@@ -21,9 +22,7 @@ public static class ConnectionApi
|
||||
|
||||
endpoints.MapPost("/api/connection/begin", async (HttpContext context, IConnectionService connection, CancellationToken ct) =>
|
||||
{
|
||||
var body = context.Request.ContentLength is null or > 0
|
||||
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
|
||||
: new BeginDrivingRequest(false);
|
||||
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false);
|
||||
await connection.BeginUserDrivingAsync(body.OpenLogin, ct).ConfigureAwait(false);
|
||||
return Results.NoContent();
|
||||
});
|
||||
@@ -36,9 +35,20 @@ public static class ConnectionApi
|
||||
return ApiHttp.Json(new FinishDto(result.Connected, result.Message), FebeJsonContext.Default.FinishDto);
|
||||
});
|
||||
|
||||
endpoints.MapPost("/api/connection/cancel", async (IConnectionService connection, CancellationToken ct) =>
|
||||
// «Annulla», or a page left without either button ({ pageLeft: true }). On Windows the browser is a window of its
|
||||
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52).
|
||||
endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) =>
|
||||
{
|
||||
await connection.CancelAsync(ct).ConfigureAwait(false);
|
||||
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false);
|
||||
if (body.PageLeft && window.IsSeparateWindow)
|
||||
{
|
||||
await connection.ReleaseAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await connection.CancelAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
|
||||
@@ -56,15 +56,17 @@ public static class EngineApi
|
||||
FebeJsonContext.Default.ResumeDto);
|
||||
});
|
||||
|
||||
// «Apri il browser» on Windows: the window of the browser comes to the front.
|
||||
endpoints.MapPost("/api/browser/show", async (IBrowserWindow browser, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
// «Apri il browser» on Windows: the window of the browser comes to the front, on the start page when it was at rest
|
||||
// and on the login page with { openLogin: true } (the red strip of a disconnection; issue #52).
|
||||
endpoints.MapPost("/api/browser/show", async (HttpContext context, IBrowserWindow browser, IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
if (!browser.IsSeparateWindow)
|
||||
{
|
||||
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
|
||||
}
|
||||
|
||||
await browser.ShowAsync(ct).ConfigureAwait(false);
|
||||
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false);
|
||||
await connection.ShowBrowserAsync(body.OpenLogin, ct).ConfigureAwait(false);
|
||||
tracker.MarkUsed(clock.Now);
|
||||
return ApiHttp.Message("Il browser di Febe è in primo piano.");
|
||||
});
|
||||
|
||||
@@ -49,6 +49,7 @@ namespace Febe.Web.Api;
|
||||
[JsonSerializable(typeof(Library.LibraryChange))]
|
||||
[JsonSerializable(typeof(ConnectionStatusDto))]
|
||||
[JsonSerializable(typeof(BeginDrivingRequest))]
|
||||
[JsonSerializable(typeof(CancelDrivingRequest))]
|
||||
[JsonSerializable(typeof(FinishDto))]
|
||||
[JsonSerializable(typeof(IncidentListDto))]
|
||||
[JsonSerializable(typeof(AlertListDto))]
|
||||
|
||||
@@ -11,6 +11,12 @@ public sealed record ConnectionStatusDto(string State, string? Username, string?
|
||||
/// <summary><c>POST /api/connection/begin</c>.</summary>
|
||||
public sealed record BeginDrivingRequest(bool OpenLogin);
|
||||
|
||||
/// <summary>
|
||||
/// «Annulla», or the page that held the browser was left (<paramref name="PageLeft"/>): on Windows the window then
|
||||
/// stays as it is (issue #52).
|
||||
/// </summary>
|
||||
public sealed record CancelDrivingRequest(bool PageLeft);
|
||||
|
||||
/// <summary><c>POST /api/connection/finish</c>.</summary>
|
||||
public sealed record FinishDto(bool Connected, string Message);
|
||||
|
||||
|
||||
@@ -55,6 +55,21 @@ public interface IConnectionService
|
||||
/// <summary>«Annulla»: ends user driving and puts the browser on the empty rest page.</summary>
|
||||
Task CancelAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// «Apri il browser» on Windows (spec §10.3, issue #52): the window comes to the front and holds the engine still
|
||||
/// while it is on screen. A browser resting on the empty page first opens the start page (the site's home when
|
||||
/// connected, the login page otherwise); with <paramref name="openLogin"/> the login page in any case (the red strip
|
||||
/// of a disconnection).
|
||||
/// </summary>
|
||||
Task ShowBrowserAsync(bool openLogin, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// The Febe page that took the browser was left (another page, a reload, the tab closed) while the browser is a
|
||||
/// window of its own (Windows, issue #52): only the page's hold ends. The window stays as it is, on screen and with
|
||||
/// its page, until Alberto closes it or presses «Ho finito».
|
||||
/// </summary>
|
||||
Task ReleaseAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>«Scollega» (after confirmation in the UI): stops the engine and deletes the browser profile.</summary>
|
||||
Task DisconnectAsync(CancellationToken ct);
|
||||
}
|
||||
@@ -8,16 +8,31 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
|
||||
| Endpoint | Corpo e risposta |
|
||||
|---|---|
|
||||
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` |
|
||||
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera |
|
||||
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) |
|
||||
| `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») |
|
||||
| `POST /api/connection/cancel` | → 204 («Annulla») |
|
||||
| `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) |
|
||||
| `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) |
|
||||
| `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale |
|
||||
|
||||
**Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la
|
||||
pagina di accesso. Aprirla, dal riposo o con il pulsante «Pagina iniziale» (barra della finestra di Windows, vista
|
||||
remota), è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non del motore: Febe aspetta che la
|
||||
sessione del motore finisca, prende il turno della pagina (un passo della ricerca dei profili finisce prima) e solo
|
||||
dopo naviga. La pressione del pulsante vale finché resta aperto chi l'ha premuta (la finestra sullo schermo, la vista
|
||||
remota): se nel frattempo Alberto l'ha chiusa, o non guida più, o il turno della pagina non arriva entro 15 s, non
|
||||
succede nulla. Nella vista remota l'attesa non ferma la vista: una pressione per volta, e finché non è finita i clic,
|
||||
i tasti, «Indietro» e «Ricarica» si scartano (finirebbero sulla pagina che sta per cambiare). Fuori da quell'attesa
|
||||
«Indietro», «Ricarica» e i clic nella pagina agiscono subito, come nel browser. La striscia rossa
|
||||
di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina Browser con `?accesso=1`).
|
||||
|
||||
In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`.
|
||||
|
||||
L'interfaccia manda `cancel` anche quando Alberto lascia la pagina Browser, o la pagina Collegamento mentre accede,
|
||||
senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch` con `keepalive`, che porta
|
||||
l'`Origin` dell'interfaccia). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
|
||||
L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina
|
||||
Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch`
|
||||
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo).
|
||||
Su Windows, dove il browser è una finestra a parte, finisce solo il permesso tenuto dalla pagina: la finestra resta
|
||||
com'è, sullo schermo e con la sua pagina, finché Alberto non la chiude (e finché è sullo schermo il motore resta
|
||||
fermo). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
|
||||
|
||||
## Vista remota (`/api/vista`, solo veste Docker)
|
||||
|
||||
@@ -30,13 +45,24 @@ Dal server al browser di Alberto:
|
||||
all'apertura e a ogni cambio di indirizzo o dimensione (l'indirizzo senza parametri di ricerca);
|
||||
- messaggi binari: un fotogramma JPEG ciascuno (da `Page.startScreencast`), da disegnare su un `<canvas>`.
|
||||
|
||||
I fotogrammi non devono fermarsi in silenzio (issue #52). Il server li riavvia (`Page.stopScreencast` e
|
||||
`Page.startScreencast`) quando una pagina nuova si è caricata (`Page.loadEventFired`) senza che ne sia arrivato
|
||||
uno, e quando non ne arrivano da circa 2 s; l'attesa raddoppia a ogni riavvio senza esito, fino a 30 s, e torna a
|
||||
2 s quando i fotogrammi scorrono di nuovo o cambia la pagina. Se entro mezzo secondo dal riavvio non arriva nessun
|
||||
fotogramma, manda un'immagine ferma della pagina (`Page.captureScreenshot`) come messaggio binario come gli altri;
|
||||
se durante la cattura arriva un fotogramma vero, l'immagine ferma non si manda. Avvii, riavvii e silenzi vanno
|
||||
nel registro (livello Info, categoria `vista`), senza indirizzi né contenuti. L'interfaccia, se dopo 8 s
|
||||
dall'apertura non ha ancora un fotogramma, mostra «Nessuna immagine dal browser» con «Riprova», che riapre la vista.
|
||||
Sul riposo (`about:blank`) la barra dice «Il browser è a riposo su una pagina vuota» invece dell'indirizzo.
|
||||
|
||||
Dal browser di Alberto al server, solo messaggi di testo JSON:
|
||||
|
||||
- `{ "type": "mouse", "action": "move"|"down"|"up"|"wheel", "x": 0..1, "y": 0..1, "button": "left"|"right"|"middle", "deltaX": n, "deltaY": n, "clickCount": n }`
|
||||
con coordinate relative al fotogramma;
|
||||
- `{ "type": "key", "action": "down"|"up"|"char", "key": "a", "code": "KeyA", "text": "a", "modifiers": n }`
|
||||
(i tasti non si registrano mai, né sul server né nel browser di Alberto);
|
||||
- `{ "type": "navigate", "action": "back"|"reload" }`.
|
||||
- `{ "type": "navigate", "action": "back"|"reload"|"home" }`: «Indietro» (salta la pagina di riposo), «Ricarica»,
|
||||
«Pagina iniziale» (la pagina iniziale descritta sopra).
|
||||
|
||||
## Problemi di configurazione
|
||||
|
||||
|
||||
@@ -114,6 +114,12 @@ public enum RemoteViewNavigation
|
||||
|
||||
/// <summary>Reload the current page.</summary>
|
||||
Reload,
|
||||
|
||||
/// <summary>
|
||||
/// «Pagina iniziale» (issue #52): the site's home when connected, the login page when not connected or after a
|
||||
/// disconnection. Alberto's own navigation while he drives (rule 7), like the other two.
|
||||
/// </summary>
|
||||
Home,
|
||||
}
|
||||
|
||||
/// <summary>The browser is not available (starting, restarting, missing, or Febe stopped by a configuration problem).</summary>
|
||||
|
||||
@@ -321,6 +321,7 @@ public static class RemoteViewSocket
|
||||
{
|
||||
"back" => RemoteViewNavigation.Back,
|
||||
"reload" => RemoteViewNavigation.Reload,
|
||||
"home" => RemoteViewNavigation.Home,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
|
||||
@@ -19,5 +19,9 @@ public sealed class UnavailableConnectionService : IConnectionService
|
||||
|
||||
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct) => throw new BadRequestException(Message);
|
||||
|
||||
public Task ReleaseAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct) => throw new BadRequestException(Message);
|
||||
}
|
||||
@@ -385,8 +385,6 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
|
||||
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
|
||||
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task ShowAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Files of the demo: the shared sample pictures. Videos have only their cover.</summary>
|
||||
|
||||
@@ -57,6 +57,10 @@ public sealed class DemoConnectionService(IHttpContextAccessor accessor, DemoWor
|
||||
|
||||
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task ReleaseAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct) =>
|
||||
throw new BadRequestException("Dimostrazione: Febe non si scollega davvero. Nella versione vera ferma il motore e cancella il profilo del browser con la sessione.");
|
||||
}
|
||||
|
||||
@@ -75,17 +75,15 @@ public sealed class BrowserShell : INativeShell
|
||||
/// </summary>
|
||||
public interface IBrowserWindow
|
||||
{
|
||||
/// <summary>True when the browser is a window of its own (Windows): «Apri il browser» calls <see cref="ShowAsync"/>.</summary>
|
||||
/// <summary>
|
||||
/// True when the browser is a window of its own (Windows): «Apri il browser» asks the connection to bring it to the
|
||||
/// front (<c>IConnectionService.ShowBrowserAsync</c>), and leaving a Febe page leaves the window as it is.
|
||||
/// </summary>
|
||||
bool IsSeparateWindow { get; }
|
||||
|
||||
/// <summary>Brings the browser window to the front (Windows). The engine stays still while Alberto uses it.</summary>
|
||||
Task ShowAsync(CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>No browser window (Docker uses the Browser page; the demo has no browser).</summary>
|
||||
public sealed class NoBrowserWindow : IBrowserWindow
|
||||
{
|
||||
public bool IsSeparateWindow => false;
|
||||
|
||||
public Task ShowAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<!-- @license lucide-static v1.56.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-house"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8" />
|
||||
<path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 459 B |
@@ -248,7 +248,9 @@ function renderBanner(frame, state) {
|
||||
}
|
||||
},
|
||||
}, icon('rotate-cw'), t('arresto.riprendi'));
|
||||
const open = h('button.btn.primo', { type: 'button', onclick: openBrowser }, icon('app-window'), t('arresto.apriBrowser'));
|
||||
// After a disconnection the browser opens on the login page (issue #52); after a verification it stays as it is.
|
||||
const disconnected = Boolean(state.connection && state.connection.state === 'disconnected');
|
||||
const open = h('button.btn.primo', { type: 'button', onclick: () => openBrowser({ login: disconnected }) }, icon('app-window'), t('arresto.apriBrowser'));
|
||||
const box = h(`div.arresto${isError ? '' : '.ambra'}`, { role: 'alert' },
|
||||
icon(isError ? 'octagon-alert' : 'triangle-alert', 'l'),
|
||||
h('div.testo', h('b', banner.title), h('span', banner.message)),
|
||||
@@ -257,18 +259,22 @@ function renderBanner(frame, state) {
|
||||
fill(frame.bannerSlot, box);
|
||||
}
|
||||
|
||||
/** «Apri il browser»: on Windows the window comes to the front; in Docker the Browser page with the remote view. */
|
||||
export async function openBrowser() {
|
||||
/**
|
||||
* «Apri il browser»: on Windows the window comes to the front; in Docker the Browser page with the remote view. A
|
||||
* browser at rest opens its start page; with login (the red strip of a disconnection) the login page.
|
||||
*/
|
||||
export async function openBrowser({ login = false } = {}) {
|
||||
const openLogin = login === true;
|
||||
if (caps().browserWindow) {
|
||||
try {
|
||||
const result = await api('/api/browser/show', { method: 'POST' });
|
||||
const result = await api('/api/browser/show', { method: 'POST', body: { openLogin } });
|
||||
toast(result.message);
|
||||
refreshEngine();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
} else {
|
||||
navigate('/browser');
|
||||
navigate(openLogin ? '/browser?accesso=1' : '/browser');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ function drawActions(page, state) {
|
||||
}, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
|
||||
page.actions(
|
||||
first,
|
||||
h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
|
||||
h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
|
||||
diagnosticsButton(),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
|
||||
// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
|
||||
// engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito»
|
||||
// (another page, a reload, closing the tab) gives the browser back, like «Annulla».
|
||||
// (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it
|
||||
// is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
|
||||
// opens the login page, once: the parameter leaves the address straight away.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
import { navigate } from '../core/shell.js';
|
||||
import { navigate, setQuery } from '../core/shell.js';
|
||||
import { t } from '../core/text.js';
|
||||
import { toast } from '../core/ui.js';
|
||||
import { drivingLease, finishDriving, passwordNote, windowPanel } from './connection.js';
|
||||
@@ -24,7 +26,10 @@ export default {
|
||||
}
|
||||
if (page.signal.aborted) return;
|
||||
const lease = drivingLease(page);
|
||||
lease.begin(false);
|
||||
const login = new URLSearchParams(location.search).get('accesso') === '1';
|
||||
lease.begin(login);
|
||||
// Asked once: a reload of the page, or the tab restored later, must not open the login page again.
|
||||
if (login) setQuery({ accesso: null });
|
||||
const message = h('div', { 'aria-live': 'polite' });
|
||||
const done = async () => {
|
||||
const result = await finishDriving();
|
||||
@@ -40,7 +45,7 @@ export default {
|
||||
h('div.destra', h('button.btn.primo.grande', { type: 'button', onclick: done }, t('impostazioni.collegamento.hoFinito')))));
|
||||
fill(page.body, h('div.pagina-browser',
|
||||
message,
|
||||
windows ? windowPanel() : remoteView(page, { url: status && status.currentUrl, login: status && status.state === 'notConnected' }).element,
|
||||
windows ? windowPanel() : remoteView(page, { url: status && status.currentUrl, login: login || (status && status.state === 'notConnected') }).element,
|
||||
passwordNote(windows)));
|
||||
},
|
||||
};
|
||||
@@ -40,15 +40,16 @@ export async function beginDriving(openLogin) {
|
||||
/**
|
||||
* The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin()
|
||||
* takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the
|
||||
* page in any other way — another page, a reload, closing the tab — counts as «Annulla»: the browser goes back to the
|
||||
* empty page and the engine may work again.
|
||||
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like «Annulla» (the
|
||||
* browser goes back to the empty page and the engine may work again); on Windows the window «Browser di Febe» stays as
|
||||
* it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
|
||||
*/
|
||||
export function drivingLease(page) {
|
||||
let held = false;
|
||||
const release = (keepalive) => {
|
||||
if (!held) return;
|
||||
held = false;
|
||||
releasing = api('/api/connection/cancel', { method: 'POST', keepalive }).then(() => {}, () => {});
|
||||
releasing = api('/api/connection/cancel', { method: 'POST', body: { pageLeft: true }, keepalive }).then(() => {}, () => {});
|
||||
};
|
||||
const onHide = () => release(true);
|
||||
window.addEventListener('pagehide', onHide);
|
||||
|
||||
@@ -11,6 +11,14 @@ import { label } from '../core/ui.js';
|
||||
const BUTTONS = ['left', 'middle', 'right'];
|
||||
const MAC = /Mac|iPhone|iPad/.test(navigator.platform || '');
|
||||
|
||||
/** How long the view waits for the first image before saying that none comes (issue #52). */
|
||||
const FIRST_FRAME_WAIT = 8000;
|
||||
|
||||
/** The empty page the browser rests on: the bar says so instead of showing an address. */
|
||||
function isRest(url) {
|
||||
return !url || url === 'about:blank';
|
||||
}
|
||||
|
||||
function altGraph(e) {
|
||||
return Boolean(e.getModifierState && e.getModifierState('AltGraph'));
|
||||
}
|
||||
@@ -44,8 +52,9 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
const address = h('span.dati');
|
||||
const back = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.indietro'), title: t('browser.indietro'), onclick: () => send({ type: 'navigate', action: 'back' }) }, icon('arrow-left'));
|
||||
const reload = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.ricarica'), title: t('browser.ricarica'), onclick: () => send({ type: 'navigate', action: 'reload' }) }, icon('rotate-cw'));
|
||||
const home = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.paginaIniziale'), title: t('browser.paginaInizialeAiuto'), onclick: () => send({ type: 'navigate', action: 'home' }) }, icon('house'));
|
||||
const bar = h('div.vista-barra',
|
||||
back, reload,
|
||||
back, reload, home,
|
||||
h('div.vista-indirizzo', { 'aria-label': t('browser.indirizzo') }, icon('lock', 's'), address),
|
||||
label(t('browser.vista')));
|
||||
const canvas = h('canvas.vista-schermo', { tabindex: '0', 'aria-label': t('browser.schermo'), hidden: true, width: '1280', height: '900' });
|
||||
@@ -56,10 +65,14 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
let socket = null;
|
||||
let closed = false;
|
||||
let frames = 0;
|
||||
// Each connection has its number: what a replaced socket still says is ignored.
|
||||
let generation = 0;
|
||||
let waiting = null;
|
||||
|
||||
function showAddress(value) {
|
||||
if (!value) {
|
||||
address.replaceChildren();
|
||||
if (isRest(value)) {
|
||||
// Never a white area without a word (issue #52): the bar says the browser is resting, «Pagina iniziale» leaves.
|
||||
fill(address, h('span.muto', t('browser.aRiposo')));
|
||||
return;
|
||||
}
|
||||
const clean = String(value).replace(/^https?:\/\//, '');
|
||||
@@ -85,16 +98,41 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
status.hidden = false;
|
||||
}
|
||||
|
||||
/** No image from the browser after a while (the view is open): said plainly, with «Riprova». */
|
||||
function noImage() {
|
||||
canvas.hidden = true;
|
||||
fill(status, h('div.vista-segnaposto',
|
||||
icon('image', 'l'),
|
||||
h('p', t('browser.nessunaImmagine')),
|
||||
h('button.btn', { type: 'button', onclick: connect }, icon('refresh-cw', 's'), t('browser.riprova'))));
|
||||
status.hidden = false;
|
||||
}
|
||||
|
||||
function send(message) {
|
||||
if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
function stopWaiting() {
|
||||
if (waiting) clearTimeout(waiting);
|
||||
waiting = null;
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (closed) return;
|
||||
if (caps().demo) {
|
||||
placeholder();
|
||||
return;
|
||||
}
|
||||
generation += 1;
|
||||
const mine = generation;
|
||||
stopWaiting();
|
||||
if (socket) {
|
||||
// «Riprova» on an open view: the old socket goes, its close says nothing.
|
||||
const old = socket;
|
||||
socket = null;
|
||||
old.close();
|
||||
}
|
||||
frames = 0;
|
||||
fill(status, h('div.vista-segnaposto', icon('hourglass', 'l'), h('p', t('browser.collegamento'))));
|
||||
status.hidden = false;
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
@@ -104,8 +142,13 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
failure();
|
||||
return;
|
||||
}
|
||||
waiting = setTimeout(() => {
|
||||
waiting = null;
|
||||
if (mine === generation && !closed && frames === 0) noImage();
|
||||
}, FIRST_FRAME_WAIT);
|
||||
socket.binaryType = 'blob';
|
||||
socket.addEventListener('message', async (e) => {
|
||||
if (mine !== generation) return;
|
||||
if (typeof e.data === 'string') {
|
||||
try {
|
||||
const meta = JSON.parse(e.data);
|
||||
@@ -127,6 +170,7 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
bitmap.close();
|
||||
frames += 1;
|
||||
if (frames === 1) {
|
||||
stopWaiting();
|
||||
canvas.hidden = false;
|
||||
status.hidden = true;
|
||||
}
|
||||
@@ -135,6 +179,8 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
}
|
||||
});
|
||||
socket.addEventListener('close', () => {
|
||||
if (mine !== generation) return;
|
||||
stopWaiting();
|
||||
socket = null;
|
||||
if (!closed) failure();
|
||||
});
|
||||
@@ -220,6 +266,7 @@ export function remoteView(page, { url = null, login = false } = {}) {
|
||||
|
||||
function close() {
|
||||
closed = true;
|
||||
stopWaiting();
|
||||
document.removeEventListener('paste', onPaste);
|
||||
window.removeEventListener('blur', releaseAll);
|
||||
if (socket) socket.close();
|
||||
|
||||
@@ -832,6 +832,10 @@
|
||||
"segnapostoAccesso": "Qui compare la vera pagina di accesso di Instagram, caricata dal sito. Febe non la ridisegna e non la imita.",
|
||||
"indietro": "Indietro",
|
||||
"ricarica": "Ricarica",
|
||||
"paginaIniziale": "Pagina iniziale",
|
||||
"paginaInizialeAiuto": "Pagina iniziale: la home del sito se sei collegato, altrimenti la pagina di accesso",
|
||||
"aRiposo": "Il browser è a riposo su una pagina vuota: premi «Pagina iniziale».",
|
||||
"nessunaImmagine": "Nessuna immagine dal browser: la vista è aperta, ma la pagina non arriva. Premi «Riprova»; se resta così, guarda il registro.",
|
||||
"indirizzo": "Indirizzo della pagina",
|
||||
"collegamento": "Collegamento alla vista remota…",
|
||||
"nonRisponde": "La vista remota non risponde: il browser di Febe non è raggiungibile in questo momento.",
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Interop;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Desktop.Browser;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Windows.Support;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Febe.Tests.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// The decisions of the window «Browser di Febe» that need no browser (Gitea issue #52): what a failed process of
|
||||
/// WebView2 asks of the host, and how much a page is shrunk to fit a small screen.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class BrowserWindowDecisionTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void AFailedProcessIsAnsweredByWhatItBroke()
|
||||
{
|
||||
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: false));
|
||||
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: true));
|
||||
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessExited, userIsDriving: true), "a crashed page is gone anyway");
|
||||
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: false));
|
||||
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: true), "never white under Alberto's eyes");
|
||||
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: false));
|
||||
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: true));
|
||||
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.UtilityProcessExited, userIsDriving: false));
|
||||
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.FrameRenderProcessExited, userIsDriving: true));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void APageThatDoesNotFitIsShrunkButNeverBelowTheSmallestFit()
|
||||
{
|
||||
// 1280×900 and its bar, in a frame of 16×39.
|
||||
Assert.AreEqual(1, BrowserWindow.FitFor(1920, 1040, 1280, 900, 16, 39), "a full HD screen: as it is");
|
||||
Assert.AreEqual(0.72, BrowserWindow.FitFor(1366, 728, 1280, 900, 16, 39), 1e-9, "a small laptop: by the height");
|
||||
Assert.AreEqual(0.78, BrowserWindow.FitFor(1024, 1200, 1280, 900, 16, 39), 1e-9, "a narrow screen: by the width");
|
||||
Assert.AreEqual(BrowserWindow.SmallestFit, BrowserWindow.FitFor(400, 300, 1280, 900, 16, 39));
|
||||
Assert.AreEqual(1, BrowserWindow.FitFor(1366, 728, 0, 0, 16, 39), "no page size: nothing to fit");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The window «Browser di Febe» on a real Windows (Gitea issue #52): on screen it has its taskbar button and says when
|
||||
/// the page is the empty rest page, «Pagina iniziale» opens the start page, the window is never hidden while on screen
|
||||
/// (WPF hides it to change its taskbar button) and out of view the page is at 100%, and a minimised window keeps Alberto
|
||||
/// at the wheel until it has been minimised too long. The window comes on screen for a moment.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class BrowserWindowTests
|
||||
{
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireWebView2() => WebView2Runtime.Require();
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task OnScreenTheWindowHasItsTaskbarButtonAndSaysWhenItRests()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
|
||||
var start = site.Url("/benvenuto");
|
||||
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale", startPage: () => start);
|
||||
await bed.StartAsync(ct);
|
||||
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view, no taskbar button");
|
||||
|
||||
// Every hide of the window (SWP_HIDEWINDOW), and those while it is on screen, where Alberto would see it go.
|
||||
var hides = 0;
|
||||
var hidesOnScreen = 0;
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
var source = (HwndSource)PresentationSource.FromVisual(window);
|
||||
source.AddHook((IntPtr _, int message, IntPtr _, IntPtr data, ref bool _) =>
|
||||
{
|
||||
const int WindowPosChanged = 0x0047;
|
||||
const int HideWindow = 0x0080;
|
||||
if (message == WindowPosChanged && (System.Runtime.InteropServices.Marshal.ReadInt32(data, (IntPtr.Size * 2) + 16) & HideWindow) != 0)
|
||||
{
|
||||
hides++;
|
||||
if (window.IsOnScreen)
|
||||
{
|
||||
hidesOnScreen++;
|
||||
}
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
});
|
||||
return true;
|
||||
});
|
||||
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar), "on screen, a taskbar button");
|
||||
Assert.AreEqual(BrowserWindow.RestNotice, await bed.OnUiAsync(() => window.AddressText), "the empty page says what it is");
|
||||
Assert.IsGreaterThan(0, await bed.OnUiAsync(() => window.Fit));
|
||||
|
||||
// «Pagina iniziale»: Alberto's own navigation, to the start page the composition gives.
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
|
||||
return true;
|
||||
});
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
|
||||
while (await bed.OnUiAsync(() => window.AddressText) != start)
|
||||
{
|
||||
Assert.IsLessThan(deadline, DateTime.UtcNow, "la pagina iniziale nella barra: " + bed.Lines.Text);
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
|
||||
Assert.AreEqual(start, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
|
||||
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view again, no taskbar button");
|
||||
Assert.AreEqual(1.0, await bed.OnUiAsync(() => window.Fit), "out of view the page is at 100%, whatever the screen");
|
||||
Assert.AreEqual(0, await bed.OnUiAsync(() => hidesOnScreen), $"never hidden on screen ({await bed.OnUiAsync(() => hides)} hides out of view)");
|
||||
TestContext.WriteLine($"Nascosta fuori vista {await bed.OnUiAsync(() => hides)} volte per il pulsante nella barra delle applicazioni.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeLastsAsLongAsTheWindowsLease()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var pressedWith = new TaskCompletionSource<CancellationToken>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
// As the connection while a session ends or a search step holds the page: it waits, here until the press is over.
|
||||
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale-chiusa", openStartPage: async token =>
|
||||
{
|
||||
pressedWith.TrySetResult(token);
|
||||
await Task.Delay(Timeout.Infinite, token);
|
||||
});
|
||||
await bed.StartAsync(ct);
|
||||
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
|
||||
return true;
|
||||
});
|
||||
var token = await pressedWith.Task.WaitAsync(TimeSpan.FromSeconds(30), ct);
|
||||
Assert.IsFalse(token.IsCancellationRequested, "the window is still on screen");
|
||||
|
||||
// Alberto closes the window before the start page opened: the press is over with the window's lease.
|
||||
await bed.OnUiAsync(() =>
|
||||
{
|
||||
window.Close();
|
||||
return true;
|
||||
});
|
||||
Assert.IsFalse(bed.Browser.UserIsDriving);
|
||||
await bed.WaitUntilAsync(() => token.IsCancellationRequested, TimeSpan.FromSeconds(10), "la fine della «Pagina iniziale» con la finestra", ct);
|
||||
Assert.IsFalse(bed.Lines.Any("non aperta"), "a press given up is no failure: " + bed.Lines.Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await BrowserBed.CreateAsync("finestra-ridotta");
|
||||
await bed.StartAsync(ct);
|
||||
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromSeconds(1));
|
||||
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving, "minimised is not «ho finito»: its taskbar button brings it back");
|
||||
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar));
|
||||
|
||||
// Left there: restored and put out of view, as if closed (S2: never minimised for long).
|
||||
await bed.WaitUntilAsync(() => !bed.Browser.UserIsDriving, TimeSpan.FromSeconds(15), "la fine della guida dopo la finestra ridotta a icona", ct);
|
||||
Assert.AreEqual(WindowState.Normal, await bed.OnUiAsync(() => window.WindowState));
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
|
||||
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar));
|
||||
|
||||
// Brought back before the limit, it stays Alberto's.
|
||||
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromMinutes(2));
|
||||
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
|
||||
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
|
||||
await bed.OnUiAsync(() => window.WindowState = WindowState.Normal);
|
||||
await Task.Delay(1500, ct);
|
||||
Assert.IsTrue(bed.Browser.UserIsDriving);
|
||||
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
|
||||
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(240_000, CooperativeCancellation = true)]
|
||||
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenWithItsPage()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopBed.StartAsync("finestra-resta", autoLogin: false, ct);
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
|
||||
var connection = bed.App.Connection!;
|
||||
var browser = bed.Browser;
|
||||
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
|
||||
|
||||
// «Usa il browser» on the rest page, not connected: the login page of the test site, never a white window.
|
||||
await connection.BeginUserDrivingAsync(openLogin: false, ct);
|
||||
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
|
||||
StringAssert.StartsWith(opened, bed.Site.Url("/benvenuto"));
|
||||
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
|
||||
|
||||
// The page of Febe goes (another page, the tab closed): the window stays, with its page and the engine still.
|
||||
await connection.ReleaseAsync(ct);
|
||||
await Task.Delay(1500, ct);
|
||||
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "still on screen");
|
||||
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine");
|
||||
Assert.AreEqual(opened, (await connection.GetStatusAsync(ct)).CurrentUrl, "its page as it was");
|
||||
Assert.IsTrue(bed.Lines.Any("Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi."), bed.Lines.Text);
|
||||
|
||||
// Closed with its X: out of view, the engine may work again.
|
||||
await bed.Ui.InvokeAsync(() =>
|
||||
{
|
||||
window.Close();
|
||||
return true;
|
||||
});
|
||||
await bed.WaitUntilAsync(() => Task.FromResult(!browser.UserIsDriving), TimeSpan.FromSeconds(10), "la fine della guida dopo la chiusura", ct);
|
||||
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
|
||||
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
|
||||
}
|
||||
|
||||
private static Button Button(DependencyObject root, string text) =>
|
||||
FindOrNull(root, text) ?? throw new AssertFailedException($"Nessun pulsante «{text}» nella finestra.");
|
||||
|
||||
private static Button? FindOrNull(DependencyObject root, string text)
|
||||
{
|
||||
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
|
||||
{
|
||||
if (child is Button { Content: string content } button && content == text)
|
||||
{
|
||||
return button;
|
||||
}
|
||||
|
||||
if (FindOrNull(child, text) is { } found)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Data;
|
||||
@@ -42,7 +43,14 @@ internal sealed class BrowserBed : IAsyncDisposable
|
||||
|
||||
public WebView2Browser Browser { get; }
|
||||
|
||||
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
|
||||
/// <param name="name">Prefix of the temporary folder.</param>
|
||||
/// <param name="hosting">How WebView2 draws (S2).</param>
|
||||
/// <param name="startPage">
|
||||
/// Where «Pagina iniziale» goes, opened as the connection would (here without an engine to wait for); null: the button
|
||||
/// does nothing (never the default login page of the options, which is Instagram's).
|
||||
/// </param>
|
||||
/// <param name="openStartPage">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
|
||||
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null, Func<CancellationToken, Task>? openStartPage = null)
|
||||
{
|
||||
var folder = new TestFolder(name);
|
||||
var ui = await UiThread.StartAsync();
|
||||
@@ -53,11 +61,14 @@ internal sealed class BrowserBed : IAsyncDisposable
|
||||
var database = await FebeDatabase.OpenAsync(data.Root);
|
||||
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
|
||||
var tracker = new BrowserUseTracker();
|
||||
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
|
||||
WebView2Browser? built = null;
|
||||
openStartPage ??= startPage is null ? null : async ct => await built!.Cdp.NavigateAsync(startPage(), ct);
|
||||
var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage);
|
||||
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
|
||||
|
||||
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
|
||||
var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null);
|
||||
built = browser;
|
||||
return new BrowserBed(folder, ui, lines, log, database, tracker, browser);
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,8 @@ public sealed class RemoteViewDuringNavigationTests
|
||||
var notes = new ConcurrentQueue<string>();
|
||||
var log = new DelegateBrowserLog((level, message, _) =>
|
||||
{
|
||||
if (level == BrowserLogLevel.Debug)
|
||||
// The retry note is written at Info since issue #52 (it reaches the registro).
|
||||
if (level is BrowserLogLevel.Debug or BrowserLogLevel.Information)
|
||||
{
|
||||
notes.Enqueue(message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
using System.Diagnostics;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The remote view that stayed white (Gitea issue #52), on a real Chromium on Xvfb and the local test site: a page that
|
||||
/// does not move still shows itself, and the frames keep coming when the page changes renderer (another site, the rest
|
||||
/// page and back). Only in the Linux CI; never Instagram. The tests ask that a picture arrives, not how fast: the waits are
|
||||
/// generous for a busy runner (issue #46), and the time it took goes to the test's output (about two seconds, the
|
||||
/// watchdog's silence, at most five on a calm machine).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public sealed class RemoteViewFramesTests
|
||||
{
|
||||
/// <summary>How long a picture may take on a busy runner before the view counts as white.</summary>
|
||||
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(20);
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireBrowser()
|
||||
{
|
||||
if (RealBrowser.UnavailableReason() is { } reason)
|
||||
{
|
||||
Assert.Inconclusive(reason);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task AStillPageAndTheRestPageShowAPicture()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var browser = await RealBrowser.StartAsync();
|
||||
var cdp = browser.Cdp;
|
||||
var opened = await cdp.NavigateAsync(browser.Site.Url("/accesso"), ct);
|
||||
Assert.IsTrue(opened.Succeeded, opened.ErrorText);
|
||||
await cdp.WaitForLoadAsync(new Febe.Core.Abstractions.SystemClock(), TimeSpan.FromSeconds(15), ct);
|
||||
|
||||
var view = new RemoteViewSession(cdp, browser.Host.UserDriving);
|
||||
try
|
||||
{
|
||||
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
|
||||
var watch = Stopwatch.StartNew();
|
||||
Assert.IsTrue(await PictureAfterAsync(view.Screencast, null, Patience, ct), "a picture of the login page");
|
||||
TestContext.WriteLine($"pagina di accesso: immagine dopo {watch.ElapsedMilliseconds} ms.");
|
||||
|
||||
var last = view.Screencast.LastFrame;
|
||||
var rest = await cdp.RestAsync(ct);
|
||||
Assert.IsTrue(rest.Succeeded, rest.ErrorText);
|
||||
watch.Restart();
|
||||
Assert.IsTrue(await PictureAfterAsync(view.Screencast, last, Patience, ct), "a picture of the rest page too");
|
||||
TestContext.WriteLine($"pagina di riposo: immagine dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task FramesKeepComingWhenThePageChangesRenderer()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var browser = await RealBrowser.StartAsync();
|
||||
var cdp = browser.Cdp;
|
||||
var first = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
|
||||
Assert.IsTrue(first.Succeeded, first.ErrorText);
|
||||
|
||||
var view = new RemoteViewSession(cdp, browser.Host.UserDriving);
|
||||
try
|
||||
{
|
||||
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
|
||||
Assert.IsTrue(await FramesAfterAsync(view.Screencast, ct), "frames of the animated page");
|
||||
|
||||
foreach (var (address, moving) in new[]
|
||||
{
|
||||
(browser.Site.LocalhostUrl("/animata"), true),
|
||||
("about:blank", false),
|
||||
(browser.Site.Url("/animata"), true),
|
||||
})
|
||||
{
|
||||
var last = view.Screencast.LastFrame;
|
||||
var watch = Stopwatch.StartNew();
|
||||
var navigated = await cdp.NavigateAsync(address, ct);
|
||||
Assert.IsTrue(navigated.Succeeded, $"{address}: {navigated.ErrorText}");
|
||||
var shown = moving
|
||||
? await FramesAfterAsync(view.Screencast, ct)
|
||||
: await PictureAfterAsync(view.Screencast, last, Patience, ct);
|
||||
TestContext.WriteLine($"{address}: {(shown ? "immagini" : "niente")} dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}.");
|
||||
Assert.IsTrue(shown, $"{address}: the view is not white");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame or a still picture other than <paramref name="last"/>, within <paramref name="timeout"/>.</summary>
|
||||
private static async Task<bool> PictureAfterAsync(ScreencastSession screencast, ScreencastFrame? last, TimeSpan timeout, CancellationToken ct)
|
||||
{
|
||||
var deadline = Stopwatch.StartNew();
|
||||
while (deadline.Elapsed < timeout)
|
||||
{
|
||||
if (screencast.LastFrame is { Jpeg: [0xFF, 0xD8, ..] } frame && !ReferenceEquals(frame, last))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>A few real frames of the screencast (not still pictures) after now, within <see cref="Patience"/>.</summary>
|
||||
private static async Task<bool> FramesAfterAsync(ScreencastSession screencast, CancellationToken ct)
|
||||
{
|
||||
var before = screencast.FramesReceived;
|
||||
var deadline = Stopwatch.StartNew();
|
||||
while (deadline.Elapsed < Patience)
|
||||
{
|
||||
if (screencast.FramesReceived >= before + 3)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
await Task.Delay(50, ct);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Diagnostics;
|
||||
using Febe.Browser.RemoteView;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The frames' watchdog of the remote view (Gitea issue #52), without a browser: a lost acknowledgement, a page that
|
||||
/// does not repaint and a new document loaded without frames must never leave the view white and silent. The clock
|
||||
/// moves only when the test says so, one look of the watchdog at a time.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ScreencastWatchdogTests
|
||||
{
|
||||
private static readonly ScreencastWatchdog Watchdog = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ALostAcknowledgementIsFollowedByARestartAndTheFramesComeBack()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(lostAcks: true);
|
||||
await bed.StartAsync(ct);
|
||||
bed.Frame();
|
||||
Assert.AreEqual(1, bed.Starts);
|
||||
|
||||
// The ack was lost: Chromium sends nothing more. Two seconds later the frames are started again.
|
||||
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
|
||||
|
||||
Assert.AreEqual(1, bed.Session.Restarts);
|
||||
Assert.AreEqual(2, bed.Starts, "a new screencast session");
|
||||
var methods = bed.Cdp.Sent.Select(c => c.Method).Where(m => m is "Page.stopScreencast" or "Page.startScreencast").ToList();
|
||||
CollectionAssert.AreEqual(new[] { "Page.startScreencast", "Page.stopScreencast", "Page.startScreencast" }, methods);
|
||||
Assert.IsTrue(bed.Info.Contains("Vista remota: nessun fotogramma da 2 s, riavvio dei fotogrammi."), bed.AllLines);
|
||||
|
||||
// Frames flow again: said once, at Info.
|
||||
for (var i = 0; i < ScreencastWatchdog.FlowingFrames; i++)
|
||||
{
|
||||
bed.Frame();
|
||||
}
|
||||
|
||||
Assert.IsTrue(bed.Info.Any(l => l.StartsWith("Vista remota: fotogrammi di nuovo in arrivo, dopo ", StringComparison.Ordinal)), bed.AllLines);
|
||||
Assert.AreEqual(1 + ScreencastWatchdog.FlowingFrames, bed.Session.FramesReceived);
|
||||
|
||||
// The stop is the last word: no start after it.
|
||||
await bed.Session.StopAsync(ct);
|
||||
Assert.AreEqual("Page.stopScreencast", bed.Cdp.Sent.Last(c => c.Method.Contains("Screencast", StringComparison.Ordinal) && c.Method != "Page.screencastFrameAck").Method);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task APageThatNeverSendsAFrameGetsAStillPictureOfItself()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(screenshot: Jpeg(800, 600));
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
// The restart after two seconds, then its wait for a first frame.
|
||||
await bed.StepAsync(TimeSpan.FromSeconds(2.25) + ScreencastWatchdog.FirstFrameWait, ct);
|
||||
|
||||
var still = bed.Session.LastFrame;
|
||||
Assert.IsNotNull(still, "something to show");
|
||||
Assert.IsTrue(still.Still);
|
||||
Assert.AreEqual(800, still.DeviceWidth, "the size written in the picture");
|
||||
Assert.AreEqual(600, still.DeviceHeight);
|
||||
Assert.AreEqual(0, bed.Session.FramesReceived, "a still picture is not a frame of the screencast");
|
||||
Assert.AreEqual(1, bed.Cdp.Sent.Count(c => c.Method == "Page.captureScreenshot"));
|
||||
|
||||
using var read = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
read.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
await foreach (var frame in bed.Session.ReadFramesAsync(read.Token))
|
||||
{
|
||||
Assert.IsTrue(frame.Still, "the reader gets it like any frame");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task AFrameSoonAfterARestartNeedsNoStillPicture()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(screenshot: Jpeg(800, 600));
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
// Restarted after two seconds: Chromium answers the start first and sends its frame a moment later.
|
||||
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
|
||||
Assert.AreEqual(1, bed.Session.Restarts);
|
||||
bed.Frame();
|
||||
await bed.StepAsync(TimeSpan.FromSeconds(1), ct);
|
||||
|
||||
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"), "the frame came: no picture taken. " + string.Join(", ", bed.Cdp.Sent.Where(c => c.Method != "Page.screencastFrameAck").Select(c => $"{c.Method}@{c.At:ss.fff}")) + " | " + bed.AllLines);
|
||||
Assert.IsNotNull(bed.Session.LastFrame);
|
||||
Assert.IsFalse(bed.Session.LastFrame.Still);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed();
|
||||
await bed.StartAsync(ct);
|
||||
bed.Frame();
|
||||
|
||||
// A frame of a page inside the page changes nothing; the main frame does.
|
||||
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F2", ["parentId"] = "F1", ["url"] = "http://127.0.0.1/pubblicita" } });
|
||||
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
|
||||
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
|
||||
|
||||
await bed.StepAsync(Watchdog.Tick, ct);
|
||||
|
||||
Assert.AreEqual(1, bed.Session.Restarts, "no two seconds of white after a new page");
|
||||
Assert.IsTrue(bed.Info.Contains("Vista remota: pagina nuova caricata senza fotogrammi, riavvio dei fotogrammi."), bed.AllLines);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task ANewDocumentWhoseFramesArriveIsLeftAlone()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed();
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
|
||||
bed.Frame();
|
||||
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
|
||||
for (var i = 0; i < 6; i++)
|
||||
{
|
||||
await bed.StepAsync(Watchdog.Tick, ct);
|
||||
bed.Frame();
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, bed.Session.Restarts);
|
||||
Assert.AreEqual(1, bed.Starts);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task AStillPageCostsFewerAndFewerRestartsAndOneLineInTheRegistro()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(screenshot: Jpeg(1280, 900));
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
// Thirty seconds of a page that does not move: restarts after 2, 4, 8 and 16 more seconds, not fifteen.
|
||||
await bed.StepAsync(TimeSpan.FromSeconds(30.25), ct);
|
||||
|
||||
Assert.AreEqual(4, bed.Session.Restarts, bed.AllLines);
|
||||
Assert.AreEqual(1, bed.Info.Count(l => l.Contains("riavvio dei fotogrammi", StringComparison.Ordinal)), "one line for the whole silence, the others at Debug");
|
||||
Assert.IsFalse(bed.AllLines.Contains("http", StringComparison.Ordinal), "no addresses in the registro");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task WithoutAWatchdogNothingIsStartedAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(noWatchdog: true);
|
||||
await bed.StartAsync(ct);
|
||||
|
||||
Assert.AreEqual(0, bed.Clock.Waiting, "nobody watches");
|
||||
bed.Clock.Advance(TimeSpan.FromMinutes(1));
|
||||
Assert.AreEqual(1, bed.Starts);
|
||||
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSizeOfAJpegIsReadFromItsFrameHeader()
|
||||
{
|
||||
Assert.AreEqual((800, 600), ScreencastSession.JpegSize(Jpeg(800, 600)));
|
||||
Assert.AreEqual((1280, 900), ScreencastSession.JpegSize(Jpeg(1280, 900, progressive: true)));
|
||||
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xD9]), "no frame header");
|
||||
Assert.IsNull(ScreencastSession.JpegSize([0x89, 0x50, 0x4E, 0x47]), "not a JPEG");
|
||||
Assert.IsNull(ScreencastSession.JpegSize([]));
|
||||
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08]), "cut short");
|
||||
}
|
||||
|
||||
/// <summary>A minimal JPEG header: SOI, an APP0 segment, then a SOF0 (or SOF2) with the size.</summary>
|
||||
private static byte[] Jpeg(int width, int height, bool progressive = false) =>
|
||||
[
|
||||
0xFF, 0xD8,
|
||||
0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
|
||||
0xFF, progressive ? (byte)0xC2 : (byte)0xC0, 0x00, 0x11, 0x08,
|
||||
(byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width,
|
||||
0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
|
||||
0xFF, 0xD9,
|
||||
];
|
||||
|
||||
/// <summary>A screencast over a fake page and a clock that moves only when stepped.</summary>
|
||||
private sealed class Bed : IAsyncDisposable
|
||||
{
|
||||
private readonly ConcurrentQueue<(BrowserLogLevel Level, string Message)> _lines = new();
|
||||
private readonly ScreencastWatchdog? _watchdog;
|
||||
private int _starts;
|
||||
private int _frameSession;
|
||||
|
||||
public Bed(bool lostAcks = false, byte[]? screenshot = null, bool noWatchdog = false)
|
||||
{
|
||||
_watchdog = noWatchdog ? null : Watchdog;
|
||||
Clock = new SteppingClock();
|
||||
Cdp = new FakeCdpSession(Clock)
|
||||
{
|
||||
Responder = (method, _) =>
|
||||
{
|
||||
switch (method)
|
||||
{
|
||||
case "Page.startScreencast":
|
||||
Interlocked.Increment(ref _starts);
|
||||
return null;
|
||||
case "Page.screencastFrameAck" when lostAcks:
|
||||
throw new CdpCommandException(method, CdpCommandException.ServerErrorCode, "Session is not attached");
|
||||
case "Page.captureScreenshot":
|
||||
return screenshot is null ? null : new JsonObject { ["data"] = Convert.ToBase64String(screenshot) };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
Session = new ScreencastSession(Cdp, new DelegateBrowserLog((level, message, _) => _lines.Enqueue((level, message))), Clock);
|
||||
}
|
||||
|
||||
public SteppingClock Clock { get; }
|
||||
|
||||
public FakeCdpSession Cdp { get; }
|
||||
|
||||
public ScreencastSession Session { get; }
|
||||
|
||||
public int Starts => Volatile.Read(ref _starts);
|
||||
|
||||
public List<string> Info => [.. _lines.Where(l => l.Level == BrowserLogLevel.Information).Select(l => l.Message)];
|
||||
|
||||
public string AllLines => string.Join('\n', _lines.Select(l => $"{l.Level} {l.Message}"));
|
||||
|
||||
public async Task StartAsync(CancellationToken ct)
|
||||
{
|
||||
await Session.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: _watchdog), ct);
|
||||
if (_watchdog is not null)
|
||||
{
|
||||
await Clock.WaitForSleeperAsync(ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame of the screencast, as Chromium sends it.</summary>
|
||||
public void Frame() => Cdp.Raise("Page.screencastFrame", new JsonObject
|
||||
{
|
||||
["sessionId"] = Interlocked.Increment(ref _frameSession),
|
||||
["data"] = Convert.ToBase64String(Jpeg(1280, 900)),
|
||||
["metadata"] = new JsonObject { ["deviceWidth"] = 1280, ["deviceHeight"] = 900, ["pageScaleFactor"] = 1 },
|
||||
});
|
||||
|
||||
/// <summary>Moves the clock by <paramref name="time"/>, one look of the watchdog at a time.</summary>
|
||||
public async Task StepAsync(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
var tick = (_watchdog ?? Watchdog).Tick;
|
||||
for (var moved = TimeSpan.Zero; moved < time; moved += tick)
|
||||
{
|
||||
Clock.Advance(tick);
|
||||
await Clock.WaitForSleeperAsync(ct);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync() => await Session.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>A clock whose delays end only when the test moves it past them.</summary>
|
||||
private sealed class SteppingClock : IClock
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _sleepers = [];
|
||||
private DateTimeOffset _now = new(2026, 11, 16, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
public DateTimeOffset Now
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
||||
|
||||
public int Waiting
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _sleepers.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (time <= TimeSpan.Zero)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
lock (_gate)
|
||||
{
|
||||
_sleepers.Add((_now + time, done));
|
||||
}
|
||||
|
||||
ct.Register(() =>
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_sleepers.RemoveAll(s => s.Done == done);
|
||||
}
|
||||
|
||||
done.TrySetCanceled(ct);
|
||||
});
|
||||
return done.Task;
|
||||
}
|
||||
|
||||
public void Advance(TimeSpan time)
|
||||
{
|
||||
List<TaskCompletionSource> due;
|
||||
lock (_gate)
|
||||
{
|
||||
_now += time;
|
||||
due = [.. _sleepers.Where(s => s.Due <= _now).Select(s => s.Done)];
|
||||
_sleepers.RemoveAll(s => s.Due <= _now);
|
||||
}
|
||||
|
||||
foreach (var done in due)
|
||||
{
|
||||
done.TrySetResult();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits (in real time) until someone sleeps on the clock again: the watchdog finished its look.</summary>
|
||||
public async Task WaitForSleeperAsync(CancellationToken ct)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
while (Waiting == 0)
|
||||
{
|
||||
await Task.Delay(1, timeout.Token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,15 +44,47 @@ public sealed class LocalTestSite : IDisposable
|
||||
|
||||
public string Url(string path) => $"http://{SiteHost}{path}";
|
||||
|
||||
/// <summary>The same site under the name «localhost»: another site for Chromium, so another renderer.</summary>
|
||||
public string LocalhostUrl(string path) => $"http://localhost:{SitePort}{path}";
|
||||
|
||||
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
|
||||
|
||||
// Ports handed out by FreePort come from 20000-29999: below the ephemeral ranges of Linux (32768-60999) and Windows
|
||||
// (49152-65535), so an outgoing connection of another test cannot take one between the probe and the moment the
|
||||
// test binds it (a port handed out by the system's port 0 could, CI run 350 of #52). Each port is handed out once
|
||||
// per process; the start depends on the process id, so two test processes on one machine rarely meet.
|
||||
private const int FirstTestPort = 20000;
|
||||
private const int TestPorts = 10000;
|
||||
private static int _nextPort = Environment.ProcessId * 7919 % TestPorts;
|
||||
|
||||
/// <summary>
|
||||
/// A port of 127.0.0.1 that is free now, never handed out before in this process and outside the system's ephemeral
|
||||
/// range. The caller binds it soon after; nothing can reserve it in between, but no other test of this process gets
|
||||
/// it and no outgoing connection is given it.
|
||||
/// </summary>
|
||||
public static int FreePort()
|
||||
{
|
||||
var probe = new TcpListener(IPAddress.Loopback, 0);
|
||||
probe.Start();
|
||||
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
||||
probe.Stop();
|
||||
return port;
|
||||
for (var attempt = 0; attempt < TestPorts; attempt++)
|
||||
{
|
||||
var port = FirstTestPort + (int)((uint)Interlocked.Increment(ref _nextPort) % TestPorts);
|
||||
var probe = new TcpListener(IPAddress.Loopback, port);
|
||||
try
|
||||
{
|
||||
probe.Start();
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
finally
|
||||
{
|
||||
probe.Stop();
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Nessuna porta libera fra 20000 e 29999.");
|
||||
}
|
||||
|
||||
private int _disposed;
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// What the HTTP site client (issue #36, S2) puts on the wire, read by a bare listener on 127.0.0.1: the headers of the
|
||||
/// catalog with the session's values and nothing else, the cookies as one line, the GraphQL form with the variables
|
||||
/// typed as the template; and where it refuses to go at all. Never Instagram: an Instagram address is only built,
|
||||
/// never asked.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class HttpSiteRequesterShapeTests
|
||||
{
|
||||
private const string UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
|
||||
|
||||
[TestMethod]
|
||||
public async Task APlainAddressCarriesTheCatalogHeadersTheSessionCookiesAndNothingElse()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{"nome":"x"}}""");
|
||||
using var requester = Requester(listener.Port);
|
||||
|
||||
// An activity of the host (ASP.NET Core starts one per request) must not add «traceparent» to what leaves.
|
||||
using var activity = new System.Diagnostics.Activity("prova").Start();
|
||||
var answer = await requester.SendAsync(SiteRequest.For("profilo", (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
var request = await listener.Request;
|
||||
|
||||
Assert.AreEqual(200, answer.Status);
|
||||
Assert.IsTrue(answer.RootFieldsPresent);
|
||||
Assert.AreEqual("GET /api/dati/profilo/marta.prova?scheda=post HTTP/1.1", request.Line);
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "host", "accept", "user-agent", "x-app-id", "x-csrftoken", "cookie", "accept-encoding" },
|
||||
request.Headers.Select(h => h.Name).ToArray(),
|
||||
"Only the catalog's headers, the cookie line, and what the HTTP stack must write.");
|
||||
Assert.AreEqual(UserAgent, request.Header("user-agent"), "Copied as it is, double space included (rule 4).");
|
||||
Assert.AreEqual("application/json", request.Header("accept"));
|
||||
Assert.AreEqual(TestSite.AppId, request.Header("x-app-id"));
|
||||
Assert.AreEqual("csrf-1", request.Header("x-csrftoken"), "The value of the cookie csrftoken.");
|
||||
Assert.AreEqual("csrftoken=csrf-1; sessione_prova=attiva; rur=\"FRC\\05412\"", request.Header("cookie"), "One line, the session's order.");
|
||||
Assert.AreEqual("gzip, deflate, br", request.Header("accept-encoding"));
|
||||
Assert.AreEqual($"127.0.0.1:{listener.Port}", request.Header("host"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AGraphQlQueryIsTheFormOfThePageWithTheVariablesTypedAsTheTemplate()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{"nome":"x"}}""");
|
||||
using var requester = Requester(listener.Port);
|
||||
|
||||
await requester.SendAsync(SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
var request = await listener.Request;
|
||||
|
||||
Assert.AreEqual("POST /api/graphql HTTP/1.1", request.Line);
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "host", "accept", "content-length", "content-type", "user-agent", "x-app-id", "x-csrftoken", "x-fb-friendly-name", "x-ig-www-claim", "cookie", "accept-encoding" },
|
||||
request.Headers.Select(h => h.Name).ToArray());
|
||||
Assert.AreEqual("application/x-www-form-urlencoded", request.Header("content-type"), "As the catalog writes it, no charset added.");
|
||||
Assert.AreEqual(TestSite.ProfileQuery, request.Header("x-fb-friendly-name"));
|
||||
Assert.AreEqual("0", request.Header("x-ig-www-claim"));
|
||||
Assert.AreEqual(
|
||||
"av=17841400000000077&__a=1&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
|
||||
+ "&variables=%7B%22username%22%3A%22marta.prova%22%2C%22scheda%22%3A%22post%22%2C%22primi%22%3A12%2C%22raccolte%22%3Atrue%7D"
|
||||
+ "&doc_id=8000000000000001",
|
||||
request.Body,
|
||||
"Fields in the order of the file; the variables as JSON.stringify writes them: 12 a number, true a boolean.");
|
||||
Assert.AreEqual(Encoding.UTF8.GetByteCount(request.Body).ToString(System.Globalization.CultureInfo.InvariantCulture), request.Header("content-length"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void VariablesAndFormFieldsAreWrittenAsThePageWritesThem()
|
||||
{
|
||||
var search = RequestCatalog.LoadInstagram().Operations.Single(o => o.Name == "PolarisSearchBoxRefetchableQuery");
|
||||
var variables = HttpSiteRequester.Variables(search, SiteRequest.For(search.Name, (CaseValues.SearchText, "caffè & «latte» <b>\"x\"")));
|
||||
StringAssert.Contains(variables, "\"query\":\"caffè & «latte» <b>\\\"x\\\"\"", "No escaping of letters or of < > & (JSON.stringify).");
|
||||
Assert.IsFalse(variables.Contains("\": ", StringComparison.Ordinal) || variables.Contains(", \"", StringComparison.Ordinal), "No spaces between tokens.");
|
||||
|
||||
Assert.AreEqual("a+b%26c%3Dd%C3%A8*-._%2B%2F", HttpSiteRequester.FormEncode("a b&c=dè*-._+/"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoRedirectIsFollowed()
|
||||
{
|
||||
using var listener = new OneShotListener(string.Empty, status: "302 Found", extraHeaders: "Location: http://127.0.0.1:1/accounts/login/?next=%2Fmarta.prova%2F\r\nSet-Cookie: sessione_prova=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/\r\n");
|
||||
var session = new InMemorySiteSession(Session());
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
|
||||
var answer = await requester.SendAsync(SiteRequest.For("profilo", (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(302, answer.Status);
|
||||
Assert.AreEqual("/accounts/login/", answer.RedirectPathShape);
|
||||
Assert.IsTrue(answer.Deletes(TestSite.SessionCookie));
|
||||
Assert.IsNull(session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.AreEqual(1, listener.Connections, "One request: the redirect was not followed (port 1 was never tried either).");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("prova", "http://example.com/")]
|
||||
[DataRow("prova", "http://10.1.2.3:8080/")]
|
||||
[DataRow("prova", "https://www.instagram.com/")]
|
||||
[DataRow("prova", "http://localhost:8481/")]
|
||||
[DataRow("prova", "http://127.0.0.1:8481/api/")]
|
||||
[DataRow("prova", "http://utente:segreto@127.0.0.1:8481/")]
|
||||
[DataRow("prova", "ftp://127.0.0.1/")]
|
||||
[DataRow("instagram", "http://www.instagram.com/")]
|
||||
[DataRow("instagram", "https://instagram.com/")]
|
||||
[DataRow("instagram", "https://www.instagram.com:8443/")]
|
||||
[DataRow("instagram", "https://www.instagram.com.example.net/")]
|
||||
[DataRow("instagram", "https://127.0.0.1/")]
|
||||
public void AnyOtherAddressIsRefusedBeforeAnyConnection(string site, string address)
|
||||
{
|
||||
var catalog = site == "instagram" ? SettledCatalog.Instagram() : RequestCatalog.LoadTestSite();
|
||||
var options = site == "instagram" ? HttpSiteRequesterOptions.Instagram() with { SiteAddress = new Uri(address) } : HttpSiteRequesterOptions.TestSite(new Uri(address));
|
||||
var refused = Assert.ThrowsExactly<ArgumentException>(() => new HttpSiteRequester(catalog, new InMemorySiteSession(Session()), options, new VirtualClock()));
|
||||
Assert.IsFalse(refused.Message.Contains("segreto", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheOnlyAddressesAreInstagramOverHttpsAndLoopbackTestSites()
|
||||
{
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(SettledCatalog.Instagram(), HttpSiteRequesterOptions.InstagramAddress));
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(RequestCatalog.LoadTestSite(), new Uri("http://127.0.0.1:8481/")));
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(RequestCatalog.LoadTestSite(), new Uri("http://127.0.0.2:8481/")));
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(RequestCatalog.LoadTestSite(), new Uri("https://[::1]:8443/")));
|
||||
|
||||
// Built, never asked: the constructor opens no connection.
|
||||
using var instagram = new HttpSiteRequester(SettledCatalog.Instagram(), new InMemorySiteSession(null), HttpSiteRequesterOptions.Instagram(), new VirtualClock());
|
||||
Assert.AreEqual("https://www.instagram.com/", instagram.Site.AbsoluteUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheHandlerFollowsNothingKeepsNoCookiesAndSpeaksHttp2OrHttp11()
|
||||
{
|
||||
using var site = HttpSiteRequester.CreateHandler(HttpSiteRequesterOptions.Instagram(), loopback: false);
|
||||
Assert.IsFalse(site.AllowAutoRedirect);
|
||||
Assert.IsFalse(site.UseCookies);
|
||||
Assert.IsTrue(site.UseProxy, "The system proxy, as WebView2.");
|
||||
Assert.IsNull(site.Proxy, "Null is HttpClient.DefaultProxy, the system's.");
|
||||
Assert.AreEqual(System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.Brotli, site.AutomaticDecompression);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(10), site.ConnectTimeout);
|
||||
Assert.IsNull(site.ActivityHeadersPropagator, "No traceparent or Request-Id added to the request.");
|
||||
|
||||
using var local = HttpSiteRequester.CreateHandler(HttpSiteRequesterOptions.TestSite(new Uri("http://127.0.0.1:1/")), loopback: true);
|
||||
Assert.IsFalse(local.UseProxy, "A loopback test site is never reached through a proxy.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARenewedCookieAndTheClaimAreKeptAndTheAnswerShowsOnlyTheirNames()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""", extraHeaders: "Set-Cookie: csrftoken=csrf-2; Max-Age=31449600; Path=/; Secure\r\nSet-Cookie: estraneo=1; Domain=altro.example; Path=/\r\nx-ig-set-www-claim: hmac.nuovo\r\nRetry-After: 30\r\n");
|
||||
var session = new InMemorySiteSession(Session());
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
|
||||
var answer = await requester.SendAsync(SiteRequest.For("profilo", (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken" }, answer.CookiesSet.ToArray(), "A cookie of another domain is not the site's.");
|
||||
Assert.IsTrue(answer.SetsClaim);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(30), answer.RetryAfter);
|
||||
Assert.AreEqual("csrf-2", session.Read()!.Cookie("csrftoken"));
|
||||
Assert.IsNull(session.Read()!.Cookie("estraneo"));
|
||||
Assert.AreEqual("hmac.nuovo", session.Read()!.Fields["claim"]);
|
||||
Assert.IsFalse(answer.ToString().Contains("csrf-2", StringComparison.Ordinal));
|
||||
Assert.IsFalse(answer.ToString().Contains("hmac", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheVariablesAreWhatJsonStringifyWrites()
|
||||
{
|
||||
var search = RequestCatalog.LoadInstagram().Operations.Single(o => o.Name == "PolarisSearchBoxRefetchableQuery");
|
||||
var variables = HttpSiteRequester.Variables(search, SiteRequest.For(search.Name, (CaseValues.SearchText, "mare \U0001F30A \\ \"blu\"")));
|
||||
StringAssert.Contains(variables, "\"query\":\"mare \U0001F30A \\\\ \\\"blu\\\"\"", "The emoji as it is, never \\uD83C\\uDF0A.");
|
||||
using (var parsed = System.Text.Json.JsonDocument.Parse(variables))
|
||||
{
|
||||
Assert.IsNotNull(parsed, "Still JSON.");
|
||||
}
|
||||
|
||||
// JSON.stringify (ECMA-262 QuoteJSONString): U+2028, U+2029 and DEL as they are; controls and a lone surrogate
|
||||
// as lower-case \u; the short escapes.
|
||||
var text = new System.Text.StringBuilder();
|
||||
HttpSiteRequester.WriteString(text, "a\u2028b\u2029c\u007F d\u0001e\u001f\b\f\n\r\t" + "\ud800" + "!");
|
||||
Assert.AreEqual("\"a\u2028b\u2029c\u007F d\\u0001e\\u001f\\b\\f\\n\\r\\t\\ud800!\"", text.ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARenewalCountsAsSoonAsTheHeadersArriveWhateverHappensToTheBody()
|
||||
{
|
||||
// The body is larger than allowed: no answer, but the site rotated the cookie and the claim with the headers.
|
||||
using (var listener = new OneShotListener(new string('x', 4096), extraHeaders: "Set-Cookie: sessione_prova=rinnovata; Path=/\r\nSet-Cookie: rur=\"CLN\\05412\"; Path=/\r\nx-ig-set-www-claim: hmac.nuovo\r\n"))
|
||||
{
|
||||
var session = new InMemorySiteSession(Session());
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")) with { MaxBodyBytes = 64 }, new VirtualClock());
|
||||
var large = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(SiteUnreachableReason.TooLarge, large.Reason);
|
||||
Assert.AreEqual("rinnovata", session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.AreEqual("\"CLN\\05412\"", session.Read()!.Cookie("rur"), "Quotes kept, as the browser keeps them.");
|
||||
Assert.AreEqual("hmac.nuovo", session.Read()!.Fields["claim"]);
|
||||
}
|
||||
|
||||
// The body never ends and the caller cancels while it is read: the deletion of the session cookie still counts.
|
||||
using (var listener = new OneShotListener("{\"pro", extraHeaders: "Set-Cookie: sessione_prova=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/\r\n", declaredLength: 1000, holdOpen: true))
|
||||
{
|
||||
var session = new InMemorySiteSession(Session());
|
||||
var log = new List<string>();
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock(), log.Add);
|
||||
using var caller = new CancellationTokenSource();
|
||||
var sending = requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), caller.Token);
|
||||
await listener.Request;
|
||||
await WaitUntilAsync(() => session.Updates == 1);
|
||||
await caller.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => sending);
|
||||
Assert.IsNull(session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.IsTrue(log.Any(l => l.Contains("ha cancellato il cookie di sessione", StringComparison.Ordinal)));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("gzip")]
|
||||
[DataRow("br")]
|
||||
[DataRow("deflate")]
|
||||
public async Task ABodyThatDoesNotDecompressIsBrokenNotTooLarge(string encoding)
|
||||
{
|
||||
using var listener = new OneShotListener(string.Empty, extraHeaders: $"Content-Encoding: {encoding}\r\n", raw: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
using var requester = Requester(listener.Port);
|
||||
var broken = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(SiteUnreachableReason.Broken, broken.Reason);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnExpiredSessionCookieIsAMissingSessionAndAnExpiredCookieIsNotSent()
|
||||
{
|
||||
var clock = new VirtualClock(new DateTimeOffset(2026, 11, 16, 10, 0, 0, TimeSpan.Zero));
|
||||
var values = Session();
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
|
||||
// «rur» expired a minute ago: not in the cookie line.
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, values.DocIds, new Dictionary<string, DateTimeOffset> { ["rur"] = clock.Now.AddMinutes(-1) }));
|
||||
using (var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), clock))
|
||||
{
|
||||
await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
Assert.AreEqual("csrftoken=csrf-1; sessione_prova=attiva", (await listener.Request).Header("cookie"));
|
||||
}
|
||||
|
||||
// The session cookie expired: nothing leaves, a Disconnessione.
|
||||
var expired = new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, values.DocIds, new Dictionary<string, DateTimeOffset> { [TestSite.SessionCookie] = clock.Now }));
|
||||
using var late = new HttpSiteRequester(RequestCatalog.LoadTestSite(), expired, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), clock);
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => late.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(TestSite.SessionCookie, refused.Missing);
|
||||
Assert.AreEqual(1, listener.Connections);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutAClaimYetTheQuerySendsThePagesZero()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
var values = Session();
|
||||
var fields = values.Fields.Where(f => f.Key != "claim").ToDictionary();
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
await requester.SendAsync(SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
Assert.AreEqual("0", (await listener.Request).Header("x-ig-www-claim"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DisposeEndsARequestInFlightAsACancellationAndRefusesLaterOnes()
|
||||
{
|
||||
using var listener = new OneShotListener("{", declaredLength: 1000, holdOpen: true);
|
||||
var requester = Requester(listener.Port);
|
||||
var sending = requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
await listener.Request;
|
||||
requester.Dispose();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => sending);
|
||||
await Assert.ThrowsExactlyAsync<ObjectDisposedException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
requester.Dispose();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnWindowsTheProxyVariablesWebView2IgnoresStopTheClient()
|
||||
{
|
||||
var none = new Dictionary<string, string?>();
|
||||
var set = new Dictionary<string, string?> { ["HTTPS_PROXY"] = "http://utente:segreto@proxy.example:3128", ["NO_PROXY"] = "localhost" };
|
||||
Assert.IsNull(HttpSiteRequester.EnvironmentProxyRefusal(windows: true, n => none.GetValueOrDefault(n)));
|
||||
Assert.IsNull(HttpSiteRequester.EnvironmentProxyRefusal(windows: false, n => set.GetValueOrDefault(n)), "In Docker Chromium reads them too.");
|
||||
var refusal = HttpSiteRequester.EnvironmentProxyRefusal(windows: true, n => set.GetValueOrDefault(n));
|
||||
Assert.IsNotNull(refusal);
|
||||
StringAssert.Contains(refusal, "HTTPS_PROXY");
|
||||
Assert.IsFalse(refusal.Contains("segreto", StringComparison.Ordinal) || refusal.Contains("proxy.example", StringComparison.Ordinal), "Never the value.");
|
||||
}
|
||||
|
||||
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
while (!condition())
|
||||
{
|
||||
await Task.Delay(10, limit.Token);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpSiteRequester Requester(int port) =>
|
||||
new(RequestCatalog.LoadTestSite(), new InMemorySiteSession(Session()), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{port}/")), new VirtualClock());
|
||||
|
||||
private static SiteSessionValues Session() => new(
|
||||
[new("csrftoken", "csrf-1"), new(TestSite.SessionCookie, SiteControl.InitialSession), new("rur", "\"FRC\\05412\"")],
|
||||
UserAgent,
|
||||
new Dictionary<string, string> { ["app_id"] = TestSite.AppId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = "17841400000000077" },
|
||||
TestSite.DocIds);
|
||||
|
||||
/// <summary>The head and body of one HTTP/1.1 request, as they arrived.</summary>
|
||||
private sealed record RawRequest(string Line, IReadOnlyList<(string Name, string Value)> Headers, string Body)
|
||||
{
|
||||
public string Header(string name) => Headers.Single(h => h.Name == name).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A bare HTTP/1.1 listener on 127.0.0.1 that reads requests as they arrive and answers each with the same
|
||||
/// response, closing the connection: what the client really wrote, with nothing in between.
|
||||
/// </summary>
|
||||
private sealed class OneShotListener : IDisposable
|
||||
{
|
||||
private readonly TcpListener _listener;
|
||||
private readonly TaskCompletionSource<RawRequest> _first = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly byte[] _response;
|
||||
private int _connections;
|
||||
|
||||
private readonly bool _holdOpen;
|
||||
|
||||
/// <param name="body">The body, as UTF-8.</param>
|
||||
/// <param name="status">Status line after the version.</param>
|
||||
/// <param name="extraHeaders">More header lines, each ending in CRLF.</param>
|
||||
/// <param name="raw">The body as bytes, in place of <paramref name="body"/>.</param>
|
||||
/// <param name="declaredLength">The Content-Length to declare, when it is not the body's (a body that never ends).</param>
|
||||
/// <param name="holdOpen">Keeps the connection open after writing, until disposed.</param>
|
||||
public OneShotListener(string body, string status = "200 OK", string extraHeaders = "", byte[]? raw = null, int? declaredLength = null, bool holdOpen = false)
|
||||
{
|
||||
Port = LocalTestSite.FreePort();
|
||||
_listener = new TcpListener(IPAddress.Loopback, Port);
|
||||
_listener.Start();
|
||||
var bytes = raw ?? Encoding.UTF8.GetBytes(body);
|
||||
_holdOpen = holdOpen;
|
||||
_response = [.. Encoding.ASCII.GetBytes($"HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {declaredLength ?? bytes.Length}\r\n{extraHeaders}Connection: close\r\n\r\n"), .. bytes];
|
||||
_ = Task.Run(LoopAsync);
|
||||
}
|
||||
|
||||
public int Port { get; }
|
||||
|
||||
public int Connections => Volatile.Read(ref _connections);
|
||||
|
||||
public Task<RawRequest> Request => _first.Task.WaitAsync(TimeSpan.FromSeconds(30));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stop.Cancel();
|
||||
_listener.Stop();
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task LoopAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
TcpClient client;
|
||||
try
|
||||
{
|
||||
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref _connections);
|
||||
using (client)
|
||||
{
|
||||
try
|
||||
{
|
||||
var stream = client.GetStream();
|
||||
var request = await ReadAsync(stream);
|
||||
_first.TrySetResult(request);
|
||||
await stream.WriteAsync(_response, _stop.Token);
|
||||
if (_holdOpen)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, _stop.Token);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or OperationCanceledException or InvalidDataException)
|
||||
{
|
||||
_first.TrySetException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<RawRequest> ReadAsync(NetworkStream stream)
|
||||
{
|
||||
var buffer = new List<byte>();
|
||||
var chunk = new byte[4096];
|
||||
int end;
|
||||
while ((end = IndexOfHeadEnd(buffer)) < 0)
|
||||
{
|
||||
var read = await stream.ReadAsync(chunk, _stop.Token);
|
||||
if (read == 0)
|
||||
{
|
||||
throw new InvalidDataException("Richiesta interrotta.");
|
||||
}
|
||||
|
||||
buffer.AddRange(chunk.AsSpan(0, read).ToArray());
|
||||
}
|
||||
|
||||
var head = Encoding.ASCII.GetString([.. buffer.Take(end)]).Split("\r\n");
|
||||
var headers = head.Skip(1).Select(l =>
|
||||
{
|
||||
var colon = l.IndexOf(':', StringComparison.Ordinal);
|
||||
return (l[..colon].Trim().ToLowerInvariant(), l[(colon + 1)..].Trim());
|
||||
}).ToList();
|
||||
var length = headers.Where(h => h.Item1 == "content-length").Select(h => int.Parse(h.Item2, System.Globalization.CultureInfo.InvariantCulture)).FirstOrDefault();
|
||||
var body = buffer.Skip(end + 4).ToList();
|
||||
while (body.Count < length)
|
||||
{
|
||||
var read = await stream.ReadAsync(chunk, _stop.Token);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
body.AddRange(chunk.AsSpan(0, read).ToArray());
|
||||
}
|
||||
|
||||
return new RawRequest(head[0], headers, Encoding.UTF8.GetString([.. body]));
|
||||
}
|
||||
|
||||
private static int IndexOfHeadEnd(List<byte> buffer)
|
||||
{
|
||||
for (var i = 0; i + 3 < buffer.Count; i++)
|
||||
{
|
||||
if (buffer[i] == '\r' && buffer[i + 1] == '\n' && buffer[i + 2] == '\r' && buffer[i + 3] == '\n')
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
using System.Collections.Concurrent;
|
||||
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.Collection.Requests;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Support;
|
||||
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP site client (issue #36, S2) against the real test site on 127.0.0.1, never Instagram: every configured
|
||||
/// operation of <c>richieste.prova.json</c> returns the data the pages read, the stop cases of §7.6 come back as answers
|
||||
/// and signals, redirects are never followed, the session keeps what the site renews, one request at a time, nothing
|
||||
/// leaves without its permit, and the log holds no value.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[TestCategory(SyntheticSite.Category)]
|
||||
public sealed class HttpSiteRequesterTests
|
||||
{
|
||||
private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
|
||||
private const string Csrf = "gettone-csrf-di-prova-7";
|
||||
private const string OtherCookie = "valore-di-un-altro-cookie";
|
||||
private const string AccountId = "17841400000000077";
|
||||
|
||||
private static readonly RequestCatalog Catalog = RequestCatalog.LoadTestSite();
|
||||
private static readonly SiteAnswerSignals Signals = new(SignalRules.LoadTestSite(), TestSite.SessionCookie);
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryConfiguredOperationReturnsTheDataThePagesRead()
|
||||
{
|
||||
// A fixed clock for the site: the signed addresses of the two answers must be the same to compare them.
|
||||
await using var site = await SyntheticSite.StartAsync(new FixedTime(DateTimeOffset.UtcNow));
|
||||
using var bed = new Bed(site);
|
||||
var cases = Cases(site);
|
||||
CollectionAssert.AreEquivalent(Catalog.Configured.Select(o => o.Name).ToArray(), cases.Keys.ToArray(), "Every configured operation has a case here.");
|
||||
|
||||
var reads = 0;
|
||||
foreach (var operation in Catalog.Configured)
|
||||
{
|
||||
var (values, pagePath) = cases[operation.Name];
|
||||
var answer = await bed.SendAsync(new SiteRequest(operation.Name, values), operation.Category);
|
||||
|
||||
Assert.AreEqual(200, answer.Status, operation.Name);
|
||||
Assert.AreEqual("application/json", answer.MimeType, operation.Name);
|
||||
Assert.IsTrue(answer.RootFieldsPresent, operation.Name);
|
||||
Assert.IsNull(Signals.Classify(operation, answer, bed.Clock.Now), operation.Name);
|
||||
|
||||
var page = await site.GetDataAsync(pagePath);
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(page), JsonNode.Parse(answer.Body.Span)), $"{operation.Name}: not the JSON of {pagePath}.");
|
||||
|
||||
// Through the delivery to the readers of lettori.prova.json, as the captured answer of the page.
|
||||
var requested = await ReadAsync(answer.Body, answer, bed.Clock);
|
||||
var captured = await ReadAsync(System.Text.Encoding.UTF8.GetBytes(page), answer, bed.Clock);
|
||||
CollectionAssert.AreEqual(captured, requested, operation.Name);
|
||||
reads += requested.Sum(r => r.Length);
|
||||
}
|
||||
|
||||
Assert.IsTrue(reads > 2000, "The readers keep something of the answers, so the comparison proves something.");
|
||||
Assert.AreEqual(Catalog.Configured.Count(), site.Control.DirectRequests.Count);
|
||||
Assert.IsTrue(site.Control.DirectRequests.All(r => r.StartsWith("GET /api/dati/", StringComparison.Ordinal) || r.StartsWith("POST /api/graphql", StringComparison.Ordinal)));
|
||||
StringAssert.StartsWith(site.Control.DirectRequests.Single(r => r.Contains("graphql", StringComparison.Ordinal)), "POST /api/graphql");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStopCasesComeBackAsAnswersAndSignalsAndRedirectsAreNeverFollowed()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
var profile = Profile();
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.TooManyRequests);
|
||||
var slow = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(429, slow.Status);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(60), slow.RetryAfter);
|
||||
var throttle = Classify(slow);
|
||||
Assert.AreEqual(SignalLevel.Throttle, throttle.Signal.Level);
|
||||
Assert.AreEqual("http-429", throttle.Signal.Code);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.RedirectToLogin);
|
||||
var login = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, login.Status);
|
||||
Assert.IsTrue(login.IsRedirect);
|
||||
Assert.AreEqual("/{testo}/", login.RedirectPathShape, "Only the shape: no host, no query string with the path asked.");
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, Classify(login).Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, Classify(login).Signal.Level);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.RedirectToChallenge);
|
||||
var challenge = await bed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, challenge.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, Classify(challenge).Signal.Code);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.HtmlInsteadOfJson);
|
||||
var html = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.IsTrue(html.IsHtml);
|
||||
Assert.IsFalse(html.RootFieldsPresent);
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(html).Signal.Code);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.MissingRootField);
|
||||
var missing = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, missing.Status);
|
||||
Assert.IsTrue(missing.IsDeclaredData);
|
||||
Assert.IsFalse(missing.RootFieldsPresent);
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(missing).Signal.Code);
|
||||
Assert.AreEqual(SiteAnswerSignals.H16, Classify(missing).Hypothesis);
|
||||
|
||||
// The whole site's stop modes reach the site client too.
|
||||
site.Control.Set(StopMode.Challenge);
|
||||
var mode = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.IsTrue(mode.IsRedirect);
|
||||
site.Control.Set(StopMode.Normal);
|
||||
|
||||
var fine = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, fine.Status);
|
||||
Assert.IsNull(Signals.Classify(Operation("profilo"), fine, bed.Clock.Now));
|
||||
|
||||
Assert.AreEqual(0, site.Control.LoginPageVisits, "A redirect is a signal, never an address to visit.");
|
||||
Assert.AreEqual(0, site.Control.ChallengePageVisits);
|
||||
Assert.HasCount(7, site.Control.DirectRequests);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSessionKeepsWhatTheSiteRenewsAndADeletedSessionCookieIsReported()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.RenewSessionCookie);
|
||||
var renewed = await bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, renewed.Status);
|
||||
CollectionAssert.AreEqual(new[] { TestSite.SessionCookie }, renewed.CookiesSet.ToArray());
|
||||
Assert.AreEqual("rinnovata-1", bed.Session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.IsFalse(site.Control.IsSession(SiteControl.InitialSession), "The old value stopped working on the site.");
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status, "The renewed cookie is the one sent now.");
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.SetClaim);
|
||||
var claimed = await bed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.IsTrue(claimed.SetsClaim);
|
||||
Assert.AreEqual("claim-prova-1", bed.Session.Read()!.Fields["claim"]);
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Graph(), ActionKind.ProfileOpen)).Status);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.DeleteSessionCookie);
|
||||
var deleted = await bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, deleted.Status, "The data came, but the session is over.");
|
||||
Assert.IsTrue(deleted.Deletes(TestSite.SessionCookie));
|
||||
var signal = Classify(deleted);
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, signal.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
|
||||
Assert.IsNull(bed.Session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.IsTrue(bed.Log.Any(l => l.Contains("ha cancellato il cookie di sessione", StringComparison.Ordinal)));
|
||||
|
||||
var sent = site.Control.DirectRequests.Count;
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => bed.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(TestSite.SessionCookie, refused.Missing);
|
||||
Assert.AreEqual(SignalLevel.Disconnect, SiteAnswerSignals.ForMissingSession(refused, bed.Clock.Now).Signal.Level);
|
||||
Assert.HasCount(sent, site.Control.DirectRequests, "Without the session cookie nothing leaves.");
|
||||
Assert.AreEqual(3, bed.Session.Updates);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnEndedSessionAMissingValueOrAWrongHeaderIsWhatARealSiteWouldAnswer()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
|
||||
// A session cookie the site does not know (expired): a plain address is sent to the login page, a query gets 401.
|
||||
using (var stale = new Bed(site, Values(session: "scaduta")))
|
||||
{
|
||||
var rest = await stale.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, rest.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, Classify(rest).Signal.Code);
|
||||
var graph = await stale.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(401, graph.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.UnauthorizedCode, Classify(graph).Signal.Code);
|
||||
Assert.AreEqual(0, site.Control.LoginPageVisits);
|
||||
}
|
||||
|
||||
// A header of the catalog with a value the site does not expect: 400 with a JSON without the fields.
|
||||
using (var wrongApp = new Bed(site, Values(appId: "un-altra-applicazione")))
|
||||
{
|
||||
var answer = await wrongApp.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(400, answer.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(answer).Signal.Code);
|
||||
}
|
||||
|
||||
// Values the catalog asks for and the session does not have: nothing leaves.
|
||||
var before = site.Control.DirectRequests.Count;
|
||||
foreach (var (values, missing) in new[]
|
||||
{
|
||||
(Values(csrf: null), "x-csrftoken"),
|
||||
(Values(session: null), TestSite.SessionCookie),
|
||||
(Values(docIds: false), "doc_id"),
|
||||
})
|
||||
{
|
||||
using var bed = new Bed(site, values);
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => bed.SendAsync(Graph(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(missing, refused.Missing);
|
||||
}
|
||||
|
||||
using (var none = new Bed(site, noSession: true))
|
||||
{
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => none.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.IsNull(refused.Missing);
|
||||
}
|
||||
|
||||
Assert.HasCount(before, site.Control.DirectRequests);
|
||||
|
||||
// The site checks the token against its cookie, as a real site does (H16-generic answer): a plain client here,
|
||||
// only to show the test site refuses what the site client never sends.
|
||||
using var plain = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, site.Url("/api/dati/inizio"));
|
||||
request.Headers.TryAddWithoutValidation("cookie", $"{TestSite.SessionCookie}={SiteControl.InitialSession}; {TestSite.CsrfCookie}={Csrf}");
|
||||
request.Headers.TryAddWithoutValidation("x-csrftoken", "un-altro-gettone");
|
||||
request.Headers.TryAddWithoutValidation("x-app-id", TestSite.AppId);
|
||||
request.Headers.TryAddWithoutValidation("accept", "application/json");
|
||||
request.Headers.TryAddWithoutValidation("user-agent", UserAgent);
|
||||
using var forbidden = await plain.SendAsync(request);
|
||||
Assert.AreEqual(403, (int)forbidden.StatusCode);
|
||||
Assert.AreEqual("text/html", forbidden.Content.Headers.ContentType?.MediaType);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSiteChecksTheTypesOfTheVariablesAndTheFriendlyName()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
|
||||
// An edited copy of the catalog that writes «primi» as a text: the request is not the page's, the site refuses it.
|
||||
var file = JsonNode.Parse(Febe.Core.Collection.SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
var query = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == TestSite.ProfileQuery)!;
|
||||
query["variables"]!["primi"] = "12";
|
||||
using (var typed = new Bed(site, catalog: RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json (modificato)")))
|
||||
{
|
||||
var answer = await typed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(400, answer.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(answer).Signal.Code);
|
||||
}
|
||||
|
||||
// A doc_id of another operation.
|
||||
var docIds = new Dictionary<string, string> { [TestSite.ProfileQuery] = "8000000000000002" };
|
||||
var values = Values();
|
||||
using var wrongDoc = new Bed(site, new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, docIds));
|
||||
Assert.AreEqual(400, (await wrongDoc.SendAsync(Graph(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OneRequestAtATimeAndTheOthersAreRefusedNotQueued()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
site.Control.DirectDelay = TimeSpan.FromSeconds(1);
|
||||
site.Control.ReplyToDirect(DirectReply.TooManyRequests);
|
||||
|
||||
var first = bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
await WaitUntilAsync(() => site.Control.DirectRequests.Count == 1);
|
||||
|
||||
// While the first is in flight: refused at once, not queued behind it (a queued one would leave right after a
|
||||
// 429 before anybody read it, rule 8).
|
||||
var others = await Task.WhenAll(Enumerable.Range(0, 3).Select(_ => Task.Run(async () =>
|
||||
{
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
return refused.Message;
|
||||
})));
|
||||
|
||||
Assert.AreEqual(429, (await first).Status);
|
||||
Assert.IsTrue(others.All(m => m.Contains("in corso", StringComparison.Ordinal)));
|
||||
Assert.HasCount(1, site.Control.DirectRequests, "Nothing left after the 429.");
|
||||
Assert.AreEqual(1, site.Control.MaxDirectInFlight, "Never two requests in flight.");
|
||||
|
||||
// Once the answer is in, the next may leave.
|
||||
site.Control.DirectDelay = TimeSpan.Zero;
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStopModesOfTheSiteCountTheRequestsOfTheSiteClientToo()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
|
||||
// «After one data request»: the site client's requests count, as the pages' do.
|
||||
site.Control.Set(StopMode.TooManyRequests, afterDataRequests: 1);
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
Assert.AreEqual(429, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
|
||||
// The session ends: the cookie goes, and on the site too.
|
||||
site.Control.Set(StopMode.SessionEnded);
|
||||
var ended = await bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, ended.Status);
|
||||
Assert.IsTrue(ended.Deletes(TestSite.SessionCookie));
|
||||
Assert.IsFalse(site.Control.IsSession(SiteControl.InitialSession));
|
||||
Assert.IsNull(bed.Session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSessionThePagesOpenWorksForTheSiteClientAndEndsOnBothSides()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var browser = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
|
||||
|
||||
// The first visit is a login: a new value, never the fixed one, and the site client accepts it once copied.
|
||||
var (_, _, first) = await VisitAsync(browser, site, "/", null);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(first));
|
||||
Assert.AreNotEqual(SiteControl.InitialSession, first);
|
||||
Assert.IsTrue(site.Control.IsSession(first));
|
||||
using (var copied = new Bed(site, Values(session: first)))
|
||||
{
|
||||
Assert.AreEqual(200, (await copied.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
// The session expires on the page side: the browser loses the cookie and the site ends the value, so the same
|
||||
// value copied in the site client is refused afterwards.
|
||||
site.Control.Set(StopMode.SessionEnded);
|
||||
var (status, location, deleted) = await VisitAsync(browser, site, "/profilo/marta.prova", first);
|
||||
Assert.AreEqual(302, status);
|
||||
Assert.AreEqual("/sessione-scaduta", location);
|
||||
Assert.AreEqual(string.Empty, deleted, "The page deletes the cookie.");
|
||||
Assert.IsFalse(site.Control.IsSession(first));
|
||||
site.Control.Set(StopMode.Normal);
|
||||
using (var stale = new Bed(site, Values(session: first)))
|
||||
{
|
||||
var refused = await stale.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, refused.Status);
|
||||
Assert.AreEqual("/{testo}/", refused.RedirectPathShape);
|
||||
}
|
||||
|
||||
// A new login (a visit without the cookie) opens a new session the site client accepts.
|
||||
var (_, _, second) = await VisitAsync(browser, site, "/", null);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(second));
|
||||
Assert.AreNotEqual(first, second);
|
||||
using (var renewed = new Bed(site, Values(session: second)))
|
||||
{
|
||||
Assert.AreEqual(200, (await renewed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
// A browser that kept a value the site ended gets a new one at its next visit.
|
||||
var (_, _, third) = await VisitAsync(browser, site, "/", first);
|
||||
Assert.IsTrue(site.Control.IsSession(third));
|
||||
Assert.AreNotEqual(first, third);
|
||||
|
||||
// The data of the pages end the session too when it expires.
|
||||
site.Control.Set(StopMode.SessionEnded);
|
||||
using (var data = new HttpRequestMessage(HttpMethod.Get, site.Url("/dati/inizio")))
|
||||
{
|
||||
data.Headers.TryAddWithoutValidation("cookie", $"{TestSite.SessionCookie}={second}");
|
||||
using var answer = await browser.SendAsync(data);
|
||||
Assert.AreEqual(401, (int)answer.StatusCode);
|
||||
}
|
||||
|
||||
Assert.IsFalse(site.Control.IsSession(second));
|
||||
site.Control.Set(StopMode.Normal);
|
||||
using (var ended = new Bed(site, Values(session: second)))
|
||||
{
|
||||
Assert.AreEqual(302, (await ended.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, site.Control.LoginPageVisits);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLateAnswerOfAReplacedSessionDoesNotTouchTheNewOne()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
site.Control.DirectDelay = TimeSpan.FromMilliseconds(500);
|
||||
site.Control.ReplyToDirect(DirectReply.DeleteSessionCookie);
|
||||
|
||||
var sending = bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
await WaitUntilAsync(() => site.Control.DirectRequests.Count == 1);
|
||||
|
||||
// A new login while the request is in flight: «Ho finito» copies a new session.
|
||||
bed.Session.Replace(Values(session: "nuova-sessione"));
|
||||
var answer = await sending;
|
||||
|
||||
Assert.IsTrue(answer.Deletes(TestSite.SessionCookie), "The answer still says what the site did.");
|
||||
Assert.AreEqual("nuova-sessione", bed.Session.Read()!.Cookie(TestSite.SessionCookie), "But the new session is not changed by the old one's answer.");
|
||||
Assert.AreEqual(0, bed.Session.Updates);
|
||||
}
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
while (!condition())
|
||||
{
|
||||
await Task.Delay(10, limit.Token);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NothingLeavesWithoutAPermitGrantedForThatRequest()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
|
||||
var denied = Permit.Deny(ActionKind.ProfileOpen, null, DenialReason.HourlyBudgetReached, "Tetto orario raggiunto.");
|
||||
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(Profile(), denied, CancellationToken.None));
|
||||
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(Profile(), Permit.Grant(ActionKind.StoryView, null), CancellationToken.None));
|
||||
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(new SiteRequest("cerca", new Dictionary<string, string> { [CaseValues.SearchText] = "marta" }), Permit.Grant(ActionKind.ProfileSearch, null), CancellationToken.None));
|
||||
Assert.IsEmpty(site.Control.DirectRequests);
|
||||
|
||||
var permit = Permit.Grant(ActionKind.ProfileOpen, null);
|
||||
await bed.Requester.SendAsync(Profile(), permit, CancellationToken.None);
|
||||
var again = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(Profile(), permit, CancellationToken.None));
|
||||
StringAssert.Contains(again.Message, "già stato usato");
|
||||
Assert.HasCount(1, site.Control.DirectRequests);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoAnswerIsAnErrorWithoutTheAddress()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
site.Control.DirectDelay = TimeSpan.FromSeconds(5);
|
||||
using var slow = new Bed(site, options: HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")) with { Timeout = TimeSpan.FromMilliseconds(300) });
|
||||
var timeout = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => slow.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(SiteUnreachableReason.Timeout, timeout.Reason);
|
||||
AssertNoAddress(timeout.Message, site.SitePort);
|
||||
|
||||
var closed = Browser.TestSupport.LocalTestSite.FreePort();
|
||||
using var nobody = new Bed(site, options: HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{closed}/")));
|
||||
var unreachable = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => nobody.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(SiteUnreachableReason.Unreachable, unreachable.Reason);
|
||||
AssertNoAddress(unreachable.Message, closed);
|
||||
Assert.IsNull(unreachable.InnerException, "The network error may name the address: it is not passed on.");
|
||||
|
||||
using var caller = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||
using var patient = new Bed(site);
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => patient.Requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), caller.Token));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLogNamesOnlyOperationsPathShapesAndStatuses()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
var cases = Cases(site);
|
||||
foreach (var operation in Catalog.Configured)
|
||||
{
|
||||
await bed.SendAsync(new SiteRequest(operation.Name, cases[operation.Name].Values), operation.Category);
|
||||
}
|
||||
|
||||
foreach (var reply in new[] { DirectReply.RedirectToLogin, DirectReply.SetClaim, DirectReply.RenewSessionCookie, DirectReply.DeleteSessionCookie })
|
||||
{
|
||||
site.Control.ReplyToDirect(reply);
|
||||
await bed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
}
|
||||
|
||||
Assert.IsTrue(bed.Log.Count >= Catalog.Configured.Count() + 4);
|
||||
Assert.IsTrue(bed.Log.Any(l => l.Contains("«ProvaProfiloQuery» /api/graphql, stato 200", StringComparison.Ordinal)), string.Join("\n", bed.Log));
|
||||
Assert.IsTrue(bed.Log.Any(l => l.Contains("«profilo» /api/dati/profilo/{testo}, stato 200", StringComparison.Ordinal)), string.Join("\n", bed.Log));
|
||||
var secrets = new List<string>
|
||||
{
|
||||
Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId,
|
||||
TestSite.DocIds[TestSite.ProfileQuery], UserAgent, "Mozilla", "marta.prova", "luca.prova", "c12", "127.0.0.1", "scheda", "primi", "accesso", "next",
|
||||
};
|
||||
secrets.AddRange(cases.Values.SelectMany(c => c.Values.Values));
|
||||
foreach (var line in bed.Log)
|
||||
{
|
||||
foreach (var secret in secrets)
|
||||
{
|
||||
Assert.IsFalse(line.Contains(secret, StringComparison.OrdinalIgnoreCase), $"«{secret}» in «{line}».");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, (Dictionary<string, string> Values, string PagePath)> Cases(TestSite site)
|
||||
{
|
||||
string code;
|
||||
string highlight;
|
||||
lock (site.World.Gate)
|
||||
{
|
||||
var marta = site.World.FindByUsername("marta.prova")!;
|
||||
code = marta.Posts[0].Code;
|
||||
highlight = marta.Highlights[0].Id;
|
||||
}
|
||||
|
||||
static Dictionary<string, string> V(params (string Name, string Value)[] values) => values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);
|
||||
return new(StringComparer.Ordinal)
|
||||
{
|
||||
["inizio"] = (V(), "/dati/inizio"),
|
||||
["profilo"] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=post"),
|
||||
["profilo-altri"] = (V((CaseValues.Username, "luca.prova"), (CaseValues.Cursor, "c12")), "/dati/profilo/luca.prova/altri?dopo=c12&scheda=post"),
|
||||
[TestSite.ProfileQuery] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=post"),
|
||||
["taggati"] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=taggati"),
|
||||
["post"] = (V((CaseValues.Code, code)), "/dati/post/" + code),
|
||||
["storie"] = (V((CaseValues.Username, "marta.prova")), "/dati/storie/marta.prova"),
|
||||
["evidenza"] = (V((CaseValues.HighlightId, highlight)), "/dati/evidenza/" + Uri.EscapeDataString(highlight)),
|
||||
["seguiti"] = (V(), "/dati/seguiti"),
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<string[]> ReadAsync(ReadOnlyMemory<byte> body, SiteAnswer answer, VirtualClock clock)
|
||||
{
|
||||
var collector = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock);
|
||||
var descriptor = new ResponseDescriptor("r1", HostKind.Site, "http://127.0.0.1" + answer.PathShape, "127.0.0.1", answer.PathShape, answer.Status, answer.MimeType, "Fetch", false, clock.Now);
|
||||
Assert.AreEqual(1, await new ResponseDelivery("Client del sito").DeliverBodyAsync(descriptor, body, [collector], CancellationToken.None));
|
||||
return [.. collector.Since(0).Select(r => JsonSerializer.Serialize(r.Result))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A page visit as the browser makes it, with <paramref name="session"/> as its cookie: the status, the redirect and
|
||||
/// the value of the session cookie the page set (empty when it deleted it, null when it set none).
|
||||
/// </summary>
|
||||
private static async Task<(int Status, string? Location, string? Session)> VisitAsync(HttpClient browser, TestSite site, string path, string? session)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, site.Url(path));
|
||||
if (session is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("cookie", $"{TestSite.SessionCookie}={session}");
|
||||
}
|
||||
|
||||
using var response = await browser.SendAsync(request);
|
||||
string? set = null;
|
||||
if (response.Headers.TryGetValues("Set-Cookie", out var cookies))
|
||||
{
|
||||
var prefix = TestSite.SessionCookie + "=";
|
||||
set = cookies.Where(c => c.StartsWith(prefix, StringComparison.Ordinal)).Select(c => c[prefix.Length..].Split(';')[0]).LastOrDefault();
|
||||
}
|
||||
|
||||
return ((int)response.StatusCode, response.Headers.Location?.OriginalString, set);
|
||||
}
|
||||
|
||||
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static SiteRequest Graph() => SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static SiteOperation Operation(string name) => Catalog.Operations.Single(o => o.Name == name);
|
||||
|
||||
private static SiteAnswerSignal Classify(SiteAnswer answer) =>
|
||||
Signals.Classify(Operation(answer.Operation), answer, DateTimeOffset.UnixEpoch) ?? throw new AssertFailedException($"Nessun segnale per {answer}.");
|
||||
|
||||
private static void AssertNoAddress(string message, int port)
|
||||
{
|
||||
Assert.IsFalse(message.Contains("127.0.0.1", StringComparison.Ordinal), message);
|
||||
Assert.IsFalse(message.Contains(port.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal), message);
|
||||
Assert.IsFalse(message.Contains("marta", StringComparison.Ordinal), message);
|
||||
Assert.IsFalse(message.Contains("http", StringComparison.Ordinal), message);
|
||||
}
|
||||
|
||||
/// <summary>The saved session of a test: the cookies, tokens and doc_id the pages of the test site hand out.</summary>
|
||||
internal static SiteSessionValues Values(string? session = SiteControl.InitialSession, string? csrf = Csrf, string appId = TestSite.AppId, bool docIds = true)
|
||||
{
|
||||
var cookies = new List<KeyValuePair<string, string>>();
|
||||
if (csrf is not null)
|
||||
{
|
||||
cookies.Add(new(TestSite.CsrfCookie, csrf));
|
||||
}
|
||||
|
||||
if (session is not null)
|
||||
{
|
||||
cookies.Add(new(TestSite.SessionCookie, session));
|
||||
}
|
||||
|
||||
cookies.Add(new("altro", OtherCookie));
|
||||
return new SiteSessionValues(
|
||||
cookies,
|
||||
UserAgent,
|
||||
new Dictionary<string, string> { ["app_id"] = appId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = AccountId },
|
||||
docIds ? TestSite.DocIds : null);
|
||||
}
|
||||
|
||||
/// <summary>A site client for the test site with its session, clock and log.</summary>
|
||||
private sealed class Bed : IDisposable
|
||||
{
|
||||
private readonly ConcurrentQueue<string> _log = new();
|
||||
|
||||
/// <param name="site">The test site.</param>
|
||||
/// <param name="values">The saved session; <see cref="Values"/> by default.</param>
|
||||
/// <param name="options">Options; the test site's by default.</param>
|
||||
/// <param name="noSession">No saved session at all.</param>
|
||||
/// <param name="catalog">The catalog; the shipped one by default.</param>
|
||||
public Bed(TestSite site, SiteSessionValues? values = null, HttpSiteRequesterOptions? options = null, bool noSession = false, RequestCatalog? catalog = null)
|
||||
{
|
||||
Session = new InMemorySiteSession(noSession ? null : values ?? Values());
|
||||
Requester = new HttpSiteRequester(catalog ?? Catalog, Session, options ?? HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), Clock, _log.Enqueue);
|
||||
}
|
||||
|
||||
public InMemorySiteSession Session { get; }
|
||||
|
||||
public VirtualClock Clock { get; } = new();
|
||||
|
||||
public HttpSiteRequester Requester { get; }
|
||||
|
||||
public IReadOnlyList<string> Log => [.. _log];
|
||||
|
||||
public Task<SiteAnswer> SendAsync(SiteRequest request, ActionKind kind) =>
|
||||
Requester.SendAsync(request, Permit.Grant(kind, null), CancellationToken.None);
|
||||
|
||||
public void Dispose() => Requester.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>A clock that does not move.</summary>
|
||||
private sealed class FixedTime(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,16 @@ public sealed partial class RequestCatalogTests
|
||||
ownAgent["headers"] = new JsonObject { ["user-agent"] = "constant:Febe/1.0" };
|
||||
StringAssert.Contains(Refuse(Alone(ownAgent)), "user-agent");
|
||||
|
||||
// A configured operation without the browser's user agent would leave with none (rule 4).
|
||||
var noAgent = Rest("post2", "/dati/post/{code}");
|
||||
noAgent.Remove("headers");
|
||||
StringAssert.Contains(Refuse(Alone(noAgent)), "user-agent");
|
||||
var notConfigured = Rest("post2", "/dati/post/{code}");
|
||||
notConfigured.Remove("headers");
|
||||
notConfigured["configured"] = false;
|
||||
notConfigured["reason"] = "da campioni";
|
||||
Assert.IsNotNull(RequestCatalog.Parse(Alone(notConfigured), "richieste.prova.json"), "Not configured: it never leaves, the line can wait.");
|
||||
|
||||
var unknownValue = Rest("post2", "/dati/post/{password}");
|
||||
StringAssert.Contains(Refuse(Alone(unknownValue)), "valore del caso");
|
||||
|
||||
@@ -350,6 +360,7 @@ public sealed partial class RequestCatalogTests
|
||||
["path"] = path,
|
||||
["category"] = "post",
|
||||
["configured"] = true,
|
||||
["headers"] = new JsonObject { ["user-agent"] = "session:user_agent" },
|
||||
["rootFields"] = new JsonArray("contenuto"),
|
||||
["sample"] = "000005-post-serie",
|
||||
};
|
||||
@@ -362,7 +373,7 @@ public sealed partial class RequestCatalogTests
|
||||
["path"] = "/api/graphql",
|
||||
["category"] = "profilo",
|
||||
["configured"] = true,
|
||||
["headers"] = new JsonObject { ["x-fb-friendly-name"] = "operation" },
|
||||
["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-fb-friendly-name"] = "operation" },
|
||||
["body"] = new JsonObject { ["variables"] = "variables", ["doc_id"] = "session:doc_id", ["fb_api_req_friendly_name"] = "operation" },
|
||||
["variables"] = new JsonObject { ["id"] = "{account_id}" },
|
||||
["rootFields"] = new JsonArray("data.user"),
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The stop signals of §7.6 read from the answers of the site client (issue #36, S2), whatever brought them: 429 as for
|
||||
/// the browser, and until the true shapes are known (H16) a redirect, a 401 or 403, an HTML or a JSON without the
|
||||
/// expected fields, a deleted session cookie are a Verifica; a JSON with its fields is no signal.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SiteAnswerSignalsTests
|
||||
{
|
||||
private static readonly DateTimeOffset At = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
|
||||
private static readonly SiteOperation Tray = SettledCatalog.Instagram().Operations.Single(o => o.Name == "PolarisProfileStoryHighlightsTrayContentQuery");
|
||||
private static readonly SiteOperation Profile = RequestCatalog.LoadTestSite().Operations.Single(o => o.Name == "profilo");
|
||||
private static readonly SiteAnswerSignals Instagram = new(SignalRules.LoadDefault(), "sessionid");
|
||||
private static readonly SiteAnswerSignals Prova = new(SignalRules.LoadTestSite(), "sessione_prova");
|
||||
|
||||
[TestMethod]
|
||||
public void AJsonWithItsFieldsIsNoSignal()
|
||||
{
|
||||
Assert.IsNull(Prova.Classify(Profile, Json(Profile, 200, """{"profilo":{"nome":"marta"}}"""), At));
|
||||
Assert.IsNull(Prova.Classify(Profile, Json(Profile, 200, """{"profilo":{}}""", rootFieldsPresent: true), At));
|
||||
|
||||
// A cookie renewed or another cookie deleted is not a stop.
|
||||
Assert.IsNull(Prova.Classify(Profile, new SiteAnswer(Profile, 200, "application/json", Bytes("""{"profilo":{}}"""), cookiesSet: ["sessione_prova"], cookiesDeleted: ["altro"], setsClaim: true), At));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void A429IsARallentamentoAsForTheBrowser()
|
||||
{
|
||||
var signal = Instagram.Classify(Tray, new SiteAnswer(Tray, 429, "text/html", ReadOnlyMemory<byte>.Empty, retryAfter: TimeSpan.FromMinutes(2)), At)!;
|
||||
Assert.AreEqual(SignalLevel.Throttle, signal.Signal.Level);
|
||||
Assert.AreEqual("http-429", signal.Signal.Code);
|
||||
Assert.AreEqual(At, signal.Signal.At);
|
||||
StringAssert.Contains(signal.Message, "429");
|
||||
StringAssert.Contains(signal.Message, "120 s");
|
||||
|
||||
Assert.AreEqual(SignalLevel.Throttle, Prova.Classify(Profile, Json(Profile, 429, """{"errore":"troppe-richieste"}"""), At)!.Signal.Level);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(301)]
|
||||
[DataRow(302)]
|
||||
[DataRow(303)]
|
||||
[DataRow(307)]
|
||||
public void ARedirectIsAVerificaAndShowsOnlyTheShapeOfWhereItPointed(int status)
|
||||
{
|
||||
var answer = new SiteAnswer(Tray, status, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: "https://www.instagram.com/accounts/login/?next=%2Fmarta.prova%2F");
|
||||
var signal = Instagram.Classify(Tray, answer, At)!;
|
||||
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, signal.Signal.Code);
|
||||
Assert.AreEqual(SiteAnswerSignals.H16, signal.Hypothesis);
|
||||
StringAssert.Contains(signal.Message, "/accounts/login/");
|
||||
StringAssert.Contains(signal.Message, "non seguito");
|
||||
Assert.IsFalse(signal.Message.Contains("marta", StringComparison.Ordinal));
|
||||
Assert.IsFalse(signal.Message.Contains("instagram.com", StringComparison.Ordinal));
|
||||
Assert.AreEqual(Tray.PathShape, signal.Signal.Url, "The address of the signal is the path shape, never a value.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void A401OrA403IsAVerifica()
|
||||
{
|
||||
Assert.AreEqual(SiteAnswerSignals.UnauthorizedCode, Instagram.Classify(Tray, Json(Tray, 401, """{"message":"login_required"}"""), At)!.Signal.Code);
|
||||
var forbidden = Instagram.Classify(Tray, new SiteAnswer(Tray, 403, "text/html", Bytes("<html><body>CSRF</body></html>")), At)!;
|
||||
Assert.AreEqual(SiteAnswerSignals.ForbiddenCode, forbidden.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, forbidden.Signal.Level);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnHtmlANonJsonOrAJsonWithoutTheExpectedFieldsIsAVerifica()
|
||||
{
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 200, "text/html; charset=utf-8", Bytes("<!DOCTYPE html><html></html>"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 200, "application/json", Bytes("\n <!doctype HTML><html></html>"))), "Declared JSON, but an HTML document.");
|
||||
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 200, "text/javascript", Bytes("for (;;);{\"a\":1}"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 200, "application/json", ReadOnlyMemory<byte>.Empty)));
|
||||
|
||||
var missing = Prova.Classify(Profile, Json(Profile, 200, """{"risposta":{"voci":[]}}"""), At)!;
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, missing.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, missing.Signal.Level);
|
||||
StringAssert.Contains(missing.Message, "profilo", "Names the expected fields.");
|
||||
Assert.IsFalse(missing.Message.Contains("voci", StringComparison.Ordinal), "Never the body.");
|
||||
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 200, """{"profilo":null}""")), "A null field is missing.");
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 200, """{"profilo":{}}""", rootFieldsPresent: false)), "What the site client saw wins.");
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 400, """{"errore":"richiesta-non-valida"}""")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSessionCookieDeletedIsAVerificaEvenWithGoodData()
|
||||
{
|
||||
var answer = new SiteAnswer(Tray, 200, "text/javascript", Bytes("""{"data":{}}"""), cookiesDeleted: ["sessionid"]);
|
||||
var signal = Instagram.Classify(Tray, answer, At)!;
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, signal.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
|
||||
StringAssert.Contains(signal.Message, "cookie di sessione");
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, Instagram.Classify(Tray, new SiteAnswer(Tray, 302, null, ReadOnlyMemory<byte>.Empty, redirectTo: "/accounts/login/", cookiesDeleted: ["sessionid"]), At)!.Signal.Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTextRulesOfTheSiteApplyToShortJsonAnswers()
|
||||
{
|
||||
var wait = Instagram.Classify(Tray, Json(Tray, 400, """{"message":"Please wait a few minutes before you try again.","status":"fail"}"""), At)!;
|
||||
Assert.AreEqual(SignalLevel.Throttle, wait.Signal.Level);
|
||||
Assert.AreEqual("wait-text", wait.Signal.Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AJsonNotFoundOrServerErrorIsLeftToTheCallerButAnHtmlOneStops()
|
||||
{
|
||||
Assert.IsNull(Classify(Json(Profile, 404, """{"errore":"non-trovato"}""")));
|
||||
Assert.IsNull(Classify(Json(Profile, 500, """{"status":"fail"}""")));
|
||||
|
||||
// §6.0: not JSON where JSON is expected stops the session, whatever the status (an HTML login or error page).
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 404, "text/html", Bytes("<!DOCTYPE html><html></html>"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 500, "text/html", Bytes("<html></html>"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 503, null, ReadOnlyMemory<byte>.Empty)));
|
||||
|
||||
// The text rules apply to a short JSON of any status.
|
||||
Assert.AreEqual("wait-text", Instagram.Classify(Tray, Json(Tray, 500, """{"message":"Please wait a few minutes before you try again."}"""), At)!.Signal.Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AMissingSessionIsADisconnessioneAndAnAnswerOfAnotherOperationIsRefused()
|
||||
{
|
||||
var none = SiteAnswerSignals.ForMissingSession(new SiteSessionMissingException("…", missing: null), At);
|
||||
Assert.AreEqual(SignalLevel.Disconnect, none.Signal.Level);
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionMissingCode, none.Signal.Code);
|
||||
StringAssert.Contains(SiteAnswerSignals.ForMissingSession(new SiteSessionMissingException("…", "x-csrftoken"), At).Message, "x-csrftoken");
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Prova.Classify(Profile, Json(Tray, 200, "{}"), At));
|
||||
}
|
||||
|
||||
private static string? Classify(SiteAnswer answer) => Prova.Classify(Profile, answer, At)?.Signal.Code;
|
||||
|
||||
private static SiteAnswer Json(SiteOperation operation, int status, string body, bool? rootFieldsPresent = null) =>
|
||||
new(operation, status, "application/json; charset=utf-8", Bytes(body), rootFieldsPresent: rootFieldsPresent);
|
||||
|
||||
private static byte[] Bytes(string text) => Encoding.UTF8.GetBytes(text);
|
||||
}
|
||||
|
||||
/// <summary>The saved session of the site client (issue #36, S2): cookies read as a browser reads them, updates in one write, no value in its text.</summary>
|
||||
[TestClass]
|
||||
public sealed class SiteSessionTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("sessionid=abc; Path=/; HttpOnly", "abc", false)]
|
||||
[DataRow("sessionid=\"abc\"; Path=/", "\"abc\"", false)]
|
||||
[DataRow("sessionid=\"\"; Path=/", "\"\"", true)]
|
||||
[DataRow("sessionid=; Path=/", "", true)]
|
||||
[DataRow("sessionid=abc; Max-Age=0; Path=/", "abc", true)]
|
||||
[DataRow("sessionid=abc; Max-Age=-1", "abc", true)]
|
||||
[DataRow("sessionid=abc; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/", "abc", true)]
|
||||
[DataRow("sessionid=abc; expires=Wed, 16 Nov 2027 10:00:00 GMT; path=/", "abc", false)]
|
||||
[DataRow("sessionid=abc; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=3600", "abc", false)]
|
||||
[DataRow("sessionid=abc; Domain=.instagram.com; Path=/", "abc", false)]
|
||||
[DataRow("sessionid=abc; Domain=instagram.com", "abc", false)]
|
||||
public void ACookieLineIsReadAsABrowserReadsIt(string line, string value, bool deletes)
|
||||
{
|
||||
var cookie = SiteCookies.Parse(line, "www.instagram.com", Now);
|
||||
Assert.IsNotNull(cookie);
|
||||
Assert.AreEqual("sessionid", cookie.Value.Name);
|
||||
Assert.AreEqual(value, cookie.Value.Value);
|
||||
Assert.AreEqual(deletes, cookie.Value.Deletes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AQuotedValueIsKeptAsTheBrowserKeepsItAndTheExpiryIsRead()
|
||||
{
|
||||
// RFC 6265 §5.2: the quotes are part of the value; sent back without them the cookie would not be the browser's.
|
||||
var rur = SiteCookies.Parse("rur=\"CLN\\05412\\0541795\"; Domain=.instagram.com; Path=/; Max-Age=3600", "www.instagram.com", Now)!.Value;
|
||||
Assert.AreEqual("\"CLN\\05412\\0541795\"", rur.Value);
|
||||
Assert.AreEqual(Now.AddHours(1), rur.Expires, "Max-Age from now.");
|
||||
|
||||
Assert.AreEqual(new DateTimeOffset(2027, 11, 16, 10, 0, 0, TimeSpan.Zero), SiteCookies.Parse("a=b; expires=Tue, 16 Nov 2027 10:00:00 GMT", "www.instagram.com", Now)!.Value.Expires);
|
||||
Assert.IsNull(SiteCookies.Parse("a=b; Path=/", "www.instagram.com", Now)!.Value.Expires, "No expiry: it lasts as the session.");
|
||||
Assert.IsNull(SiteCookies.Parse("a=b; Max-Age=0", "www.instagram.com", Now)!.Value.Expires, "A deletion has no expiry.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NewCookiesKeepTheOrderOfTheSiteAndExpiredOnesAreNotSent()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(
|
||||
[new("csrftoken", "c1"), new("sessionid", "s1"), new("vecchio", "v1")],
|
||||
"agente",
|
||||
expires: new Dictionary<string, DateTimeOffset> { ["vecchio"] = Now.AddMinutes(1) }));
|
||||
var capture = session.Read()!.Capture;
|
||||
|
||||
// Ten names, in an order no hash keeps by chance.
|
||||
var names = new[] { "ig_nrcb", "ps_l", "zz", "aa", "mid", "datr", "ps_n", "wd", "b1", "a9" };
|
||||
await session.UpdateAsync(
|
||||
new SiteSessionUpdate(names.Select(n => new KeyValuePair<string, string>(n, "x-" + n)), expires: new Dictionary<string, DateTimeOffset> { ["wd"] = Now.AddDays(7) }, capture: capture),
|
||||
CancellationToken.None);
|
||||
|
||||
var values = session.Read()!;
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Key).ToArray());
|
||||
Assert.AreEqual(capture, values.Capture, "A renewal keeps the capture.");
|
||||
Assert.AreEqual(Now.AddDays(7), values.Expires["wd"]);
|
||||
|
||||
Assert.AreEqual("v1", values.CookieAt("vecchio", Now));
|
||||
Assert.IsNull(values.CookieAt("vecchio", Now.AddMinutes(1)), "Expired: the browser would not send it.");
|
||||
Assert.IsFalse(values.CookiesAt(Now.AddMinutes(2)).Any(c => c.Key == "vecchio"));
|
||||
Assert.IsNull(values.CookieAt("wd", Now.AddDays(8)));
|
||||
Assert.AreEqual("s1", values.CookieAt("sessionid", Now.AddYears(5)), "No expiry: as long as the session.");
|
||||
|
||||
// Renewed without an expiry: the old expiry goes.
|
||||
await session.UpdateAsync(new SiteSessionUpdate([new("wd", "x2")], capture: capture), CancellationToken.None);
|
||||
Assert.IsFalse(session.Read()!.Expires.ContainsKey("wd"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLateAnswerOfAReplacedSessionChangesNothing()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues([new("sessionid", "vecchia")], "agente"));
|
||||
var old = session.Read()!.Capture;
|
||||
session.Replace(new SiteSessionValues([new("sessionid", "nuova")], "agente"));
|
||||
Assert.AreNotEqual(old, session.Read()!.Capture, "A new login is a new capture.");
|
||||
|
||||
await session.UpdateAsync(new SiteSessionUpdate(cookiesDeleted: ["sessionid"], claim: "vecchio", capture: old), CancellationToken.None);
|
||||
Assert.AreEqual("nuova", session.Read()!.Cookie("sessionid"));
|
||||
Assert.AreEqual(SiteSessionValues.InitialClaim, session.Read()!.Field("claim", "Op"), "No claim yet: the page's «0».");
|
||||
Assert.AreEqual(0, session.Updates);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("sessionid=abc; Domain=facebook.com")]
|
||||
[DataRow("sessionid=abc; Domain=evilinstagram.com")]
|
||||
[DataRow("senza-uguale")]
|
||||
[DataRow("=abc")]
|
||||
[DataRow("nome con spazio=abc")]
|
||||
public void ACookieOfAnotherDomainOrNotACookieIsIgnored(string line) =>
|
||||
Assert.IsNull(SiteCookies.Parse(line, "www.instagram.com", Now));
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUpdateIsAppliedAtOnceAndTheTextShowsNoValue()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(
|
||||
[new("csrftoken", "segreto-1"), new("sessionid", "segreto-2"), new("rur", "segreto-3")],
|
||||
"Mozilla/5.0 segreto-agente",
|
||||
new Dictionary<string, string> { ["claim"] = "0", ["lsd"] = "segreto-4" },
|
||||
new Dictionary<string, string> { ["Op"] = "segreto-5" }));
|
||||
|
||||
await session.UpdateAsync(new SiteSessionUpdate(new Dictionary<string, string> { ["csrftoken"] = "segreto-6", ["nuovo"] = "segreto-7" }, ["rur"], "segreto-8"), CancellationToken.None);
|
||||
await session.UpdateAsync(new SiteSessionUpdate(), CancellationToken.None);
|
||||
|
||||
var values = session.Read()!;
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "nuovo" }, values.Cookies.Select(c => c.Key).ToArray(), "Renewed in place, new at the end, deleted gone.");
|
||||
Assert.AreEqual("segreto-6", values.Cookie("csrftoken"));
|
||||
Assert.AreEqual("segreto-8", values.Field("claim", "Op"));
|
||||
Assert.AreEqual("segreto-5", values.Field("doc_id", "Op"));
|
||||
Assert.IsNull(values.Field("doc_id", "Altra"));
|
||||
Assert.AreEqual("Mozilla/5.0 segreto-agente", values.Field("user_agent", "Op"));
|
||||
Assert.AreEqual(1, session.Updates, "An empty update writes nothing.");
|
||||
|
||||
foreach (var text in new[] { session.ToString(), values.ToString(), new SiteSessionUpdate(new Dictionary<string, string> { ["a"] = "segreto-9" }, ["b"], "segreto-10").ToString() })
|
||||
{
|
||||
Assert.IsFalse(text.Contains("segreto", StringComparison.Ordinal), text);
|
||||
Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal), text);
|
||||
}
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new SiteSessionValues([new("a=b", "c")], "agente"));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new SiteSessionValues([], "agente", new Dictionary<string, string> { ["password"] = "x" }));
|
||||
|
||||
var empty = new InMemorySiteSession(null);
|
||||
await empty.UpdateAsync(new SiteSessionUpdate(claim: "x"), CancellationToken.None);
|
||||
Assert.IsNull(empty.Read(), "No session: an update creates none.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using System.Net;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// The browser that showed nothing (Gitea issue #52), in the shared composition with the fake window «Browser di Febe»:
|
||||
/// opened from the empty rest page it goes to a page of its own, «Apri il browser» of a disconnection opens the login,
|
||||
/// leaving a page of Febe leaves the window as it is, and the test site's automatic login raises no false alarm.
|
||||
/// Never Instagram: the fake browser answers by itself.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class BrowserStartPageTests
|
||||
{
|
||||
private const string Login = "https://www.instagram.com/accounts/login/";
|
||||
private const string Home = "https://www.instagram.com/";
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task UsaIlBrowserFromTheRestPageOpensTheLoginOrTheHomeAndAnyOtherPageStays()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
|
||||
|
||||
// Not connected: never a white window, the login page.
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
Assert.AreEqual(Login, browser.FakeCdp.Url);
|
||||
Assert.AreEqual(1, browser.Shown, "the window came to the front");
|
||||
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
|
||||
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
|
||||
|
||||
// Connected: the site's home.
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
Assert.AreEqual(Home, browser.FakeCdp.Url);
|
||||
|
||||
// A page he opened stays as it is.
|
||||
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
|
||||
var navigations = Navigations(browser);
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
|
||||
Assert.AreEqual(navigations, Navigations(browser), "no navigation of his page");
|
||||
|
||||
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
|
||||
Assert.IsTrue(status.GetProperty("userIsDriving").GetBoolean());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task ApriIlBrowserBringsTheWindowWithItsStartPageAndTheLoginAfterADisconnection()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
|
||||
// Connected, at rest: «Apri il browser» (Attività) opens the home, the window in front.
|
||||
await LoginAsync(bed);
|
||||
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
|
||||
var shown = browser.Shown;
|
||||
var result = await bed.JsonAsync(HttpMethod.Post, "/api/browser/show");
|
||||
StringAssert.Contains(result.GetProperty("message").GetString(), "primo piano");
|
||||
Assert.AreEqual(Home, browser.FakeCdp.Url);
|
||||
Assert.AreEqual(shown + 1, browser.Shown);
|
||||
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine still");
|
||||
|
||||
// Closed with its X: out of view, the engine puts the page to rest.
|
||||
await browser.HideFromUserAsync(ct);
|
||||
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo la chiusura");
|
||||
|
||||
// The session goes while nobody looks: a disconnection. The red strip's «Apri il browser» asks for the login.
|
||||
browser.FakeCdp.LoggedIn = false;
|
||||
await bed.App.Connection!.RefreshAsync(ct);
|
||||
var breaker = bed.App.Engine!.Services.Breaker;
|
||||
await breaker.FlushAsync();
|
||||
Assert.AreEqual(BreakerStatus.Disconnected, breaker.State.Status);
|
||||
Assert.AreEqual(Login, bed.App.Connection.StartPageUrl, "disconnected: the start page is the login");
|
||||
|
||||
using (var show = await bed.SendAsync(HttpMethod.Post, "/api/browser/show", """{"openLogin":true}"""))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, show.StatusCode, await show.Content.ReadAsStringAsync(ct));
|
||||
}
|
||||
|
||||
Assert.AreEqual(Login, browser.FakeCdp.Url);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenButAnnullaPutsItAway()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
await LoginAsync(bed);
|
||||
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
|
||||
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
Assert.AreEqual(Home, browser.FakeCdp.Url);
|
||||
var hidden = browser.Hidden;
|
||||
|
||||
// Another page of Febe, the tab closed or reloaded: the page's hold ends, the window stays where it is.
|
||||
using (var left = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel", """{"pageLeft":true}"""))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, left.StatusCode);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), ct);
|
||||
Assert.AreEqual(hidden, browser.Hidden, "not put out of view");
|
||||
Assert.AreEqual(Home, browser.FakeCdp.Url, "not put to rest");
|
||||
Assert.IsTrue(browser.UserIsDriving, "on screen, the window still holds the engine");
|
||||
Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving);
|
||||
|
||||
// «Annulla» from the page is still «Annulla»: out of view and at rest.
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
|
||||
}
|
||||
|
||||
Assert.AreEqual(hidden + 1, browser.Hidden);
|
||||
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo «Annulla»");
|
||||
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task HoFinitoWithoutTheLoginSaysTheSessionIsNotThere()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
|
||||
await BeginAsync(bed, openLogin: true);
|
||||
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
|
||||
Assert.IsFalse(finish.GetProperty("connected").GetBoolean());
|
||||
StringAssert.Contains(finish.GetProperty("message").GetString(), "non trova la sessione");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(90_000, CooperativeCancellation = true)]
|
||||
public async Task TheTestSitesAutomaticLoginIsNoDisconnectionAtTheNextStart()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
const string site = "http://127.0.0.1:8481";
|
||||
string[] args = ["--sito-di-prova", site, "--accesso-di-prova"];
|
||||
using var temp = new TempFolder("accesso-di-prova");
|
||||
var locations = new MemoryLocationStore();
|
||||
FakeDesktopShell Shell() => new() { OnCreated = b => b.FakeCdp.LogsInOnVisit = site };
|
||||
|
||||
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
|
||||
{
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
Assert.IsTrue(bed.App.Connection!.IsConnected, "logged in by the automatic login");
|
||||
await bed.StopAsync();
|
||||
}
|
||||
|
||||
// The next start: the new browser has no session yet (the test site forgot it); the automatic login opens it again.
|
||||
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
|
||||
{
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var breaker = bed.App.Engine!.Services.Breaker;
|
||||
await breaker.FlushAsync();
|
||||
Assert.IsTrue(bed.App.Connection!.IsConnected);
|
||||
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status, "not a disconnection: the session the login was about to open");
|
||||
Assert.IsEmpty(await bed.App.Database.Incidents.ListOpenAsync(ct));
|
||||
await bed.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
|
||||
// Nobody at the browser: the page is the engine's, the button does nothing.
|
||||
var navigations = Navigations(browser);
|
||||
await connection.OpenStartPageAsync(ct);
|
||||
Assert.AreEqual(navigations, Navigations(browser));
|
||||
|
||||
// At the browser, on a page of his: the start page — but only once a step of the profile search let go of the page.
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
|
||||
var turns = bed.App.Engine!.Services.PageTurns;
|
||||
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
|
||||
var home = connection.OpenStartPageAsync(ct);
|
||||
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
|
||||
Assert.IsFalse(home.IsCompleted, "the search step still has the page");
|
||||
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
|
||||
turn.Dispose();
|
||||
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
Assert.AreEqual(Login, browser.FakeCdp.Url, "not connected: the login page");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeIsForgottenWhenAlbertoLetGoOfTheBrowserWhileItWaited()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
var turns = bed.App.Engine!.Services.PageTurns;
|
||||
|
||||
// The window on screen (its lease), a step of the profile search on the page: «Pagina iniziale» waits for its turn.
|
||||
var window = browser.UserDriving.Begin();
|
||||
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
|
||||
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
|
||||
var home = connection.OpenStartPageAsync(ct);
|
||||
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
|
||||
|
||||
// Alberto closes the window meanwhile: the page is the engine's again, and the press is forgotten (rules 7 and 8).
|
||||
window.Dispose();
|
||||
Assert.IsFalse(browser.UserIsDriving);
|
||||
turn.Dispose();
|
||||
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
Assert.DoesNotContain(Login, browser.FakeCdp.Visited, "no navigation of Alberto's without his lease");
|
||||
Assert.DoesNotContain(Home, browser.FakeCdp.Visited);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeEndsWithTheLeaseOfWhoPressedIt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
var turns = bed.App.Engine!.Services.PageTurns;
|
||||
|
||||
// Someone else still drives (Febe's page with «Usa il browser»), but the window that pressed the button closed.
|
||||
using var other = browser.UserDriving.Begin();
|
||||
using var pressedBy = new CancellationTokenSource();
|
||||
var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
|
||||
var home = connection.OpenStartPageAsync(pressedBy.Token);
|
||||
await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina");
|
||||
await pressedBy.CancelAsync();
|
||||
await home.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
Assert.IsFalse(turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), "no longer in the queue");
|
||||
turn.Dispose();
|
||||
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeNeverTakesThePageFromUnderASearchStep()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await DesktopTestBed.StartAsync();
|
||||
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
connection.PageTurnWait = TimeSpan.FromMilliseconds(300);
|
||||
var turns = bed.App.Engine!.Services.PageTurns;
|
||||
|
||||
using var window = browser.UserDriving.Begin();
|
||||
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
|
||||
using var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct);
|
||||
await connection.OpenStartPageAsync(ct).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
|
||||
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url, "the step keeps its page");
|
||||
Assert.DoesNotContain(Login, browser.FakeCdp.Visited);
|
||||
}
|
||||
|
||||
private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
|
||||
|
||||
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
|
||||
{
|
||||
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
|
||||
}
|
||||
|
||||
private static async Task LoginAsync(DesktopTestBed bed)
|
||||
{
|
||||
await BeginAsync(bed, openLogin: true);
|
||||
bed.Browser!.FakeCdp.LoggedIn = true;
|
||||
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
|
||||
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
|
||||
}
|
||||
}
|
||||
@@ -336,12 +336,5 @@ public sealed class DesktopCompositionTests
|
||||
StringAssert.Contains(log, "Windows non ha legato Edge a Febe");
|
||||
}
|
||||
|
||||
private static int FreePort()
|
||||
{
|
||||
var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
return port;
|
||||
}
|
||||
private static int FreePort() => Febe.Tests.Browser.TestSupport.LocalTestSite.FreePort();
|
||||
}
|
||||
@@ -28,11 +28,15 @@ internal sealed class FakeDesktopShell : IDesktopShell
|
||||
|
||||
public ConcurrentQueue<string> ProcessWindows { get; } = new();
|
||||
|
||||
/// <summary>Called with each browser as it is created, before Febe uses it (to set up the fake page).</summary>
|
||||
public Action<FakeBrowser>? OnCreated { get; set; }
|
||||
|
||||
public string? WebView2Version() => RuntimeVersion;
|
||||
|
||||
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
|
||||
{
|
||||
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
|
||||
OnCreated?.Invoke(browser);
|
||||
Created.Enqueue((settings, browser));
|
||||
return browser;
|
||||
}
|
||||
@@ -225,10 +229,19 @@ internal sealed class FakeCdp : ICdpSession
|
||||
|
||||
public bool LoggedIn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Like the test site, which sets its session cookie on any visit: a navigation to an address starting with this
|
||||
/// logs in, and the page reports itself loaded. Null: only the test logs in.
|
||||
/// </summary>
|
||||
public string? LogsInOnVisit { get; set; }
|
||||
|
||||
public string Url { get; private set; } = "about:blank";
|
||||
|
||||
public ConcurrentQueue<string> Methods { get; } = new();
|
||||
|
||||
/// <summary>Every address a <c>Page.navigate</c> asked for, in order.</summary>
|
||||
public ConcurrentQueue<string> Visited { get; } = new();
|
||||
|
||||
/// <summary>The main frame moved to <paramref name="url"/> by itself (a redirect of the site), not by a command.</summary>
|
||||
public void Navigated(string url)
|
||||
{
|
||||
@@ -244,7 +257,9 @@ internal sealed class FakeCdp : ICdpSession
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
|
||||
"Page.navigate" => Navigate(parameters),
|
||||
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }) : new JsonArray() },
|
||||
// The session cookie of Instagram, and the test site's one.
|
||||
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }, new JsonObject { ["name"] = "sessione_prova" }) : new JsonArray() },
|
||||
"Runtime.evaluate" when LogsInOnVisit is not null => new JsonObject { ["result"] = new JsonObject { ["type"] = "string", ["value"] = "complete" } },
|
||||
_ => new JsonObject(),
|
||||
};
|
||||
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
|
||||
@@ -276,6 +291,12 @@ internal sealed class FakeCdp : ICdpSession
|
||||
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
|
||||
if (url is not null)
|
||||
{
|
||||
Visited.Enqueue(url);
|
||||
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
|
||||
{
|
||||
LoggedIn = true;
|
||||
}
|
||||
|
||||
Navigated(url);
|
||||
}
|
||||
|
||||
|
||||
@@ -177,6 +177,17 @@ public sealed class RemoteViewSocketTests
|
||||
Assert.AreEqual("about:blank", BrowserRemoteViewConnection.WithoutQuery("about:blank"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheThreeButtonsOfTheBarAreNavigations()
|
||||
{
|
||||
static object? Parse(string json) => RemoteViewSocket.Parse(Encoding.UTF8.GetBytes(json));
|
||||
|
||||
Assert.AreEqual(RemoteViewNavigation.Back, Parse("""{"type":"navigate","action":"back"}"""));
|
||||
Assert.AreEqual(RemoteViewNavigation.Reload, Parse("""{"type":"navigate","action":"reload"}"""));
|
||||
Assert.AreEqual(RemoteViewNavigation.Home, Parse("""{"type":"navigate","action":"home"}"""), "«Pagina iniziale» (issue #52)");
|
||||
Assert.IsNull(Parse("""{"type":"navigate","action":"https://example.com/"}"""), "never an address from the page");
|
||||
}
|
||||
|
||||
private static Task<WebTestServer> StartAsync(FakeRemoteViewHost host) =>
|
||||
WebTestServer.StartAsync(
|
||||
new FebeWebOptions { Edition = FebeEdition.Docker, Access = AccessMode.Password, Password = Password },
|
||||
|
||||
@@ -132,6 +132,131 @@ public sealed class RemoteViewStartTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeOpensTheStartPageOfTheMoment()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var start = "http://127.0.0.1:8481/benvenuto";
|
||||
await using var bed = new Bed(_ => null, () => start);
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
|
||||
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
||||
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
Assert.AreEqual(start, bed.LastNavigation, "not connected: the login page");
|
||||
|
||||
// Connected meanwhile: the same button opens the site's home.
|
||||
start = "http://127.0.0.1:8481/";
|
||||
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
||||
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
Assert.AreEqual(start, bed.LastNavigation);
|
||||
Assert.AreEqual(2, bed.Cdp.Sent.Count(c => c.Method == "Page.navigate"), "Alberto's own navigations, one per press");
|
||||
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task PaginaInizialeWaitsBesideTheViewDroppingItsInputAndEndsWithIt()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var presses = 0;
|
||||
var pressedWith = new TaskCompletionSource<CancellationToken>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
await using var bed = new Bed(_ => null, open: async token =>
|
||||
{
|
||||
Interlocked.Increment(ref presses);
|
||||
pressedWith.TrySetResult(token);
|
||||
|
||||
// As the connection while a session ends or a search step holds the page: up to half a minute.
|
||||
await Task.Delay(Timeout.Infinite, token);
|
||||
});
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
bed.Cdp.Raise("Page.screencastFrame", Frame());
|
||||
await ReadUntilFrameAsync(view, ct);
|
||||
bed.Cdp.ClearSent();
|
||||
|
||||
// The receive loop goes on at once: the press waits beside it.
|
||||
await view.NavigateAsync(RemoteViewNavigation.Home, ct).WaitAsync(TimeSpan.FromSeconds(5), ct);
|
||||
var token = await pressedWith.Task.WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
Assert.IsFalse(StartPageOf(view).IsCompleted, "still waiting for its turn");
|
||||
|
||||
// Meanwhile clicks, keys and the other buttons are dropped (they would land on the start page as it loads), and a
|
||||
// second press waits for the first.
|
||||
await view.MouseAsync(new RemoteViewMouse(RemoteViewMouseAction.Down, 0.5, 0.5, RemoteViewButton.Left, 1, 0, 0), ct);
|
||||
await view.KeyAsync(new RemoteViewKey(RemoteViewKeyAction.Char, "a", "KeyA", "a", 0), ct);
|
||||
await view.NavigateAsync(RemoteViewNavigation.Reload, ct);
|
||||
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
||||
Assert.IsFalse(bed.Cdp.Sent.Any(c => IsInputOrNavigation(c.Method)), "nothing reached the browser: " + string.Join(", ", bed.Cdp.Sent.Select(c => c.Method)));
|
||||
Assert.AreEqual(1, Volatile.Read(ref presses));
|
||||
|
||||
// The view closes: its lease is gone, and so is the press.
|
||||
Assert.IsFalse(token.IsCancellationRequested);
|
||||
await view.DisposeAsync();
|
||||
Assert.IsTrue(token.IsCancellationRequested, "the press lasts as long as the view");
|
||||
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task AfterPaginaInizialeTheInputReachesTheBrowserAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => null, () => "http://127.0.0.1:8481/benvenuto");
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
|
||||
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
||||
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
bed.Cdp.ClearSent();
|
||||
await view.KeyAsync(new RemoteViewKey(RemoteViewKeyAction.Char, "a", "KeyA", "a", 0), ct);
|
||||
|
||||
Assert.IsTrue(bed.Cdp.Sent.Any(c => c.Method.StartsWith("Input.", StringComparison.Ordinal)), string.Join(", ", bed.Cdp.Sent.Select(c => c.Method)));
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task WithoutAStartPageTheButtonDoesNothing()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => null);
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
|
||||
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
|
||||
await StartPageOf(view).WaitAsync(TimeSpan.FromSeconds(10), ct);
|
||||
|
||||
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task IndietroNeverLandsOnTheEmptyRestPage()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = new Bed(_ => null);
|
||||
var view = await bed.Host.OpenAsync(ct);
|
||||
|
||||
// The view opened on the rest page; then a page, the rest page again (a session of the engine), another page.
|
||||
bed.Navigated("http://127.0.0.1:8481/profilo/marta.prova/");
|
||||
bed.Navigated("about:blank");
|
||||
bed.Navigated("http://127.0.0.1:8481/esplora/");
|
||||
|
||||
await view.NavigateAsync(RemoteViewNavigation.Back, ct);
|
||||
Assert.AreEqual("http://127.0.0.1:8481/profilo/marta.prova/", bed.LastNavigation, "the rest page in between is skipped");
|
||||
|
||||
// Before that only the rest page: «Indietro» stays where it is instead of turning the view white.
|
||||
bed.Cdp.ClearSent();
|
||||
await view.NavigateAsync(RemoteViewNavigation.Back, ct);
|
||||
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
|
||||
|
||||
await view.DisposeAsync();
|
||||
}
|
||||
|
||||
private static bool IsInputOrNavigation(string method) =>
|
||||
method.StartsWith("Input.", StringComparison.Ordinal) || method is "Page.navigate" or "Page.reload";
|
||||
|
||||
private static Task StartPageOf(IRemoteViewConnection view) => ((BrowserRemoteViewConnection)view).StartPageOpening;
|
||||
|
||||
private static CdpCommandException InactivePage() =>
|
||||
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage);
|
||||
|
||||
@@ -170,7 +295,12 @@ public sealed class RemoteViewStartTests
|
||||
private int _starts;
|
||||
|
||||
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
|
||||
public Bed(Func<int, Exception?> startFailure)
|
||||
/// <param name="startPage">
|
||||
/// Where «Pagina iniziale» goes, as the connection would open it (BrowserConnectionService.OpenStartPageAsync,
|
||||
/// tested in BrowserStartPageTests); null: nowhere.
|
||||
/// </param>
|
||||
/// <param name="open">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
|
||||
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null)
|
||||
{
|
||||
Clock = new VirtualClock();
|
||||
_start = Clock.Now;
|
||||
@@ -196,7 +326,11 @@ public sealed class RemoteViewStartTests
|
||||
};
|
||||
Browser = new PageBrowser(Cdp);
|
||||
_log = new FebeLog(null, null, Clock);
|
||||
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock);
|
||||
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)))
|
||||
{
|
||||
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
|
||||
Watchdog = null,
|
||||
};
|
||||
}
|
||||
|
||||
public VirtualClock Clock { get; }
|
||||
@@ -209,6 +343,13 @@ public sealed class RemoteViewStartTests
|
||||
|
||||
public int Starts => Volatile.Read(ref _starts);
|
||||
|
||||
/// <summary>The address of the last <c>Page.navigate</c>.</summary>
|
||||
public string? LastNavigation => Cdp.Sent.LastOrDefault(c => c.Method == "Page.navigate")?.Parameters?["url"]?.GetValue<string>();
|
||||
|
||||
/// <summary>The main frame committed a new document.</summary>
|
||||
public void Navigated(string url) =>
|
||||
Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } });
|
||||
|
||||
/// <summary>Time spent in the host's pauses (the virtual clock moves only there).</summary>
|
||||
public TimeSpan Elapsed => Clock.Now - _start;
|
||||
|
||||
|
||||
@@ -227,12 +227,15 @@ public sealed partial class ServerEndToEndTests
|
||||
TimeSpan.FromSeconds(60),
|
||||
"il motore di nuovo in funzione, in attesa del collegamento");
|
||||
|
||||
// «Ho finito» without having logged in: Febe says it does not find the session.
|
||||
// «Usa il browser» on the rest page, not connected (issue #52): never the white page, the login page. (The test
|
||||
// site sets its session on any visit, so «Ho finito» without a login is proved with the fake browser of
|
||||
// BrowserStartPageTests.)
|
||||
await connection.BeginUserDrivingAsync(openLogin: false, ct);
|
||||
Assert.IsTrue(server.Browser.UserIsDriving);
|
||||
var finish = await connection.FinishAsync(ct);
|
||||
Assert.IsFalse(finish.Connected);
|
||||
StringAssert.Contains(finish.Message, "non trova la sessione");
|
||||
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
|
||||
Assert.IsNotNull(opened);
|
||||
StringAssert.Contains(opened, "/benvenuto", "the login page of the test site");
|
||||
await connection.CancelAsync(ct);
|
||||
Assert.IsFalse(server.Browser.UserIsDriving);
|
||||
|
||||
// «Annulla» ends the driving and leaves the browser on the rest page.
|
||||
|
||||
@@ -24,11 +24,12 @@ internal static class SyntheticSite
|
||||
public static int Seed => ParseSeed(Environment.GetEnvironmentVariable(Variable));
|
||||
|
||||
/// <summary>Starts the test site with the seed of this run, and says which one in the output of the test.</summary>
|
||||
public static Task<TestSite> StartAsync()
|
||||
/// <param name="time">Clock of the site (dates, signed addresses); the system clock by default.</param>
|
||||
public static Task<TestSite> StartAsync(TimeProvider? time = null)
|
||||
{
|
||||
var seed = Seed;
|
||||
Console.WriteLine($"Sito di prova con il seme {seed.ToString(CultureInfo.InvariantCulture)} (si cambia con {Variable}).");
|
||||
return TestSite.StartAsync(new TestSiteOptions { Seed = seed });
|
||||
return TestSite.StartAsync(new TestSiteOptions { Seed = seed, Time = time ?? TimeProvider.System });
|
||||
}
|
||||
|
||||
/// <summary>The seed written in <paramref name="value"/>: the default when it is empty, an error when it is not a number.</summary>
|
||||
|
||||
@@ -62,6 +62,66 @@ public sealed class ConnectionApiTests
|
||||
CollectionAssert.AreEqual(new[] { "begin:True", "finish", "cancel", "disconnect" }, connection.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
|
||||
{
|
||||
// Docker: the remote view is the page, leaving it gives the browser back to rest.
|
||||
var docker = new RecordingConnection();
|
||||
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(docker)))
|
||||
{
|
||||
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, status);
|
||||
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
|
||||
|
||||
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
|
||||
var windows = new RecordingConnection();
|
||||
await using (var server = await Part2.StartAsync(services: s => s
|
||||
.AddSingleton<IConnectionService>(windows)
|
||||
.AddSingleton<Febe.Web.Native.IBrowserWindow>(new SeparateWindow())))
|
||||
{
|
||||
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
|
||||
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
|
||||
var (shown, message) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
|
||||
Assert.AreEqual(HttpStatusCode.OK, shown);
|
||||
StringAssert.Contains(message.Str("message"), "primo piano");
|
||||
await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show", new { openLogin = true });
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "release", "cancel", "show:False", "show:True" }, windows.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody()
|
||||
{
|
||||
// Chunked, as a body without Content-Length may come (HTTP/2 too): empty is the default, not a 400.
|
||||
var windows = new RecordingConnection();
|
||||
await using var server = await Part2.StartAsync(services: s => s
|
||||
.AddSingleton<IConnectionService>(windows)
|
||||
.AddSingleton<Febe.Web.Native.IBrowserWindow>(new SeparateWindow()));
|
||||
foreach (var (path, body) in new[]
|
||||
{
|
||||
("/api/connection/begin", ""),
|
||||
("/api/connection/cancel", ""),
|
||||
("/api/browser/show", ""),
|
||||
("/api/connection/cancel", """{"pageLeft":true}"""),
|
||||
("/api/browser/show", """{"openLogin":true}"""),
|
||||
})
|
||||
{
|
||||
using var request = server.Request(HttpMethod.Post, path);
|
||||
request.Content = new StreamContent(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(body)));
|
||||
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
|
||||
request.Headers.TransferEncodingChunked = true;
|
||||
using var response = await server.Client.SendAsync(request);
|
||||
Assert.IsTrue(response.IsSuccessStatusCode, $"{path} «{body}»: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "begin:False", "cancel", "show:False", "release", "show:True" }, windows.Calls);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CommandsFromAnotherPageAreRefused()
|
||||
{
|
||||
@@ -99,4 +159,10 @@ public sealed class ConnectionApiTests
|
||||
Assert.AreEqual(problem.Message, listed[0].Str("message"));
|
||||
Assert.AreEqual(problem.Remedy, listed[0].Str("remedy"));
|
||||
}
|
||||
|
||||
/// <summary>The browser as a window of its own, as on Windows.</summary>
|
||||
private sealed class SeparateWindow : Febe.Web.Native.IBrowserWindow
|
||||
{
|
||||
public bool IsSeparateWindow => true;
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,20 @@ internal sealed class RecordingConnection : IConnectionService
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct)
|
||||
{
|
||||
Record("show:" + openLogin);
|
||||
Status = Status with { UserIsDriving = true };
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task ReleaseAsync(CancellationToken ct)
|
||||
{
|
||||
Record("release");
|
||||
Status = Status with { UserIsDriving = false };
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisconnectAsync(CancellationToken ct)
|
||||
{
|
||||
Record("disconnect");
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Febe.SitoDiProva;
|
||||
|
||||
/// <summary>
|
||||
/// The answers to the site client of Febe (issue #36, spec §6.0, §14.2): the operations of <c>richieste.prova.json</c>,
|
||||
/// served under <c>/api/</c> in the request shape the catalog describes, with the same JSON the pages fetch from
|
||||
/// <c>/dati/</c>. Here the site checks what a real site checks: the session cookie, <c>x-csrftoken</c> equal to the
|
||||
/// cookie <c>csrftoken</c>, the headers and fields of the catalog. The pages keep their <c>/dati/</c>, which checks
|
||||
/// nothing, so the browser tests do not change.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// What a refused request gets is generic and marked H16: the true answers of Instagram to an expired session, a wrong
|
||||
/// token or a malformed request are not known from samples. A missing or ended session: a plain address gets 302 to
|
||||
/// <c>/accesso/</c>, a GraphQL query 401 with a short JSON. A wrong or missing <c>x-csrftoken</c>: 403 with an HTML page.
|
||||
/// A missing header, an unknown <c>doc_id</c>, a field or variables that do not match: 400 with a short JSON.
|
||||
/// </remarks>
|
||||
public sealed partial class TestSite
|
||||
{
|
||||
/// <summary>Name of the cookie whose value goes in <c>x-csrftoken</c>.</summary>
|
||||
public const string CsrfCookie = "csrftoken";
|
||||
|
||||
/// <summary>The value of <c>x-app-id</c> the pages of the site would send (a value of the page, session:app_id).</summary>
|
||||
public const string AppId = "prova-applicazione-1";
|
||||
|
||||
/// <summary>The token <c>lsd</c> the pages of the site would hold (session:lsd).</summary>
|
||||
public const string Lsd = "lsd-di-prova";
|
||||
|
||||
/// <summary>The token <c>fb_dtsg</c> the pages of the site would hold (session:fb_dtsg).</summary>
|
||||
public const string Dtsg = "dtsg-di-prova";
|
||||
|
||||
/// <summary>The GraphQL query of the site: a profile page, with the JSON of <c>/dati/profilo/{nome}</c>.</summary>
|
||||
public const string ProfileQuery = "ProvaProfiloQuery";
|
||||
|
||||
/// <summary>The <c>doc_id</c> of each GraphQL query, as the modules of the pages would hold them (session:doc_id).</summary>
|
||||
public static IReadOnlyDictionary<string, string> DocIds { get; } =
|
||||
new Dictionary<string, string> { [ProfileQuery] = "8000000000000001" }.ToFrozenDictionary(StringComparer.Ordinal);
|
||||
|
||||
private const string Html = "<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Sito di prova</title></head><body><p>Una pagina, non dati.</p></body></html>";
|
||||
|
||||
private async Task DirectAsync(HttpContext context, string path)
|
||||
{
|
||||
var request = context.Request;
|
||||
var (reply, mode) = Control.OnDirectRequest($"{request.Method} {path}{request.QueryString.Value}");
|
||||
try
|
||||
{
|
||||
if (Control.DirectDelay > TimeSpan.Zero)
|
||||
{
|
||||
await Task.Delay(Control.DirectDelay, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (await StopAsync(context, path, reply, mode).ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var isGraphQl = path == "/api/graphql";
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
if (!isGraphQl && segments is not ["api", "dati", ..])
|
||||
{
|
||||
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isGraphQl ? !HttpMethods.IsPost(request.Method) : !HttpMethods.IsGet(request.Method))
|
||||
{
|
||||
// A write (POST of a plain address) or a GET of the GraphQL entry: no site answers it with data.
|
||||
await JsonAsync(context, 405, new JsonObject { ["errore"] = "metodo" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var session = request.Cookies[SessionCookie];
|
||||
if (!Control.IsSession(session))
|
||||
{
|
||||
// H16-generic: what Instagram answers to a missing or ended session is not known from samples.
|
||||
if (isGraphQl)
|
||||
{
|
||||
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione", ["accesso_richiesto"] = true }).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
context.Response.Redirect("/accesso/?next=" + Uri.EscapeDataString(path));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var csrf = request.Cookies[CsrfCookie];
|
||||
if (string.IsNullOrEmpty(csrf) || request.Headers["x-csrftoken"].ToString() != csrf)
|
||||
{
|
||||
// H16-generic: a token missing or different from its cookie.
|
||||
await HtmlAsync(context, 403, "<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Vietato</title></head><body><h1>Verifica del gettone non riuscita</h1></body></html>").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(request.Headers.UserAgent.ToString())
|
||||
|| request.Headers.Accept.Count == 0
|
||||
|| request.Headers["x-app-id"].ToString() != AppId)
|
||||
{
|
||||
await BadRequestAsync(context, "intestazioni").ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
JsonObject? data;
|
||||
if (isGraphQl)
|
||||
{
|
||||
var (problem, answer) = await GraphQlAsync(request).ConfigureAwait(false);
|
||||
if (problem is not null)
|
||||
{
|
||||
await BadRequestAsync(context, problem).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
data = answer;
|
||||
}
|
||||
else if (segments is ["api", "dati", "cerca"])
|
||||
{
|
||||
lock (World.Gate)
|
||||
{
|
||||
data = Api.Search(request.Query["testo"].ToString());
|
||||
}
|
||||
}
|
||||
else if (segments is ["api", "dati", "ricerche-recenti"])
|
||||
{
|
||||
// Read only: the site client never writes (a POST was refused above).
|
||||
lock (World.Gate)
|
||||
{
|
||||
data = Api.RecentSearches([.. World.Following.Take(3).Select(a => a.Username)]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
data = Lookup(segments[1..], request.Query);
|
||||
}
|
||||
|
||||
if (data is null)
|
||||
{
|
||||
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
Decorate(context, reply, session!);
|
||||
await JsonAsync(context, 200, data).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Control.OnDirectFinished();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The stop cases, before any check: the reply the tests asked for, or the mode of the whole site.</summary>
|
||||
private async Task<bool> StopAsync(HttpContext context, string path, DirectReply reply, StopMode mode)
|
||||
{
|
||||
if (reply == DirectReply.TooManyRequests || (reply == DirectReply.Normal && mode == StopMode.TooManyRequests))
|
||||
{
|
||||
context.Response.Headers.RetryAfter = "60";
|
||||
await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (reply == DirectReply.RedirectToChallenge || (reply == DirectReply.Normal && mode == StopMode.Challenge))
|
||||
{
|
||||
context.Response.Redirect("/verifica?motivo=prova&next=" + Uri.EscapeDataString(path));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (reply == DirectReply.RedirectToLogin || (reply == DirectReply.Normal && mode == StopMode.SessionEnded))
|
||||
{
|
||||
if (mode == StopMode.SessionEnded)
|
||||
{
|
||||
// The session ends on the site too: a client that kept the cookie gets the login page after it.
|
||||
EndSession(context);
|
||||
}
|
||||
|
||||
context.Response.Redirect("/accesso/?next=" + Uri.EscapeDataString(path));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (reply == DirectReply.HtmlInsteadOfJson)
|
||||
{
|
||||
await HtmlAsync(context, 200, Html).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (reply == DirectReply.MissingRootField || (reply == DirectReply.Normal && mode == StopMode.UnknownFormat))
|
||||
{
|
||||
await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (reply == DirectReply.Normal && mode == StopMode.EmptyPages)
|
||||
{
|
||||
await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The GraphQL query: form fields, <c>doc_id</c>, friendly name, tokens and variables as the pages would send them.
|
||||
/// Returns why it is refused, or the data.
|
||||
/// </summary>
|
||||
private async Task<(string? Problem, JsonObject? Data)> GraphQlAsync(HttpRequest request)
|
||||
{
|
||||
if (!request.HasFormContentType || request.ContentType?.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != true)
|
||||
{
|
||||
return ("tipo", null);
|
||||
}
|
||||
|
||||
var form = await request.ReadFormAsync().ConfigureAwait(false);
|
||||
var docId = form["doc_id"].ToString();
|
||||
var name = form["fb_api_req_friendly_name"].ToString();
|
||||
if (!DocIds.TryGetValue(name, out var expected) || expected != docId || request.Headers["x-fb-friendly-name"].ToString() != name)
|
||||
{
|
||||
return ("doc_id", null);
|
||||
}
|
||||
|
||||
if (form["lsd"].ToString() != Lsd || form["fb_dtsg"].ToString() != Dtsg || form["__a"].ToString() != "1"
|
||||
|| string.IsNullOrEmpty(request.Headers["x-ig-www-claim"].ToString()))
|
||||
{
|
||||
return ("campi", null);
|
||||
}
|
||||
|
||||
JsonObject variables;
|
||||
try
|
||||
{
|
||||
variables = JsonNode.Parse(form["variables"].ToString()) as JsonObject ?? throw new JsonException();
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return ("variabili", null);
|
||||
}
|
||||
|
||||
// ProvaProfiloQuery: {"username": text, "scheda": "post" | "reel" | "taggati", "primi": 12, "raccolte": true | false}.
|
||||
if (variables.Count != 4
|
||||
|| variables["username"] is not JsonValue user || user.GetValueKind() != JsonValueKind.String
|
||||
|| variables["scheda"] is not JsonValue tab || tab.GetValueKind() != JsonValueKind.String
|
||||
|| variables["primi"] is not JsonValue first || first.GetValueKind() != JsonValueKind.Number || first.ToJsonString() != "12"
|
||||
|| variables["raccolte"] is not JsonValue highlights || highlights.GetValueKind() is not (JsonValueKind.True or JsonValueKind.False))
|
||||
{
|
||||
return ("variabili", null);
|
||||
}
|
||||
|
||||
var profileTab = tab.GetValue<string>() switch
|
||||
{
|
||||
"post" => ProfileTab.Posts,
|
||||
"reel" => ProfileTab.Reels,
|
||||
"taggati" => ProfileTab.Tagged,
|
||||
_ => (ProfileTab?)null,
|
||||
};
|
||||
if (profileTab is null)
|
||||
{
|
||||
return ("variabili", null);
|
||||
}
|
||||
|
||||
lock (World.Gate)
|
||||
{
|
||||
return (null, Api.Profile(user.GetValue<string>(), profileTab.Value, null));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a normal answer carries besides the data, when the tests asked for it.</summary>
|
||||
private void Decorate(HttpContext context, DirectReply reply, string session)
|
||||
{
|
||||
switch (reply)
|
||||
{
|
||||
case DirectReply.RenewSessionCookie:
|
||||
context.Response.Cookies.Append(SessionCookie, Control.RenewSession(session), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
|
||||
break;
|
||||
case DirectReply.DeleteSessionCookie:
|
||||
EndSession(context);
|
||||
break;
|
||||
case DirectReply.SetClaim:
|
||||
context.Response.Headers["x-ig-set-www-claim"] = Control.NextClaim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static Task BadRequestAsync(HttpContext context, string what) =>
|
||||
JsonAsync(context, 400, new JsonObject { ["errore"] = "richiesta-non-valida", ["dove"] = what });
|
||||
}
|
||||
@@ -101,6 +101,53 @@ pagina { altro, dopo }
|
||||
chiave, stessa immagine a ogni dimensione); i video sono due MP4 minuscoli generati una volta con ffmpeg
|
||||
(`Risorse/filmato-con-audio.mp4`, `Risorse/filmato-muto.mp4`), resi unici aggiungendo in coda un riquadro `free`.
|
||||
|
||||
## Richieste dirette del client del sito (issue #36)
|
||||
|
||||
Dalla tappa S2 il sito risponde anche al **client del sito** di Febe (`HttpSiteRequester`, specifica §6.0), che chiede i
|
||||
dati senza browser con la sessione copiata. Le operazioni sono quelle di `src/Febe.Core/Config/richieste.prova.json`,
|
||||
servite sotto `/api/` con lo **stesso JSON** che le pagine leggono da `/dati/`. Le pagine continuano a chiedere `/dati/`,
|
||||
che non controlla nulla: per il browser non cambia niente.
|
||||
|
||||
| Richiesta | Risposta |
|
||||
|---|---|
|
||||
| `GET /api/dati/...` | lo stesso indirizzo e la stessa risposta di `/dati/...` (tabella sopra) |
|
||||
| `POST /api/graphql` | la richiesta GraphQL `ProvaProfiloQuery`: modulo `application/x-www-form-urlencoded` con `doc_id`, `fb_api_req_friendly_name`, `variables`, `lsd`, `fb_dtsg`, `__a=1`, `av`; risponde con il JSON di `/dati/profilo/{nome}?scheda=...` |
|
||||
| un'altra richiesta sotto `/api/` | 404; un `POST` di un indirizzo semplice o un `GET` di `/api/graphql`: 405 (il client non scrive mai) |
|
||||
|
||||
Su `/api/` il sito controlla quello che controlla un sito vero, nell'ordine:
|
||||
|
||||
1. il cookie `sessione_prova` con un valore che il sito ha dato e non ha chiuso: quello che le pagine danno a una visita
|
||||
senza sessione viva (`aperta-1`, `aperta-2`…), un valore rinnovato (`rinnovata-1`…), oppure `attiva`
|
||||
(`SiteControl.InitialSession`), una sessione già aperta all'avvio e dopo `/_controllo/reimposta`, che le pagine non
|
||||
danno mai e che usano le prove che preparano una sessione salvata senza il browser;
|
||||
2. l'intestazione `x-csrftoken` uguale al cookie `csrftoken`;
|
||||
3. `user-agent` non vuoto, `accept` presente, `x-app-id` uguale a `prova-applicazione-1`;
|
||||
4. per `/api/graphql`: `content-type`, il `doc_id` della query (`ProvaProfiloQuery` = `8000000000000001`) con lo stesso
|
||||
nome in `fb_api_req_friendly_name` e in `x-fb-friendly-name`, `lsd` = `lsd-di-prova`, `fb_dtsg` = `dtsg-di-prova`,
|
||||
`x-ig-www-claim` presente (il client manda `0`, come la pagina, finché il sito non ne dà uno), e le variabili con i
|
||||
loro tipi: `{"username": testo, "scheda": "post"|"reel"|"taggati", "primi": 12 (numero), "raccolte": vero/falso}`.
|
||||
|
||||
I valori sono costanti di `TestSite` (`AppId`, `Lsd`, `Dtsg`, `DocIds`, `CsrfCookie`). Le pagine del sito **non danno
|
||||
ancora** nessuno di questi valori: né il cookie `csrftoken`, né `app_id`, `lsd`, `fb_dtsg`, il `doc_id` della query o un
|
||||
claim. Per ora li mettono le prove nella sessione salvata (`InMemorySiteSession`); perché una sessione copiata dal
|
||||
browser di prova passi i controlli, la tappa S4 deve farli esporre alle pagine (un cookie e i moduli, come su
|
||||
Instagram). Le risposte a una richiesta che non passa i controlli sono **generiche e marcate H16**: non si sa ancora
|
||||
che cosa risponde Instagram a una sessione scaduta, a un gettone sbagliato o a una richiesta malformata.
|
||||
|
||||
| Controllo non passato | Risposta (H16, generica) |
|
||||
|---|---|
|
||||
| sessione mancante o chiusa | indirizzo semplice: `302` a `/accesso/?next=...`; GraphQL: `401` con `{"errore":"sessione","accesso_richiesto":true}` |
|
||||
| `x-csrftoken` mancante o diverso dal cookie | `403` con una pagina HTML |
|
||||
| intestazione, `doc_id`, campo o variabili che non tornano | `400` con `{"errore":"richiesta-non-valida","dove":...}` |
|
||||
|
||||
I modi di tutto il sito (`/_controllo/modo`) valgono anche qui: `troppe-richieste` dà 429, `verifica` un rinvio a
|
||||
`/verifica`, `sessione-scaduta` chiude la sessione anche sul sito, cancella il cookie e rinvia a `/accesso/`, `vuoto` e
|
||||
`formato-sconosciuto` come per `/dati/`. Un modo armato «dopo N richieste di dati» (`/_controllo/modo?dopo=N`,
|
||||
`Control.Set(modo, afterDataRequests: N)`) conta anche le richieste del client del sito, come quelle delle pagine. Le
|
||||
richieste del client si elencano a parte (`DirectRequests`), non fra quelle delle pagine (`DataRequests`).
|
||||
Le visite di `/accesso…` e `/verifica…` si contano (`LoginPageVisits`, `ChallengePageVisits`): un rinvio seguito
|
||||
lascerebbe il segno. `/accesso` resta una pagina che non esiste (404): il sito non ha moduli d'accesso.
|
||||
|
||||
## Casi di arresto e comandi per le prove
|
||||
|
||||
Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...` sul sito.
|
||||
@@ -109,7 +156,7 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
|
||||
|---|---|
|
||||
| `/_controllo/modo?valore=troppe-richieste[&dopo=N]` | le richieste di dati ricevono 429 (dopo N richieste) |
|
||||
| `/_controllo/modo?valore=verifica` | le pagine rimandano a `/verifica`; i dati rispondono 403 e la pagina ci va da sola |
|
||||
| `/_controllo/modo?valore=sessione-scaduta` | il cookie `sessione_prova` si cancella e le pagine vanno a `/sessione-scaduta` |
|
||||
| `/_controllo/modo?valore=sessione-scaduta` | il cookie `sessione_prova` si cancella e le pagine vanno a `/sessione-scaduta`; la sessione si chiude anche sul sito, così lo stesso valore copiato nel client del sito non vale più |
|
||||
| `/_controllo/modo?valore=vuoto` | le pagine di dati arrivano vuote |
|
||||
| `/_controllo/modo?valore=formato-sconosciuto` | i dati arrivano in una forma che nessun lettore conosce |
|
||||
| `/_controllo/modo?valore=normale`, `/_controllo/reimposta` | tutto torna normale |
|
||||
@@ -123,6 +170,11 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
|
||||
| `/_controllo/ricerca/disordine?valore=si\|no` | le risposte ai testi più corti arrivano più tardi (fuori ordine) |
|
||||
| `/_controllo/ricerca/memoria?valore=si\|no` | il pannello ricorda il testo quando si richiude, come Instagram |
|
||||
| `/_controllo/ricerca/recenti` | quante ricerche recenti sono state scritte |
|
||||
| `/_controllo/stato` | modo attuale e numero di richieste di dati |
|
||||
| `/_controllo/diretto?valore=troppe-richieste\|accesso\|verifica\|html\|senza-campi\|rinnova-cookie\|cancella-cookie\|claim\|normale[&sempre=si]` | la prossima richiesta del client del sito (con `sempre=si` tutte) riceve: 429 con `Retry-After: 60`; 302 a `/accesso/`; 302 a `/verifica`; una pagina HTML al posto del JSON; un JSON senza i campi attesi; i dati con un `Set-Cookie` che rinnova `sessione_prova` (il valore vecchio smette di valere); i dati con un `Set-Cookie` che lo cancella (la sessione finisce); i dati con un nuovo `x-ig-set-www-claim`. Dentro il processo: `site.Control.ReplyToDirect(DirectReply...)` |
|
||||
| `/_controllo/diretto/ritardo?ms=` | ritardo di ogni risposta al client del sito (`Control.DirectDelay`); `Control.MaxDirectInFlight` dice quante ne ha servite insieme al massimo |
|
||||
| `/_controllo/stato` | modo attuale, numero di richieste di dati delle pagine e del client del sito, visite delle pagine di accesso e di verifica |
|
||||
|
||||
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla prima visita di una pagina.
|
||||
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla visita di una pagina senza una
|
||||
sessione viva, cioè senza cookie o con un valore che il sito ha chiuso (sessione scaduta, cookie cancellato dal client
|
||||
del sito, reimpostazione). Ogni visita così è un nuovo accesso, con un valore nuovo che vale anche per `/api/`: dopo
|
||||
`sessione-scaduta` e poi `normale`, rivisitare una pagina riapre la sessione.
|
||||
@@ -24,11 +24,56 @@ public enum StopMode
|
||||
UnknownFormat,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the site answers to the next request of the site client (<c>/api/…</c>, issue #36) instead of the data: the stop
|
||||
/// cases of spec §7.6 and the renewals the client must keep. The shapes not known from samples are generic (H16).
|
||||
/// </summary>
|
||||
public enum DirectReply
|
||||
{
|
||||
/// <summary>The data, after the checks of a real site.</summary>
|
||||
Normal,
|
||||
|
||||
/// <summary>429 with a short JSON and <c>Retry-After: 60</c> (Rallentamento).</summary>
|
||||
TooManyRequests,
|
||||
|
||||
/// <summary>302 to the login page <c>/accesso/</c> (H16-generic).</summary>
|
||||
RedirectToLogin,
|
||||
|
||||
/// <summary>302 to the challenge page <c>/verifica</c> (H16-generic).</summary>
|
||||
RedirectToChallenge,
|
||||
|
||||
/// <summary>200 with an HTML document where JSON is expected (H16-generic).</summary>
|
||||
HtmlInsteadOfJson,
|
||||
|
||||
/// <summary>200 with a JSON that has none of the expected root fields (H16-generic).</summary>
|
||||
MissingRootField,
|
||||
|
||||
/// <summary>The data, with a <c>Set-Cookie</c> that renews the session cookie (new value, the old one stops working).</summary>
|
||||
RenewSessionCookie,
|
||||
|
||||
/// <summary>The data, with a <c>Set-Cookie</c> that deletes the session cookie (the session ends).</summary>
|
||||
DeleteSessionCookie,
|
||||
|
||||
/// <summary>The data, with a new <c>x-ig-set-www-claim</c>.</summary>
|
||||
SetClaim,
|
||||
}
|
||||
|
||||
/// <summary>Switches and counters of the test site. Thread-safe.</summary>
|
||||
public sealed class SiteControl
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly ConcurrentQueue<string> _dataRequests = new();
|
||||
private readonly ConcurrentQueue<string> _directRequests = new();
|
||||
private readonly ConcurrentQueue<DirectReply> _directReplies = new();
|
||||
private readonly HashSet<string> _sessions = new(StringComparer.Ordinal) { InitialSession };
|
||||
private DirectReply _directAlways = DirectReply.Normal;
|
||||
private int _directInFlight;
|
||||
private int _maxDirectInFlight;
|
||||
private int _loginVisits;
|
||||
private int _challengeVisits;
|
||||
private int _renewals;
|
||||
private int _logins;
|
||||
private int _claims;
|
||||
private StopMode _mode = StopMode.Normal;
|
||||
private int _armAfter;
|
||||
|
||||
@@ -76,6 +121,140 @@ public sealed class SiteControl
|
||||
/// </summary>
|
||||
public int RecentSearchWrites => _recentSearchWrites;
|
||||
|
||||
/// <summary>
|
||||
/// A session already open when the site starts and after <see cref="Reset"/>, as one opened before the test: the
|
||||
/// tests that build a saved session without the browser use it. The pages never hand it out: a visit without a live
|
||||
/// session gets a new value (<see cref="OpenSession"/>).
|
||||
/// </summary>
|
||||
public const string InitialSession = "attiva";
|
||||
|
||||
/// <summary>Method, path and query of every request of the site client (<c>/api/…</c>), in arrival order.</summary>
|
||||
public IReadOnlyList<string> DirectRequests => [.. _directRequests];
|
||||
|
||||
/// <summary>The most requests of the site client the site was answering at the same time.</summary>
|
||||
public int MaxDirectInFlight => Volatile.Read(ref _maxDirectInFlight);
|
||||
|
||||
/// <summary>Extra wait before every answer to the site client (slow answers).</summary>
|
||||
public TimeSpan DirectDelay { get; set; }
|
||||
|
||||
/// <summary>Requests of the login page <c>/accesso…</c> (a redirect followed would land there).</summary>
|
||||
public int LoginPageVisits => Volatile.Read(ref _loginVisits);
|
||||
|
||||
/// <summary>Requests of the challenge page <c>/verifica…</c>.</summary>
|
||||
public int ChallengePageVisits => Volatile.Read(ref _challengeVisits);
|
||||
|
||||
/// <summary>The site client answers to the next request (or, with <paramref name="always"/>, to every one) with <paramref name="reply"/>.</summary>
|
||||
public void ReplyToDirect(DirectReply reply, bool always = false)
|
||||
{
|
||||
if (always)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_directAlways = reply;
|
||||
}
|
||||
|
||||
_directReplies.Clear();
|
||||
return;
|
||||
}
|
||||
|
||||
_directReplies.Enqueue(reply);
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="value"/> is a session cookie the site handed out and did not end.</summary>
|
||||
public bool IsSession(string? value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return value is { Length: > 0 } && _sessions.Contains(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new session, as a new login opens: its value works for the pages and for the site client.</summary>
|
||||
internal string OpenSession()
|
||||
{
|
||||
var opened = "aperta-" + Interlocked.Increment(ref _logins).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
lock (_gate)
|
||||
{
|
||||
_sessions.Add(opened);
|
||||
}
|
||||
|
||||
return opened;
|
||||
}
|
||||
|
||||
/// <summary>A new value of the session cookie in place of <paramref name="old"/>, which stops working.</summary>
|
||||
internal string RenewSession(string old)
|
||||
{
|
||||
var renewed = "rinnovata-" + Interlocked.Increment(ref _renewals).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
lock (_gate)
|
||||
{
|
||||
_sessions.Remove(old);
|
||||
_sessions.Add(renewed);
|
||||
}
|
||||
|
||||
return renewed;
|
||||
}
|
||||
|
||||
/// <summary>Ends the session <paramref name="value"/>.</summary>
|
||||
internal void EndSession(string value)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_sessions.Remove(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A new claim value.</summary>
|
||||
internal string NextClaim() => "claim-prova-" + Interlocked.Increment(ref _claims).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>
|
||||
/// Records a request of the site client and returns the reply it gets and the mode of the site that applies to it:
|
||||
/// a request of the site client counts as a data request for <see cref="Set"/> with <c>afterDataRequests</c>, as a
|
||||
/// page's <c>/dati/</c> does. Pair with <see cref="OnDirectFinished"/>.
|
||||
/// </summary>
|
||||
internal (DirectReply Reply, StopMode Mode) OnDirectRequest(string methodPathAndQuery)
|
||||
{
|
||||
_directRequests.Enqueue(methodPathAndQuery);
|
||||
var now = Interlocked.Increment(ref _directInFlight);
|
||||
int max;
|
||||
while (now > (max = Volatile.Read(ref _maxDirectInFlight)) && Interlocked.CompareExchange(ref _maxDirectInFlight, now, max) != max)
|
||||
{
|
||||
}
|
||||
|
||||
StopMode mode;
|
||||
DirectReply always;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_armAfter > 0)
|
||||
{
|
||||
_armAfter--;
|
||||
mode = StopMode.Normal;
|
||||
}
|
||||
else
|
||||
{
|
||||
mode = _mode;
|
||||
}
|
||||
|
||||
always = _directAlways;
|
||||
}
|
||||
|
||||
return (_directReplies.TryDequeue(out var next) ? next : always, mode);
|
||||
}
|
||||
|
||||
internal void OnDirectFinished() => Interlocked.Decrement(ref _directInFlight);
|
||||
|
||||
/// <summary>Counts the visits of the login and challenge pages.</summary>
|
||||
internal void OnPageVisit(string path)
|
||||
{
|
||||
if (path.StartsWith("/accesso", StringComparison.Ordinal))
|
||||
{
|
||||
Interlocked.Increment(ref _loginVisits);
|
||||
}
|
||||
else if (path.StartsWith("/verifica", StringComparison.Ordinal))
|
||||
{
|
||||
Interlocked.Increment(ref _challengeVisits);
|
||||
}
|
||||
}
|
||||
|
||||
public StopMode Mode
|
||||
{
|
||||
get
|
||||
@@ -107,6 +286,19 @@ public sealed class SiteControl
|
||||
}
|
||||
|
||||
_dataRequests.Clear();
|
||||
_directRequests.Clear();
|
||||
_directReplies.Clear();
|
||||
lock (_gate)
|
||||
{
|
||||
_directAlways = DirectReply.Normal;
|
||||
_sessions.Clear();
|
||||
_sessions.Add(InitialSession);
|
||||
}
|
||||
|
||||
DirectDelay = TimeSpan.Zero;
|
||||
Interlocked.Exchange(ref _maxDirectInFlight, 0);
|
||||
Interlocked.Exchange(ref _loginVisits, 0);
|
||||
Interlocked.Exchange(ref _challengeVisits, 0);
|
||||
StoryDuration = TimeSpan.FromSeconds(5);
|
||||
AddressLifetime = TimeSpan.FromHours(6);
|
||||
CdnTooManyRequests = false;
|
||||
|
||||
@@ -38,7 +38,7 @@ public sealed record TestSiteOptions
|
||||
/// fetch JSON in a synthetic format of our own; stop cases are switched through <see cref="Control"/> or the
|
||||
/// <c>/_controllo</c> endpoints. Never Instagram, never anything that looks like it.
|
||||
/// </summary>
|
||||
public sealed class TestSite : IAsyncDisposable
|
||||
public sealed partial class TestSite : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Name of the session cookie of the site.</summary>
|
||||
public const string SessionCookie = "sessione_prova";
|
||||
@@ -165,12 +165,19 @@ public sealed class TestSite : IAsyncDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
if (path.StartsWith("/api/", StringComparison.Ordinal))
|
||||
{
|
||||
await DirectAsync(context, path).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await PageAsync(context, path).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task PageAsync(HttpContext context, string path)
|
||||
{
|
||||
var mode = Control.Mode;
|
||||
Control.OnPageVisit(path);
|
||||
if (path is "/verifica" or "/verifica/")
|
||||
{
|
||||
await HtmlAsync(context, 200, Pages.Challenge()).ConfigureAwait(false);
|
||||
@@ -195,14 +202,16 @@ public sealed class TestSite : IAsyncDisposable
|
||||
context.Response.Redirect("/verifica?motivo=prova");
|
||||
return;
|
||||
case StopMode.SessionEnded:
|
||||
ExpireSession(context);
|
||||
EndSession(context);
|
||||
context.Response.Redirect("/sessione-scaduta");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.Request.Cookies.ContainsKey(SessionCookie))
|
||||
if (!Control.IsSession(context.Request.Cookies[SessionCookie]))
|
||||
{
|
||||
context.Response.Cookies.Append(SessionCookie, "attiva", new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
|
||||
// No cookie, or one the site ended (a session that expired, a reset): the visit is a new login, with a new
|
||||
// value that the site client accepts too once copied.
|
||||
context.Response.Cookies.Append(SessionCookie, Control.OpenSession(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
@@ -272,7 +281,7 @@ public sealed class TestSite : IAsyncDisposable
|
||||
await JsonAsync(context, 403, new JsonObject { ["errore"] = "verifica" }).ConfigureAwait(false);
|
||||
return;
|
||||
case StopMode.SessionEnded:
|
||||
ExpireSession(context);
|
||||
EndSession(context);
|
||||
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione" }).ConfigureAwait(false);
|
||||
return;
|
||||
case StopMode.EmptyPages:
|
||||
@@ -310,13 +319,28 @@ public sealed class TestSite : IAsyncDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
var result = Lookup(segments, query);
|
||||
if (result is null)
|
||||
{
|
||||
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The JSON of a data address (<c>/dati/…</c> for the pages, the same under <c>/api/dati/…</c> for the site client),
|
||||
/// by its segments from «dati» on; null when there is nothing there.
|
||||
/// </summary>
|
||||
private JsonObject? Lookup(string[] segments, IQueryCollection query)
|
||||
{
|
||||
var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts };
|
||||
var after = query["dopo"].ToString();
|
||||
JsonObject? result;
|
||||
lock (World.Gate)
|
||||
{
|
||||
var api = Api;
|
||||
result = segments switch
|
||||
return segments switch
|
||||
{
|
||||
["dati", "inizio"] => api.Home(),
|
||||
["dati", "inizio", "altri"] => api.HomeMore(after),
|
||||
@@ -329,14 +353,6 @@ public sealed class TestSite : IAsyncDisposable
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
if (result is null)
|
||||
{
|
||||
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The answer of the search box, after the waits the control asks for (slow, out of order).</summary>
|
||||
@@ -415,6 +431,28 @@ public sealed class TestSite : IAsyncDisposable
|
||||
case "stato":
|
||||
answer["modo"] = Control.Mode.ToString();
|
||||
answer["richieste"] = Control.DataRequests.Count;
|
||||
answer["dirette"] = Control.DirectRequests.Count;
|
||||
answer["accesso"] = Control.LoginPageVisits;
|
||||
answer["verifica"] = Control.ChallengePageVisits;
|
||||
break;
|
||||
case "diretto":
|
||||
var reply = q["valore"].ToString() switch
|
||||
{
|
||||
"troppe-richieste" => DirectReply.TooManyRequests,
|
||||
"accesso" => DirectReply.RedirectToLogin,
|
||||
"verifica" => DirectReply.RedirectToChallenge,
|
||||
"html" => DirectReply.HtmlInsteadOfJson,
|
||||
"senza-campi" => DirectReply.MissingRootField,
|
||||
"rinnova-cookie" => DirectReply.RenewSessionCookie,
|
||||
"cancella-cookie" => DirectReply.DeleteSessionCookie,
|
||||
"claim" => DirectReply.SetClaim,
|
||||
_ => DirectReply.Normal,
|
||||
};
|
||||
Control.ReplyToDirect(reply, always: q["sempre"].ToString() is "si" or "sì" or "true");
|
||||
answer["risposta"] = reply.ToString();
|
||||
break;
|
||||
case "diretto/ritardo":
|
||||
Control.DirectDelay = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "modo":
|
||||
var mode = q["valore"].ToString() switch
|
||||
@@ -509,8 +547,19 @@ public sealed class TestSite : IAsyncDisposable
|
||||
await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static void ExpireSession(HttpContext context) =>
|
||||
/// <summary>
|
||||
/// The session of the request ends on the site (pages and site client alike) and its cookie is deleted: a copy of
|
||||
/// the same value held elsewhere stops working too.
|
||||
/// </summary>
|
||||
private void EndSession(HttpContext context)
|
||||
{
|
||||
if (context.Request.Cookies[SessionCookie] is { Length: > 0 } ended)
|
||||
{
|
||||
Control.EndSession(ended);
|
||||
}
|
||||
|
||||
context.Response.Cookies.Delete(SessionCookie, new CookieOptions { Path = "/" });
|
||||
}
|
||||
|
||||
private static Task HtmlAsync(HttpContext context, int status, string html)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user