Ricerca dei profili con suggerimenti e foto (#37)
«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono subito i suggerimenti locali, poi i profili di Instagram con la foto, come chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima il fuoco, legge la risposta della pagina e non clicca mai un risultato. La ricerca ha una categoria propria nel Governatore, con tetti larghi che non consumano quelli della raccolta, e si dà il turno con il motore sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le foto passano dal CDN con un permesso ciascuna e restano solo in memoria. Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli search-open e search-box saranno raccolti dal vivo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5e417c666d
commit
9941a2fa1f
98 files changed
+8021
-229
No files matched your search
+19
-9
@@ -132,7 +132,13 @@ Sono scelte fatte al posto di Alberto per poter scrivere una specifica coerente.
|
||||
|
||||
### 4.2 Account da seguire
|
||||
|
||||
- Si aggiungono in due modi (mockup 04): scegliendoli dall'elenco dei profili che Alberto segue, oppure scrivendo o incollando nomi utente e indirizzi di profilo, uno per riga. Il secondo modo serve per i profili pubblici che non segue.
|
||||
- Si aggiungono da **una sola casella di ricerca** (mockup 04, issue #37), come in 4K Stogram. Mentre Alberto scrive, sotto la casella compare un elenco di suggerimenti che si aggiorna a ogni lettera: prima, subito, i profili che segue e gli account già in Febe il cui nome utente o nome completo contiene il testo; poi, appena arrivano, i profili che trova Instagram. Ogni riga ha la foto del profilo, il nome utente, il nome completo e le etichette «Seguito», «Privato», «Già in Febe»; un profilo trovato sia in locale sia su Instagram compare una volta sola.
|
||||
- Le etichette vengono solo dai dati di Febe (elenco dei seguiti, account): la risposta di Instagram non dice se un profilo è privato o seguito.
|
||||
- Su Instagram cerca il browser di Febe, nel pannello «Cerca» del sito (§6.3, «Ricerca dei profili»), e ne scarica le foto (§6.5): la pagina di Febe chiede tutto a Febe, mai a Instagram. Si cercano solo profili, niente hashtag né luoghi.
|
||||
- «Aggiungi» mette il profilo in «Da aggiungere»; un profilo «Già in Febe» non si aggiunge una seconda volta, neanche se ha cambiato nome (si riconosce dall'identificativo). Frecce, Invio ed Esc funzionano nell'elenco; la riga «Aggiungi @nome per nome utente» aggiunge il nome scritto anche se non compare fra i risultati.
|
||||
- Nella stessa casella si possono **incollare più nomi** utente o indirizzi di profilo, uno per riga o separati da virgole: vanno tutti in «Da aggiungere», con i nomi non validi spiegati. Gli spazi da soli non separano: «mario rossi» si cerca.
|
||||
- Quando la ricerca su Instagram non è possibile (Alberto usa il browser, browser spento, fuori fascia, tetto della ricerca raggiunto, un arresto di §7.6, bersagli da configurare), una riga sotto «Da Instagram» lo dice; i suggerimenti locali funzionano sempre.
|
||||
- «Scegli fra tutti i profili che segui» apre al posto di «Da aggiungere» l'elenco completo dei seguiti con le caselle di spunta e «Seleziona tutti»; la casella in alto lo filtra.
|
||||
- L'elenco dei profili seguiti si legge a ritmo umano, dentro i tetti: può richiedere più sessioni. La finestra mostra a che punto è («Letti 96 profili, continuo alla prossima sessione») e lavora su ciò che ha. L'elenco resta in memoria locale con la data di lettura e si rilegge solo su richiesta.
|
||||
- Aggiungendo account si sceglie uno di tre punti di partenza, che poi si cambiano account per account:
|
||||
|
||||
@@ -318,8 +324,8 @@ public interface IRandomSource { double NextDouble(); }
|
||||
|
||||
| Scopo | Comandi |
|
||||
|---|---|
|
||||
| Navigare e leggere lo stato | `Page.enable`, `Page.navigate`, `Page.getFrameTree`, `Runtime.evaluate` in sola lettura (posizione degli elementi, indirizzo, presenza di finestre) |
|
||||
| Catturare le risposte | `Network.enable`, `Network.getResponseBody` |
|
||||
| Navigare e leggere lo stato | `Page.enable`, `Page.navigate`, `Page.getFrameTree`, `Runtime.evaluate` in sola lettura (posizione degli elementi, indirizzo, presenza di finestre; per la ricerca dei profili, se il fuoco è nella casella «Cerca», quanti caratteri contiene e se il cursore è in fondo, mai il testo né altri campi: decisione di Alberto del 15 novembre 2026, #37) |
|
||||
| Catturare le risposte | `Network.enable`, `Network.getResponseBody`; degli eventi di rete si legge anche `Network.requestWillBeSent`, solo l'indirizzo e solo per l'ordine delle richieste della ricerca (decisione di Alberto del 15 novembre 2026, #37) |
|
||||
| Gesti | `Input.dispatchMouseEvent`, `Input.dispatchKeyEvent` |
|
||||
| Scaricare i file | `Network.loadNetworkResource` (richiede l'identificativo del frame), `IO.read`, `IO.close` |
|
||||
| Vista remota e anteprima | `Page.startScreencast`, `Page.screencastFrameAck`, `Page.stopScreencast`, `Page.captureScreenshot` |
|
||||
@@ -360,6 +366,7 @@ Una ricetta è una sequenza di gesti con uno scopo. Sono poche e fisse. I passi
|
||||
| **Taggati** e **Reel** | Come Controllo e Storico, sulle rispettive schede del profilo | come sopra |
|
||||
| **Post singolo** | Apre la pagina di un post: quando la griglia non ha dato tutti i dati, o per recuperare un indirizzo scaduto (§6.5) | 1 post |
|
||||
| **Elenco dei seguiti** | Apre l'elenco dei profili seguiti da Alberto e lo scorre. Solo su richiesta | 1 pagina di elenco per caricamento |
|
||||
| **Ricerca dei profili** | Solo mentre Alberto scrive nella finestra «Aggiungi account» (§4.2), anche durante una sessione, a turno con il motore fra un'azione e l'altra. Apre «Cerca» e fa clic nella casella; prima di scrivere controlla che il fuoco sia nella casella; scrive con `Input.dispatchKeyEvent` a ritmo umano solo lettere, numeri, «.», «_» e spazi, e cancella con il tasto di cancellazione; non preme mai Invio, Tab o Esc. Legge la risposta che la pagina riceve (`PolarisSearchBoxRefetchableQuery`, riconosciuta dalla forma) e **non fa mai clic su un risultato**, che finirebbe fra le ricerche recenti di Alberto (una scrittura). Fuori sessione, a finestra chiusa o dopo qualche minuto senza lettere nuove, torna alla pagina di riposo | 1 ricerca di profili per apertura, clic nella casella e raffica di tasti |
|
||||
|
||||
Regole comuni:
|
||||
|
||||
@@ -370,7 +377,7 @@ Regole comuni:
|
||||
- **Lo storico non corre più veloce dei download.** Lo storico di un account si sospende finché quell'account ha più di 60 file in attesa di essere scaricati o il tetto dei dati è raggiunto: gli indirizzi scadono, e accumularli non serve.
|
||||
- Se a metà ricetta compare un segnale di §7.6, la ricetta si ferma dov'è e lascia la pagina com'è, così Alberto vede che cosa è successo.
|
||||
|
||||
**Mappa dei bersagli.** Per agire, una ricetta deve trovare poche cose nella pagina: l'immagine del profilo con l'anello delle storie, il comando per chiudere il visualizzatore, la zona per andare avanti, le schede del profilo, l'elenco dei seguiti. Come trovarle sta in un file di configurazione per sito (`bersagli.instagram.json`, `bersagli.prova.json`), non nel codice: ruolo dell'elemento, nome accessibile, forma del collegamento. Mai coordinate fisse, mai nomi di classi generate. Il file si aggiorna senza ricompilare, ed è la seconda cosa da ritoccare, dopo i lettori, quando Instagram cambia.
|
||||
**Mappa dei bersagli.** Per agire, una ricetta deve trovare poche cose nella pagina: l'immagine del profilo con l'anello delle storie, il comando per chiudere il visualizzatore, la zona per andare avanti, le schede del profilo, l'elenco dei seguiti, il comando «Cerca» e la sua casella (`search-open`, `search-box`). Come trovarle sta in un file di configurazione per sito (`bersagli.instagram.json`, `bersagli.prova.json`), non nel codice: ruolo dell'elemento, nome accessibile, forma del collegamento. Mai coordinate fisse, mai nomi di classi generate. Il file si aggiorna senza ricompilare, ed è la seconda cosa da ritoccare, dopo i lettori, quando Instagram cambia.
|
||||
|
||||
### 6.4 Lettori
|
||||
|
||||
@@ -469,7 +476,8 @@ Il Governatore è l'unico punto da cui passa un'azione del motore verso il sito.
|
||||
|
||||
- I tetti orari valgono su una finestra mobile di 60 minuti; quelli giornalieri sul giorno di calendario nel fuso di Alberto.
|
||||
- Il conteggio sta nella tabella `action_log`, non in memoria.
|
||||
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati. Le richieste della pagina (regola 2, eccezione) contano nella categoria di ciò che chiedono; la ricerca dei profili mentre si scrive avrà una categoria e un tetto propri (issue #36 e #37).
|
||||
- Categorie: home, profili aperti, storie viste, pagine di storico, post singoli, pagine dell'elenco dei seguiti, dati scaricati, ricerche di profili. Le richieste della pagina (regola 2, eccezione) contano nella categoria di ciò che chiedono.
|
||||
- **Ricerche di profili** (issue #37) hanno tetti propri e larghi (§7.5), che fanno da guardia e non devono mai fermare l'uso normale, e non consumano i tetti della raccolta. Non chiedono una sessione e non contano fra le azioni della sessione. L'ordine dei controlli: interruttore (ogni segnale di §7.6 ferma anche la ricerca), browser in uso da Alberto, pausa, fascia oraria, tetto orario e giornaliero proprio, distanza propria fra due passi della ricerca (1,2 s per il ritmo), 1,2 s di distanza dalle azioni del motore in entrambi i versi. Le riduzioni (avvio graduale, tetti dimezzati) valgono anche qui. Le foto dei risultati contano fra i dati scaricati.
|
||||
- Sopra l'80% di un tetto l'interfaccia lo segnala in ambra. Raggiunto il tetto, quella categoria si ferma fino all'ora o al giorno dopo; le altre proseguono, salvo la regola sullo storico di §6.3.
|
||||
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte, non il loro prodotto.
|
||||
|
||||
@@ -488,6 +496,7 @@ I valori sono **stime di partenza scelte con prudenza**. Non sono limiti ufficia
|
||||
| Pagine di storico | 20 / 100 | 30 / 180 | 45 / 300 |
|
||||
| Post singoli | 10 / 60 | 15 / 100 | 20 / 160 |
|
||||
| Pagine dell'elenco dei seguiti | 15 / 60 | 20 / 90 | 30 / 150 |
|
||||
| Ricerche di profili | 240 / 1200 | 300 / 1500 | 360 / 1800 |
|
||||
| Dati scaricati al giorno | 4 GB | 8 GB | 16 GB |
|
||||
| Storico per account al giorno | 300 post | 500 post | 800 post |
|
||||
| Avvio graduale | 7 giorni | 5 giorni | 3 giorni |
|
||||
@@ -693,10 +702,10 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f
|
||||
| `01-libreria.png` | Libreria | Righe giustificate che rispettano le proporzioni delle foto, 4 px fra le tessere. Segni in alto a destra: durata per i video, numero dei file per i post con più file, anello tratteggiato per le storie. I menu Account, Periodo e Provenienza mostrano il nome del filtro finché non si sceglie un valore. Il cursore accanto a «Seleziona» regola la grandezza delle tessere. Al passaggio del mouse: account, ora, cerchio di selezione. I nuovi elementi compaiono in cima senza spostare ciò che si sta guardando |
|
||||
| `02-visualizzatore.png` | Visualizzatore | Copre tutta la finestra. Frecce e tasti freccia; Esc chiude. I video partono senza audio. Nel browser «Mostra nella cartella» diventa «Scarica» |
|
||||
| `03-account.png` | Account | Le cinque icone di «Raccoglie» sono nell'ordine: foto, video, storie, evidenza, taggati; spente se non attive. L'interruttore agisce subito. Un clic sulla riga apre la scheda |
|
||||
| `04-aggiungi-account.png` | Aggiungi account | I tre punti di partenza sono quelli di §4.2. La seconda linguetta «Per nome utente» ha un'area di testo, una riga per account, e la stessa colonna destra. I profili già presenti sono attenuati. Durante la lettura dell'elenco compare l'avanzamento di §4.2 |
|
||||
| `04-aggiungi-account.png` | Aggiungi account | I tre punti di partenza sono quelli di §4.2. **Superato da #37**: niente linguette, una sola casella con l'elenco dei suggerimenti sotto (profili seguiti, poi Instagram, con foto ed etichette), «Da aggiungere» al posto dell'elenco a spunte, che si apre con «Scegli fra tutti i profili che segui». I profili già presenti sono attenuati. Durante la lettura dell'elenco compare l'avanzamento di §4.2. Finché non c'è un mockup nuovo, il riferimento è la schermata `docs/schermate/04-aggiungi-account.png` |
|
||||
| `05-account-impostazioni.png` | Scheda account, impostazioni | Il riquadro a destra si ricalcola a ogni modifica. «Controlla ora» segue §7.8. Con «Su misura» compaiono i due campi di §4.4 |
|
||||
| `06-attivita.png` | Attività | Si aggiorna da sola con gli eventi del server. L'anteprima del browser è un fotogramma ogni pochi secondi, non un video. «Tutti i tetti» apre l'elenco completo di §7.4 |
|
||||
| `07-limiti-e-comportamento.png` | Impostazioni, limiti | Modificare un valore cambia il profilo in «Su misura». I cerchi con le iniziali sono i giorni attivi. Nel programma la tabella dei tetti ha anche le righe Home, Post singoli ed Elenco dei seguiti di §7.5. La riga degli arresti è informativa: non si modifica |
|
||||
| `07-limiti-e-comportamento.png` | Impostazioni, limiti | Modificare un valore cambia il profilo in «Su misura». I cerchi con le iniziali sono i giorni attivi. Nel programma la tabella dei tetti ha anche le righe Home, Post singoli ed Elenco dei seguiti di §7.5, e «Ricerche di profili» (#37). La riga degli arresti è informativa: non si modifica |
|
||||
| `08-impostazioni-generali.png` | Impostazioni, generali | In Docker le due cartelle sono in sola lettura, con la nota che si cambiano dal contenitore. Il blocco «Avvio» esiste solo su Windows |
|
||||
| `09-importa-revisione.png` | Importa, passo 3 | I passi 1, 2 e 4 usano la stessa intestazione: scelta della cartella, barra di avanzamento con possibilità di interrompere, resoconto finale. Nel confronto dei doppioni nessuna scelta è già fatta in partenza: l'immagine mostra una decisione presa da Alberto. «Sposta» non compare se la sorgente è in sola lettura |
|
||||
| `10-collegamento-instagram.png` | Collegamento, versione Docker | Il riquadro grande è la vista remota del browser del server. Il rettangolo tratteggiato dell'immagine è un segnaposto: la pagina di Instagram non si ridisegna. Versione Windows qui sotto |
|
||||
@@ -728,7 +737,8 @@ Fuoco da tastiera sempre visibile; contrasto del testo almeno 4,5 a 1 in entramb
|
||||
|
||||
Con `--demo` il programma parte senza browser e senza rete, in ascolto solo su `127.0.0.1` e senza password, con una libreria temporanea di account `.demo`, immagini generate e uno stato del motore finto. Non deve poter scrivere nella libreria vera.
|
||||
|
||||
- Lo stato si sceglie dall'indirizzo: `?scena=normale`, `sessione`, `fermo`, `scollegato`; il tema con `?tema=chiaro` o `scuro`. Ci sono indirizzi che aprono direttamente il dialogo «Aggiungi account» e il passo 3 dell'importazione.
|
||||
- Lo stato si sceglie dall'indirizzo: `?scena=normale`, `sessione`, `fermo`, `scollegato`, `alvolante` (Alberto usa il browser); il tema con `?tema=chiaro` o `scuro`. Ci sono indirizzi che aprono direttamente il dialogo «Aggiungi account» e il passo 3 dell'importazione.
|
||||
- La ricerca dei profili del dialogo risponde con dati finti, senza browser: account e profili seguiti dimostrativi il cui nome contiene il testo, più qualche nome inventato, con foto disegnate che arrivano un attimo dopo. Con `fermo`, `scollegato` e `alvolante` dice perché non cerca.
|
||||
- I dati dimostrativi devono essere coerenti fra loro (i conteggi tornano, gli orari sono plausibili). Non serve che ricalchino i numeri dei mockup.
|
||||
|
||||
### 10.7 Come si verifica una schermata
|
||||
@@ -738,7 +748,7 @@ Avvia con `--demo`, fai uno screenshot nelle condizioni della tabella e confront
|
||||
| Mockup | Finestra in pixel CSS | Tema e scena |
|
||||
|---|---|---|
|
||||
| 01, 02, 03, 08 | 1440 × 900 | chiaro, normale |
|
||||
| 04 | 1440 × 900 | chiaro, dialogo aperto |
|
||||
| 04 | 1440 × 900 | chiaro, dialogo aperto con «gaia» scritto e l'elenco dei suggerimenti aperto |
|
||||
| 05 | 1440 × 1000 | chiaro, normale |
|
||||
| 06 | 1440 × 900 | chiaro, sessione |
|
||||
| 07 | 1440 × 1470 | chiaro, normale |
|
||||
|
||||
@@ -328,3 +328,25 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-11-13 | Avvio di Chromium (`ChromiumLaunchOptions.StartupTimeout`): **120 s** invece di 30 per aprire la porta di debug, e la prima scheda si aspetta entro la **stessa scadenza**, non più 50 tentativi da 100 ms; finisce subito se il processo si chiude, e una risposta lenta o mancata di `/json/list` vale «non ancora» come già per `/json/version`. Il ricollegamento dopo una connessione caduta usa la stessa scadenza ma smette appena il processo si chiude o il supervisore lo sostituisce, così non tiene il blocco del collegamento a un riavvio. Nessun comando CDP nuovo e nessun cambio della riga di comando (§6.1) | #46: la scadenza serve solo contro un Chromium vivo e bloccato, perché uno che si chiude fa già fallire l'avvio all'istante. Su una macchina carica (la CI era 4-6 volte più lenta del solito, un NAS durante un controllo di parità) Febe uccideva un Chromium lento ma sano e ricominciava da capo sotto lo stesso carico, anche per sempre; i 5 s per la prima scheda erano il punto più fragile |
|
||||
| 2026-11-13 | Nelle prove i limiti di tempo sono **protezioni contro un blocco, non misure**: ogni attesa finisce appena la sua condizione è vera e il limite è largo (il browser delle prove dell'interfaccia: 2 minuti per avvio, comandi DevTools e condizioni, e si ferma subito se Chromium si chiude, con le sue ultime righe di stderr; l'avvio del server di prova: 4 minuti, con l'ultimo errore del browser); niente attese fisse né conteggi di tentativi al posto di una scadenza. Ciò che una prova deve far accadere a un certo momento (il rilascio di un blocco, una lettura che non deve finire mai) gira su un thread suo, non sul pool; il pool delle prove parte con almeno 64 thread. Il browser delle prove dell'interfaccia usa la porta di debug 0 e legge quella scelta da Chromium; il browser di Febe resta sulla porta fissa (§6.1). Nelle prove di WebView2 su Windows la seconda «Scollega» e l'arresto non hanno più un limite di 10 s: la prova chiede che il processo del browser esca davvero (atteso per condizione) e che il profilo sparisca, con 90 s solo contro un blocco | #46: le prove cadevano a ogni carico del runner, ogni volta prove diverse, mai sul codice cambiato. Un limite stretto su un'attesa non misura nulla: dice solo quanto era carica la macchina. Con il parallelismo per metodo diverse prove bloccano thread del pool, e un pool di 2-4 thread ne aggiunge altri lentamente: il rilascio di un blocco dopo 300 ms arrivava dopo più di 10 s. Fra la porta libera trovata e il bind di Chromium un altro processo poteva prenderla. Con tutti i core occupati il processo di WebView2 (a priorità bassa) segnala l'uscita dopo i 15 s di attesa dell'host: la prova di «Scollega» cadeva 5 volte su 5 a 15,7-21 s, mentre ciò che deve escludere, una WebView orfana, tiene vivo il processo per sempre e lascia il profilo |
|
||||
| 2026-11-13 | `FebeDatabase.DisposeAsync` chiude davvero i file prima di tornare: ogni comando SQLite si chiude appena usato (gli aiuti `Execute` e `Scalar` sulla connessione dello scrittore, e un ambito che chiude i comandi di ogni lettura), le connessioni di lettura del pool si chiudono **prima** dello scrittore, così è lo scrittore, ultimo, a togliere `febe.sqlite-wal` e `-shm`. All'arresto `FebeApp` aspetta anche i lavori in sottofondo che un avvio ancora in corso aggiunge mentre si ferma | #46: un comando lasciato al garbage collector tiene viva la sua istruzione finché il finalizzatore non passa; la connessione chiusa nel frattempo si chiudeva davvero solo dopo, e il WAL spariva durante lo spostamento della cartella Dati (`Could not find file …febe.sqlite-wal`). Riprodotto tenendo occupato il thread del finalizzatore, ora con una prova apposita. Una connessione di sola lettura chiusa per ultima lascia il WAL: per questo il pool si svuota prima |
|
||||
| 2026-11-15 | Ricerca dei profili (#37), prima parte: si cerca **nel pannello «Cerca» di Instagram**, scrivendo con `Input.dispatchKeyEvent` (già in §6.1) da una mappa chiusa di tasti (`SearchKeyMap`: lettere, cifre, `.`, `_` e spazio, più Backspace ed End), cancellando e riscrivendo con i tasti; si leggono le risposte `PolarisSearchBoxRefetchableQuery` del campione ripulito 000002. Nessun comando CDP nuovo, nessun `doc_id`, nessuna richiesta della pagina; non si preme mai Invio e non si clicca mai un risultato; solo profili | Decisioni 1 e 2 di Alberto del 15/11: la ricerca deve essere quella che il sito fa già quando una persona scrive, senza chiamate inventate; un risultato aperto o una «ricerca recente» scritta sarebbero un'azione in più sul sito |
|
||||
| 2026-11-15 | Categoria del Governatore `ProfileSearch`: tetti propri per ora e per giorno (Prudente 240/1200, Equilibrato 300/1500, Rapido 360/1800, nessuno sopra 2×Rapido), un blocco proprio e una spaziatura propria (`SearchSpacing` 1,2 s × ritmo) più uno **scarto d'incrocio** della stessa durata fra un passo di ricerca e un'azione del motore, in tutte e due le direzioni. Non serve una sessione, non conta fra le azioni della sessione, non consuma i tetti della raccolta e non conta come «ultima azione del motore» (`GetLastActionAtAsync(null)` esclude `ProfileSearch` e `DataDownload`). La fermano come il motore l'interruttore (§7.6), Alberto al browser, la pausa e la fascia oraria; le riduzioni dei tetti valgono anche qui | Decisione 3: niente sezione separata nelle impostazioni, una riga nella tabella di Prudenza. Un passo di ricerca è una frazione di testo scritto, non un profilo aperto: con i tetti della raccolta la ricerca si fermerebbe dopo poche lettere e ruberebbe passi alla raccolta |
|
||||
| 2026-11-15 | `PageTurns`: un blocco FIFO sull'unica pagina del browser, a turni fra motore e ricerca. Il motore prende un turno per ricetta e lo cede ai permessi che aprono una pagina; la ricerca prende il turno per un passo e lo lascia appena il motore aspetta. Fuori sessione la ricerca apre Instagram e la pagina torna a riposo quando la finestra si chiude (5 s) o dopo 3 minuti senza testo nuovo, solo se l'ultima ad aver usato la pagina è la ricerca | Decisione 4: una sola pagina, nessuna seconda scheda (§6.1). Il turno per ricetta evita che una ricerca entri a metà di una lettura e sposti la pagina sotto i piedi della ricetta |
|
||||
| 2026-11-15 | Foto dei risultati: `BrowserFileFetcher` (solo CDN, §6.5) con un permesso `DataDownload` per foto, al più 2 in parallelo e 8 per risposta, ridotte a JPEG di 160 px in una **cache solo in memoria** (400 foto, 8 MB, 3 giorni, chiavi casuali di 32 cifre esadecimali); i byte contano nel budget giornaliero dei dati. L'interfaccia le chiede a Febe (`/api/ricerca/foto/{chiave}`), mai a Instagram. Un errore HTTP passa al rilevatore dei segnali e svuota la coda | Decisione 5: le foto non sono archivio e non devono restare su disco; una chiave casuale non rivela il profilo né l'indirizzo firmato |
|
||||
| 2026-11-15 | Il controllo del fuoco della casella (`TargetResolver.BuildFocusExpression`) è uno script di sola lettura che restituisce lo stato e la **lunghezza** del testo, mai il testo; un tasto non ricevuto vale «Tasti non ricevuti» prima di «Fuoco perso» | Regola 10: il testo cercato non deve tornare indietro dalla pagina né finire nei log. Da confermare con Alberto (domanda N1) che uno script così rientri in §6.1 |
|
||||
| 2026-11-15 | La finestra legge la ricerca **a domande** (POST `/api/ricerca`, GET `/api/ricerca?client=`, POST `/api/ricerca/fine`), non con un flusso SSE; un cliente si riconosce da 16 cifre esadecimali scelte dalla pagina; il testo è al più di 60 caratteri e la richiesta deve venire dall'Origin dell'interfaccia | Una sola persona e una finestra: le domande ogni poche centinaia di millisecondi bastano e non tengono aperta una connessione per ogni scheda; l'Origin impedisce che una pagina di un altro sito faccia scrivere Febe |
|
||||
| 2026-11-15 | Prima di aprire Instagram per una ricerca fuori sessione si guarda il cookie di sessione: se manca vale **Disconnessione** (segnale §7.6), non un errore della ricerca | Senza sessione Instagram mostrerebbe l'accesso: aprirlo per niente è un'azione in più e la regola di §7.6 è la stessa del motore |
|
||||
| 2026-11-15 | Il sito di prova risponde alla ricerca (`/dati/cerca`) **con le chiavi del campione ripulito 000002**, lette dallo stesso vocabolario di Instagram; pannello «Cerca» con i bersagli `search-open` e `search-box` in `bersagli.prova.json`. Per Instagram i due bersagli restano da raccogliere (H11): finché Alberto non li conferma la ricerca dal vivo dice «Febe non sa ancora dove sta «Cerca» su questo sito…» (`SearchState.NotConfigured`) | Regola 9: il formato non si inventa. Le prove e la modalità dimostrativa (risultati e foto disegnati, nessuna rete) mostrano la ricerca funzionante senza toccare Instagram |
|
||||
| 2026-11-15 | Diagnostica della ricerca: nel rapporto solo i conteggi dei passi per esito (`searchSteps`, elenco chiuso `SearchOutcome`) e delle foto per sorte (`searchPhotos`: scaricata, rifiutata, saltata, altrimenti «altro»), fuori sessione; mai testo, nomi o indirizzi. Nella cronologia una riga per finestra di ricerca con il numero di passi, risposte e foto | «Tracciare sempre tutto» (richiesta di Alberto) senza dati di altre persone (§2 regola 10 e #39) |
|
||||
| 2026-11-15 | Ricerca dei profili (#37), seconda parte: la finestra «Aggiungi account» ha **una sola casella** senza linguette. I suggerimenti locali (seguiti e account in Febe, al più 8, prima chi comincia con il testo) si filtrano nella pagina a ogni lettera; il testo va a Febe 150 ms dopo l'ultima lettera; i risultati di Instagram si uniscono per identificativo e poi per nome, senza doppioni | È il comportamento chiesto da Alberto (come 4K Stogram): i profili noti subito, Instagram quando arriva |
|
||||
| 2026-11-15 | Nella stessa casella: più nomi incollati (a capo, virgola, punto e virgola, più indirizzi) vanno a `/api/accounts/parse` e in «Da aggiungere», mai su Instagram; la riga «Aggiungi @nome per nome utente» aggiunge il nome scritto; «Scegli fra tutti i profili che segui» riapre l'elenco a spunte con «Seleziona tutti» (default della domanda Q8) | L'aggiunta per nome e la scelta in blocco restano possibili, anche finché la ricerca su Instagram non è configurata (H11) |
|
||||
| 2026-11-15 | Il dialogo di `core/ui.js` accetta `onEscape` (Esc chiude prima l'elenco dei suggerimenti, il secondo Esc il dialogo) e `onClose` (una volta sola comunque si chiuda: `POST /api/ricerca/fine`, fine delle domande) | La ricerca non deve restare aperta su Instagram quando la finestra non c'è più |
|
||||
| 2026-11-15 | Scena dimostrativa `alvolante` (motore `UserDriving`, ricerca `non-possibile`) | Mostrare e provare il caso in cui Alberto usa il browser senza un browser vero |
|
||||
| 2026-11-15 | Ricerca dei profili, revisione: una risposta della ricerca vale per il testo nella casella **solo se la pagina ne ha avviato la richiesta dopo l'ultimo tasto**. `ResponseTap` ascolta anche l'evento `Network.requestWillBeSent` (un evento del dominio già attivo con `Network.enable`, nessun comando nuovo) e dà a ogni richiesta del sito un numero d'ordine; prima di ogni tasto, Backspace compresi, la ricerca annota dove sono arrivate le richieste. Fra quelle avviate dopo l'ultimo tasto si prende la più recente, subito; senza numero d'ordine (un flusso di eventi che non lo porta) si torna all'ordine d'arrivo con la pagina quieta. Della richiesta si guarda solo il tipo di indirizzo, niente si conserva né si registra | Il campione 000002 non ripete il testo cercato: mentre Febe scrive la pagina chiede anche i prefissi, e le loro risposte possono arrivare dopo quella giusta (modalità «ricerca/disordine» del sito di prova). Prenderle per il testo intero le metteva nella memoria delle risposte per 5 minuti |
|
||||
| 2026-11-15 | Una pagina che mostra un testo già cercato dalla sua memoria non manda richieste: la ricerca tiene le risposte lette **su quella pagina** e, se dopo l'attesa minima la pagina è quieta e non è arrivato nulla, usa quella del testo. Il ricordo vale fino alla prossima pagina aperta o messa a riposo (`PageTurns.Generation`), insieme a ciò che Febe ha scritto nella casella | Modalità «ricerca/memoria» del sito di prova: senza, tornare a un testo già scritto finiva in «Instagram non ha mandato risultati». Con la generazione della pagina, durante una sessione la lettera nuova è l'unico tasto, invece di cancellare e riscrivere tutto a ogni passo |
|
||||
| 2026-11-15 | Riposo della pagina con i turni: la pagina vuota a fine sessione e dopo che Alberto ha usato il browser passa da `PageTurns.TakeForRestAsync`. Se la ricerca tiene o aspetta la pagina, il riposo **tocca alla ricerca** (`RestOwed`), che lo fa a finestra chiusa (5 s) o dopo 3 minuti senza testo nuovo, subito se Instagram ha chiesto di rallentare, anche se non ha mai scritto; la ricerca mette a riposo anche la pagina del motore su cui ha scritto. La pagina di accesso di Alberto aspetta il turno (al più 15 s). Supera la condizione «solo se l'ultima ad aver usato la pagina è la ricerca» della riga dei turni | Durante una sessione è il motore ad aprire le pagine: una sessione finita mentre Alberto cercava lasciava Instagram aperto fuori sessione (§6.1). Un riposo o una navigazione senza turno potevano cadere a metà di un passo della ricerca |
|
||||
| 2026-11-15 | Un tasto premuto si rilascia sempre: se il passo viene annullato fra «giù» e «su», `HumanGestures.PressKeyAsync` manda comunque il rilascio del tasto e di Maiusc, senza attesa | La pagina passa poi al motore o ad Alberto: un tasto rimasto giù cambierebbe ciò che scrivono |
|
||||
| 2026-11-15 | Le foto della ricerca arrivano all'interfaccia con `Cache-Control: no-store` | La cache delle foto è solo in memoria: il browser che mostra Febe non deve tenerne una copia sul suo disco |
|
||||
| 2026-11-15 | La ricerca riprende da sola dopo un arresto passeggero: dopo «Ho finito» e dopo la pausa (ricontrollate ogni 2 s, senza chiedere al Governatore), all'apertura della fascia o allo scadere di un tetto (il `RetryAfter` del rifiuto), dopo «Riprendi» (il cambio dell'interruttore). Dopo un errore o «nessuna risposta» lo stesso testo, scritto di nuovo, si riprova. La finestra continua a chiedere lo stato (ogni 2 s) mentre la ricerca è ferma per uno di questi motivi, e subito quando cambia lo stato del motore | I testi dicevano «riprende quando hai finito», ma la finestra smetteva di chiedere e il servizio non riprovava |
|
||||
| 2026-11-15 | Nella finestra, l'indirizzo di un post, di un reel, di una storia o di un'altra pagina di Instagram non diventa un nome (`p`, `reel`, `stories`…): stesso elenco di `UsernameParser.ReservedPaths` | Incollare `instagram.com/p/…` offriva «Aggiungi @p per nome utente» |
|
||||
| 2026-11-15 | Il mockup 04 è superato da #37: il riferimento è la schermata `docs/schermate/04-aggiungi-account.png` finché Alberto non ne fornisce uno nuovo (domanda Q9) | Non esiste il sorgente del mockup nel repository; la schermata segue gli elementi del foglio di stile (mockup 13) |
|
||||
| 2026-11-15 | Risposte di Alberto sulla ricerca dei profili (#37): il controllo del fuoco con `Runtime.evaluate` in sola lettura è ammesso e scritto in §6.1 (N1); i turni cadono a ogni ricetta e prima di ogni apertura di pagina, non dentro il visualizzatore né fra le raffiche di scorrimento (N2); l'ascolto di `Network.requestWillBeSent`, solo per l'indirizzo, è ammesso e scritto in §6.1; le foto dei profili seguiti non si scaricano per ora | Domande poste ad Alberto il 15 novembre 2026 alla fine del disegno; tutte con la risposta consigliata |
|
||||
@@ -9,14 +9,74 @@ evidenza); un **file** è ogni singola foto o video. I contatori contano element
|
||||
|
||||
## Aggiungere account
|
||||
|
||||
«Aggiungi account» apre una finestra con due linguette:
|
||||
«Aggiungi account» apre una finestra con **una sola casella di ricerca**, come in 4K Stogram. Scrivi un nome utente
|
||||
o un nome completo (anche solo una parte, «mar» trova @marta.rossi e Mario Bianchi): sotto la casella compare un
|
||||
elenco che si aggiorna a ogni lettera.
|
||||
|
||||
- **Dai profili che segui:** l'elenco dei profili che segui, letto da Febe a ritmo umano e dentro i tetti. La prima
|
||||
volta va letto («Leggi l'elenco»): può servire più di una sessione, e la finestra dice a che punto è («Letti 96
|
||||
profili, continuo alla prossima sessione»). L'elenco resta in memoria con la data di lettura e si rilegge solo se lo
|
||||
chiedi. I profili già presenti in Febe sono attenuati.
|
||||
- **Per nome utente:** scrivi o incolla nomi utente o indirizzi di profilo, uno per riga (`nome.utente`,
|
||||
`@nome.utente` oppure `instagram.com/nome.utente`). Serve per i profili pubblici che non segui.
|
||||
- **Profili che segui e account in Febe:** compaiono subito, mentre scrivi, dalla memoria di Febe. Per averli bisogna
|
||||
aver letto almeno una volta l'elenco dei profili che segui («Leggi l'elenco», in basso nella finestra).
|
||||
- **Da Instagram:** i profili che trova Instagram arrivano poco dopo, di solito in un paio di secondi. Un profilo che
|
||||
compare in tutte e due le parti è mostrato una volta sola.
|
||||
|
||||
Ogni riga ha la **foto del profilo**, il nome utente, il nome completo e le etichette «Seguito», «Privato», «Già in
|
||||
Febe». Finché la foto non è arrivata vedi le iniziali. La foto c'è per gli account già in Febe e per i profili che
|
||||
Instagram ha appena trovato; un profilo che segui ma che non è in Febe ha la foto solo quando compare anche fra i
|
||||
risultati di Instagram per lo stesso testo, altrimenti restano le iniziali: Febe non conserva le foto dei profili che
|
||||
segui, e senza la ricerca su Instagram (per esempio con una lettera sola) non ne ha. «Privato» e «Seguito» li sa solo Febe: un profilo che Febe non
|
||||
conosce non ha queste etichette anche se è privato. I profili «Già in Febe» non si aggiungono una seconda volta, anche
|
||||
se nel frattempo hanno cambiato nome.
|
||||
|
||||
- **Aggiungere:** premi «Aggiungi» sulla riga, o un clic sulla riga, o scendi con le frecce e premi Invio. Il profilo
|
||||
passa in **«Da aggiungere»**, sotto la casella; la × lo toglie. Esc chiude l'elenco dei suggerimenti, un secondo Esc
|
||||
chiude la finestra.
|
||||
- **Per nome utente:** l'ultima riga dell'elenco, «Aggiungi @nome per nome utente», aggiunge il nome che hai scritto
|
||||
anche se non compare fra i risultati (Invio fa lo stesso). Febe controlla il profilo alla prossima sessione.
|
||||
- **Più nomi insieme:** incolla nella casella più nomi utente o indirizzi di profilo, uno per riga o separati da
|
||||
virgole (`nome.utente`, `@nome.utente`, `instagram.com/nome.utente`). Vanno tutti in «Da aggiungere»; quelli già in
|
||||
Febe e quelli non validi sono spiegati sotto l'elenco, con il loro posto («2° nome: …»). Gli spazi da soli non
|
||||
separano: «mario rossi» si cerca. L'indirizzo di un post, di un reel o di una storia non è un profilo: la finestra lo
|
||||
dice e non lo aggiunge. Incollati mentre è aperto l'elenco completo dei seguiti, i nomi vanno in «Da aggiungere» lo
|
||||
stesso: le caselle dei profili che segui si spuntano e un avviso dice quanti sono.
|
||||
- **Scegli fra tutti i profili che segui:** apre al posto di «Da aggiungere» l'elenco completo dei profili che segui,
|
||||
con le caselle di spunta e «Seleziona tutti»; la casella in alto lo filtra. L'elenco è letto da Febe a ritmo umano e
|
||||
dentro i tetti: la prima volta può servire più di una sessione, e la finestra dice a che punto è («Letti 96 profili,
|
||||
continuo alla prossima sessione»). Resta in memoria con la data di lettura e si rilegge solo se lo chiedi.
|
||||
|
||||
### Come cerca su Instagram
|
||||
|
||||
Cerca il **browser di Febe**, non la pagina che stai guardando: apre il pannello «Cerca» di Instagram e scrive il testo
|
||||
nella sua casella, a ritmo umano, come faresti tu. Legge i risultati che Instagram manda a quella pagina e ne scarica le
|
||||
foto, che tiene per poco e solo in memoria. Non apre mai i profili trovati e non fa clic sui risultati, quindi le tue
|
||||
«ricerche recenti» su Instagram non cambiano. Cerca solo profili, niente hashtag né luoghi. Le lettere accentate si
|
||||
cercano senza accento («Niccolò» diventa «niccolo»); simboli diversi da punto, trattino basso e spazio restano solo
|
||||
nei suggerimenti locali.
|
||||
|
||||
Ogni passo della ricerca chiede il permesso al Governatore, con un tetto proprio e largo che non consuma i tetti della
|
||||
raccolta («Ricerche di profili» in [Limiti e comportamento](Limiti-e-comportamento)). Durante una sessione la ricerca e
|
||||
la raccolta si danno il turno sull'unica pagina: i risultati di Instagram possono aspettare che finisca un passo della
|
||||
raccolta (la finestra dice «In attesa del turno…»), la sessione non si ferma. Fuori dalle sessioni, quando chiudi la
|
||||
finestra o dopo qualche minuto senza lettere nuove, il browser torna alla pagina vuota. Anche se una sessione finisce
|
||||
mentre stai cercando: la pagina torna vuota appena la ricerca ha finito.
|
||||
|
||||
La riga sotto «Da Instagram» dice quando la ricerca su Instagram non è possibile; i suggerimenti locali funzionano
|
||||
sempre:
|
||||
|
||||
| Messaggio | Perché |
|
||||
|---|---|
|
||||
| «Stai usando il browser di Febe…» | Lo stai usando tu (accesso, verifica, «Apri il browser»): la ricerca riprende da sola quando premi «Ho finito», senza riscrivere |
|
||||
| «Febe è in pausa…» | La pausa ferma anche la ricerca: riprende da sola quando premi «Riprendi» |
|
||||
| «Fuori dalla fascia oraria…» | Fuori fascia Febe non apre Instagram, neanche per cercare: la ricerca riprende da sola quando la fascia si apre, se la finestra è ancora aperta |
|
||||
| «Febe è fermo…» o il motivo dell'arresto | Un segnale di Instagram (verifica, rallentamento, disconnessione) ferma anche la ricerca; riprende da sola dopo «Riprendi» o alla fine del rallentamento. Vedi [Attività e arresti](Attivita-e-arresti) |
|
||||
| Tetto delle ricerche raggiunto | Il tetto orario o giornaliero delle ricerche di profili; riprende da solo |
|
||||
| «… non è riuscita: riprova» e simili | Riscrivi lo stesso testo, anche solo con uno spazio in più: Febe ci riprova |
|
||||
| «Il browser di Febe non è pronto» / «Il motore non è avviato» | Febe si sta avviando o il browser non è collegato |
|
||||
| «Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.» | Mancano i bersagli del pannello «Cerca» per questo sito (vedi sotto). Se invece dice che Febe «non sa ancora leggere le risposte della ricerca», manca il lettore delle risposte |
|
||||
| «La ricerca su Instagram è in uso da un'altra finestra» | Cerca una finestra di Febe alla volta: l'ultima in cui hai scritto |
|
||||
|
||||
**Ancora da verificare dal vivo.** Su Instagram vero la ricerca ha bisogno dei bersagli `search-open` e `search-box`
|
||||
(il comando «Cerca» e la sua casella), che si raccolgono con una prova dal vivo: finché mancano, sotto «Da Instagram»
|
||||
leggi «Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.» e funzionano i suggerimenti locali e l'aggiunta per nome. La scrittura nella casella con il browser di
|
||||
Windows (WebView2) non è ancora stata provata.
|
||||
|
||||
A destra scegli il **punto di partenza**, che poi puoi cambiare account per account:
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ ritoccati guardando che cosa succede.
|
||||
| Pagine di storico | 20 / 100 | 30 / 180 | 45 / 300 |
|
||||
| Post singoli | 10 / 60 | 15 / 100 | 20 / 160 |
|
||||
| Pagine dell'elenco dei seguiti | 15 / 60 | 20 / 90 | 30 / 150 |
|
||||
| Ricerche di profili | 240 / 1200 | 300 / 1500 | 360 / 1800 |
|
||||
| Dati scaricati al giorno | 4 GB | 8 GB | 16 GB |
|
||||
| Storico per account al giorno | 300 post | 500 post | 800 post |
|
||||
| Avvio graduale | 7 giorni | 5 giorni | 3 giorni |
|
||||
@@ -60,7 +61,8 @@ ritoccati guardando che cosa succede.
|
||||
con pesi (frequenza e ritardo), mai lo stesso. Lo storico avanza su un solo account per sessione.
|
||||
- **Umore della sessione.** Ogni sessione ha un fattore di velocità estratto una volta: alcune sono svelte, altre lente.
|
||||
- **Riposo.** A fine sessione, nelle pause e di notte il browser sta su una pagina vuota: nessuna pagina di Instagram
|
||||
resta aperta fuori da una sessione.
|
||||
resta aperta fuori da una sessione, salvo mentre cerchi un profilo in «Aggiungi account» (fino a quando chiudi la
|
||||
finestra o a qualche minuto dopo l'ultima lettera).
|
||||
- **Lo storico non corre più veloce degli scaricamenti.** Lo storico di un account si sospende finché quell'account ha
|
||||
più di 60 file in attesa o il tetto dei dati è raggiunto: gli indirizzi dei file scadono, accumularli non serve.
|
||||
|
||||
@@ -75,6 +77,10 @@ ritmo «naturale»), limiti dell'account. Risponde con un permesso o con un rifi
|
||||
giorno dopo; le altre proseguono.
|
||||
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte,
|
||||
non il loro prodotto.
|
||||
- **Ricerche di profili.** La ricerca della finestra «Aggiungi account» ha tetti propri, larghi apposta: fanno da
|
||||
guardia e non devono fermare l'uso normale, e non consumano i tetti della raccolta. Non serve una sessione, ma valgono
|
||||
l'interruttore, la pausa e la fascia oraria; fra due passi della ricerca, e fra la ricerca e il motore, passa almeno
|
||||
poco più di un secondo. Vedi [Account e impostazioni](Account-e-impostazioni).
|
||||
|
||||
## Avvio graduale
|
||||
|
||||
|
||||
@@ -47,6 +47,21 @@ Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
||||
stato scaricato una volta.
|
||||
8. **Disco pieno:** vedi sotto.
|
||||
|
||||
## Cercare un profilo da aggiungere
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| Sotto «Da Instagram» c'è «Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.» | Su Instagram mancano ancora i bersagli del pannello «Cerca» (`search-open`, `search-box`, ipotesi H11 di [Ipotesi da verificare](Ipotesi-da-verificare)): si raccolgono con una prova dal vivo. Intanto usa i suggerimenti dei profili che segui, la riga «Aggiungi @nome per nome utente» o incolla più nomi |
|
||||
| «Stai usando il browser di Febe…» | Mentre usi tu il browser (accesso, verifica, pagina Browser) Febe non cerca: premi «Ho finito», e la ricerca riprende da sola con il testo che c'è nella casella |
|
||||
| «Febe è in pausa…» | Premi «Riprendi»: la ricerca riprende da sola |
|
||||
| «… non è riuscita: riprova», «Instagram non ha mandato risultati…» | Riscrivi lo stesso testo (basta uno spazio in più) o aggiungi una lettera: Febe ci riprova |
|
||||
| Un profilo che segui ha solo le iniziali | Febe non conserva le foto dei profili che segui: la foto arriva solo se il profilo compare anche fra i risultati di Instagram per lo stesso testo, o se l'account è già in Febe |
|
||||
| «È l'indirizzo di un post, di un reel…» | Hai incollato l'indirizzo di un post, di un reel o di una storia: serve quello del profilo, `instagram.com/nome.utente` |
|
||||
| «Fuori dalla fascia oraria…» o «Febe è fermo…» | Fuori fascia e durante un arresto Febe non apre Instagram, neanche per cercare. I suggerimenti locali funzionano; la ricerca riprende da sola quando la fascia si apre o l'arresto finisce |
|
||||
| «In attesa del turno…» per qualche secondo | Una sessione sta facendo un passo della raccolta sull'unica pagina del browser: i risultati arrivano appena la pagina è libera |
|
||||
| Nessun suggerimento mentre scrivi | Su Instagram Febe cerca da due lettere in su. I profili che segui compaiono già dalla prima lettera, ma solo se l'elenco dei seguiti è stato letto almeno una volta («Leggi l'elenco») |
|
||||
| Su Windows i risultati di Instagram non arrivano mai | La scrittura nella casella di Instagram con il browser di Windows non è ancora stata provata dal vivo: riferisci il caso, con il rapporto di diagnostica |
|
||||
|
||||
## File e libreria
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|
||||
@@ -52,7 +52,8 @@ si può usare. Dettagli in [Installazione con Docker e Unraid](Installazione-Doc
|
||||
- È un browser normale: nessuna modifica di user agent, impronta, lingua, fuso orario o intestazioni; niente modalità
|
||||
senza finestra; niente proxy; nessuna estensione «stealth».
|
||||
- Salvataggio delle password e compilazione automatica sono spenti: nel profilo resta solo la sessione.
|
||||
- Fra una sessione e l'altra sta su una pagina vuota; non segue mai collegamenti che portano fuori da Instagram.
|
||||
- Fra una sessione e l'altra sta su una pagina vuota, salvo mentre cerchi un profilo in «Aggiungi account»; non segue
|
||||
mai collegamenti che portano fuori da Instagram.
|
||||
- Verso Instagram parla solo il browser di Febe. L'unica altra connessione verso i server di Instagram è lo
|
||||
scaricamento dei file già indicati dalla pagina, dal solo CDN (e oggi passa anch'essa dal browser).
|
||||
|
||||
@@ -60,7 +61,9 @@ si può usare. Dettagli in [Installazione con Docker e Unraid](Installazione-Doc
|
||||
|
||||
Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né
|
||||
suggerimenti. L'unica traccia che lascia è quella di una normale visita, **compresa la visualizzazione delle storie:
|
||||
le storie aperte da Febe risultano viste.** Un profilo privato che non ti ha accettato non si tocca.
|
||||
le storie aperte da Febe risultano viste.** Un profilo privato che non ti ha accettato non si tocca. Quando cerchi un
|
||||
profilo, Febe scrive nella casella «Cerca» di Instagram ma non fa clic sui risultati: le tue ricerche recenti su
|
||||
Instagram non cambiano.
|
||||
|
||||
## Un account, un motore
|
||||
|
||||
@@ -71,15 +74,17 @@ visite e il rischio.
|
||||
|
||||
Il registro contiene azioni ed esiti: nomi utente sì; didascalie, corpi delle risposte, password, cookie, tasti,
|
||||
indirizzi firmati dei file, gettoni (compreso quello di Telegram) no. Il client del browser registra solo i nomi dei
|
||||
comandi, mai i loro parametri. Il registro è nella cartella dei dati (`registro`), un file al giorno, tenuto
|
||||
comandi, mai i loro parametri. Di una ricerca di profili restano solo quanti passi ha fatto e come sono finiti, mai il
|
||||
testo che hai scritto né i nomi trovati; le foto dei profili trovati stanno solo in memoria, per poco, e non finiscono
|
||||
mai su disco. Il registro è nella cartella dei dati (`registro`), un file al giorno, tenuto
|
||||
quattordici giorni.
|
||||
|
||||
## Che cosa esce da Febe
|
||||
|
||||
| Verso | Che cosa | Quando |
|
||||
|---|---|---|
|
||||
| Instagram | Le visite del browser di Febe, con la tua sessione | Nelle sessioni, dentro la fascia |
|
||||
| CDN di Instagram | Lo scaricamento dei file indicati dalla pagina | Quando ci sono file in coda |
|
||||
| Instagram | Le visite del browser di Febe, con la tua sessione | Nelle sessioni, dentro la fascia; e quando cerchi un profilo in «Aggiungi account» |
|
||||
| CDN di Instagram | Lo scaricamento dei file indicati dalla pagina | Quando ci sono file in coda, e per le foto dei profili trovati dalla ricerca |
|
||||
| Telegram (`api.telegram.org`) | Il testo degli avvisi | Solo se hai configurato il bot |
|
||||
|
||||
Nient'altro: niente statistiche, niente aggiornamenti automatici, nessun carattere o icona caricato dalla rete.
|
||||
|
||||
@@ -10,5 +10,6 @@ Le immagini sono il riferimento grafico di §10.3 della specifica. Sono in scala
|
||||
| `08-impostazioni-generali.png` | Originale |
|
||||
| `10-collegamento-instagram.png` | Originale |
|
||||
| `miniature/02…14` | **Ritagli ingranditi della panoramica**: gli originali a piena risoluzione non sono stati forniti. Bastano per disposizione e gerarchia, non per misure e testi minuti |
|
||||
| `miniature/04-aggiungi-account.png` | **Superato da #37** (ricerca unica dei profili): linguette ed elenco a spunte non ci sono più. Finché Alberto non fornisce un mockup nuovo, il riferimento della finestra è la schermata `docs/schermate/04-aggiungi-account.png`, con le differenze in `docs/schermate/differenze.md` |
|
||||
|
||||
Quando arrivano gli originali mancanti vanno messi qui con i nomi di §10.3 e i ritagli in `miniature/` si possono cancellare.
|
||||
+11
-3
@@ -141,6 +141,9 @@ cliccare: è il clic che registra ruolo e nome accessibile.
|
||||
5. **Le schede «Reel» e «Taggati»** di un profilo: clicca la **scheda** e scorri un poco, per ognuna.
|
||||
6. **I tuoi seguiti.** Dal tuo profilo clicca **«Seguiti»** e scorri l'elenco per 3–4 schermate.
|
||||
7. **Un post con più foto** (una serie): aprilo dalla griglia e passa alla foto successiva con la **freccia**.
|
||||
8. **La ricerca** (bersagli `search-open` e `search-box`, issue #37). Clicca **«Cerca»** nella colonna laterale,
|
||||
poi **clicca nella casella** e scrivi a mano le prime lettere di un nome. **Non cliccare nessun risultato** (finirebbe
|
||||
fra le tue ricerche recenti, ed è proprio ciò che Febe non fa mai): chiudi il pannello cliccando di nuovo **«Cerca»**.
|
||||
|
||||
Ci si aspetta: nessuna verifica, nessun avviso.
|
||||
|
||||
@@ -394,15 +397,20 @@ cosa aspettarsi; riferisci per ogni voce «sì/no» e, dove chiesto, la schermat
|
||||
anche `--cdn-di-prova http://127.0.0.1:8482`.
|
||||
2. Avvia Febe **con cartelle di prova** (i dati veri non si toccano):
|
||||
`"%LOCALAPPDATA%\Programs\Febe\Febe.exe" --dati C:\FebeProva\dati --libreria C:\FebeProva\libreria --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30`
|
||||
3. In Account ▸ Aggiungi account ▸ «Per nome utente»: `marta.prova` e `luca.prova`, «Scarica tutto e tieni aggiornato».
|
||||
3. In Account ▸ Aggiungi account scrivi `marta.prova` nella casella e scegli la riga «Aggiungi @marta.prova per nome
|
||||
utente»; lo stesso con `luca.prova`; «Scarica tutto e tieni aggiornato».
|
||||
4. Su `marta.prova`: «Controlla ora».
|
||||
5. Atteso entro qualche minuto, in **Attività**: una sessione con righe «ricetta.…» senza errori; l'anteprima del
|
||||
browser mostra le pagine del sito di prova (fotogrammi con `Page.captureScreenshot`); in **Libreria** le foto e i video
|
||||
di Marta con le miniature (corpo delle risposte con `Network.getResponseBody`, scorrimento con
|
||||
`Input.dispatchMouseEvent`, scaricamenti con `Network.loadNetworkResource` e `IO.read`).
|
||||
6. Riferisci: numero di file arrivati; eventuali righe gialle o rosse di Attività; nel registro, le righe
|
||||
6. **Scrittura nella casella (ricerca dei profili, #37).** Con la finestra del browser fuori schermo, apri di nuovo
|
||||
Aggiungi account e scrivi `mar` nella casella. Atteso entro qualche secondo, sotto «Da Instagram», i profili del sito
|
||||
di prova con la foto (tasti con `Input.dispatchKeyEvent`). Se la finestra dice che il browser «non riceve i tasti»,
|
||||
WebView2 non accetta i tasti fuori schermo: riferiscilo così com'è.
|
||||
7. Riferisci: numero di file arrivati; l'esito del passo 6; eventuali righe gialle o rosse di Attività; nel registro, le righe
|
||||
`[browser]` con «WebView2» e qualunque «Comando CDP … è fallito».
|
||||
7. Prima prova di S3 senza Instagram: Esci, riapri Febe con lo stesso comando **senza** `--accesso-di-prova`. Atteso:
|
||||
8. Prima prova di S3 senza Instagram: Esci, riapri Febe con lo stesso comando **senza** `--accesso-di-prova`. Atteso:
|
||||
Collegamento dice «Collegato» (il cookie del sito di prova è rimasto nel profilo `C:\FebeProva\dati\browser`).
|
||||
|
||||
### C4. S2 — la pagina lavora fuori vista
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 239 KiB After Width: | Height: | Size: 262 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 207 KiB After Width: | Height: | Size: 203 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 236 KiB After Width: | Height: | Size: 212 KiB |
@@ -10,7 +10,7 @@ solo per l'interfaccia di Febe (§10.7).
|
||||
| `02-visualizzatore.png` | `/libreria`, clic su un post con più file, seconda foto | `miniature/02-visualizzatore.png` |
|
||||
| `03-account.png` | `/account?tema=chiaro` | `docs/mockup/03-account.png` |
|
||||
| `03-account-telefono.png` | `/account`, 390 × 844 | (nessuno: tabella come elenco) |
|
||||
| `04-aggiungi-account.png` | `/account?dialogo=aggiungi`, tre profili scelti | `miniature/04-aggiungi-account.png` |
|
||||
| `04-aggiungi-account.png` | `/account?dialogo=aggiungi`, «gaia» scritto nella casella, due profili aggiunti, puntatore su una riga (passo `aggiungi.js`; rifatta il 15/11 da Windows) | `miniature/04-aggiungi-account.png` (superato da #37, vedi sotto) |
|
||||
| `05-account-impostazioni.png` | `/account/3/impostazioni` (@studio.lumen.demo) | `miniature/05-account-impostazioni.png` |
|
||||
| `11-libreria-fermo-tema-scuro.png` | `/libreria?scena=fermo&tema=scuro` | striscia rossa di `miniature/11-attivita-fermo-tema-scuro.png` |
|
||||
| `12-account-storie-tema-scuro.png` | `/account/2?tema=scuro&tipo=storie` (@marta.demo) | `miniature/12-account-storie-tema-scuro.png` |
|
||||
@@ -18,8 +18,8 @@ solo per l'interfaccia di Febe (§10.7).
|
||||
| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività al telefono) |
|
||||
| `account-cronologia.png` | `/account/2/cronologia` | (nessuno) |
|
||||
| `06-attivita.png` | `/attivita?scena=sessione&tema=chiaro` | `miniature/06-attivita.png` |
|
||||
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto | (nessuno: §7.4) |
|
||||
| `07-limiti-e-comportamento.png` | `/impostazioni/limiti`, 1440 × 1470 | `miniature/07-limiti-e-comportamento.png` |
|
||||
| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto (rifatta il 15/11 da Windows: c'è la riga «Ricerche di profili») | (nessuno: §7.4) |
|
||||
| `07-limiti-e-comportamento.png` | `/impostazioni/limiti`, 1440 × 1470 (rifatta il 15/11 da Windows: riga «Ricerche di profili», 240 all'ora e 1.200 al giorno con «Prudente») | `miniature/07-limiti-e-comportamento.png` |
|
||||
| `07-limiti-su-misura.png` | come sopra, un tetto cambiato: «Su misura» e barra di salvataggio attiva | (nessuno: §7.5) |
|
||||
| `08-impostazioni-generali.png` | `/impostazioni/generali` | `docs/mockup/08-impostazioni-generali.png` |
|
||||
| `09-importa-sorgente.png` | `/importa?passo=1&veste=docker` | (nessuno: passo 1 di §9.1) |
|
||||
@@ -68,6 +68,36 @@ dovute ai dati dimostrativi:
|
||||
- **Telefono, libreria.** `14-telefono.png` mostra la libreria; la pagina Attività del mockup al telefono è in
|
||||
`14-attivita-telefono.png`. I filtri a pastiglia vanno a capo su due righe.
|
||||
|
||||
### Aggiungi account dopo la ricerca unica (#37)
|
||||
|
||||
Il mockup 04 mostra due linguette («Dai profili che segui», «Per nome utente») e l'elenco a spunte dei seguiti. La
|
||||
richiesta di #37 (una sola casella, suggerimenti mentre si scrive, con foto, come 4K Stogram) lo supera: finché non c'è
|
||||
un mockup nuovo (domanda Q9 per Alberto), il riferimento è questa schermata. Confronto fatto il 15/11 a 1440 × 900:
|
||||
|
||||
- **Uguale al mockup.** Misure e posizione del dialogo, titolo con la X, colonna destra («Per i 2 account scelti», i
|
||||
tre punti di partenza, «Quanto indietro nel tempo», la nota azzurra), piede con «Elenco letto il…», «Rileggi
|
||||
l'elenco», «Annulla» e il pulsante che dice quanti account aggiunge. Avatar, etichette ed elenchi usano gli stessi
|
||||
elementi del foglio di stile (mockup 13).
|
||||
- **Voluto da #37.** Niente linguette: sotto il titolo c'è una riga di separazione e poi la casella, più alta (40 px)
|
||||
e larga quanto la colonna. Al posto dell'elenco a spunte c'è «Da aggiungere», coperto nella schermata dall'elenco dei
|
||||
suggerimenti: un riquadro sospeso con l'ombra dei menu, diviso in «Profili che segui e account in Febe» e «Da
|
||||
Instagram per «gaia»», righe da 52 px con foto rotonda da 40 px, nome utente in grassetto, nome completo sotto,
|
||||
etichette «Seguito» (con l'icona della persona con la spunta), «Privato», «Già in Febe» e il pulsante «Aggiungi» /
|
||||
«Aggiunto» (azzurro chiaro con la spunta). La riga scelta con la tastiera ha il fondo azzurro chiaro dei filtri,
|
||||
quella sotto il puntatore il grigio dei menu. L'ultima riga, «Aggiungi @gaia per nome utente», resta in parte sotto
|
||||
il bordo: l'elenco scorre.
|
||||
- **«Seleziona tutti»** non è più accanto alla casella: sta nell'elenco completo dei seguiti, che si apre con
|
||||
«Scegli fra tutti i profili che segui (98)» sopra «Da aggiungere».
|
||||
- **Contenuti dimostrativi.** Le foto sono disegni generati; i risultati «Da Instagram» sono nomi inventati dalla
|
||||
dimostrazione (`gaia_foto`, `gaia.viaggi`, `gaia_official` con il segno di profilo verificato).
|
||||
- **Foto nei suggerimenti locali.** Nella dimostrazione ogni riga di «Profili che segui e account in Febe» ha la foto
|
||||
perché la ricerca dimostrativa restituisce anche quei profili. Con Instagram vero una riga locale ha la foto solo se
|
||||
il profilo è già in Febe con la sua foto o se è comparso fra i risultati di una ricerca recente; altrimenti mostra le
|
||||
iniziali (vedi la guida, «Aggiungi account»). Dopo la revisione del 15/11 cambiano solo attributi ARIA: nessuna
|
||||
differenza visibile, la schermata resta quella.
|
||||
- **Telefono** (390 × 844, non nella tabella di §10.7): una colonna; nelle righe le etichette vanno sotto il nome, i nomi
|
||||
lunghi finiscono con i puntini e il pulsante resta a destra; il piede va su due righe.
|
||||
|
||||
### Seconda parte (Attività, Impostazioni, Collegamento, Importa)
|
||||
|
||||
Rifatte con `bash tools/schermate/tutte.sh 8490` (le righe dopo «Part 2»), su una dimostrazione appena avviata: la
|
||||
|
||||
+28
-1
@@ -1,12 +1,39 @@
|
||||
# Stato
|
||||
|
||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||
Aggiornato il 13 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
|
||||
Aggiornato il 15 novembre 2026, versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
|
||||
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
|
||||
fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
|
||||
## In breve
|
||||
|
||||
**15 novembre 2026: una sola casella per cercare i profili, con suggerimenti e foto** (#37).
|
||||
|
||||
- «Aggiungi account» ha una sola casella. Mentre Alberto scrive compaiono subito i suggerimenti locali (profili
|
||||
seguiti e account già in Febe), poi i risultati di Instagram con la foto, uniti senza doppioni. Frecce e Invio
|
||||
aggiungono, Esc chiude l'elenco; più nomi incollati vanno in «Da aggiungere», mai su Instagram; «Scegli fra tutti i
|
||||
profili che segui» apre il vecchio elenco con le caselle.
|
||||
- Come cerca: il browser di Febe apre «Cerca» su Instagram e scrive nella casella con `Input.dispatchKeyEvent`, solo
|
||||
lettere, cifre, «.», «_» e spazi (`SearchKeyMap`, mai Invio, Tab o Esc), dopo aver controllato che il fuoco sia nella
|
||||
casella. Legge la risposta `PolarisSearchBoxRefetchableQuery` (campione ripulito 000002) e **non fa mai clic su un
|
||||
risultato**, che finirebbe fra le ricerche recenti. Solo profili.
|
||||
- Governatore: categoria nuova «Ricerche di profili» con tetti propri (Prudente 240/ora e 1200/giorno, Equilibrato
|
||||
300/1500, Rapido 360/1800) che non consumano quelli della raccolta; si ferma con l'interruttore, la pausa, fuori
|
||||
fascia e quando Alberto usa il browser. In sessione ricerca e motore si danno il turno sull'unica pagina
|
||||
(`PageTurns`); a fine sessione la pagina torna comunque al riposo.
|
||||
- Foto: dal CDN con `BrowserFileFetcher` e un permesso per foto, ridotte a 160 px, solo in memoria (nessun file su
|
||||
disco dice chi si è cercato), servite con `no-store`.
|
||||
- Risposte di Alberto del 15 novembre (righe in `docs/decisioni.md`, §6.1 aggiornato): il controllo del fuoco con
|
||||
`Runtime.evaluate` in sola lettura è ammesso; i turni restano a ogni ricetta e prima di ogni apertura di pagina;
|
||||
l'ascolto di `Network.requestWillBeSent`, solo per l'indirizzo, è ammesso; le foto dei profili seguiti non si
|
||||
scaricano per ora.
|
||||
- Schermate rifatte: 04 (che sostituisce il mockup 04, Q9), 06 e 07 con la riga nuova dei tetti.
|
||||
- **Non verificato qui**: le prove con Chromium (la ricerca intera sul sito di prova e l'interfaccia) girano
|
||||
solo nella CI Linux. **Su Instagram vero la ricerca non parte ancora**: i bersagli `search-open` e `search-box` di
|
||||
`bersagli.instagram.json` sono vuoti (H11) finché Alberto non li raccoglie dal vivo; fino ad allora funzionano i
|
||||
suggerimenti locali e la dimostrazione. Mai provato: la scrittura in WebView2 con la finestra fuori schermo (passo
|
||||
C3 delle prove dal vivo).
|
||||
|
||||
**13 novembre 2026, sera: le prove che cadevano con il runner carico** (#46).
|
||||
|
||||
- Cause trovate, non solo tempi allungati. Tre erano difetti del prodotto:
|
||||
|
||||
@@ -152,8 +152,10 @@ 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.
|
||||
// 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."
|
||||
@@ -540,6 +542,29 @@ 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.
|
||||
/// </summary>
|
||||
private async Task<PageTurn?> TakePageAsync(CancellationToken ct)
|
||||
{
|
||||
if (_engine is not { } engine)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
limit.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
try
|
||||
{
|
||||
return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> CurrentUrlAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
|
||||
+23
-2
@@ -5,6 +5,7 @@ using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Import;
|
||||
@@ -86,6 +87,9 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
|
||||
public CollectionPipeline? Pipeline { get; private set; }
|
||||
|
||||
/// <summary>The profile search (issue #37): local suggestions at once, the site's own search box between engine actions.</summary>
|
||||
public ProfileSearchService? Search { get; private set; }
|
||||
|
||||
public ImportService? Import { get; private set; }
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
@@ -267,6 +271,9 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
var runner = new DeferredRecipeRunner();
|
||||
var engine = new EngineHost(services, runner);
|
||||
Engine = engine;
|
||||
var search = new ProfileSearchService(services);
|
||||
Search = search;
|
||||
search.Start();
|
||||
connection.AttachEngine(engine);
|
||||
EventHandler<bool> drivingChanged = (_, _) => engine.NotifyUserDrivingChanged();
|
||||
browser.UserDriving.Changed += drivingChanged;
|
||||
@@ -282,6 +289,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
s.AddSingleton(Tracker);
|
||||
s.AddSingleton(engine.Monitor);
|
||||
s.AddSingleton<IEngineControl>(new EngineHostControl(engine));
|
||||
s.AddSingleton<IProfileSearch>(search);
|
||||
s.AddSingleton<IConnectionService>(connection);
|
||||
s.AddSingleton<IEngineSettingsControl>(new EngineHostSettingsControl(engine));
|
||||
s.AddSingleton(ingest);
|
||||
@@ -324,7 +332,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
var lifetime = _lifetime.Token;
|
||||
InBackground(() => CleanTemporaryFilesAsync(staging, layout, lifetime));
|
||||
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime));
|
||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||
}
|
||||
|
||||
@@ -388,7 +396,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
}
|
||||
|
||||
/// <summary>The browser, then the pipeline, the downloads, the connection check and the engine.</summary>
|
||||
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, CancellationToken ct)
|
||||
private async Task BringUpBrowserAsync(LibraryIngest ingest, string staging, EngineServices services, EngineHost engine, DeferredRecipeRunner runner, ProfileSearchService search, CancellationToken ct)
|
||||
{
|
||||
var browser = Browser!;
|
||||
await browser.RunAsync(ct).ConfigureAwait(false);
|
||||
@@ -422,9 +430,16 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
UserOwnsPage = () => browser.UserIsDriving && services.Runtime.CurrentSession is null,
|
||||
Log = Log.ForBrowser(),
|
||||
Diagnostics = Diagnostics,
|
||||
PageTurns = services.PageTurns,
|
||||
SearchOptions = search.Options,
|
||||
SearchPhotos = search.Photos,
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
runner.Target = Pipeline.Runner;
|
||||
if (Pipeline.Search is { } searchRunner)
|
||||
{
|
||||
search.Attach(searchRunner, Pipeline.SearchPhotos);
|
||||
}
|
||||
await CheckCollectionConfigurationAsync(Pipeline, engine, ct).ConfigureAwait(false);
|
||||
var changes = Web.Services.GetRequiredService<LibraryChanges>();
|
||||
DisposeOnStop(changes.Attach(Pipeline.Downloads, Clock));
|
||||
@@ -722,6 +737,12 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
await Quietly(() => import.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Search is { } profileSearch)
|
||||
{
|
||||
profileSearch.Detach();
|
||||
await Quietly(() => profileSearch.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (Pipeline is { } pipeline)
|
||||
{
|
||||
await Quietly(() => pipeline.DisposeAsync().AsTask()).ConfigureAwait(false);
|
||||
|
||||
@@ -54,6 +54,7 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
|
||||
/// </remarks>
|
||||
public sealed class ResponseTap : IAsyncDisposable
|
||||
{
|
||||
private const int MaxRequestOrders = 4096;
|
||||
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
|
||||
|
||||
private readonly ICdpSession _cdp;
|
||||
@@ -68,6 +69,8 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
private readonly Dictionary<string, long> _requestOrders = new(StringComparer.Ordinal);
|
||||
private long _requestCounter;
|
||||
private Task? _worker;
|
||||
private volatile string? _mainFrameId;
|
||||
private long _responses;
|
||||
@@ -137,6 +140,7 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
throw new InvalidOperationException("La cattura è già avviata.");
|
||||
}
|
||||
|
||||
_subscriptions.Add(_cdp.On("Network.requestWillBeSent", OnRequestWillBeSent));
|
||||
_subscriptions.Add(_cdp.On("Network.responseReceived", OnResponseReceived));
|
||||
_subscriptions.Add(_cdp.On("Network.loadingFinished", OnLoadingFinished));
|
||||
_subscriptions.Add(_cdp.On("Network.loadingFailed", OnLoadingFailed));
|
||||
@@ -216,6 +220,51 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page starts a request: a site request gets its order (issue #37), kept until its response. Only the host
|
||||
/// kind of the address is looked at; nothing of the request is kept or logged.
|
||||
/// </summary>
|
||||
private void OnRequestWillBeSent(JsonElement p)
|
||||
{
|
||||
if (p.ValueKind != JsonValueKind.Object
|
||||
|| !p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|
||||
|| !p.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var url = request.TryGetProperty("url", out var u) ? u.GetString() : null;
|
||||
if (_hosts.Classify(url) != HostKind.Site)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var order = Interlocked.Increment(ref _requestCounter);
|
||||
lock (_requestOrders)
|
||||
{
|
||||
if (_requestOrders.Count >= MaxRequestOrders)
|
||||
{
|
||||
// Requests whose response never came: their order is forgotten, and their answers count by arrival.
|
||||
_requestOrders.Clear();
|
||||
}
|
||||
|
||||
// A redirect starts the same request again: the later order holds.
|
||||
_requestOrders[requestId] = order;
|
||||
}
|
||||
|
||||
foreach (var observer in SnapshotObservers())
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnRequestStarted(order);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("Cattura: errore in un osservatore delle richieste.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnResponseReceived(JsonElement p)
|
||||
{
|
||||
if (p.ValueKind != JsonValueKind.Object || !p.TryGetProperty("requestId", out var idElement) || !p.TryGetProperty("response", out var response))
|
||||
@@ -245,7 +294,8 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
mime,
|
||||
type,
|
||||
isMainDocument,
|
||||
_clock.Now);
|
||||
_clock.Now,
|
||||
TakeRequestOrder(requestId));
|
||||
|
||||
Interlocked.Increment(ref _responses);
|
||||
foreach (var observer in SnapshotObservers())
|
||||
@@ -271,6 +321,14 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private long TakeRequestOrder(string requestId)
|
||||
{
|
||||
lock (_requestOrders)
|
||||
{
|
||||
return _requestOrders.Remove(requestId, out var order) ? order : 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnLoadingFinished(JsonElement p)
|
||||
{
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
|
||||
@@ -297,8 +355,13 @@ public sealed class ResponseTap : IAsyncDisposable
|
||||
|
||||
private void OnLoadingFailed(JsonElement p)
|
||||
{
|
||||
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
|
||||
&& _inFlight.TryRemove(requestId, out _))
|
||||
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TakeRequestOrder(requestId);
|
||||
if (_inFlight.TryRemove(requestId, out _))
|
||||
{
|
||||
NotifyDropped(requestId, BodyDropReason.LoadingFailed);
|
||||
}
|
||||
|
||||
@@ -79,4 +79,16 @@ public sealed record GestureSettings
|
||||
|
||||
/// <summary>Length of a distraction.</summary>
|
||||
public Interval DistractionMs { get; init; } = new(15000, 90000);
|
||||
|
||||
/// <summary>Gap between two keys while typing (issue #37), before mood and pace.</summary>
|
||||
public Interval KeyGapMs { get; init; } = new(60, 250, 110);
|
||||
|
||||
/// <summary>How long a key is held down.</summary>
|
||||
public Interval KeyHoldMs { get; init; } = new(40, 120);
|
||||
|
||||
/// <summary>Probability of a short hesitation before a key, as a person who thinks of the next letter.</summary>
|
||||
public double TypingHesitationProbability { get; init; } = 0.03;
|
||||
|
||||
/// <summary>Length of such a hesitation, before mood and pace.</summary>
|
||||
public Interval TypingHesitationMs { get; init; } = new(300, 900);
|
||||
}
|
||||
@@ -239,6 +239,84 @@ public sealed class HumanGestures
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Presses one key with a human hold time, through <c>Input.dispatchKeyEvent</c>; with a real Shift key down and
|
||||
/// up around it when the stroke needs Shift. Throws <see cref="GestureInterruptedException"/> while Alberto drives.
|
||||
/// </summary>
|
||||
public async Task PressKeyAsync(KeyStroke key, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
EnsureUserNotDriving();
|
||||
var shift = (key.Modifiers & KeyModifiers.Shift) != 0;
|
||||
var shiftKey = new KeyStroke("Shift", "ShiftLeft", 16, KeyModifiers.Shift, null);
|
||||
var shiftDown = false;
|
||||
var keyDown = false;
|
||||
try
|
||||
{
|
||||
if (shift)
|
||||
{
|
||||
shiftDown = true;
|
||||
await Keyboard.KeyDownAsync(_cdp, shiftKey, ct).ConfigureAwait(false);
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(Draw(new Interval(30, 90))), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
keyDown = true;
|
||||
await Keyboard.KeyDownAsync(_cdp, key, ct).ConfigureAwait(false);
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(Draw(Settings.KeyHoldMs)), ct).ConfigureAwait(false);
|
||||
await Keyboard.KeyUpAsync(_cdp, key, ct).ConfigureAwait(false);
|
||||
keyDown = false;
|
||||
if (shift)
|
||||
{
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(Draw(new Interval(20, 70))), ct).ConfigureAwait(false);
|
||||
await Keyboard.KeyUpAsync(_cdp, shiftKey with { Modifiers = KeyModifiers.None }, ct).ConfigureAwait(false);
|
||||
shiftDown = false;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// A cancelled step never leaves a key or Shift down in the page, which goes to the engine or to Alberto next.
|
||||
if (keyDown || shiftDown)
|
||||
{
|
||||
await ReleaseQuietlyAsync(keyDown ? key : null, shiftDown ? shiftKey with { Modifiers = KeyModifiers.None } : null).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReleaseQuietlyAsync(KeyStroke? key, KeyStroke? shiftKey)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (key is not null)
|
||||
{
|
||||
await Keyboard.KeyUpAsync(_cdp, key, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (shiftKey is not null)
|
||||
{
|
||||
await Keyboard.KeyUpAsync(_cdp, shiftKey, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// The browser is gone or restarting: no key stays down in a page that no longer exists.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gap before the next key while typing: 60–250 ms (median 110) times mood and pace, now and then a short
|
||||
/// hesitation.
|
||||
/// </summary>
|
||||
public async Task TypingGapAsync(CancellationToken ct = default)
|
||||
{
|
||||
var gap = Draw(Settings.KeyGapMs);
|
||||
if (_random.Chance(Settings.TypingHesitationProbability))
|
||||
{
|
||||
gap += Draw(Settings.TypingHesitationMs);
|
||||
}
|
||||
|
||||
await _clock.Delay(TimeSpan.FromMilliseconds(gap * Multiplier), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Waits a drawn time from <paramref name="interval"/> (milliseconds), multiplied by mood and pace.</summary>
|
||||
public async Task<TimeSpan> WaitAsync(Interval interval, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.Browser.Gestures;
|
||||
|
||||
/// <summary>
|
||||
/// The closed key map of the profile search (issue #37): the only characters Febe may type into the site's search
|
||||
/// box, each with its full key stroke. Letters a–z, digits, «.», «_» (Shift and Minus, with a real Shift key) and the
|
||||
/// space. There is no path to Enter, Tab or Escape: <see cref="Keyboard.ForText"/>, which maps a line break to Enter,
|
||||
/// is never used by the search.
|
||||
/// </summary>
|
||||
public static class SearchKeyMap
|
||||
{
|
||||
/// <summary>The stroke for <paramref name="c"/>, or null when the search may not type it.</summary>
|
||||
public static KeyStroke? For(char c)
|
||||
{
|
||||
var text = c.ToString(CultureInfo.InvariantCulture);
|
||||
return c switch
|
||||
{
|
||||
>= 'a' and <= 'z' => new KeyStroke(text, "Key" + char.ToUpperInvariant(c).ToString(CultureInfo.InvariantCulture), char.ToUpperInvariant(c), KeyModifiers.None, text),
|
||||
>= '0' and <= '9' => new KeyStroke(text, "Digit" + text, c, KeyModifiers.None, text),
|
||||
'.' => new KeyStroke(".", "Period", 190, KeyModifiers.None, "."),
|
||||
'_' => new KeyStroke("_", "Minus", 189, KeyModifiers.Shift, "_"),
|
||||
' ' => new KeyStroke(" ", "Space", 32, KeyModifiers.None, " "),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>True when every character of <paramref name="text"/> is in the map.</summary>
|
||||
public static bool CanType(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (For(c) is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Backspace: the only key the search uses to erase.</summary>
|
||||
public static KeyStroke Backspace { get; } = Keyboard.Special(SpecialKey.Backspace);
|
||||
|
||||
/// <summary>End: the only key the search uses to move the caret.</summary>
|
||||
public static KeyStroke End { get; } = Keyboard.Special(SpecialKey.End);
|
||||
}
|
||||
@@ -38,7 +38,12 @@ public sealed record BrowserDriverOptions
|
||||
/// read-only state with <c>Runtime.evaluate</c>, targets found with the target map and clicked with human gestures
|
||||
/// through <c>Input</c>, wheel bursts, and the rest page. It never opens an address outside the site.
|
||||
/// </summary>
|
||||
public sealed class BrowserPageDriver : IPageDriver
|
||||
/// <remarks>
|
||||
/// As <see cref="ISearchInput"/> it types into the site's search box for the profile search (issue #37): the focus
|
||||
/// check is one read-only <c>Runtime.evaluate</c> that never returns the text, and keys come only from the closed
|
||||
/// <see cref="SearchKeyMap"/>.
|
||||
/// </remarks>
|
||||
public sealed class BrowserPageDriver : IPageDriver, ISearchInput
|
||||
{
|
||||
/// <summary>Read-only: the page has loaded and painted (input before the first paint is ignored by Chromium).</summary>
|
||||
private const string ReadyExpression =
|
||||
@@ -190,6 +195,52 @@ public sealed class BrowserPageDriver : IPageDriver
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => _cdp.RestAsync(ct);
|
||||
|
||||
public async Task<SearchFocus> FocusAsync(CancellationToken ct)
|
||||
{
|
||||
var (found, focused, length, atEnd) = await _resolver.FocusAsync(SiteTargets.SearchBox, ct).ConfigureAwait(false);
|
||||
return found ? new SearchFocus(true, focused, length, atEnd) : SearchFocus.None;
|
||||
}
|
||||
|
||||
public Task EndKeyAsync(CancellationToken ct) => _gestures.PressKeyAsync(SearchKeyMap.End, ct);
|
||||
|
||||
public async Task EraseAsync(int count, Action? beforeKey, CancellationToken ct)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
await _gestures.TypingGapAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
beforeKey?.Invoke();
|
||||
await _gestures.PressKeyAsync(SearchKeyMap.Backspace, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(next);
|
||||
var typed = 0;
|
||||
while (true)
|
||||
{
|
||||
if (typed > 0)
|
||||
{
|
||||
await _gestures.TypingGapAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// The checks of the caller run right before the key they allow.
|
||||
if (await next(typed, ct).ConfigureAwait(false) is not { } c)
|
||||
{
|
||||
return typed;
|
||||
}
|
||||
|
||||
// A second line behind the text rules of Core: a character outside the map is never sent.
|
||||
var stroke = SearchKeyMap.For(c) ?? throw new ArgumentException("Carattere che la ricerca non scrive.", nameof(next));
|
||||
await _gestures.PressKeyAsync(stroke, ct).ConfigureAwait(false);
|
||||
typed++;
|
||||
}
|
||||
}
|
||||
|
||||
private (HumanGestures, TargetActions) CreateGestures(double mood)
|
||||
{
|
||||
var gestures = new HumanGestures(_cdp, _clock, _random, mood, _options.Pace, _options.UserIsDriving, _options.Gestures);
|
||||
|
||||
@@ -9,6 +9,7 @@ using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
@@ -91,6 +92,18 @@ public sealed record CollectionPipelineOptions
|
||||
/// recipes, the stop signals and the download queue. Null: nothing is recorded.
|
||||
/// </summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The turns of the one page shared by the recipes and the profile search (issue #37). Null: no profile search
|
||||
/// (the pipeline builds no search runner).
|
||||
/// </summary>
|
||||
public PageTurns? PageTurns { get; init; }
|
||||
|
||||
/// <summary>Times and bounds of the profile search.</summary>
|
||||
public ProfileSearchOptions SearchOptions { get; init; } = ProfileSearchOptions.Default;
|
||||
|
||||
/// <summary>Where the photos of the search results are kept (memory). Null: the search fetches no photo.</summary>
|
||||
public SearchPhotoCache? SearchPhotos { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -101,8 +114,10 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
{
|
||||
private readonly List<IDisposable> _subscriptions = [];
|
||||
|
||||
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets)
|
||||
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets, ProfileSearchRunner? search, SearchPhotoQueue? searchPhotos)
|
||||
{
|
||||
Search = search;
|
||||
SearchPhotos = searchPhotos;
|
||||
Tap = tap;
|
||||
Signals = signals;
|
||||
Capture = capture;
|
||||
@@ -126,6 +141,12 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
|
||||
public DownloadQueue Downloads { get; }
|
||||
|
||||
/// <summary>The browser half of the profile search (issue #37); null without <see cref="CollectionPipelineOptions.PageTurns"/>.</summary>
|
||||
public ProfileSearchRunner? Search { get; }
|
||||
|
||||
/// <summary>The photo queue of the profile search; null without a photo cache.</summary>
|
||||
public SearchPhotoQueue? SearchPhotos { get; }
|
||||
|
||||
public SiteMap SiteMap { get; }
|
||||
|
||||
public TargetMap Targets { get; }
|
||||
@@ -169,18 +190,58 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
Breaker = options.Breaker,
|
||||
Options = options.Recipes,
|
||||
Diagnostics = diagnostics,
|
||||
PageTurns = options.PageTurns,
|
||||
});
|
||||
var fetcher = new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log);
|
||||
var downloads = new DownloadQueue(
|
||||
options.Storage,
|
||||
options.Ingest,
|
||||
new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log),
|
||||
fetcher,
|
||||
options.DataBudget,
|
||||
options.Clock,
|
||||
options.Random,
|
||||
new DownloadOptions { StagingFolder = options.StagingFolder },
|
||||
signals);
|
||||
|
||||
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets);
|
||||
ProfileSearchRunner? search = null;
|
||||
SearchPhotoQueue? searchPhotos = null;
|
||||
if (options.PageTurns is { } turns)
|
||||
{
|
||||
search = new ProfileSearchRunner(
|
||||
driver,
|
||||
driver,
|
||||
capture,
|
||||
siteMap,
|
||||
options.Governor,
|
||||
signals,
|
||||
options.Breaker,
|
||||
options.Clock,
|
||||
options.Random,
|
||||
turns,
|
||||
options.SearchOptions,
|
||||
options.UserIsDriving,
|
||||
diagnostics);
|
||||
if (options.SearchPhotos is { } photos)
|
||||
{
|
||||
// Photos only while the page is on the site: from the rest page the browser may block the CDN (H7).
|
||||
searchPhotos = new SearchPhotoQueue(
|
||||
photos,
|
||||
fetcher,
|
||||
options.Governor,
|
||||
options.DataBudget,
|
||||
options.Breaker,
|
||||
options.Clock,
|
||||
options.Random,
|
||||
options.SearchOptions,
|
||||
signals,
|
||||
() => turns.LastUser is not null)
|
||||
{
|
||||
Diagnostics = diagnostics,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets, search, searchPhotos);
|
||||
pipeline._subscriptions.Add(tap.AddObserver(signals));
|
||||
pipeline._subscriptions.Add(tap.AddConsumer(signals));
|
||||
pipeline._subscriptions.Add(tap.AddObserver(capture));
|
||||
@@ -208,6 +269,11 @@ public sealed class CollectionPipeline : IAsyncDisposable
|
||||
subscription.Dispose();
|
||||
}
|
||||
|
||||
if (SearchPhotos is not null)
|
||||
{
|
||||
await SearchPhotos.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Tap.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -139,6 +139,39 @@ public sealed class TargetResolver
|
||||
};
|
||||
const nameRe = spec.name ? new RegExp(spec.name, 'i') : null;
|
||||
const hrefRe = spec.href ? new RegExp(spec.href, 'i') : null;
|
||||
if (spec.focus) {
|
||||
// The focus check of the search box (issue #37): whether the focus is in the box, how many characters it
|
||||
// holds and whether the caret is at the end. Never its text, and nothing about any other field.
|
||||
const boxes = [];
|
||||
for (const el of document.querySelectorAll('*')) {
|
||||
const role = roleOf(el);
|
||||
if (spec.roles.length > 0 && !spec.roles.includes(role)) continue;
|
||||
if (nameRe && !nameRe.test(nameOf(el, role))) continue;
|
||||
const r = el.getBoundingClientRect();
|
||||
let shown = r.width > 0 && r.height > 0;
|
||||
if (shown && typeof el.checkVisibility === 'function') {
|
||||
shown = el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
|
||||
}
|
||||
if (shown) boxes.push(el);
|
||||
if (boxes.length >= 50) break;
|
||||
}
|
||||
const at = spec.index < 0 ? boxes.length + spec.index : spec.index;
|
||||
const box = at >= 0 && at < boxes.length ? boxes[at] : null;
|
||||
if (!box) return { found: false, focused: false, length: null, atEnd: false };
|
||||
const active = document.activeElement;
|
||||
const inBox = !!active && (active === box || box.contains(active));
|
||||
let length = null;
|
||||
let atEnd = false;
|
||||
if (inBox) {
|
||||
const tag = active.tagName.toLowerCase();
|
||||
const type = (active.getAttribute('type') || '').toLowerCase();
|
||||
if ((tag === 'input' && type !== 'password') || tag === 'textarea') {
|
||||
length = active.value.length;
|
||||
atEnd = active.selectionStart === length && active.selectionEnd === length;
|
||||
}
|
||||
}
|
||||
return { found: true, focused: inBox, length, atEnd };
|
||||
}
|
||||
const candidates = document.querySelectorAll(hrefRe ? 'a[href], area[href]' : '*');
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
@@ -241,6 +274,45 @@ public sealed class TargetResolver
|
||||
return Script.Replace("__SPEC__", json.ToJsonString(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The read-only focus check of a text box target (issue #37): the same role and name query as
|
||||
/// <see cref="BuildExpression"/>, answering only «found, focused, length, caret at the end», never the text.
|
||||
/// </summary>
|
||||
public static string BuildFocusExpression(TargetSpec spec)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(spec);
|
||||
var json = new JsonObject
|
||||
{
|
||||
["roles"] = new JsonArray([.. spec.Roles.Select(r => (JsonNode?)JsonValue.Create(r))]),
|
||||
["name"] = spec.NamePattern is null ? null : TargetMap.ExpandNamePattern(spec.NamePattern, null),
|
||||
["href"] = null,
|
||||
["index"] = spec.Index,
|
||||
["focus"] = true,
|
||||
};
|
||||
return Script.Replace("__SPEC__", json.ToJsonString(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Runs the focus check of <paramref name="id"/>; a target not configured is never looked up.</summary>
|
||||
public async Task<(bool Found, bool Focused, int? Length, bool AtEnd)> FocusAsync(string id, CancellationToken ct = default)
|
||||
{
|
||||
if (!_map.Contains(id) || _map.Get(id) is not { IsConfigured: true } spec)
|
||||
{
|
||||
return (false, false, null, false);
|
||||
}
|
||||
|
||||
var value = await _cdp.EvaluateAsync(BuildFocusExpression(spec), ct).ConfigureAwait(false);
|
||||
if (value.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return (false, false, null, false);
|
||||
}
|
||||
|
||||
var found = value.TryGetProperty("found", out var f) && f.ValueKind == JsonValueKind.True;
|
||||
var focused = found && value.TryGetProperty("focused", out var g) && g.ValueKind == JsonValueKind.True;
|
||||
int? length = focused && value.TryGetProperty("length", out var l) && l.ValueKind == JsonValueKind.Number && l.TryGetInt32(out var n) ? n : null;
|
||||
var atEnd = focused && value.TryGetProperty("atEnd", out var e) && e.ValueKind == JsonValueKind.True;
|
||||
return (found, focused, length, atEnd);
|
||||
}
|
||||
|
||||
private async Task<(List<TargetElement> All, double Width, double Height)> MeasureAsync(TargetSpec spec, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
var value = await _cdp.EvaluateAsync(BuildExpression(spec, parameters), ct).ConfigureAwait(false);
|
||||
|
||||
@@ -24,6 +24,13 @@ public enum ActionKind
|
||||
/// <summary>One page of the list of profiles Alberto follows.</summary>
|
||||
FollowingListPage,
|
||||
|
||||
/// <summary>
|
||||
/// One step of the profile search toward the site: opening Instagram for the search, opening its «Cerca» panel or
|
||||
/// focusing its box, or one burst of typing (issue #37). Outside sessions, with its own wide budget that does not
|
||||
/// consume the collection budgets.
|
||||
/// </summary>
|
||||
ProfileSearch,
|
||||
|
||||
/// <summary>Bytes downloaded from the CDN (daily byte budget).</summary>
|
||||
DataDownload,
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
@@ -265,6 +266,17 @@ public sealed partial class CollectionDiagnostics : IResponseObserver, IDisposab
|
||||
b.Queued[key] = (current.Saves + 1, current.Files + Math.Max(0, files), current.Skipped + Math.Max(0, skipped));
|
||||
});
|
||||
|
||||
/// <summary>Fates of a photo of a search result: downloaded, refused by the CDN or the budget, skipped.</summary>
|
||||
public static readonly IReadOnlySet<string> SearchPhotoOutcomes = new HashSet<string>(StringComparer.Ordinal) { "scaricata", "rifiutata", "saltata" };
|
||||
|
||||
/// <summary>One step of the profile search ended (issue #37): only its outcome, never the text or the profiles.</summary>
|
||||
public void SearchStepEnded(SearchOutcome outcome) =>
|
||||
Record(null, (b, _) => Bump(b.SearchSteps, outcome));
|
||||
|
||||
/// <summary>A photo of a search result was downloaded, refused or skipped.</summary>
|
||||
public void SearchPhotoSettled(string outcome) =>
|
||||
Record(null, (b, _) => Bump(b.SearchPhotos, SearchPhotoOutcomes.Contains(outcome) ? outcome : Other));
|
||||
|
||||
/// <summary>The Governor refused an action (its event <c>Denied</c>).</summary>
|
||||
public void PermitDenied(long? session, ActionKind kind, DenialReason reason) =>
|
||||
Record(session, (b, _) => Bump(b.Denials, (kind, reason)));
|
||||
@@ -1104,6 +1116,10 @@ public sealed partial class CollectionDiagnostics : IResponseObserver, IDisposab
|
||||
|
||||
public long DownloadedBytes { get; set; }
|
||||
|
||||
public Dictionary<SearchOutcome, int> SearchSteps { get; } = [];
|
||||
|
||||
public Dictionary<string, int> SearchPhotos { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public OverflowCounter Overflow { get; } = new();
|
||||
|
||||
public void Touch(DateTimeOffset now)
|
||||
@@ -1181,6 +1197,8 @@ public sealed partial class CollectionDiagnostics : IResponseObserver, IDisposab
|
||||
FilesQueued = [.. Queued.Select(q => new QueuedFiles(q.Key.Kind, q.Key.Outcome, q.Value.Saves, q.Value.Files, q.Value.Skipped)).OrderBy(q => q.Kind).ThenBy(q => q.Outcome, StringComparer.Ordinal)],
|
||||
Downloads = [.. Downloads.Select(d => new DownloadGroup(d.Key.Kind, d.Key.Step, d.Value.Count, d.Value.Bytes) { Cause = d.Key.Cause }).OrderBy(d => d.Kind).ThenBy(d => d.Step).ThenBy(d => d.Cause, StringComparer.Ordinal)],
|
||||
DownloadedBytes = DownloadedBytes,
|
||||
SearchSteps = [.. SearchSteps.Select(s => new SearchStepCount(s.Key, s.Value)).OrderBy(s => s.Outcome)],
|
||||
SearchPhotos = [.. SearchPhotos.Select(s => new SearchPhotoCount(s.Key, s.Value)).OrderBy(s => s.Outcome, StringComparer.Ordinal)],
|
||||
Overflow = new TraceOverflow
|
||||
{
|
||||
Pages = Overflow.Pages,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
@@ -69,6 +70,12 @@ public sealed record SessionTrace
|
||||
/// <summary>Bytes of the files downloaded (what crossed the network), when the queue said.</summary>
|
||||
public long DownloadedBytes { get; init; }
|
||||
|
||||
/// <summary>Steps of the profile search on the site (issue #37), by how they ended: never a typed text or a name.</summary>
|
||||
public IReadOnlyList<SearchStepCount> SearchSteps { get; init; } = [];
|
||||
|
||||
/// <summary>Photos of search results, by what happened to them («scaricata», «rifiutata», «saltata»).</summary>
|
||||
public IReadOnlyList<SearchPhotoCount> SearchPhotos { get; init; } = [];
|
||||
|
||||
/// <summary>Items not kept because a list was full: counted, never dropped silently.</summary>
|
||||
public TraceOverflow Overflow { get; init; } = new();
|
||||
}
|
||||
@@ -130,6 +137,12 @@ public sealed record SignalLine(DateTimeOffset At, SignalLevel Level, string Cod
|
||||
|
||||
public sealed record DenialCount(ActionKind Action, DenialReason Reason, int Count);
|
||||
|
||||
/// <summary>Search steps that ended the same way (a name of the closed list <see cref="SearchOutcome"/>).</summary>
|
||||
public sealed record SearchStepCount(SearchOutcome Outcome, int Count);
|
||||
|
||||
/// <summary>Photos of search results with the same fate.</summary>
|
||||
public sealed record SearchPhotoCount(string Outcome, int Count);
|
||||
|
||||
/// <summary>Saves of contents read by the recipes: how many, and how many files they put in the download queue.</summary>
|
||||
/// <param name="Outcome">A <see cref="SaveOutcome"/> name, or «Completed» for a «Post singolo» completion.</param>
|
||||
public sealed record QueuedFiles(EntryKind Kind, string Outcome, int Saves, int Files, int Skipped);
|
||||
|
||||
@@ -29,6 +29,11 @@ public enum HostKind
|
||||
/// <param name="ResourceType">Browser resource type (Document, XHR, Fetch, Image, ...), when known.</param>
|
||||
/// <param name="IsMainFrameDocument">True for the document of the main frame (a page load).</param>
|
||||
/// <param name="At">When the response was seen.</param>
|
||||
/// <param name="RequestOrder">
|
||||
/// Order in which the page started the request among the site's requests (from 1, <c>Network.requestWillBeSent</c>);
|
||||
/// 0 when unknown. The profile search (issue #37) tells answers to texts typed before the last key from the answer to
|
||||
/// the text in the box with it.
|
||||
/// </param>
|
||||
public sealed record ResponseDescriptor(
|
||||
string RequestId,
|
||||
HostKind HostKind,
|
||||
@@ -39,7 +44,8 @@ public sealed record ResponseDescriptor(
|
||||
string MimeType,
|
||||
string? ResourceType,
|
||||
bool IsMainFrameDocument,
|
||||
DateTimeOffset At);
|
||||
DateTimeOffset At,
|
||||
long RequestOrder = 0);
|
||||
|
||||
/// <summary>A main-frame navigation: a new document, or a route change inside a single-page site.</summary>
|
||||
/// <param name="HostKind">Site, CDN or other.</param>
|
||||
@@ -92,6 +98,14 @@ public interface IResponseObserver
|
||||
void OnLoadingFinished(string requestId, long encodedBytes)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The page started a request to the site: <paramref name="order"/> is its <see cref="ResponseDescriptor.RequestOrder"/>.
|
||||
/// Nothing else of the request is passed (no address, no body).
|
||||
/// </summary>
|
||||
void OnRequestStarted(long order)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the body of a response did not reach the consumers (closed list: a report may show it).</summary>
|
||||
|
||||
@@ -160,4 +160,30 @@ public sealed record ReadResult
|
||||
|
||||
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
|
||||
public string? KeyStructure { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The answer of the site's search box (issue #37), when this response is one. Its profiles are not in
|
||||
/// <see cref="Profiles"/>, so a search answer never looks like a page of the followed list or a profile check.
|
||||
/// </summary>
|
||||
public SearchAnswer? Search { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The profiles a search box answer gave, in their order (issue #37). Never printed with names.</summary>
|
||||
public sealed record SearchAnswer(IReadOnlyList<SearchProfile> Hits)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Hits = {Hits.Count}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One profile of a search answer. Private and followed are never in the answer: they stay null.</summary>
|
||||
public sealed record SearchProfile(int Position, ProfileInfo Profile, bool? IsVerified)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Position = {Position}, HasPicture = {Profile.Picture is not null}, IsVerified = {IsVerified}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -150,6 +150,40 @@ public sealed record PageKeys
|
||||
public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keys of the answer of the site's own search box (issue #37). The search carries its own profile keys, so a site
|
||||
/// whose other concepts use other keys can still serve the search in its own shape. Only profiles are read: hashtags
|
||||
/// and places are ignored.
|
||||
/// </summary>
|
||||
public sealed record SearchKeys
|
||||
{
|
||||
/// <summary>The key of the search answer: found anywhere in the tree, its value holds <see cref="Items"/>.</summary>
|
||||
public VocabularyKeys Root { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The list of profile results under the root.</summary>
|
||||
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>Order of an item in the list (array order when missing).</summary>
|
||||
public VocabularyKeys Position { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The profile node of an item.</summary>
|
||||
public VocabularyKeys Profile { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Username { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys DisplayName { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The profile picture: the first key present wins (the small one is enough for a suggestion).</summary>
|
||||
public VocabularyKeys Picture { get; init; } = VocabularyKeys.None;
|
||||
|
||||
public VocabularyKeys Verified { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>True when the reader can recognize a search answer.</summary>
|
||||
public bool IsSet => Root.IsSet && Items.IsSet && Id.IsSet && Username.IsSet;
|
||||
}
|
||||
|
||||
/// <summary>Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10).</summary>
|
||||
public enum VocabularyStatus
|
||||
{
|
||||
@@ -185,6 +219,12 @@ public sealed record ReaderVocabulary
|
||||
|
||||
public PageKeys Page { get; init; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// The answer of the site's search box (issue #37). Not among <see cref="MissingConcepts"/>: the collection does not
|
||||
/// depend on it, and without it the search on the site is «da configurare».
|
||||
/// </summary>
|
||||
public SearchKeys Search { get; init; } = new();
|
||||
|
||||
/// <summary>The key under which the response describes the connected account (H10).</summary>
|
||||
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
|
||||
|
||||
@@ -295,6 +335,7 @@ public sealed record ReaderVocabulary
|
||||
var p = file.Profile ?? new ProfileDto();
|
||||
var h = file.Highlight ?? new HighlightDto();
|
||||
var g = file.Page ?? new PageDto();
|
||||
var s = file.Search ?? new SearchDto();
|
||||
return new ReaderVocabulary
|
||||
{
|
||||
Site = file.Site.Trim(),
|
||||
@@ -330,6 +371,18 @@ public sealed record ReaderVocabulary
|
||||
},
|
||||
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items), Cover = K(h.Cover) },
|
||||
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
|
||||
Search = new SearchKeys
|
||||
{
|
||||
Root = K(s.Root),
|
||||
Items = K(s.Items),
|
||||
Position = K(s.Position),
|
||||
Profile = K(s.Profile),
|
||||
Id = K(s.Id),
|
||||
Username = K(s.Username),
|
||||
DisplayName = K(s.DisplayName),
|
||||
Picture = K(s.Picture),
|
||||
Verified = K(s.Verified),
|
||||
},
|
||||
Viewer = K(file.Viewer),
|
||||
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
};
|
||||
@@ -354,6 +407,8 @@ internal sealed class VocabularyFile
|
||||
|
||||
public PageDto? Page { get; set; }
|
||||
|
||||
public SearchDto? Search { get; set; }
|
||||
|
||||
public List<string>? Viewer { get; set; }
|
||||
|
||||
public RelevanceDto? Relevance { get; set; }
|
||||
@@ -453,6 +508,29 @@ internal sealed class PageDto
|
||||
public List<string>? Cursor { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class SearchDto
|
||||
{
|
||||
public string? Note { get; set; }
|
||||
|
||||
public List<string>? Root { get; set; }
|
||||
|
||||
public List<string>? Items { get; set; }
|
||||
|
||||
public List<string>? Position { get; set; }
|
||||
|
||||
public List<string>? Profile { get; set; }
|
||||
|
||||
public List<string>? Id { get; set; }
|
||||
|
||||
public List<string>? Username { get; set; }
|
||||
|
||||
public List<string>? DisplayName { get; set; }
|
||||
|
||||
public List<string>? Picture { get; set; }
|
||||
|
||||
public List<string>? Verified { get; set; }
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
|
||||
@@ -44,6 +44,22 @@ public sealed class ShapeReader
|
||||
|
||||
var profiles = walk.Profiles.Values.ToList();
|
||||
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
|
||||
if (walk.Search is not null)
|
||||
{
|
||||
// A search answer, even with no profile in it: never an empty page and never an unknown shape (issue #37).
|
||||
return new ReadResult
|
||||
{
|
||||
Shape = ReadShape.Recognized,
|
||||
Search = walk.Search,
|
||||
Contents = walk.Contents,
|
||||
Profiles = profiles,
|
||||
Highlights = walk.Highlights,
|
||||
Page = walk.Page,
|
||||
Viewer = viewer,
|
||||
ViewerId = viewer?.Id ?? walk.ViewerId,
|
||||
};
|
||||
}
|
||||
|
||||
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
|
||||
{
|
||||
return new ReadResult
|
||||
@@ -173,6 +189,13 @@ public sealed class ShapeReader
|
||||
|
||||
foreach (var property in node.EnumerateObject())
|
||||
{
|
||||
if (IsSearchRoot(property, out var items))
|
||||
{
|
||||
// The search answer: read with its own keys, and its subtree is not walked for generic profiles.
|
||||
walk.Search ??= ReadSearch(items);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
Visit(property.Value, walk, inherited, highlightId, depth + 1);
|
||||
@@ -180,6 +203,60 @@ public sealed class ShapeReader
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A member named like the search root, whose value holds the list of results (issue #37).</summary>
|
||||
private bool IsSearchRoot(JsonProperty property, out JsonElement items)
|
||||
{
|
||||
items = default;
|
||||
var search = _v.Search;
|
||||
return search.IsSet
|
||||
&& property.Value.ValueKind == JsonValueKind.Object
|
||||
&& search.Root.Paths.Contains(property.Name, StringComparer.Ordinal)
|
||||
&& search.Items.TryGet(property.Value, out items)
|
||||
&& items.ValueKind == JsonValueKind.Array;
|
||||
}
|
||||
|
||||
/// <summary>The profiles of a search answer in their order; hashtags and places are never read.</summary>
|
||||
private SearchAnswer ReadSearch(JsonElement items)
|
||||
{
|
||||
var search = _v.Search;
|
||||
var hits = new List<SearchProfile>();
|
||||
var index = 0;
|
||||
foreach (var item in items.EnumerateArray())
|
||||
{
|
||||
var order = index++;
|
||||
if (item.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var node = search.Profile.TryGet(item, out var inner) && inner.ValueKind == JsonValueKind.Object ? inner : item;
|
||||
var id = AsText(Get(search.Id, node));
|
||||
var username = AsText(Get(search.Username, node));
|
||||
if (id is null || string.IsNullOrWhiteSpace(username))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
FileVersion? picture = null;
|
||||
if (search.Picture.TryGet(node, out var pictureNode))
|
||||
{
|
||||
picture = ReadVersions(pictureNode).MaxBy(x => x.Version.Area)?.Version;
|
||||
}
|
||||
|
||||
var profile = new ProfileInfo
|
||||
{
|
||||
Id = id,
|
||||
Username = username.Trim(),
|
||||
DisplayName = AsText(Get(search.DisplayName, node)),
|
||||
Picture = picture,
|
||||
};
|
||||
var position = AsInt(Get(search.Position, item)) ?? order;
|
||||
hits.Add(new SearchProfile(position, profile, search.Verified.TryGet(node, out var verified) ? AsBool(verified) : null));
|
||||
}
|
||||
|
||||
return new SearchAnswer([.. hits.OrderBy(h => h.Position)]);
|
||||
}
|
||||
|
||||
private bool IsContent(JsonElement node) =>
|
||||
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
|
||||
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
|
||||
@@ -544,6 +621,9 @@ public sealed class ShapeReader
|
||||
/// <summary>Identifier of the connected account when the answer gives no more than that.</summary>
|
||||
public string? ViewerId { get; set; }
|
||||
|
||||
/// <summary>The search box answer, when the response holds one (issue #37).</summary>
|
||||
public SearchAnswer? Search { get; set; }
|
||||
|
||||
/// <summary>Merges what different parts of a response say about the same profile.</summary>
|
||||
public void AddProfile(ProfileInfo profile)
|
||||
{
|
||||
|
||||
@@ -11,6 +11,12 @@ namespace Febe.Core.Collection.Recipes;
|
||||
/// <param name="Result">What the reader recognized, detached from the body.</param>
|
||||
public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, ReadResult Result);
|
||||
|
||||
/// <summary>
|
||||
/// Where the search answers stood at one moment (issue #37): the last search answer that arrived and the last request
|
||||
/// the page started. Pass it to <see cref="CaptureCollector.SearchSince"/>.
|
||||
/// </summary>
|
||||
public readonly record struct SearchAnswerMark(long Arrival, long Request);
|
||||
|
||||
/// <summary>
|
||||
/// Bridge between the response tap and the recipes (spec §6.2, §6.4): every JSON body the site sends is read by the
|
||||
/// <see cref="ShapeReader"/> as it arrives, and the recipes wait for what they expect after a gesture. Bodies are
|
||||
@@ -23,13 +29,18 @@ public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, Re
|
||||
public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
{
|
||||
private const int MaxKept = 2000;
|
||||
private const int MaxSearchKept = 50;
|
||||
|
||||
private readonly ShapeReader _reader;
|
||||
private readonly IClock _clock;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<CapturedRead> _reads = [];
|
||||
private readonly List<CapturedRead> _searchReads = [];
|
||||
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
|
||||
private long _sequence;
|
||||
private long _searchSequence;
|
||||
private long _lastRequestOrder;
|
||||
private DateTimeOffset? _lastArrivalAt;
|
||||
private string? _viewerId;
|
||||
|
||||
public CaptureCollector(ShapeReader reader, IClock clock)
|
||||
@@ -82,6 +93,46 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where the search box answers stand now (issue #37): pass it to <see cref="SearchSince"/>. Search answers have
|
||||
/// their own buffer, so recipe windows (<see cref="Mark"/>, <see cref="Since"/>) never see them. Taken right before
|
||||
/// a key, it separates the requests the page started for the texts before that key from the ones after it.
|
||||
/// </summary>
|
||||
public SearchAnswerMark SearchMark()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return new SearchAnswerMark(_searchSequence, _lastRequestOrder);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Search box answers to requests the page started after <paramref name="mark"/>, oldest request first. An answer
|
||||
/// whose request order is unknown counts by its arrival instead.
|
||||
/// </summary>
|
||||
public IReadOnlyList<CapturedRead> SearchSince(SearchAnswerMark mark)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return [.. _searchReads
|
||||
.Where(r => r.Response.RequestOrder > 0 ? r.Response.RequestOrder > mark.Request : r.Sequence > mark.Arrival)
|
||||
.OrderBy(r => r.Response.RequestOrder)
|
||||
.ThenBy(r => r.Sequence)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When the body of the last response of the site was read (any kind, unrelated ones included).</summary>
|
||||
public DateTimeOffset? LastArrivalAt
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _lastArrivalAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Data responses whose body has not been read yet.</summary>
|
||||
public int Pending
|
||||
{
|
||||
@@ -178,14 +229,31 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
|
||||
var result = _reader.Read(body);
|
||||
Observe(response, result, body);
|
||||
if (result.ViewerId is { } viewerId)
|
||||
lock (_gate)
|
||||
{
|
||||
lock (_gate)
|
||||
_lastArrivalAt = _clock.Now;
|
||||
if (result.ViewerId is { } viewerId)
|
||||
{
|
||||
_viewerId = viewerId;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.Search is not null)
|
||||
{
|
||||
// A search box answer goes to its own buffer: it never stops, fills or judges a recipe (issue #37).
|
||||
lock (_gate)
|
||||
{
|
||||
var found = new CapturedRead(++_searchSequence, response, result);
|
||||
_searchReads.Add(found);
|
||||
if (_searchReads.Count > MaxSearchKept)
|
||||
{
|
||||
_searchReads.RemoveRange(0, _searchReads.Count - MaxSearchKept);
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.Shape == ReadShape.Unrelated)
|
||||
{
|
||||
// Not about contents (promotions, logging): neither data nor an empty page, and not «something new
|
||||
@@ -241,6 +309,17 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnRequestStarted(long order)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (order > _lastRequestOrder)
|
||||
{
|
||||
_lastRequestOrder = order;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IResponseObserver.OnBodyDropped(string requestId)
|
||||
{
|
||||
lock (_gate)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Collection.Recipes;
|
||||
|
||||
/// <summary>
|
||||
/// What the focus check of the site's search box says (issue #37). Never the text: only whether the box is on the
|
||||
/// page, whether the focus is in it, how many characters it holds and whether the caret is at the end.
|
||||
/// </summary>
|
||||
/// <param name="BoxFound">The search box is on the page and visible.</param>
|
||||
/// <param name="Focused">The focus is in the box.</param>
|
||||
/// <param name="Length">Characters in the box, only when the focus is in it (null otherwise).</param>
|
||||
/// <param name="CaretAtEnd">The caret is at the end of the text, with nothing selected.</param>
|
||||
public sealed record SearchFocus(bool BoxFound, bool Focused, int? Length, bool CaretAtEnd)
|
||||
{
|
||||
/// <summary>No box on the page.</summary>
|
||||
public static SearchFocus None { get; } = new(false, false, null, false);
|
||||
|
||||
/// <summary>The box has the focus and the caret is at the end: keys go where Febe wants them.</summary>
|
||||
public bool Ready => BoxFound && Focused && Length is not null && CaretAtEnd;
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"BoxFound = {BoxFound}, Focused = {Focused}, Length = {Length}, CaretAtEnd = {CaretAtEnd}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Typing into the site's own search box (issue #37), with <c>Input.dispatchKeyEvent</c> only: letters, digits,
|
||||
/// «.», «_» and spaces, Backspace and End, never Enter, Tab or Escape. Separate from <see cref="IPageDriver"/>, which
|
||||
/// the recipes use: only the profile search types.
|
||||
/// </summary>
|
||||
public interface ISearchInput
|
||||
{
|
||||
/// <summary>The read-only focus check of the search box.</summary>
|
||||
Task<SearchFocus> FocusAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Presses End: the caret goes to the end of the text.</summary>
|
||||
Task EndKeyAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Presses Backspace <paramref name="count"/> times at a human rhythm; <paramref name="beforeKey"/> runs right
|
||||
/// before every key (the search notes where the page's requests stand).
|
||||
/// </summary>
|
||||
Task EraseAsync(int count, Action? beforeKey, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Types the characters <paramref name="next"/> gives, one at a time at a human rhythm, until it returns null.
|
||||
/// <paramref name="next"/> receives how many characters were typed so far, and may run its own checks (it is
|
||||
/// awaited before every key). Returns how many characters were typed. A character outside the closed key map stops
|
||||
/// the burst with <see cref="ArgumentException"/> before its key is sent.
|
||||
/// </summary>
|
||||
Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct);
|
||||
}
|
||||
@@ -78,10 +78,20 @@ internal sealed class RecipeRun : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Asks the Governor for a counted action; stops in order when refused or when the session is over.</summary>
|
||||
public async Task PermitAsync(ActionKind kind, long? accountId)
|
||||
/// <summary>
|
||||
/// Asks the Governor for a counted action; stops in order when refused or when the session is over. With
|
||||
/// <paramref name="opensPage"/> (the next step opens a page), this is a turn point of the page (issue #37): when the
|
||||
/// profile search waits, it gets the page for one step first, and the checks run again after it.
|
||||
/// </summary>
|
||||
public async Task PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
|
||||
{
|
||||
ThrowIfSignal();
|
||||
if (opensPage && Env.PageTurns is { } turns && turns.EngineTurn is { } turn && await turns.YieldAsync(turn, Ct).ConfigureAwait(false))
|
||||
{
|
||||
// The page may have changed meanwhile: what follows opens a page anyway, but the state is looked at again.
|
||||
ThrowIfSignal();
|
||||
}
|
||||
|
||||
if (Env.Clock.Now > Session.PlannedEnd)
|
||||
{
|
||||
throw Stop(RecipeStatus.Denied, "La sessione è finita: la ricetta riprenderà alla prossima.");
|
||||
@@ -104,6 +114,7 @@ internal sealed class RecipeRun : IDisposable
|
||||
try
|
||||
{
|
||||
load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
|
||||
Env.PageTurns?.NoteOpened(PageUser.Engine);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -47,7 +47,7 @@ public sealed partial class RecipeRunner
|
||||
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
|
||||
}
|
||||
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Post, Values(("code", entry.Code))).ConfigureAwait(false);
|
||||
bool Matches(Readers.ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code);
|
||||
@@ -94,7 +94,7 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(
|
||||
byPage ? SitePages.FollowingFrom : SitePages.Following,
|
||||
|
||||
@@ -251,7 +251,7 @@ public sealed partial class RecipeRunner
|
||||
|
||||
if (Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
|
||||
start = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
@@ -359,7 +359,7 @@ public sealed partial class RecipeRunner
|
||||
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
|
||||
{
|
||||
// Resume where the last run stopped: the page of the site that starts after the stored point.
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.BackfillPage, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
|
||||
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
|
||||
@@ -738,7 +738,7 @@ public sealed partial class RecipeRunner
|
||||
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account, bool waitForGrid = false)
|
||||
{
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
if (Env.SiteMap.IsTargetConfigured(SiteTargets.ProfileNotFound)
|
||||
|
||||
@@ -14,7 +14,7 @@ public sealed partial class RecipeRunner
|
||||
/// </summary>
|
||||
private async Task<RecipeStatus> FollowingSweepAsync(RecipeRun run)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.Home, null, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -45,13 +45,15 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
|
||||
var parameters = Values(("username", account.Username));
|
||||
var fromBar = Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
|
||||
// After a search step the home page may be covered by the site's search panel: the profile is opened instead.
|
||||
var fromBar = Env.PageTurns?.SearchTouchedPage != true
|
||||
&& Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
|
||||
&& Env.SiteMap.Match(SitePages.Home, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is not null
|
||||
&& (await run.FindAsync(SiteTargets.HomeStory, parameters).ConfigureAwait(false)).Found;
|
||||
|
||||
if (!fromBar)
|
||||
{
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
|
||||
@@ -135,7 +137,7 @@ public sealed partial class RecipeRunner
|
||||
var highlightId = ShapeReader.HighlightId(requested);
|
||||
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
|
||||
var parameters = Values(("username", account.Username));
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
|
||||
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
|
||||
var mark = Env.Capture.Mark();
|
||||
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -44,6 +44,12 @@ public sealed record RecipeEnvironment
|
||||
|
||||
/// <summary>The recorder of the diagnostic report (issue #39). Null: nothing is recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The turns of the page shared with the profile search (issue #37): recipes give the page to the search before an
|
||||
/// action that opens a page, when the search waits. Null: no search, no turn points.
|
||||
/// </summary>
|
||||
public PageTurns? PageTurns { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>
|
||||
/// Times and bounds of the profile search (issue #37). Waits marked «× ritmo» are multiplied by the gesture pace of the
|
||||
/// caution profile; every value is an option so that the tests can shorten them.
|
||||
/// </summary>
|
||||
public sealed record ProfileSearchOptions
|
||||
{
|
||||
public static ProfileSearchOptions Default { get; } = new();
|
||||
|
||||
/// <summary>How long the wanted text must stay still before Febe types it (× ritmo).</summary>
|
||||
public TimeSpan EngineDebounce { get; init; } = TimeSpan.FromMilliseconds(350);
|
||||
|
||||
/// <summary>After a step, how long the search keeps the page waiting for the next letter (× ritmo).</summary>
|
||||
public TimeSpan HoldWindow { get; init; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Longest the search keeps the page in one go, however Alberto keeps typing.</summary>
|
||||
public TimeSpan MaxHold { get; init; } = TimeSpan.FromSeconds(20);
|
||||
|
||||
/// <summary>Least wait after the last key before an answer is taken (covers the site's own debounce, × ritmo).</summary>
|
||||
public TimeSpan MinAnswerWait { get; init; } = TimeSpan.FromMilliseconds(700);
|
||||
|
||||
/// <summary>No data response for this long: the page is quiet (× ritmo).</summary>
|
||||
public TimeSpan Quiet { get; init; } = TimeSpan.FromMilliseconds(600);
|
||||
|
||||
/// <summary>Longest wait for the answer after the last key.</summary>
|
||||
public TimeSpan AnswerTimeout { get; init; } = TimeSpan.FromSeconds(8);
|
||||
|
||||
/// <summary>Longest wait for the page to be quiet before the page goes back to the engine.</summary>
|
||||
public TimeSpan ReleaseSettle { get; init; } = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Longest one step may take (above the load timeout of a page plus the waits).</summary>
|
||||
public TimeSpan StepGuard { get; init; } = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>After the dialog closes, how long before the page goes to rest.</summary>
|
||||
public TimeSpan EndGrace { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>With the dialog open and nothing typed for this long, the page goes to rest.</summary>
|
||||
public TimeSpan IdleRest { get; init; } = TimeSpan.FromMinutes(3);
|
||||
|
||||
/// <summary>After the dialog closes, results and cached answers are forgotten after this long.</summary>
|
||||
public TimeSpan DropHitsAfter { get; init; } = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Keys of one burst under one permit of the Governor.</summary>
|
||||
public int KeysPerPermit { get; init; } = 40;
|
||||
|
||||
/// <summary>A focus check every this many keys.</summary>
|
||||
public int FocusCheckEvery { get; init; } = 4;
|
||||
|
||||
/// <summary>How often the waits look at the page and the answers.</summary>
|
||||
public TimeSpan Poll { get; init; } = TimeSpan.FromMilliseconds(100);
|
||||
|
||||
/// <summary>Wait after the «Cerca» button before clicking the box (× ritmo).</summary>
|
||||
public TimeSpan PanelWaitMin { get; init; } = TimeSpan.FromMilliseconds(400);
|
||||
|
||||
/// <summary>Upper bound of <see cref="PanelWaitMin"/>.</summary>
|
||||
public TimeSpan PanelWaitMax { get; init; } = TimeSpan.FromMilliseconds(1000);
|
||||
|
||||
/// <summary>Texts whose answer Febe remembers (no new search on the site for them).</summary>
|
||||
public int CachedTexts { get; init; } = 40;
|
||||
|
||||
/// <summary>How long a remembered answer holds.</summary>
|
||||
public TimeSpan CachedAnswerLifetime { get; init; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>Photos fetched for each answer (the first results).</summary>
|
||||
public int PhotosPerAnswer { get; init; } = 8;
|
||||
|
||||
/// <summary>Photos kept in memory.</summary>
|
||||
public int MaxPhotos { get; init; } = 400;
|
||||
|
||||
/// <summary>Bytes of photos kept in memory.</summary>
|
||||
public long MaxPhotoBytes { get; init; } = 8L * 1024 * 1024;
|
||||
|
||||
/// <summary>A photo older than this is forgotten.</summary>
|
||||
public TimeSpan PhotoLifetime { get; init; } = TimeSpan.FromDays(3);
|
||||
|
||||
/// <summary>Long side of the photos kept (pixels).</summary>
|
||||
public int PhotoLongSide { get; init; } = 160;
|
||||
|
||||
/// <summary>Largest photo file Febe downloads.</summary>
|
||||
public long PhotoMaxDownload { get; init; } = 512 * 1024;
|
||||
|
||||
/// <summary>Photos downloaded at the same time.</summary>
|
||||
public int PhotoConcurrency { get; init; } = 2;
|
||||
|
||||
/// <summary>A signed photo address waiting in the queue is dropped after this long.</summary>
|
||||
public TimeSpan PhotoAddressLifetime { get; init; } = TimeSpan.FromMinutes(10);
|
||||
|
||||
/// <summary>Small pause between two photos of the same worker (bounds).</summary>
|
||||
public TimeSpan PhotoPauseMin { get; init; } = TimeSpan.FromMilliseconds(150);
|
||||
|
||||
/// <summary>Upper bound of <see cref="PhotoPauseMin"/>.</summary>
|
||||
public TimeSpan PhotoPauseMax { get; init; } = TimeSpan.FromMilliseconds(600);
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>
|
||||
/// How one search step ended. <paramref name="Typed"/> is the text the answer belongs to (what Febe typed), never
|
||||
/// printed; <paramref name="Denial"/> is the Governor's refusal when there was one.
|
||||
/// </summary>
|
||||
public sealed record SearchStepResult(SearchOutcome Outcome, string Typed, string? Message, SearchAnswer? Answer = null, Permit? Denial = null)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Outcome = {Outcome}, TypedLength = {Typed.Length}, Hits = {Answer?.Hits.Count}, Denial = {Denial?.Reason}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The browser half of the profile search (issue #37): one step on the site's own search box.</summary>
|
||||
public interface IProfileSearchRunner
|
||||
{
|
||||
/// <summary>Why the search cannot run on this site (missing targets or reader), in Italian; null when it can.</summary>
|
||||
string? NotConfiguredReason { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Types the wanted text into the site's search box and reads the answer. <paramref name="wanted"/> gives the
|
||||
/// current wanted text (already normalized and typable), or null when it is not wanted any more: the step stops
|
||||
/// between two keys. Every gesture follows a permit of the Governor.
|
||||
/// </summary>
|
||||
Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct);
|
||||
|
||||
/// <summary>Waits, briefly, for the page to be quiet before it goes back to the engine.</summary>
|
||||
Task SettleAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>The rest page (spec §6.1), unless the breaker says to leave the page as it is.</summary>
|
||||
Task RestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>A multiplier of the waits (mood × ritmo).</summary>
|
||||
double WaitMultiplier { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One search step on the site (issue #37, design §1.5.3): be on the site (home, under a permit), focus the box
|
||||
/// (open the panel, click the box, End), type in bursts (one permit each) with the closed key map, then take the
|
||||
/// answer to the request the page started last after the last key. It never clicks a result and never presses Enter.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The answers have no echo of the text (cleaned sample 000002): while Febe types, the page may ask for the texts
|
||||
/// before the last key, and their answers may arrive after the right one. So Febe notes where the page's requests
|
||||
/// stand right before every key it sends (<see cref="CaptureCollector.SearchMark"/>), and only an answer to a request
|
||||
/// started after the last key belongs to the text in the box. A page that answers a text again from its own memory
|
||||
/// sends no request: the answer Febe read for that text on the same page is used.
|
||||
/// </remarks>
|
||||
public sealed class ProfileSearchRunner : IProfileSearchRunner
|
||||
{
|
||||
private readonly IPageDriver _driver;
|
||||
private readonly ISearchInput _input;
|
||||
private readonly CaptureCollector _capture;
|
||||
private readonly SiteMap _siteMap;
|
||||
private readonly IGovernor _governor;
|
||||
private readonly IStopSignals _signals;
|
||||
private readonly ICircuitBreaker _breaker;
|
||||
private readonly IClock _clock;
|
||||
private readonly IRandomSource _random;
|
||||
private readonly PageTurns _turns;
|
||||
private readonly ProfileSearchOptions _options;
|
||||
private readonly Func<bool> _userIsDriving;
|
||||
private readonly CollectionDiagnostics? _diagnostics;
|
||||
|
||||
/// <summary>Most answers remembered for one page (see <see cref="_pageAnswers"/>).</summary>
|
||||
private const int MaxPageAnswers = 40;
|
||||
|
||||
/// <summary>What Febe typed into the box on the page of <see cref="_typedGeneration"/> (its own record; never logged).</summary>
|
||||
private string _typed = string.Empty;
|
||||
|
||||
/// <summary>The page (<see cref="PageTurns.Generation"/>) that <see cref="_typed"/>, <see cref="_keyMark"/> and <see cref="_pageAnswers"/> belong to.</summary>
|
||||
private long _typedGeneration = -1;
|
||||
|
||||
/// <summary>Where the page's requests stood right before the last key Febe sent on this page.</summary>
|
||||
private SearchAnswerMark? _keyMark;
|
||||
|
||||
/// <summary>The answers read on this page, by text: the page answers a text again from its memory, without a request.</summary>
|
||||
private readonly Dictionary<string, SearchAnswer> _pageAnswers = new(StringComparer.Ordinal);
|
||||
|
||||
public ProfileSearchRunner(
|
||||
IPageDriver driver,
|
||||
ISearchInput input,
|
||||
CaptureCollector capture,
|
||||
SiteMap siteMap,
|
||||
IGovernor governor,
|
||||
IStopSignals signals,
|
||||
ICircuitBreaker breaker,
|
||||
IClock clock,
|
||||
IRandomSource random,
|
||||
PageTurns turns,
|
||||
ProfileSearchOptions? options = null,
|
||||
Func<bool>? userIsDriving = null,
|
||||
CollectionDiagnostics? diagnostics = null)
|
||||
{
|
||||
_driver = driver ?? throw new ArgumentNullException(nameof(driver));
|
||||
_input = input ?? throw new ArgumentNullException(nameof(input));
|
||||
_capture = capture ?? throw new ArgumentNullException(nameof(capture));
|
||||
_siteMap = siteMap ?? throw new ArgumentNullException(nameof(siteMap));
|
||||
_governor = governor ?? throw new ArgumentNullException(nameof(governor));
|
||||
_signals = signals ?? throw new ArgumentNullException(nameof(signals));
|
||||
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_random = random ?? throw new ArgumentNullException(nameof(random));
|
||||
_turns = turns ?? throw new ArgumentNullException(nameof(turns));
|
||||
_options = options ?? ProfileSearchOptions.Default;
|
||||
_userIsDriving = userIsDriving ?? (() => false);
|
||||
_diagnostics = diagnostics;
|
||||
}
|
||||
|
||||
public double WaitMultiplier => _driver.WaitMultiplier;
|
||||
|
||||
public string? NotConfiguredReason
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_siteMap.HasPage(SitePages.Home) || !_siteMap.IsTargetConfigured(SiteTargets.SearchOpen) || !_siteMap.IsTargetConfigured(SiteTargets.SearchBox))
|
||||
{
|
||||
return "Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.";
|
||||
}
|
||||
|
||||
return _capture.Reader.Vocabulary.Search.IsSet
|
||||
? null
|
||||
: "Febe non sa ancora leggere le risposte della ricerca di questo sito: per ora vedi solo i profili che segui.";
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(wanted);
|
||||
if (wanted() is not { } first)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Interrupted, string.Empty, null);
|
||||
}
|
||||
|
||||
if (NotConfiguredReason is { } reason)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.NotConfigured, first, reason);
|
||||
}
|
||||
|
||||
if (Stop(first) is { } stop)
|
||||
{
|
||||
return stop;
|
||||
}
|
||||
|
||||
// 1. Be on the site: outside a session the page is the rest page.
|
||||
if (!await _driver.IsOnSiteAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
var home = await OpenHomeAsync(first, ct).ConfigureAwait(false);
|
||||
if (home is not null)
|
||||
{
|
||||
return home;
|
||||
}
|
||||
}
|
||||
else if (_turns.Generation != _typedGeneration)
|
||||
{
|
||||
// A page was opened since (by the engine, between two steps): Febe's record of the box no longer holds.
|
||||
ForgetPage();
|
||||
}
|
||||
|
||||
// 2. Focus the box.
|
||||
var focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!focus.Ready)
|
||||
{
|
||||
var focused = await FocusBoxAsync(first, focus, ct).ConfigureAwait(false);
|
||||
if (focused.Result is not null)
|
||||
{
|
||||
return focused.Result;
|
||||
}
|
||||
|
||||
focus = focused.Focus;
|
||||
}
|
||||
|
||||
// 3. Bursts of keys, then the answer.
|
||||
var passes = 0;
|
||||
while (true)
|
||||
{
|
||||
var text = wanted();
|
||||
if (text is null)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Interrupted, _typed, null);
|
||||
}
|
||||
|
||||
if (Stop(text) is { } stopped)
|
||||
{
|
||||
return stopped;
|
||||
}
|
||||
|
||||
if (focus.Length != _typed.Length)
|
||||
{
|
||||
// The site restored a text, or Alberto typed in the box: Febe's record is reset and the box erased.
|
||||
if (++passes > 3)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.FocusLost, text, "Febe non riesce a scrivere nella casella «Cerca»: riprova fra poco.");
|
||||
}
|
||||
|
||||
var unknown = focus.Length ?? 0;
|
||||
var cleared = await BurstAsync(text, unknown, wanted, ct).ConfigureAwait(false);
|
||||
if (cleared.Result is not null)
|
||||
{
|
||||
return cleared.Result;
|
||||
}
|
||||
|
||||
focus = cleared.Focus;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!string.Equals(_typed, text, StringComparison.Ordinal))
|
||||
{
|
||||
var prefix = CommonPrefix(_typed, text);
|
||||
var burst = await BurstAsync(text, _typed.Length - prefix, wanted, ct).ConfigureAwait(false);
|
||||
if (burst.Result is not null)
|
||||
{
|
||||
return burst.Result;
|
||||
}
|
||||
|
||||
focus = burst.Focus;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The box holds the wanted text: read the answer.
|
||||
var answer = await ReadAnswerAsync(text, wanted, ct).ConfigureAwait(false);
|
||||
if (answer is not null)
|
||||
{
|
||||
return answer;
|
||||
}
|
||||
|
||||
// The text changed before any answer came: next burst.
|
||||
focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!focus.Ready)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non è più attiva: riprova.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task SettleAsync(CancellationToken ct) =>
|
||||
_capture.SettleAsync(Scaled(_options.Quiet), _options.ReleaseSettle, _options.Poll, ct);
|
||||
|
||||
public async Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
ForgetPage();
|
||||
if (_breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
|
||||
{
|
||||
// Left as it is, so that Alberto sees what happened (spec §7.6).
|
||||
return;
|
||||
}
|
||||
|
||||
await _driver.RestAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<SearchStepResult?> OpenHomeAsync(string text, CancellationToken ct)
|
||||
{
|
||||
if (_userIsDriving())
|
||||
{
|
||||
return NotPossible(text);
|
||||
}
|
||||
|
||||
if (await _driver.HasSessionCookieAsync(ct).ConfigureAwait(false) is false)
|
||||
{
|
||||
// The same stop path as the recipes: a missing session cookie is a disconnection (§7.6).
|
||||
_signals.ObserveSessionCookie(false);
|
||||
return new SearchStepResult(SearchOutcome.NotConnected, text, "Instagram ha chiuso la sessione di Febe: riconnetti il browser per cercare.");
|
||||
}
|
||||
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
|
||||
{
|
||||
return Denied(text, denied);
|
||||
}
|
||||
|
||||
if (_userIsDriving())
|
||||
{
|
||||
return NotPossible(text);
|
||||
}
|
||||
|
||||
PageLoad load;
|
||||
try
|
||||
{
|
||||
load = await _driver.OpenAsync(_siteMap.BuildPath(SitePages.Home), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_diagnostics?.PageOpened(null, SitePages.Home, ok: false);
|
||||
throw;
|
||||
}
|
||||
|
||||
_turns.NoteOpened(PageUser.Search);
|
||||
ForgetPage();
|
||||
_diagnostics?.PageOpened(null, SitePages.Home, load.Succeeded);
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "La pagina di Instagram non si è caricata: la ricerca riprova al prossimo testo.");
|
||||
}
|
||||
|
||||
if (Stop(text) is { } stop)
|
||||
{
|
||||
return stop;
|
||||
}
|
||||
|
||||
if (!await _driver.IsOnSiteAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "Instagram ha portato il browser fuori dal sito: la ricerca si ferma.");
|
||||
}
|
||||
|
||||
await _driver.WaitAfterLoadAsync(ct).ConfigureAwait(false);
|
||||
return Stop(text);
|
||||
}
|
||||
|
||||
private async Task<(SearchStepResult? Result, SearchFocus Focus)> FocusBoxAsync(string text, SearchFocus focus, CancellationToken ct)
|
||||
{
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
|
||||
{
|
||||
return (Denied(text, denied), focus);
|
||||
}
|
||||
|
||||
if (!focus.BoxFound)
|
||||
{
|
||||
var open = await ClickAsync(SiteTargets.SearchOpen, ct).ConfigureAwait(false);
|
||||
if (!open.Found && open.Status != TargetCheckStatus.NotConfigured)
|
||||
{
|
||||
// One recovery: the page may be a viewer or a list left by a recipe.
|
||||
if (_userIsDriving())
|
||||
{
|
||||
return (NotPossible(text), focus);
|
||||
}
|
||||
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } again)
|
||||
{
|
||||
return (Denied(text, again), focus);
|
||||
}
|
||||
|
||||
if (await OpenHomeAfterPermitAsync(text, ct).ConfigureAwait(false) is { } failed)
|
||||
{
|
||||
return (failed, focus);
|
||||
}
|
||||
|
||||
open = await ClickAsync(SiteTargets.SearchOpen, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!open.Found)
|
||||
{
|
||||
return (new SearchStepResult(SearchOutcome.TargetMissing, text, "Febe non trova «Cerca» sulla pagina di Instagram."), focus);
|
||||
}
|
||||
|
||||
_turns.NoteSearchUsedPage();
|
||||
await _driver.WaitAsync(Scaled(_random.Between(_options.PanelWaitMin, _options.PanelWaitMax)), ct).ConfigureAwait(false);
|
||||
if (Stop(text) is { } stop)
|
||||
{
|
||||
return (stop, focus);
|
||||
}
|
||||
}
|
||||
|
||||
var box = await ClickAsync(SiteTargets.SearchBox, ct).ConfigureAwait(false);
|
||||
if (!box.Found)
|
||||
{
|
||||
return (new SearchStepResult(SearchOutcome.TargetMissing, text, "Febe non trova la casella «Cerca» sulla pagina di Instagram."), focus);
|
||||
}
|
||||
|
||||
_turns.NoteSearchUsedPage();
|
||||
|
||||
// The click may put the caret anywhere in a text already there.
|
||||
await _input.EndKeyAsync(ct).ConfigureAwait(false);
|
||||
focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
return focus.Ready
|
||||
? (null, focus)
|
||||
: (new SearchStepResult(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non ha preso il cursore: Febe non scrive."), focus);
|
||||
}
|
||||
|
||||
private async Task<SearchStepResult?> OpenHomeAfterPermitAsync(string text, CancellationToken ct)
|
||||
{
|
||||
var load = await _driver.OpenAsync(_siteMap.BuildPath(SitePages.Home), ct).ConfigureAwait(false);
|
||||
_turns.NoteOpened(PageUser.Search);
|
||||
ForgetPage();
|
||||
_diagnostics?.PageOpened(null, SitePages.Home, load.Succeeded);
|
||||
if (!load.Succeeded)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "La pagina di Instagram non si è caricata: la ricerca riprova al prossimo testo.");
|
||||
}
|
||||
|
||||
await _driver.WaitAfterLoadAsync(ct).ConfigureAwait(false);
|
||||
return Stop(text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One burst under one permit: <paramref name="erase"/> Backspaces, then the letters of the wanted text while it
|
||||
/// keeps extending what is typed, at most <see cref="ProfileSearchOptions.KeysPerPermit"/> keys.
|
||||
/// </summary>
|
||||
private async Task<(SearchStepResult? Result, SearchFocus Focus)> BurstAsync(string text, int erase, Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
|
||||
{
|
||||
return (Denied(text, denied), SearchFocus.None);
|
||||
}
|
||||
|
||||
// The permit may have waited (spacing, the gap from the engine): the focus is looked at again right before the
|
||||
// first key of the burst (§6.3).
|
||||
var before = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!before.Ready)
|
||||
{
|
||||
return (FocusLost(text), before);
|
||||
}
|
||||
|
||||
var keys = 0;
|
||||
if (erase == 0 && before.Length != _typed.Length)
|
||||
{
|
||||
// The box changed meanwhile: the caller erases it first.
|
||||
return (null, before);
|
||||
}
|
||||
|
||||
if (erase > 0)
|
||||
{
|
||||
var count = Math.Min(erase, _options.KeysPerPermit);
|
||||
await _input.EraseAsync(count, NoteKey, ct).ConfigureAwait(false);
|
||||
keys += count;
|
||||
var after = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (!after.Focused || after.Length is not { } length)
|
||||
{
|
||||
return (FocusLost(text), after);
|
||||
}
|
||||
|
||||
if (length == before.Length)
|
||||
{
|
||||
return (KeysNotReceived(text), after);
|
||||
}
|
||||
|
||||
if (before.Length == _typed.Length && length == _typed.Length - count)
|
||||
{
|
||||
_typed = _typed[..length];
|
||||
}
|
||||
else
|
||||
{
|
||||
// The box held a text Febe did not type: now it holds what is left of it, unknown.
|
||||
_typed = length == 0 ? string.Empty : _typed;
|
||||
if (length != 0)
|
||||
{
|
||||
return (null, after);
|
||||
}
|
||||
}
|
||||
|
||||
if (erase > count || keys >= _options.KeysPerPermit)
|
||||
{
|
||||
return (null, after);
|
||||
}
|
||||
}
|
||||
|
||||
var startLength = _typed.Length;
|
||||
var lost = false;
|
||||
var typed = await _input.TypeAsync(
|
||||
async (index, token) =>
|
||||
{
|
||||
var current = wanted();
|
||||
if (current is null || keys >= _options.KeysPerPermit || current.Length <= _typed.Length || !current.StartsWith(_typed, StringComparison.Ordinal))
|
||||
{
|
||||
// Not wanted any more, done, at the end of the burst, or an erase is needed: the burst ends.
|
||||
return null;
|
||||
}
|
||||
|
||||
if (index > 0 && index % _options.FocusCheckEvery == 0)
|
||||
{
|
||||
var check = await _input.FocusAsync(token).ConfigureAwait(false);
|
||||
if (!check.Ready || check.Length != _typed.Length)
|
||||
{
|
||||
lost = true;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var c = current[_typed.Length];
|
||||
NoteKey();
|
||||
_typed += c;
|
||||
keys++;
|
||||
return c;
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
var focus = await _input.FocusAsync(ct).ConfigureAwait(false);
|
||||
if (typed > 0 && focus.Focused && focus.Length == startLength)
|
||||
{
|
||||
// Not one key reached the box (seen at the end or at a focus check in between).
|
||||
_typed = _typed[..startLength];
|
||||
return (KeysNotReceived(text), focus);
|
||||
}
|
||||
|
||||
if (lost || !focus.Focused || focus.Length is null)
|
||||
{
|
||||
return (FocusLost(text), focus);
|
||||
}
|
||||
|
||||
return (null, focus);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The answer to the text in the box: an answer to a request the page started after the last key, or, when the
|
||||
/// page sends no request for a text it already answered on this page, the answer Febe read then. Null when the text
|
||||
/// changed before any answer came.
|
||||
/// </summary>
|
||||
private async Task<SearchStepResult?> ReadAnswerAsync(string text, Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
var mark = _keyMark ?? _capture.SearchMark();
|
||||
var start = _clock.Now;
|
||||
var least = start + Scaled(_options.MinAnswerWait);
|
||||
var deadline = start + _options.AnswerTimeout;
|
||||
var quiet = Scaled(_options.Quiet);
|
||||
while (true)
|
||||
{
|
||||
if (Stop(text) is { } stop)
|
||||
{
|
||||
return stop;
|
||||
}
|
||||
|
||||
var answers = _capture.SearchSince(mark);
|
||||
var now = _clock.Now;
|
||||
var current = wanted();
|
||||
if (!string.Equals(current, text, StringComparison.Ordinal))
|
||||
{
|
||||
// Alberto kept typing: an answer already here is for this text and is kept, otherwise the next burst
|
||||
// starts at once.
|
||||
return answers.Count > 0 ? Answered(text, answers) : null;
|
||||
}
|
||||
|
||||
var settled = _capture.Pending == 0 && (_capture.LastArrivalAt is not { } last || now - last >= quiet);
|
||||
if (answers.Count > 0 && (answers[^1].Response.RequestOrder > 0 || (now >= least && settled)))
|
||||
{
|
||||
// A request started after the last key is for this text: no need to wait more. Without the order of
|
||||
// the requests (an older browser event stream), the page must be quiet first.
|
||||
return Answered(text, answers);
|
||||
}
|
||||
|
||||
if (answers.Count == 0 && now >= least && settled && _pageAnswers.TryGetValue(text, out var remembered))
|
||||
{
|
||||
// The page answered this text from its memory: no request, the results Febe read before on this page.
|
||||
return Result(text, remembered);
|
||||
}
|
||||
|
||||
if (now >= deadline)
|
||||
{
|
||||
return answers.Count > 0
|
||||
? Answered(text, answers)
|
||||
: _pageAnswers.TryGetValue(text, out var late)
|
||||
? Result(text, late)
|
||||
: new SearchStepResult(SearchOutcome.NoAnswer, text, "Instagram non ha mandato risultati per questo testo: scrivi un'altra lettera o riprova.");
|
||||
}
|
||||
|
||||
await _clock.Delay(_options.Poll, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private SearchStepResult Answered(string text, IReadOnlyList<CapturedRead> answers)
|
||||
{
|
||||
// The answer to the request started last (SearchSince orders them): earlier ones may belong to a text the page
|
||||
// asked for while Febe was still typing.
|
||||
var answer = answers[^1].Result.Search!;
|
||||
if (!_pageAnswers.ContainsKey(text) && _pageAnswers.Count >= MaxPageAnswers)
|
||||
{
|
||||
_pageAnswers.Clear();
|
||||
}
|
||||
|
||||
_pageAnswers[text] = answer;
|
||||
return Result(text, answer);
|
||||
}
|
||||
|
||||
private static SearchStepResult Result(string text, SearchAnswer answer) =>
|
||||
answer.Hits.Count == 0
|
||||
? new SearchStepResult(SearchOutcome.Empty, text, "Nessun profilo trovato su Instagram.", answer)
|
||||
: new SearchStepResult(SearchOutcome.Ready, text, null, answer);
|
||||
|
||||
/// <summary>Right before a key: from here on, the page's requests are for the text with this key.</summary>
|
||||
private void NoteKey() => _keyMark = _capture.SearchMark();
|
||||
|
||||
/// <summary>A new page (opened, rested, or opened by the engine): nothing Febe knew of the box holds.</summary>
|
||||
private void ForgetPage()
|
||||
{
|
||||
_typed = string.Empty;
|
||||
_keyMark = null;
|
||||
_pageAnswers.Clear();
|
||||
_typedGeneration = _turns.Generation;
|
||||
}
|
||||
|
||||
private async Task<TargetCheck> ClickAsync(string target, CancellationToken ct)
|
||||
{
|
||||
var check = await _driver.ClickAsync(target, null, ct).ConfigureAwait(false);
|
||||
_diagnostics?.TargetClicked(null, target, check.Status);
|
||||
return check;
|
||||
}
|
||||
|
||||
/// <summary>A permit of the Governor for one search action; the refusal when denied.</summary>
|
||||
private async Task<Permit?> PermitAsync(CancellationToken ct)
|
||||
{
|
||||
var permit = await _governor.RequestAsync(ActionKind.ProfileSearch, null, ct).ConfigureAwait(false);
|
||||
return permit.Granted ? null : permit;
|
||||
}
|
||||
|
||||
private SearchStepResult? Stop(string text)
|
||||
{
|
||||
var state = _breaker.State;
|
||||
if (!state.AllowsSiteActions)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Stopped, text, Governor.BreakerMessage(state, _clock.Now, _clock.LocalZone));
|
||||
}
|
||||
|
||||
return _userIsDriving() ? NotPossible(text) : null;
|
||||
}
|
||||
|
||||
private static SearchStepResult Denied(string text, Permit permit) => new(SearchOutcome.Denied, text, permit.Message, Denial: permit);
|
||||
|
||||
private static SearchStepResult NotPossible(string text) =>
|
||||
new(SearchOutcome.NotPossible, text, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
|
||||
|
||||
private static SearchStepResult FocusLost(string text) =>
|
||||
new(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non è più attiva: Febe smette di scrivere.");
|
||||
|
||||
private static SearchStepResult KeysNotReceived(string text) =>
|
||||
new(SearchOutcome.KeysNotReceived, text, "Il browser di Febe non riceve i tasti: la ricerca su Instagram non funziona su questo computer.");
|
||||
|
||||
private TimeSpan Scaled(TimeSpan value) => value * Math.Max(0.1, _driver.WaitMultiplier);
|
||||
|
||||
private static int CommonPrefix(string a, string b)
|
||||
{
|
||||
var n = Math.Min(a.Length, b.Length);
|
||||
var i = 0;
|
||||
while (i < n && a[i] == b[i])
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,128 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>What the profile search is doing for the wanted text (issue #37). The interface shows it in Italian.</summary>
|
||||
public enum SearchState
|
||||
{
|
||||
/// <summary>Nothing wanted (empty box, dialog closed).</summary>
|
||||
Idle,
|
||||
|
||||
/// <summary>The text is not one Febe types on the site (several names, too short, other characters): local suggestions only.</summary>
|
||||
LocalOnly,
|
||||
|
||||
/// <summary>Waiting for the page: a collection step holds it, or the search spacing.</summary>
|
||||
Waiting,
|
||||
|
||||
/// <summary>Febe is typing on the site or waiting for its answer.</summary>
|
||||
Searching,
|
||||
|
||||
/// <summary>The site answered with profiles.</summary>
|
||||
Ready,
|
||||
|
||||
/// <summary>The site answered with no profile.</summary>
|
||||
Empty,
|
||||
|
||||
/// <summary>No answer of the site came for this text (it may have answered from its own memory).</summary>
|
||||
NoAnswer,
|
||||
|
||||
/// <summary>Alberto is using Febe's browser: the search on the site waits.</summary>
|
||||
NotPossible,
|
||||
|
||||
/// <summary>Outside the active window Febe does not open the site.</summary>
|
||||
OutsideWindow,
|
||||
|
||||
/// <summary>The breaker is open (spec §7.6), or the search's own budget is used up.</summary>
|
||||
Stopped,
|
||||
|
||||
/// <summary>The browser or the engine is not up.</summary>
|
||||
Unavailable,
|
||||
|
||||
/// <summary>The map of the site lacks the search targets, or the readers lack the search answer (H11).</summary>
|
||||
NotConfigured,
|
||||
|
||||
/// <summary>The text holds a character Febe never types (a control character).</summary>
|
||||
Refused,
|
||||
|
||||
/// <summary>A step went wrong; the next text tries again.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>Closed list of how one search step ended: diagnostics count these names, never a text (issue #37).</summary>
|
||||
public enum SearchOutcome
|
||||
{
|
||||
Ready,
|
||||
Empty,
|
||||
NoAnswer,
|
||||
Cached,
|
||||
Refused,
|
||||
Stopped,
|
||||
NotConfigured,
|
||||
NotConnected,
|
||||
OutsideWindow,
|
||||
TargetMissing,
|
||||
FocusLost,
|
||||
KeysNotReceived,
|
||||
PageNotLoaded,
|
||||
BrowserNotResponding,
|
||||
Interrupted,
|
||||
NotPossible,
|
||||
Denied,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One profile the search found or knows. Never printed with its values: the record prints only counts and flags.
|
||||
/// </summary>
|
||||
/// <param name="Position">Order in the site's answer, from 0.</param>
|
||||
/// <param name="InstagramId">The site's identifier of the profile.</param>
|
||||
/// <param name="Username">User name, lowercase.</param>
|
||||
/// <param name="DisplayName">Full name, when the site gives one.</param>
|
||||
/// <param name="IsVerified">Verified mark, when the site says.</param>
|
||||
/// <param name="PhotoKey">Key of the photo in Febe's memory cache (32 hex characters), when it is there.</param>
|
||||
/// <param name="PhotoReady">True once the photo is in the cache.</param>
|
||||
public sealed record SearchHit(int Position, string InstagramId, string Username, string? DisplayName, bool? IsVerified, string? PhotoKey, bool PhotoReady)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Position = {Position}, HasDisplayName = {DisplayName is not null}, IsVerified = {IsVerified}, PhotoReady = {PhotoReady}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the search shows now. <paramref name="Owner"/> is the random id of the window that wrote the text last;
|
||||
/// <paramref name="Text"/> is the text Febe typed (or would type), as the interface labels results «per "testo"».
|
||||
/// </summary>
|
||||
public sealed record SearchView(long Version, string Owner, string Text, SearchState State, string? Message, IReadOnlyList<SearchHit> Hits, DateTimeOffset? RetryAfter)
|
||||
{
|
||||
public static SearchView Initial { get; } = new(0, string.Empty, string.Empty, SearchState.Idle, null, [], null);
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Version = {Version}, State = {State}, Hits = {Hits.Count}, TextLength = {Text.Length}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The profile search as the interface sees it (issue #37): one wanted text at a time (the last window that writes
|
||||
/// wins), the latest view for polling, and the photos of the results from Febe's memory.
|
||||
/// </summary>
|
||||
public interface IProfileSearch
|
||||
{
|
||||
/// <summary>Sets the wanted text of window <paramref name="client"/> and returns at once.</summary>
|
||||
SearchView Update(string client, string text);
|
||||
|
||||
/// <summary>The latest view.</summary>
|
||||
SearchView Current { get; }
|
||||
|
||||
/// <summary>The dialog of window <paramref name="client"/> closed; ignored when another window wrote last.</summary>
|
||||
void End(string client);
|
||||
|
||||
/// <summary>The last result seen with this user name (for adding it with its identifier), server side only.</summary>
|
||||
SearchHit? Known(string username);
|
||||
|
||||
/// <summary>A photo of the memory cache by its key.</summary>
|
||||
bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>
|
||||
/// The photos of the search results, in memory only (issue #37): no file on disk reveals whom Alberto searched for and
|
||||
/// nothing survives a restart. Bounded by count and bytes (least recently used goes first), entries expire, and every
|
||||
/// photo has a random key of 32 hex characters that says nothing about the profile.
|
||||
/// </summary>
|
||||
/// <remarks>Not the library: rule 11 (the library never deletes files by itself) is not touched.</remarks>
|
||||
public sealed class SearchPhotoCache
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly IClock _clock;
|
||||
private readonly ProfileSearchOptions _options;
|
||||
private readonly Dictionary<string, LinkedListNode<Entry>> _byKey = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, LinkedListNode<Entry>> _byProfile = new(StringComparer.Ordinal);
|
||||
private readonly LinkedList<Entry> _lru = new();
|
||||
private long _bytes;
|
||||
|
||||
public SearchPhotoCache(IClock clock, ProfileSearchOptions? options = null)
|
||||
{
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_options = options ?? ProfileSearchOptions.Default;
|
||||
}
|
||||
|
||||
/// <summary>Photos in memory.</summary>
|
||||
public int Count
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _byKey.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bytes in memory.</summary>
|
||||
public long Bytes
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A short hash of the file name of a photo address (the signature in the query is left out).</summary>
|
||||
public static string FileHash(Uri address)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(address);
|
||||
var name = address.AbsolutePath;
|
||||
var slash = name.LastIndexOf('/');
|
||||
name = slash >= 0 ? name[(slash + 1)..] : name;
|
||||
return Convert.ToHexStringLower(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(name)))[..16];
|
||||
}
|
||||
|
||||
/// <summary>The key of the photo of this profile, when it is in memory (any picture).</summary>
|
||||
public string? KeyOf(string instagramId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instagramId);
|
||||
lock (_gate)
|
||||
{
|
||||
DropExpiredLocked();
|
||||
return _byProfile.TryGetValue(instagramId, out var node) ? node.Value.Key : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True when this very picture (same file name) of the profile is already in memory.</summary>
|
||||
public bool Has(string instagramId, string fileHash)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
DropExpiredLocked();
|
||||
return _byProfile.TryGetValue(instagramId, out var node) && node.Value.FileHash == fileHash;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Keeps a photo (already a small JPEG); a new picture of the same profile replaces the old one.</summary>
|
||||
/// <returns>The key of the photo.</returns>
|
||||
public string Put(string instagramId, string fileHash, byte[] jpeg)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instagramId);
|
||||
ArgumentNullException.ThrowIfNull(fileHash);
|
||||
ArgumentNullException.ThrowIfNull(jpeg);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_byProfile.TryGetValue(instagramId, out var old))
|
||||
{
|
||||
RemoveLocked(old);
|
||||
}
|
||||
|
||||
var key = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
|
||||
var node = _lru.AddFirst(new Entry(key, instagramId, fileHash, jpeg, _clock.Now));
|
||||
_byKey[key] = node;
|
||||
_byProfile[instagramId] = node;
|
||||
_bytes += jpeg.Length;
|
||||
while ((_byKey.Count > _options.MaxPhotos || _bytes > _options.MaxPhotoBytes) && _lru.Last is { } last && !ReferenceEquals(last, node))
|
||||
{
|
||||
RemoveLocked(last);
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A photo by its key, as a read-only stream.</summary>
|
||||
public bool TryOpen(string key, [NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
stream = null;
|
||||
if (string.IsNullOrEmpty(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
DropExpiredLocked();
|
||||
if (!_byKey.TryGetValue(key, out var node))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_lru.Remove(node);
|
||||
_lru.AddFirst(node);
|
||||
stream = new MemoryStream(node.Value.Jpeg, writable: false);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets every photo (disconnection, «Scollega», the dialog forgotten).</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_byKey.Clear();
|
||||
_byProfile.Clear();
|
||||
_lru.Clear();
|
||||
_bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void DropExpiredLocked()
|
||||
{
|
||||
var limit = _clock.Now - _options.PhotoLifetime;
|
||||
var node = _lru.Last;
|
||||
while (node is not null)
|
||||
{
|
||||
var previous = node.Previous;
|
||||
if (node.Value.At < limit)
|
||||
{
|
||||
RemoveLocked(node);
|
||||
}
|
||||
|
||||
node = previous;
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveLocked(LinkedListNode<Entry> node)
|
||||
{
|
||||
_lru.Remove(node);
|
||||
_byKey.Remove(node.Value.Key);
|
||||
if (_byProfile.TryGetValue(node.Value.InstagramId, out var current) && ReferenceEquals(current, node))
|
||||
{
|
||||
_byProfile.Remove(node.Value.InstagramId);
|
||||
}
|
||||
|
||||
_bytes -= node.Value.Jpeg.Length;
|
||||
}
|
||||
|
||||
private sealed record Entry(string Key, string InstagramId, string FileHash, byte[] Jpeg, DateTimeOffset At)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Bytes = {Jpeg.Length}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>A photo to fetch: the profile and its picture (the signed address stays in memory, never logged).</summary>
|
||||
public sealed record SearchPhotoRequest(string InstagramId, Uri Address)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append("Photo");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches the photos of the search results (issue #37, design §3) from the CDN through the browser's file fetcher,
|
||||
/// two at a time with small random pauses, and keeps them small in <see cref="SearchPhotoCache"/>. Each photo asks the
|
||||
/// Governor for a <see cref="ActionKind.DataDownload"/> permit and counts its bytes in the daily data budget; a CDN
|
||||
/// status that is a stop signal (§7.6) goes to the signal detector, as the download queue does, and empties the queue.
|
||||
/// It works only while the breaker allows site actions and the page is on the site.
|
||||
/// </summary>
|
||||
public sealed class SearchPhotoQueue : IAsyncDisposable
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly SearchPhotoCache _cache;
|
||||
private readonly IFileFetcher _fetcher;
|
||||
private readonly IGovernor _governor;
|
||||
private readonly IDataBudget _budget;
|
||||
private readonly ICircuitBreaker _breaker;
|
||||
private readonly SignalDetector? _signals;
|
||||
private readonly IClock _clock;
|
||||
private readonly IRandomSource _random;
|
||||
private readonly ProfileSearchOptions _options;
|
||||
private readonly Func<bool> _onSite;
|
||||
private readonly LinkedList<(SearchPhotoRequest Request, DateTimeOffset At)> _queue = new();
|
||||
private readonly HashSet<string> _queued = new(StringComparer.Ordinal);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly List<Task> _workers = [];
|
||||
private int _running;
|
||||
private long _generation;
|
||||
|
||||
public SearchPhotoQueue(
|
||||
SearchPhotoCache cache,
|
||||
IFileFetcher fetcher,
|
||||
IGovernor governor,
|
||||
IDataBudget budget,
|
||||
ICircuitBreaker breaker,
|
||||
IClock clock,
|
||||
IRandomSource random,
|
||||
ProfileSearchOptions? options = null,
|
||||
SignalDetector? signals = null,
|
||||
Func<bool>? onSite = null)
|
||||
{
|
||||
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
|
||||
_fetcher = fetcher ?? throw new ArgumentNullException(nameof(fetcher));
|
||||
_governor = governor ?? throw new ArgumentNullException(nameof(governor));
|
||||
_budget = budget ?? throw new ArgumentNullException(nameof(budget));
|
||||
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_random = random ?? throw new ArgumentNullException(nameof(random));
|
||||
_options = options ?? ProfileSearchOptions.Default;
|
||||
_signals = signals;
|
||||
_onSite = onSite ?? (() => true);
|
||||
}
|
||||
|
||||
/// <summary>A photo landed in the cache: the profile and the key.</summary>
|
||||
public event Action<string, string>? PhotoReady;
|
||||
|
||||
/// <summary>What happened to a photo («scaricata», «rifiutata», «saltata»): for the diagnostic report.</summary>
|
||||
public event Action<string>? Settled;
|
||||
|
||||
/// <summary>The recorder of the diagnostic report. Null: nothing is recorded.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; init; }
|
||||
|
||||
/// <summary>Photos waiting.</summary>
|
||||
public int Waiting
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _queue.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Adds the photos of an answer; those already in memory with the same file name are skipped.</summary>
|
||||
public void Enqueue(IEnumerable<SearchPhotoRequest> photos)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(photos);
|
||||
var now = _clock.Now;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lifetime.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var photo in photos)
|
||||
{
|
||||
if (_cache.Has(photo.InstagramId, SearchPhotoCache.FileHash(photo.Address)) || !_queued.Add(photo.InstagramId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_queue.AddLast((photo, now));
|
||||
}
|
||||
|
||||
while (_running < _options.PhotoConcurrency && _queue.Count > _running)
|
||||
{
|
||||
_running++;
|
||||
_workers.RemoveAll(t => t.IsCompleted);
|
||||
_workers.Add(Task.Run(() => WorkAsync(_lifetime.Token)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops every photo waiting (rest page, stop signal, «Scollega»); one being fetched is not kept.</summary>
|
||||
public void Clear()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_queue.Clear();
|
||||
_queued.Clear();
|
||||
_generation++;
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Task[] workers;
|
||||
lock (_gate)
|
||||
{
|
||||
_queue.Clear();
|
||||
_queued.Clear();
|
||||
workers = [.. _workers];
|
||||
}
|
||||
|
||||
await _lifetime.CancelAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(workers).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Stopping.
|
||||
}
|
||||
|
||||
_lifetime.Dispose();
|
||||
}
|
||||
|
||||
private async Task WorkAsync(CancellationToken ct)
|
||||
{
|
||||
var counted = true;
|
||||
try
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
SearchPhotoRequest request;
|
||||
long generation;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_queue.First is not { } first)
|
||||
{
|
||||
_running--;
|
||||
counted = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.RemoveFirst();
|
||||
request = first.Value.Request;
|
||||
generation = _generation;
|
||||
if (_clock.Now - first.Value.At > _options.PhotoAddressLifetime)
|
||||
{
|
||||
_queued.Remove(request.InstagramId);
|
||||
Report("saltata");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await FetchAsync(request, generation, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// An optional photo: the initials stay. Only the type would be worth noting, and it is not text.
|
||||
Report("rifiutata");
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_queued.Remove(request.InstagramId);
|
||||
}
|
||||
}
|
||||
|
||||
await _clock.Delay(_random.Between(_options.PhotoPauseMin, _options.PhotoPauseMax), ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
// Stopping.
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (counted)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_running = Math.Max(0, _running - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchAsync(SearchPhotoRequest request, long generation, CancellationToken ct)
|
||||
{
|
||||
if (!_breaker.State.AllowsSiteActions || !_onSite())
|
||||
{
|
||||
Clear();
|
||||
Report("saltata");
|
||||
return;
|
||||
}
|
||||
|
||||
var permit = await _governor.RequestAsync(ActionKind.DataDownload, null, ct).ConfigureAwait(false);
|
||||
if (!permit.Granted)
|
||||
{
|
||||
// The daily data budget is used up: the initials stay.
|
||||
Clear();
|
||||
Report("saltata");
|
||||
return;
|
||||
}
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
var result = await _fetcher.FetchAsync(request.Address, buffer, new FetchOptions(MaxBytes: _options.PhotoMaxDownload), ct).ConfigureAwait(false);
|
||||
if (result.BudgetBytes > 0)
|
||||
{
|
||||
await _budget.RecordAsync(result.BudgetBytes, null, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
if (result.HttpStatus is { } status && _signals?.ObserveDownload(request.Address, status) is not null)
|
||||
{
|
||||
// A stop signal of the CDN (e.g. 429): no more photos.
|
||||
Clear();
|
||||
}
|
||||
|
||||
Report("rifiutata");
|
||||
return;
|
||||
}
|
||||
|
||||
buffer.Position = 0;
|
||||
var jpeg = ThumbnailStore.EncodeSmallJpeg(buffer, _options.PhotoLongSide);
|
||||
if (jpeg is null)
|
||||
{
|
||||
Report("rifiutata");
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (generation != _generation)
|
||||
{
|
||||
// Cleared meanwhile (rest page, stop): the photo is not kept.
|
||||
Report("saltata");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var key = _cache.Put(request.InstagramId, SearchPhotoCache.FileHash(request.Address), jpeg);
|
||||
Report("scaricata");
|
||||
PhotoReady?.Invoke(request.InstagramId, key);
|
||||
}
|
||||
|
||||
private void Report(string outcome)
|
||||
{
|
||||
Diagnostics?.SearchPhotoSettled(outcome);
|
||||
Settled?.Invoke(outcome);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Collection.Search;
|
||||
|
||||
/// <summary>What the normalized text of the search box is good for.</summary>
|
||||
public enum SearchQueryKind
|
||||
{
|
||||
/// <summary>Nothing to search.</summary>
|
||||
Empty,
|
||||
|
||||
/// <summary>Febe may type it into the site's search box.</summary>
|
||||
Typable,
|
||||
|
||||
/// <summary>Several names or addresses: they go to the list, Febe does not search them on the site.</summary>
|
||||
SeveralNames,
|
||||
|
||||
/// <summary>A character Febe never types (a control character other than a line break).</summary>
|
||||
Refused,
|
||||
|
||||
/// <summary>Too short, too long, or other characters: local suggestions only.</summary>
|
||||
LocalOnly,
|
||||
}
|
||||
|
||||
/// <summary>The search text after <see cref="SearchText.Normalize"/>. Never printed with the text.</summary>
|
||||
/// <param name="Kind">What it is good for.</param>
|
||||
/// <param name="Typed">The text Febe types (lowercase, no accents, single spaces); empty unless <see cref="SearchQueryKind.Typable"/>.</param>
|
||||
/// <param name="Shown">The cleaned text, for the local suggestions and the label of the results.</param>
|
||||
public sealed record SearchQuery(SearchQueryKind Kind, string Typed, string Shown)
|
||||
{
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Kind = {Kind}, Length = {Typed.Length}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules of what the profile search may type (issue #37), decided here in Core and not in the interface: a line
|
||||
/// break, a tab or any control character is never typed (so nothing can ever press Enter on the site); several names
|
||||
/// stay local; a profile address becomes its user name; accents are removed; only letters, digits, «.», «_» and single
|
||||
/// spaces are typed, from 2 to 40 characters.
|
||||
/// </summary>
|
||||
public static partial class SearchText
|
||||
{
|
||||
/// <summary>Longest text the interface may send (characters, before cleaning).</summary>
|
||||
public const int MaxRawLength = 60;
|
||||
|
||||
/// <summary>Shortest text Febe types on the site.</summary>
|
||||
public const int MinTyped = 2;
|
||||
|
||||
/// <summary>Longest text Febe types on the site.</summary>
|
||||
public const int MaxTyped = 40;
|
||||
|
||||
/// <summary>First path segments of Instagram that are pages, not profiles.</summary>
|
||||
private static readonly HashSet<string> Reserved = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"p", "reel", "reels", "tv", "stories", "explore", "accounts", "direct", "about", "legal", "developer", "web", "challenge", "emails", "session",
|
||||
};
|
||||
|
||||
public static SearchQuery Normalize(string? raw)
|
||||
{
|
||||
if (string.IsNullOrEmpty(raw))
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
|
||||
}
|
||||
|
||||
// 1. Control characters: a line break means several names, any other is refused. Never typed.
|
||||
foreach (var c in raw)
|
||||
{
|
||||
if (c is '\r' or '\n')
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.SeveralNames, string.Empty, string.Empty);
|
||||
}
|
||||
|
||||
if (char.IsControl(c) || char.GetUnicodeCategory(c) is UnicodeCategory.Format or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator)
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.Refused, string.Empty, string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Trim and single spaces.
|
||||
var text = Spaces().Replace(raw.Trim(), " ");
|
||||
if (text.Length == 0)
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
|
||||
}
|
||||
|
||||
// 4. Several names: only an explicit separator or more than one profile address.
|
||||
if (text.Contains(',', StringComparison.Ordinal) || text.Contains(';', StringComparison.Ordinal) || Addresses().Count(text) > 1)
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.SeveralNames, string.Empty, text);
|
||||
}
|
||||
|
||||
// 3. A profile address becomes its user name; a leading @ goes.
|
||||
if (text.Contains("instagram.com", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (ProfileName(text) is not { } name)
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.LocalOnly, string.Empty, text);
|
||||
}
|
||||
|
||||
text = name;
|
||||
}
|
||||
|
||||
text = text.TrimStart('@').Trim();
|
||||
|
||||
// 5. Lowercase, letters with diacritics folded to their base letter.
|
||||
var typed = Fold(text.ToLowerInvariant());
|
||||
var shown = text;
|
||||
|
||||
// 6. Only the closed set of characters, 2 to 40 of them.
|
||||
if (typed.Length < MinTyped || typed.Length > MaxTyped || !Typable().IsMatch(typed))
|
||||
{
|
||||
return new SearchQuery(SearchQueryKind.LocalOnly, string.Empty, shown);
|
||||
}
|
||||
|
||||
return new SearchQuery(SearchQueryKind.Typable, typed, shown);
|
||||
}
|
||||
|
||||
/// <summary>Lowercase text without diacritics, for comparing names (local suggestions use the same rule).</summary>
|
||||
public static string Fold(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var decomposed = text.Normalize(NormalizationForm.FormD);
|
||||
var builder = new StringBuilder(decomposed.Length);
|
||||
foreach (var c in decomposed)
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString().Normalize(NormalizationForm.FormC);
|
||||
}
|
||||
|
||||
private static string? ProfileName(string text)
|
||||
{
|
||||
var address = text.Contains("://", StringComparison.Ordinal) ? text : "https://" + text;
|
||||
if (!Uri.TryCreate(address, UriKind.Absolute, out var uri)
|
||||
|| !(uri.Host.Equals("instagram.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".instagram.com", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var segments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
return segments.Length == 0 || Reserved.Contains(segments[0]) ? null : Uri.UnescapeDataString(segments[0]);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\s+", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Spaces();
|
||||
|
||||
[GeneratedRegex("instagram\\.com/", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)]
|
||||
private static partial Regex Addresses();
|
||||
|
||||
[GeneratedRegex("^[a-z0-9._]+( [a-z0-9._]+)*$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex Typable();
|
||||
}
|
||||
@@ -72,8 +72,14 @@ public static class SiteTargets
|
||||
/// <summary>The command that closes the viewer.</summary>
|
||||
public const string ViewerClose = "viewer-close";
|
||||
|
||||
/// <summary>The command that opens the site's search panel («Cerca» in the side column; issue #37).</summary>
|
||||
public const string SearchOpen = "search-open";
|
||||
|
||||
/// <summary>The search box of that panel, where the profile search types (issue #37).</summary>
|
||||
public const string SearchBox = "search-box";
|
||||
|
||||
public static IReadOnlyList<string> All { get; } =
|
||||
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose];
|
||||
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose, SearchOpen, SearchBox];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -22,6 +22,8 @@
|
||||
"profile-tab-tagged": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post in cui l'account è taggato." },
|
||||
"profile-highlight": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Una raccolta in evidenza ({id})." },
|
||||
"viewer-next": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Zona o comando per andare alla storia successiva." },
|
||||
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." }
|
||||
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." },
|
||||
"search-open": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Il comando «Cerca» della colonna laterale, che apre il pannello di ricerca (ricerca dei profili, issue #37)." },
|
||||
"search-box": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "La casella del pannello «Cerca», dove la ricerca dei profili scrive. Mai cliccare un risultato." }
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@
|
||||
"profile-tab-tagged": { "role": "tab", "name": "^taggati$" },
|
||||
"profile-highlight": { "role": "link", "href": "/evidenza/{id}/" },
|
||||
"viewer-next": { "role": "button", "name": "^storia successiva$" },
|
||||
"viewer-close": { "role": "button", "name": "^chiudi$" }
|
||||
"viewer-close": { "role": "button", "name": "^chiudi$" },
|
||||
"search-open": { "role": "button", "name": "^cerca$", "note": "Il comando «Cerca» della colonna laterale: apre il pannello di ricerca." },
|
||||
"search-box": { "role": "searchbox", "name": "^cerca$", "note": "La casella del pannello di ricerca, dove la ricerca dei profili scrive." }
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,18 @@
|
||||
"hasMore": ["has_next_page", "more_available"],
|
||||
"cursor": ["end_cursor"]
|
||||
},
|
||||
"search": {
|
||||
"note": "Risposta della casella di ricerca (PolarisSearchBoxRefetchableQuery, campione ricerca-profili): xdt_api__v1__fbsearch__topsearch_connection con users[] { position, user }. Niente is_private né friendship_status: «Privato» e «Seguito» vengono solo dai dati di Febe. Hashtag e luoghi si ignorano. Non si leggono mai search_social_context (nomi di chi segui in comune), rank_token, ai_agent_owner_username, attribution_label_text. La foto piccola viene prima: basta per un suggerimento.",
|
||||
"root": ["xdt_api__v1__fbsearch__topsearch_connection"],
|
||||
"items": ["users"],
|
||||
"position": ["position"],
|
||||
"profile": ["user"],
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"picture": ["profile_pic_url", "hd_profile_pic_url_info"],
|
||||
"verified": ["is_verified"]
|
||||
},
|
||||
"relevance": {
|
||||
"note": "Una risposta che non contiene nessuna di queste chiavi non parla di contenuti né di profili e si ignora: promozioni, registri, il segno «storia vista», le definizioni delle pagine. Senza questo elenco ognuna conterebbe come «formato non riconosciuto».",
|
||||
"keys": ["image_versions2", "video_versions", "carousel_media", "taken_at", "username"]
|
||||
|
||||
@@ -44,5 +44,17 @@
|
||||
"hasMore": ["altro"],
|
||||
"cursor": ["dopo"]
|
||||
},
|
||||
"search": {
|
||||
"note": "La casella di ricerca del sito di prova risponde nella forma del campione ripulito di Instagram (ricerca-profili, PolarisSearchBoxRefetchableQuery), eccezione voluta alla regola «formato nostro, chiavi italiane» (tools/Febe.SitoDiProva/LEGGIMI.md): xdt_api__v1__fbsearch__topsearch_connection con users[] { position, user }. Niente is_private né friendship_status: «Privato» e «Seguito» vengono solo dai dati di Febe. Hashtag e luoghi si ignorano. Non si leggono mai search_social_context (nomi di chi segui in comune), rank_token, ai_agent_owner_username, attribution_label_text. La foto piccola viene prima: basta per un suggerimento.",
|
||||
"root": ["xdt_api__v1__fbsearch__topsearch_connection"],
|
||||
"items": ["users"],
|
||||
"position": ["position"],
|
||||
"profile": ["user"],
|
||||
"id": ["pk", "id"],
|
||||
"username": ["username"],
|
||||
"displayName": ["full_name"],
|
||||
"picture": ["profile_pic_url", "hd_profile_pic_url_info"],
|
||||
"verified": ["is_verified"]
|
||||
},
|
||||
"viewer": ["io"]
|
||||
}
|
||||
@@ -66,6 +66,7 @@ public sealed record CautionProfile
|
||||
[ActionKind.BackfillPage] = new(20, 100),
|
||||
[ActionKind.SinglePost] = new(10, 60),
|
||||
[ActionKind.FollowingListPage] = new(15, 60),
|
||||
[ActionKind.ProfileSearch] = new(240, 1200),
|
||||
},
|
||||
DataPerDayBytes = 4 * GB,
|
||||
BackfillPostsPerAccountPerDay = 300,
|
||||
@@ -90,6 +91,7 @@ public sealed record CautionProfile
|
||||
[ActionKind.BackfillPage] = new(30, 180),
|
||||
[ActionKind.SinglePost] = new(15, 100),
|
||||
[ActionKind.FollowingListPage] = new(20, 90),
|
||||
[ActionKind.ProfileSearch] = new(300, 1500),
|
||||
},
|
||||
DataPerDayBytes = 8 * GB,
|
||||
BackfillPostsPerAccountPerDay = 500,
|
||||
@@ -114,6 +116,7 @@ public sealed record CautionProfile
|
||||
[ActionKind.BackfillPage] = new(45, 300),
|
||||
[ActionKind.SinglePost] = new(20, 160),
|
||||
[ActionKind.FollowingListPage] = new(30, 150),
|
||||
[ActionKind.ProfileSearch] = new(360, 1800),
|
||||
},
|
||||
DataPerDayBytes = 16 * GB,
|
||||
BackfillPostsPerAccountPerDay = 800,
|
||||
|
||||
@@ -724,22 +724,34 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
// using the browser (spec §6.1, §7.6).
|
||||
var breaker = s.Breaker.State;
|
||||
var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving;
|
||||
|
||||
if (!keepPage)
|
||||
{
|
||||
// This rest also serves a driving period that ended during the session.
|
||||
Interlocked.Exchange(ref _restAfterDriving, 0);
|
||||
try
|
||||
|
||||
// The rest takes the page turn (issue #37). When the profile search holds or waits for the page, the rest is
|
||||
// left to it (PageTurns.RestOwed): it rests the page when it is done, no session running.
|
||||
var turn = await s.PageTurns.TakeForRestAsync(ct).ConfigureAwait(false);
|
||||
if (turn is not null)
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
await s.Events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
EngineEventCodes.RecipeFailed,
|
||||
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
|
||||
sessionId: record.Id,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
await using (turn.ConfigureAwait(false))
|
||||
{
|
||||
try
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
s.PageTurns.NoteRested();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
await s.Events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
EngineEventCodes.RecipeFailed,
|
||||
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
|
||||
sessionId: record.Id,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -799,7 +811,19 @@ public sealed class EngineHost : IAsyncDisposable
|
||||
|
||||
try
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
// With the page turn (issue #37): a search step in progress is never cut by the rest. When the search holds
|
||||
// or waits for the page, the rest is left to it.
|
||||
var turn = await _s.PageTurns.TakeForRestAsync(ct).ConfigureAwait(false);
|
||||
if (turn is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await using (turn.ConfigureAwait(false))
|
||||
{
|
||||
await _runner.RestAsync(ct).ConfigureAwait(false);
|
||||
_s.PageTurns.NoteRested();
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@@ -27,6 +27,12 @@ public sealed record EngineOptions
|
||||
/// <summary>Minimum distance between two counted actions at the «naturale» gesture pace (spec §7.2); scaled by the pace.</summary>
|
||||
public TimeSpan MinimumSpacing { get; init; } = TimeSpan.FromSeconds(4);
|
||||
|
||||
/// <summary>
|
||||
/// Minimum distance between two profile-search steps, and between a search step and an engine action in either
|
||||
/// direction, at the «naturale» pace (issue #37); scaled by the pace. A pace, not a refusal.
|
||||
/// </summary>
|
||||
public TimeSpan SearchSpacing { get; init; } = TimeSpan.FromSeconds(1.2);
|
||||
|
||||
/// <summary>The first session starts 2–10 minutes after the program (spec §7.2).</summary>
|
||||
public TimeSpan StartupDelayMin { get; init; } = TimeSpan.FromMinutes(2);
|
||||
|
||||
|
||||
@@ -65,6 +65,9 @@ public sealed class EngineServices
|
||||
/// <summary>Current engine and caution settings.</summary>
|
||||
public EngineSettings Settings { get; private set; }
|
||||
|
||||
/// <summary>The turns of the one browser page, shared by the recipes and the profile search (issue #37).</summary>
|
||||
public PageTurns PageTurns { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// The recorder of the diagnostic report (issue #39): told when sessions start and end, and why. Null: nothing is
|
||||
/// recorded. Set by the composition before the engine starts.
|
||||
|
||||
@@ -15,6 +15,9 @@ namespace Febe.Core.Engine;
|
||||
/// <remarks>
|
||||
/// <para>The minimum spacing is a pace, not a refusal: <see cref="RequestAsync"/> waits for it (on <see cref="IClock"/>)
|
||||
/// and then grants; <see cref="EvaluateAsync"/> reports it as <see cref="DenialReason.MinimumSpacing"/>.</para>
|
||||
/// <para>The profile search (<see cref="ActionKind.ProfileSearch"/>, issue #37) has its own branch: no session is needed,
|
||||
/// it has its own gate, budget and spacing, and it keeps a short crossing gap from the engine's actions both ways; the
|
||||
/// breaker, Alberto at the browser, the pause and the active window stop it as they stop the engine.</para>
|
||||
/// <para>CDN downloads are not site actions: <see cref="ActionKind.DataDownload"/> only checks the daily byte budget, also
|
||||
/// during a stop (spec §7.6: queued downloads may complete), and bytes are recorded with <see cref="RecordAsync"/>.</para>
|
||||
/// </remarks>
|
||||
@@ -30,6 +33,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
private readonly EngineOptions _options;
|
||||
private readonly EngineEvents? _events;
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly SemaphoreSlim _searchGate = new(1, 1);
|
||||
private readonly Lock _noticeGate = new();
|
||||
private readonly HashSet<(ActionKind, DateOnly)> _dailyNoticesSent = [];
|
||||
|
||||
@@ -60,6 +64,9 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
/// <summary>Minimum distance between two counted actions at the current gesture pace.</summary>
|
||||
public TimeSpan MinimumSpacing => _options.MinimumSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
|
||||
|
||||
/// <summary>Distance between two search steps, and between a search step and an engine action, at the current pace.</summary>
|
||||
public TimeSpan SearchSpacing => _options.SearchSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
|
||||
|
||||
/// <summary>Budgets in force at <paramref name="now"/>: profile, gradual start and halved budgets, strongest reduction.</summary>
|
||||
public EffectiveBudgets GetEffectiveBudgets(DateTimeOffset now) =>
|
||||
BudgetLimits.Compute(_runtime.Profile, _runtime.RampStart, _breaker.State.HalvedBudgetsUntil, now);
|
||||
@@ -71,13 +78,17 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
return await EvaluateDataAsync(accountId, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await _gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
var search = kind == ActionKind.ProfileSearch;
|
||||
var gate = search ? _searchGate : _gate;
|
||||
await gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var now = _clock.Now;
|
||||
var permit = await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
|
||||
var permit = search
|
||||
? await EvaluateSearchAsync(now, ct).ConfigureAwait(false)
|
||||
: await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
|
||||
if (permit.Reason == DenialReason.MinimumSpacing && permit.RetryAfter is { } retry)
|
||||
{
|
||||
// Spacing is a pace: wait for it, then look again (the state may have changed meanwhile).
|
||||
@@ -92,7 +103,8 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
return permit;
|
||||
}
|
||||
|
||||
var session = _runtime.CurrentSession;
|
||||
// A search step belongs to no session and is not one of its actions (issue #37).
|
||||
var session = search ? null : _runtime.CurrentSession;
|
||||
await _storage.ActionLog.AppendAsync(
|
||||
new ActionLogRecord { At = now, Category = kind, AccountId = accountId, SessionId = session?.SessionId },
|
||||
ct).ConfigureAwait(false);
|
||||
@@ -103,7 +115,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
}
|
||||
finally
|
||||
{
|
||||
_gate.Release();
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,10 +123,12 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
/// What <see cref="RequestAsync"/> would answer now, without recording or waiting (spacing is reported as a
|
||||
/// refusal with its retry time). The scheduler uses it to skip work whose budget is exhausted.
|
||||
/// </summary>
|
||||
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) =>
|
||||
kind == ActionKind.DataDownload
|
||||
? EvaluateDataAsync(accountId, ct)
|
||||
: EvaluateCoreAsync(kind, accountId, _clock.Now, ct);
|
||||
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) => kind switch
|
||||
{
|
||||
ActionKind.DataDownload => EvaluateDataAsync(accountId, ct),
|
||||
ActionKind.ProfileSearch => EvaluateSearchAsync(_clock.Now, ct),
|
||||
_ => EvaluateCoreAsync(kind, accountId, _clock.Now, ct),
|
||||
};
|
||||
|
||||
/// <summary>Budget checks only (no breaker, window, session or spacing): «is there room today for this?».</summary>
|
||||
public async Task<Permit> EvaluateBudgetAsync(ActionKind kind, long? accountId, CancellationToken ct = default)
|
||||
@@ -279,10 +293,97 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
|
||||
previous + spacing);
|
||||
}
|
||||
|
||||
// The crossing gap from the last profile-search step (issue #37), which does not move the spacing above.
|
||||
var crossing = await CrossingGapAsync(ActionKind.ProfileSearch, kind, accountId, now, ct).ConfigureAwait(false);
|
||||
if (crossing is not null)
|
||||
{
|
||||
return crossing;
|
||||
}
|
||||
|
||||
return await CheckAccountAsync(kind, accountId, now, budgets, session, ct).ConfigureAwait(false)
|
||||
?? Permit.Grant(kind, accountId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rules of the profile search (issue #37), in order: breaker (every stop of spec §7.6 stops the search too),
|
||||
/// Alberto at the browser, pause, active window, the search's own budgets (reductions apply), its own spacing, and
|
||||
/// the crossing gap from the engine's last action. No session check and no account check.
|
||||
/// </summary>
|
||||
private async Task<Permit> EvaluateSearchAsync(DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
const ActionKind kind = ActionKind.ProfileSearch;
|
||||
var zone = _clock.LocalZone;
|
||||
var breaker = _breaker.State;
|
||||
if (!breaker.AllowsSiteActions)
|
||||
{
|
||||
return Permit.Deny(kind, null, DenialReason.BreakerOpen, BreakerMessage(breaker, now, zone), breaker.Until);
|
||||
}
|
||||
|
||||
if (_runtime.UserIsDriving)
|
||||
{
|
||||
return Permit.Deny(kind, null, DenialReason.UserIsDriving, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
|
||||
}
|
||||
|
||||
if (_runtime.IsPaused)
|
||||
{
|
||||
return Permit.Deny(kind, null, DenialReason.Paused, "Febe è in pausa: la ricerca su Instagram riprende quando premi «Riprendi».");
|
||||
}
|
||||
|
||||
var window = await _planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
|
||||
if (window is null)
|
||||
{
|
||||
var next = await _planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
|
||||
var when = next is null ? "nei giorni attivi" : ItalianText.Around(next.Start, now, zone);
|
||||
return Permit.Deny(
|
||||
kind,
|
||||
null,
|
||||
DenialReason.OutsideActiveWindow,
|
||||
$"Fuori dalla fascia oraria Febe non apre Instagram: per ora vedi solo i profili che segui. Riprende {when}.",
|
||||
next?.Start);
|
||||
}
|
||||
|
||||
var denial = await CheckCategoryBudgetsAsync(kind, null, now, GetEffectiveBudgets(now), ct).ConfigureAwait(false);
|
||||
if (denial is not null)
|
||||
{
|
||||
return denial;
|
||||
}
|
||||
|
||||
var spacing = SearchSpacing;
|
||||
var lastSearch = await _storage.ActionLog.GetLastActionAtAsync(kind, ct).ConfigureAwait(false);
|
||||
if (lastSearch is { } previous && now - previous < spacing)
|
||||
{
|
||||
return Permit.Deny(
|
||||
kind,
|
||||
null,
|
||||
DenialReason.MinimumSpacing,
|
||||
$"Troppo vicino al passo di ricerca precedente: fra due passi passano almeno {ItalianText.Decimal(spacing.TotalSeconds, 1)} secondi.",
|
||||
previous + spacing);
|
||||
}
|
||||
|
||||
return await CrossingGapAsync(null, kind, null, now, ct).ConfigureAwait(false) ?? Permit.Grant(kind, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The short distance between a search step and an engine action, both ways: <paramref name="other"/> is
|
||||
/// <see cref="ActionKind.ProfileSearch"/> for an engine request, and null (the engine's own actions) for a search.
|
||||
/// </summary>
|
||||
private async Task<Permit?> CrossingGapAsync(ActionKind? other, ActionKind kind, long? accountId, DateTimeOffset now, CancellationToken ct)
|
||||
{
|
||||
var last = await _storage.ActionLog.GetLastActionAtAsync(other, ct).ConfigureAwait(false);
|
||||
var gap = SearchSpacing;
|
||||
if (last is { } previous && now - previous < gap)
|
||||
{
|
||||
return Permit.Deny(
|
||||
kind,
|
||||
accountId,
|
||||
DenialReason.MinimumSpacing,
|
||||
$"Troppo vicino all'azione precedente: fra la ricerca e il motore passano almeno {ItalianText.Decimal(gap.TotalSeconds, 1)} secondi.",
|
||||
previous + gap);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task<Permit?> CheckBudgetsAsync(ActionKind kind, long? accountId, DateTimeOffset now, EffectiveBudgets budgets, CancellationToken ct) =>
|
||||
await CheckCategoryBudgetsAsync(kind, accountId, now, budgets, ct).ConfigureAwait(false)
|
||||
?? await CheckAccountAsync(kind, accountId, now, budgets, _runtime.CurrentSession, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -192,6 +192,7 @@ public static class ItalianText
|
||||
ActionKind.BackfillPage => "pagine di storico",
|
||||
ActionKind.SinglePost => "post singoli",
|
||||
ActionKind.FollowingListPage => "pagine dell'elenco dei seguiti",
|
||||
ActionKind.ProfileSearch => "ricerche di profili",
|
||||
ActionKind.DataDownload => "dati scaricati",
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Febe.Core.Engine;
|
||||
|
||||
/// <summary>Who uses the one page of Febe's browser.</summary>
|
||||
public enum PageUser
|
||||
{
|
||||
/// <summary>The engine: a recipe of a session.</summary>
|
||||
Engine,
|
||||
|
||||
/// <summary>The profile search (issue #37).</summary>
|
||||
Search,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One page, two users (issue #37): the engine's recipes and the profile search take turns on Febe's single browser
|
||||
/// page. A FIFO queue with one holder at a time; cancellable; no timers. The engine takes a turn at the start of each
|
||||
/// recipe and gives it back before an action that opens a page when the search is waiting (<see cref="YieldAsync"/>);
|
||||
/// the search takes it for one step (and keeps it while Alberto keeps typing, bounded by the search itself).
|
||||
/// </summary>
|
||||
/// <remarks>The session never stops for a search: the search only slides in between two engine actions.</remarks>
|
||||
public sealed class PageTurns
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly LinkedList<Waiter> _queue = new();
|
||||
private PageTurn? _holder;
|
||||
private PageUser? _lastUser;
|
||||
private bool _searchTouchedPage;
|
||||
private bool _restOwed;
|
||||
private long _generation;
|
||||
private List<TaskCompletionSource>? _freeWaiters;
|
||||
|
||||
/// <summary>Raised after every rest of the page (the search's photo queue forgets its addresses).</summary>
|
||||
public event Action? Rested;
|
||||
|
||||
/// <summary>Raised when the rest of the page is left to the search (<see cref="TakeForRestAsync"/>).</summary>
|
||||
public event Action? RestLeftToSearch;
|
||||
|
||||
/// <summary>
|
||||
/// Changes every time a page is opened or put to rest: what the search typed in the box holds only within one
|
||||
/// generation (the engine may open pages between two search steps without the search seeing it).
|
||||
/// </summary>
|
||||
public long Generation
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _generation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The engine wanted to rest the page while the search held or waited for it (end of a session, Alberto let go
|
||||
/// of the browser): the search rests it when it is done, no session running. Cleared by a rest, by a page the
|
||||
/// engine opens (the next session rests it), or by <see cref="ForgetOwedRest"/>.
|
||||
/// </summary>
|
||||
public bool RestOwed
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _restOwed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Who opened the page last (null before anyone did, or after a rest).</summary>
|
||||
public PageUser? LastUser
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _lastUser;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True from a search step until the next page the engine opens: the page state of a recipe may be gone.</summary>
|
||||
public bool SearchTouchedPage
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _searchTouchedPage;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Who holds the page now, if anyone.</summary>
|
||||
public PageUser? Holder
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _holder?.User;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while <paramref name="user"/> waits for a turn.</summary>
|
||||
public bool IsWaiting(PageUser user)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _queue.Any(w => w.Turn.User == user);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Waits for a turn of <paramref name="user"/>; dispose the result to give it back.</summary>
|
||||
public async ValueTask<PageTurn> TakeAsync(PageUser user, CancellationToken ct)
|
||||
{
|
||||
var turn = new PageTurn(this, user);
|
||||
await AcquireAsync(turn, ct).ConfigureAwait(false);
|
||||
return turn;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When the other user waits, gives the page to it and waits to have it back (FIFO, so right after the other's
|
||||
/// step). Returns true when it yielded. Does nothing when <paramref name="turn"/> does not hold the page.
|
||||
/// </summary>
|
||||
public async ValueTask<bool> YieldAsync(PageTurn turn, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(turn);
|
||||
var other = turn.User == PageUser.Engine ? PageUser.Search : PageUser.Engine;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!ReferenceEquals(_holder, turn) || !_queue.Any(w => w.Turn.User == other))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ReleaseLocked(turn);
|
||||
}
|
||||
|
||||
await AcquireAsync(turn, ct).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The engine's current turn, for the recipes' yield points; null when the engine holds none.</summary>
|
||||
public PageTurn? EngineTurn
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _holder is { User: PageUser.Engine } turn ? turn : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A turn for a navigation of the engine outside its recipes (the rest page, Alberto's login page): at once when
|
||||
/// the page is free. When the search holds or waits for the page, returns null and records that the rest is left to
|
||||
/// the search (<see cref="RestOwed"/>): it rests the page itself when it is done. Otherwise waits for the turn.
|
||||
/// </summary>
|
||||
public async ValueTask<PageTurn?> TakeForRestAsync(CancellationToken ct)
|
||||
{
|
||||
var turn = new PageTurn(this, PageUser.Engine);
|
||||
bool leftToSearch;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_holder is null && _queue.Count == 0)
|
||||
{
|
||||
_holder = turn;
|
||||
return turn;
|
||||
}
|
||||
|
||||
leftToSearch = _holder?.User == PageUser.Search || _queue.Any(w => w.Turn.User == PageUser.Search);
|
||||
if (leftToSearch)
|
||||
{
|
||||
_restOwed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (leftToSearch)
|
||||
{
|
||||
RestLeftToSearch?.Invoke();
|
||||
return null;
|
||||
}
|
||||
|
||||
await AcquireAsync(turn, ct).ConfigureAwait(false);
|
||||
return turn;
|
||||
}
|
||||
|
||||
/// <summary>The search will not rest the page after all (it stays as it is after a verification, no browser).</summary>
|
||||
public void ForgetOwedRest()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_restOwed = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Completes when nobody holds the page and nobody waits.</summary>
|
||||
public Task WhenFreeAsync(CancellationToken ct)
|
||||
{
|
||||
TaskCompletionSource tcs;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_holder is null && _queue.Count == 0)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
(_freeWaiters ??= []).Add(tcs);
|
||||
}
|
||||
|
||||
return tcs.Task.WaitAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>A page was opened by <paramref name="user"/>.</summary>
|
||||
public void NoteOpened(PageUser user)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lastUser = user;
|
||||
_searchTouchedPage = user == PageUser.Search;
|
||||
_generation++;
|
||||
if (user == PageUser.Engine)
|
||||
{
|
||||
// A session is on the page again: its end rests it.
|
||||
_restOwed = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The search used the page (typed, opened its panel): the engine's page state may be gone.</summary>
|
||||
public void NoteSearchUsedPage()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_searchTouchedPage = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The page went to rest (spec §6.1).</summary>
|
||||
public void NoteRested()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lastUser = null;
|
||||
_searchTouchedPage = false;
|
||||
_restOwed = false;
|
||||
_generation++;
|
||||
}
|
||||
|
||||
Rested?.Invoke();
|
||||
}
|
||||
|
||||
internal void Release(PageTurn turn)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (ReferenceEquals(_holder, turn))
|
||||
{
|
||||
ReleaseLocked(turn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async ValueTask AcquireAsync(PageTurn turn, CancellationToken ct)
|
||||
{
|
||||
Waiter waiter;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_holder is null && _queue.Count == 0)
|
||||
{
|
||||
_holder = turn;
|
||||
return;
|
||||
}
|
||||
|
||||
waiter = new Waiter(turn, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously));
|
||||
waiter.Node = _queue.AddLast(waiter);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await waiter.Ready.Task.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (waiter.Node?.List is not null)
|
||||
{
|
||||
_queue.Remove(waiter.Node);
|
||||
NotifyFreeLocked();
|
||||
throw;
|
||||
}
|
||||
|
||||
// Granted while being cancelled: give it back at once.
|
||||
if (ReferenceEquals(_holder, turn))
|
||||
{
|
||||
ReleaseLocked(turn);
|
||||
}
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseLocked(PageTurn turn)
|
||||
{
|
||||
Debug.Assert(ReferenceEquals(_holder, turn), "Only the holder gives the page back.");
|
||||
_holder = null;
|
||||
if (_queue.First is { } first)
|
||||
{
|
||||
_queue.RemoveFirst();
|
||||
first.Value.Node = null;
|
||||
_holder = first.Value.Turn;
|
||||
first.Value.Ready.TrySetResult();
|
||||
return;
|
||||
}
|
||||
|
||||
NotifyFreeLocked();
|
||||
}
|
||||
|
||||
private void NotifyFreeLocked()
|
||||
{
|
||||
if (_holder is not null || _queue.Count > 0 || _freeWaiters is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var waiter in _freeWaiters)
|
||||
{
|
||||
waiter.TrySetResult();
|
||||
}
|
||||
|
||||
_freeWaiters = null;
|
||||
}
|
||||
|
||||
private sealed class Waiter(PageTurn turn, TaskCompletionSource ready)
|
||||
{
|
||||
public PageTurn Turn { get; } = turn;
|
||||
|
||||
public TaskCompletionSource Ready { get; } = ready;
|
||||
|
||||
public LinkedListNode<Waiter>? Node { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A turn on the page; disposing it gives the page back (to the next in the queue).</summary>
|
||||
public sealed class PageTurn : IAsyncDisposable, IDisposable
|
||||
{
|
||||
private readonly PageTurns _owner;
|
||||
|
||||
internal PageTurn(PageTurns owner, PageUser user)
|
||||
{
|
||||
_owner = owner;
|
||||
User = user;
|
||||
}
|
||||
|
||||
public PageUser User { get; }
|
||||
|
||||
public void Dispose() => _owner.Release(this);
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
_owner.Release(this);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -864,6 +864,35 @@ internal sealed class SessionComposer
|
||||
}
|
||||
}
|
||||
|
||||
// The page is shared with the profile search (issue #37): a recipe starts on its turn. While the search holds
|
||||
// the page the activity says so; the checks below run again once the turn is ours.
|
||||
var turns = _s.PageTurns;
|
||||
var waitsForSearch = turns.Holder is PageUser.Search || turns.IsWaiting(PageUser.Search);
|
||||
if (waitsForSearch)
|
||||
{
|
||||
_s.Runtime.Activity = "In attesa della ricerca dei profili";
|
||||
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
|
||||
}
|
||||
|
||||
PageTurn turn;
|
||||
try
|
||||
{
|
||||
turn = await turns.TakeAsync(PageUser.Engine, ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (waitsForSearch)
|
||||
{
|
||||
_s.Runtime.Activity = null;
|
||||
}
|
||||
}
|
||||
|
||||
await using var heldTurn = turn;
|
||||
if (waitsForSearch && Clock.Now >= state.Context.PlannedEnd && !request.Manual)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!_s.Breaker.State.AllowsSiteActions || _s.Runtime.IsPaused || _s.Runtime.UserIsDriving)
|
||||
{
|
||||
state.Stop = true;
|
||||
|
||||
@@ -117,6 +117,31 @@ public sealed class ThumbnailStore
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-encodes an image to a small JPEG in memory (issue #37, photos of the profile search: never on disk). Returns
|
||||
/// null when the content is not a decodable image.
|
||||
/// </summary>
|
||||
public static byte[]? EncodeSmallJpeg(Stream source, int longSide)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
|
||||
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
|
||||
if (decoded is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var small = Render(decoded, longSide);
|
||||
using var pixmap = small.PeekPixels();
|
||||
if (pixmap is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
|
||||
return data?.ToArray();
|
||||
}
|
||||
|
||||
private static SKBitmap Render(SKBitmap source, int longSide)
|
||||
{
|
||||
var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
|
||||
|
||||
@@ -60,7 +60,10 @@ public interface IActionLogStore
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<ActionKind, BudgetUsage>> GetUsageAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Time of the last action (of a category, or of any category except data downloads when null).</summary>
|
||||
/// <summary>
|
||||
/// Time of the last action of a category, or, when null, of the engine's own actions: neither data downloads nor
|
||||
/// profile-search steps (issue #37), so a search never moves the engine's spacing or its last session end.
|
||||
/// </summary>
|
||||
Task<DateTimeOffset?> GetLastActionAtAsync(ActionKind? category = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Actions in [from, to), oldest first.</summary>
|
||||
|
||||
@@ -222,7 +222,9 @@ internal sealed class ActionLogStore(FebeDatabase db) : IActionLogStore
|
||||
{
|
||||
var command = category is { } k
|
||||
? c.Command("SELECT MAX(at) FROM action_log WHERE category = @c").With("@c", Sql.Enum(k))
|
||||
: c.Command("SELECT MAX(at) FROM action_log WHERE category <> @c").With("@c", Sql.Enum(ActionKind.DataDownload));
|
||||
: c.Command("SELECT MAX(at) FROM action_log WHERE category NOT IN (@c, @s)")
|
||||
.With("@c", Sql.Enum(ActionKind.DataDownload))
|
||||
.With("@s", Sql.Enum(ActionKind.ProfileSearch));
|
||||
var value = command.ExecuteScalar();
|
||||
return value is long ms ? Sql.ToTime(ms) : (DateTimeOffset?)null;
|
||||
},
|
||||
|
||||
@@ -57,7 +57,7 @@ internal static class DemoCommand
|
||||
var address = new Uri(demo.Address, "/libreria");
|
||||
await output.WriteLineAsync($"Pronto: {demo.World.Accounts} account e {Febe.Core.Engine.ItalianText.Number(demo.World.Entries)} elementi dimostrativi.").ConfigureAwait(false);
|
||||
await output.WriteLineAsync($"Apri {address}").ConfigureAwait(false);
|
||||
await output.WriteLineAsync("Scene: ?scena=normale, sessione, fermo, scollegato; tema: ?tema=chiaro o scuro; veste: ?veste=desktop o docker.").ConfigureAwait(false);
|
||||
await output.WriteLineAsync("Scene: ?scena=normale, sessione, fermo, scollegato, alvolante; tema: ?tema=chiaro o scuro; veste: ?veste=desktop o docker.").ConfigureAwait(false);
|
||||
await output.WriteLineAsync("Premi Ctrl+C per chiudere: la cartella temporanea viene cancellata.").ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library;
|
||||
@@ -150,8 +151,8 @@ public static class AccountsApi
|
||||
return ApiHttp.Message("Aperto nel tuo browser.");
|
||||
});
|
||||
|
||||
endpoints.MapGet("/api/following", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await FollowingAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.FollowingDto));
|
||||
endpoints.MapGet("/api/following", async (IFebeStorage storage, IClock clock, IProfileSearch search, CancellationToken ct) =>
|
||||
ApiHttp.Json(await FollowingAsync(storage, clock, ct, search).ConfigureAwait(false), FebeJsonContext.Default.FollowingDto));
|
||||
|
||||
endpoints.MapPost("/api/following/read", async (IFebeStorage storage, IEngineControl engine, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
@@ -165,10 +166,10 @@ public static class AccountsApi
|
||||
return ApiHttp.Json(await ParseAsync(storage, body.Text, ct).ConfigureAwait(false), FebeJsonContext.Default.ParseResultDto);
|
||||
});
|
||||
|
||||
endpoints.MapPost("/api/accounts", async (HttpContext context, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) =>
|
||||
endpoints.MapPost("/api/accounts", async (HttpContext context, IFebeStorage storage, IEngineControl engine, LibraryChanges changes, IClock clock, IProfileSearch search, CancellationToken ct) =>
|
||||
{
|
||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AddAccountsRequest).ConfigureAwait(false);
|
||||
var result = await AddAsync(storage, body, clock, ct).ConfigureAwait(false);
|
||||
var result = await AddAsync(storage, body, clock, ct, search).ConfigureAwait(false);
|
||||
if (result.Added > 0)
|
||||
{
|
||||
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
|
||||
@@ -403,7 +404,11 @@ public static class AccountsApi
|
||||
|
||||
// ------------------------------------------------------------------------------------------ following and adding
|
||||
|
||||
public static async Task<FollowingDto> FollowingAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// The profiles of the local suggestions (issue #37): the ones Alberto follows, then the accounts in Febe he does
|
||||
/// not follow, with the library avatar and the search photo when Febe has one.
|
||||
/// </summary>
|
||||
public static async Task<FollowingDto> FollowingAsync(IFebeStorage storage, IClock clock, CancellationToken ct, IProfileSearch? search = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
@@ -415,6 +420,10 @@ public static class AccountsApi
|
||||
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
|
||||
var byName = accounts.ToDictionary(a => a.Username, StringComparer.OrdinalIgnoreCase);
|
||||
var byId = accounts.Where(a => a.InstagramId is not null).ToDictionary(a => a.InstagramId!, StringComparer.Ordinal);
|
||||
var avatars = await AvatarsAsync(storage, ct).ConfigureAwait(false);
|
||||
var listed = new HashSet<long>();
|
||||
string? Photo(string? instagramId, string username) =>
|
||||
search?.Known(username) is { PhotoReady: true, PhotoKey: { } key } hit && (instagramId is null || hit.InstagramId == instagramId) ? key : null;
|
||||
var list = profiles.Select(p =>
|
||||
{
|
||||
Account? present = null;
|
||||
@@ -427,15 +436,43 @@ public static class AccountsApi
|
||||
present = b;
|
||||
}
|
||||
|
||||
return new FollowingProfileDto(p.Username, p.DisplayName, p.IsPrivate, present?.Id);
|
||||
if (present is not null)
|
||||
{
|
||||
listed.Add(present.Id);
|
||||
}
|
||||
|
||||
return new FollowingProfileDto(
|
||||
p.Username,
|
||||
p.DisplayName,
|
||||
p.IsPrivate,
|
||||
present?.Id,
|
||||
p.InstagramId ?? present?.InstagramId,
|
||||
present is not null && avatars.TryGetValue(present.Id, out var avatar) ? avatar : null,
|
||||
Photo(p.InstagramId, p.Username),
|
||||
Followed: true);
|
||||
}).ToList();
|
||||
var total = list.Count;
|
||||
|
||||
// Accounts in Febe that Alberto does not follow (added by name): suggestions marked «Già in Febe».
|
||||
list.AddRange(accounts
|
||||
.Where(a => !listed.Contains(a.Id) && !a.IsMine)
|
||||
.OrderBy(a => a.Username, StringComparer.Ordinal)
|
||||
.Select(a => new FollowingProfileDto(
|
||||
a.Username,
|
||||
a.DisplayName,
|
||||
a.IsPrivate,
|
||||
a.Id,
|
||||
a.InstagramId,
|
||||
avatars.TryGetValue(a.Id, out var avatar) ? avatar : null,
|
||||
Photo(a.InstagramId, a.Username),
|
||||
Followed: false)));
|
||||
var profile = (await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).EffectiveProfile;
|
||||
return new FollowingDto(
|
||||
lastRead?.ToUnixTimeMilliseconds(),
|
||||
lastRead is { } l ? ApiMapping.Day(LocalCalendar.Today(l, clock.LocalZone)) : null,
|
||||
pending || !string.IsNullOrEmpty(started),
|
||||
read,
|
||||
list.Count,
|
||||
total,
|
||||
list,
|
||||
profile.BackfillPostsPerAccountPerDay);
|
||||
}
|
||||
@@ -459,7 +496,12 @@ public static class AccountsApi
|
||||
}
|
||||
|
||||
/// <summary>Adds accounts with one of the three starting points of spec §4.2.</summary>
|
||||
public static async Task<AddAccountsDto> AddAsync(IFebeStorage storage, AddAccountsRequest request, IClock clock, CancellationToken ct)
|
||||
/// <remarks>
|
||||
/// A name found by the profile search (issue #37) takes its identifier and full name from the result the server
|
||||
/// holds (<see cref="IProfileSearch.Known"/>), never from the page. When an account with that identifier is already
|
||||
/// in Febe under another name, nothing is added and the name is reported.
|
||||
/// </remarks>
|
||||
public static async Task<AddAccountsDto> AddAsync(IFebeStorage storage, AddAccountsRequest request, IClock clock, CancellationToken ct, IProfileSearch? search = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
@@ -488,6 +530,7 @@ public static class AccountsApi
|
||||
var zone = clock.LocalZone;
|
||||
var added = 0;
|
||||
var skipped = new List<string>();
|
||||
var renamed = new List<string>();
|
||||
foreach (var raw in request.Usernames.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var username = raw.Trim().TrimStart('@').ToLowerInvariant();
|
||||
@@ -529,6 +572,18 @@ public static class AccountsApi
|
||||
IsPrivate = f.IsPrivate ?? false,
|
||||
};
|
||||
}
|
||||
else if (search?.Known(username) is { } hit)
|
||||
{
|
||||
account = account with { InstagramId = hit.InstagramId, DisplayName = hit.DisplayName };
|
||||
}
|
||||
|
||||
if (account.InstagramId is { } instagramId && await storage.Accounts.FindByInstagramIdAsync(instagramId, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
// The same profile is already in Febe under its old name.
|
||||
renamed.Add(username);
|
||||
skipped.Add(username);
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
@@ -544,6 +599,10 @@ public static class AccountsApi
|
||||
var message = added == 0
|
||||
? "Nessun account aggiunto: erano già tutti in Febe."
|
||||
: $"{ItalianText.Count(added, "account aggiunto", "account aggiunti")}." + (skipped.Count > 0 ? $" {ItalianText.Count(skipped.Count, "era già presente", "erano già presenti o non validi")}." : string.Empty);
|
||||
if (renamed.Count > 0)
|
||||
{
|
||||
message += $" Già in Febe (con un altro nome): {string.Join(", ", renamed)}.";
|
||||
}
|
||||
return new AddAccountsDto(added, skipped, message);
|
||||
}
|
||||
|
||||
|
||||
@@ -214,11 +214,57 @@ public sealed record AddAccountsRequest(IReadOnlyList<string> Usernames, string
|
||||
|
||||
public sealed record AddAccountsDto(int Added, IReadOnlyList<string> Skipped, string Message);
|
||||
|
||||
public sealed record FollowingProfileDto(string Username, string? DisplayName, bool? IsPrivate, long? AccountId);
|
||||
/// <summary>A profile for the local suggestions: one Alberto follows, or an account in Febe he does not follow.</summary>
|
||||
/// <param name="InstagramId">The site's identifier, when known (to merge with the results of the search).</param>
|
||||
/// <param name="Avatar">Thumbnail key of the newest profile picture in the library (<c>/api/thumbnails/{key}</c>).</param>
|
||||
/// <param name="Photo">Key of a photo of the search in memory (<c>/api/ricerca/foto/{key}</c>).</param>
|
||||
/// <param name="Followed">True when Alberto follows the profile (from the list of followed profiles).</param>
|
||||
public sealed record FollowingProfileDto(string Username, string? DisplayName, bool? IsPrivate, long? AccountId, string? InstagramId = null, string? Avatar = null, string? Photo = null, bool Followed = true);
|
||||
|
||||
/// <param name="BackfillPerDay">Default «Storico, massimo al giorno» of the caution profile, for the note of the dialog.</param>
|
||||
public sealed record FollowingDto(long? ReadAt, string? ReadDay, bool InProgress, int ReadSoFar, int Total, IReadOnlyList<FollowingProfileDto> Profiles, int BackfillPerDay);
|
||||
|
||||
// ---------------------------------------------------------------- profile search (issue #37)
|
||||
|
||||
/// <summary>The text of the search box of the dialog. <paramref name="Client"/> is a random id of the window (16 hex).</summary>
|
||||
public sealed record ProfileSearchRequest(string Client, string? Text)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append($"TextLength = {Text?.Length ?? 0}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The dialog closed.</summary>
|
||||
public sealed record ProfileSearchEndRequest(string Client);
|
||||
|
||||
/// <summary>
|
||||
/// What the search shows. <paramref name="State"/> is one of
|
||||
/// <c>idle|solo-locale|attesa|cerca|pronta|vuota|nessuna-risposta|non-possibile|fuori-fascia|ferma|non-pronto|da-configurare|rifiutata|errore</c>;
|
||||
/// <paramref name="Mine"/> is true when the window that asks wrote the text.
|
||||
/// </summary>
|
||||
public sealed record ProfileSearchDto(long Version, bool Mine, string Text, string State, string? Message, long? RetryAfter, IReadOnlyList<ProfileSearchHitDto> Hits)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Version = {Version}, State = {State}, Hits = {Hits.Count}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A profile found on the site, with what Febe knows of it (account, followed, private).</summary>
|
||||
/// <param name="Photo">Key of its photo in memory, once <paramref name="PhotoReady"/>.</param>
|
||||
/// <param name="Avatar">Thumbnail key of the account's newest profile picture in the library, when it is in Febe.</param>
|
||||
public sealed record ProfileSearchHitDto(string InstagramId, string Username, string? DisplayName, bool? IsVerified, string? Photo, bool PhotoReady, long? AccountId, bool Followed, bool? IsPrivate, string? Avatar)
|
||||
{
|
||||
private bool PrintMembers(System.Text.StringBuilder builder)
|
||||
{
|
||||
builder.Append($"PhotoReady = {PhotoReady}, InFebe = {AccountId is not null}, Followed = {Followed}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- engine
|
||||
|
||||
/// <summary>The connected account at the bottom of the sidebar.</summary>
|
||||
|
||||
@@ -38,6 +38,9 @@ namespace Febe.Web.Api;
|
||||
[JsonSerializable(typeof(ParseResultDto))]
|
||||
[JsonSerializable(typeof(AddAccountsRequest))]
|
||||
[JsonSerializable(typeof(AddAccountsDto))]
|
||||
[JsonSerializable(typeof(ProfileSearchRequest))]
|
||||
[JsonSerializable(typeof(ProfileSearchEndRequest))]
|
||||
[JsonSerializable(typeof(ProfileSearchDto))]
|
||||
[JsonSerializable(typeof(FollowingDto))]
|
||||
[JsonSerializable(typeof(EngineDto))]
|
||||
[JsonSerializable(typeof(ResumeDto))]
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Storage;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
|
||||
namespace Febe.Web.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The profile search of the «Aggiungi account» dialog (issue #37): the window sends what Alberto types (POST, so the
|
||||
/// Origin check applies and the text is never in an address), then polls the view. The photos come from Febe's
|
||||
/// memory, never from Instagram: the page never contacts the site.
|
||||
/// </summary>
|
||||
public static partial class SearchApi
|
||||
{
|
||||
/// <summary>Closed list of the states on the wire.</summary>
|
||||
public static string StateName(SearchState state) => state switch
|
||||
{
|
||||
SearchState.Idle => "idle",
|
||||
SearchState.LocalOnly => "solo-locale",
|
||||
SearchState.Waiting => "attesa",
|
||||
SearchState.Searching => "cerca",
|
||||
SearchState.Ready => "pronta",
|
||||
SearchState.Empty => "vuota",
|
||||
SearchState.NoAnswer => "nessuna-risposta",
|
||||
SearchState.NotPossible => "non-possibile",
|
||||
SearchState.OutsideWindow => "fuori-fascia",
|
||||
SearchState.Stopped => "ferma",
|
||||
SearchState.Unavailable => "non-pronto",
|
||||
SearchState.NotConfigured => "da-configurare",
|
||||
SearchState.Refused => "rifiutata",
|
||||
_ => "errore",
|
||||
};
|
||||
|
||||
public static void Map(IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
endpoints.MapPost("/api/ricerca", async (HttpContext context, IProfileSearch search, IFebeStorage storage, CancellationToken ct) =>
|
||||
{
|
||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ProfileSearchRequest).ConfigureAwait(false);
|
||||
var client = CheckClient(body.Client);
|
||||
if (body.Text is { Length: > SearchText.MaxRawLength })
|
||||
{
|
||||
throw new BadRequestException($"Testo troppo lungo: al massimo {SearchText.MaxRawLength} caratteri.");
|
||||
}
|
||||
|
||||
var view = search.Update(client, body.Text ?? string.Empty);
|
||||
return ApiHttp.Json(await DtoAsync(view, client, storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ProfileSearchDto);
|
||||
});
|
||||
|
||||
endpoints.MapGet("/api/ricerca", async (string? client, IProfileSearch search, IFebeStorage storage, CancellationToken ct) =>
|
||||
{
|
||||
var id = client is null ? string.Empty : CheckClient(client);
|
||||
return ApiHttp.Json(await DtoAsync(search.Current, id, storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ProfileSearchDto);
|
||||
});
|
||||
|
||||
endpoints.MapPost("/api/ricerca/fine", async (HttpContext context, IProfileSearch search) =>
|
||||
{
|
||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ProfileSearchEndRequest).ConfigureAwait(false);
|
||||
search.End(CheckClient(body.Client));
|
||||
return Results.NoContent();
|
||||
});
|
||||
|
||||
endpoints.MapGet("/api/ricerca/foto/{key}", (string key, HttpContext context, IProfileSearch search) =>
|
||||
{
|
||||
if (!PhotoKey().IsMatch(key) || !search.TryOpenPhoto(key, out var stream))
|
||||
{
|
||||
throw new NotFoundException("Foto non trovata: Febe tiene le foto della ricerca solo per poco, in memoria.");
|
||||
}
|
||||
|
||||
// Memory only (SearchPhotoCache): the browser of the interface keeps no copy on its disk either.
|
||||
context.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Stream(stream, "image/jpeg");
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The view for the window <paramref name="client"/>, with what Febe knows of each profile.</summary>
|
||||
public static async Task<ProfileSearchDto> DtoAsync(SearchView view, string client, IFebeStorage storage, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(view);
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
var hits = new List<ProfileSearchHitDto>(view.Hits.Count);
|
||||
if (view.Hits.Count > 0)
|
||||
{
|
||||
var following = await storage.Following.ListAsync(ct).ConfigureAwait(false);
|
||||
var followedIds = following.Where(f => f.InstagramId is not null).Select(f => f.InstagramId!).ToHashSet(StringComparer.Ordinal);
|
||||
var followedNames = following.Select(f => f.Username).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var hit in view.Hits)
|
||||
{
|
||||
// By identifier first: a renamed account comes back under its new name with the same identifier.
|
||||
var account = await storage.Accounts.FindByInstagramIdAsync(hit.InstagramId, ct).ConfigureAwait(false)
|
||||
?? await storage.Accounts.FindByUsernameAsync(hit.Username, ct).ConfigureAwait(false);
|
||||
var avatar = account is null ? null : await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
|
||||
var followed = followedIds.Contains(hit.InstagramId) || followedNames.Contains(hit.Username) || account?.IsFollowed == true;
|
||||
hits.Add(new ProfileSearchHitDto(
|
||||
hit.InstagramId,
|
||||
hit.Username,
|
||||
hit.DisplayName ?? account?.DisplayName,
|
||||
hit.IsVerified,
|
||||
hit.PhotoReady ? hit.PhotoKey : null,
|
||||
hit.PhotoReady,
|
||||
account?.Id,
|
||||
followed,
|
||||
account?.IsPrivate,
|
||||
avatar));
|
||||
}
|
||||
}
|
||||
|
||||
return new ProfileSearchDto(
|
||||
view.Version,
|
||||
client.Length > 0 && string.Equals(view.Owner, client, StringComparison.Ordinal),
|
||||
view.Text,
|
||||
StateName(view.State),
|
||||
view.Message,
|
||||
view.RetryAfter?.ToUnixTimeMilliseconds(),
|
||||
hits);
|
||||
}
|
||||
|
||||
private static string CheckClient(string? client) =>
|
||||
client is not null && ClientId().IsMatch(client)
|
||||
? client
|
||||
: throw new BadRequestException("Finestra della ricerca sconosciuta.");
|
||||
|
||||
[GeneratedRegex("^[0-9a-f]{16}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex ClientId();
|
||||
|
||||
[GeneratedRegex("^[0-9a-f]{32}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex PhotoKey();
|
||||
}
|
||||
|
||||
/// <summary>The search when no engine runs (a configuration problem, the tests): local suggestions only.</summary>
|
||||
public sealed class OfflineProfileSearch : IProfileSearch
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private SearchView _view = SearchView.Initial;
|
||||
|
||||
public SearchView Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _view;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public SearchView Update(string client, string text)
|
||||
{
|
||||
var query = SearchText.Normalize(text);
|
||||
lock (_gate)
|
||||
{
|
||||
_view = query.Kind switch
|
||||
{
|
||||
SearchQueryKind.Empty => SearchView.Initial with { Version = _view.Version + 1, Owner = client },
|
||||
SearchQueryKind.Typable => new SearchView(_view.Version + 1, client, query.Typed, SearchState.Unavailable, "Il motore non è avviato: per ora vedi solo i profili che segui.", [], null),
|
||||
SearchQueryKind.Refused => new SearchView(_view.Version + 1, client, string.Empty, SearchState.Refused, "Il testo contiene un carattere che Febe non scrive mai su Instagram.", [], null),
|
||||
_ => new SearchView(_view.Version + 1, client, string.Empty, SearchState.LocalOnly, null, [], null),
|
||||
};
|
||||
return _view;
|
||||
}
|
||||
}
|
||||
|
||||
public void End(string client)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_view.Owner == client)
|
||||
{
|
||||
_view = SearchView.Initial with { Version = _view.Version + 1, Owner = client };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public SearchHit? Known(string username) => null;
|
||||
|
||||
public bool TryOpenPhoto(string key, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
stream = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,12 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
|
||||
details = ["Il motore non parte finché il problema di configurazione non è risolto."];
|
||||
sidebar = "Problema di configurazione";
|
||||
break;
|
||||
case DemoScene.UserDriving:
|
||||
mode = EngineMode.UserDriving;
|
||||
headline = "Stai usando il browser";
|
||||
details = ["Il motore resta fermo finché non hai finito."];
|
||||
sidebar = "Stai usando il browser";
|
||||
break;
|
||||
case DemoScene.Disconnected:
|
||||
mode = EngineMode.NotConnected;
|
||||
headline = "Non collegato";
|
||||
|
||||
@@ -91,6 +91,7 @@ public sealed class DemoHost : IAsyncDisposable
|
||||
services.AddSingleton<DemoEngine>();
|
||||
services.AddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<DemoEngine>());
|
||||
services.AddSingleton<IEngineControl>(sp => sp.GetRequiredService<DemoEngine>());
|
||||
services.AddSingleton<Febe.Core.Collection.Search.IProfileSearch>(sp => new DemoProfileSearch(db, clock, sp.GetRequiredService<IHttpContextAccessor>()));
|
||||
services.AddSingleton(sp => new DemoShell(sp.GetRequiredService<IHttpContextAccessor>(), root));
|
||||
services.AddSingleton<INativeShell>(sp => sp.GetRequiredService<DemoShell>());
|
||||
services.AddSingleton<IBrowserWindow>(sp => sp.GetRequiredService<DemoShell>());
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Storage;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Febe.Web.Demo;
|
||||
|
||||
/// <summary>
|
||||
/// The profile search of the demo (issue #37): no browser, no network. The same text rules as the real search
|
||||
/// (<see cref="SearchText.Normalize"/>); after a short simulated wait, up to six profiles that depend only on the text —
|
||||
/// demo accounts and followed profiles whose name contains it, then a few invented ones — with drawn portraits that
|
||||
/// appear a moment later. The waits are computed from the clock at each poll: nothing runs in the background, so a
|
||||
/// headless screenshot always ends.
|
||||
/// </summary>
|
||||
public sealed class DemoProfileSearch : IProfileSearch
|
||||
{
|
||||
/// <summary>Simulated time Instagram takes to answer.</summary>
|
||||
public static readonly TimeSpan AnswerAfter = TimeSpan.FromMilliseconds(750);
|
||||
|
||||
/// <summary>Simulated time of the photos after the answer.</summary>
|
||||
public static readonly TimeSpan PhotosAfter = TimeSpan.FromMilliseconds(300);
|
||||
|
||||
/// <summary>Portraits kept (the oldest go first; a later answer draws them again).</summary>
|
||||
public const int MaxPhotos = 120;
|
||||
|
||||
/// <summary>Profiles of the answers kept for <see cref="Known"/> (the oldest go first).</summary>
|
||||
public const int MaxKnown = 400;
|
||||
|
||||
private static readonly string[] Suffixes = ["_foto", ".viaggi", "_official"];
|
||||
private readonly Lock _gate = new();
|
||||
private readonly IFebeStorage _storage;
|
||||
private readonly IClock _clock;
|
||||
private readonly IHttpContextAccessor? _context;
|
||||
private readonly OrderedDictionary<string, byte[]> _photos = new(StringComparer.Ordinal);
|
||||
private readonly OrderedDictionary<string, SearchHit> _seen = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Task<IReadOnlyList<Profile>>? _known;
|
||||
private string _owner = string.Empty;
|
||||
private SearchQuery _query = new(SearchQueryKind.Empty, string.Empty, string.Empty);
|
||||
private DateTimeOffset _at;
|
||||
private long _version;
|
||||
|
||||
public DemoProfileSearch(IFebeStorage storage, IClock clock, IHttpContextAccessor? context = null)
|
||||
{
|
||||
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public SearchView Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return ViewLocked();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public SearchView Update(string client, string text)
|
||||
{
|
||||
var query = SearchText.Normalize(text);
|
||||
lock (_gate)
|
||||
{
|
||||
_known ??= LoadAsync();
|
||||
_owner = client;
|
||||
if (!(query.Kind == SearchQueryKind.Typable && _query.Kind == SearchQueryKind.Typable && query.Typed == _query.Typed))
|
||||
{
|
||||
_query = query;
|
||||
_at = _clock.Now;
|
||||
_version++;
|
||||
}
|
||||
|
||||
return ViewLocked();
|
||||
}
|
||||
}
|
||||
|
||||
public void End(string client)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (client != _owner)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_query = new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
|
||||
_version++;
|
||||
}
|
||||
}
|
||||
|
||||
public SearchHit? Known(string username)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
// Any profile of an answer shown in this run, not only the last one: one chosen earlier keeps its identifier.
|
||||
var name = username?.Trim().TrimStart('@') ?? string.Empty;
|
||||
return _seen.TryGetValue(name, out var hit) ? hit : null;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_photos.TryGetValue(key, out var jpeg))
|
||||
{
|
||||
stream = new MemoryStream(jpeg, writable: false);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
stream = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
private SearchView ViewLocked()
|
||||
{
|
||||
var phase = 0;
|
||||
SearchView Make(SearchState state, string text, string? message, IReadOnlyList<SearchHit>? hits = null) =>
|
||||
new((_version * 4) + phase, _owner, text, state, message, hits ?? [], null);
|
||||
|
||||
switch (_query.Kind)
|
||||
{
|
||||
case SearchQueryKind.Empty:
|
||||
return Make(SearchState.Idle, string.Empty, null);
|
||||
case SearchQueryKind.Refused:
|
||||
return Make(SearchState.Refused, string.Empty, "Il testo contiene un carattere che Febe non scrive mai su Instagram.");
|
||||
case SearchQueryKind.SeveralNames:
|
||||
return Make(SearchState.LocalOnly, string.Empty, "Più nomi insieme: Febe li aggiunge all'elenco; su Instagram cerca un nome alla volta.");
|
||||
case SearchQueryKind.LocalOnly:
|
||||
return Make(SearchState.LocalOnly, string.Empty, SearchText.Fold(_query.Shown.TrimStart('@')).Length < SearchText.MinTyped
|
||||
? "Scrivi almeno due lettere per cercare anche su Instagram."
|
||||
: "Su Instagram Febe cerca solo con lettere, numeri, punto, trattino basso e spazi: per ora vedi i profili che segui.");
|
||||
}
|
||||
|
||||
var text = _query.Typed;
|
||||
switch (_context?.HttpContext is { } http ? DemoRequest.Scene(http) : DemoScene.Normal)
|
||||
{
|
||||
case DemoScene.Stopped:
|
||||
return Make(SearchState.Stopped, text, "Instagram ha chiesto una verifica: la ricerca è ferma finché non la completi e premi «Riprendi».");
|
||||
case DemoScene.Disconnected:
|
||||
return Make(SearchState.Unavailable, text, "Il browser di Febe non è collegato a Instagram: per ora vedi solo i profili che segui.");
|
||||
case DemoScene.UserDriving:
|
||||
return Make(SearchState.NotPossible, text, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
|
||||
}
|
||||
|
||||
var elapsed = _clock.Now - _at;
|
||||
if (elapsed < AnswerAfter || _known is not { IsCompletedSuccessfully: true } known)
|
||||
{
|
||||
return Make(SearchState.Searching, text, null);
|
||||
}
|
||||
|
||||
var photos = elapsed >= AnswerAfter + PhotosAfter;
|
||||
phase = photos ? 2 : 1;
|
||||
var hits = Hits(text, known.Result, photos);
|
||||
foreach (var hit in hits)
|
||||
{
|
||||
_seen.Remove(hit.Username);
|
||||
_seen.Add(hit.Username, hit);
|
||||
}
|
||||
|
||||
while (_seen.Count > MaxKnown)
|
||||
{
|
||||
_seen.RemoveAt(0);
|
||||
}
|
||||
|
||||
return hits.Count == 0 ? Make(SearchState.Empty, text, "Nessun profilo trovato su Instagram.") : Make(SearchState.Ready, text, null, hits);
|
||||
}
|
||||
|
||||
private List<SearchHit> Hits(string text, IReadOnlyList<Profile> known, bool photos)
|
||||
{
|
||||
var folded = SearchText.Fold(text);
|
||||
var found = known
|
||||
.Where(k => k.Username.Contains(folded.Replace(' ', '.'), StringComparison.Ordinal) || k.Folded.Contains(folded, StringComparison.Ordinal) || k.Username.Contains(folded.Replace(" ", string.Empty, StringComparison.Ordinal), StringComparison.Ordinal))
|
||||
.OrderBy(k => k.Username.StartsWith(folded, StringComparison.Ordinal) ? 0 : 1)
|
||||
.ThenBy(k => k.Username, StringComparer.Ordinal)
|
||||
.Take(3)
|
||||
.ToList();
|
||||
var stem = folded.Replace(' ', '.');
|
||||
foreach (var suffix in Suffixes)
|
||||
{
|
||||
if (found.Count >= 6)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var name = stem + suffix;
|
||||
if (name.Length <= 30 && found.All(f => f.Username != name))
|
||||
{
|
||||
found.Add(new Profile(Id(name), name, Title(text), string.Empty));
|
||||
}
|
||||
}
|
||||
|
||||
var hits = new List<SearchHit>(found.Count);
|
||||
for (var i = 0; i < found.Count; i++)
|
||||
{
|
||||
var k = found[i];
|
||||
string? key = null;
|
||||
if (photos)
|
||||
{
|
||||
key = PhotoKey(k.Username);
|
||||
if (_photos.Remove(key, out var jpeg))
|
||||
{
|
||||
// Used again: it goes to the end, the last to be dropped.
|
||||
_photos.Add(key, jpeg);
|
||||
}
|
||||
else
|
||||
{
|
||||
_photos.Add(key, DemoImages.Render(DemoSubject.Portrait, Seed(k.Username), 160, 160));
|
||||
while (_photos.Count > MaxPhotos)
|
||||
{
|
||||
_photos.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hits.Add(new SearchHit(i, k.InstagramId, k.Username, k.DisplayName, k.Username.EndsWith("_official", StringComparison.Ordinal), key, key is not null));
|
||||
}
|
||||
|
||||
return hits;
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Profile>> LoadAsync()
|
||||
{
|
||||
var list = new List<Profile>();
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var account in await _storage.Accounts.ListAsync().ConfigureAwait(false))
|
||||
{
|
||||
if (!account.IsMine && seen.Add(account.Username))
|
||||
{
|
||||
list.Add(new Profile(account.InstagramId ?? Id(account.Username), account.Username, account.DisplayName, SearchText.Fold((account.DisplayName ?? string.Empty).ToLowerInvariant())));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var profile in await _storage.Following.ListAsync().ConfigureAwait(false))
|
||||
{
|
||||
if (seen.Add(profile.Username))
|
||||
{
|
||||
list.Add(new Profile(profile.InstagramId ?? Id(profile.Username), profile.Username, profile.DisplayName, SearchText.Fold((profile.DisplayName ?? string.Empty).ToLowerInvariant())));
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static string Title(string text) =>
|
||||
CultureInfo.GetCultureInfo("it-IT").TextInfo.ToTitleCase(text.Replace('.', ' ').Replace('_', ' '));
|
||||
|
||||
private static string Id(string username) =>
|
||||
"9" + (BitConverter.ToUInt64(SHA256.HashData(Encoding.UTF8.GetBytes("demo:" + username)), 0) % 1_000_000_000_000UL).ToString("D12", CultureInfo.InvariantCulture);
|
||||
|
||||
private static string PhotoKey(string username) =>
|
||||
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes("demo-foto:" + username)))[..32];
|
||||
|
||||
private static int Seed(string username) => BitConverter.ToInt32(SHA256.HashData(Encoding.UTF8.GetBytes(username)), 0) & 0x7fffffff;
|
||||
|
||||
private sealed record Profile(string InstagramId, string Username, string? DisplayName, string Folded);
|
||||
}
|
||||
@@ -19,6 +19,9 @@ public enum DemoScene
|
||||
|
||||
/// <summary>«errore»: a configuration problem (missing password): the interface shows only the problem page.</summary>
|
||||
Error,
|
||||
|
||||
/// <summary>«alvolante»: Alberto is using Febe's browser; the engine waits and the profile search stays local (issue #37).</summary>
|
||||
UserDriving,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -36,7 +39,7 @@ public static class DemoRequest
|
||||
private const string SceneItem = "febe.demo.scena";
|
||||
private const string EditionItem = "febe.demo.veste";
|
||||
|
||||
public static IReadOnlyList<string> SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato", "errore"];
|
||||
public static IReadOnlyList<string> SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato", "errore", "alvolante"];
|
||||
|
||||
public static DemoScene? ParseScene(string? text) => text?.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
@@ -45,6 +48,7 @@ public static class DemoRequest
|
||||
"fermo" => DemoScene.Stopped,
|
||||
"scollegato" => DemoScene.Disconnected,
|
||||
"errore" => DemoScene.Error,
|
||||
"alvolante" => DemoScene.UserDriving,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@@ -54,6 +58,7 @@ public static class DemoRequest
|
||||
DemoScene.Stopped => "fermo",
|
||||
DemoScene.Disconnected => "scollegato",
|
||||
DemoScene.Error => "errore",
|
||||
DemoScene.UserDriving => "alvolante",
|
||||
_ => "normale",
|
||||
};
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ public static class SnapshotParts
|
||||
|
||||
/// <summary>Every category in the order of the table of spec §7.5.</summary>
|
||||
public static readonly ActionKind[] All =
|
||||
[ActionKind.Home, ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.SinglePost, ActionKind.FollowingListPage, ActionKind.DataDownload];
|
||||
[ActionKind.Home, ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.SinglePost, ActionKind.FollowingListPage, ActionKind.ProfileSearch, ActionKind.DataDownload];
|
||||
|
||||
/// <summary>A minimal snapshot: no sessions, empty budgets.</summary>
|
||||
public static EngineSnapshot Build(IClock clock, EngineMode mode, string headline, IReadOnlyList<string> details, string sidebar, CautionProfile profile)
|
||||
|
||||
@@ -63,6 +63,7 @@ public static class FebeWeb
|
||||
services.TryAddSingleton<OfflineEngine>();
|
||||
services.TryAddSingleton<IEngineMonitor>(sp => sp.GetRequiredService<OfflineEngine>());
|
||||
services.TryAddSingleton<IEngineControl>(sp => sp.GetRequiredService<OfflineEngine>());
|
||||
services.TryAddSingleton<Febe.Core.Collection.Search.IProfileSearch, OfflineProfileSearch>();
|
||||
services.TryAddSingleton<IEngineSettingsControl>(sp => new StoredEngineSettingsControl(sp.GetRequiredService<IFebeStorage>()));
|
||||
services.TryAddSingleton<IConfigurationProblems, NoConfigurationProblems>();
|
||||
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
||||
@@ -138,6 +139,7 @@ public static class FebeWeb
|
||||
SettingsApi.Map(endpoints);
|
||||
ImportApi.Map(endpoints);
|
||||
DuplicatesApi.Map(endpoints);
|
||||
SearchApi.Map(endpoints);
|
||||
RemoteViewSocket.Map(endpoints);
|
||||
HealthEndpoint.Map(endpoints);
|
||||
|
||||
|
||||
@@ -114,7 +114,8 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) |
|
||||
| `GET /api/accounts`, `GET /api/accounts/{id}`, `GET /{id}/history` | Elenco con conteggi, scheda, cronologia |
|
||||
| `POST /api/accounts/{id}/plan`, `PUT /{id}/settings`, `POST /{id}/keep-updated`, `/pause`, `/resume`, `/check-now`, `/remove`, `/pick-folder`, `/open-on-instagram` | Impostazioni dell'account e comandi |
|
||||
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account» |
|
||||
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account»: `/api/following` dà anche gli account in Febe non seguiti (`followed: false`) per i suggerimenti locali, con `instagramId`, `avatar` e `photo` |
|
||||
| `POST /api/ricerca` (`{ client, text }`), `GET /api/ricerca?client=`, `POST /api/ricerca/fine`, `GET /api/ricerca/foto/{chiave}` | Ricerca dei profili mentre si scrive (#37, `Api/SearchApi.cs`): `client` di 16 cifre esadecimali, testo al più 60 caratteri, Origin dell'interfaccia; la finestra chiede lo stato ogni 400 ms (poi ogni 2 s) finché Febe cerca o mancano foto. Stati: `idle`, `solo-locale`, `attesa`, `cerca`, `pronta`, `vuota`, `nessuna-risposta`, `non-possibile`, `fuori-fascia`, `ferma`, `non-pronto`, `da-configurare`, `rifiutata`, `errore`. Le foto (JPEG 160 px) stanno solo in memoria |
|
||||
| `GET /accesso`, `POST /api/accesso`, `POST /api/uscita` | Accesso con password |
|
||||
| `GET /api/connection`, `POST /api/connection/begin` (`{ openLogin }`), `/finish`, `/cancel`, `/disconnect` | Collegamento a Instagram (`IConnectionService`, §6.4): stato `notConnected`, `connected`, `verificationRequired`, `browserUnavailable` |
|
||||
| `GET /api/engine/incidents` | Incidenti degli ultimi 14 giorni (rallentamenti, verifiche, arresti), con un consiglio dopo 3 rallentamenti in 7 giorni |
|
||||
@@ -228,13 +229,16 @@ virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `p
|
||||
cartella temporanea con dati e libreria finti (38 account, circa 18.000 elementi), cancellata alla chiusura. Non
|
||||
scrive mai nella libreria vera e non usa la rete.
|
||||
|
||||
- Scene del motore: `?scena=normale|sessione|fermo|scollegato|errore` (`errore`: password mancante, pagina di errore
|
||||
di configurazione); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
|
||||
- Scene del motore: `?scena=normale|sessione|fermo|scollegato|errore|alvolante` (`errore`: password mancante, pagina
|
||||
di errore di configurazione; `alvolante`: Alberto usa il browser, la ricerca dei profili resta locale); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
|
||||
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`,
|
||||
`/importa?passo=3` (revisione di un'importazione già analizzata), `/doppioni`, `/impostazioni/collegamento?scena=scollegato&veste=docker`.
|
||||
- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`, `Demo/DemoDiagnostics.cs`): collegamento, anteprima del
|
||||
browser, incidenti e rapporto di diagnostica secondo la scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
|
||||
(copie identiche, varianti, cartelle senza account, file non riconosciuti) e già analizzata all'avvio.
|
||||
- Ricerca dei profili (`Demo/DemoProfileSearch.cs`): nessun browser; dopo 750 ms profili dimostrativi il cui nome
|
||||
contiene il testo e qualche nome inventato, con foto disegnate 300 ms dopo. Con `fermo`, `scollegato` e `alvolante`
|
||||
risponde `ferma`, `non-pronto` e `non-possibile`.
|
||||
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
|
||||
conti tornino.
|
||||
|
||||
@@ -250,5 +254,6 @@ rimaste dai mockup sono in `docs/schermate/differenze.md`.
|
||||
`tests/Febe.Tests/Web/` avvia Kestrel vero su una porta libera di 127.0.0.1 (`Support/WebTestServer.cs`), con
|
||||
archivio e libreria temporanei e orologio manuale; `DemoTests` avvia una dimostrazione intera una volta per classe.
|
||||
Le prove della seconda parte (`ConnectionApiTests`, `SettingsApiTests`, `ActivityApiTests`, `ImportApiTests`,
|
||||
`DemoPart2Tests`) usano gli aiuti di `Part2Support/`.
|
||||
`DemoPart2Tests`) usano gli aiuti di `Part2Support/`. `InterfaceTests` e `ProfileSearchInterfaceTests` guidano
|
||||
l'interfaccia in un Chromium senza finestra (solo Linux; su Windows risultano «Inconclusive»).
|
||||
`dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Web"`.
|
||||
@@ -2,16 +2,18 @@ using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Web.Library;
|
||||
|
||||
/// <summary>A user name read from a line of the «Per nome utente» text area.</summary>
|
||||
/// <summary>A user name read from the names pasted in «Aggiungi account»; <paramref name="Line"/> is its place (from 1).</summary>
|
||||
public sealed record ParsedUsername(int Line, string Username);
|
||||
|
||||
/// <summary>A line that is not a user name, with the reason in Italian.</summary>
|
||||
/// <summary>A pasted name that is not a user name, with its place and the reason in Italian.</summary>
|
||||
public sealed record UsernameProblem(int Line, string Text, string Reason);
|
||||
|
||||
/// <summary>
|
||||
/// «Per nome utente» (spec §4.2, mockup 04): one user name or profile address per line. Accepts «marta.demo»,
|
||||
/// «@marta.demo», «instagram.com/marta.demo», «https://www.instagram.com/marta.demo/?hl=it». Refuses addresses of
|
||||
/// posts, reels and other pages, and names Instagram would not accept. Names are compared and stored in lowercase.
|
||||
/// The names pasted or chosen in «Aggiungi account» (spec §4.2, mockup 04, issue #37): the window sends one name per
|
||||
/// line (it splits what Alberto pasted at line breaks, commas and semicolons). Accepts «marta.demo», «@marta.demo»,
|
||||
/// «instagram.com/marta.demo», «https://www.instagram.com/marta.demo/?hl=it». Refuses addresses of posts, reels and
|
||||
/// other pages, and names Instagram would not accept. Names are compared and stored in lowercase. The reasons speak
|
||||
/// of «names», not lines: the window shows each as «n° nome».
|
||||
/// </summary>
|
||||
public static partial class UsernameParser
|
||||
{
|
||||
@@ -43,7 +45,7 @@ public static partial class UsernameParser
|
||||
|
||||
if (line.Length > 300)
|
||||
{
|
||||
problems.Add(new UsernameProblem(number, line[..60] + "…", "Riga troppo lunga per essere un nome utente."));
|
||||
problems.Add(new UsernameProblem(number, line[..60] + "…", "Troppo lungo per essere un nome utente."));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -56,7 +58,7 @@ public static partial class UsernameParser
|
||||
|
||||
if (seen.TryGetValue(candidate, out var first))
|
||||
{
|
||||
problems.Add(new UsernameProblem(number, line, $"Già scritto alla riga {first}."));
|
||||
problems.Add(new UsernameProblem(number, line, $"Già scritto: è uguale al {first}° nome."));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -104,7 +106,7 @@ public static partial class UsernameParser
|
||||
text = text.Trim().TrimStart('@').ToLowerInvariant();
|
||||
if (text.Contains(' ', StringComparison.Ordinal))
|
||||
{
|
||||
return (null, "Un nome utente non contiene spazi: uno per riga.");
|
||||
return (null, "Un nome utente non contiene spazi: per cercare un nome e cognome scrivilo da solo nella casella.");
|
||||
}
|
||||
|
||||
return IsValid(text)
|
||||
|
||||
@@ -561,12 +561,39 @@ a.stato:hover{border-color:var(--bordo-forte)}
|
||||
|
||||
/* dialogo «Aggiungi account» */
|
||||
.aggiungi{width:min(900px,calc(100vw - 32px));height:min(660px,calc(100vh - 32px))}
|
||||
.aggiungi .linguette{padding:0 22px;margin-top:6px}
|
||||
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px}
|
||||
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:14px 18px 0 22px;border-right:1px solid var(--bordo)}
|
||||
.aggiungi .corpo-dialogo{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr) 316px;border-top:1px solid var(--bordo)}
|
||||
.aggiungi .sinistra{display:flex;flex-direction:column;min-height:0;padding:16px 18px 0 22px;border-right:1px solid var(--bordo)}
|
||||
.aggiungi .destra-dialogo{padding:16px 18px;overflow:auto;background:var(--superficie)}
|
||||
.aggiungi .cerca-riga{display:flex;gap:10px;margin-bottom:6px}
|
||||
.aggiungi .cerca-riga .campo{flex:1}
|
||||
/* ricerca unica con i suggerimenti mentre si scrive (#37) */
|
||||
.aggiungi .cerca-zona{position:relative;flex:none;margin-bottom:12px}
|
||||
.aggiungi .cerca-zona .campo{height:40px}
|
||||
.aggiungi .suggerimenti{position:absolute;left:0;right:0;top:calc(100% + 4px);z-index:5;max-height:min(420px,60vh);overflow:auto;background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello);box-shadow:var(--ombra-menu);padding:4px 6px 6px}
|
||||
.aggiungi .suggerimenti[hidden]{display:none}
|
||||
.aggiungi .sezione-titolo{display:flex;gap:6px;align-items:baseline;padding:9px 8px 5px;font-size:12px;font-weight:600;color:var(--testo-3)}
|
||||
.aggiungi .sezione-titolo .per{font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
|
||||
.aggiungi .stato-remoto{display:flex;gap:8px;align-items:flex-start;padding:4px 8px 8px;font-size:12.5px;line-height:1.4;color:var(--testo-2)}
|
||||
.aggiungi .stato-remoto .ic{flex:none;margin-top:1px}
|
||||
.aggiungi .stato-remoto.allarme{color:var(--ambra)}
|
||||
.aggiungi .opzione{display:flex;align-items:center;gap:12px;padding:6px 8px;border-radius:6px;cursor:pointer;min-height:52px}
|
||||
.aggiungi .opzione:hover{background:var(--rialzo)}
|
||||
.aggiungi .opzione[aria-selected=true]{background:var(--accento-tinta)}
|
||||
.aggiungi .opzione.presente{cursor:default}
|
||||
.aggiungi .opzione.presente .chi-nome,.aggiungi .opzione.presente .av{opacity:.6}
|
||||
.aggiungi .opzione .chi-nome,.aggiungi .voce.scelto .chi-nome{flex:1;min-width:0}
|
||||
.aggiungi .opzione b,.aggiungi .voce.scelto b{display:block;font-weight:600;font-size:13.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.aggiungi .opzione small,.aggiungi .voce.scelto small{display:block;color:var(--testo-2);font-size:12.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.aggiungi .opzione .verificato{display:inline-flex;vertical-align:-2px;margin-left:4px;color:var(--accento)}
|
||||
.aggiungi .etichette{display:flex;gap:6px;flex:none}
|
||||
.aggiungi .opzione .btn{flex:none;min-width:96px;justify-content:center}
|
||||
.aggiungi .opzione .btn.scelto{background:var(--accento-tinta);border-color:var(--accento-bordo);color:var(--accento-scuro)}
|
||||
.aggiungi .opzione.azione .av{color:var(--testo-2)}
|
||||
.aggiungi .scelti-testa{display:flex;align-items:center;gap:10px;flex:none;padding:2px 0 6px;border-bottom:1px solid var(--bordo)}
|
||||
.aggiungi .scelti-testa h3{margin:0;font-size:13.5px;font-weight:650;display:flex;gap:7px;align-items:baseline}
|
||||
.aggiungi .scelti-testa h3 i{font-style:normal;font-size:12px;color:var(--testo-3);font-weight:500}
|
||||
.aggiungi .scelti-testa > .btn.collegamento{margin-left:auto;font-size:13px}
|
||||
.aggiungi .vuoto-scelti{display:flex;gap:10px;align-items:flex-start;padding:16px 2px;color:var(--testo-2);font-size:13px;line-height:1.45}
|
||||
.aggiungi .vuoto-scelti .ic{flex:none;margin-top:2px}
|
||||
.aggiungi .elenco .voce.scelto{cursor:default}
|
||||
.aggiungi .elenco{flex:1;overflow:auto;margin:0 -18px 0 -4px;padding:0 18px 0 4px}
|
||||
.aggiungi .elenco .voce{padding:9px 2px;border-bottom:1px solid var(--bordo);gap:12px}
|
||||
.aggiungi .elenco .voce.presente{opacity:.5}
|
||||
@@ -582,6 +609,7 @@ a.stato:hover{border-color:var(--bordo-forte)}
|
||||
.aggiungi .partenza .tondo{margin-top:2px}
|
||||
.aggiungi .problemi{margin-top:10px;font-size:12.5px;color:var(--rosso);display:flex;flex-direction:column;gap:3px}
|
||||
.aggiungi .riconosciuti{margin-top:10px;font-size:12.5px;color:var(--testo-2)}
|
||||
.aggiungi .riconosciuti:empty,.aggiungi .problemi:empty{display:none}
|
||||
|
||||
/* ==========================================================================
|
||||
Parte 2 dell'interfaccia: Attività, Impostazioni, Collegamento, Browser,
|
||||
@@ -970,8 +998,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento
|
||||
.tabella-account .tab td.menu-riga{position:absolute;right:4px;top:12px;width:auto}
|
||||
.tabella-account .nome .sotto{flex-wrap:wrap;white-space:normal}
|
||||
.tipi{grid-template-columns:1fr 1fr}
|
||||
.aggiungi .corpo-dialogo{grid-template-columns:1fr;overflow:auto}
|
||||
.aggiungi .corpo-dialogo{grid-template-columns:minmax(0,1fr);overflow:auto}
|
||||
.aggiungi footer{flex-wrap:wrap;row-gap:10px}
|
||||
.aggiungi footer .destra{margin-left:auto}
|
||||
.aggiungi .sinistra{border-right:0;min-height:320px}
|
||||
.aggiungi .opzione{flex-wrap:wrap;row-gap:4px}
|
||||
.aggiungi .opzione .chi-nome{flex:1 1 0}
|
||||
.aggiungi .opzione .btn{min-width:0}
|
||||
.aggiungi .opzione .etichette{order:3;flex-basis:100%;padding-left:52px;flex-wrap:wrap}
|
||||
.aggiungi .opzione .etichette:empty{display:none}
|
||||
.salva{padding:10px 16px;flex-wrap:wrap}
|
||||
.brevi{bottom:72px}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:n
|
||||
/**
|
||||
* Opens a modal dialog over the whole window. build(close) returns { header?, body, footer? } or a node; close(value)
|
||||
* resolves the returned promise. Esc and the veil close with undefined. Focus is trapped and restored.
|
||||
* build may also return onEscape (called first on Esc: returning true means the dialog handled it, say by closing a
|
||||
* list of suggestions, and stays open) and onClose (called once, however the dialog closes).
|
||||
*/
|
||||
export function dialog({ title, className = '', build, labelledBy, dismissable = true }) {
|
||||
return new Promise((resolve) => {
|
||||
@@ -42,6 +44,13 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
|
||||
closed = true;
|
||||
veil.remove();
|
||||
document.removeEventListener('keydown', onKey, true);
|
||||
if (parts && typeof parts.onClose === 'function') {
|
||||
try {
|
||||
parts.onClose();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
if (opener && opener.focus && document.contains(opener)) opener.focus();
|
||||
resolve(value);
|
||||
};
|
||||
@@ -61,7 +70,10 @@ export function dialog({ title, className = '', build, labelledBy, dismissable =
|
||||
if (e.target === veil && dismissable) close(undefined);
|
||||
});
|
||||
const onKey = (e) => {
|
||||
if (e.key === 'Escape' && dismissable) {
|
||||
if (e.key === 'Escape' && parts && typeof parts.onEscape === 'function' && parts.onEscape()) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
} else if (e.key === 'Escape' && dismissable) {
|
||||
e.stopPropagation();
|
||||
close(undefined);
|
||||
} else if (e.key === 'Tab') {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
// «Aggiungi account» (mockup 04, spec §4.2): from the local copy of the list of followed profiles (with its reading
|
||||
// date and progress; it is read again only on request) or by user name, one per line; the three starting points on
|
||||
// the right; the button says how many accounts it adds.
|
||||
// «Aggiungi account» (mockup 04, spec §4.2, issue #37): one search box. While Alberto types, the list under it shows
|
||||
// at once the profiles he follows and the accounts already in Febe, then the profiles Instagram finds, with their
|
||||
// photo, user name, full name and the labels «Seguito», «Privato», «Già in Febe». Febe's browser searches on the site
|
||||
// and fetches the photos (the page asks only Febe: /api/ricerca, /api/ricerca/foto, /api/thumbnails). Several names or
|
||||
// profile addresses can be pasted in the same box. The chosen profiles go to «Da aggiungere»; the three starting
|
||||
// points stay on the right; the button says how many accounts it adds. «Scegli fra tutti i profili che segui» opens
|
||||
// the whole list of followed profiles with check boxes.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill, later } from '../core/dom.js';
|
||||
import { h, icon, fill, later, uid } from '../core/dom.js';
|
||||
import { t, number, shortDay } from '../core/text.js';
|
||||
import { caps } from '../core/context.js';
|
||||
import { engineState, onEngine } from '../core/engine.js';
|
||||
import { avatar, checkbox, dialog, label, showError, toast } from '../core/ui.js';
|
||||
|
||||
const STARTS = ['everything', 'newOnly', 'storiesOnly'];
|
||||
@@ -17,6 +22,31 @@ const DEPTHS = [
|
||||
{ key: 'year', depth: 'fromDate' },
|
||||
];
|
||||
|
||||
/** Local suggestions shown at most. */
|
||||
const MAX_LOCAL = 8;
|
||||
/** Pause after the last key before the text goes to Febe (the local suggestions do not wait). */
|
||||
const DEBOUNCE_MS = 150;
|
||||
/** Asking for the results: often at first, then less. Never stops while Febe is still searching. */
|
||||
const FAST_POLL_MS = 400;
|
||||
const SLOW_POLL_MS = 2000;
|
||||
const FAST_FOR_MS = 10000;
|
||||
/** How long to keep asking only for photos still on their way. */
|
||||
const PHOTOS_FOR_MS = 60000;
|
||||
/** Longest text the server accepts (SearchText.MaxRawLength). */
|
||||
const MAX_TEXT = 60;
|
||||
/** States of the search while Febe still works on the text. */
|
||||
const WORKING = ['attesa', 'cerca'];
|
||||
/**
|
||||
* States the search leaves by itself (Alberto lets go of the browser, the pause or the stop ends, the active window
|
||||
* opens, the cap frees up): the window keeps asking, slowly, and at once when the engine changes.
|
||||
*/
|
||||
const RESUMING = ['non-possibile', 'fuori-fascia', 'ferma'];
|
||||
/**
|
||||
* First path segments of instagram.com that are pages, not profiles (UsernameParser.ReservedPaths, SearchText): an
|
||||
* address of a post, a reel or a story is never taken for the account «p», «reel» or «stories».
|
||||
*/
|
||||
const RESERVED_PATHS = new Set(['p', 'reel', 'reels', 'tv', 'stories', 'explore', 'accounts', 'direct', 'about', 'legal', 'developer', 'web', 'challenge', 'emails', 'session']);
|
||||
|
||||
/** Opens the dialog; resolves to true when accounts were added. */
|
||||
export function openAddAccounts() {
|
||||
return dialog({
|
||||
@@ -26,75 +56,594 @@ export function openAddAccounts() {
|
||||
});
|
||||
}
|
||||
|
||||
/** Lowercase text without accents (the server folds the same way, SearchText.Fold). */
|
||||
export function fold(text) {
|
||||
return String(text || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
|
||||
}
|
||||
|
||||
/** True for an instagram.com address of a post, a reel, a story or another page that is not a profile. */
|
||||
export function isPageAddress(raw) {
|
||||
const address = /instagram\.com\/([^/?#\s]+)/i.exec(String(raw || ''));
|
||||
return Boolean(address && RESERVED_PATHS.has(address[1].toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* What the box asks for: a profile address becomes its user name, a leading @ goes, single spaces. The address of a
|
||||
* post or another page gives nothing: it is not a profile.
|
||||
*/
|
||||
export function searchTerm(raw) {
|
||||
let text = String(raw || '').trim();
|
||||
const address = /instagram\.com\/([^/?#\s]+)/i.exec(text);
|
||||
if (address) {
|
||||
if (RESERVED_PATHS.has(address[1].toLowerCase())) return '';
|
||||
text = address[1];
|
||||
}
|
||||
return fold(text.replace(/^@/, '')).replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/** True for a text holding several names: a line break, a comma, a semicolon or more than one profile address. */
|
||||
export function isSeveralNames(raw) {
|
||||
const text = String(raw || '');
|
||||
return /[\r\n,;]/.test(text) || (text.match(/instagram\.com\//gi) || []).length > 1;
|
||||
}
|
||||
|
||||
/** One name per line, for /api/accounts/parse (which reads one per line). */
|
||||
export function namesPerLine(raw) {
|
||||
return String(raw || '')
|
||||
.split(/[\r\n,;]+/)
|
||||
.flatMap((part) => ((part.match(/instagram\.com\//gi) || []).length > 1 ? part.trim().split(/\s+/) : [part]))
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
/** A user name Instagram accepts (UsernameParser.IsValid). */
|
||||
function validName(name) {
|
||||
return /^[a-z0-9._]{1,30}$/.test(name) && !name.startsWith('.') && !name.endsWith('.') && !name.includes('..');
|
||||
}
|
||||
|
||||
/** A text Febe would type on the site (SearchText: letters, digits, «.», «_» and spaces, 2 to 40). */
|
||||
function likelyTypable(term) {
|
||||
return term.length >= 2 && term.length <= 40 && /^[a-z0-9._]+( [a-z0-9._]+)*$/.test(term);
|
||||
}
|
||||
|
||||
function randomClient() {
|
||||
const bytes = new Uint8Array(8);
|
||||
crypto.getRandomValues(bytes);
|
||||
return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
|
||||
function photoOf(avatarKey, searchKey) {
|
||||
if (avatarKey) return `/api/thumbnails/${avatarKey}`;
|
||||
if (searchKey) return `/api/ricerca/foto/${searchKey}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
function build(close) {
|
||||
let tab = 'seguiti';
|
||||
const client = randomClient();
|
||||
const listId = uid('suggerimenti');
|
||||
const aborter = new AbortController();
|
||||
let closed = false;
|
||||
let following = null;
|
||||
let parsed = { names: [], problems: [] };
|
||||
const chosen = new Set();
|
||||
let byName = new Map();
|
||||
let byId = new Map();
|
||||
let view = 'scelti';
|
||||
let open = false;
|
||||
let options = [];
|
||||
let active = -1;
|
||||
let remote = null;
|
||||
let lastVersion = -1;
|
||||
let awaiting = false;
|
||||
let pollTimer = 0;
|
||||
let pollFrom = 0;
|
||||
let photosFrom = 0;
|
||||
let start = 'everything';
|
||||
let depth = 'all';
|
||||
let parsedNote = null;
|
||||
/** username → { username, displayName, photo, followed, isPrivate } */
|
||||
const chosen = new Map();
|
||||
/** One avatar node per place, name and photo, moved from one drawing to the next so a photo never flickers. */
|
||||
const faces = new Map();
|
||||
|
||||
const tabFollowed = h('button', { type: 'button', role: 'tab', class: 'qui', 'aria-selected': 'true' }, t('aggiungi.seguiti'), h('i'));
|
||||
const tabNames = h('button', { type: 'button', role: 'tab', 'aria-selected': 'false' }, t('aggiungi.perNome'));
|
||||
const tabs = h('div.linguette', { role: 'tablist' }, tabFollowed, tabNames);
|
||||
const left = h('div.sinistra', { role: 'tabpanel' });
|
||||
const right = h('div.destra-dialogo');
|
||||
const footerLeft = h('div', { style: { display: 'flex', alignItems: 'center', gap: '12px', fontSize: '13px', color: 'var(--testo-2)' } });
|
||||
const addButton = h('button.btn.primo', { type: 'button', disabled: true, onclick: submit });
|
||||
|
||||
// ---------------------------------------------------------------------------- left: followed profiles
|
||||
const search = h('input', { type: 'search', placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cerca') });
|
||||
const allButton = h('button.btn', { type: 'button' }, t('aggiungi.selezionaTutti'));
|
||||
const list = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
|
||||
const progress = h('div.avanzamento', { role: 'status' });
|
||||
const followedPanel = h('div', { style: { display: 'contents' } }, h('div.cerca-riga', h('label.campo', icon('search'), search), allButton), list, progress);
|
||||
// ---------------------------------------------------------------------------- left: the box and its list
|
||||
const box = h('input', {
|
||||
type: 'search', autocomplete: 'off', spellcheck: 'false', autocapitalize: 'off', maxlength: String(MAX_TEXT),
|
||||
placeholder: t('aggiungi.cerca'), 'aria-label': t('aggiungi.cercaEtichetta'),
|
||||
role: 'combobox', 'aria-expanded': 'false', 'aria-controls': listId, 'aria-autocomplete': 'list',
|
||||
});
|
||||
const suggestions = h('div.suggerimenti', { id: listId, role: 'listbox', 'aria-label': t('aggiungi.suggerimenti'), hidden: true });
|
||||
const announce = h('div.vh', { role: 'status', 'aria-live': 'polite' });
|
||||
const searchZone = h('div.cerca-zona', h('label.campo', icon('search'), box), suggestions, announce);
|
||||
|
||||
// ---------------------------------------------------------------------------- left: by user name
|
||||
const area = h('textarea', { rows: '8', spellcheck: 'false', autocapitalize: 'off', 'aria-describedby': 'aiuto-nomi', placeholder: 'marta.demo\n@luca.viaggi.demo\ninstagram.com/studio.lumen.demo' });
|
||||
const chosenTitle = h('h3');
|
||||
const toFollowed = h('button.btn.collegamento', { type: 'button', onclick: () => setView(view === 'scelti' ? 'seguiti' : 'scelti') });
|
||||
const chosenList = h('div.elenco.scelti', { role: 'list', 'aria-label': t('aggiungi.daAggiungere') });
|
||||
const parsedInfo = h('div.riconosciuti', { role: 'status' });
|
||||
const problems = h('div.problemi');
|
||||
const namesPanel = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px', paddingBottom: '14px', overflow: 'auto' } },
|
||||
h('label.etichetta', t('aggiungi.area')),
|
||||
h('label.campo.area', area),
|
||||
h('p.aiuto', { id: 'aiuto-nomi' }, t('aggiungi.areaAiuto')),
|
||||
parsedInfo, problems);
|
||||
|
||||
const allButton = h('button.btn.piccolo', { type: 'button' }, t('aggiungi.selezionaTutti'));
|
||||
const followedList = h('div.elenco', { role: 'group', 'aria-label': t('aggiungi.seguiti') });
|
||||
const progress = h('div.avanzamento', { role: 'status' });
|
||||
|
||||
const left = h('div.sinistra');
|
||||
|
||||
// ---------------------------------------------------------------------------- what Febe knows locally
|
||||
function present(p) {
|
||||
return p.accountId != null;
|
||||
}
|
||||
|
||||
function drawList() {
|
||||
if (!following) {
|
||||
fill(list, h('div.caricamento', t('comune.caricamento')));
|
||||
return;
|
||||
function known(username, instagramId) {
|
||||
return (instagramId && byId.get(instagramId)) || byName.get(username) || null;
|
||||
}
|
||||
|
||||
/** Followed profiles and accounts in Febe whose name or full name holds the text: prefix first, then alphabetical. */
|
||||
function localMatches(term) {
|
||||
if (!following || !term) return [];
|
||||
const dotted = term.replace(/ /g, '.');
|
||||
const joined = term.replace(/ /g, '');
|
||||
const found = [];
|
||||
for (const p of following.profiles) {
|
||||
const name = p.username;
|
||||
const full = fold(p.displayName);
|
||||
let rank = -1;
|
||||
if (name.startsWith(term) || name.startsWith(dotted) || name.startsWith(joined)) rank = 0;
|
||||
else if (full.startsWith(term) || full.split(/\s+/).some((w) => w.startsWith(term))) rank = 1;
|
||||
else if (name.includes(term) || name.includes(dotted) || name.includes(joined) || full.includes(term)) rank = 2;
|
||||
if (rank >= 0) found.push([rank, p]);
|
||||
}
|
||||
const term = search.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const shown = following.profiles.filter((p) => !term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term));
|
||||
if (!shown.length) {
|
||||
fill(list, h('div.caricamento', following.profiles.length ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
|
||||
return;
|
||||
}
|
||||
fill(list, shown.map((p) => {
|
||||
const isPresent = present(p);
|
||||
const box = checkbox({
|
||||
checked: isPresent || chosen.has(p.username),
|
||||
disabled: isPresent,
|
||||
labelNode: h('span', { style: { display: 'contents' } },
|
||||
avatar(p.username, 'm'),
|
||||
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
|
||||
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
|
||||
onchange: (on) => {
|
||||
if (on) chosen.add(p.username);
|
||||
else chosen.delete(p.username);
|
||||
drawRight();
|
||||
},
|
||||
});
|
||||
box.classList.toggle('presente', isPresent);
|
||||
return box;
|
||||
found.sort((a, b) => a[0] - b[0] || a[1].username.localeCompare(b[1].username));
|
||||
return found.slice(0, MAX_LOCAL).map(([, p]) => ({
|
||||
username: p.username,
|
||||
displayName: p.displayName,
|
||||
followed: p.followed !== false,
|
||||
isPrivate: p.isPrivate,
|
||||
accountId: p.accountId,
|
||||
instagramId: p.instagramId,
|
||||
isVerified: null,
|
||||
photo: photoOf(p.avatar, p.photo),
|
||||
}));
|
||||
}
|
||||
|
||||
/** The profiles of Instagram's answer that are not already among the local ones; the local ones take their photo. */
|
||||
function mergeRemote(local, term) {
|
||||
if (!remote || !remote.mine) return [];
|
||||
const current = !awaiting || remote.text === term;
|
||||
const extra = [];
|
||||
for (const hit of remote.hits) {
|
||||
// While a newer text is on its way, the older answer stays only where it still fits what is written.
|
||||
if (!current && !(hit.username.includes(term.replace(/ /g, '.')) || hit.username.includes(term.replace(/ /g, '')) || fold(hit.displayName).includes(term))) continue;
|
||||
const photo = photoOf(hit.avatar, hit.photoReady ? hit.photo : null);
|
||||
const same = local.find((r) => (r.instagramId && r.instagramId === hit.instagramId) || r.username === hit.username);
|
||||
if (same) {
|
||||
same.photo = same.photo || photo;
|
||||
same.displayName = same.displayName || hit.displayName;
|
||||
same.isVerified = hit.isVerified;
|
||||
continue;
|
||||
}
|
||||
const f = known(hit.username, hit.instagramId);
|
||||
extra.push({
|
||||
username: hit.username,
|
||||
displayName: hit.displayName || (f && f.displayName),
|
||||
followed: hit.followed || Boolean(f && f.followed !== false),
|
||||
isPrivate: hit.isPrivate != null ? hit.isPrivate : f ? f.isPrivate : null,
|
||||
accountId: hit.accountId != null ? hit.accountId : f ? f.accountId : null,
|
||||
instagramId: hit.instagramId,
|
||||
isVerified: hit.isVerified,
|
||||
photo: photo || (f ? photoOf(f.avatar, f.photo) : null),
|
||||
});
|
||||
}
|
||||
return extra;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- the list under the box
|
||||
function face(where, username, photo) {
|
||||
const key = `${where}|${username}|${photo || ''}`;
|
||||
let node = faces.get(key);
|
||||
if (node) return node;
|
||||
node = avatar(username, 'm');
|
||||
if (photo) {
|
||||
// The initials stay until the photo has arrived from Febe.
|
||||
const img = h('img', { src: photo, alt: '', decoding: 'async' });
|
||||
img.addEventListener('load', () => {
|
||||
node.textContent = '';
|
||||
node.append(img);
|
||||
node.classList.add('con-foto');
|
||||
}, { once: true });
|
||||
}
|
||||
faces.set(key, node);
|
||||
return node;
|
||||
}
|
||||
|
||||
function labelsOf(r) {
|
||||
return h('span.etichette',
|
||||
r.followed ? label(t('aggiungi.seguito'), '', 'user-check') : null,
|
||||
r.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null,
|
||||
present(r) ? label(t('aggiungi.giaPresente')) : null);
|
||||
}
|
||||
|
||||
function optionRow(r, index) {
|
||||
const isPresent = present(r);
|
||||
const isChosen = chosen.has(r.username);
|
||||
// The option itself says whether the profile is in «Da aggiungere» (aria-checked; aria-selected is the keyboard
|
||||
// cursor): the children of an option are presentational, so the button below is only for the mouse.
|
||||
const row = h(`div.opzione${isPresent ? '.presente' : ''}`, {
|
||||
id: `${listId}-${index}`, role: 'option', 'aria-selected': String(index === active),
|
||||
'aria-checked': isPresent ? null : String(isChosen),
|
||||
'aria-disabled': isPresent ? 'true' : null,
|
||||
onmousedown: (e) => e.preventDefault(),
|
||||
onclick: () => activate(index),
|
||||
},
|
||||
face('lista', r.username, r.photo),
|
||||
h('span.chi-nome',
|
||||
h('b', `@${r.username}`, r.isVerified ? h('span.verificato', { title: t('aggiungi.verificato'), 'aria-label': t('aggiungi.verificato') }, icon('circle-check', 's')) : null),
|
||||
r.displayName ? h('small', r.displayName) : null),
|
||||
labelsOf(r),
|
||||
isPresent ? null : h(`button.btn.piccolo${isChosen ? '.scelto' : ''}`, {
|
||||
type: 'button', tabindex: '-1', 'aria-hidden': 'true',
|
||||
onmousedown: (e) => e.preventDefault(),
|
||||
onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
activate(index);
|
||||
},
|
||||
}, isChosen ? [icon('check', 's'), t('aggiungi.aggiunto')] : [icon('plus', 's'), t('aggiungi.aggiungiUno')]));
|
||||
return row;
|
||||
}
|
||||
|
||||
function actionRow(o, index) {
|
||||
return h('div.opzione.azione', {
|
||||
id: `${listId}-${index}`, role: 'option', 'aria-selected': String(index === active),
|
||||
onmousedown: (e) => e.preventDefault(),
|
||||
onclick: () => activate(index),
|
||||
},
|
||||
h('span.av.m.segnaposto', { 'aria-hidden': 'true' }, icon(o.action === 'nomi' ? 'users' : 'at-sign')),
|
||||
h('span.chi-nome', h('b', o.title), h('small', o.note)));
|
||||
}
|
||||
|
||||
/** The status line of the Instagram part: searching, waiting for the page, or why Instagram is not searched. */
|
||||
function remoteStatus(term, extraCount) {
|
||||
const driving = (engineState() && engineState().snapshot && engineState().snapshot.mode) === 'UserDriving';
|
||||
if (awaiting) {
|
||||
if (!likelyTypable(term)) return null;
|
||||
return driving ? { text: t('aggiungi.alVolante'), kind: 'info' } : { text: t('aggiungi.cercoSuInstagram'), kind: 'lavoro' };
|
||||
}
|
||||
if (!remote) return null;
|
||||
if (!remote.mine) return { text: t('aggiungi.altraFinestra'), kind: 'info' };
|
||||
switch (remote.state) {
|
||||
case 'idle':
|
||||
return null;
|
||||
case 'cerca':
|
||||
return { text: t('aggiungi.cercoSuInstagram'), kind: 'lavoro' };
|
||||
case 'attesa':
|
||||
return { text: remote.message || t('aggiungi.attesa'), kind: 'lavoro' };
|
||||
case 'pronta':
|
||||
return extraCount ? null : { text: t('aggiungi.nessunAltro'), kind: 'info' };
|
||||
case 'non-possibile':
|
||||
return { text: remote.message || t('aggiungi.alVolante'), kind: 'info' };
|
||||
case 'ferma':
|
||||
case 'errore':
|
||||
case 'rifiutata':
|
||||
return { text: remote.message || t('comune.errore'), kind: 'allarme' };
|
||||
default:
|
||||
return remote.message ? { text: remote.message, kind: 'info' } : null;
|
||||
}
|
||||
}
|
||||
|
||||
function drawSuggestions() {
|
||||
const term = searchTerm(box.value);
|
||||
const several = isSeveralNames(box.value);
|
||||
const pageAddress = !several && isPageAddress(box.value);
|
||||
const keep = active >= 0 && options[active] ? options[active].username || options[active].action : null;
|
||||
options = [];
|
||||
const parts = [];
|
||||
if (!several && term) {
|
||||
const local = localMatches(term);
|
||||
const extra = mergeRemote(local, term);
|
||||
if (local.length) {
|
||||
const titleId = `${listId}-locali`;
|
||||
parts.push(h('div', { role: 'group', 'aria-labelledby': titleId },
|
||||
h('div.sezione-titolo', { id: titleId, 'aria-hidden': 'true' }, t('aggiungi.traSeguiti')),
|
||||
local.map((r) => {
|
||||
options.push(r);
|
||||
return optionRow(r, options.length - 1);
|
||||
})));
|
||||
}
|
||||
const status = remoteStatus(term, extra.length);
|
||||
if (extra.length || status) {
|
||||
const titleId = `${listId}-instagram`;
|
||||
const shown = remote && remote.mine && remote.text ? remote.text : term;
|
||||
parts.push(h('div', { role: 'group', 'aria-labelledby': titleId },
|
||||
h('div.sezione-titolo', { id: titleId, 'aria-hidden': 'true' }, t('aggiungi.daInstagram'), h('span.per', t('aggiungi.perTesto', { testo: shown }))),
|
||||
// The status is read out by the live region (announce): inside the list it is only seen.
|
||||
status ? h(`div.stato-remoto.${status.kind}`, { 'aria-hidden': 'true' }, icon(status.kind === 'lavoro' ? 'hourglass' : status.kind === 'allarme' ? 'triangle-alert' : 'info', 's'), h('span', status.text)) : null,
|
||||
extra.map((r) => {
|
||||
options.push(r);
|
||||
return optionRow(r, options.length - 1);
|
||||
})));
|
||||
}
|
||||
if (validName(term) && !options.some((r) => r.username === term)) {
|
||||
options.push({ action: 'nome', name: term, title: t('aggiungi.perNomeUtente', { nome: term }), note: t('aggiungi.perNomeSpiega') });
|
||||
parts.push(actionRow(options[options.length - 1], options.length - 1));
|
||||
}
|
||||
if (!local.length && following && following.profiles.length && !extra.length) {
|
||||
// Seen, not an option: hidden from the list's structure (the live region says how many were found).
|
||||
parts.unshift(h('div', { 'aria-hidden': 'true' },
|
||||
h('div.sezione-titolo', t('aggiungi.traSeguiti')),
|
||||
h('div.stato-remoto.info', icon('info', 's'), h('span', t('aggiungi.nessunLocale')))));
|
||||
}
|
||||
announce.textContent = status ? status.text : t('aggiungi.trovati', { n: options.filter((o) => !o.action).length });
|
||||
} else if (pageAddress) {
|
||||
parts.push(h('div', { 'aria-hidden': 'true' }, h('div.stato-remoto.info', icon('info', 's'), h('span', t('aggiungi.nonProfilo')))));
|
||||
announce.textContent = t('aggiungi.nonProfilo');
|
||||
} else if (several) {
|
||||
options.push({ action: 'nomi', title: t('aggiungi.piuNomi'), note: t('aggiungi.piuNomiSpiega') });
|
||||
parts.push(actionRow(options[0], 0));
|
||||
announce.textContent = t('aggiungi.piuNomi');
|
||||
}
|
||||
active = keep ? options.findIndex((o) => (o.username || o.action) === keep) : -1;
|
||||
fill(suggestions, parts);
|
||||
setOpen(view === 'scelti' && document.activeElement === box && options.length + parts.length > 0);
|
||||
markActive();
|
||||
}
|
||||
|
||||
function setOpen(value) {
|
||||
open = value;
|
||||
suggestions.hidden = !value;
|
||||
box.setAttribute('aria-expanded', String(value));
|
||||
if (!value) {
|
||||
active = -1;
|
||||
box.removeAttribute('aria-activedescendant');
|
||||
}
|
||||
}
|
||||
|
||||
function markActive() {
|
||||
const rows = [...suggestions.querySelectorAll('[role=option]')];
|
||||
rows.forEach((row, i) => row.setAttribute('aria-selected', String(i === active)));
|
||||
if (active >= 0 && rows[active]) {
|
||||
box.setAttribute('aria-activedescendant', rows[active].id);
|
||||
rows[active].scrollIntoView({ block: 'nearest' });
|
||||
} else {
|
||||
box.removeAttribute('aria-activedescendant');
|
||||
}
|
||||
}
|
||||
|
||||
function move(step) {
|
||||
if (!open) {
|
||||
drawSuggestions();
|
||||
if (!open) return;
|
||||
}
|
||||
if (!options.length) return;
|
||||
active = active < 0 ? (step > 0 ? 0 : options.length - 1) : active + step;
|
||||
if (active >= options.length || active < 0) active = -1;
|
||||
markActive();
|
||||
}
|
||||
|
||||
function activate(index) {
|
||||
const o = options[index];
|
||||
if (!o) return;
|
||||
active = index;
|
||||
if (o.action === 'nomi') {
|
||||
addNames(box.value, true);
|
||||
return;
|
||||
}
|
||||
if (o.action === 'nome') {
|
||||
addNames(o.name, true);
|
||||
return;
|
||||
}
|
||||
if (present(o)) return;
|
||||
if (chosen.has(o.username)) chosen.delete(o.username);
|
||||
else chosen.set(o.username, { username: o.username, displayName: o.displayName, photo: o.photo, followed: o.followed, isPrivate: o.isPrivate });
|
||||
drawChosen();
|
||||
drawSuggestions();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- talking to Febe
|
||||
const send = later(async () => {
|
||||
if (closed) return;
|
||||
pollFrom = Date.now();
|
||||
photosFrom = 0;
|
||||
let answer;
|
||||
try {
|
||||
answer = await api('/api/ricerca', { method: 'POST', body: { client, text: box.value.slice(0, MAX_TEXT) }, signal: aborter.signal });
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') return;
|
||||
awaiting = false;
|
||||
remote = { version: lastVersion, mine: true, text: '', state: 'errore', message: error.message, hits: [] };
|
||||
drawSuggestions();
|
||||
return;
|
||||
}
|
||||
accept(answer, true);
|
||||
}, DEBOUNCE_MS);
|
||||
|
||||
function accept(answer, fromSend) {
|
||||
if (closed || !answer || answer.version < lastVersion) {
|
||||
schedule();
|
||||
return;
|
||||
}
|
||||
lastVersion = answer.version;
|
||||
remote = answer;
|
||||
if (fromSend) awaiting = false;
|
||||
drawSuggestions();
|
||||
schedule();
|
||||
}
|
||||
|
||||
function needsPoll() {
|
||||
if (!remote || !remote.mine || closed) return false;
|
||||
if (WORKING.includes(remote.state) || RESUMING.includes(remote.state)) {
|
||||
photosFrom = 0;
|
||||
return true;
|
||||
}
|
||||
if (!remote.hits.some((hit) => !hit.photoReady && !hit.avatar)) return false;
|
||||
photosFrom = photosFrom || Date.now();
|
||||
return Date.now() - photosFrom < PHOTOS_FOR_MS;
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
if (awaiting || !needsPoll()) return;
|
||||
let wait = Date.now() - pollFrom < FAST_FOR_MS ? FAST_POLL_MS : SLOW_POLL_MS;
|
||||
if (RESUMING.includes(remote.state)) {
|
||||
// Febe resumes the search by itself: slowly, and right when the stop says it ends (retryAfter).
|
||||
wait = SLOW_POLL_MS;
|
||||
if (remote.retryAfter) wait = Math.max(FAST_POLL_MS, Math.min(wait, remote.retryAfter - Date.now() + 250));
|
||||
}
|
||||
pollTimer = setTimeout(poll, wait);
|
||||
}
|
||||
|
||||
async function poll() {
|
||||
pollTimer = 0;
|
||||
try {
|
||||
accept(await api(`/api/ricerca?client=${client}`, { signal: aborter.signal }), false);
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') return;
|
||||
schedule();
|
||||
}
|
||||
}
|
||||
|
||||
function onInput() {
|
||||
if (view === 'seguiti') {
|
||||
drawFollowed();
|
||||
return;
|
||||
}
|
||||
awaiting = !isSeveralNames(box.value);
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
drawSuggestions();
|
||||
if (isSeveralNames(box.value)) {
|
||||
send.cancel();
|
||||
return;
|
||||
}
|
||||
send();
|
||||
}
|
||||
|
||||
async function addNames(raw, clearBox) {
|
||||
const text = namesPerLine(raw);
|
||||
if (!text) return;
|
||||
let parsed;
|
||||
try {
|
||||
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text }, signal: aborter.signal });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
}
|
||||
let ready = 0;
|
||||
let already = 0;
|
||||
for (const n of parsed.names) {
|
||||
if (n.present) {
|
||||
already += 1;
|
||||
continue;
|
||||
}
|
||||
ready += 1;
|
||||
const f = byName.get(n.username);
|
||||
chosen.set(n.username, {
|
||||
username: n.username,
|
||||
displayName: n.displayName || (f && f.displayName),
|
||||
photo: f ? photoOf(f.avatar, f.photo) : null,
|
||||
followed: n.followed,
|
||||
isPrivate: n.isPrivate,
|
||||
});
|
||||
}
|
||||
parsedNote = parsed.names.length > 1 || parsed.problems.length || already ? { ready, already, problems: parsed.problems } : null;
|
||||
if (clearBox) {
|
||||
box.value = '';
|
||||
awaiting = false;
|
||||
send();
|
||||
}
|
||||
drawChosen();
|
||||
drawSuggestions();
|
||||
// Pasted names went to «Da aggiungere»: the list under the box gives way, so the result shows.
|
||||
if (!clearBox) setOpen(false);
|
||||
if (view === 'seguiti') {
|
||||
// «Da aggiungere» is not on screen in this view: the check boxes show the names, and a note says where they went.
|
||||
drawFollowed();
|
||||
if (ready) toast(t('aggiungi.incollatiSeguiti', { n: ready }));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- left: «Da aggiungere»
|
||||
function drawChosen() {
|
||||
fill(chosenTitle, t('aggiungi.daAggiungere'), chosen.size ? h('i', number(chosen.size)) : null);
|
||||
if (!chosen.size) {
|
||||
fill(chosenList, h('div.vuoto-scelti', { role: 'listitem' }, icon('search', 's'), h('span', t('aggiungi.sceltiNessuno'))));
|
||||
} else {
|
||||
fill(chosenList, [...chosen.values()].map((c) => h('div.voce.scelto', { role: 'listitem' },
|
||||
face('scelti', c.username, c.photo),
|
||||
h('span.chi-nome', h('b', `@${c.username}`), c.displayName ? h('small', c.displayName) : null),
|
||||
h('span.etichette', c.followed ? label(t('aggiungi.seguito'), '', 'user-check') : null, c.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
|
||||
h('button.btn.nudo.solo', {
|
||||
type: 'button', 'aria-label': t('aggiungi.togli', { nome: c.username }), title: t('aggiungi.togli', { nome: c.username }),
|
||||
onclick: () => {
|
||||
chosen.delete(c.username);
|
||||
drawChosen();
|
||||
box.focus();
|
||||
},
|
||||
}, icon('x', 's')))));
|
||||
}
|
||||
if (parsedNote) {
|
||||
fill(parsedInfo, t('aggiungi.riconosciuti', { n: parsedNote.ready }), parsedNote.already ? ` · ${t('aggiungi.presenti', { n: parsedNote.already })}` : '');
|
||||
fill(problems, parsedNote.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
|
||||
} else {
|
||||
fill(parsedInfo);
|
||||
fill(problems);
|
||||
}
|
||||
drawRight();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- left: all followed profiles
|
||||
function followedShown() {
|
||||
const term = searchTerm(box.value);
|
||||
return following.profiles.filter((p) => p.followed !== false && (!term || p.username.includes(term) || fold(p.displayName).includes(term)));
|
||||
}
|
||||
|
||||
function drawFollowed() {
|
||||
if (!following) {
|
||||
fill(followedList, h('div.caricamento', t('comune.caricamento')));
|
||||
return;
|
||||
}
|
||||
const shown = followedShown();
|
||||
if (!shown.length) {
|
||||
fill(followedList, h('div.caricamento', following.total ? t('aggiungi.nessunSeguito') : t('aggiungi.maiLetto')));
|
||||
return;
|
||||
}
|
||||
fill(followedList, shown.map((p) => {
|
||||
const isPresent = present(p);
|
||||
const item = checkbox({
|
||||
checked: isPresent || chosen.has(p.username),
|
||||
disabled: isPresent,
|
||||
labelNode: h('span', { style: { display: 'contents' } },
|
||||
face('seguiti', p.username, photoOf(p.avatar, p.photo)),
|
||||
h('span.chi-nome', h('b', `@${p.username}`), p.displayName ? h('small', p.displayName) : null),
|
||||
isPresent ? label(t('aggiungi.giaPresente')) : p.isPrivate ? label(t('aggiungi.privato'), '', 'lock') : null),
|
||||
onchange: (on) => {
|
||||
if (on) chosen.set(p.username, { username: p.username, displayName: p.displayName, photo: photoOf(p.avatar, p.photo), followed: true, isPrivate: p.isPrivate });
|
||||
else chosen.delete(p.username);
|
||||
drawChosen();
|
||||
},
|
||||
});
|
||||
item.classList.toggle('presente', isPresent);
|
||||
return item;
|
||||
}));
|
||||
}
|
||||
|
||||
allButton.addEventListener('click', () => {
|
||||
if (!following) return;
|
||||
const shown = followedShown().filter((p) => !present(p));
|
||||
const all = shown.every((p) => chosen.has(p.username));
|
||||
for (const p of shown) {
|
||||
if (all) chosen.delete(p.username);
|
||||
else chosen.set(p.username, { username: p.username, displayName: p.displayName, photo: photoOf(p.avatar, p.photo), followed: true, isPrivate: p.isPrivate });
|
||||
}
|
||||
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
|
||||
drawFollowed();
|
||||
drawChosen();
|
||||
});
|
||||
|
||||
function drawProgress() {
|
||||
fill(toFollowed, view === 'seguiti' ? t('aggiungi.chiudiSeguiti') : t('aggiungi.scegliTraSeguiti', { n: following ? following.total : 0 }));
|
||||
if (!following) return;
|
||||
progress.hidden = !following.inProgress;
|
||||
fill(progress, following.inProgress
|
||||
@@ -104,65 +653,111 @@ function build(close) {
|
||||
h('span', following.readDay ? t('aggiungi.lettoIl', { giorno: shortDay(following.readDay, caps().today) }) : t('aggiungi.maiLetto')),
|
||||
h('button.btn.collegamento', { type: 'button', disabled: following.inProgress, onclick: reread, title: t('aggiungi.rilettura') },
|
||||
icon('refresh-cw', 's'), following.readDay ? t('aggiungi.rileggi') : t('aggiungi.leggi')));
|
||||
const count = tabFollowed.querySelector('i');
|
||||
count.textContent = number(following.total);
|
||||
}
|
||||
|
||||
function setFollowing(value) {
|
||||
following = value;
|
||||
byName = new Map(following.profiles.map((p) => [p.username, p]));
|
||||
byId = new Map(following.profiles.filter((p) => p.instagramId).map((p) => [p.instagramId, p]));
|
||||
}
|
||||
|
||||
async function loadFollowing() {
|
||||
try {
|
||||
following = await api('/api/following');
|
||||
setFollowing(await api('/api/following', { signal: aborter.signal }));
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') return;
|
||||
showError(error);
|
||||
following = { profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 };
|
||||
setFollowing({ profiles: [], total: 0, inProgress: false, readSoFar: 0, readDay: null, backfillPerDay: 300 });
|
||||
}
|
||||
drawList();
|
||||
drawProgress();
|
||||
drawFollowed();
|
||||
drawRight();
|
||||
if (box.value) drawSuggestions();
|
||||
}
|
||||
|
||||
async function reread() {
|
||||
try {
|
||||
following = await api('/api/following/read', { method: 'POST' });
|
||||
setFollowing(await api('/api/following/read', { method: 'POST' }));
|
||||
drawProgress();
|
||||
drawList();
|
||||
drawFollowed();
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
allButton.addEventListener('click', () => {
|
||||
if (!following) return;
|
||||
const term = search.value.trim().toLowerCase().replace(/^@/, '');
|
||||
const shown = following.profiles.filter((p) => !present(p) && (!term || p.username.includes(term) || (p.displayName || '').toLowerCase().includes(term)));
|
||||
const all = shown.every((p) => chosen.has(p.username));
|
||||
for (const p of shown) {
|
||||
if (all) chosen.delete(p.username);
|
||||
else chosen.add(p.username);
|
||||
function setView(value) {
|
||||
view = value;
|
||||
if (value === 'seguiti') {
|
||||
setOpen(false);
|
||||
send.cancel();
|
||||
awaiting = false;
|
||||
fill(left, searchZone,
|
||||
h('div.scelti-testa', h('h3', t('aggiungi.seguiti')), allButton, toFollowed),
|
||||
followedList, progress);
|
||||
drawFollowed();
|
||||
endRemote();
|
||||
} else {
|
||||
fill(left, searchZone,
|
||||
h('div.scelti-testa', chosenTitle, toFollowed),
|
||||
chosenList, parsedInfo, problems);
|
||||
drawChosen();
|
||||
}
|
||||
allButton.textContent = t(all ? 'aggiungi.selezionaTutti' : 'aggiungi.togliTutti');
|
||||
drawList();
|
||||
drawRight();
|
||||
});
|
||||
search.addEventListener('input', later(drawList, 120));
|
||||
drawProgress();
|
||||
box.placeholder = value === 'seguiti' ? t('aggiungi.filtraSeguiti') : t('aggiungi.cerca');
|
||||
box.focus();
|
||||
if (value === 'scelti' && box.value) onInput();
|
||||
}
|
||||
|
||||
const parse = later(async () => {
|
||||
try {
|
||||
parsed = await api('/api/accounts/parse', { method: 'POST', body: { text: area.value } });
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
return;
|
||||
/** The window no longer searches on Instagram (closed, or the whole list is open). */
|
||||
function endRemote() {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = 0;
|
||||
remote = null;
|
||||
lastVersion = -1;
|
||||
api('/api/ricerca/fine', { method: 'POST', body: { client }, keepalive: true }).catch(() => {});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- the box
|
||||
box.addEventListener('input', onInput);
|
||||
box.addEventListener('focus', () => {
|
||||
if (view === 'scelti' && box.value) drawSuggestions();
|
||||
});
|
||||
box.addEventListener('blur', () => setOpen(false));
|
||||
// A press on the list (its scroll bar, a title) keeps the focus in the box, so the list stays open.
|
||||
suggestions.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
box.addEventListener('paste', (e) => {
|
||||
const text = e.clipboardData ? e.clipboardData.getData('text') : '';
|
||||
if (!isSeveralNames(text)) return; // one name or address: it goes in the box and is searched
|
||||
e.preventDefault();
|
||||
addNames(text, false);
|
||||
});
|
||||
box.addEventListener('keydown', (e) => {
|
||||
if (view !== 'scelti') return;
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
move(e.key === 'ArrowDown' ? 1 : -1);
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (open && active >= 0) {
|
||||
activate(active);
|
||||
return;
|
||||
}
|
||||
if (isSeveralNames(box.value)) {
|
||||
addNames(box.value, true);
|
||||
return;
|
||||
}
|
||||
const name = searchTerm(box.value);
|
||||
const exact = options.findIndex((o) => o.username === name);
|
||||
if (exact >= 0) activate(exact);
|
||||
else if (validName(name)) addNames(name, true);
|
||||
} else if (e.key === 'Tab') {
|
||||
setOpen(false);
|
||||
}
|
||||
const ready = parsed.names.filter((n) => !n.present);
|
||||
const already = parsed.names.length - ready.length;
|
||||
fill(parsedInfo, area.value.trim() ? [t('aggiungi.riconosciuti', { n: ready.length }), already ? ` · ${t('aggiungi.presenti', { n: already })}` : ''] : '');
|
||||
fill(problems, parsed.problems.map((p) => h('div', t('aggiungi.riga', { n: p.line, motivo: `«${p.text}»: ${p.reason}` }))));
|
||||
drawRight();
|
||||
}, 250);
|
||||
area.addEventListener('input', parse);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------- right: starting point
|
||||
function selection() {
|
||||
return tab === 'seguiti' ? [...chosen] : parsed.names.filter((n) => !n.present).map((n) => n.username);
|
||||
return [...chosen.keys()];
|
||||
}
|
||||
|
||||
function drawRight() {
|
||||
@@ -208,26 +803,37 @@ function build(close) {
|
||||
}
|
||||
}
|
||||
|
||||
function setTab(value) {
|
||||
tab = value;
|
||||
tabFollowed.classList.toggle('qui', value === 'seguiti');
|
||||
tabNames.classList.toggle('qui', value === 'nomi');
|
||||
tabFollowed.setAttribute('aria-selected', String(value === 'seguiti'));
|
||||
tabNames.setAttribute('aria-selected', String(value === 'nomi'));
|
||||
fill(left, value === 'seguiti' ? followedPanel : namesPanel);
|
||||
footerLeft.hidden = value !== 'seguiti';
|
||||
drawRight();
|
||||
(value === 'seguiti' ? search : area).focus();
|
||||
}
|
||||
tabFollowed.addEventListener('click', () => setTab('seguiti'));
|
||||
tabNames.addEventListener('click', () => setTab('nomi'));
|
||||
let engineMode = null;
|
||||
const stopEngine = onEngine((state) => {
|
||||
if (open) drawSuggestions();
|
||||
const mode = state && state.snapshot ? state.snapshot.mode : null;
|
||||
const changed = mode !== engineMode;
|
||||
engineMode = mode;
|
||||
// Alberto let go of the browser, «Riprendi»: the search resumes by itself, the window asks at once.
|
||||
if (changed && remote && remote.mine && RESUMING.includes(remote.state) && !awaiting && !closed) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = setTimeout(poll, FAST_POLL_MS);
|
||||
}
|
||||
});
|
||||
|
||||
fill(left, followedPanel);
|
||||
drawList();
|
||||
box.setAttribute('autofocus', '');
|
||||
setView('scelti');
|
||||
drawRight();
|
||||
loadFollowing();
|
||||
return {
|
||||
body: h('div', { style: { display: 'contents' } }, tabs, h('div.corpo-dialogo', left, right)),
|
||||
body: h('div.corpo-dialogo', left, right),
|
||||
footer: h('footer', footerLeft, h('div.destra', h('button.btn', { type: 'button', onclick: () => close(false) }, t('comune.annulla')), addButton)),
|
||||
onEscape: () => {
|
||||
if (!open) return false;
|
||||
setOpen(false);
|
||||
return true;
|
||||
},
|
||||
onClose: () => {
|
||||
closed = true;
|
||||
send.cancel();
|
||||
stopEngine();
|
||||
endRemote();
|
||||
aborter.abort();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -313,9 +313,36 @@
|
||||
},
|
||||
"aggiungi": {
|
||||
"titolo": "Aggiungi account",
|
||||
"seguiti": "Dai profili che segui",
|
||||
"perNome": "Per nome utente",
|
||||
"cerca": "Cerca tra i profili che segui",
|
||||
"seguiti": "Profili che segui",
|
||||
"cerca": "Cerca un profilo per nome o nome utente, o incolla più nomi",
|
||||
"cercaEtichetta": "Cerca un profilo da aggiungere",
|
||||
"filtraSeguiti": "Filtra i profili che segui",
|
||||
"suggerimenti": "Profili trovati",
|
||||
"traSeguiti": "Profili che segui e account in Febe",
|
||||
"nessunLocale": "Nessun profilo che segui ha questo nome.",
|
||||
"nonProfilo": "È l'indirizzo di un post, di un reel o di un'altra pagina, non di un profilo: incolla l'indirizzo del profilo (instagram.com/nome.utente).",
|
||||
"incollatiSeguiti": "1 nome aggiunto a «Da aggiungere»|{n} nomi aggiunti a «Da aggiungere»",
|
||||
"daInstagram": "Da Instagram",
|
||||
"perTesto": "per «{testo}»",
|
||||
"cercoSuInstagram": "Cerco su Instagram…",
|
||||
"attesa": "In attesa del turno: i risultati di Instagram arrivano appena il browser di Febe è libero.",
|
||||
"nessunAltro": "Su Instagram nessun altro profilo oltre a questi.",
|
||||
"alVolante": "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito. Intanto vedi i profili che segui.",
|
||||
"altraFinestra": "La ricerca su Instagram è in uso da un'altra finestra di Febe: qui vedi solo i profili che segui.",
|
||||
"trovati": "1 profilo trovato|{n} profili trovati",
|
||||
"seguito": "Seguito",
|
||||
"verificato": "Profilo verificato",
|
||||
"aggiungiUno": "Aggiungi",
|
||||
"aggiunto": "Aggiunto",
|
||||
"perNomeUtente": "Aggiungi @{nome} per nome utente",
|
||||
"perNomeSpiega": "Anche se non compare fra i risultati: Febe lo controlla alla prossima sessione",
|
||||
"piuNomi": "Aggiungi all'elenco i nomi scritti",
|
||||
"piuNomiSpiega": "Più nomi utente o indirizzi di profilo, separati da virgole",
|
||||
"daAggiungere": "Da aggiungere",
|
||||
"sceltiNessuno": "Cerca un profilo qui sopra e premi «Aggiungi», oppure incolla più nomi utente o indirizzi di profilo: uno per riga o separati da virgole.",
|
||||
"togli": "Togli @{nome} dall'elenco",
|
||||
"scegliTraSeguiti": "Scegli fra tutti i profili che segui ({n})",
|
||||
"chiudiSeguiti": "Torna a «Da aggiungere»",
|
||||
"selezionaTutti": "Seleziona tutti",
|
||||
"togliTutti": "Togli tutti",
|
||||
"giaPresente": "Già in Febe",
|
||||
@@ -328,11 +355,9 @@
|
||||
"inAttesa": "Lettura chiesta: comincia alla prossima sessione",
|
||||
"rilettura": "Febe rilegge l'elenco a ritmo umano, dentro i tetti: può servire più di una sessione.",
|
||||
"nessunSeguito": "Nessun profilo con questo nome nell'elenco.",
|
||||
"area": "Nomi utente o indirizzi dei profili",
|
||||
"areaAiuto": "Uno per riga: nome.utente, @nome.utente oppure instagram.com/nome.utente",
|
||||
"riconosciuti": "1 nome pronto|{n} nomi pronti",
|
||||
"presenti": "1 già in Febe|{n} già in Febe",
|
||||
"riga": "Riga {n}: {motivo}",
|
||||
"riga": "{n}° nome: {motivo}",
|
||||
"perScelti": "Per l'account scelto|Per i {n} account scelti",
|
||||
"perNessuno": "Scegli gli account a sinistra",
|
||||
"potraiCambiare": "Potrai cambiare tutto dopo, account per account.",
|
||||
|
||||
@@ -8,6 +8,7 @@ using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Privacy;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.SitoDiProva;
|
||||
@@ -179,12 +180,20 @@ public sealed class DiagnosticPrivacyTests
|
||||
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Story, DownloadStep.Retried) { Cause = DownloadCauses.Of(404) });
|
||||
diagnostics.DownloadSettled(new DownloadProgress(1, 2, 3, EntryKind.Story, DownloadStep.Failed) { Cause = "https://cdn.esempio/marta.prova.jpg" });
|
||||
|
||||
// The profile search (issue #37): outcomes only, and a name where an outcome is expected becomes «altro».
|
||||
diagnostics.SearchStepEnded(SearchOutcome.Ready);
|
||||
diagnostics.SearchStepEnded(SearchOutcome.Empty);
|
||||
diagnostics.SearchPhotoSettled("scaricata");
|
||||
diagnostics.SearchPhotoSettled("marta.prova");
|
||||
|
||||
var text = Export(diagnostics.Collect(), clock);
|
||||
Assert.AreEqual(0, diagnostics.Faults);
|
||||
using var report = JsonDocument.Parse(text);
|
||||
Assert.AreEqual(1, report.RootElement.GetProperty("sessioni").GetArrayLength());
|
||||
Assert.AreEqual(1, report.RootElement.GetProperty("fuoriSessione").GetArrayLength());
|
||||
StringAssert.Contains(text, "\"structure\"", "The unknown shape is there, by its keys.");
|
||||
StringAssert.Contains(text, "\"searchSteps\"", "The steps of the search are there, by outcome.");
|
||||
StringAssert.Contains(text, "\"altro\"", "An odd fate of a search photo becomes «altro».");
|
||||
foreach (var hiddenMap in new[] { "{data:{counts:{#},node:{tags:{#:[]},edges:{seen:{#:{pk,seen}}},items:[{#:{pk}}]}}}" })
|
||||
{
|
||||
StringAssert.Contains(text, hiddenMap, "The maps are there, without their names.");
|
||||
@@ -457,11 +466,12 @@ internal static partial class ReportLeaks
|
||||
}
|
||||
|
||||
values.UnionWith(CdpResourceTypes);
|
||||
values.UnionWith(CollectionDiagnostics.SearchPhotoOutcomes);
|
||||
foreach (var type in new[]
|
||||
{
|
||||
typeof(SessionOutcome), typeof(SessionStopCause), typeof(RecipeStatus), typeof(RecipeKind), typeof(SignalLevel), typeof(ActionKind),
|
||||
typeof(DenialReason), typeof(EntryKind), typeof(DownloadStep), typeof(BodyDropReason), typeof(HostKind), typeof(TargetCheckStatus),
|
||||
typeof(SaveOutcome),
|
||||
typeof(SaveOutcome), typeof(SearchOutcome),
|
||||
})
|
||||
{
|
||||
values.UnionWith(Enum.GetNames(type));
|
||||
@@ -478,7 +488,7 @@ internal static partial class ReportLeaks
|
||||
"count", "resourceType", "mime", "status", "bytes", "maxBytes", "recognized", "empty", "unrelated", "unrecognized", "notSite",
|
||||
"notRead", "contents", "profiles", "dropped", "reason", "structure", "verdict", "target", "kind", "signal", "actions",
|
||||
"newEntries", "level", "code", "action", "saves", "files", "skipped", "step", "requests", "ok", "cdn", "error", "cause", "late",
|
||||
"righeRovinate", "erroriRegistratore", "fileIlleggibili", "sessioniSenzaFine",
|
||||
"righeRovinate", "erroriRegistratore", "fileIlleggibili", "sessioniSenzaFine", "searchSteps", "searchPhotos",
|
||||
];
|
||||
|
||||
private static IEnumerable<string> Literals(SiteMap map) =>
|
||||
|
||||
@@ -70,6 +70,8 @@ public sealed class InstagramReaderTests
|
||||
Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt,
|
||||
Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items, Vocabulary.Highlight.Cover,
|
||||
Vocabulary.Page.HasMore, Vocabulary.Page.Cursor, Vocabulary.Viewer,
|
||||
Vocabulary.Search.Root, Vocabulary.Search.Items, Vocabulary.Search.Position, Vocabulary.Search.Profile, Vocabulary.Search.Id, Vocabulary.Search.Username,
|
||||
Vocabulary.Search.DisplayName, Vocabulary.Search.Picture, Vocabulary.Search.Verified,
|
||||
};
|
||||
foreach (var path in concepts.SelectMany(c => c.Paths))
|
||||
{
|
||||
@@ -328,7 +330,9 @@ public sealed class InstagramReaderTests
|
||||
{
|
||||
var search = ReadSample("ricerca-profili");
|
||||
Assert.AreEqual(ReadShape.Recognized, search.Shape);
|
||||
Assert.AreEqual(5, search.Profiles.Count);
|
||||
// Issue #37: the profiles of a search answer are results of the search, not followed or seen profiles.
|
||||
Assert.AreEqual(0, search.Profiles.Count);
|
||||
Assert.HasCount(5, search.Search!.Hits);
|
||||
Assert.AreEqual(0, search.Contents.Count);
|
||||
|
||||
var suggested = ReadSample("profili-suggeriti");
|
||||
|
||||
@@ -0,0 +1,827 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Gestures;
|
||||
using Febe.Browser.Targets;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The profile search on the site (issue #37): the text rules, the closed key map, the reader of the answer, the
|
||||
/// capture's own buffer, the step on a fake page with a search box, and the photo cache. Nothing here contacts a site.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ProfileSearchTests
|
||||
{
|
||||
private static readonly DateTimeOffset Start = new(2026, 11, 15, 11, 0, 0, TimeSpan.Zero);
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ text rules
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("mario", "mario")]
|
||||
[DataRow(" @Mario.Rossi ", "mario.rossi")]
|
||||
[DataRow("Niccolò", "niccolo")]
|
||||
[DataRow("mario rossi", "mario rossi")]
|
||||
[DataRow("https://www.instagram.com/mario_rossi/", "mario_rossi")]
|
||||
[DataRow("instagram.com/Mario_Rossi?igsh=x", "mario_rossi")]
|
||||
public void ATypableTextIsCleanedAsTheSiteWouldTypeIt(string raw, string typed)
|
||||
{
|
||||
var query = SearchText.Normalize(raw);
|
||||
Assert.AreEqual(SearchQueryKind.Typable, query.Kind);
|
||||
Assert.AreEqual(typed, query.Typed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("mario\nrossi", SearchQueryKind.SeveralNames)]
|
||||
[DataRow("mario\r", SearchQueryKind.SeveralNames)]
|
||||
[DataRow("mario, rossi", SearchQueryKind.SeveralNames)]
|
||||
[DataRow("a;b", SearchQueryKind.SeveralNames)]
|
||||
[DataRow("instagram.com/a instagram.com/b", SearchQueryKind.SeveralNames)]
|
||||
[DataRow("mario\trossi", SearchQueryKind.Refused)]
|
||||
[DataRow("mariorossi", SearchQueryKind.Refused)]
|
||||
[DataRow("m", SearchQueryKind.LocalOnly)]
|
||||
[DataRow("mario-rossi", SearchQueryKind.LocalOnly)]
|
||||
[DataRow("mario+", SearchQueryKind.LocalOnly)]
|
||||
[DataRow("instagram.com/p/ABC123/", SearchQueryKind.LocalOnly)]
|
||||
[DataRow(" ", SearchQueryKind.Empty)]
|
||||
[DataRow("", SearchQueryKind.Empty)]
|
||||
public void TextsFebeNeverTypesStayLocal(string raw, SearchQueryKind kind)
|
||||
{
|
||||
var query = SearchText.Normalize(raw);
|
||||
Assert.AreEqual(kind, query.Kind);
|
||||
Assert.AreEqual(string.Empty, query.Typed, "nothing to type");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AtMostFortyCharactersAreTyped()
|
||||
{
|
||||
Assert.AreEqual(SearchQueryKind.Typable, SearchText.Normalize(new string('a', 40)).Kind);
|
||||
Assert.AreEqual(SearchQueryKind.LocalOnly, SearchText.Normalize(new string('a', 41)).Kind);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryTypableTextHasAKeyForEachCharacterAndNothingElseDoes()
|
||||
{
|
||||
foreach (var c in "abcdefghijklmnopqrstuvwxyz0123456789._ ")
|
||||
{
|
||||
Assert.IsNotNull(SearchKeyMap.For(c), $"«{c}»");
|
||||
}
|
||||
|
||||
foreach (var c in "\n\r\t\u001bA-@#é+/\\'\"")
|
||||
{
|
||||
Assert.IsNull(SearchKeyMap.For(c), $"U+{(int)c:X4} must have no key");
|
||||
}
|
||||
|
||||
Assert.IsTrue(SearchKeyMap.CanType(SearchText.Normalize("Mario Rossi_92.").Typed));
|
||||
var underscore = SearchKeyMap.For('_')!;
|
||||
Assert.AreEqual("Minus", underscore.Code);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- the reader
|
||||
|
||||
[TestMethod]
|
||||
public void TheSearchAnswerOfTheCleanedSampleGivesFiveProfilesInOrder()
|
||||
{
|
||||
var reader = new ShapeReader(ReaderVocabulary.LoadInstagram());
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram", "000002-ricerca-profili.json")));
|
||||
var body = document.RootElement.GetProperty("corpo");
|
||||
var result = reader.Read(body);
|
||||
|
||||
Assert.AreEqual(ReadShape.Recognized, result.Shape);
|
||||
Assert.IsNotNull(result.Search);
|
||||
Assert.AreEqual(0, result.Profiles.Count, "search results are not followed profiles");
|
||||
Assert.AreEqual(0, result.Contents.Count);
|
||||
var hits = result.Search.Hits;
|
||||
Assert.HasCount(5, hits);
|
||||
CollectionAssert.AreEqual(new[] { 0, 1, 2, 3, 4 }, hits.Select(h => h.Position).ToArray());
|
||||
var users = body.GetProperty("data").GetProperty("xdt_api__v1__fbsearch__topsearch_connection").GetProperty("users").EnumerateArray().ToList();
|
||||
for (var i = 0; i < hits.Count; i++)
|
||||
{
|
||||
var user = users[i].GetProperty("user");
|
||||
Assert.AreEqual(user.GetProperty("pk").GetString(), hits[i].Profile.Id);
|
||||
Assert.AreEqual(user.GetProperty("username").GetString(), hits[i].Profile.Username);
|
||||
Assert.AreEqual(user.GetProperty("profile_pic_url").GetString(), hits[i].Profile.Picture?.Url);
|
||||
Assert.IsFalse(hits[i].IsVerified);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnEmptyAnswerIsAnAnswerAndTheTestSiteReadsTheSameShape()
|
||||
{
|
||||
var instagram = new ShapeReader(ReaderVocabulary.LoadInstagram());
|
||||
var empty = instagram.Read(Parse("""{"data":{"xdt_api__v1__fbsearch__topsearch_connection":{"hashtags":[],"places":[],"users":[]}},"extensions":{"is_final":true}}"""));
|
||||
Assert.AreEqual(ReadShape.Recognized, empty.Shape);
|
||||
Assert.IsNotNull(empty.Search);
|
||||
Assert.HasCount(0, empty.Search.Hits);
|
||||
|
||||
var prova = new ShapeReader(ReaderVocabulary.LoadTestSite());
|
||||
var answer = prova.Read(Answer(("1", "mario.rossi"), ("2", "maria.bianchi")));
|
||||
Assert.IsNotNull(answer.Search);
|
||||
CollectionAssert.AreEqual(new[] { "mario.rossi", "maria.bianchi" }, answer.Search.Hits.Select(h => h.Profile.Username).ToArray());
|
||||
Assert.AreEqual(0, answer.Profiles.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheVocabularyOfTheSearchComesFromTheRealSample()
|
||||
{
|
||||
var search = ReaderVocabulary.LoadInstagram().Search;
|
||||
Assert.IsTrue(search.IsSet);
|
||||
var text = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram", "000002-ricerca-profili.json"));
|
||||
foreach (var key in new[] { search.Root, search.Items, search.Position, search.Profile, search.Id, search.Username, search.DisplayName, search.Picture, search.Verified }.SelectMany(k => k.Paths))
|
||||
{
|
||||
StringAssert.Contains(text, $"\"{key}\"", $"«{key}» non compare nel campione ripulito della ricerca.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SearchAnswersGoToTheirOwnBufferNotToTheRecipes()
|
||||
{
|
||||
var clock = new InstantClock(Start);
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock);
|
||||
var mark = capture.Mark();
|
||||
var searchMark = capture.SearchMark();
|
||||
capture.Accept(Descriptor("r1", clock), Answer(("1", "mario.rossi")));
|
||||
|
||||
Assert.HasCount(0, capture.Since(mark), "a recipe never sees a search answer");
|
||||
Assert.HasCount(1, capture.SearchSince(searchMark));
|
||||
Assert.IsNotNull(capture.LastArrivalAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RecordsOfTheSearchNeverPrintNamesOrTexts()
|
||||
{
|
||||
var hit = new SearchHit(0, "12345678901", "segreto.nome", "Nome Segreto", true, "0123456789abcdef0123456789abcdef", true);
|
||||
var view = new SearchView(3, "aaaaaaaaaaaaaaaa", "segreto", SearchState.Ready, null, [hit], null);
|
||||
var query = SearchText.Normalize("segreto.nome");
|
||||
var step = new SearchStepResult(SearchOutcome.Ready, "segreto.nome", null);
|
||||
var photo = new SearchPhotoRequest("12345678901", new Uri("https://cdn.esempio/segreto.jpg?firma=abc"));
|
||||
foreach (var text in new[] { hit.ToString(), view.ToString(), query.ToString(), step.ToString(), photo.ToString() })
|
||||
{
|
||||
foreach (var secret in new[] { "segreto", "Segreto", "12345678901", "0123456789abcdef", "firma", "aaaaaaaa" })
|
||||
{
|
||||
Assert.IsFalse(text.Contains(secret, StringComparison.Ordinal), $"«{text}» prints «{secret}»");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheFocusCheckIsAReadOnlyScriptThatNeverReturnsTheText()
|
||||
{
|
||||
var map = TargetMap.LoadEmbedded("bersagli.prova.json");
|
||||
var expression = TargetResolver.BuildFocusExpression(map.Get(SiteTargets.SearchBox));
|
||||
ReadOnlyScriptGuard.EnsureReadOnly(expression);
|
||||
StringAssert.Contains(expression, "value.length");
|
||||
StringAssert.Contains(expression, "return { found: true, focused: inBox, length, atEnd }", "the answer holds a length, never the text");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------- one search step
|
||||
|
||||
[TestMethod]
|
||||
public async Task AStepOpensTheSiteTypesTheTextAndReadsTheLatestAnswer()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "mario.rossi"), ("2", "mario.bianchi"), ("3", "luca.verdi")];
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
|
||||
Assert.AreEqual("mario", result.Typed);
|
||||
CollectionAssert.AreEqual(new[] { "mario.rossi", "mario.bianchi" }, result.Answer!.Hits.Select(h => h.Profile.Username).ToArray(), "the answer for the whole text, not for a prefix");
|
||||
Assert.AreEqual("mario", bed.Site.Box);
|
||||
Assert.AreEqual(1, bed.Site.Opened, "the home page, once");
|
||||
CollectionAssert.AreEqual(new[] { SiteTargets.SearchOpen, SiteTargets.SearchBox }, bed.Site.Clicks, "only «Cerca» and the box: never a result");
|
||||
Assert.AreEqual(3, bed.Governor.Granted(ActionKind.ProfileSearch), "home, focus, one burst");
|
||||
Assert.AreEqual(PageUser.Search, bed.Turns.LastUser);
|
||||
Assert.AreEqual(0, bed.Site.EnterPressed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ANewTextKeepsTheCommonPrefixAndErasesOnlyTheRest()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "mario.rossi"), ("2", "matteo.neri")];
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mario", CancellationToken.None)).Outcome);
|
||||
var keys = bed.Site.Keys;
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "mat", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
|
||||
Assert.AreEqual("mat", bed.Site.Box);
|
||||
Assert.AreEqual(keys + 3 + 1, bed.Site.Keys, "three Backspaces and one letter");
|
||||
Assert.AreEqual(1, bed.Site.Opened, "the page is still the site: no new home");
|
||||
CollectionAssert.AreEqual(new[] { "matteo.neri" }, result.Answer!.Hits.Select(h => h.Profile.Username).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ATextInTheBoxThatFebeDidNotTypeIsErasedFirst()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "anna.blu")];
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "anna", CancellationToken.None)).Outcome);
|
||||
bed.Site.Box = "qualcosa";
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "anna", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
|
||||
Assert.AreEqual("anna", bed.Site.Box);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoProfileIsEmptyAndNoAnswerIsNotEmpty()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "mario.rossi")];
|
||||
var empty = await bed.Runner.SearchAsync(() => "zzz", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.Empty, empty.Outcome);
|
||||
Assert.AreEqual(0, bed.Signals.EmptyPages, "an empty search is not an empty page");
|
||||
|
||||
bed.Site.Answers = false;
|
||||
var none = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.NoAnswer, none.Outcome);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheSessionCookieTheStepStopsAsADisconnection()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Cookie = false;
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.NotConnected, result.Outcome);
|
||||
Assert.AreEqual(1, bed.Signals.MissingCookie);
|
||||
Assert.AreEqual(0, bed.Site.Opened);
|
||||
Assert.AreEqual(0, bed.Governor.Granted(ActionKind.ProfileSearch));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARefusalOfTheGovernorStopsBeforeAnyGesture()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Governor.Limit(ActionKind.ProfileSearch, 0);
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Denied, result.Outcome);
|
||||
Assert.AreEqual(DenialReason.HourlyBudgetReached, result.Denial!.Reason);
|
||||
Assert.AreEqual(0, bed.Site.Opened);
|
||||
Assert.AreEqual(0, bed.Site.Keys);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task KeysThatDoNotReachTheBoxAreReported()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.IgnoreKeys = true;
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.KeysNotReceived, result.Outcome);
|
||||
StringAssert.Contains(result.Message!, "non riceve i tasti");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AlbertoAtTheBrowserOrAnOpenBreakerTouchNothing()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Driving = true;
|
||||
Assert.AreEqual(SearchOutcome.NotPossible, (await bed.Runner.SearchAsync(() => "mario", CancellationToken.None)).Outcome);
|
||||
bed.Driving = false;
|
||||
bed.Breaker.Current = new BreakerState(BreakerStatus.Throttled, Start.AddHours(1), null, null);
|
||||
Assert.AreEqual(SearchOutcome.Stopped, (await bed.Runner.SearchAsync(() => "mario", CancellationToken.None)).Outcome);
|
||||
Assert.AreEqual(0, bed.Site.Opened);
|
||||
Assert.AreEqual(0, bed.Governor.Requests.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnInstagramTheSearchWaitsForItsTargets()
|
||||
{
|
||||
var bed = new StepBed(SiteMap.LoadInstagram());
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.NotConfigured, result.Outcome);
|
||||
StringAssert.Contains(result.Message!, "«Cerca»");
|
||||
Assert.AreEqual(0, bed.Site.Opened);
|
||||
Assert.AreEqual(0, bed.Governor.Requests.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ATextNoLongerWantedStopsBetweenTwoKeys()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
var wanted = "mariarosa";
|
||||
bed.Site.OnKey = box =>
|
||||
{
|
||||
if (box.Length == 3)
|
||||
{
|
||||
wanted = null!;
|
||||
}
|
||||
};
|
||||
|
||||
var result = await bed.Runner.SearchAsync(() => wanted, CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Interrupted, result.Outcome);
|
||||
Assert.AreEqual("mar", bed.Site.Box);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnswersToTheTextsBeforeTheLastKeyAreNeverTakenForTheTextEvenWhenTheyArriveLater()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "marta.prova"), ("2", "mario.rossi"), ("3", "matteo.neri"), ("4", "luca.martini")];
|
||||
|
||||
// The page asks for every text without waiting, and the shorter the text the later its answer comes
|
||||
// (the «disordine» of the test site): «m», «ma», «mar» and «mart» answer after «marta».
|
||||
bed.Site.Disorder = true;
|
||||
var result = await bed.Runner.SearchAsync(() => "marta", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
|
||||
Assert.AreEqual(5, bed.Site.Requests, "one request for each text the box held");
|
||||
CollectionAssert.AreEqual(new[] { "marta.prova" }, result.Answer!.Hits.Select(h => h.Profile.Username).ToArray(), "the answer to «marta», not to a prefix");
|
||||
|
||||
// Later answers to the prefixes do not change what the next step takes either.
|
||||
bed.Clock.Advance(TimeSpan.FromSeconds(5));
|
||||
await bed.Clock.Delay(TimeSpan.Zero, CancellationToken.None);
|
||||
var again = await bed.Runner.SearchAsync(() => "marta", CancellationToken.None);
|
||||
CollectionAssert.AreEqual(new[] { "marta.prova" }, again.Answer!.Hits.Select(h => h.Profile.Username).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ATextThePageAnswersFromItsMemoryUsesTheAnswerReadBeforeOnThatPage()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "marta.prova"), ("2", "mario.rossi")];
|
||||
bed.Site.Memory = true;
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "marta", CancellationToken.None)).Outcome);
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mar", CancellationToken.None)).Outcome);
|
||||
var requests = bed.Site.Requests;
|
||||
|
||||
var back = await bed.Runner.SearchAsync(() => "marta", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(requests, bed.Site.Requests, "the page sends no request for a text it has already searched");
|
||||
Assert.AreEqual(SearchOutcome.Ready, back.Outcome, back.Message);
|
||||
CollectionAssert.AreEqual(new[] { "marta.prova" }, back.Answer!.Hits.Select(h => h.Profile.Username).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnThePageOfTheEngineTheNextLetterIsTheOnlyKeyUntilTheEngineOpensAnotherPage()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "maria.blu")];
|
||||
|
||||
// A session: the engine opened the page, the search types on it between two engine actions.
|
||||
await bed.Site.OpenAsync("/", CancellationToken.None);
|
||||
bed.Turns.NoteOpened(PageUser.Engine);
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mar", CancellationToken.None)).Outcome);
|
||||
Assert.AreEqual(PageUser.Engine, bed.Turns.LastUser, "the search did not open a page");
|
||||
var keys = bed.Site.Keys;
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mari", CancellationToken.None)).Outcome);
|
||||
Assert.AreEqual(keys + 1, bed.Site.Keys, "one letter: what Febe typed on this page still holds");
|
||||
|
||||
// The engine opens another page: the box is gone, and Febe's record with it.
|
||||
await bed.Site.OpenAsync("/marta.prova/", CancellationToken.None);
|
||||
bed.Turns.NoteOpened(PageUser.Engine);
|
||||
keys = bed.Site.Keys;
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "maria", CancellationToken.None)).Outcome);
|
||||
Assert.AreEqual(keys + 5, bed.Site.Keys, "the whole text in the new box, nothing erased");
|
||||
Assert.AreEqual("maria", bed.Site.Box);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheFocusIsLookedAtAgainAfterThePermitRightBeforeTheFirstKey()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
bed.Site.Profiles = [("1", "mario.rossi")];
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await bed.Runner.SearchAsync(() => "mar", CancellationToken.None)).Outcome);
|
||||
var keys = bed.Site.Keys;
|
||||
|
||||
// While the Governor makes the burst wait, something takes the focus away from the box.
|
||||
bed.Governor.OnRequest = kind =>
|
||||
{
|
||||
if (kind == ActionKind.ProfileSearch)
|
||||
{
|
||||
bed.Site.Focused = false;
|
||||
}
|
||||
};
|
||||
var result = await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.FocusLost, result.Outcome);
|
||||
Assert.AreEqual(keys, bed.Site.Keys, "not one key without the focus in the box");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheRestPageIsSkippedAfterAVerification()
|
||||
{
|
||||
var bed = new StepBed();
|
||||
await bed.Runner.SearchAsync(() => "mario", CancellationToken.None);
|
||||
bed.Breaker.Current = new BreakerState(BreakerStatus.Challenge, null, null, null);
|
||||
await bed.Runner.RestAsync(CancellationToken.None);
|
||||
Assert.AreEqual(0, bed.Site.Rested);
|
||||
bed.Breaker.Current = BreakerState.Normal;
|
||||
await bed.Runner.RestAsync(CancellationToken.None);
|
||||
Assert.AreEqual(1, bed.Site.Rested);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- photo cache
|
||||
|
||||
[TestMethod]
|
||||
public void ThePhotoCacheIsBoundedAndANewPictureReplacesTheOld()
|
||||
{
|
||||
var clock = new InstantClock(Start);
|
||||
var cache = new SearchPhotoCache(clock, new ProfileSearchOptions { MaxPhotos = 2, MaxPhotoBytes = 1000 });
|
||||
var a = cache.Put("1", "f1", new byte[100]);
|
||||
StringAssert.Matches(a, new System.Text.RegularExpressions.Regex("^[0-9a-f]{32}$"));
|
||||
var b = cache.Put("2", "f2", new byte[100]);
|
||||
Assert.IsTrue(cache.TryOpen(a, out var stream));
|
||||
stream.Dispose();
|
||||
cache.Put("3", "f3", new byte[100]);
|
||||
Assert.IsFalse(cache.TryOpen(b, out _), "the least recently used goes first");
|
||||
Assert.IsTrue(cache.TryOpen(a, out var again));
|
||||
again.Dispose();
|
||||
|
||||
var replaced = cache.Put("1", "f9", new byte[50]);
|
||||
Assert.IsFalse(cache.TryOpen(a, out _));
|
||||
Assert.AreEqual(replaced, cache.KeyOf("1"));
|
||||
Assert.IsTrue(cache.Has("1", "f9"));
|
||||
Assert.IsFalse(cache.Has("1", "f1"));
|
||||
|
||||
clock.Advance(TimeSpan.FromDays(4));
|
||||
Assert.IsNull(cache.KeyOf("1"), "photos expire");
|
||||
Assert.AreEqual(0, cache.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheFileHashLeavesTheSignatureOut()
|
||||
{
|
||||
var one = SearchPhotoCache.FileHash(new Uri("https://cdn.esempio/v/t51/123_n.jpg?stp=a&oh=1"));
|
||||
var two = SearchPhotoCache.FileHash(new Uri("https://cdn.esempio/v/t51/123_n.jpg?stp=b&oh=2"));
|
||||
var other = SearchPhotoCache.FileHash(new Uri("https://cdn.esempio/v/t51/456_n.jpg?stp=a&oh=1"));
|
||||
Assert.AreEqual(one, two);
|
||||
Assert.AreNotEqual(one, other);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ support
|
||||
|
||||
private static JsonElement Parse(string json)
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
|
||||
private static JsonElement Answer(params (string Id, string Username)[] users)
|
||||
{
|
||||
var list = new JsonArray();
|
||||
for (var i = 0; i < users.Length; i++)
|
||||
{
|
||||
list.Add(new JsonObject
|
||||
{
|
||||
["position"] = i,
|
||||
["user"] = new JsonObject
|
||||
{
|
||||
["username"] = users[i].Username,
|
||||
["is_verified"] = false,
|
||||
["full_name"] = "Nome " + i,
|
||||
["pk"] = users[i].Id,
|
||||
["profile_pic_url"] = $"https://cdn.prova/foto/{users[i].Id}_n.jpg?firma=x",
|
||||
["id"] = users[i].Id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
var body = new JsonObject
|
||||
{
|
||||
["data"] = new JsonObject
|
||||
{
|
||||
["xdt_api__v1__fbsearch__topsearch_connection"] = new JsonObject { ["hashtags"] = new JsonArray(), ["places"] = new JsonArray(), ["users"] = list },
|
||||
},
|
||||
["extensions"] = new JsonObject { ["is_final"] = true },
|
||||
};
|
||||
return Parse(body.ToJsonString());
|
||||
}
|
||||
|
||||
private static ResponseDescriptor Descriptor(string id, IClock clock) =>
|
||||
new(id, HostKind.Site, "http://127.0.0.1:5000/dati/cerca", "127.0.0.1:5000", "/dati/cerca", 200, "application/json", "Fetch", false, clock.Now);
|
||||
|
||||
/// <summary>A clock whose waits pass at once and run what falls due meanwhile (answers arrive while the step waits).</summary>
|
||||
private sealed class InstantClock(DateTimeOffset start) : IClock
|
||||
{
|
||||
private readonly List<(DateTimeOffset At, Action Action)> _due = [];
|
||||
|
||||
public DateTimeOffset Now { get; private set; } = start;
|
||||
|
||||
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
|
||||
|
||||
public void After(TimeSpan delay, Action action) => _due.Add((Now + delay, action));
|
||||
|
||||
public void Advance(TimeSpan time) => Now += time;
|
||||
|
||||
public Task Delay(TimeSpan time, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (time > TimeSpan.Zero)
|
||||
{
|
||||
Now += time;
|
||||
}
|
||||
|
||||
foreach (var item in _due.Where(d => d.At <= Now).ToList())
|
||||
{
|
||||
_due.Remove(item);
|
||||
item.Action();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeSignals : IStopSignals
|
||||
{
|
||||
public int EmptyPages { get; private set; }
|
||||
|
||||
public int MissingCookie { get; private set; }
|
||||
|
||||
public event EventHandler<Signal>? SignalRaised
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public Signal? ObserveEmptyPage(string? url = null)
|
||||
{
|
||||
EmptyPages++;
|
||||
return null;
|
||||
}
|
||||
|
||||
public void ObserveNonEmptyPage()
|
||||
{
|
||||
}
|
||||
|
||||
public Signal? ObserveSessionCookie(bool present)
|
||||
{
|
||||
if (!present)
|
||||
{
|
||||
MissingCookie++;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeBreaker : ICircuitBreaker
|
||||
{
|
||||
public BreakerState Current { get; set; } = BreakerState.Normal;
|
||||
|
||||
public BreakerState State => Current;
|
||||
|
||||
public void Report(Signal signal)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A page of the site with a «Cerca» button, a box, and answers that come 300 ms after each key.</summary>
|
||||
private sealed class SearchSite(InstantClock clock, CaptureCollector capture) : IPageDriver, ISearchInput
|
||||
{
|
||||
private int _answers;
|
||||
|
||||
public bool OnSite { get; set; }
|
||||
|
||||
public bool PanelOpen { get; set; }
|
||||
|
||||
public bool Focused { get; set; }
|
||||
|
||||
public string Box { get; set; } = string.Empty;
|
||||
|
||||
public bool? Cookie { get; set; } = true;
|
||||
|
||||
public bool Answers { get; set; } = true;
|
||||
|
||||
public bool IgnoreKeys { get; set; }
|
||||
|
||||
/// <summary>The page asks for every text at once (no wait), and shorter texts are answered later.</summary>
|
||||
public bool Disorder { get; set; }
|
||||
|
||||
/// <summary>The page answers a text it has already searched on this page from its memory, without a request.</summary>
|
||||
public bool Memory { get; set; }
|
||||
|
||||
/// <summary>Requests the page sent for the search.</summary>
|
||||
public int Requests { get; private set; }
|
||||
|
||||
private readonly HashSet<string> _memory = new(StringComparer.Ordinal);
|
||||
|
||||
public int EnterPressed { get; }
|
||||
|
||||
public (string Id, string Username)[] Profiles { get; set; } = [];
|
||||
|
||||
public Action<string>? OnKey { get; set; }
|
||||
|
||||
public int Opened { get; private set; }
|
||||
|
||||
public int Rested { get; private set; }
|
||||
|
||||
public int Keys { get; private set; }
|
||||
|
||||
public List<string> Clicks { get; } = [];
|
||||
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public void BeginSession(double mood)
|
||||
{
|
||||
}
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct)
|
||||
{
|
||||
Opened++;
|
||||
OnSite = true;
|
||||
PanelOpen = false;
|
||||
Focused = false;
|
||||
Box = string.Empty;
|
||||
_memory.Clear();
|
||||
return Task.FromResult(new PageLoad(true, path, null));
|
||||
}
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => Task.FromResult(OnSite ? "/" : string.Empty);
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(OnSite);
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) =>
|
||||
Task.FromResult(new TargetCheck(target, TargetCheckStatus.Found, 1, string.Empty));
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
|
||||
{
|
||||
Clicks.Add(target);
|
||||
var ok = target switch
|
||||
{
|
||||
SiteTargets.SearchOpen when OnSite => PanelOpen = true,
|
||||
SiteTargets.SearchBox when PanelOpen => Focused = true,
|
||||
_ => false,
|
||||
};
|
||||
return Task.FromResult(new TargetCheck(target, ok ? TargetCheckStatus.Clicked : TargetCheckStatus.NotFound, ok ? 1 : 0, string.Empty));
|
||||
}
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct) => throw new AssertFailedException("the search never scrolls");
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => clock.Delay(TimeSpan.FromSeconds(1), ct);
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => clock.Delay(duration, ct);
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult(Cookie);
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
Rested++;
|
||||
OnSite = false;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<SearchFocus> FocusAsync(CancellationToken ct) =>
|
||||
Task.FromResult(PanelOpen ? new SearchFocus(true, Focused, Focused ? Box.Length : null, true) : SearchFocus.None);
|
||||
|
||||
public Task EndKeyAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public async Task EraseAsync(int count, Action? beforeKey, CancellationToken ct)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
beforeKey?.Invoke();
|
||||
Keys++;
|
||||
if (Focused && !IgnoreKeys && Box.Length > 0)
|
||||
{
|
||||
Box = Box[..^1];
|
||||
Answer();
|
||||
}
|
||||
|
||||
await clock.Delay(TimeSpan.FromMilliseconds(110), ct);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct)
|
||||
{
|
||||
var typed = 0;
|
||||
while (await next(typed, ct) is { } c)
|
||||
{
|
||||
Assert.IsNotNull(SearchKeyMap.For(c), "only keys of the map");
|
||||
Keys++;
|
||||
typed++;
|
||||
if (Focused && !IgnoreKeys)
|
||||
{
|
||||
Box += c;
|
||||
Answer();
|
||||
}
|
||||
|
||||
OnKey?.Invoke(Box);
|
||||
await clock.Delay(TimeSpan.FromMilliseconds(110), ct);
|
||||
}
|
||||
|
||||
return typed;
|
||||
}
|
||||
|
||||
private void Answer()
|
||||
{
|
||||
if (!Answers)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var text = Box;
|
||||
var id = "s" + _answers++;
|
||||
if (Disorder)
|
||||
{
|
||||
// No wait: a request for every text at once, the shorter ones answered later.
|
||||
var order = Start();
|
||||
clock.After(TimeSpan.FromMilliseconds(300 + (Math.Max(0, 8 - text.Length) * 250)), () => Reply(id, text, order));
|
||||
return;
|
||||
}
|
||||
|
||||
clock.After(TimeSpan.FromMilliseconds(300), () =>
|
||||
{
|
||||
// The site's debounce: only the answer for what the box holds then.
|
||||
if (text != Box)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (Memory)
|
||||
{
|
||||
if (!_memory.Add(text))
|
||||
{
|
||||
// Shown from the page's memory: no request.
|
||||
return;
|
||||
}
|
||||
|
||||
var order = Start();
|
||||
clock.After(TimeSpan.FromMilliseconds(200), () => Reply(id, text, order));
|
||||
return;
|
||||
}
|
||||
|
||||
Requests++;
|
||||
var users = Profiles.Where(p => p.Username.Contains(text, StringComparison.Ordinal)).ToArray();
|
||||
capture.Accept(Descriptor(id, clock), ProfileSearchTests.Answer(users));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The page starts a request: the capture learns its order, as from Network.requestWillBeSent.</summary>
|
||||
private long Start()
|
||||
{
|
||||
Requests++;
|
||||
((IResponseObserver)capture).OnRequestStarted(Requests);
|
||||
return Requests;
|
||||
}
|
||||
|
||||
private void Reply(string id, string text, long order)
|
||||
{
|
||||
var users = Profiles.Where(p => p.Username.Contains(text, StringComparison.Ordinal)).ToArray();
|
||||
capture.Accept(Descriptor(id, clock) with { RequestOrder = order }, ProfileSearchTests.Answer(users));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class StepBed
|
||||
{
|
||||
public StepBed(SiteMap? map = null)
|
||||
{
|
||||
Clock = new InstantClock(Start);
|
||||
Capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), Clock);
|
||||
Site = new SearchSite(Clock, Capture);
|
||||
Runner = new ProfileSearchRunner(
|
||||
Site,
|
||||
Site,
|
||||
Capture,
|
||||
map ?? SiteMap.LoadTestSite(),
|
||||
Governor,
|
||||
Signals,
|
||||
Breaker,
|
||||
Clock,
|
||||
new SeededRandom(3),
|
||||
Turns,
|
||||
ProfileSearchOptions.Default,
|
||||
() => Driving);
|
||||
}
|
||||
|
||||
public InstantClock Clock { get; }
|
||||
|
||||
public CaptureCollector Capture { get; }
|
||||
|
||||
public SearchSite Site { get; }
|
||||
|
||||
public PermissiveGovernor Governor { get; } = new();
|
||||
|
||||
public FakeSignals Signals { get; } = new();
|
||||
|
||||
public FakeBreaker Breaker { get; } = new();
|
||||
|
||||
public PageTurns Turns { get; } = new();
|
||||
|
||||
public bool Driving { get; set; }
|
||||
|
||||
public ProfileSearchRunner Runner { get; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Collection.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The profile search (issue #37) against the local test site, with a real Chromium on a private Xvfb display: the
|
||||
/// panel «Cerca», typing with key events, the answers in the shape of the cleaned sample, the photos from the CDN, and
|
||||
/// the rest page. Never Instagram.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[TestCategory(SyntheticSite.Category)]
|
||||
[DoNotParallelize]
|
||||
public sealed class SearchIntegrationTests
|
||||
{
|
||||
private static SharedChromium? s_chromium;
|
||||
private static string? s_unavailable;
|
||||
|
||||
private static SharedChromium Chromium => s_chromium ?? throw new InvalidOperationException("Browser non avviato.");
|
||||
|
||||
[ClassInitialize]
|
||||
public static async Task StartAsync(TestContext context)
|
||||
{
|
||||
s_unavailable = SharedChromium.UnavailableReason();
|
||||
if (s_unavailable is null)
|
||||
{
|
||||
s_chromium = await SharedChromium.StartAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[ClassCleanup]
|
||||
public static async Task StopAsync()
|
||||
{
|
||||
if (s_chromium is not null)
|
||||
{
|
||||
await s_chromium.DisposeAsync();
|
||||
s_chromium = null;
|
||||
}
|
||||
}
|
||||
|
||||
[TestInitialize]
|
||||
public void RequireBrowser()
|
||||
{
|
||||
if (s_unavailable is not null)
|
||||
{
|
||||
Assert.Inconclusive(s_unavailable);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(90_000, CooperativeCancellation = true)]
|
||||
public async Task TheSearchTypesInTheSitesBoxAndReadsItsAnswerWithoutOpeningAResult()
|
||||
{
|
||||
await using var h = await CollectionHarness.CreateAsync(Chromium);
|
||||
|
||||
var first = await h.Search.SearchAsync(() => "marta", CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, first.Outcome, first.Message);
|
||||
Assert.AreEqual("marta.prova", first.Answer!.Hits[0].Profile.Username);
|
||||
Assert.AreEqual("/", await h.CurrentPathAsync(), "the page stays the home page: no result is opened");
|
||||
Assert.AreEqual(PageUser.Search, h.Turns.LastUser);
|
||||
Assert.IsTrue(h.Governor.Granted(ActionKind.ProfileSearch) >= 3, "every gesture after a permit");
|
||||
Assert.AreEqual(0, h.Site.Control.RecentSearchWrites, "Enter is never pressed and no result is clicked");
|
||||
|
||||
// Alberto keeps typing: «marta» → «ma»: three Backspaces, the same box, a wider answer.
|
||||
var second = await h.Search.SearchAsync(() => "ma", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.Ready, second.Outcome, second.Message);
|
||||
Assert.IsTrue(second.Answer!.Hits.Count >= 1);
|
||||
|
||||
var none = await h.Search.SearchAsync(() => "zzzz", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.Empty, none.Outcome, none.Message);
|
||||
|
||||
await h.Search.RestAsync(CancellationToken.None);
|
||||
Assert.IsFalse(await h.Driver.IsOnSiteAsync(CancellationToken.None), "back to the rest page");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(90_000, CooperativeCancellation = true)]
|
||||
public async Task ThePhotosOfTheResultsComeFromTheCdnIntoMemory()
|
||||
{
|
||||
await using var h = await CollectionHarness.CreateAsync(Chromium);
|
||||
var result = await h.Search.SearchAsync(() => "prova", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.Ready, result.Outcome, result.Message);
|
||||
var queue = h.Pipeline.SearchPhotos!;
|
||||
|
||||
queue.Enqueue(result.Answer!.Hits.Take(3).Select(x => new SearchPhotoRequest(x.Profile.Id, new Uri(x.Profile.Picture!.Url))));
|
||||
|
||||
await TestWait.UntilAsync(() => h.SearchPhotos.Count == 3, "three photos in memory");
|
||||
var key = h.SearchPhotos.KeyOf(result.Answer.Hits[0].Profile.Id)!;
|
||||
Assert.IsTrue(h.SearchPhotos.TryOpen(key, out var stream));
|
||||
using (stream)
|
||||
{
|
||||
var head = new byte[2];
|
||||
Assert.AreEqual(2, stream.Read(head));
|
||||
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8 }, head, "a JPEG");
|
||||
}
|
||||
|
||||
Assert.IsTrue(h.DataBudget.Used > 0, "the bytes count in the daily data budget");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task OutOfOrderAnswersAndThePagesMemoryStillGiveTheAnswerToTheWholeText()
|
||||
{
|
||||
await using var h = await CollectionHarness.CreateAsync(Chromium);
|
||||
|
||||
// «ricerca/disordine»: shorter texts are answered later; «ricerca/memoria»: the page sends no request for a
|
||||
// text it has already searched. Both are read when the page loads: the first step opens the home page.
|
||||
h.Site.Control.SearchDisorder = true;
|
||||
h.Site.Control.SearchMemory = true;
|
||||
|
||||
var first = await h.Search.SearchAsync(() => "marta", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.Ready, first.Outcome, first.Message);
|
||||
Assert.IsTrue(first.Answer!.Hits.All(Matches), "only profiles that match «marta», never the answer to a prefix");
|
||||
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await h.Search.SearchAsync(() => "ma", CancellationToken.None)).Outcome);
|
||||
var back = await h.Search.SearchAsync(() => "marta", CancellationToken.None);
|
||||
Assert.AreEqual(SearchOutcome.Ready, back.Outcome, back.Message);
|
||||
CollectionAssert.AreEqual(
|
||||
first.Answer.Hits.Select(x => x.Profile.Username).ToArray(),
|
||||
back.Answer!.Hits.Select(x => x.Profile.Username).ToArray(),
|
||||
"the page shows «marta» from its memory: Febe gives the answer it read on this page");
|
||||
Assert.AreEqual(0, h.Site.Control.RecentSearchWrites);
|
||||
|
||||
static bool Matches(SearchProfile hit) =>
|
||||
hit.Profile.Username.Contains("marta", StringComparison.Ordinal)
|
||||
|| (hit.Profile.DisplayName ?? string.Empty).Contains("marta", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task ARecipeAfterASearchStillWorks()
|
||||
{
|
||||
await using var h = await CollectionHarness.CreateAsync(Chromium);
|
||||
var marta = await h.AddAccountAsync("marta.prova");
|
||||
Assert.AreEqual(SearchOutcome.Ready, (await h.Search.SearchAsync(() => "luca", CancellationToken.None)).Outcome);
|
||||
|
||||
var check = await h.RunAsync(RecipeKind.ProfileCheck, marta.Id);
|
||||
|
||||
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
|
||||
Assert.AreEqual(PageUser.Engine, h.Turns.LastUser);
|
||||
Assert.IsFalse(h.Turns.SearchTouchedPage);
|
||||
}
|
||||
}
|
||||
@@ -82,9 +82,13 @@ public sealed class PermissiveGovernor : IGovernor, IBudgetView
|
||||
/// <summary>After <paramref name="grants"/> granted requests of <paramref name="kind"/>, the next ones are refused.</summary>
|
||||
public void Limit(ActionKind kind, int grants) => _limits[kind] = grants;
|
||||
|
||||
/// <summary>Runs at every request, before the answer (a test changes the page while the permit is asked).</summary>
|
||||
public Action<ActionKind>? OnRequest { get; set; }
|
||||
|
||||
public Task<Permit> RequestAsync(ActionKind kind, long? accountId, CancellationToken ct)
|
||||
{
|
||||
_requests.Enqueue((kind, accountId));
|
||||
OnRequest?.Invoke(kind);
|
||||
if (_limits.TryGetValue(kind, out var limit) && Granted(kind) >= limit)
|
||||
{
|
||||
return Task.FromResult(Permit.Deny(kind, accountId, DenialReason.HourlyBudgetReached, "Tetto orario raggiunto (prova)."));
|
||||
|
||||
@@ -12,6 +12,7 @@ using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.SitoDiProva;
|
||||
@@ -131,7 +132,16 @@ internal sealed class CollectionHarness : IAsyncDisposable
|
||||
/// <summary>The recorder of the diagnostic report, when asked for: what the page does goes to <see cref="Session"/>.</summary>
|
||||
public CollectionDiagnostics? Diagnostics { get; private set; }
|
||||
|
||||
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10, bool diagnostics = false)
|
||||
/// <summary>The turns of the page shared by the recipes and the profile search (issue #37).</summary>
|
||||
public PageTurns Turns { get; } = new();
|
||||
|
||||
/// <summary>The photos of the profile search, in memory.</summary>
|
||||
public SearchPhotoCache SearchPhotos { get; private set; } = null!;
|
||||
|
||||
/// <summary>The browser half of the profile search.</summary>
|
||||
public ProfileSearchRunner Search => Pipeline.Search!;
|
||||
|
||||
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10, bool diagnostics = false, ProfileSearchOptions? search = null)
|
||||
{
|
||||
var site = await SyntheticSite.StartAsync();
|
||||
var temp = new TempFolder("raccolta");
|
||||
@@ -143,8 +153,13 @@ internal sealed class CollectionHarness : IAsyncDisposable
|
||||
harness.Diagnostics = new CollectionDiagnostics(clock, () => harness.Session.SessionId);
|
||||
}
|
||||
|
||||
var searchOptions = search ?? new ProfileSearchOptions { AnswerTimeout = TimeSpan.FromSeconds(30) };
|
||||
harness.SearchPhotos = new SearchPhotoCache(clock, searchOptions);
|
||||
harness.Pipeline = await CollectionPipeline.StartAsync(new CollectionPipelineOptions
|
||||
{
|
||||
PageTurns = harness.Turns,
|
||||
SearchOptions = searchOptions,
|
||||
SearchPhotos = harness.SearchPhotos,
|
||||
Cdp = chromium.Cdp,
|
||||
Site = CollectionSite.TestSite(site.SiteHost, site.CdnHost),
|
||||
Storage = library.Db,
|
||||
|
||||
@@ -232,6 +232,28 @@ public sealed partial class SyntheticSiteSeedTests
|
||||
Assert.IsEmpty(hidden.Contents);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(30_000, CooperativeCancellation = true)]
|
||||
public async Task TheSearchOfTheSiteAnswersInTheShapeOfTheCleanedSample()
|
||||
{
|
||||
// Issue #37: the same keys as 000002-ricerca-profili, read by the same search vocabulary as Instagram's.
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
var answer = await ReadAsync(site, "/dati/cerca?testo=" + Uri.EscapeDataString("Marta"));
|
||||
Assert.IsNotNull(answer.Search);
|
||||
Assert.AreEqual("marta.prova", answer.Search.Hits[0].Profile.Username);
|
||||
Assert.AreEqual("1001", answer.Search.Hits[0].Profile.Id);
|
||||
Assert.IsNotNull(answer.Search.Hits[0].Profile.Picture, "a photo on the CDN of the site");
|
||||
Assert.IsEmpty(answer.Profiles, "search results are not followed profiles");
|
||||
|
||||
var all = await ReadAsync(site, "/dati/cerca?testo=prova");
|
||||
Assert.IsTrue(all.Search!.Hits.Count is > 1 and <= DataApi.SearchSize);
|
||||
Assert.IsFalse(all.Search.Hits.Any(h => h.Profile.Username == "alberto.prova"), "the connected account is not a result");
|
||||
CollectionAssert.AreEqual(Enumerable.Range(0, all.Search.Hits.Count).ToArray(), all.Search.Hits.Select(h => h.Position).ToArray());
|
||||
|
||||
var none = await ReadAsync(site, "/dati/cerca?testo=qqqzzz");
|
||||
Assert.HasCount(0, none.Search!.Hits);
|
||||
}
|
||||
|
||||
private async Task<ReadResult> ReadAsync(TestSite site, string pathAndQuery)
|
||||
{
|
||||
var result = Reader.Read(await site.GetDataAsync(pathAndQuery, TestContext.CancellationToken));
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Engine.Support;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>The profile search in the engine (issue #37): its own Governor category and the turns of the page.</summary>
|
||||
[TestClass]
|
||||
public sealed class ProfileSearchEngineTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task ASearchStepNeedsNoSessionAndIsLoggedWithoutOne()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
|
||||
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(permit.Granted, permit.Message);
|
||||
var logged = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddMinutes(-1), bed.Clock.Now.AddMinutes(1));
|
||||
Assert.HasCount(1, logged);
|
||||
Assert.AreEqual(ActionKind.ProfileSearch, logged[0].Category);
|
||||
Assert.IsNull(logged[0].SessionId);
|
||||
Assert.IsNull(logged[0].AccountId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task InsideASessionTheSearchIsNotAnActionOfTheSession()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
var session = await bed.BeginSessionAsync();
|
||||
|
||||
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
|
||||
|
||||
Assert.AreEqual(0, session.ActionCount, "a search step does not count toward the session's actions");
|
||||
var logged = await bed.Db.ActionLog.ListAsync(bed.Clock.Now.AddMinutes(-1), bed.Clock.Now.AddMinutes(1));
|
||||
Assert.IsNull(logged.Single().SessionId);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OutsideTheWindowTheSearchDoesNotOpenTheSite()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync(EngineTestBed.Local(2026, 10, 14, 3, 0));
|
||||
|
||||
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(DenialReason.OutsideActiveWindow, permit.Reason);
|
||||
StringAssert.Contains(permit.Message!, "Fuori dalla fascia oraria");
|
||||
StringAssert.Contains(permit.Message!, "profili che segui");
|
||||
Assert.IsNotNull(permit.RetryAfter);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryStopOfTheBreakerStopsTheSearch()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
|
||||
|
||||
var permit = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(DenialReason.BreakerOpen, permit.Reason);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AlbertoAtTheBrowserAndThePauseStopTheSearch()
|
||||
{
|
||||
var driving = true;
|
||||
await using var bed = await EngineTestBed.CreateAsync(userIsDriving: () => driving);
|
||||
|
||||
var atBrowser = await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None);
|
||||
Assert.AreEqual(DenialReason.UserIsDriving, atBrowser.Reason);
|
||||
StringAssert.Contains(atBrowser.Message!, "ricerca su Instagram");
|
||||
|
||||
driving = false;
|
||||
bed.Runtime.IsPaused = true;
|
||||
Assert.AreEqual(DenialReason.Paused, (await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Reason);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSearchHasItsOwnBudgetThatDoesNotTouchTheCollection()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
bed.Clock.AutoAdvance = true;
|
||||
var homeBefore = await bed.Governor.RemainingAsync(ActionKind.Home);
|
||||
var profileBefore = await bed.Governor.RemainingAsync(ActionKind.ProfileOpen);
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
|
||||
}
|
||||
|
||||
Assert.AreEqual(homeBefore, await bed.Governor.RemainingAsync(ActionKind.Home));
|
||||
Assert.AreEqual(profileBefore, await bed.Governor.RemainingAsync(ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(240 - 5, await bed.Governor.RemainingAsync(ActionKind.ProfileSearch), "«Prudente»: 240 search steps per hour");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSearchBudgetsAreWideButBelowTwiceRapido()
|
||||
{
|
||||
var prudent = CautionProfile.Prudent.Budgets[ActionKind.ProfileSearch];
|
||||
var balanced = CautionProfile.Balanced.Budgets[ActionKind.ProfileSearch];
|
||||
var fast = CautionProfile.Fast.Budgets[ActionKind.ProfileSearch];
|
||||
Assert.IsTrue(prudent.PerHour <= balanced.PerHour && balanced.PerHour <= fast.PerHour);
|
||||
Assert.IsTrue(prudent.PerDay <= balanced.PerDay && balanced.PerDay <= fast.PerDay);
|
||||
Assert.IsTrue(prudent.PerHour > CautionProfile.Fast.Budgets[ActionKind.ProfileOpen].PerHour, "wide: typing a name takes several steps");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HalvedBudgetsAfterAThrottleApplyToTheSearchToo()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Throttle, "http-429", null, bed.Clock.Now));
|
||||
bed.Clock.Advance(TimeSpan.FromHours(1));
|
||||
var budgets = bed.Governor.GetEffectiveBudgets(bed.Clock.Now);
|
||||
Assert.AreEqual(new Budget(120, 600), budgets.Budgets[ActionKind.ProfileSearch]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSearchKeepsItsOwnSpacingAndAGapFromTheEngineBothWays()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.BeginSessionAsync();
|
||||
var spacing = bed.Governor.SearchSpacing;
|
||||
|
||||
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
|
||||
var again = await bed.Governor.EvaluateAsync(ActionKind.ProfileSearch, null);
|
||||
Assert.AreEqual(DenialReason.MinimumSpacing, again.Reason, "the search's own spacing");
|
||||
|
||||
// The engine right after a search step waits the crossing gap, not its own 4 s spacing.
|
||||
var engine = await bed.Governor.EvaluateAsync(ActionKind.Home, null);
|
||||
Assert.AreEqual(DenialReason.MinimumSpacing, engine.Reason);
|
||||
Assert.AreEqual(bed.Clock.Now + spacing, engine.RetryAfter);
|
||||
|
||||
bed.Clock.Advance(spacing);
|
||||
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
|
||||
|
||||
// And the search right after an engine action waits the same gap.
|
||||
var search = await bed.Governor.EvaluateAsync(ActionKind.ProfileSearch, null);
|
||||
Assert.AreEqual(DenialReason.MinimumSpacing, search.Reason);
|
||||
Assert.AreEqual(bed.Clock.Now + spacing, search.RetryAfter);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEngineSpacingIgnoresTheSearchSteps()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.BeginSessionAsync();
|
||||
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.Home, null, CancellationToken.None)).Granted);
|
||||
var home = bed.Clock.Now;
|
||||
bed.Clock.Advance(TimeSpan.FromSeconds(2));
|
||||
Assert.IsTrue((await bed.Governor.RequestAsync(ActionKind.ProfileSearch, null, CancellationToken.None)).Granted);
|
||||
|
||||
Assert.AreEqual(home, await bed.Db.ActionLog.GetLastActionAtAsync(null), "the engine's last action is not a search step");
|
||||
Assert.AreEqual(bed.Clock.Now, await bed.Db.ActionLog.GetLastActionAtAsync(ActionKind.ProfileSearch));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- page turns
|
||||
|
||||
[TestMethod]
|
||||
public async Task TurnsAreGivenInOrderOneAtATime()
|
||||
{
|
||||
var turns = new PageTurns();
|
||||
var engine = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
|
||||
Assert.AreEqual(PageUser.Engine, turns.Holder);
|
||||
var searchTask = turns.TakeAsync(PageUser.Search, CancellationToken.None).AsTask();
|
||||
Assert.IsFalse(searchTask.IsCompleted);
|
||||
Assert.IsTrue(turns.IsWaiting(PageUser.Search));
|
||||
|
||||
await engine.DisposeAsync();
|
||||
var search = await searchTask.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
Assert.AreEqual(PageUser.Search, turns.Holder);
|
||||
search.Dispose();
|
||||
Assert.IsNull(turns.Holder);
|
||||
await turns.WhenFreeAsync(CancellationToken.None).WaitAsync(TimeSpan.FromSeconds(5));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEngineYieldsOnlyWhenTheSearchWaits()
|
||||
{
|
||||
var turns = new PageTurns();
|
||||
var engine = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
|
||||
Assert.IsFalse(await turns.YieldAsync(engine, CancellationToken.None), "nobody waits: no yield");
|
||||
|
||||
var searchTask = turns.TakeAsync(PageUser.Search, CancellationToken.None).AsTask();
|
||||
var yieldTask = turns.YieldAsync(engine, CancellationToken.None).AsTask();
|
||||
var search = await searchTask.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
Assert.IsFalse(yieldTask.IsCompleted, "the engine waits for the search step");
|
||||
await search.DisposeAsync();
|
||||
Assert.IsTrue(await yieldTask.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
Assert.AreSame(engine, turns.EngineTurn);
|
||||
engine.Dispose();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACancelledWaitLeavesTheQueue()
|
||||
{
|
||||
var turns = new PageTurns();
|
||||
var engine = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
|
||||
using var cts = new CancellationTokenSource();
|
||||
var waiting = turns.TakeAsync(PageUser.Search, cts.Token).AsTask();
|
||||
await cts.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(async () => await waiting);
|
||||
Assert.IsFalse(turns.IsWaiting(PageUser.Search));
|
||||
engine.Dispose();
|
||||
Assert.IsNull(turns.Holder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSearchMarksThePageAndARestClearsIt()
|
||||
{
|
||||
var turns = new PageTurns();
|
||||
var rested = 0;
|
||||
turns.Rested += () => rested++;
|
||||
turns.NoteOpened(PageUser.Search);
|
||||
Assert.AreEqual(PageUser.Search, turns.LastUser);
|
||||
Assert.IsTrue(turns.SearchTouchedPage);
|
||||
turns.NoteOpened(PageUser.Engine);
|
||||
Assert.IsFalse(turns.SearchTouchedPage);
|
||||
turns.NoteSearchUsedPage();
|
||||
Assert.IsTrue(turns.SearchTouchedPage);
|
||||
turns.NoteRested();
|
||||
Assert.IsNull(turns.LastUser);
|
||||
Assert.IsFalse(turns.SearchTouchedPage);
|
||||
Assert.AreEqual(1, rested);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// The service of the profile search (issue #37) over a scripted browser half: what the window sees while Alberto
|
||||
/// types, the remembered answers, the stops, and the rest page outside sessions.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ProfileSearchServiceTests
|
||||
{
|
||||
private const string Client = "0123456789abcdef";
|
||||
|
||||
private static readonly ProfileSearchOptions Fast = new()
|
||||
{
|
||||
EngineDebounce = TimeSpan.Zero,
|
||||
HoldWindow = TimeSpan.Zero,
|
||||
};
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheBrowserOnlyTheLocalSuggestionsWork()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
search.Start();
|
||||
|
||||
var view = search.Update(Client, "mario");
|
||||
|
||||
Assert.AreEqual(SearchState.Unavailable, view.State);
|
||||
StringAssert.Contains(view.Message!, "profili che segui");
|
||||
Assert.AreEqual(Client, view.Owner);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TextsThatAreNotTypedStayLocal()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
|
||||
Assert.AreEqual(SearchState.LocalOnly, search.Update(Client, "m").State);
|
||||
Assert.AreEqual(SearchState.LocalOnly, search.Update(Client, "anna\nbea").State);
|
||||
Assert.AreEqual(SearchState.Refused, search.Update(Client, "anna\tbea").State);
|
||||
Assert.AreEqual(SearchState.Idle, search.Update(Client, string.Empty).State);
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(0, runner.Steps, "nothing is typed on the site");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheAnswerOfTheSiteBecomesTheViewAndIsRemembered()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
|
||||
var first = search.Update(Client, "Mario");
|
||||
Assert.AreEqual(SearchState.Waiting, first.State);
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer of the site");
|
||||
var ready = search.Current;
|
||||
Assert.AreEqual("mario", ready.Text);
|
||||
CollectionAssert.AreEqual(new[] { "mario.rossi", "mario.bianchi" }, ready.Hits.Select(h => h.Username).ToArray());
|
||||
Assert.IsTrue(ready.Version > first.Version);
|
||||
Assert.AreEqual("1", search.Known("@Mario.Rossi")!.InstagramId, "the server keeps the identifier for adding");
|
||||
|
||||
search.Update(Client, "luca");
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Empty, "an empty answer");
|
||||
var steps = runner.Steps;
|
||||
|
||||
var again = search.Update(Client, "mario");
|
||||
Assert.AreEqual(SearchState.Ready, again.State, "a text seen a moment ago comes from Febe's memory");
|
||||
Assert.HasCount(2, again.Hits);
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(steps, runner.Steps, "no new step on the site");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnotherWindowTakesTheSearchOverAndOnlyTheOwnerEndsIt()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
search.Attach(new ScriptedSearch(bed.Services.PageTurns), null);
|
||||
search.Start();
|
||||
|
||||
search.Update(Client, "mario");
|
||||
var other = search.Update("fedcba9876543210", "luca");
|
||||
Assert.AreEqual("fedcba9876543210", other.Owner);
|
||||
search.End(Client);
|
||||
Assert.AreNotEqual(SearchState.Idle, search.Current.State, "the end of a window that no longer owns the search is ignored");
|
||||
search.End("fedcba9876543210");
|
||||
Assert.AreEqual(SearchState.Idle, search.Current.State);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AStopOfTheBreakerStopsTheSearchAndTheGovernorsRefusalIsShown()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
|
||||
runner.Next = new SearchStepResult(SearchOutcome.Denied, "mario", "Fuori dalla fascia oraria (prova).", Denial: Permit.Deny(ActionKind.ProfileSearch, null, DenialReason.OutsideActiveWindow, "Fuori dalla fascia oraria (prova)."));
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.OutsideWindow, "the refusal of the Governor");
|
||||
|
||||
await bed.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "challenge-url", null, bed.Clock.Now));
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Stopped, "the stop of the breaker");
|
||||
Assert.AreEqual(SearchState.Stopped, search.Update(Client, "anna").State, "no new step while the breaker is open");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OutsideSessionsThePageGoesToRestWhenTheDialogCloses()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer");
|
||||
var ended = bed.Clock.Now;
|
||||
search.End(Client);
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(0, runner.Rests, "not before the grace");
|
||||
|
||||
await TestWait.UntilAsync(
|
||||
() =>
|
||||
{
|
||||
bed.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
return runner.Rests == 1;
|
||||
},
|
||||
"the rest page");
|
||||
Assert.IsTrue(bed.Clock.Now - ended >= search.Options.EndGrace);
|
||||
Assert.IsNull(bed.Services.PageTurns.LastUser);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DuringASessionTheSearchDoesNotRestThePage()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.BeginSessionAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer");
|
||||
search.End(Client);
|
||||
bed.Clock.Advance(TimeSpan.FromMinutes(5));
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(0, runner.Rests, "the session rests the page when it ends");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSearchWaitsForTheEngineToGiveThePage()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
var engine = await bed.Services.PageTurns.TakeAsync(PageUser.Engine, CancellationToken.None);
|
||||
|
||||
var view = search.Update(Client, "mario");
|
||||
Assert.AreEqual(SearchState.Waiting, view.State);
|
||||
StringAssert.Contains(view.Message!, "raccolta");
|
||||
await TestWait.UntilAsync(() => bed.Services.PageTurns.IsWaiting(PageUser.Search), "the search in the queue");
|
||||
Assert.AreEqual(0, runner.Steps);
|
||||
|
||||
await engine.DisposeAsync();
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the step after the engine's");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASessionThatEndsWhileTheSearchHoldsThePageLeavesTheRestToTheSearch()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.BeginSessionAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var turns = bed.Services.PageTurns;
|
||||
|
||||
// Inside a session the page is the engine's: the real runner types on it without opening one.
|
||||
turns.NoteOpened(PageUser.Engine);
|
||||
var runner = new ScriptedSearch(turns) { OpensPage = false, Gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) };
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => turns.Holder == PageUser.Search && runner.Steps == 1, "the search holds the page");
|
||||
Assert.AreEqual(PageUser.Engine, turns.LastUser, "the search did not open the page");
|
||||
|
||||
// The session ends now (EngineHost.EndSessionAsync): its rest is left to the search.
|
||||
bed.Runtime.CurrentSession = null;
|
||||
Assert.IsNull(await turns.TakeForRestAsync(CancellationToken.None));
|
||||
Assert.IsTrue(turns.RestOwed);
|
||||
|
||||
runner.Gate.SetResult();
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the answer");
|
||||
search.End(Client);
|
||||
await TestWait.UntilAsync(
|
||||
() =>
|
||||
{
|
||||
bed.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
return runner.Rests == 1;
|
||||
},
|
||||
"the rest page, by the search");
|
||||
Assert.IsFalse(turns.RestOwed);
|
||||
Assert.IsNull(turns.LastUser);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASearchStillQueuedAtTheEndOfASessionRestsThePageEvenIfTheDialogCloses()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await bed.BeginSessionAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var turns = bed.Services.PageTurns;
|
||||
turns.NoteOpened(PageUser.Engine);
|
||||
var runner = new ScriptedSearch(turns) { OpensPage = false };
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
var recipe = await turns.TakeAsync(PageUser.Engine, CancellationToken.None);
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => turns.IsWaiting(PageUser.Search), "the search in the queue");
|
||||
|
||||
bed.Runtime.CurrentSession = null;
|
||||
Assert.IsNull(await turns.TakeForRestAsync(CancellationToken.None), "the search waits: the rest is left to it");
|
||||
search.End(Client);
|
||||
await recipe.DisposeAsync();
|
||||
await TestWait.UntilAsync(
|
||||
() =>
|
||||
{
|
||||
bed.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
return runner.Rests == 1;
|
||||
},
|
||||
"the rest page, although the search never typed");
|
||||
Assert.AreEqual(0, runner.Steps);
|
||||
Assert.IsFalse(turns.RestOwed);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithTheSearchAwayTheEngineRestsThePageItself()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
var turns = bed.Services.PageTurns;
|
||||
turns.NoteOpened(PageUser.Engine);
|
||||
|
||||
var turn = await turns.TakeForRestAsync(CancellationToken.None);
|
||||
|
||||
Assert.IsNotNull(turn);
|
||||
Assert.AreEqual(PageUser.Engine, turns.Holder);
|
||||
Assert.IsFalse(turns.RestOwed);
|
||||
await turn.DisposeAsync();
|
||||
Assert.IsNull(turns.Holder);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ThoseFoundLatelyAreRememberedAlsoAfterManyAnswers()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns) { Many = true };
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
|
||||
// 60 answers of 8 profiles each: more than the 400 profiles Febe remembers.
|
||||
for (var i = 0; i < 60; i++)
|
||||
{
|
||||
var text = $"p{i:D2}";
|
||||
search.Update(Client, text);
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready && search.Current.Text == text, "the answer for " + text);
|
||||
}
|
||||
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
Assert.IsNotNull(search.Known($"p59.{i}"), "every profile of the last answer");
|
||||
Assert.IsNotNull(search.Known($"p20.{i}"), "and of the ones before, up to 400 profiles");
|
||||
}
|
||||
|
||||
Assert.IsNull(search.Known("p00.0"), "the oldest go first");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSameTextWrittenAgainAfterAFailureIsTriedAgain()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
runner.Next = new SearchStepResult(SearchOutcome.FocusLost, "mario", "La casella «Cerca» di Instagram non è più attiva: riprova.");
|
||||
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Failed, "the failure");
|
||||
search.Update(Client, "mario ");
|
||||
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the second try");
|
||||
Assert.AreEqual(2, runner.Steps);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OutsideTheWindowTheSearchResumesByItselfWhenTheWindowOpens()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
var opens = bed.Clock.Now + TimeSpan.FromMinutes(30);
|
||||
runner.Next = new SearchStepResult(SearchOutcome.Denied, "mario", "Fuori dalla fascia oraria (prova).", Denial: Permit.Deny(ActionKind.ProfileSearch, null, DenialReason.OutsideActiveWindow, "Fuori dalla fascia oraria (prova).", opens));
|
||||
|
||||
search.Update(Client, "mario");
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.OutsideWindow, "the refusal");
|
||||
Assert.AreEqual(opens, search.Current.RetryAfter);
|
||||
bed.Clock.Advance(TimeSpan.FromMinutes(31));
|
||||
|
||||
await TestWait.UntilAsync(() => search.Current.State == SearchState.Ready, "the search once the window opens");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DuringThePauseNothingIsTypedAndRiprendiResumesTheSearch()
|
||||
{
|
||||
await using var bed = await EngineTestBed.CreateAsync();
|
||||
await using var search = new ProfileSearchService(bed.Services, Fast);
|
||||
var runner = new ScriptedSearch(bed.Services.PageTurns);
|
||||
search.Attach(runner, null);
|
||||
search.Start();
|
||||
bed.Runtime.IsPaused = true;
|
||||
|
||||
var paused = search.Update(Client, "mario");
|
||||
Assert.AreEqual(SearchState.Stopped, paused.State);
|
||||
StringAssert.Contains(paused.Message!, "pausa");
|
||||
await Task.Delay(100);
|
||||
Assert.AreEqual(0, runner.Steps);
|
||||
|
||||
bed.Runtime.IsPaused = false;
|
||||
await TestWait.UntilAsync(
|
||||
() =>
|
||||
{
|
||||
bed.Clock.Advance(TimeSpan.FromSeconds(1));
|
||||
return search.Current.State == SearchState.Ready;
|
||||
},
|
||||
"the search after «Riprendi»");
|
||||
}
|
||||
|
||||
/// <summary>A browser half that answers from a small list, at once.</summary>
|
||||
private sealed class ScriptedSearch(PageTurns turns) : IProfileSearchRunner
|
||||
{
|
||||
private static readonly (string Id, string Username)[] Profiles = [("1", "mario.rossi"), ("2", "mario.bianchi"), ("3", "anna.verdi")];
|
||||
private readonly ConcurrentQueue<SearchStepResult> _next = new();
|
||||
private int _steps;
|
||||
private int _rests;
|
||||
|
||||
/// <summary>Opens the page itself (outside sessions); false: types on the page the engine opened.</summary>
|
||||
public bool OpensPage { get; init; } = true;
|
||||
|
||||
/// <summary>When set, every step waits for it before answering (the search holds the page meanwhile).</summary>
|
||||
public TaskCompletionSource? Gate { get; init; }
|
||||
|
||||
/// <summary>Eight invented profiles «text.0» … «text.7» for every text.</summary>
|
||||
public bool Many { get; init; }
|
||||
|
||||
public string? NotConfiguredReason => null;
|
||||
|
||||
public double WaitMultiplier => 1;
|
||||
|
||||
public int Steps => Volatile.Read(ref _steps);
|
||||
|
||||
public int Rests => Volatile.Read(ref _rests);
|
||||
|
||||
public SearchStepResult Next
|
||||
{
|
||||
set => _next.Enqueue(value);
|
||||
}
|
||||
|
||||
public async Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _steps);
|
||||
if (OpensPage)
|
||||
{
|
||||
turns.NoteOpened(PageUser.Search);
|
||||
}
|
||||
else
|
||||
{
|
||||
turns.NoteSearchUsedPage();
|
||||
}
|
||||
|
||||
if (Gate is { } gate)
|
||||
{
|
||||
await gate.Task.WaitAsync(ct);
|
||||
}
|
||||
|
||||
if (_next.TryDequeue(out var scripted))
|
||||
{
|
||||
return scripted;
|
||||
}
|
||||
|
||||
var text = wanted();
|
||||
if (text is null)
|
||||
{
|
||||
return new SearchStepResult(SearchOutcome.Interrupted, string.Empty, null);
|
||||
}
|
||||
|
||||
List<SearchProfile> hits = Many
|
||||
? [.. Enumerable.Range(0, 8).Select(i => new SearchProfile(i, new ProfileInfo { Id = $"{text}-{i}", Username = $"{text}.{i}" }, false))]
|
||||
: [.. Profiles
|
||||
.Where(p => p.Username.Contains(text, StringComparison.Ordinal))
|
||||
.Select((p, i) => new SearchProfile(i, new ProfileInfo { Id = p.Id, Username = p.Username }, false))];
|
||||
var answer = new SearchAnswer(hits);
|
||||
return new SearchStepResult(hits.Count == 0 ? SearchOutcome.Empty : SearchOutcome.Ready, text, null, answer);
|
||||
}
|
||||
|
||||
public Task SettleAsync(CancellationToken ct) => Task.CompletedTask;
|
||||
|
||||
public Task RestAsync(CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _rests);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +260,51 @@ public sealed class DemoTests
|
||||
Assert.IsFalse(string.IsNullOrWhiteSpace(body.RootElement.Str("message")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSearchOfTheDemoFindsProfilesWithDrawnPhotos()
|
||||
{
|
||||
var origin = $"{Demo.Address.Scheme}://{Demo.Address.Authority}";
|
||||
async Task<JsonElement> PostAsync(string text, string scene = "normale")
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, $"/api/ricerca?scena={scene}")
|
||||
{
|
||||
Content = new StringContent(JsonSerializer.Serialize(new { client = "0123456789abcdef", text }), System.Text.Encoding.UTF8, "application/json"),
|
||||
};
|
||||
request.Headers.Add("Origin", origin);
|
||||
using var response = await Client.SendAsync(request);
|
||||
var body = await response.Content.ReadAsStringAsync();
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, body);
|
||||
return JsonDocument.Parse(body).RootElement.Clone();
|
||||
}
|
||||
|
||||
Assert.AreEqual("solo-locale", (await PostAsync("m")).Str("state"));
|
||||
Assert.AreEqual("cerca", (await PostAsync("marta")).Str("state"));
|
||||
JsonElement view = default;
|
||||
await TestWait.UntilAsync(
|
||||
async () =>
|
||||
{
|
||||
view = await GetAsync("/api/ricerca?client=0123456789abcdef");
|
||||
return view.Str("state") == "pronta" && view.Items("hits").All(h => h.Bool("photoReady"));
|
||||
},
|
||||
"the demo answer with its photos");
|
||||
var hits = view.Items("hits").ToList();
|
||||
Assert.IsTrue(hits.Count is > 0 and <= 6);
|
||||
Assert.IsTrue(hits.Any(h => h.Str("username") == "marta.demo"), "a demo account whose name holds the text");
|
||||
Assert.IsTrue(hits.Any(h => h.GetProperty("accountId").ValueKind == JsonValueKind.Number), "already in Febe");
|
||||
using var photo = await Client.GetAsync($"/api/ricerca/foto/{hits[0].Str("photo")}");
|
||||
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
|
||||
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
Assert.AreEqual("ferma", (await PostAsync("luca", "fermo")).Str("state"));
|
||||
Assert.AreEqual("non-pronto", (await PostAsync("luca", "scollegato")).Str("state"));
|
||||
|
||||
// «alvolante»: Alberto uses the browser; the engine says so and the search on Instagram is not possible.
|
||||
var driving = await PostAsync("luca", "alvolante");
|
||||
Assert.AreEqual("non-possibile", driving.Str("state"));
|
||||
StringAssert.Contains(driving.Str("message"), "Stai usando il browser");
|
||||
Assert.AreEqual("UserDriving", (await GetAsync("/api/engine?scena=alvolante")).GetProperty("snapshot").Str("mode"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheEditionCanBeChosenByAddress()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The «Aggiungi account» dialog with its one search box (issue #37), in a real headless Chromium against a test server
|
||||
/// with a scripted search: the profiles Alberto follows show at once, Instagram's results come after and merge without
|
||||
/// doubles, photos swap in when Febe has them, the keyboard adds a row, Esc closes only the list, pasting several names
|
||||
/// fills «Da aggiungere», and while Alberto drives the browser the dialog says so. The page only ever asks Febe.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[DoNotParallelize]
|
||||
public sealed class ProfileSearchInterfaceTests
|
||||
{
|
||||
private const string Box = "document.querySelector('.aggiungi input[role=combobox]')";
|
||||
|
||||
[TestMethod]
|
||||
public async Task FollowedProfilesShowAtOnceThenInstagramsResultsWithTheirPhotos()
|
||||
{
|
||||
var search = new ScriptedSearch();
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(search));
|
||||
await SeedAsync(server);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await OpenDialogAsync(ui, server);
|
||||
|
||||
// Instagram's answer waits: the followed profiles and the accounts in Febe are there before it.
|
||||
await ui.EvalAsync("window.__hold('/api/ricerca')");
|
||||
await TypeAsync(ui, "mar");
|
||||
await ui.WaitAsync("window.__started['/api/ricerca'] >= 1", "testo mandato a Febe");
|
||||
await ui.WaitAsync(Rows("@marta.rossi") + " === 1 && " + Rows("@mario.bianchi") + " === 1 && " + Rows("@marco.archivio") + " === 1", "suggerimenti locali subito");
|
||||
Assert.AreEqual(0, (await ui.EvalAsync("window.__done['/api/ricerca'] || 0")).GetInt32(), "the local rows came before the answer");
|
||||
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Cerco su Instagram");
|
||||
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Già in Febe");
|
||||
|
||||
await ui.EvalAsync("window.__release('/api/ricerca')");
|
||||
await ui.WaitForAsync(() => search.Texts.Contains("mar"), "testo arrivato al server");
|
||||
search.Answer(
|
||||
new SearchHit(0, "11", "marta.rossi", "Marta Rossi", false, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false),
|
||||
new SearchHit(1, "99", "mara.nuova", "Mara Nuova", true, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", false));
|
||||
await ui.WaitAsync(Rows("@mara.nuova") + " === 1", "risultato di Instagram");
|
||||
Assert.AreEqual(1, (await ui.EvalAsync(Rows("@marta.rossi"))).GetInt32(), "a followed profile found on Instagram is shown once");
|
||||
StringAssert.Contains(await TextAsync(ui, ".suggerimenti"), "Da Instagram");
|
||||
|
||||
// The photo replaces the initials once Febe has it.
|
||||
search.PhotosReady();
|
||||
await ui.WaitAsync(
|
||||
"[...document.querySelectorAll('.suggerimenti [role=option]')].some((r) => r.textContent.includes('@mara.nuova') && [...r.querySelectorAll('.av img')].some((i) => i.complete && i.naturalWidth > 0))",
|
||||
"foto del risultato");
|
||||
|
||||
// Keyboard: down to the Instagram result, Enter adds it; Esc closes the list and not the dialog.
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var current = await ui.EvalAsync($"(() => {{ const id = {Box}.getAttribute('aria-activedescendant'); return id ? document.getElementById(id).textContent : ''; }})()");
|
||||
if (current.GetString()!.Contains("@mara.nuova", StringComparison.Ordinal))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
await KeyAsync(ui, "ArrowDown");
|
||||
}
|
||||
|
||||
await KeyAsync(ui, "Enter");
|
||||
await ui.WaitAsync("document.querySelector('.aggiungi .scelti').textContent.includes('@mara.nuova')", "aggiunto a «Da aggiungere»");
|
||||
await KeyAsync(ui, "Escape");
|
||||
await ui.WaitAsync("document.querySelector('.suggerimenti').hidden && document.querySelector('.aggiungi') !== null", "solo l'elenco chiuso");
|
||||
|
||||
// The page asked only Febe: every resource (fetches and photos) on its own address, the search by POST and polls.
|
||||
Assert.IsTrue((await ui.EvalAsync("performance.getEntriesByType('resource').every((e) => new URL(e.name).origin === location.origin)")).GetBoolean());
|
||||
var asked = await ui.AskedAsync("/api/ricerca");
|
||||
Assert.IsTrue(asked.All(r => r == "POST /api/ricerca" || r.StartsWith("GET /api/ricerca?client=", StringComparison.Ordinal)), string.Join(", ", asked));
|
||||
|
||||
// Added with the identifier of the result the server holds.
|
||||
await ui.EvalAsync("document.querySelector('.aggiungi footer .btn.primo').click()");
|
||||
await ui.WaitAsync("document.querySelector('.aggiungi') === null", "dialogo chiuso dopo l'aggiunta");
|
||||
var added = await server.Db.Accounts.FindByUsernameAsync("mara.nuova");
|
||||
Assert.AreEqual("99", added?.InstagramId);
|
||||
await ui.WaitForAsync(() => search.Ended > 0, "ricerca chiusa con il dialogo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PastedNamesGoToTheListWhileATypedNameIsSearched()
|
||||
{
|
||||
var search = new ScriptedSearch();
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(search));
|
||||
await SeedAsync(server);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await OpenDialogAsync(ui, server);
|
||||
|
||||
await ui.EvalAsync($$"""
|
||||
(() => {
|
||||
const data = new DataTransfer();
|
||||
data.setData('text/plain', 'uno.nome\n@due.nome, instagram.com/tre.nome/\nmarta.rossi');
|
||||
{{Box}}.focus();
|
||||
{{Box}}.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
|
||||
return true;
|
||||
})()
|
||||
""");
|
||||
await ui.WaitAsync("['@uno.nome', '@due.nome', '@tre.nome', '@marta.rossi'].every((n) => document.querySelector('.aggiungi .scelti').textContent.includes(n))", "nomi incollati da aggiungere");
|
||||
Assert.AreEqual("Aggiungi 4 account", (await TextAsync(ui, ".aggiungi footer .btn.primo")).Trim());
|
||||
Assert.HasCount(1, await ui.AskedAsync("POST /api/accounts/parse"));
|
||||
Assert.IsEmpty(await ui.AskedAsync("POST /api/ricerca"), "several names are never searched on Instagram");
|
||||
|
||||
// A name with a space is a search, not two names.
|
||||
await TypeAsync(ui, "mario rossi");
|
||||
await ui.WaitForAsync(() => search.Texts.Contains("mario rossi"), "ricerca di «mario rossi»");
|
||||
Assert.IsFalse(search.Texts.Any(t => t.Contains('\n', StringComparison.Ordinal) || t.Contains(',', StringComparison.Ordinal)));
|
||||
|
||||
// The × takes a name away.
|
||||
await ui.EvalAsync("document.querySelector('.aggiungi .scelti .voce.scelto button').click()");
|
||||
await ui.WaitAsync("document.querySelector('.aggiungi footer .btn.primo').textContent.trim() === 'Aggiungi 3 account'", "un nome tolto");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WhileAlbertoUsesTheBrowserTheDialogSaysSoAndLocalSuggestionsWork()
|
||||
{
|
||||
var search = new ScriptedSearch { State = SearchState.NotPossible, Message = "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito." };
|
||||
await using var server = await WebTestServer.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton<IProfileSearch>(search);
|
||||
s.AddSingleton<IEngineMonitor>(new DrivingMonitor());
|
||||
});
|
||||
await SeedAsync(server);
|
||||
await using var ui = await UiBrowser.StartAsync();
|
||||
await ui.AddInitScriptAsync(UiBrowser.Requests);
|
||||
await OpenDialogAsync(ui, server);
|
||||
await ui.WaitAsync("document.querySelector('.stato') !== null && document.querySelector('.stato').textContent.includes('Stai usando il browser')", "motore al volante");
|
||||
|
||||
await ui.EvalAsync("window.__hold('/api/ricerca')");
|
||||
await TypeAsync(ui, "mar");
|
||||
await ui.WaitAsync(Rows("@marta.rossi") + " === 1", "suggerimenti locali");
|
||||
await ui.WaitAsync("document.querySelector('.suggerimenti').textContent.includes('Stai usando il browser di Febe')", "avviso subito, prima della risposta");
|
||||
await ui.EvalAsync("window.__release('/api/ricerca')");
|
||||
await ui.WaitAsync("window.__done['/api/ricerca'] >= 1", "risposta arrivata");
|
||||
await ui.WaitAsync($"document.querySelector('.suggerimenti .stato-remoto').textContent === {JsonSerializer.Serialize(search.Message)}", "messaggio del server");
|
||||
Assert.AreEqual(1, (await ui.EvalAsync(Rows("@marta.rossi"))).GetInt32());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ helpers
|
||||
|
||||
private static async Task SeedAsync(WebTestServer server)
|
||||
{
|
||||
await server.Db.Following.UpsertAsync(
|
||||
[
|
||||
new FollowingRecord { InstagramId = "11", Username = "marta.rossi", DisplayName = "Marta Rossi", IsPrivate = true, Position = 0, ReadAt = server.Clock.Now },
|
||||
new FollowingRecord { InstagramId = "12", Username = "mario.bianchi", DisplayName = "Mario Bianchi", Position = 1, ReadAt = server.Clock.Now },
|
||||
new FollowingRecord { InstagramId = "13", Username = "luca.verdi", DisplayName = "Luca Verdi", Position = 2, ReadAt = server.Clock.Now },
|
||||
]);
|
||||
await server.Db.Accounts.AddAsync(Make.Account("marco.archivio") with { InstagramId = "14", DisplayName = "Marco" });
|
||||
}
|
||||
|
||||
private static async Task OpenDialogAsync(UiBrowser ui, WebTestServer server)
|
||||
{
|
||||
await ui.OpenAsync(new Uri(server.Address, "/account?dialogo=aggiungi"));
|
||||
await ui.WaitAsync($"{Box} !== null && document.querySelector('.aggiungi .scelti-testa .btn.collegamento').textContent.includes('(3)')", "dialogo con l'elenco dei seguiti");
|
||||
}
|
||||
|
||||
private static Task TypeAsync(UiBrowser ui, string text) =>
|
||||
ui.EvalAsync($"(() => {{ const b = {Box}; b.focus(); b.value = {JsonSerializer.Serialize(text)}; b.dispatchEvent(new Event('input', {{ bubbles: true }})); return true; }})()");
|
||||
|
||||
private static Task KeyAsync(UiBrowser ui, string key) =>
|
||||
ui.EvalAsync($"{Box}.dispatchEvent(new KeyboardEvent('keydown', {{ key: {JsonSerializer.Serialize(key)}, bubbles: true, cancelable: true }}))");
|
||||
|
||||
private static string Rows(string text) =>
|
||||
$"[...document.querySelectorAll('.suggerimenti [role=option]')].filter((r) => r.querySelector('b') && r.querySelector('b').textContent === {JsonSerializer.Serialize(text)}).length";
|
||||
|
||||
private static async Task<string> TextAsync(UiBrowser ui, string selector) =>
|
||||
(await ui.EvalAsync($"document.querySelector({JsonSerializer.Serialize(selector)}).textContent")).GetString() ?? string.Empty;
|
||||
|
||||
/// <summary>A search the test drives: the state of the next texts, then the answer and the photos when it says.</summary>
|
||||
private sealed class ScriptedSearch : IProfileSearch
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private SearchView _view = SearchView.Initial;
|
||||
|
||||
public SearchState State { get; init; } = SearchState.Searching;
|
||||
|
||||
public string? Message { get; init; }
|
||||
|
||||
public List<string> Texts { get; } = [];
|
||||
|
||||
public int Ended { get; private set; }
|
||||
|
||||
public SearchView Current
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _view;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public SearchView Update(string client, string text)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Texts.Add(text);
|
||||
var query = SearchText.Normalize(text);
|
||||
_view = new SearchView(_view.Version + 1, client, query.Typed, query.Kind == SearchQueryKind.Typable ? State : SearchState.LocalOnly, Message, [], null);
|
||||
return _view;
|
||||
}
|
||||
}
|
||||
|
||||
public void Answer(params SearchHit[] hits)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_view = _view with { Version = _view.Version + 1, State = SearchState.Ready, Hits = hits };
|
||||
}
|
||||
}
|
||||
|
||||
public void PhotosReady()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_view = _view with { Version = _view.Version + 1, Hits = [.. _view.Hits.Select(h => h with { PhotoReady = true })] };
|
||||
}
|
||||
}
|
||||
|
||||
public void End(string client)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Ended++;
|
||||
}
|
||||
}
|
||||
|
||||
public SearchHit? Known(string username)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
return _view.Hits.FirstOrDefault(h => h.Username == username);
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
stream = _view.Hits.Any(h => h.PhotoReady && h.PhotoKey == key)
|
||||
? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 7, 32, 32))
|
||||
: null;
|
||||
return stream is not null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An engine while Alberto uses the browser.</summary>
|
||||
private sealed class DrivingMonitor : IEngineMonitor
|
||||
{
|
||||
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
|
||||
Task.FromResult(SnapshotParts.Build(new ManualClock(Make.T0), EngineMode.UserDriving, "Stai usando il browser", ["Il motore resta fermo finché non hai finito."], "Stai usando il browser", CautionProfile.Prudent));
|
||||
|
||||
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using Febe.Core.Collection.Search;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The API of the profile search (issue #37): what the window sends, what it reads, the photos from Febe's memory,
|
||||
/// the local suggestions with the accounts not followed, and adding a found profile with its identifier.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SearchApiTests
|
||||
{
|
||||
private const string Client = "0123456789abcdef";
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutTheEngineTheSearchSaysOnlyLocalSuggestionsWork()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
|
||||
var (status, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" });
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
Assert.AreEqual("non-pronto", view.Str("state"));
|
||||
Assert.IsTrue(view.Bool("mine"));
|
||||
StringAssert.Contains(view.Str("message"), "profili che segui");
|
||||
Assert.AreEqual("non-pronto", (await server.GetJsonAsync($"/api/ricerca?client={Client}")).Str("state"));
|
||||
Assert.IsFalse((await server.GetJsonAsync("/api/ricerca?client=fedcba9876543210")).Bool("mine"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BadRequestsAreRefused()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = "x", text = "mario" })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = new string('a', 61) })).Status);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/nonunachiave")).Status);
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/ricerca/foto/0123456789abcdef0123456789abcdef")).Status);
|
||||
|
||||
using var end = server.Request(HttpMethod.Post, "/api/ricerca/fine", new { client = Client });
|
||||
using var ended = await server.Client.SendAsync(end);
|
||||
Assert.AreEqual(HttpStatusCode.NoContent, ended.StatusCode);
|
||||
|
||||
// Without the Origin of the interface a page of another site cannot make Febe type.
|
||||
using var foreign = server.Request(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "mario" }, origin: "http://altro.esempio");
|
||||
using var refused = await server.Client.SendAsync(foreign);
|
||||
Assert.AreNotEqual(HttpStatusCode.OK, refused.StatusCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HitsAreEnrichedWithWhatFebeKnowsAndPhotosComeFromMemory()
|
||||
{
|
||||
var fake = new FixedSearch();
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(fake));
|
||||
var renamed = await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
|
||||
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
|
||||
|
||||
var (_, view) = await server.SendJsonAsync(HttpMethod.Post, "/api/ricerca", new { client = Client, text = "nome" });
|
||||
|
||||
Assert.AreEqual("pronta", view.Str("state"));
|
||||
var hits = view.Items("hits").ToList();
|
||||
Assert.HasCount(3, hits);
|
||||
Assert.AreEqual(renamed.Id, hits[0].Long("accountId"), "found by identifier under its new name");
|
||||
Assert.IsTrue(hits[1].Bool("followed"));
|
||||
Assert.AreEqual(System.Text.Json.JsonValueKind.Null, hits[2].GetProperty("accountId").ValueKind);
|
||||
Assert.IsTrue(hits[2].Bool("photoReady"));
|
||||
|
||||
using var photo = await server.Client.GetAsync($"/api/ricerca/foto/{hits[2].Str("photo")}");
|
||||
Assert.AreEqual(HttpStatusCode.OK, photo.StatusCode);
|
||||
Assert.AreEqual("image/jpeg", photo.Content.Headers.ContentType?.MediaType);
|
||||
Assert.IsTrue(photo.Headers.CacheControl?.NoStore == true, "the photos stay in Febe's memory, never on the disk of the viewer's browser");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLocalSuggestionsAlsoHoldTheAccountsNotFollowed()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var added = await server.Db.Accounts.AddAsync(Make.Account("aggiunto.per.nome"));
|
||||
await server.Db.Following.UpsertAsync([new FollowingRecord { InstagramId = "200", Username = "seguito.uno", ReadAt = server.Clock.Now }]);
|
||||
|
||||
var following = await server.GetJsonAsync("/api/following");
|
||||
|
||||
Assert.AreEqual(1, following.Int("total"), "the count is of the followed profiles");
|
||||
var profiles = following.Items("profiles").ToList();
|
||||
Assert.HasCount(2, profiles);
|
||||
Assert.IsTrue(profiles[0].Bool("followed"));
|
||||
Assert.AreEqual("200", profiles[0].Str("instagramId"));
|
||||
Assert.AreEqual("aggiunto.per.nome", profiles[1].Str("username"));
|
||||
Assert.IsFalse(profiles[1].Bool("followed"));
|
||||
Assert.AreEqual(added.Id, profiles[1].Long("accountId"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFoundProfileIsAddedWithItsIdentifierAndARenamedOneIsReported()
|
||||
{
|
||||
var fake = new FixedSearch();
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IProfileSearch>(fake));
|
||||
await server.Db.Accounts.AddAsync(Make.Account("vecchio.nome") with { InstagramId = "100" });
|
||||
|
||||
var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/accounts", new { usernames = new[] { "nuovo.nome", "senza.nome" }, start = "newOnly" });
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
Assert.AreEqual(1, result.Int("added"));
|
||||
StringAssert.Contains(result.Str("message"), "con un altro nome");
|
||||
var account = await server.Db.Accounts.FindByUsernameAsync("senza.nome");
|
||||
Assert.AreEqual("300", account!.InstagramId);
|
||||
Assert.AreEqual("Senza Nome", account.DisplayName);
|
||||
Assert.IsNull(await server.Db.Accounts.FindByUsernameAsync("nuovo.nome"), "the same profile is not added twice");
|
||||
}
|
||||
|
||||
/// <summary>A search that always shows the same three results.</summary>
|
||||
private sealed class FixedSearch : IProfileSearch
|
||||
{
|
||||
private const string PhotoKey = "abcdefabcdefabcdefabcdefabcdef12";
|
||||
|
||||
private static readonly SearchHit[] Hits =
|
||||
[
|
||||
new(0, "100", "nuovo.nome", "Nuovo Nome", false, null, false),
|
||||
new(1, "200", "seguito.uno", null, false, null, false),
|
||||
new(2, "300", "senza.nome", "Senza Nome", true, PhotoKey, true),
|
||||
];
|
||||
|
||||
public SearchView Current { get; private set; } = SearchView.Initial;
|
||||
|
||||
public SearchView Update(string client, string text) =>
|
||||
Current = new SearchView(Current.Version + 1, client, text, SearchState.Ready, null, Hits, null);
|
||||
|
||||
public void End(string client)
|
||||
{
|
||||
}
|
||||
|
||||
public SearchHit? Known(string username) => Hits.FirstOrDefault(h => h.Username == username);
|
||||
|
||||
public bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream)
|
||||
{
|
||||
stream = key == PhotoKey ? new MemoryStream(Febe.Web.Demo.DemoImages.Render(Febe.Web.Demo.DemoSubject.Portrait, 1, 32, 32)) : null;
|
||||
return stream is not null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ public sealed class SettingsApiTests
|
||||
Assert.AreEqual(20, rules.Int("maxWindowHours"));
|
||||
var current = limits.GetProperty("current");
|
||||
var kinds = current.Items("budgets").Select(b => b.Str("kind")).ToList();
|
||||
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage" }, kinds, "every row of the table of §7.5");
|
||||
CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage", "ProfileSearch" }, kinds, "every row of the table of §7.5");
|
||||
CollectionAssert.AreEqual(new[] { "1 ora", "6 ore", "24 ore" }, limits.Items("stops").Select(s => s.GetString()).ToArray());
|
||||
|
||||
object Body(Func<Dictionary<string, object?>, Dictionary<string, object?>> edit, string profile = "custom")
|
||||
|
||||
@@ -6,7 +6,8 @@ namespace Febe.SitoDiProva;
|
||||
/// <summary>
|
||||
/// The JSON the pages fetch, in the site's own synthetic format (LEGGIMI.md). It is what the response tap captures
|
||||
/// and what the readers of <c>lettori.prova.json</c> read. Keys are Italian and the shape is ours: it does not
|
||||
/// imitate Instagram.
|
||||
/// imitate Instagram. One exception: the answer of the search box (<see cref="Search"/>) has the shape of the cleaned
|
||||
/// Instagram sample, so the search of Febe is exercised end to end on the real format (issue #37).
|
||||
/// </summary>
|
||||
public sealed class DataApi(World world, CdnSigner signer, SiteControl control, Func<string> cdnBase, TimeProvider time)
|
||||
{
|
||||
@@ -168,6 +169,87 @@ public sealed class DataApi(World world, CdnSigner signer, SiteControl control,
|
||||
|
||||
public static string Cursor(int offset) => "c" + offset.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>
|
||||
/// The answer of the search box: up to <see cref="SearchSize"/> profiles whose name or display name contains the text
|
||||
/// (accents folded), the ones that start with it first. The shape and keys are those of the cleaned Instagram sample
|
||||
/// «ricerca-profili» (PolarisSearchBoxRefetchableQuery), and only keys present there: no «is_private», no
|
||||
/// «friendship_status», no echo of the text.
|
||||
/// </summary>
|
||||
public JsonObject Search(string text)
|
||||
{
|
||||
var wanted = Fold(text.Trim());
|
||||
var users = new JsonArray();
|
||||
if (wanted.Length > 0)
|
||||
{
|
||||
var found = world.Accounts
|
||||
.Where(a => !a.IsViewer)
|
||||
.Select(a => (Account: a, Name: Fold(a.Username), Display: Fold(a.DisplayName)))
|
||||
.Where(x => x.Name.Contains(wanted, StringComparison.Ordinal) || x.Display.Contains(wanted, StringComparison.Ordinal))
|
||||
.OrderBy(x => x.Name.StartsWith(wanted, StringComparison.Ordinal) || x.Display.StartsWith(wanted, StringComparison.Ordinal) ? 0 : 1)
|
||||
.ThenBy(x => x.Name, StringComparer.Ordinal)
|
||||
.Take(SearchSize)
|
||||
.ToList();
|
||||
var position = 0;
|
||||
foreach (var (account, _, _) in found)
|
||||
{
|
||||
var small = Version(account.PictureKey, 150, 150, video: false)["indirizzo"]!.GetValue<string>();
|
||||
var large = Version(account.PictureKey, 320, 320, video: false)["indirizzo"]!.GetValue<string>();
|
||||
users.Add(new JsonObject
|
||||
{
|
||||
["position"] = position++,
|
||||
["user"] = new JsonObject
|
||||
{
|
||||
["username"] = account.Username,
|
||||
["is_verified"] = false,
|
||||
["full_name"] = account.DisplayName,
|
||||
["pk"] = account.Id,
|
||||
["profile_pic_url"] = small,
|
||||
["hd_profile_pic_url_info"] = new JsonObject { ["url"] = large },
|
||||
["id"] = account.Id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["data"] = new JsonObject
|
||||
{
|
||||
["xdt_api__v1__fbsearch__topsearch_connection"] = new JsonObject
|
||||
{
|
||||
["hashtags"] = new JsonArray(),
|
||||
["places"] = new JsonArray(),
|
||||
["users"] = users,
|
||||
},
|
||||
},
|
||||
["extensions"] = new JsonObject { ["is_final"] = true },
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The «ricerche recenti» shown when the search panel opens: the site's own format, never read by Febe.</summary>
|
||||
public JsonObject RecentSearches(IReadOnlyList<string> names) => new()
|
||||
{
|
||||
["recenti"] = new JsonArray([.. names.Select(n => (JsonNode)new JsonObject { ["voce"] = n })]),
|
||||
};
|
||||
|
||||
/// <summary>Profiles in one search answer.</summary>
|
||||
public const int SearchSize = 8;
|
||||
|
||||
private static string Fold(string text)
|
||||
{
|
||||
var decomposed = text.ToLowerInvariant().Normalize(System.Text.NormalizationForm.FormD);
|
||||
var builder = new System.Text.StringBuilder(decomposed.Length);
|
||||
foreach (var c in decomposed)
|
||||
{
|
||||
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static JsonObject Page(int total, int offset, int size)
|
||||
{
|
||||
var more = offset + size < total;
|
||||
|
||||
@@ -53,6 +53,7 @@ storie attive di Marta è anche nella raccolta «Estate», con lo **stesso ident
|
||||
| `/post/{codice}/` | pagina di un post, con tutti i file |
|
||||
| `/verifica` | pagina di verifica, semplice testo |
|
||||
| `/sessione-scaduta` | pagina di sessione terminata, semplice testo (non è un modulo di accesso) |
|
||||
| pulsante «Cerca» (in ogni pagina) | apre il pannello di ricerca (bersagli `search-open` e `search-box`): a ogni tasto la pagina chiede `/dati/cerca` e mostra i profili trovati; con la casella vuota mostra le ricerche recenti. Premere Invio o aprire un risultato scrive una «ricerca recente» (`POST /dati/ricerche-recenti`), cosa che Febe non deve fare mai (issue #37) |
|
||||
| `/benvenuto` | quella che Febe apre come «pagina di accesso» del sito di prova (Collegamento): semplice testo, nessun modulo; la visita apre la sessione, come ogni pagina |
|
||||
|
||||
La mappa dei bersagli di queste pagine è `src/Febe.Core/Config/bersagli.prova.json` (copiata accanto al programma
|
||||
@@ -74,6 +75,8 @@ di Instagram (regola 10). Il vocabolario che lo descrive ai lettori è `src/Febe
|
||||
| `/dati/storie/{nome}` | `{ autore, storie: [contenuto], successivo }`: tutte le storie attive arrivano subito |
|
||||
| `/dati/evidenza/{id}` | `{ raccolta: { numero, titolo, autore, contenuti }, successiva }` |
|
||||
| `/dati/seguiti?dopo=` | `{ seguiti: [profilo], pagina }` |
|
||||
| `/dati/cerca?testo=` | **eccezione**: le chiavi del campione ripulito `000002-ricerca-profili` di Instagram (`data.xdt_api__v1__fbsearch__topsearch_connection.users[].user`), al più 8 profili, mai l'account collegato, prima quelli il cui nome comincia con il testo; maiuscole, accenti e spazi ai lati non contano |
|
||||
| `/dati/ricerche-recenti` | GET: le ricerche recenti; POST: ne scrive una (conta in `/_controllo/ricerca/recenti`) |
|
||||
|
||||
Oggetti:
|
||||
|
||||
@@ -116,6 +119,10 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
|
||||
| `/_controllo/rinomina?da=&a=` | un account cambia nome (stesso numero) |
|
||||
| `/_controllo/ritratto?nome=` | nuova foto del profilo |
|
||||
| `/_controllo/pubblica?nome=&tipo=foto\|video\|serie` | nuovo post in cima |
|
||||
| `/_controllo/ricerca/ritardo?ms=` | ritardo di ogni risposta della ricerca |
|
||||
| `/_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 |
|
||||
|
||||
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla prima visita di una pagina.
|
||||
@@ -88,7 +88,12 @@ internal static class Pages
|
||||
<html lang="it">
|
||||
<head><meta charset="utf-8"><title>{Html(title)} · Sito di prova</title><link rel="stylesheet" href="/risorse/sito.css"></head>
|
||||
<body data-pagina="{page}" {attributes}>
|
||||
<header class="sito"><strong>Sito di prova di Febe</strong><a href="/">Inizio</a><a href="/profilo/alberto.prova/seguiti/">Seguiti</a></header>
|
||||
<header class="sito"><strong>Sito di prova di Febe</strong><a href="/">Inizio</a><a href="/profilo/alberto.prova/seguiti/">Seguiti</a><button type="button" id="apri-cerca" aria-label="Cerca" aria-expanded="false">Cerca</button></header>
|
||||
<section id="pannello-cerca" class="pannello-cerca" hidden aria-label="Pannello di ricerca">
|
||||
<input type="search" id="casella-cerca" aria-label="Cerca" placeholder="Cerca" autocomplete="off">
|
||||
<ul id="recenti-cerca" aria-label="Ricerche recenti"></ul>
|
||||
<ul id="risultati-cerca" aria-label="Risultati"></ul>
|
||||
</section>
|
||||
<main>
|
||||
{main}
|
||||
</main>
|
||||
|
||||
@@ -37,3 +37,12 @@ body.visualizzatore { background: #111; color: #eee; overflow: hidden; }
|
||||
.chi { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 3; font-size: 13px; }
|
||||
button.zona-avanti { position: fixed; top: 60px; bottom: 60px; left: 50%; right: 80px; background: transparent; border: 0; z-index: 2; cursor: pointer; }
|
||||
button.chiudi { position: fixed; top: 16px; right: 24px; z-index: 4; background: #333; color: #eee; border: 1px solid #777; width: 44px; height: 44px; font-size: 20px; cursor: pointer; }
|
||||
|
||||
/* Pannello di ricerca (issue #37 di Febe). */
|
||||
header.sito button#apri-cerca { margin-left: auto; font: inherit; padding: 4px 10px; }
|
||||
.pannello-cerca { max-width: 640px; margin: 8px auto; padding: 8px; border: 1px solid #ccc; background: #fff; }
|
||||
.pannello-cerca input { width: 100%; font: inherit; padding: 6px; box-sizing: border-box; }
|
||||
.pannello-cerca ul { list-style: none; margin: 6px 0 0; padding: 0; }
|
||||
.pannello-cerca li a { display: flex; align-items: center; gap: 8px; padding: 4px 0; color: inherit; text-decoration: none; }
|
||||
.pannello-cerca li img { width: 32px; height: 32px; border-radius: 50%; }
|
||||
.pannello-cerca .esteso { color: #666; }
|
||||
@@ -234,6 +234,73 @@
|
||||
mostra();
|
||||
}
|
||||
|
||||
// Il pannello «Cerca» della colonna laterale, come la casella di ricerca di un sito vero (issue #37 di Febe). Le
|
||||
// risposte di /dati/cerca hanno la forma del campione ripulito di Instagram. Aprire il pannello chiede le ricerche
|
||||
// recenti; cliccare un risultato o premere Invio nella casella ne scrive una, come Instagram registra una ricerca:
|
||||
// Febe non deve mai farlo.
|
||||
function ricerca() {
|
||||
const bottone = document.getElementById('apri-cerca');
|
||||
const pannello = document.getElementById('pannello-cerca');
|
||||
const casella = document.getElementById('casella-cerca');
|
||||
const risultati = document.getElementById('risultati-cerca');
|
||||
const recenti = document.getElementById('recenti-cerca');
|
||||
if (!bottone || !pannello || !casella || !risultati || !recenti) return;
|
||||
const memoria = new Map();
|
||||
const conMemoria = corpo.dataset.memoriaRicerca === 'si';
|
||||
let attesa = null;
|
||||
|
||||
function registra() {
|
||||
return fetch('/dati/ricerche-recenti', { method: 'POST', credentials: 'same-origin' }).catch(() => {});
|
||||
}
|
||||
|
||||
function mostra(utenti) {
|
||||
risultati.replaceChildren(...utenti.map((voce) => {
|
||||
const u = voce.user || {};
|
||||
return el('li', {}, el('a', { href: '/profilo/' + encodeURIComponent(u.username || '') + '/' },
|
||||
u.profile_pic_url ? el('img', { src: u.profile_pic_url, alt: '' }) : null,
|
||||
el('span', { class: 'nome', testo: u.username || '' }),
|
||||
el('span', { class: 'esteso', testo: u.full_name || '' })));
|
||||
}));
|
||||
}
|
||||
|
||||
async function cerca(testo) {
|
||||
if (conMemoria && memoria.has(testo)) { mostra(memoria.get(testo)); return; }
|
||||
try {
|
||||
const dati = await carica('/dati/cerca?testo=' + encodeURIComponent(testo));
|
||||
const radice = (dati && dati.data && dati.data.xdt_api__v1__fbsearch__topsearch_connection) || {};
|
||||
const utenti = radice.users || [];
|
||||
memoria.set(testo, utenti);
|
||||
if (casella.value.trim() === testo) mostra(utenti);
|
||||
} catch { /* la pagina resta com'è */ }
|
||||
}
|
||||
|
||||
bottone.addEventListener('click', async () => {
|
||||
const apri = pannello.hidden;
|
||||
pannello.hidden = !apri;
|
||||
bottone.setAttribute('aria-expanded', apri ? 'true' : 'false');
|
||||
if (!apri) return;
|
||||
try {
|
||||
const dati = await carica('/dati/ricerche-recenti');
|
||||
recenti.replaceChildren(...((dati && dati.recenti) || []).map((r) => el('li', { testo: r.voce })));
|
||||
} catch { /* niente ricerche recenti */ }
|
||||
});
|
||||
casella.addEventListener('input', () => {
|
||||
clearTimeout(attesa);
|
||||
const testo = casella.value.trim();
|
||||
if (!testo) { risultati.replaceChildren(); return; }
|
||||
attesa = setTimeout(() => { cerca(testo); }, 200);
|
||||
});
|
||||
casella.addEventListener('keydown', (e) => { if (e.key === 'Enter') registra(); });
|
||||
risultati.addEventListener('click', (e) => {
|
||||
const collegamento = e.target.closest('a');
|
||||
if (!collegamento) return;
|
||||
e.preventDefault();
|
||||
registra().finally(() => { location.href = percorsoSicuro(collegamento.getAttribute('href')); });
|
||||
});
|
||||
}
|
||||
|
||||
ricerca();
|
||||
|
||||
const avvio = {
|
||||
inizio,
|
||||
profilo,
|
||||
|
||||
@@ -56,6 +56,25 @@ public sealed class SiteControl
|
||||
private int _cdnFiles;
|
||||
private int _cdnExpired;
|
||||
private int _cdnThrottled;
|
||||
private int _recentSearchWrites;
|
||||
|
||||
/// <summary>Extra wait before every answer of the search box (slow answers).</summary>
|
||||
public TimeSpan SearchDelay { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The search box answers shorter texts later than longer ones, so an earlier prefix arrives last (answers out of
|
||||
/// order, as on a slow network).
|
||||
/// </summary>
|
||||
public bool SearchDisorder { get; set; }
|
||||
|
||||
/// <summary>The page sends no request for a text it already searched, as a page with its own memory does.</summary>
|
||||
public bool SearchMemory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Number of «ricerche recenti» the page wrote: clicking a result or pressing Enter in the search box writes one,
|
||||
/// as Instagram registers a search. Febe must never cause one.
|
||||
/// </summary>
|
||||
public int RecentSearchWrites => _recentSearchWrites;
|
||||
|
||||
public StopMode Mode
|
||||
{
|
||||
@@ -91,6 +110,10 @@ public sealed class SiteControl
|
||||
StoryDuration = TimeSpan.FromSeconds(5);
|
||||
AddressLifetime = TimeSpan.FromHours(6);
|
||||
CdnTooManyRequests = false;
|
||||
SearchDelay = TimeSpan.Zero;
|
||||
SearchDisorder = false;
|
||||
SearchMemory = false;
|
||||
Interlocked.Exchange(ref _recentSearchWrites, 0);
|
||||
Interlocked.Exchange(ref _cdnFiles, 0);
|
||||
Interlocked.Exchange(ref _cdnExpired, 0);
|
||||
Interlocked.Exchange(ref _cdnThrottled, 0);
|
||||
@@ -116,6 +139,8 @@ public sealed class SiteControl
|
||||
|
||||
internal void OnCdnServed() => Interlocked.Increment(ref _cdnFiles);
|
||||
|
||||
internal void OnRecentSearchWritten() => Interlocked.Increment(ref _recentSearchWrites);
|
||||
|
||||
internal void OnCdnExpired() => Interlocked.Increment(ref _cdnExpired);
|
||||
|
||||
internal void OnCdnThrottled() => Interlocked.Increment(ref _cdnThrottled);
|
||||
|
||||
@@ -251,6 +251,11 @@ public sealed class TestSite : IAsyncDisposable
|
||||
}
|
||||
}
|
||||
|
||||
if (Control.SearchMemory)
|
||||
{
|
||||
html = html.Replace("<body ", "<body data-memoria-ricerca=\"si\" ", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
await HtmlAsync(context, status, html).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -279,6 +284,32 @@ public sealed class TestSite : IAsyncDisposable
|
||||
}
|
||||
|
||||
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
|
||||
if (segments is ["dati", "cerca"])
|
||||
{
|
||||
await SearchAsync(context, query["testo"].ToString()).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (segments is ["dati", "ricerche-recenti"])
|
||||
{
|
||||
if (HttpMethods.IsPost(context.Request.Method))
|
||||
{
|
||||
// The analogue of Instagram registering a search in the recent ones: a write Febe must never cause.
|
||||
Control.OnRecentSearchWritten();
|
||||
await JsonAsync(context, 200, new JsonObject { ["ok"] = true }).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
JsonObject recent;
|
||||
lock (World.Gate)
|
||||
{
|
||||
recent = Api.RecentSearches([.. World.Following.Take(3).Select(a => a.Username)]);
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, recent).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts };
|
||||
var after = query["dopo"].ToString();
|
||||
JsonObject? result;
|
||||
@@ -308,6 +339,29 @@ public sealed class TestSite : IAsyncDisposable
|
||||
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>
|
||||
private async Task SearchAsync(HttpContext context, string text)
|
||||
{
|
||||
var delay = Control.SearchDelay;
|
||||
if (Control.SearchDisorder)
|
||||
{
|
||||
delay += TimeSpan.FromMilliseconds(Math.Max(0, 8 - text.Trim().Length) * 250);
|
||||
}
|
||||
|
||||
if (delay > TimeSpan.Zero)
|
||||
{
|
||||
await Task.Delay(delay, context.RequestAborted).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
JsonObject answer;
|
||||
lock (World.Gate)
|
||||
{
|
||||
answer = Api.Search(text);
|
||||
}
|
||||
|
||||
await JsonAsync(context, 200, answer).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ServeCdnAsync(HttpContext context)
|
||||
{
|
||||
var path = context.Request.Path.Value ?? string.Empty;
|
||||
@@ -381,6 +435,18 @@ public sealed class TestSite : IAsyncDisposable
|
||||
case "durata-storie":
|
||||
Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "ricerca/ritardo":
|
||||
Control.SearchDelay = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
|
||||
break;
|
||||
case "ricerca/disordine":
|
||||
Control.SearchDisorder = q["valore"].ToString() is not ("no" or "false");
|
||||
break;
|
||||
case "ricerca/memoria":
|
||||
Control.SearchMemory = q["valore"].ToString() is not ("no" or "false");
|
||||
break;
|
||||
case "ricerca/recenti":
|
||||
answer["scritte"] = Control.RecentSearchWrites;
|
||||
break;
|
||||
case "cdn-troppe-richieste":
|
||||
Control.CdnTooManyRequests = q["valore"].ToString() is "si" or "sì" or "true";
|
||||
break;
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
// Chooses three followed profiles in the «Aggiungi account» dialog (mockup 04).
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
const boxes = [...document.querySelectorAll('.aggiungi .elenco input[type=checkbox]:not(:disabled)')];
|
||||
for (const i of [0, 2, 5]) if (boxes[i]) boxes[i].click();
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
return document.querySelector('.aggiungi footer .btn.primo')?.textContent;
|
||||
// The «Aggiungi account» dialog (mockup 04, issue #37): «gaia» typed in the search box, the list under it with the
|
||||
// followed profiles and the demo's Instagram results with their drawn photos, two of them added, the pointer on a row.
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
let box = null;
|
||||
for (let i = 0; i < 50 && !box; i++) {
|
||||
box = document.querySelector('.aggiungi input[role=combobox]');
|
||||
if (!box) await sleep(100);
|
||||
}
|
||||
// Wait for the list of followed profiles, so the local suggestions are there at once.
|
||||
for (let i = 0; i < 50 && !/\(\d+\)/.test(document.querySelector('.aggiungi .scelti-testa .btn.collegamento')?.textContent || ''); i++) await sleep(100);
|
||||
box.focus();
|
||||
box.value = 'gaia';
|
||||
box.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
const rows = () => [...document.querySelectorAll('.suggerimenti [role=option]:not(.azione)')];
|
||||
const ready = () => rows().length >= 6 && rows().every((r) => {
|
||||
const img = r.querySelector('.av img');
|
||||
return img && img.complete && img.naturalWidth > 0;
|
||||
});
|
||||
for (let i = 0; i < 80 && !ready(); i++) await sleep(100);
|
||||
for (const i of [0, 3]) rows()[i]?.querySelector('button')?.click();
|
||||
await sleep(300);
|
||||
const r = rows()[1].getBoundingClientRect();
|
||||
return { hover: [r.left + r.width / 2, r.top + r.height / 2] };
|
||||
Reference in new issue
Block a user