diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index cff7dbc..499004e 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -43,7 +43,7 @@ aggiorna docs/stato.md e docs/decisioni.md e fermati. **Messaggio per una schermata** ```text -Costruisci la schermata «Attività» seguendo docs/mockup/06-attivita.png e docs/mockup/13-foglio-di-stile.png (§10). +Costruisci la schermata «Account» seguendo docs/mockup/03-account.png e docs/mockup/13-foglio-di-stile.png (§10). Poi verificala come descritto in §10.7 ed elenca le differenze rimaste. ``` @@ -217,11 +217,11 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz - Mosaico di tutti gli elementi in ordine di pubblicazione, raggruppati per giorno (mockup 01). Filtri per tipo, account, periodo, provenienza (scaricati o importati). Ricerca per nome dell'account e testo della didascalia. - Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate. -- **«Raggruppa i post» o «Tutte le foto»** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): un interruttore a due voci nella riga di strumenti della Libreria e della vista dei contenuti della scheda account. «Raggruppa i post», il predefinito, è il mosaico di oggi: una tessera per elemento, con il numero dei file in alto a destra. «Tutte le foto» mette una tessera per file, video compresi, nello stesso ordine (data dell'elemento, poi posizione nella serie): utile quando un post ha più foto. In quel modo la tessera di un file di una serie dice la sua posizione («2/4»), il conteggio della riga del giorno conta i file, il visualizzatore si apre su quel file e le frecce vanno di file in file. La selezione è di file: «Copia in…» e «Fotogrammi…» lavorano sui file scelti; l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e la conferma lo dice («3 file scelti appartengono a 2 post: elimino i 2 post, 9 file»). La scelta si ricorda per pagina, una per la Libreria e una per le viste degli account, nel browser di chi guarda come il tema (memoria locale del browser, letta e scritta dentro un `try`); se manca o non si legge vale «Raggruppa i post». Filtri, ricerca e caricamento a finestre funzionano uguali nei due modi, anche con 200.000 elementi e i loro file. +- **«Raggruppa i post» o «Tutte le foto»** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): un interruttore a due voci nella riga di strumenti della Libreria e della vista dei contenuti della scheda account, tranne «In evidenza», disegnata per raccolta. «Raggruppa i post», il predefinito, è il mosaico di oggi: una tessera per elemento, con il numero dei file in alto a destra. «Tutte le foto» mette una tessera per file, video compresi, nello stesso ordine (data dell'elemento, poi posizione nella serie): utile quando un post ha più foto. Ha una tessera solo un file presente in libreria (scaricato o importato): un file ancora da scaricare, fallito o saltato no; con i filtri «Foto» e «Video» si vedono solo i file di quel tipo. In quel modo la tessera di un file di una serie dice la sua posizione («2/4»), il conteggio della riga del giorno conta i file, il visualizzatore si apre su quel file e le frecce vanno di file in file. La selezione è di file: «Copia in…» e «Fotogrammi…» lavorano sui file scelti; l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e la conferma lo dice («3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file.»). La scelta si ricorda per pagina, una per la Libreria e una per le viste degli account, **solo nel browser in cui si fa** (memoria locale del browser, chiavi `febe.mosaico.libreria` e `febe.mosaico.account`, lette e scritte dentro un `try`): a differenza del tema, che Febe conserva nelle sue impostazioni (Impostazioni → Generali, §10.5) e ogni browser ritrova, non passa a un altro browser né alla finestra di Febe per Windows. Se manca o non si legge vale «Raggruppa i post». Filtri, ricerca e caricamento a finestre funzionano uguali nei due modi, anche con 200.000 elementi e i loro file. Nell'interfaccia di programmazione (`src/Febe.Web/LEGGIMI.md`) `/api/library` e `/api/library/days` prendono `mode=grouped|files` (vuoto vale `grouped`; un altro valore dà 400); con `files` il cursore della finestra è `ms.elemento.posizione` (data in millisecondi, elemento, posizione del file nella serie; raggruppato è `ms.elemento`, e un cursore malformato dà 400), e `/api/library/days` ha il campo `files`, la somma dei file presenti in libreria dei giorni (con `grouped` è `null`), mentre i totali `entries` e `accounts` contano sempre elementi. - **File danneggiato o incompleto** (risposta di Alberto del 25 novembre 2026). Un'immagine troncata o rovinata, scaricata o importata (§3, §8.4), si rifiuta e lo dice: tessera neutra nel mosaico e «File danneggiato o incompleto» nel visualizzatore al posto dell'immagine, con le azioni sul file (mostra nella cartella o scarica, elimina) che restano. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Un HEIC che non si decodifica ha solo la tessera neutra, senza questa scritta (§3). - Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video, «È un video fermo?» a richiesta, e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· fotogramma»). - Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». Le copie esterne di un elemento eliminato restano dove sono (§4.10). -- Scheda dell'account con gli elementi divisi in Post, Storie, In evidenza, Taggati (mockup 12), con lo stesso interruttore «Raggruppa i post» / «Tutte le foto», le impostazioni e la cronologia dei controlli. +- Scheda dell'account con gli elementi divisi in Post, Storie, In evidenza, Taggati (mockup 12), con lo stesso interruttore «Raggruppa i post» / «Tutte le foto» in ogni linguetta tranne «In evidenza», le impostazioni e la cronologia dei controlli. - Selezione multipla per esportare (elenco CSV di §4.8; «Copia in…» e «Fotogrammi…» di §4.10) o eliminare. Dal traguardo 0.3.0 un filtro «Copie» (Tutti, Non ancora copiati, Copiati, Tolti o superati) in Libreria e nella scheda dell'account. ### 4.7 Percorsi e nomi dei file @@ -407,7 +407,7 @@ User agent e valori della pagina si leggono con **una sola** `Runtime.evaluate` La copia si fa solo da una pagina del sito che non sia un percorso di accesso o di verifica delle regole di arresto (§7.6), dentro i comandi del collegamento, dopo il controllo del cookie di sessione e prima del riposo. Si fa solo dentro il permesso di guida di Alberto («Accedi a Instagram», «Usa il browser»): Febe tiene il permesso e il turno della pagina per tutta la copia, a «Ho finito» come alla chiusura della finestra e alla fine del permesso, e in Docker lasciando la pagina del browser («Quando si copia»), e se il permesso finisce comunque prima del salvataggio la copia si butta. In ogni caso la copia dura al più 10 secondi; oltre, è un errore del browser e la copia si butta. -**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla. Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore, che rimette il browser a riposo. L'interfaccia lo dice al server con `cancel` e `pageLeft` (`IConnectionService.LeavePageAsync`); su Windows, dove il browser è una finestra a parte, lasciare la pagina rilascia solo il permesso tenuto da quella pagina e la finestra resta com'è. Una vista chiusa perché il browser si è fermato non conta come pagina lasciata. Dove la sessione si copia, solo il pulsante «Annulla» restituisce il browser senza copiare. Senza la raccolta `richieste` non c'è una sessione salvata: lasciare la pagina fa solo finire il permesso, senza copia; dove Febe non ha un collegamento che copi la sessione (la modalità dimostrativa, un avvio fermato da un problema di configurazione, il browser non disponibile) lasciare la pagina vale «Annulla». Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto (se non finisce, il permesso finisce senza copia, e il registro lo dice); poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata. +**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla (i 5 secondi di grazia sono una proposta, §16 domanda 20: Alberto ha detto solo che lasciare la pagina copia la sessione). Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore, che rimette il browser a riposo. L'interfaccia lo dice al server con `cancel` e `pageLeft` (`IConnectionService.LeavePageAsync`); su Windows, dove il browser è una finestra a parte, lasciare la pagina rilascia solo il permesso tenuto da quella pagina e la finestra resta com'è. Una vista chiusa perché il browser si è fermato non conta come pagina lasciata. Dove la sessione si copia, solo il pulsante «Annulla» restituisce il browser senza copiare. Senza la raccolta `richieste` non c'è una sessione salvata: lasciare la pagina fa solo finire il permesso, senza copia; dove Febe non ha un collegamento che copi la sessione (la modalità dimostrativa, un avvio fermato da un problema di configurazione, il browser non disponibile) lasciare la pagina vale «Annulla». Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto (se non finisce, il permesso finisce senza copia, e il registro lo dice); poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata. **Copia incompleta** (impostazione `sessione.copia-incompleta`, tappa S4b di #36, letta a ogni copia). Una copia a cui manca qualche valore o `doc_id` che un'operazione configurata manda segue l'opzione «Copia incompleta» della pagina Collegamento: **«Sostituisci comunque»** (predefinita), perché tenere una copia più vecchia potrebbe tenere i cookie di un altro accesso; oppure **«Tieni la copia completa di prima»**, che lascia la sessione salvata com'era se quella era completa, e lo dice («Ho tenuto la copia del 17 novembre: in quella nuova mancavano …»). Una copia completa sostituisce sempre. Il messaggio di «Ho finito» conta solo i valori e i `doc_id` che un'operazione configurata manda, e dice com'è secondo ciò che è successo. Se la copia nuova ha sostituito quella di prima («Sostituisci comunque», o «Tieni la copia completa di prima» quando quella di prima era già incompleta): le richieste che li usano non partono e, alla prima, Febe si ferma come disconnessione e chiede un nuovo accesso (mai un ritorno alle pagine) finché un nuovo «Ho finito» non li trova. Se Febe ha tenuto la copia completa di prima: la sessione salvata resta quella di quella data, le richieste continuano a usarla e nulla si ferma per quei valori; la copia nuova non si tiene. Dopo «Ho finito» il permesso di guida è finito: per rifare la copia Alberto riapre il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e preme di nuovo «Ho finito», ed è ciò che il messaggio di una copia rifiutata gli dice. Una copia rifiutata (pagina fuori dal sito, pagina di accesso o verifica, browser che non risponde, nessun user agent) la lascia com'era. Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico, come la farebbe Alberto. @@ -551,7 +551,7 @@ La pagina mostra versioni ridotte; gli indirizzi delle versioni migliori sono ne 3. Senza browser, la via principale dal 16 novembre 2026 (§6.0, tappa S5 di #36): `HttpClient` verso i soli domini del CDN presenti nell'indirizzo ricevuto, mai verso `instagram.com`, senza seguire rinvii fuori dal CDN. Senza cookie, con l'user agent della sessione salvata. Se il CDN la rifiuta, il file resta in attesa e l'interfaccia lo dice. 4. Il file si scrive con un nome temporaneo, se ne calcola lo SHA-256 e lo si rinomina. Uno scaricamento interrotto non lascia mai un file con il nome definitivo. 5. Se l'indirizzo è scaduto, il file torna «da scaricare». Il recupero passa dalla ricetta Post singolo, che rilegge il post e ne ottiene uno nuovo, dentro il suo tetto. Per le storie non c'è recupero dopo la scadenza. -6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. L'ordine della coda segue **«Cosa scaricare prima»** dell'account del file (§7.2; tappa D1 del traguardo 0.3.0): prima i file del tipo che viene primo, poi gli altri tipi nell'ordine, e dentro un tipo prima quelli che scadono prima, poi i più vecchi in attesa. Con l'ordine predefinito le storie, che scadono, vengono prima di tutto, come oggi; le foto del profilo vanno con i post. Finché D1 non è unita, le storie hanno la precedenza e il resto segue la scadenza e la data di scoperta. +6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. L'ordine della coda segue **«Cosa scaricare prima»** dell'account del file (§7.2; tappa D1 del traguardo 0.3.0): prima i file del tipo che viene primo, poi gli altri tipi nell'ordine, e dentro un tipo prima quelli che scadono prima, poi i più vecchi in attesa. Con l'ordine predefinito le storie, che scadono, vengono prima di tutto, come oggi; le foto del profilo vanno con i post. Come proposta (§16 domanda 21: Alberto ha chiesto solo l'ordine), un posto su otto è riservato al file che aspetta da più tempo in **tutta** la coda, di qualunque tipo: serve a garantire che nessun file aspetti per sempre (per esempio un tipo in fondo all'ordine quando il tetto dei dati finisce ogni giorno prima della coda), non è una quota per tipo. Un tipo trovato dopo un arretrato più vecchio di un altro tipo (taggati scoperti dopo migliaia di post dello storico) aspetta che quell'arretrato finisca; gli altri sette posti su otto seguono l'ordine. ### 6.6 Ipotesi da provare in M0 @@ -608,7 +608,7 @@ Nessuno può garantire che basti. Per questo il motore ha tre livelli indipenden - **Pavimento.** La pausa minima vale sempre, anche con molto lavoro arretrato. L'arretrato si smaltisce nei giorni, non stringendo le pause. - **Avvio.** Dopo l'avvio del programma la prima sessione parte dopo un'attesa casuale fra 2 e 10 minuti. Tetti e registro delle azioni sono su disco: un riavvio non azzera nulla. Un programma che riparte più volte non deve produrre più traffico di uno che resta acceso. - **Composizione.** Una sessione comincia di norma con il Giro dei seguiti, prosegue con le storie segnalate, poi con i controlli di profilo scaduti, infine con qualche pagina di storico. Non tutte le sessioni fanno tutto: circa una su tre si limita al giro e alle storie. L'ordine degli account è estratto a caso con pesi, mai lo stesso. Dalla tappa D1 l'ordine delle visite dopo il giro lo pesa anche «Cosa scaricare prima» (qui sotto). -- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine dei tipi, generale (Impostazioni → Limiti e comportamento, mockup 07) e per account (§4.4: «Come le impostazioni generali», il predefinito, oppure un ordine suo), che si cambia trascinando le righe o, da tastiera, con i pulsanti «Su» e «Giù». Ordine predefinito: storie, evidenza, post, reel, taggati (Alberto ha detto storie, post, reel, taggati; le raccolte in evidenza subito dopo le storie sono una proposta, §16 domanda 19). Un tipo è quello delle ricette di §6.3: storie per Storie di un account, evidenza per Raccolta in evidenza, post per Controllo del profilo e Storico (foto del profilo comprese), reel per Reel, taggati per Taggati. Pesa in due posti, dopo il Giro dei seguiti, che resta sempre primo: sulle **visite del motore nella sessione**, perché fra il lavoro già dovuto e permesso la visita successiva si estrae con il peso dell'account moltiplicato per il peso del tipo (tabella qui sotto), così il primo tipo viene di norma prima ma non sempre; e sulla **coda dei file** (§6.5), dove i file del primo tipo passano prima. Restano come sono il Governatore e i tetti (§7.4), le pause, la fascia, le frequenze (§7.3), la composizione casuale delle sessioni (circa una su tre si limita al giro e alle storie), l'umore e l'avvio graduale: l'ordine pesa le scelte dentro ciò che è già permesso, non aggiunge visite, non le anticipa e non le rende fisse; un tipo in cima senza nulla di dovuto non si visita. Un reel è un post: in coda conta come reel se Febe sa che lo è (trovato nella scheda Reel o segnato così nella risposta), altrimenti come post. Le storie scadono in 24 ore: spostarle in basso le espone a scadere prima di essere scaricate, e l'impostazione lo dice accanto all'elenco. +- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine dei tipi, generale (Impostazioni → Limiti e comportamento, mockup 07) e per account (§4.4: «Come le impostazioni generali», il predefinito, oppure un ordine suo), che si cambia trascinando le righe o, da tastiera, con i pulsanti «Su» e «Giù». Ordine predefinito: storie, evidenza, post, reel, taggati (Alberto ha detto storie, post, reel, taggati; le raccolte in evidenza subito dopo le storie sono una proposta, §16 domanda 19). Un tipo è quello delle ricette di §6.3: storie per Storie di un account, evidenza per Raccolta in evidenza, post per Controllo del profilo e Storico (foto del profilo comprese), reel per Reel, taggati per Taggati. Pesa in due posti, dopo il Giro dei seguiti, che resta sempre primo, e dopo le storie segnalate dalla barra delle storie, che restano davanti (lo storico viene dopo): sulle **visite del motore nella sessione**, perché fra il lavoro già dovuto e permesso la visita successiva si estrae con il peso dell'account moltiplicato per il peso del tipo (tabella qui sotto), così il primo tipo viene di norma prima ma non sempre; e sulla **coda dei file** (§6.5), dove i file del primo tipo passano prima. Restano come sono il Governatore e i tetti (§7.4), le pause, la fascia, le frequenze (§7.3), la composizione casuale delle sessioni (circa una su tre si limita al giro e alle storie), l'umore e l'avvio graduale: l'ordine pesa le scelte dentro ciò che è già permesso, non aggiunge visite, non le anticipa e non le rende fisse; un tipo in cima senza nulla di dovuto non si visita. Un reel è un post: in coda conta come reel se Febe sa che lo è, cioè se l'ha trovato percorrendo la scheda Reel del profilo o se la risposta lo dice (`product_type` «clips»), altrimenti come post. Il segno non si toglie più, un taggato non è mai un reel e i post salvati prima della tappa D1 restano post. Nella coda dei file un posto su otto va al file che aspetta da più tempo (§6.5; una proposta, §16 domanda 21). Le storie scadono in 24 ore: spostarle in basso le espone a scadere prima di essere scaricate, e l'impostazione lo dice accanto all'elenco. - **Umore della sessione.** Ogni sessione ha un fattore di velocità estratto una volta, che moltiplica tutte le attese: alcune sessioni sono svelte, altre lente. - **Riposo.** A fine sessione il browser torna alla pagina vuota (§6.1). - **Avvio graduale.** Se attivo (lo è per impostazione predefinita), nei primi giorni dopo il collegamento e dopo ogni verifica risolta i tetti partono dalla metà e risalgono in modo lineare fino al valore pieno, nel numero di giorni previsto dal profilo. @@ -621,7 +621,7 @@ Parametri delle estrazioni: | Umore della sessione | Log-normale, mediana 1, σ 0,2, tagliata fra 0,7 e 1,5 | | Scostamento del prossimo controllo | Intervallo × log-normale con mediana 1, σ 0,25, tagliata fra 0,6 e 1,8 | | Peso di un account nella scelta | (Alta 3, Normale 2, Bassa 1) × (1 + ritardo ÷ intervallo), con il rapporto limitato a 3 | -| Peso di un tipo nella scelta (tappa D1) | 16, 8, 4, 2, 1 secondo la posizione del tipo in «Cosa scaricare prima» dell'account (proposta, da tarare con la simulazione di §14.3) | +| Peso di un tipo nella scelta (tappa D1) | 16, 8, 4, 2, 1 secondo la posizione del tipo in «Cosa scaricare prima» dell'account (il suo o il generale); le visite senza account (giro, elenco dei seguiti) restano fuori. Valori costruiti come proposta: da confermare con Alberto e tarare con la simulazione di §14.3 | | Distanza minima fra due azioni contate | 4 secondi con il ritmo «naturale» | ### 7.3 Frequenze @@ -722,7 +722,9 @@ La **Dashboard** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto - la **cronologia dell'attività**, le ultime azioni con l'esito; le righe che hanno salvato qualcosa (post, storie, contenuti in evidenza, taggati, reel, foto del profilo) mostrano le **miniature** di ciò che è arrivato, piccole (le miniature di §8.4, caricate solo quando la riga è in vista, al più otto per riga con «+12» per il resto). Un clic su una miniatura apre un'**anteprima ingrandita** leggera, sopra la pagina e senza lasciarla: la foto o il video (che parte senza audio), account, tipo, data, frecce fra i file di quella riga, Esc che chiude; per il resto «Apri nella Libreria» (il visualizzatore di §4.6 su quell'elemento) e «Apri l'account» (la sua scheda). Un file danneggiato o incompleto mostra la tessera neutra (§4.6); - il pulsante «Diagnostica» nella riga del titolo (qui sotto) e, dalla tappa E2, la scheda «Esportazione» (§4.10). -Si aggiorna da sola con gli eventi del server, e con una cronologia lunga resta leggera: si caricano le ultime righe e le altre a richiesta. Gli orari futuri si scrivono sempre come «verso le», perché sono estratti a caso. Finché la tappa D1 non è unita la pagina resta «Attività» com'è oggi. +Si aggiorna da sola con gli eventi del server, e con una cronologia lunga resta leggera: si caricano le ultime righe e le altre a richiesta. Gli orari futuri si scrivono sempre come «verso le», perché sono estratti a caso. Anche in una finestra media resta compressa: l'anteprima tiene le sue proporzioni (al più 420 × 236) e si stringe restando accanto allo stato, con i tetti in due per due quando lo spazio manca, così a 1440 × 900 e a 860 × 900 anteprima, stato, tetti e l'inizio della cronologia stanno nel primo schermo; al telefono una colonna sola, con l'anteprima in alto. + +**Primo avvio.** Dalla tappa D1 `/` apre la Dashboard, non più la Libreria, quindi il benvenuto della Libreria vuota (§10.3) non è più la prima cosa che si vede. Finché non c'è nessun account la Dashboard mostra in cima, sopra il cruscotto, un riquadro «Benvenuto in Febe» compatto con gli stessi passi e pulsanti del benvenuto della Libreria: «Collegati a Instagram» e «Importa foto e video che hai già», con la nota sul rischio; se Febe è già collegato il primo pulsante è «Aggiungi account» (porta alla pagina Account) e la nota non c'è. Il riquadro sparisce da solo appena c'è un account (la Dashboard lo richiede con le altre informazioni, ogni minuto e a ogni cambio della libreria). Il benvenuto della Libreria resta com'è, per la Libreria vuota e non collegata. **Rapporto di diagnostica.** Dopo una prova dal vivo andata storta, Alberto deve poter mandare un solo file che spieghi perché, senza che nessuno apra i dati di altre persone. «Esporta il rapporto di diagnostica» (pulsante «Diagnostica» nella riga del titolo della Dashboard) scarica `febe-diagnostica-aaaa-mm-gg.json`: per ogni sessione del motore delle ultime due settimane, e per ogni giorno fuori dalle sessioni, le pagine aperte (il nome della pagina nella mappa del sito e la sua forma, mai l'indirizzo), le risposte ricevute per tipo con numero e misure, che cosa ne hanno fatto i lettori (riconosciute, vuote, ignorate, forma sconosciuta con la sola struttura delle chiavi, in cui resta solo una chiave fatta di parole di un elenco chiuso, preso dai campioni ripuliti e dai vocabolari dei lettori, mai di sole parole che sono anche nomi come «max_mark», e ogni altra diventa `#`; diventano `#` anche le voci di una mappa, cioè le chiavi sorelle con valori della stessa forma, salvo quelle che i lettori conoscono come `user` e `owner`), i bersagli cliccati, le ricette con l'esito (e, per un errore imprevisto, il solo tipo dell'eccezione), i segnali di §7.6 per livello e codice, i rifiuti del Governatore, i file messi in coda e scaricati (per un file fallito o da riprovare, la causa da un elenco chiuso, come `http-404`), e la causa di ogni fine (fine prevista, lavoro finito, tetti esauriti, ricetta che ferma, interruttore aperto, pausa, Alberto al browser, chiusura di Febe, errore). Mai cookie, password, gettoni, corpi delle risposte, nomi utente, didascalie, codici dei post, identificativi, indirizzi interi o testi liberi (messaggi, note, eccezioni): solo valori di elenchi chiusi, conteggi, misure, orari e forme degli indirizzi in cui ogni parte che non è una parola fissa del sito è `{numero}` o `{testo}`; per il CDN solo «cdn» e l'estensione del file. Le tracce finite stanno in `Dati/diagnostica/sessioni-aaaa-mm-gg.jsonl`, una riga per sessione, e si tengono 14 giorni (Febe cancella da sé solo i file più vecchi di quella cartella); le sessioni in corso entrano nel rapporto come «in corso». Una sessione scrive una riga «in corso» quando parte e poi al più ogni 5 minuti alla fine di una ricetta, così una chiusura brusca di Febe non la cancella; leggendo, di una sessione resta la riga finita, altrimenti l'ultima. I segnali entrano anche quando arrivano all'interruttore senza passare dal rilevatore (il cookie di sessione perso), e i file in attesa perché manca la connessione hanno la causa `connessione`. La testa del file dice che cosa sicuramente manca: righe del registro rovinate (`righeRovinate`), errori del registratore, scritture non riuscite comprese (`erroriRegistratore`), file di un giorno che non si sono potuti leggere (`fileIlleggibili`) e sessioni rimaste senza fine per una chiusura brusca (`sessioniSenzaFine`). Anche a zero il rapporto non promette di essere intero: gli ultimi minuti di una chiusura brusca, le ore fuori dalle sessioni del giorno e quello che supera i tetti (contato in `overflow`) possono mancare. Le forme delle pagine della mappa del sito passano per la stessa riduzione degli indirizzi, perché la mappa può venire dalla cartella dei dati. Con un problema di configurazione il motore non parte: l'indirizzo del rapporto risponde lo stesso, con gli elenchi vuoti. Una prova dimostra che nessun valore dei dati arriva nel file. @@ -768,8 +770,8 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc | Tabella | Contenuto | |---|---| | `setting` | Chiave e valore | -| `account` | Identificativo Instagram, nome utente, nome visibile, privato, seguito, è il mio, stato, tieni aggiornato, frequenza, tipi da scaricare, limiti, cartella, punto di ripresa dello storico, ultimi e prossimi controlli; dalla tappa D1 l'ordine di «Cosa scaricare prima» (vuoto: come le impostazioni generali, chiave `scaricamento.ordine` in `setting`) | -| `entry` | Un elemento: account, tipo (§4.3), identificativo e codice Instagram, data di pubblicazione in UTC, didascalia, autore (per i taggati), stato, provenienza, date di scoperta e di scaricamento; dalla tappa D1 se un post è un reel, quando Febe lo sa (§7.2) | +| `account` | Identificativo Instagram, nome utente, nome visibile, privato, seguito, è il mio, stato, tieni aggiornato, frequenza, tipi da scaricare, limiti, cartella, punto di ripresa dello storico, ultimi e prossimi controlli; l'ordine di «Cosa scaricare prima» (`download_order`, migrazione `0002` della tappa D1; vuoto: come le impostazioni generali, chiave `scaricamento.ordine` in `setting`) | +| `entry` | Un elemento: account, tipo (§4.3), identificativo e codice Instagram, data di pubblicazione in UTC, didascalia, autore (per i taggati), stato, provenienza, date di scoperta e di scaricamento; se un post è un reel, quando Febe lo sa (`is_reel`, migrazione `0002` della tappa D1, §7.2) | | `media` | Un file di un elemento: posizione, foto o video, dimensioni, durata, stato, percorso relativo, byte, SHA-256, impronta visiva, tentativi, ultimo errore | | `highlight`, `highlight_entry` | Raccolte in evidenza di un account e loro contenuti, in ordine. Un elemento può stare in più raccolte | | `duplicate_pair` | Coppie di file «doppione probabile» in attesa della decisione di Alberto, da importazione o da scaricamento | @@ -780,13 +782,13 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc | `event` | Cronologia leggibile per l'interfaccia | | `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura | | `import_run`, `import_file` | Importazioni e loro file, con esito e decisione | -| `export_destination`, `export_copy`, `export_run`, `export_item`, `video_analysis` | **Previste**, migrazione `0002` (tappa E1 del traguardo 0.3.0, §4.10): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito; rimuovere un account la disattiva, non la cancella), copie fatte per file, destinazione e account effettivo con il loro stato (§4.10), lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere), esito dell'analisi dei video fermi per SHA-256. Impostazioni in `setting` con chiavi `esportazione.*`; nessuna colonna nuova in `account` | +| `export_destination`, `export_copy`, `export_run`, `export_item`, `video_analysis` | **Previste**, migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito; rimuovere un account la disattiva, non la cancella), copie fatte per file, destinazione e account effettivo con il loro stato (§4.10), lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere), esito dell'analisi dei video fermi per SHA-256. Impostazioni in `setting` con chiavi `esportazione.*`; nessuna colonna nuova in `account` | Vincoli che contano: - `entry` è unico per (account, tipo, identificativo Instagram); `media` per (elemento, posizione). Lo stesso post può comparire sotto due account, come post di uno e come taggato di un altro: sono due elementi e due copie dei file. - Stati di un elemento: da scaricare, scaricato, parziale, fallito, saltato, importato, eliminato. «Eliminato» resta nel database senza file, perché non venga riscaricato (§4.6). -- Indici su (account, data di pubblicazione), SHA-256, impronta, stato. +- Indici su (account, data di pubblicazione), SHA-256, impronta, stato. Dalla migrazione `0002` (tappa D1) anche `ix_entry_discovered` su `entry (discovered_at)`, per le miniature della cronologia della Dashboard (§7.9), e `ix_media_entry_files` su `media (entry_id, state, kind)`, per i conteggi di «Tutte le foto» (§4.6). - Versione dello schema in `PRAGMA user_version`, migrazioni come file SQL numerati eseguiti all'avvio dentro una transazione. Un solo scrittore: le scritture passano da una coda. ### 8.4 Miniature e impronte @@ -886,12 +888,12 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f | `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. **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à, dalla tappa D1 Dashboard | Si aggiorna da sola con gli eventi del server. L'anteprima del browser è fatta di fotogrammi, non è un video; con la Dashboard è sempre visibile e si aggiorna a ogni fotogramma nuovo (§7.9). «Tutti i tetti» apre l'elenco completo di §7.4. **Superato dalla Dashboard** (qui sotto, «Schermate senza mockup») | +| `06-attivita.png` | Dashboard (nel mockup ancora «Attività», il nome di prima della tappa D1) | Si aggiorna da sola con gli eventi del server. L'anteprima del browser è fatta di fotogrammi, non è un video; con la Dashboard è sempre visibile e si aggiorna a ogni fotogramma nuovo (§7.9). «Tutti i tetti» apre l'elenco completo di §7.4. **Superato dalla Dashboard** (qui sotto, «Schermate della tappa D1») | | `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 | -| `11-attivita-fermo-tema-scuro.png` | Attività (dalla tappa D1 Dashboard) durante un arresto, tema scuro | La striscia rossa compare in cima a tutte le pagine, non solo qui. «Riprendi» si attiva dopo che Alberto ha usato il browser | +| `11-attivita-fermo-tema-scuro.png` | Dashboard (nel mockup ancora «Attività») durante un arresto, tema scuro | La striscia rossa compare in cima a tutte le pagine, non solo qui. «Riprendi» si attiva dopo che Alberto ha usato il browser | | `12-account-storie-tema-scuro.png` | Scheda account, storie, tema scuro | Griglia regolare con proporzione 9:16. Post, In evidenza e Taggati usano il mosaico della Libreria; le raccolte in evidenza sono intestazioni di gruppo | | `13-foglio-di-stile.png` | Colori, caratteri, misure, componenti | È il riferimento per qualunque elemento non disegnato altrove. Non è una schermata del programma | | `14-finestra-stretta-e-telefono.png` | Finestra stretta su Windows, telefono nel browser | Sotto i 1000 px la barra laterale si riduce alle icone; sotto i 560 px una colonna e navigazione in basso | @@ -900,14 +902,14 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f **«Apri il browser»**, dalla Dashboard e dalla striscia rossa: su Windows porta in primo piano la finestra del browser; in Docker apre la pagina «Browser», che è il mockup 10 senza la colonna dei passi, con la vista remota e il pulsante «Ho finito». Finché Alberto usa il browser il motore resta fermo. In Docker lasciare quella pagina o la vista remota di Collegamento, o chiuderne la scheda, mentre Alberto guida copia la sessione e restituisce la pagina al motore, come chiudere la finestra su Windows (§6.0, «Quando si copia»). -Schermate senza mockup, da comporre con gli elementi del foglio di stile: Scheda account → Cronologia (elenco dei controlli con esito); Impostazioni → Notifiche, Dati e copie di sicurezza, Informazioni; revisione dei doppioni dopo uno scaricamento (lo stesso confronto del mockup 09); primo avvio (la schermata vuota del mockup 13 con i due pulsanti); pagina di errore di configurazione (§8.2, §11). +Schermate senza mockup, da comporre con gli elementi del foglio di stile: Scheda account → Cronologia (elenco dei controlli con esito); Impostazioni → Notifiche, Dati e copie di sicurezza, Informazioni; revisione dei doppioni dopo uno scaricamento (lo stesso confronto del mockup 09); primo avvio (la schermata vuota del mockup 13 con i due pulsanti, nella Libreria vuota; nella Dashboard, che `/` apre per prima, lo stesso benvenuto in un riquadro compatto sopra il cruscotto finché non c'è nessun account, §7.9); pagina di errore di configurazione (§8.2, §11). Schermate dell'esportazione (§4.10, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 18 novembre 2026): Impostazioni → Esportazione (cartella generale, formati predefiniti delle copie, conversione della libreria, «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati, schema con anteprima, «Automatica» con la domanda «Solo i nuovi»; dal mockup 08 e dai dialoghi del 13); blocco «Copie esterne» nella scheda account → Impostazioni, sotto «Cartella» (mockup 05); finestra «Copia in…» con il riepilogo («312 file · 41 già copiati, saltati · 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…» e «Fotogrammi…» nella barra della selezione, il filtro «Copie» e il segno sulla tessera (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», «È un video fermo?» e le righe delle copie nel pannello File (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi e resoconto (mockup 06 e passo 2 del 09). Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`. Schermate della tappa D1 (issue #59, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 25 novembre 2026): -- **Dashboard** (§7.9), dai mockup 06 e 11 per anteprima, striscia, tetti, coda e cronologia, e dal mockup 01 per le miniature della cronologia (tessere piccole, raggio 3, i segni del mosaico: durata dei video, anello tratteggiato delle storie). La riga del titolo dice «Dashboard» con «Diagnostica» e i comandi del motore; sotto, in alto l'anteprima del browser con accanto che cosa sta facendo adesso e i quattro tetti, poi la striscia della giornata più bassa, poi in due colonne la cronologia con le miniature (la più larga) e la coda. L'anteprima ingrandita della cronologia è un dialogo leggero (mockup 13: raggio 14, ombra, Esc chiude), non il visualizzatore del mockup 02. Sotto i 1000 px una colonna sola, con l'anteprima sopra (mockup 14); -- **«Raggruppa i post» / «Tutte le foto»** (§4.6), dal mockup 01: un controllo a due voci nella riga di strumenti, accanto al cursore della grandezza delle tessere, nella Libreria e nella vista dei contenuti della scheda account (mockup 12); nel modo «Tutte le foto» il segno in alto a destra della tessera di una serie dice la posizione («2/4»); +- **Dashboard** (§7.9), dai mockup 06 e 11 per anteprima, striscia, tetti, coda e cronologia, e dal mockup 01 per le miniature della cronologia (tessere piccole, raggio 3, i segni del mosaico: durata dei video, anello tratteggiato delle storie). La riga del titolo dice «Dashboard» con «Diagnostica» e i comandi del motore; sotto, in alto l'anteprima del browser con accanto che cosa sta facendo adesso e i quattro tetti, poi la striscia della giornata più bassa, poi in due colonne la cronologia con le miniature (la più larga) e la coda. L'anteprima ingrandita della cronologia è un dialogo leggero (mockup 13: raggio 14, ombra, Esc chiude), non il visualizzatore del mockup 02. In una finestra media l'anteprima si stringe con le sue proporzioni e resta accanto allo stato, con i tetti in due per due; sotto i 1000 px cronologia e coda vanno in una colonna; al telefono, sotto i 560 px, una colonna sola con l'anteprima sopra (mockup 14). La voce della barra laterale ha un'icona sua, `layout-dashboard`, un tachimetro in un riquadro, ben diversa dai quattro quadrati della Libreria; +- **«Raggruppa i post» / «Tutte le foto»** (§4.6), dal mockup 01: un controllo a due voci nella riga di strumenti, accanto al cursore della grandezza delle tessere, nella Libreria e nella vista dei contenuti della scheda account (mockup 12), tranne «In evidenza»; nel modo «Tutte le foto» il segno in alto a destra della tessera di una serie dice la posizione («2/4»); - **«Cosa scaricare prima»** (§7.2), un blocco di Impostazioni → Limiti e comportamento (mockup 07) con l'elenco dei tipi da trascinare (maniglia, «Su» e «Giù» per la tastiera, la nota sulle storie che scadono) e lo stesso blocco nella scheda account → Impostazioni, sotto «Cosa scaricare» (mockup 05), con «Come le impostazioni generali» o «Un ordine suo». Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`, come per l'esportazione. @@ -955,7 +957,7 @@ Le immagini sono in scala 1,25 (1800 pixel di larghezza). Se non hai uno strumen ```text "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --user-data-dir=%TEMP%\febe-schermate --window-size=1440,900 --force-device-scale-factor=1.25 --virtual-time-budget=5000 - --screenshot=uscita.png "http://127.0.0.1:8480/attivita?scena=sessione" + --screenshot=uscita.png "http://127.0.0.1:8480/dashboard?scena=sessione" ``` Il divieto di modalità headless della regola 2 riguarda il browser che visita Instagram, non questi screenshot dell'interfaccia. @@ -1112,14 +1114,14 @@ Ogni tappa finisce con i controlli «Fatto quando» eseguiti e mostrati, `docs/s | **C4 Decodificatore H.265** | HEVC (ITU-T H.265) nei profili di §3: Main, Main 10, Main Still Picture e le estensioni di formato (RExt) della serie, che restano (risposta di Alberto del 25 novembre 2026, domanda 18 di §16), per fotogrammi, miniature e video fermi come H.264 | §3, §4.10, §8.4 | Tutti i flussi di ITU-T H.265.1 delle cartelle `HEVC_v1` e `RExt`, scaricati con il permesso di Alberto, in `tests/Febe.Tests/Media/H265/Conformita` con il `LEGGIMI.md` della fonte, uguali all'MD5 di riferimento, nessuno saltato | | **C5 Lettori ASF, FLV e MPEG-PS** | Durata, dimensioni, codec e data dove c'è, per ASF (WMV), FLV e MPEG-PS (ISO/IEC 13818-1), nell'analisi dell'importazione (§9.2) | §3, §9.2 | Prove su file costruiti dalle prove, troncati e rovinati compresi; nessun file reale | | **C6 Niente terzi nella CI e nell'interfaccia** | CI senza Node (passi di shell con git e curl verso l'API di Gitea), installatore di Windows scritto in casa al posto di NSIS, caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo gitleaks e Trivy nella CI, e Chromium con i suoi pacchetti Debian e Xvfb (regola 13) | §3, §10.1, §12, appendici B e C, `docs/processo.md` | Una verifica verde senza `node` nel contenitore delle prove né azioni che lo vogliano; installatore provato (§14.1); nessun file di Archivo o Lucide nel repository; schermate riconfrontate con i mockup (§10.7), con le differenze dei caratteri scritte; NSIS e Node tolti da `docs/processo.md` e dalla regola 13 | -| **E1 Schema** | Migrazione `0002` con le tabelle di §8.3, archivi e impostazioni `esportazione.*`. Nessun cambio di comportamento | §8.3, §4.10 | Database della versione 1 aggiornato con `foreign_key_check` pulito; database più nuovo rifiutato | -| **E2 Copie esterne** | Destinazioni (generale e per account), controlli delle cartelle, `/esporta` in Docker, «Copia in…» degli originali, adozione, stati «Tolto» e «Superato», «già copiato» su tessere, visualizzatore, scheda account e filtro «Copie», scheda «Esportazione» della Dashboard (di Attività, se D1 non è ancora unita) | §4.10, §10.3, §11, §12, §13.2 | Prove: cartelle rifiutate, radice mai creata, `/esporta` non montata quindi nulla scritto, nessuna sovrascrittura, adozione, filtro «Copie» con 200.000 elementi entro 250 ms. Schermate confrontate (§10.7) e guida dell'esportazione | +| **E1 Schema** | Migrazione `0003` (la `0002` è di D1) con le tabelle di §8.3, archivi e impostazioni `esportazione.*`. Nessun cambio di comportamento | §8.3, §4.10 | Database della versione 1 aggiornato con `foreign_key_check` pulito; database più nuovo rifiutato | +| **E2 Copie esterne** | Destinazioni (generale e per account), controlli delle cartelle, `/esporta` in Docker, «Copia in…» degli originali, adozione, stati «Tolto» e «Superato», «già copiato» su tessere, visualizzatore, scheda account e filtro «Copie», scheda «Esportazione» della Dashboard | §4.10, §10.3, §11, §12, §13.2 | Prove: cartelle rifiutate, radice mai creata, `/esporta` non montata quindi nulla scritto, nessuna sovrascrittura, adozione, filtro «Copie» con 200.000 elementi entro 250 ms. Schermate confrontate (§10.7) e guida dell'esportazione | | **E3 Formati e fotogrammi** | Conversione delle copie e della libreria (il convertito si aggiunge, l'originale resta), metadati copiati, rimuxaggio, fotogrammi a richiesta, zip | §4.10, §3 | Prove: JPG → JPG è una copia, PNG con trasparenza → JPG, WEBP senza perdita con i pixel identici all'originale, metadati presenti nel convertito, MOV → MP4, fotogramma a un istante, ogni k secondi, N; libreria con originale intatto | | **E4 Video fermi** | Analisi a richiesta, `video_analysis`, «Salva il fotogramma» | §4.10 | Prove su video costruiti dalle prove (immagine fissa con audio, dissolvenza dal nero, movimento, clip brevissima, tutto nero, rotazione); soglie in `docs/decisioni.md` | | **E5 Esportazione automatica** | Destinazioni automatiche, domanda «Solo i nuovi», giro orario, «Riconosci le copie già presenti» | §4.10 | Prove: «Tolto» e «Superato» non si ricopiano, destinazione irraggiungibile in pausa e poi ripresa, nessuna copia durante una sessione del motore; guida completa | -| **D1 Dashboard e ordine** | Issue #59 (decisione di Alberto del 25 novembre 2026). «Cosa scaricare prima», generale e per account, con il peso dei tipi sulle visite dopo il Giro dei seguiti e l'ordine della coda dei file (§7.2, §6.5, §4.4, §8.3); la Dashboard al posto di Attività: prima voce della barra laterale, pagina iniziale (`/`, `/attivita` e la finestra di Windows portano a `/dashboard`), compatta, con l'anteprima del browser sempre visibile e le miniature nella cronologia con l'anteprima ingrandita (§7.9, §10.2); «Raggruppa i post» / «Tutte le foto» nella Libreria e nella scheda account (§4.6) | §4.4, §4.6, §6.5, §7.2, §7.9, §10.2, §10.3, §14.3 | Prove del motore con orologio virtuale e seme fisso: ordine predefinito storie, evidenza, post, reel, taggati; con un altro ordine la prima visita dopo il giro è più spesso del primo tipo, ma non sempre, e il giro resta primo; un tipo senza lavoro dovuto non si visita; coda dei file nell'ordine dell'account; simulazione di 30 giorni per i tre profili senza superamenti dei tetti, con pause, frequenze e composizione delle sessioni invariate. Interfaccia: `/` e `/attivita` aprono la Dashboard; «Tutte le foto» con 200.000 elementi nei tempi della prova di scala; la scelta del modo si ricorda per pagina e senza memoria del browser torna «Raggruppa i post». Schermate composte confrontate (§10.7) con le differenze in `docs/schermate/differenze.md`; guida aggiornata | +| **D1 Dashboard e ordine** | Issue #59 (decisione di Alberto del 25 novembre 2026). «Cosa scaricare prima», generale e per account, con il peso dei tipi sulle visite dopo il Giro dei seguiti e l'ordine della coda dei file (§7.2, §6.5, §4.4, §8.3); la Dashboard al posto di Attività: prima voce della barra laterale, pagina iniziale (`/`, `/attivita` e la finestra di Windows portano a `/dashboard`), compatta, con l'anteprima del browser sempre visibile e le miniature nella cronologia con l'anteprima ingrandita (§7.9, §10.2); «Raggruppa i post» / «Tutte le foto» nella Libreria e nella scheda account (§4.6); migrazione `0002` con `account.download_order`, `entry.is_reel`, `ix_entry_discovered` e `ix_media_entry_files` (§8.3) | §4.4, §4.6, §6.5, §7.2, §7.9, §10.2, §10.3, §14.3 | Prove del motore con orologio virtuale e seme fisso: ordine predefinito storie, evidenza, post, reel, taggati; con un altro ordine la prima visita dopo il giro è più spesso del primo tipo, ma non sempre, e il giro resta primo; un tipo senza lavoro dovuto non si visita; coda dei file nell'ordine dell'account; simulazione di 30 giorni per i tre profili senza superamenti dei tetti, con pause, frequenze e composizione delle sessioni invariate. Interfaccia: `/` e `/attivita` aprono la Dashboard; «Tutte le foto» con 200.000 elementi nei tempi della prova di scala; la scelta del modo si ricorda per pagina e senza memoria del browser torna «Raggruppa i post». Schermate composte confrontate (§10.7) con le differenze in `docs/schermate/differenze.md`; guida aggiornata | -Dipendenze: C1 → C2 → C3 → C4; C5 dopo C2; C6 indipendente dalle altre; D1 indipendente dalle altre (se E2 arriva prima, la sua scheda nasce nella vecchia Attività e passa alla Dashboard con D1); E1 → E2 → E3 → E4, con E3 dopo C1 per le foto e dopo C2 per il rimuxaggio, i fotogrammi dopo C3 (e dopo C4 per HEVC), E4 dopo C3; E5 dopo E2. La migrazione `0002` si concorda con le tappe di #36 che toccano lo schema; D1 ha una migrazione sua, numerata dopo quelle già unite. +Dipendenze: C1 → C2 → C3 → C4; C5 dopo C2; C6 indipendente dalle altre; D1 indipendente dalle altre (costruita prima di E2, la cui scheda nasce quindi nella Dashboard); E1 → E2 → E3 → E4, con E3 dopo C1 per le foto e dopo C2 per il rimuxaggio, i fotogrammi dopo C3 (e dopo C4 per HEVC), E4 dopo C3; E5 dopo E2. La migrazione `0002` è di D1 (la prima dopo quelle già unite); E1 prende la `0003` e si concorda con le tappe di #36 che toccano lo schema. `docs/stato.md` è il filo fra le sessioni: che cosa è fatto, che cosa è in corso, che cosa è stato rimandato e perché. `docs/decisioni.md` raccoglie ogni scelta tecnica presa strada facendo, con data e motivo. @@ -1162,6 +1164,8 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 17 | **Risposta di Alberto del 18 novembre 2026: si tolgono** (regola 13, §3, §15 tappa C6). Domanda di allora: componenti in uso oltre a quelli ammessi dalla regola 13 (Xvfb e gli altri pacchetti Debian di §11, il carattere Archivo e le icone Lucide come file, NSIS e Node nella CI): restano come eccezioni per nome o si tolgono? | E0 | Risposta: escono anche questi; installatore senza NSIS (scritto in casa), CI senza Node (passi di shell con git e curl verso l'API di Gitea), caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo Xvfb e i pacchetti Debian che servono a Chromium, e gitleaks e Trivy nella sola CI. Inoltre: lo stesso post in due account si copia con «Una copia per account» come predefinito (§4.10) | | 18 | **Risposta di Alberto del 25 novembre 2026: le estensioni di formato (RExt) restano** (§3, §15 tappa C4). Domanda di allora: decodificatore H.265, oltre a Main, Main 10 e Main Still Picture, quali profili? Estensioni di formato (4:2:2, 4:4:4, 12 e 16 bit, senza perdita), scalabile (SHVC), multivista (MV-HEVC), 3D, contenuti dello schermo (SCC) | C4, prima di cominciare | Risposta: tutti i profili della serie di ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`): Main, Main 10, Main Still Picture e RExt fino a 12 bit. Ciò che non ha flussi in quella serie (precisione estesa a 16 bit, SHVC, MV-HEVC, 3D, SCC) dice «Fotogramma non disponibile per questo video». Inoltre, lo stesso giorno: in Docker lasciare la pagina del browser copia la sessione (§6.0); nell'immagine Docker `fonts-noto-color-emoji` resta e `fonts-liberation` è uscito (§11); le immagini troncate si rifiutano con «File danneggiato o incompleto», senza impronta, e restano in libreria (§8.4) | | 19 | «Cosa scaricare prima»: le raccolte in evidenza vanno subito dopo le storie? Alberto ha detto storie, post, reel, taggati, senza nominarle | D1, prima di cominciare | Sì: storie, evidenza, post, reel, taggati, perché sono storie anche loro; si possono comunque spostare trascinandole | +| 20 | In Docker lasciare la pagina del browser copia la sessione (risposta del 25 novembre, domanda 18) quando per 5 secondi non si riapre un'altra vista remota, così una pagina ricaricata non è lasciata: vanno bene i 5 secondi di grazia? Alberto non ha detto una durata | S4b, prima della prova dal vivo in Docker | Sì, 5 secondi: bastano a una pagina che si ricarica e non trattengono il motore | +| 21 | «Cosa scaricare prima», coda dei file (§6.5): basta riservare un posto su otto al file che aspetta da più tempo in tutta la coda, così nessun file aspetta per sempre, o serve un minimo per tipo? Alberto ha chiesto solo l'ordine | D1, prima di unire | Il posto su otto, senza quote per tipo: un tipo trovato dopo un arretrato più vecchio aspetta che quell'arretrato finisca, ma nessun file aspetta per sempre | --- @@ -1495,15 +1499,15 @@ Marchio: quadrato arrotondato nel colore d'accento con un anello e un punto, cio ``` -Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con cui sono disegnati i mockup. **Con C6 Lucide è uscito** (regola 13, decisione di Alberto del 18 novembre 2026): ogni icona è ridisegnata in casa (`src/Febe.Web/wwwroot/icone`), SVG in linea su una griglia di 24, tratto 1,75, con lo stesso nome d'uso, così l'interfaccia non ha cambiato i suoi riferimenti. Elenco di partenza: +Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con cui sono disegnati i mockup. **Con C6 Lucide è uscito** (regola 13, decisione di Alberto del 18 novembre 2026): ogni icona è ridisegnata in casa (`src/Febe.Web/wwwroot/icone`), SVG in linea su una griglia di 24, tratto 1,75, con lo stesso nome d'uso, così l'interfaccia non ha cambiato i suoi riferimenti. Con la tappa D1 la voce Dashboard della barra laterale ha `layout-dashboard`, disegnata in casa come un tachimetro in un riquadro perché non si confonda con i quattro quadrati di `layout-grid` della Libreria; `activity`, l'icona di Attività, è tolta; per l'elenco da trascinare di «Cosa scaricare prima» sono arrivate `grip-vertical` (la maniglia) e `chevron-up` («Su»). Elenco: | Uso | Icone | |---|---| -| Navigazione | `layout-grid`, `users`, `activity`, `folder-input`, `settings` | +| Navigazione | `layout-dashboard`, `layout-grid`, `users`, `folder-input`, `settings` | | Tipi di contenuto | `image`, `clapperboard`, `circle-dashed`, `star`, `square-user`, `circle-user`, `layers`, `play` | | Stato e avvisi | `lock`, `user-check`, `user`, `info`, `triangle-alert`, `octagon-alert`, `shield-check`, `shield-alert`, `hourglass`, `gauge`, `clock`, `history` | -| Azioni | `plus`, `search`, `x`, `check`, `circle-check`, `refresh-cw`, `rotate-ccw`, `rotate-cw`, `pause`, `external-link`, `folder-open`, `folder`, `app-window`, `trash-2`, `archive`, `file-down`, `list-filter`, `ellipsis`, `zoom-in`, `maximize`, `grid-3x3`, `square` | -| Frecce | `arrow-left`, `chevron-left`, `chevron-right`, `chevron-down` | +| Azioni | `plus`, `search`, `x`, `check`, `circle-check`, `refresh-cw`, `rotate-ccw`, `rotate-cw`, `pause`, `external-link`, `folder-open`, `folder`, `app-window`, `trash-2`, `archive`, `file-down`, `list-filter`, `ellipsis`, `zoom-in`, `maximize`, `grid-3x3`, `square`, `grip-vertical` | +| Frecce | `arrow-left`, `chevron-left`, `chevron-right`, `chevron-down`, `chevron-up` | | Impostazioni | `sliders-horizontal`, `key-round`, `bell`, `database`, `sun`, `moon`, `monitor`, `hard-drive` | --- diff --git a/docs/decisioni.md b/docs/decisioni.md index 7fc84b1..bffa1bf 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -542,5 +542,30 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-25 | Le sei prove di `PipelineTests.Pulizia` con il limite di 5 minuti girano una per volta, dopo le altre (`[DoNotParallelize]`), senza alzare il limite | In un giro completo in locale, accanto alle suite di conformità H.264/H.265, superavano i 5 minuti; da sole ne prendono circa uno | | 2026-11-25 | Carattere: il token `--carattere` è esattamente la pila dell'appendice B (`system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`), che `InHouseAssetsTests` confronta con la specifica; sostituisce la pila del 18 novembre con Cantarell, "Noto Sans" e "Liberation Sans" | La specifica fissa la pila; Liberation è fuori anche dall'immagine. Resta per i documenti: l'appendice B non elenca il token `--carattere` | | 2026-11-25 | Il commit di unione 537517b ha nel messaggio, dopo `Co-Authored-By`, le righe `# Conflicts:` lasciate da git: si accetta così, sapendolo | Rifarlo vorrebbe dire riscrivere la storia di cinque rami locali costruiti sopra; `git interpret-trailers` legge lo stesso il `Co-Authored-By` | +| 2026-11-25 | D1, prima parte: «Cosa scaricare prima» generale nella chiave `scaricamento.ordine` di `setting` (vuota per l'ordine predefinito storie, evidenza, post, reel, taggati), salvata con i limiti (`downloadOrder` in `/api/settings/limits`). Nel motore, dopo il giro, le storie non segnalate e il resto del lavoro dovuto (non in una sessione leggera) si estraggono da un solo insieme con peso dell'account × peso del tipo (16, 8, 4, 2, 1); le storie segnalate restano davanti, il giro resta primo, Storico dopo. La coda dei file ordina per posizione del tipo dell'elemento, poi per scadenza e scoperta. Ordine per account, colonna del reel e migrazione non ancora fatti | Una sola chiave di `setting` non tocca lo schema, che per la `0002` va concordato con E1 (§8.3). Unire le fasi 3 e 4 è l'unico modo perché l'ordine pesi davvero la visita successiva (§7.2: «il primo tipo viene di norma prima ma non sempre»); le prove del motore, simulazione compresa, restano verdi | +| 2026-11-25 | Dashboard al posto di Attività (`/dashboard`, `/` e `/attivita` vi portano, prima voce della barra, ritorno dopo l'accesso): anteprima del browser sempre in alto, chiesta ogni secondo mentre il motore lavora e solo con la scheda visibile, e `LiveBrowserPreview` che cattura al più un fotogramma al secondo per tutti. Le miniature della cronologia vengono da `/api/activity/arrived` (account, inizio e fine della ricetta, entrate scoperte in quell'intervallo), chieste solo quando la riga entra in vista e tenute finché la riga resta | La riga della cronologia sa già account e fine; l'inizio della ricetta (`RecentAction.StartedAt`) basta a ritrovare ciò che ha salvato senza una tabella nuova, con l'indice `ix_entry_account_kind`. Un fotogramma al secondo è il massimo di §7.9; la memoria di 1 s nel servizio evita catture doppie con più schede aperte | +| 2026-11-25 | D1, seconda parte: migrazione `0002_ordine_scaricamento` con `account.download_order` (testo dell'ordine suo, NULL per «Come le impostazioni generali») ed `entry.is_reel` (0/1, predefinito 0). Prende il numero 0002 perché è la prima migrazione dopo quelle unite; E1 userà il numero libero successivo (0003 se D1 si unisce prima) | §16 e la tabella delle tappe dicono «D1 ha una migrazione sua, numerata dopo quelle già unite»; il gestore delle migrazioni vuole numeri senza buchi, quindi E1 non può tenere 0002 se D1 arriva prima. Da sistemare nei documenti: §15 dice ancora «E1: migrazione `0002`» | +| 2026-11-25 | Un post è un reel per la coda quando è stato trovato nella scheda Reel (il percorso Reel segna ogni contenuto che salva) o quando la risposta ha `product_type` «clips» (`productType` e `reelTypes` nuovi in `lettori.instagram.json`, visti in post-video, post-del-profilo, reel-del-profilo e con-tag; il sito di prova non li ha). Il segno non si toglie mai: `MarkReelAsync` scrive solo quella colonna e `UpdateAsync` tiene il massimo fra il valore salvato e quello nuovo. Un taggato non è mai un reel. I post già in libreria restano post | Regola 9: il valore viene dai campioni ripuliti, non è inventato. Scrivere solo la colonna evita di riscrivere lo stato che la coda sta cambiando nello stesso momento; un reel che torna post per una copia vecchia sposterebbe di nuovo i suoi file in coda | +| 2026-11-25 | Coda dei file con «Cosa scaricare prima»: ogni file prende la posizione del suo tipo nell'ordine del suo account (il suo se ce l'ha, altrimenti il generale; gli account con lo stesso ordine suo condividono un ramo del `CASE`), poi scadenza, scoperta, elemento e posizione. Un posto su otto (`DownloadOptions.LongestWaitingShare`) va al file che aspetta da più tempo, di qualunque tipo | Senza la quota un tipo in fondo all'ordine aspetterebbe per sempre quando il tetto dei dati finisce ogni giorno prima della coda o il primo tipo non si esaurisce mai. Ogni file prima o poi è il più vecchio in attesa (i nuovi sono sempre più giovani), quindi ogni tipo ha almeno 1/8 degli scaricamenti finché ha file in coda; 7 posti su 8 restano all'ordine, così le storie in cima scadono come prima | +| 2026-11-25 | Nel motore il peso del tipo è quello dell'ordine dell'account della visita (`DownloadOrder.For`): il suo, o il generale. Le visite senza account (giro, elenco dei seguiti) restano fuori dall'ordine | §4.4: l'ordine suo pesa «sulle visite del motore a quell'account»; la prova con seme fisso mostra che i post di account con l'ordine suo vengono più spesso per primi senza diventare fissi, e che il giro resta primo | +| 2026-11-25 | Interfaccia: l'elenco da trascinare di «Cosa scaricare prima» è un modulo solo (`js/pages/download-order.js`) usato da Limiti e comportamento e dalla scheda account → Impostazioni («Come le impostazioni generali» mostra l'ordine generale in una riga, «Un ordine suo» parte da quello); i tipi spenti in «Cosa scaricare» restano attenuati con «spento in «Cosa scaricare»». Nella dimostrazione @luca.viaggi.demo ha un ordine suo e i post con un solo video sono reel | Due copie dello stesso elenco divergerebbero (tastiera, annunci per i lettori di schermo); i dati della dimostrazione mostrano i due casi | +| 2026-11-25 | Dashboard: la finestra di Febe per Windows apre `/dashboard?gettone=…` (`DesktopPlatform.FirstAddress`) invece di `/`; tolto il gettone resta `/dashboard`. In Docker `/` e `/attivita` portano alla Dashboard dalla pagina (`routes.js`), non dal server | §7.9, §12: la finestra si apre sulla Dashboard senza passare da un rinvio della pagina; un rinvio del server su `/` cambierebbe le risposte che le prove di sicurezza si aspettano per ogni indirizzo di pagina | +| 2026-11-25 | La voce Dashboard della barra laterale ha un'icona sua, `layout-dashboard` (quattro riquadri, disegnata in casa sulla griglia di 24); `activity` resta fra le icone | §10.3 «Schermate della tappa D1»: «prima voce, con la sua icona»; l'impulso di `activity` diceva Attività | +| 2026-11-25 | Miniature della cronologia: `/api/activity/arrived` senza `account` dà ciò che è arrivato di tutti gli account nel tempo della riga (le righe del Giro dei seguiti, che salva post di più account), sempre e solo elementi scaricati da Febe (mai gli importati); indice `ix_entry_discovered` (`discovered_at`) aggiunto alla migrazione 0002, non ancora unita, così la domanda legge solo le righe di quei minuti | §7.9: «le righe che hanno salvato qualcosa» mostrano le miniature, anche il Giro; un'importazione nello stesso momento non è uno scaricamento; libreria da 200.000 elementi | +| 2026-11-25 | Guida: la pagina «Attività e arresti» diventa «Dashboard e arresti» (`docs/guida/Dashboard-e-arresti.md`), con i collegamenti delle altre pagine | §7.9: la pagina si chiama Dashboard; il wiki si pubblica a mano: lì la pagina vecchia va tolta o lasciata con un rimando | +| 2026-11-25 | «Tutte le foto»: una tessera per ogni file **presente in libreria** (scaricato o importato), video compresi; un file ancora da scaricare, fallito o saltato non ha tessera, e la posizione «2/4» resta quella nella serie dell'elemento (il 4 è il numero dei suoi file, come sulla tessera raggruppata). Con «Foto» e «Video» si vedono solo i file di quel tipo dei post. L'API è la stessa con `mode=files`: le finestre vanno avanti con il cursore `ms.elemento.posizione`, `/api/library/days` conta i file per giorno e dice anche `files`, i totali restano elementi | §4.6: «una tessera per file»; una tessera di un file che non c'è non avrebbe nulla da mostrare; un video dentro «Foto» confonderebbe il filtro. Il titolo dice entrambi («61.034 file in 48.212 elementi di 38 account»), §4.3: i contatori contano elementi | +| 2026-11-25 | Finestre di «Tutte le foto»: le chiavi degli elementi vengono dalla stessa scansione a chiavi dell'indice di pubblicazione del mosaico raggruppato, poi i loro file si leggono per chiave; i conteggi per giorno e il totale dei file leggono i file di tutta la libreria in un passaggio sul nuovo indice `ix_media_entry_files (entry_id, state, kind)`, aggiunto alla migrazione 0002 (non ancora unita), e con un filtro sugli account li contano elemento per elemento. Per i conteggi «Foto» e «Video» valgono come «Post» (il tipo del file decide già). Il filtro «Post» usa `+e.kind` come «Tutto» | Prova di scala con 200.000 elementi: finestre 6-11 ms come quelle raggruppate; un conteggio per elemento costava 1,3-2,3 s, un passaggio sull'indice 0,2-0,3 s; senza `+` il filtro «Post» passava dall'indice del tipo e leggeva la riga di ogni post per lo stato. Una base già portata a v2 da una build precedente di D1 non riceve l'indice: le domande funzionano, solo più lente | +| 2026-11-25 | Selezione con «Tutte le foto»: si scelgono file (la chiave della tessera è il file); l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e barra e conferma lo dicono («3 file scelti, di 2 elementi», «3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»); anche «Elimina» del visualizzatore elimina l'elemento intero. «Copia in…» e «Fotogrammi…» non sono in questo ramo: quando arrivano (E2, E3) lavorano sui file scelti | §4.6: eliminare resta per elemento, per non lasciare post a metà; «Copia in…» di §4.10 lavora sui file | +| 2026-11-25 | La scelta «Raggruppa i post» / «Tutte le foto» sta nella memoria locale del browser (`febe.mosaico.libreria`, `febe.mosaico.account`, lette e scritte in un `try` da `local`); qualunque altro valore, o nessuna memoria, vale «Raggruppa i post». Nella scheda account l'interruttore manca in «In evidenza» (disegnata per raccolta) e le linguette contano elementi. Nella Libreria l'interruttore mostra solo le icone sotto i 1680 px di finestra, nella scheda account sotto i 1000 px | §4.6; la riga degli strumenti della Libreria a 1440 px non ha posto per due voci con il testo; nome e suggerimento restano sui pulsanti | +| 2026-11-25 | Dimostrazione: circa una serie di tre file o più su cinque ha un video in seconda posizione, deciso dall'identificativo dell'elemento (durata e peso compresi) e non dalla sequenza casuale, così il resto del mondo della dimostrazione resta com'era | «Tutte le foto» va provata anche con i video dentro un carosello; le prove della dimostrazione contano sugli stessi dati | +| 2026-11-25 | Il totale dei file di «Tutte le foto» in `/api/library/days` è la somma dei giorni (`CountLibraryByDayAsync` in modo file); `CountLibraryFilesAsync` è tolto | Ogni richiesta faceva due volte lo stesso passaggio su tutta la tabella `media` (0,2-0,3 s l'uno su 200.000 elementi), e il mosaico la ripete a ogni cambiamento della libreria, cioè di continuo mentre Febe scarica; i due numeri erano sempre uguali per costruzione | +| 2026-11-25 | Totali e conteggi per giorno di «Foto» e «Video» raggruppati, su tutta la libreria: `+e.kind = 'Post' AND +e.id IN (SELECT entry_id FROM media WHERE kind = …)` su un indice di copertura di `entry`, invece di un EXISTS per post; finestre, controlli del cursore e filtri sugli account restano con l'EXISTS. Nuove misure in `LibraryScaleTests` con limite 600 ms | Con l'EXISTS ogni post leggeva la sua riga: 1,3-1,6 s per i totali di «Video» e «Foto» a ogni caricamento (anche in «Tutte le foto», che chiede i totali). Con l'elenco: 86 ms (Video) e 141 ms (Foto); senza i `+` SQLite cercava ogni elemento per chiave e «Foto» costava ancora 0,85 s. Una finestra si ferma dopo poche centinaia di post, e con un account i post sono pochi: lì l'EXISTS costa meno | +| 2026-11-25 | Correzione della riga sulla quota di chi aspetta: il posto riservato (uno su otto) va al file più vecchio di **tutta** la coda, non a turno a ogni tipo. Non c'è un minimo di 1/8 per tipo: un tipo trovato dopo un arretrato più vecchio di un altro tipo (taggati scoperti dopo migliaia di post dello Storico) aspetta che quell'arretrato finisca. Vale solo che nessun file aspetta per sempre | È l'ordine che Alberto ha chiesto (storie, poi post, poi reel, poi taggati); una rotazione fra i tipi lo scavalcherebbe. Commento di `DownloadOptions.LongestWaitingShare` corretto, prova nuova con un arretrato più vecchio di un altro tipo | +| 2026-11-25 | Visualizzatore con «Tutte le foto»: le frecce saltano i file che il mosaico non mostra (le foto di un post con «Video», i video con «Foto», i file non in libreria) e passano alla tessera vicina; un file aperto dalla striscia della serie che non è una tessera non ha «file N di M» nell'intestazione. L'interruttore «Raggruppa i post» / «Tutte le foto» non fa nulla sulla voce già scelta | §4.6: «le frecce vanno di file in file» fra le tessere; prima l'intestazione diceva il numero di un altro file. Ricliccare la voce scelta ridisegnava il mosaico, tornava in cima e perdeva la selezione | +| 2026-11-25 | Tolta l'icona `activity` (`wwwroot/icone/activity.svg`): con la Dashboard (`layout-dashboard`) nessuna pagina la chiede. L'appendice C della specifica la nomina ancora fra le icone di navigazione: da aggiornare con `layout-dashboard` | Lo sprite `/icone/tutte.svg` mette insieme ogni file della cartella: un'icona che nessuno usa vi viaggia per niente | +| 2026-11-25 | Il commit 34fe5e9 del ramo `funzione/dashboard` ha all'inizio dell'oggetto un BOM (U+FEFF), entrato quando PowerShell ha passato il messaggio a git: si accetta così, sapendolo | Riscriverlo vorrebbe dire riscrivere la storia del ramo, che i passi del lavoro non possono fare; il testo è giusto, solo un carattere invisibile in testa | | 2026-11-25 | Documenti allineati alla catena della 0.3.0 costruita su `funzione/senza-terzi` (C1–C6, S4b): la regola 12 di `CLAUDE.md` e la sua copia nell'appendice A, e la regola 13 della specifica, dicono che SkiaSharp, ffprobe, ffmpeg, NSIS, Node, Archivo e Lucide **sono già usciti**; §6.0 toglie «finché questo non è costruito» e dice `LeavePageAsync` e il ripiego su «Annulla» dove non si copia; §3, §4.6, §8.4, §9.2, §9.3 e §14.1 dicono HEIC decodificato in casa (mai «danneggiato»), JPEG e PNG senza `EOI`/`IEND` troncati, HEVC negli MPEG-PS dall'SPS con il tipo 0x24 e senza fotogramma, i danneggiati segnati in revisione, resoconto e CSV, e il JPEG con codifica aritmetica, 12 bit e senza perdita; §11 l'immagine com'è (Febe processo 1, `fonts-dejavu-core` e `fonts-noto-color-emoji`, i pacchetti per il runtime .NET, `setpriv` dall'immagine di base); appendici B e C senza Archivo e Lucide, con il token `--carattere`. `SpecificationConsistencyTests` vuole il passato nella frase che nomina ogni componente, cerca le frasi che lo davano ancora in uso e ammette in `Directory.Packages.props` solo i pacchetti della regola; `InstallerTests` ammette NSIS nella regola 12 solo se dice che è uscito | Le tappe sono costruite e i documenti le davano ancora per future: le prove dei documenti chiedevano «esce con», e avrebbero lasciato passare un documento che desse un componente ancora in uso | +| 2026-11-25 | Dashboard compressa: l'anteprima del browser tiene le proporzioni 420 × 236 e si stringe con la pagina (`clamp(220px, 38%, 420px)`) restando accanto allo stato fino al telefono; i tetti del cruscotto vanno in due per due quando la colonna dello stato è sotto i 600 px, con una `@container` sulla colonna invece di una soglia della finestra; sotto i 560 px una colonna sola. La striscia della Dashboard è alta 30 px e le sessioni sono barre di quasi tutta l'altezza, con i margini in percentuale (10–18%) per tutte le strisce. L'icona `layout-dashboard` è ridisegnata in casa come un tachimetro in un riquadro | Richiesta di Alberto («comprimendola… resterà su questa pagina per monitorare»): a 860 × 900 l'anteprima a tutta larghezza spingeva la cronologia sotto il primo schermo; la colonna dello stato cambia larghezza con la barra laterale, la finestra no; con i margini in pixel la striscia bassa disegnava punti; le due icone a riquadri di Dashboard e Libreria si confondevano | +| 2026-11-25 | Documenti di D1 allineati a ciò che è costruito: §4.6 (la scelta del mosaico resta solo nel browser, a differenza del tema; `mode=grouped` o `files`, cursore `ms.elemento.posizione`, campo `files` di `/api/library/days`), §6.5 e §7.2 (posto su otto al file più vecchio di tutta la coda, reel dalla scheda Reel o da `product_type` «clips», giro primo e storie segnalate davanti, pesi 16/8/4/2/1 da confermare), §7.9 e §10.3 (Dashboard compressa, benvenuto compatto al primo avvio), §8.3 e §15 (D1 ha la migrazione `0002` con `account.download_order`, `entry.is_reel`, `ix_entry_discovered` e `ix_media_entry_files`; E1 prende la `0003`), appendice C (`layout-dashboard` al posto di `activity`, `chevron-up` e `grip-vertical`); guida, prove dal vivo e `windows.md` dicono Dashboard. Al primo avvio la Dashboard mostra il benvenuto compatto finché non c'è nessun account (`/api/accounts` vuoto), con «Collegati a Instagram» o, già collegati, «Aggiungi account», più «Importa foto e video che hai già» | Con D1 `/` apre la Dashboard e il benvenuto della Libreria vuota non era più la prima cosa vista: il benvenuto nello stesso posto in cui si apre Febe è la cosa meno sorprendente, e la condizione «nessun account» copre anche chi si è collegato senza aggiungere nessuno. Le righe precedenti di oggi lasciavano da sistemare §15 («E1: migrazione `0002`») e l'appendice C | +| 2026-11-25 | Due scelte di D1 e di S4b che la specifica dava per decise diventano proposte con una domanda di §16: i 5 secondi di grazia in Docker prima che lasciare la pagina del browser copi la sessione (§6.0 «Quando si copia», domanda 20) e il posto su otto della coda dei file al file che aspetta da più tempo (§6.5, §7.2, domanda 21). Il comportamento costruito resta quello proposto finché Alberto non risponde | Alberto ha detto solo che lasciare la pagina copia la sessione e quale ordine dei tipi vuole: la durata della grazia e la quota del più vecchio sono scelte di chi ha costruito, e `docs/stato.md` le teneva già fra le domande aperte | | 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana | diff --git a/docs/guida/Account-e-impostazioni.md b/docs/guida/Account-e-impostazioni.md index 6e0c0f6..13944b8 100644 --- a/docs/guida/Account-e-impostazioni.md +++ b/docs/guida/Account-e-impostazioni.md @@ -66,7 +66,7 @@ sempre: | «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) | +| «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 [Dashboard e arresti](Dashboard-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 | @@ -114,6 +114,12 @@ risulta «Non raggiungibile»: puoi indicare il nuovo nome. Tre linguette: **Contenuti** (Post, Storie, In evidenza raggruppati per raccolta, Taggati, e Profilo se ci sono più foto del profilo), **Impostazioni** e **Cronologia** (i controlli con il loro esito). +Nei Contenuti c'è lo stesso interruttore della Libreria, **«Raggruppa i post» / «Tutte le foto»** (vedi +[Libreria](Libreria)): una tessera per elemento oppure una per file, con la posizione nella serie («2/4») e la riga del +giorno che conta i file. La scelta vale per le schede di tutti gli account ed è separata da quella della Libreria. In +«In evidenza», ordinata per raccolta, l'interruttore non c'è: ogni contenuto di una raccolta è già un file solo, o quasi. +I numeri dell'intestazione e delle linguette restano elementi. + ### Impostazioni dell'account - **Tieni aggiornato:** con «no» Febe fa un solo scaricamento, poi mette l'account in pausa. @@ -131,6 +137,10 @@ foto del profilo), **Impostazioni** e **Cronologia** (i controlli con il loro es dentro la fascia. - **Cosa scaricare:** Foto dei post, Video e reel, Storie, Storie in evidenza, Post in cui è taggato, Foto del profilo. Quello che togli resta in libreria, ma non viene più aggiornato. +- **Cosa scaricare prima:** «Come le impostazioni generali» (di solito) oppure «Un ordine suo», che parte dall'ordine + generale e si cambia trascinando le righe o con «Su» e «Giù». Pesa sulle visite di Febe a questo account e sulla coda + dei suoi file, come l'ordine generale ([Limiti e comportamento](Limiti-e-comportamento)). I tipi spenti in «Cosa + scaricare» restano nell'elenco, attenuati. - **Limiti per questo account:** quanto indietro nel tempo (tutto, gli ultimi N post, da una data); massimo di post di storico al giorno; dimensione oltre la quale un video si salta (vuoto: nessun limite); video delle storie sì o no. Valgono insieme ai limiti generali: vince sempre il più stretto. diff --git a/docs/guida/Avvisi-e-Telegram.md b/docs/guida/Avvisi-e-Telegram.md index 8955865..e3e58fc 100644 --- a/docs/guida/Avvisi-e-Telegram.md +++ b/docs/guida/Avvisi-e-Telegram.md @@ -11,14 +11,14 @@ Quando succede qualcosa che ti riguarda, Febe te lo dice. Si regola in **Imposta | Fermo per rallentamento e ripresa | Instagram ha chiesto di rallentare: Febe aspetta 1, 6 o 24 ore, poi riparte da solo (due avvisi: il fermo e la ripresa) | Niente; se succede spesso, un profilo più prudente o meno account | | Storico di un account completato | Tutti i contenuti passati di un account sono in libreria | Niente | | Disco quasi pieno | Sul disco della libreria o della cartella dei dati restano meno di 10 GB, o meno del 5% del disco | Libera spazio o sposta la cartella su un disco più capiente | -| Formato non riconosciuto | Le risposte di Instagram sono cambiate; tre volte di fila sospendono la ricetta (un avviso a parte, «Ricetta sospesa») | Campione nuovo con la sonda, poi «Riattiva» in Attività | +| Formato non riconosciuto | Le risposte di Instagram sono cambiate; tre volte di fila sospendono la ricetta (un avviso a parte, «Ricetta sospesa») | Campione nuovo con la sonda, poi «Riattiva» nella Dashboard | -Che cosa fare, nel dettaglio: [Attività e arresti](Attivita-e-arresti). +Che cosa fare, nel dettaglio: [Dashboard e arresti](Dashboard-e-arresti). ## Dove arrivano - **Nell'interfaccia, sempre.** Una verifica, una disconnessione o un fermo mettono la striscia in cima a tutte le - pagine; ogni avviso è anche una riga della sezione **«Avvisi»** di Attività (gli ultimi 14 giorni), compresi quelli + pagine; ogni avviso è anche una riga della sezione **«Avvisi»** della Dashboard (gli ultimi 14 giorni), compresi quelli che non sei riuscito a ricevere fuori da Febe. - **Notifiche di Windows**, nella versione per Windows, se «Notifiche di Windows» è acceso. - **Telegram**, facoltativo, se scrivi il gettone di un bot e l'identificativo della chat. @@ -93,16 +93,16 @@ Uno stato che va e viene non ti manda lo stesso messaggio più volte. Lo stesso | Fermo per rallentamento, ripresa | 30 minuti | | Storico completato | 24 ore per lo stesso account | | Formato non riconosciuto, ricetta sospesa | 6 ore | -| Disco quasi pieno | 20 ore per lo stesso disco (la riga in Attività torna ogni 24 ore finché il disco resta pieno) | +| Disco quasi pieno | 20 ore per lo stesso disco (la riga nella Dashboard torna ogni 24 ore finché il disco resta pieno) | Gli orari dell'ultimo invio sono salvati: anche un riavvio non manda di nuovo lo stesso avviso. Un avviso trattenuto resta visibile nell'interfaccia. ## Quando un avviso non arriva -Se Telegram o Windows non accettano un avviso, Febe scrive una riga «Avviso non inviato» in Attività ▸ Avvisi con il +Se Telegram o Windows non accettano un avviso, Febe scrive una riga «Avviso non inviato» nella Dashboard ▸ Avvisi con il motivo in italiano (al massimo una all'ora per canale; il registro le ha tutte). Non riprova da solo: l'avviso resta -comunque nella striscia e in Attività. Controlla le impostazioni e usa «Invia una prova». +comunque nella striscia e nella Dashboard. Controlla le impostazioni e usa «Invia una prova». ## Disco quasi pieno diff --git a/docs/guida/Attivita-e-arresti.md b/docs/guida/Dashboard-e-arresti.md similarity index 77% rename from docs/guida/Attivita-e-arresti.md rename to docs/guida/Dashboard-e-arresti.md index becd8f9..5539ff3 100644 --- a/docs/guida/Attivita-e-arresti.md +++ b/docs/guida/Dashboard-e-arresti.md @@ -1,18 +1,33 @@ -# Attività e arresti +# Dashboard e arresti -## La pagina Attività +## La Dashboard -**Attività** è il cruscotto del motore. Si aggiorna da sola. +La **Dashboard** (prima si chiamava Attività) è il cruscotto del motore e la pagina con cui Febe si apre: la finestra +di Febe per Windows si apre qui, in Docker l'indirizzo di Febe (`/`) porta qui, ed è la prima voce della barra +laterale. Anche il vecchio indirizzo `/attivita` porta qui. Quando il motore lavora puoi restare su questa pagina a +guardare come va lo scaricamento. Si aggiorna da sola, ed è compatta: anche in una finestra media l'anteprima resta +accanto allo stato, così l'anteprima, i limiti di oggi e l'inizio della cronologia stanno nel primo schermo; al +telefono va tutto in una colonna. -- **Adesso:** che cosa sta facendo Febe («In sessione», «In ascolto», «Fuori fascia», «In pausa», «Fermo»), quando - riprende, e un'**anteprima del browser** di Febe (un fotogramma ogni pochi secondi, non un video; la pagina vuota fra - una sessione e l'altra). +Al primo avvio, finché non hai nessun account, in cima c'è il riquadro **Benvenuto in Febe** con i primi passi: +«Collegati a Instagram» (o, se sei già collegato, «Aggiungi account») e «Importa foto e video che hai già». Sparisce da +solo appena aggiungi un account. + +- **In alto, l'anteprima del browser**, sempre visibile: la pagina che il browser di Febe sta guardando, che scorre + mentre la ricetta la scorre (un fotogramma nuovo al più ogni secondo, non un video; la pagina vuota fra una sessione + e l'altra). Accanto, che cosa sta facendo Febe («In sessione», «In ascolto», «Fuori fascia», «In pausa», «Fermo») e + quando riprende, e i **limiti di oggi**: profili aperti, storie viste, pagine di storico, dati scaricati, con i + numeri; «Tutti i tetti» apre l'elenco completo (orari e giornalieri). Ambra sopra l'80%. - **Oggi:** la striscia della giornata, 24 ore con le sessioni come tratti, il riposo, i rallentamenti e gli arresti, e le prossime sessioni con orario indicativo. Gli orari futuri si scrivono sempre «verso le», perché sono estratti a caso. -- **Limiti di oggi:** profili aperti, storie viste, pagine di storico, dati scaricati, con i numeri; «Tutti i tetti» - apre l'elenco completo (orari e giornalieri). Ambra sopra l'80%. -- **In coda** (con orari indicativi) e **Appena fatto** (le ultime ricette con l'esito). +- **Cronologia dell'attività:** le ultime ricette con l'esito. Le righe che hanno salvato qualcosa mostrano le + miniature di ciò che è arrivato, post, storie, contenuti in evidenza, taggati (al più otto, con «+12» per il resto; + per il Giro dei seguiti, che salva post di più account, quelle di tutti). Un clic su una miniatura apre l'anteprima + ingrandita sopra la pagina: la foto o il video (senza audio), l'account, il tipo, la data, le frecce fra i file di + quella riga; Esc la chiude. «Apri nella Libreria» apre il visualizzatore su quell'elemento, «Apri l'account» la sua + scheda. +- **In coda**, con orari indicativi: le prime righe, e «Mostra tutta» per le altre. - **Arresti e rallentamenti** degli ultimi 14 giorni, con segnale, pagina, durata e quando si sono risolti. - **Avvisi** degli ultimi 14 giorni: verifiche, disconnessioni, fermi e riprese, storici completati, dischi quasi pieni, formati non riconosciuti, e gli avvisi che non sono arrivati (vedi [Avvisi e Telegram](Avvisi-e-Telegram)). @@ -25,7 +40,7 @@ browser»**, **«Diagnostica»** (vedi sotto). Se una prova va storta (Febe si ferma, non trova nulla, scarica meno del previsto) e vuoi farla guardare a qualcuno, manda il **rapporto di diagnostica**: un solo file che racconta che cosa ha fatto il motore, senza i dati di nessuno. -1. Apri **Attività** e premi **«Diagnostica»** nella riga del titolo (al telefono è l'icona del file con la freccia; +1. Apri la **Dashboard** e premi **«Diagnostica»** nella riga del titolo (al telefono è l'icona del file con la freccia; il suggerimento dice «Esporta il rapporto di diagnostica»). 2. Il file `febe-diagnostica-aaaa-mm-gg.json` finisce nei download del browser (su Windows nella cartella Download, come ogni scaricamento della finestra di Febe). @@ -122,10 +137,10 @@ sicurezza del tuo account dall'app di Instagram prima di riprendere. Se Instagram cambia il formato delle sue risposte, Febe non fallisce in silenzio: registra «formato non riconosciuto» (con la sola struttura delle chiavi, senza valori) e l'account va fra quelli «Da controllare». **Tre casi di fila per -la stessa ricetta la sospendono**, e Attività lo dice. Che cosa fare: raccogliere un campione nuovo con la sonda +la stessa ricetta la sospendono**, e la Dashboard lo dice. Che cosa fare: raccogliere un campione nuovo con la sonda passiva (vedi [Ipotesi da verificare](Ipotesi-da-verificare) e [Sviluppo](Sviluppo)), aggiornare il lettore sulla copia -ripulita, poi riattivare la ricetta da Attività. Allo stesso modo, se Febe non trova nella pagina un comando che gli -serve («bersaglio non trovato»), si ferma e lo segnala, senza cliccare a caso. +ripulita, poi riattivare la ricetta dalla Dashboard («Riattiva»). Allo stesso modo, se Febe non trova nella pagina +un comando che gli serve («bersaglio non trovato»), si ferma e lo segnala, senza cliccare a caso. ## Ricette per richieste diff --git a/docs/guida/Home.md b/docs/guida/Home.md index 1c0144c..982157a 100644 --- a/docs/guida/Home.md +++ b/docs/guida/Home.md @@ -17,7 +17,7 @@ voluto. nascondere che cos'è; lavora solo in una fascia oraria, a sessioni brevi separate da pause lunghe e mai regolari; rispetta tetti giornalieri e orari per ogni tipo di azione, contati su disco (un riavvio non li azzera); al primo segnale di Instagram si ferma: dopo una verifica o una disconnessione non riparte da solo. Vedi - [Limiti e comportamento](Limiti-e-comportamento) e [Attività e arresti](Attivita-e-arresti). + [Limiti e comportamento](Limiti-e-comportamento) e [Dashboard e arresti](Dashboard-e-arresti). - **Che cosa Febe non fa:** non risolve CAPTCHA, verifiche o codici (li completi tu, a mano); non cambia user agent, impronta o intestazioni del browser; non usa proxy, più indirizzi o più account per dividere il carico; non mette «mi piace», non segue, non commenta, non scrive messaggi; non tocca i profili privati che non ti hanno accettato. @@ -59,7 +59,7 @@ fare solo con Instagram o su Windows: | [Libreria](Libreria) | Mosaico, filtri, visualizzatore, eliminazione, esportazione CSV, nomi dei file | | [Importazione](Importazione) | Portare in libreria foto e video che hai già, senza doppioni | | [Limiti e comportamento](Limiti-e-comportamento) | Profili di prudenza, tetti, fascia oraria, ritmo delle sessioni | -| [Attività e arresti](Attivita-e-arresti) | La pagina Attività, che cosa fare dopo una verifica o un rallentamento | +| [Dashboard e arresti](Dashboard-e-arresti) | La Dashboard, pagina iniziale e cruscotto del motore; che cosa fare dopo una verifica o un rallentamento | | [Avvisi e Telegram](Avvisi-e-Telegram) | Striscia, notifiche di Windows, messaggi Telegram con un bot tuo | | [Copie e ricostruzione](Copie-e-ricostruzione) | Dove sono le copie del database, come si torna indietro, come si ricostruisce | | [Sicurezza e riservatezza](Sicurezza-e-riservatezza) | Sessione, cartella dei dati, password, rete, registri | diff --git a/docs/guida/Installazione-Windows.md b/docs/guida/Installazione-Windows.md index 2ede7f2..fc778bd 100644 --- a/docs/guida/Installazione-Windows.md +++ b/docs/guida/Installazione-Windows.md @@ -13,7 +13,7 @@ - La finestra di Febe mostra la stessa interfaccia della versione Docker, servita da Febe stesso solo su `127.0.0.1`, su una porta scelta a ogni avvio e protetta da un gettone che conosce solo la finestra. - Il browser di Instagram è una **seconda finestra, «Browser di Febe»**: WebView2 (il motore di Edge) con il suo - profilo nella cartella dei dati. La porti in primo piano con «Apri il browser» (Attività, striscia di un arresto) o + profilo nella cartella dei dati. La porti in primo piano con «Apri il browser» (Dashboard, striscia di un arresto) o «Portalo in primo piano» (Collegamento). Quando non serve **non è chiusa né ridotta a icona**: resta aperta ma fuori dallo schermo, perché deve continuare a caricare e scorrere (ipotesi S2). Salvataggio delle password e compilazione automatica sono spenti. @@ -99,8 +99,10 @@ la libreria in `Immagini\Febe`, finché non scegli altre cartelle. ## Il primo avvio -Febe si apre sulla schermata di benvenuto con due pulsanti: «Collegati a Instagram» e «Importa foto e video che hai -già». Il collegamento si fa nella finestra «Browser di Febe»: continua da [Primo collegamento](Primo-collegamento). +Febe si apre sulla [Dashboard](Dashboard-e-arresti), che finché non hai nessun account mostra in alto il riquadro di +benvenuto con due pulsanti: «Collegati a Instagram» e «Importa foto e video che hai già» (lo stesso benvenuto compare +nella Libreria vuota). Il collegamento si fa nella finestra «Browser di Febe»: continua da +[Primo collegamento](Primo-collegamento). ## Un account, un motore diff --git a/docs/guida/Ipotesi-da-verificare.md b/docs/guida/Ipotesi-da-verificare.md index fac26b1..0783833 100644 --- a/docs/guida/Ipotesi-da-verificare.md +++ b/docs/guida/Ipotesi-da-verificare.md @@ -44,13 +44,13 @@ Console lo script `tools/bersagli/raccogli-bersagli.js` per i bersagli, poi `feb | H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare: il HAR non aveva gli attributi dei comandi. Pagine compilate, bersagli vuoti | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti | Finché i bersagli non sono compilati, le ricette che ne hanno bisogno rispondono «la mappa dei bersagli non è ancora -compilata» senza aprire pagine; in Attività risultano «Da configurare» e il motore non le pianifica. +compilata» senza aprire pagine; nella Dashboard risultano «Da configurare» e il motore non le pianifica. ## Voci S: i due browser | | Ipotesi | Stato | Come la provi | |---|---|---|---| -| S1 | In WebView2 funzionano, attraverso il protocollo DevTools, il corpo delle risposte, i gesti e i fotogrammi della pagina | **Da provare su Windows** (M6) | Con l'app per Windows contro il sito di prova (parte C3 di `docs/prove-dal-vivo.md`, senza Instagram): una raccolta completa (risposte lette, scorrimento e clic arrivati, anteprima del browser in Attività che si aggiorna) | +| S1 | In WebView2 funzionano, attraverso il protocollo DevTools, il corpo delle risposte, i gesti e i fotogrammi della pagina | **Da provare su Windows** (M6) | Con l'app per Windows contro il sito di prova (parte C3 di `docs/prove-dal-vivo.md`, senza Instagram): una raccolta completa (risposte lette, scorrimento e clic arrivati, anteprima del browser nella Dashboard che si aggiorna) | | S2 | Su Windows la pagina continua a caricare e a scorrere quando la finestra del browser non è in vista | **Da provare su Windows** (M6) | Parte C4, con il sito di prova: una sessione con la finestra «Browser di Febe» fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; le ricette finiscono e i file arrivano. Se non regge, si provano nell'ordine `Febe.exe --browser composizione` e poi `--browser edge` (Edge avviato come processo separato) | | S3 | L'accesso fatto a mano sopravvive al riavvio del programma | Provato in locale con Chromium (3 prove su 3); **da provare** nel contenitore vero e su Windows | Docker: accedi, ricrea il contenitore (o riavvia Unraid), controlla che Collegamento dica «Collegato». Windows (parte C5, account di prova): accedi, «Esci» dall'icona, riapri Febe, stessa verifica; poi riavvio di Windows e avvio con il computer | | S4 | In Docker, dalla vista remota, si scrive in un modulo e si naviga con un ritardo sopportabile | Provato in locale senza contenitore; **da provare** sul tuo Unraid | Il primo accesso a Instagram dalla vista remota: riferisci se il ritardo è sopportabile | diff --git a/docs/guida/Libreria.md b/docs/guida/Libreria.md index 1601b04..797fa25 100644 --- a/docs/guida/Libreria.md +++ b/docs/guida/Libreria.md @@ -16,10 +16,29 @@ anche con centinaia di migliaia di elementi: carica a finestre e le miniature si I nuovi elementi compaiono in cima senza spostare ciò che stai guardando. +## «Raggruppa i post» o «Tutte le foto» + +Accanto al cursore della grandezza c'è un interruttore a due voci (nelle finestre meno larghe solo le due icone, con il +nome nel suggerimento): + +- **Raggruppa i post** (il predefinito): una tessera per elemento. Un post con quattro foto è una tessera sola, con + il numero dei file in alto a destra. +- **Tutte le foto**: una tessera per ogni file della libreria, video compresi, nello stesso ordine (la data + dell'elemento, poi la posizione nella serie). È utile quando un post ha più foto. La tessera di un file di una serie + dice la sua posizione («2/4»); la riga del giorno conta i file («23 file nuovi») e il titolo dice file ed elementi + («61.034 file in 48.212 elementi di 38 account»). Con «Foto» e «Video» si vedono solo le foto, o solo i video, dei + post. Un file non ancora scaricato non ha tessera. + +Filtri, ricerca e caricamento a finestre funzionano allo stesso modo nei due modi. Febe ricorda la scelta in questo +browser, una per la Libreria e una per le schede degli account. A differenza del tema, che Febe salva e ritrova in +ogni browser, questa scelta resta solo nel browser in cui l'hai fatta: in un altro browser, in una finestra privata o +se il browser non conserva nulla, si riparte da «Raggruppa i post». + ## Il visualizzatore Un clic su una tessera apre l'elemento a tutta finestra: frecce (anche da tastiera) per scorrere, Esc per chiudere, i -video partono senza audio. A lato: la serie dei file, didascalia, dati (data, codice, autore, raccolte), file +video partono senza audio. Con «Tutte le foto» si apre sul file della tessera, le frecce vanno di file in file e in alto +si legge «Libreria, file 12 di 61.034». A lato: la serie dei file, didascalia, dati (data, codice, autore, raccolte), file (nome, dimensioni, peso, cartella) e provenienza. Azioni: - **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker); @@ -46,6 +65,11 @@ resta. Un file si elimina o si sostituisce solo per una scelta tua. «Seleziona» attiva la scelta delle tessere; nella barra in basso: **Esporta l'elenco** degli elementi scelti oppure **Elimina** (con la stessa conferma di sopra). «Fine» chiude la selezione. +Con «Tutte le foto» si scelgono i file, ma l'elenco CSV ed «Elimina» lavorano sugli **elementi interi** a cui +appartengono: la barra lo dice («3 file scelti, di 2 elementi», «Elimina 2 elementi») e anche la conferma («3 file +scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»). Un solo file di un post non si elimina: si +elimina il post. Lo stesso vale per «Elimina dalla libreria» nel visualizzatore. + ## Esportare l'elenco in CSV Il pulsante con l'icona del documento nella riga degli strumenti, **«Esporta l'elenco»**, scarica in un file CSV @@ -63,7 +87,7 @@ Il CSV contiene le didascalie: trattalo come i dati che descrive. Quando Febe scarica una foto che sembra la stessa immagine già salvata nello stesso account (stessa immagine, file diverso), le tiene entrambe e mette la coppia in **«Doppioni da decidere»** (collegamento nella riga degli strumenti e -in Attività). Per ogni coppia scegli: tieni il più grande, tieni quello già in libreria, tienili entrambi. Niente si +nella Dashboard). Per ogni coppia scegli: tieni il più grande, tieni quello già in libreria, tienili entrambi. Niente si decide da solo; ciò che scarti non viene riscaricato. Un file identico byte per byte (stesso SHA-256) a uno già presente nello stesso account non entra due volte: il nuovo viene saltato e, se quello presente era stato importato senza dati di Instagram, li riceve dall'elemento appena trovato. diff --git a/docs/guida/Limiti-e-comportamento.md b/docs/guida/Limiti-e-comportamento.md index 430f101..f443b19 100644 --- a/docs/guida/Limiti-e-comportamento.md +++ b/docs/guida/Limiti-e-comportamento.md @@ -6,7 +6,7 @@ riguarda il comportamento (quando, quanto, in che ordine, a che velocità); l'id Nessuno può garantire che basti. Per questo ci sono tre livelli indipendenti: un ritmo credibile, **tetti rigidi** che valgono anche quando il ritmo sbaglia, e un **interruttore** che ferma tutto al primo segnale (vedi -[Attività e arresti](Attivita-e-arresti)). +[Dashboard e arresti](Dashboard-e-arresti)). Si regola in **Impostazioni ▸ Limiti e comportamento**. @@ -85,11 +85,24 @@ ritmo «naturale»), limiti dell'account. Risponde con un permesso o con un rifi 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). +## Cosa scaricare prima + +In fondo alla pagina c'è l'ordine dei tipi: **storie, in evidenza, post, reel, taggati** se non lo cambi. Trascina le +righe, oppure usa «Su» e «Giù», poi «Salva». Dopo il giro dei profili che segui, che resta sempre il primo, Febe sceglie +più spesso il tipo che sta più in alto, e nella coda degli scaricamenti passano prima i suoi file. L'ordine pesa le +scelte, non le rende fisse: non aggiunge controlli, non anticipa nulla e non scavalca tetti, pause e frequenze; un tipo +in cima senza nulla da controllare non si visita. Le storie scadono dopo 24 ore: più in basso stanno, più è facile che +scadano prima di essere scaricate. Un account può avere un ordine suo (scheda dell'account → Impostazioni, vedi +[Account e impostazioni](Account-e-impostazioni)). Un reel conta come reel quando Febe sa che lo è (l'ha trovato nella +scheda Reel, o la risposta lo dice), altrimenti come post. Perché i tipi in fondo non restino ad aspettare per sempre, +un file su otto della coda è quello che aspetta da più tempo, di qualunque tipo sia. Questa quota è una proposta, ancora da +confermare. + ## Avvio graduale Se attivo (lo è di partenza), nei primi giorni dopo il primo collegamento e **dopo ogni «Riprendi» che segue una verifica o una disconnessione** i tetti partono dalla metà e risalgono in modo lineare fino al valore pieno, nei -giorni previsti dal profilo. In Attività la nota dice a che punto sono («Avvio graduale: tetti al 64%»). +giorni previsti dal profilo. Nella Dashboard la nota dice a che punto sono («Avvio graduale: tetti al 64%»). ## Ritmo dei gesti @@ -102,7 +115,7 @@ trova il bersaglio si ferma e lo segnala, invece di provare a caso. Le durate dei fermi dopo un rallentamento sono fisse e non si modificano: **1 ora** la prima volta, **6 ore** la seconda nelle 24 ore, **24 ore** la terza; poi tetti dimezzati per 48 ore. Dopo una verifica o una disconnessione Febe -non riparte da solo. Vedi [Attività e arresti](Attivita-e-arresti). +non riparte da solo. Vedi [Dashboard e arresti](Dashboard-e-arresti). ## Giudicare un profilo prima di usarlo diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index 7374887..5934a53 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -13,8 +13,9 @@ Apri `http://:8480/`: la pagina «Accedi a Febe» chiede la password del cinque tentativi sbagliati da uno stesso indirizzo (o venti in tutto) l'accesso si blocca per un quarto d'ora. «Esci» chiude la sessione dell'interfaccia. -La prima volta, con la libreria vuota, compare la schermata di benvenuto: «Collegati a Instagram» oppure «Importa foto e -video che hai già». +La prima volta Febe si apre sulla Dashboard, che finché non c'è nessun account mostra in alto il riquadro di benvenuto: +«Collegati a Instagram» oppure «Importa foto e video che hai già». Dopo il collegamento, finché non aggiungi account, il +primo pulsante diventa «Aggiungi account». Nella Libreria vuota, finché non sei collegato, compare lo stesso benvenuto. ## Collegarsi a Instagram @@ -152,4 +153,4 @@ profilo, e non vanno usati insieme sullo stesso account. ## Se compare una verifica Se Instagram chiede una verifica mentre ti colleghi, completala a mano nella stessa pagina. Se la chiede più tardi, -mentre Febe lavora, Febe si ferma: vedi [Attività e arresti](Attivita-e-arresti). +mentre Febe lavora, Febe si ferma: vedi [Dashboard e arresti](Dashboard-e-arresti). diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 1c781d8..1853ae7 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -40,15 +40,15 @@ dati. ## Il motore non scarica nulla -Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti): +Controlla in quest'ordine, guardando la [Dashboard](Dashboard-e-arresti): -1. **Ricetta «Da configurare».** Se in Attività vedi «non può girare su instagram: la mappa dei bersagli non è ancora +1. **Ricetta «Da configurare».** Se nella Dashboard vedi «non può girare su instagram: la mappa dei bersagli non è ancora compilata», è lo stato attuale del progetto per storie, raccolte e schede Taggati e Reel: aspettano i bersagli dei comandi (ipotesi H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto, e quelle ricette non vengono sospese. 2. **Non collegato**, **verifica richiesta** o **sessione chiusa**: la barra laterale lo dice. Vedi - [Primo collegamento](Primo-collegamento) e [Attività e arresti](Attivita-e-arresti). -3. **Fuori fascia** o **giorno non attivo**: Attività dice «Fuori fascia» e quando riprende. + [Primo collegamento](Primo-collegamento) e [Dashboard e arresti](Dashboard-e-arresti). +3. **Fuori fascia** o **giorno non attivo**: la Dashboard dice «Fuori fascia» e quando riprende. 4. **In pausa**: «Riprendi». 5. **Avvio appena fatto:** la prima sessione parte 2–10 minuti dopo l'avvio. 6. **Tetto raggiunto** (ambra o pieno in «Limiti di oggi»), oppure **avvio graduale** con i tetti ancora bassi. @@ -94,12 +94,12 @@ fermo; su Windows «Cambia…» vale dal prossimo avvio di Febe. ## Formato non riconosciuto, ricetta sospesa, bersaglio non trovato Vuol dire che Instagram ha cambiato le sue risposte o le sue pagine. Febe non insiste: dopo tre volte di fila sospende -la ricetta e Attività lo dice. Che cosa fare: +la ricetta e la Dashboard lo dice. Che cosa fare: 1. Avvia la **sonda passiva** e raccogli un campione nuovo navigando tu le pagine interessate (procedura in `docs/prove-dal-vivo.md`, parte A, nel repository). 2. Ripulisci e verifica il campione, e fallo arrivare a chi aggiorna i lettori o la mappa dei bersagli. -3. Dopo l'aggiornamento di Febe, premi **«Riattiva»** sulla ricetta sospesa in Attività. +3. Dopo l'aggiornamento di Febe, premi **«Riattiva»** sulla ricetta sospesa nella Dashboard. Non riattivare una ricetta solo per farla ripartire: si sospenderebbe di nuovo dopo tre tentativi. @@ -114,7 +114,7 @@ Non riattivare una ricetta solo per farla ripartire: si sospenderebbe di nuovo d | «Telegram non ha risposto» o «non è raggiungibile» | Il server (in Docker, il contenitore) deve poter uscire su Internet verso `api.telegram.org` | | «Questa istanza di Febe non invia messaggi Telegram» | Sei nella dimostrazione o in una prova: lì non parte nulla | -Gli avvisi che non sono arrivati sono elencati in Attività ▸ Avvisi come «Avviso non inviato». Vedi +Gli avvisi che non sono arrivati sono elencati nella Dashboard ▸ Avvisi come «Avviso non inviato». Vedi [Avvisi e Telegram](Avvisi-e-Telegram). ## Importazione diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index c415960..27e551b 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -241,6 +241,11 @@ Il wiki di Gitea è un repository git a parte: per pubblicarla si copiano i file `https://gitea.encke-hake.ts.net/Alby96/Febe.wiki.git` e si fa push. I collegamenti fra le pagine sono nel formato del wiki, `[Testo](Nome-Pagina)`, senza `.md`. +Copiare i file non toglie le pagine rinominate: quella vecchia resta nel wiki. Con la tappa D1 «Attività e arresti» +è diventata `Dashboard-e-arresti`, quindi alla prima pubblicazione dopo D1 la pagina `Attivita-e-arresti` del wiki va +tolta (`git rm Attivita-e-arresti.md` nel repository del wiki) oppure ridotta a una riga che rimanda a +[Dashboard e arresti](Dashboard-e-arresti), per chi l'aveva tra i preferiti. + ## Convenzioni - Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano (glossario: appendice D della specifica). diff --git a/docs/guida/_Sidebar.md b/docs/guida/_Sidebar.md index 77def99..6184e3e 100644 --- a/docs/guida/_Sidebar.md +++ b/docs/guida/_Sidebar.md @@ -10,7 +10,7 @@ - [Libreria](Libreria) - [Importazione](Importazione) - [Limiti e comportamento](Limiti-e-comportamento) -- [Attività e arresti](Attivita-e-arresti) +- [Dashboard e arresti](Dashboard-e-arresti) - [Avvisi e Telegram](Avvisi-e-Telegram) **Tenere al sicuro** diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md index c35b30c..dd22530 100644 --- a/docs/prove-dal-vivo.md +++ b/docs/prove-dal-vivo.md @@ -337,7 +337,7 @@ Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, 2. In **Limiti e comportamento** controlla che il profilo sia **Prudente**. 3. Aggiungi **un solo** profilo **pubblico**, con pochi post (meno di 30), punto di partenza «Scarica tutto e tieni aggiornato». Nient'altro. -4. Attendi: la prima sessione parte fra 2 e 10 minuti dall'avvio. Guarda la pagina **Attività**. +4. Attendi: la prima sessione parte fra 2 e 10 minuti dall'avvio. Guarda la **Dashboard**. ### B3. Che cosa aspettarsi @@ -349,7 +349,7 @@ Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**, ### B4. Che cosa riferire -- Schermata della pagina Attività a fine sessione (striscia della giornata e tetti). +- Schermata della Dashboard a fine sessione (striscia della giornata e tetti). - L'elenco dei file arrivati (nomi e dimensioni) e se qualcuno è rimasto «da scaricare», «scaduto» o «fallito». - Ogni evento in giallo o rosso della cronologia, con l'ora. - Se è comparsa una verifica: che cosa diceva, a che ora, che cosa stava facendo Febe (la pagina resta com'era). @@ -400,7 +400,7 @@ cosa aspettarsi; riferisci per ogni voce «sì/no» e, dove chiesto, la schermat 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 +5. Atteso entro qualche minuto, nella **Dashboard**: 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`). @@ -408,7 +408,7 @@ cosa aspettarsi; riferisci per ogni voce «sì/no» e, dove chiesto, la schermat 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 +7. Riferisci: numero di file arrivati; l'esito del passo 6; eventuali righe gialle o rosse della Dashboard; nel registro, le righe `[browser]` con «WebView2» e qualunque «Comando CDP … è fallito». 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`). @@ -418,13 +418,13 @@ cosa aspettarsi; riferisci per ogni voce «sì/no» e, dove chiesto, la schermat Stessa configurazione di C3 (altra cartella dati, per partire puliti: `C:\FebeProva2\…`). 1. **Fuori vista**: durante la sessione la finestra «Browser di Febe» non si vede (è fuori dallo schermo). Atteso: - la sessione procede come in C3 (le stesse ricette, i file arrivano), l'anteprima di Attività cambia. + la sessione procede come in C3 (le stesse ricette, i file arrivano), l'anteprima della Dashboard cambia. 2. **Finestra di Febe ridotta a icona**: riduci a icona la finestra di Febe, aspetta 5 minuti, riaprila. Atteso: la - sessione è andata avanti (nuove righe in Attività, nuovi file). + sessione è andata avanti (nuove righe nella Dashboard, nuovi file). 3. **Schermo bloccato**: «Controlla ora» su `luca.prova` (40 post, storico su più pagine), poi blocca lo schermo (Win+L) per 10 minuti. Atteso: al rientro, lo storico di Luca è avanzato di più pagine; nessuna riga «bersaglio non trovato» o «pagina vuota» nell'intervallo. -4. «Apri il browser» (Attività) durante una sessione. Atteso: la finestra viene in primo piano con la pagina, la +4. «Apri il browser» (Dashboard) durante una sessione. Atteso: la finestra viene in primo piano con la pagina, la sessione si chiude (il motore si ferma mentre la usi); chiudendo la finestra torna fuori vista e il motore riprende alla sessione successiva. 5. **Se 1–3 non reggono**: rifai C4 con `--browser composizione` (resta scelto per gli avvii successivi), poi con @@ -477,7 +477,7 @@ serve Instagram e non va provocato su Instagram**: l'arresto lo produce il sito 2. Apri `http://127.0.0.1:8480/`, entra con `prova`. In **Impostazioni ▸ Notifiche** incolla gettone e chat, salva, **«Invia una prova»**: nella chat deve arrivare «Febe · Prova degli avvisi». 3. Aggiungi due account per nome utente: `marta.prova` e `luca.prova`, «Scarica tutto e tieni aggiornato». -4. Quando in **Attività** vedi la prima sessione in corso, chiedi al sito una verifica: +4. Quando nella **Dashboard** vedi la prima sessione in corso, chiedi al sito una verifica: ```sh curl 'http://127.0.0.1:8481/_controllo/modo?valore=verifica' @@ -488,7 +488,7 @@ serve Instagram e non va provocato su Instagram**: l'arresto lo produce il sito ### D3. Che cosa aspettarsi - In cima a ogni pagina la **striscia rossa** «Instagram chiede una verifica», con «Apri il browser». -- In Attività, sezione **Avvisi**, la riga della verifica. +- Nella Dashboard, sezione **Avvisi**, la riga della verifica. - Su Telegram, entro pochi secondi, **un solo messaggio** che comincia con «Febe · Instagram chiede una verifica» e dice che cosa fare. - Nel registro (`/tmp/febe-m8/dati/registro/`) la riga «Avviso «Instagram chiede una verifica» inviato: Telegram». @@ -505,7 +505,7 @@ Gli avvisi sono gli stessi nelle due vesti (stessa composizione); su Windows arr 1. Su Febe per Windows (installata come in C2), in Impostazioni ▸ Notifiche accendi «Notifiche di Windows» e premi «Invia una prova». Atteso: la notifica compare nell'angolo dello schermo, accanto all'icona di Febe. -2. Con la configurazione di C3 (sito di prova, cartelle `C:\FebeProva\…`), quando in Attività vedi una sessione in +2. Con la configurazione di C3 (sito di prova, cartelle `C:\FebeProva\…`), quando nella Dashboard vedi una sessione in corso, chiedi al sito una verifica: apri `http://127.0.0.1:8481/_controllo/modo?valore=verifica` in un browser qualunque (o con `curl` dal terminale). Atteso: la striscia rossa in Febe e, entro pochi secondi, la notifica di Windows «Instagram chiede una verifica»; con Telegram configurato anche il messaggio, come in D3. @@ -515,7 +515,7 @@ Gli avvisi sono gli stessi nelle due vesti (stessa composizione); su Windows arr ### D5. Che cosa riferire - Schermate della striscia e della sezione Avvisi, il testo del messaggio Telegram arrivato. -- Se un messaggio non è arrivato: la riga «Avviso non inviato» di Attività (dice il motivo, senza il gettone). +- Se un messaggio non è arrivato: la riga «Avviso non inviato» della Dashboard (dice il motivo, senza il gettone). - Nel contenitore su Unraid: il risultato di «Invia una prova» (dice se il contenitore raggiunge Telegram). - Su Windows (D4): «sì/no» per la notifica di prova e per quella della verifica; se manca, la riga `[avvisi]` del registro di quell'ora. diff --git a/docs/schermate/01-libreria-tutte-le-foto.png b/docs/schermate/01-libreria-tutte-le-foto.png new file mode 100644 index 0000000..1d932ca Binary files /dev/null and b/docs/schermate/01-libreria-tutte-le-foto.png differ diff --git a/docs/schermate/06-attivita-tutti-i-tetti.png b/docs/schermate/06-attivita-tutti-i-tetti.png index 2d844e3..8899c04 100644 Binary files a/docs/schermate/06-attivita-tutti-i-tetti.png and b/docs/schermate/06-attivita-tutti-i-tetti.png differ diff --git a/docs/schermate/06-attivita.png b/docs/schermate/06-attivita.png index ac70690..e06c41f 100644 Binary files a/docs/schermate/06-attivita.png and b/docs/schermate/06-attivita.png differ diff --git a/docs/schermate/11-attivita-fermo-tema-scuro.png b/docs/schermate/11-attivita-fermo-tema-scuro.png index b84f9f0..26c1aaf 100644 Binary files a/docs/schermate/11-attivita-fermo-tema-scuro.png and b/docs/schermate/11-attivita-fermo-tema-scuro.png differ diff --git a/docs/schermate/14-attivita-finestra-stretta-normale.png b/docs/schermate/14-attivita-finestra-stretta-normale.png index 86f04c3..3850001 100644 Binary files a/docs/schermate/14-attivita-finestra-stretta-normale.png and b/docs/schermate/14-attivita-finestra-stretta-normale.png differ diff --git a/docs/schermate/14-attivita-finestra-stretta.png b/docs/schermate/14-attivita-finestra-stretta.png index ee8c1e9..0b69e6d 100644 Binary files a/docs/schermate/14-attivita-finestra-stretta.png and b/docs/schermate/14-attivita-finestra-stretta.png differ diff --git a/docs/schermate/14-attivita-telefono-normale.png b/docs/schermate/14-attivita-telefono-normale.png index c91c74c..1dc6ff7 100644 Binary files a/docs/schermate/14-attivita-telefono-normale.png and b/docs/schermate/14-attivita-telefono-normale.png differ diff --git a/docs/schermate/14-attivita-telefono.png b/docs/schermate/14-attivita-telefono.png index 126da75..925a7b1 100644 Binary files a/docs/schermate/14-attivita-telefono.png and b/docs/schermate/14-attivita-telefono.png differ diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md index 17e4174..51d71ee 100644 --- a/docs/schermate/differenze.md +++ b/docs/schermate/differenze.md @@ -7,6 +7,7 @@ solo per l'interfaccia di Febe (§10.7). | Schermata | Indirizzo | Mockup | |---|---|---| | `01-libreria.png` | `/libreria?tema=chiaro`, puntatore su una tessera | `docs/mockup/01-libreria.png` | +| `01-libreria-tutte-le-foto.png` | `/libreria?tema=chiaro`, «Tutte le foto» scelto (passo `tutte-le-foto.js`; presa il 25/11 da Windows) | `docs/mockup/01-libreria.png` (il mockup non ha l'interruttore, vedi sotto) | | `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) | @@ -15,10 +16,10 @@ solo per l'interfaccia di Febe (§10.7). | `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` | | `14-finestra-stretta.png` | `/libreria`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` | -| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività al telefono) | +| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività, oggi Dashboard, 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 (rifatta il 15/11 da Windows: c'è la riga «Ricerche di profili») | (nessuno: §7.4) | +| `06-attivita.png` | `/dashboard?scena=sessione&tema=chiaro` (Dashboard; rifatta il 25/11 da Windows) | `miniature/06-attivita.png` | +| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto (rifatta il 25/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` | @@ -29,11 +30,11 @@ solo per l'interfaccia di Febe (§10.7). | `10-collegamento-windows.png` | come sopra con `veste=windows` | (nessuno: variante di §6.4) | | `10-collegamento-collegato.png` | `/impostazioni/collegamento?veste=docker`, account collegato | (nessuno) | | `10-browser.png` | `/browser?scena=fermo&veste=docker` | mockup 10 senza colonna dei passi | -| `11-attivita-fermo-tema-scuro.png` | `/attivita?scena=fermo&tema=scuro` | `miniature/11-attivita-fermo-tema-scuro.png` | -| `14-attivita-finestra-stretta.png` | `/attivita?scena=sessione`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` | -| `14-attivita-telefono.png` | `/attivita?scena=sessione`, 390 × 844 | parte destra di `miniature/14-finestra-stretta-e-telefono.png` | -| `14-attivita-finestra-stretta-normale.png` | `/attivita?scena=normale`, 860 × 900 | (come sopra, motore in ascolto) | -| `14-attivita-telefono-normale.png` | `/attivita?scena=normale`, 390 × 844 | (come sopra, motore in ascolto) | +| `11-attivita-fermo-tema-scuro.png` | `/dashboard?scena=fermo&tema=scuro` (rifatta il 25/11 da Windows) | `miniature/11-attivita-fermo-tema-scuro.png` | +| `14-attivita-finestra-stretta.png` | `/dashboard?scena=sessione`, 860 × 900 (rifatta il 25/11 da Windows) | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` | +| `14-attivita-telefono.png` | `/dashboard?scena=sessione`, 390 × 844 (rifatta il 25/11 da Windows) | parte destra di `miniature/14-finestra-stretta-e-telefono.png` | +| `14-attivita-finestra-stretta-normale.png` | `/dashboard?scena=normale`, 860 × 900 (rifatta il 25/11 da Windows) | (come sopra, motore in ascolto) | +| `14-attivita-telefono-normale.png` | `/dashboard?scena=normale`, 390 × 844 (rifatta il 25/11 da Windows) | (come sopra, motore in ascolto) | | `impostazioni-notifiche.png` | `/impostazioni/notifiche` | (nessuno: §13.3) | | `impostazioni-dati.png` | `/impostazioni/dati` | (nessuno: §8.2, §8.5) | | `impostazioni-informazioni.png` | `/impostazioni/informazioni` | (nessuno) | @@ -65,7 +66,7 @@ dovute ai dati dimostrativi: Il riquadro «Con queste impostazioni» usa i testi del calcolatore del motore, più lunghi di quelli del mockup. - **Storie in tema scuro.** Le tessere delle storie non hanno l'anello attorno all'elemento scelto: nel mockup c'è una tessera selezionata, qui la schermata è senza selezione. -- **Telefono, libreria.** `14-telefono.png` mostra la libreria; la pagina Attività del mockup al telefono è in +- **Telefono, libreria.** `14-telefono.png` mostra la libreria; la Dashboard (nel mockup Attività) al telefono è in `14-attivita-telefono.png`. I filtri a pastiglia vanno a capo su due righe. ### Aggiungi account dopo la ricerca unica (#37) @@ -98,7 +99,7 @@ un mockup nuovo (domanda Q9 per Alberto), il riferimento è questa schermata. Co - **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) +### Seconda parte (Dashboard, allora Attività; Impostazioni, Collegamento, Importa) Rifatte con `bash tools/schermate/tutte.sh 8490` (le righe dopo «Part 2»), su una dimostrazione appena avviata: la schermata del motore fermo si prende per prima, perché «Riprendi» resta spento finché il browser non è stato usato. @@ -139,6 +140,74 @@ schermata del motore fermo si prende per prima, perché «Riprendi» resta spent e le colonne laterali (passi del collegamento, doppioni dell'importazione) vanno sotto. Al telefono la tabella delle cartelle dell'importazione diventa un elenco di schede e «Esporta l'elenco in CSV» resta solo come icona. +### Dashboard (tappa D1, issue #59, dal 25 novembre 2026) + +Attività è diventata la **Dashboard** (§7.9, §10.3 «Schermate della tappa D1»): `/dashboard`, prima voce della barra +laterale con un'icona sua (un tachimetro in un riquadro), pagina iniziale (`/`, `/attivita` e la finestra di Windows +portano lì). Le schermate `06-attivita*`, `11-attivita-fermo-tema-scuro` e `14-attivita-*` della tabella (i nomi +restano quelli dei mockup) sono state rifatte il 25/11 e **di nuovo la sera del 25/11**, dopo le correzioni qui sotto, +con il programma delle schermate da Windows (Edge senza finestra), con `/dashboard` e le stesse scene e misure, e +messe accanto ai mockup 06, 11 e 14 da cui la pagina è composta. Le altre schermate della tabella hanno ancora nella +barra laterale l'icona vecchia della Dashboard (quattro riquadri), finché non si rifanno. Differenze: + +- **In alto il cruscotto.** L'anteprima del browser è grande (al più 420 × 236 px invece di 266 × 116) e sempre + visibile, a sinistra in un riquadro unico con accanto lo stato, che cosa sta facendo e i quattro tetti in una riga; + nel mockup 06 anteprima e stato sono un riquadro e i tetti un altro, sotto la striscia. Si aggiorna a ogni fotogramma + nuovo (al più uno al secondo) mentre il motore lavora, invece che ogni pochi secondi. +- **Striscia della giornata più bassa** (30 px invece di circa 44), sotto il cruscotto, con la legenda sulla stessa + riga del titolo quando c'è posto. +- **Cronologia e coda in due colonne**, la cronologia più larga; la coda mostra le prime cinque righe e «Mostra + tutta (N)». Le righe della cronologia che hanno salvato qualcosa hanno sotto il testo una fila di miniature da 44 px + (40 al telefono), raggio 3, con i segni del mosaico del mockup 01 (durata dei video, anello tratteggiato delle + storie), al più otto e «+N». Le righe del Giro dei seguiti mostrano ciò che è arrivato di tutti gli account. +- **Anteprima ingrandita.** Un clic su una miniatura apre un dialogo leggero (mockup 13: raggio 14, ombra), non il + visualizzatore a tutta finestra del mockup 02: foto o video senza audio su fondo scuro, frecce ai lati e da + tastiera, didascalia con account, tipo, data e «file N di M», nel piede «N di M» e i pulsanti «Apri l'account» e + «Apri nella Libreria». Esc chiude. +- **Finestra media e telefono.** L'anteprima tiene le sue proporzioni e si stringe con la pagina (fra 220 e 420 px di + larghezza, il 38% del cruscotto) restando accanto allo stato: a 860 × 900 è di circa 270 × 150 px, con accanto stato + e tetti in due per due, e la prima riga della cronologia sta nel primo schermo (come a 1440 × 900). Cronologia e coda + vanno in una colonna sotto i 1000 px. Al telefono (sotto i 560 px) una colonna sola: anteprima a tutta larghezza alta + 196 px, poi stato e tetti in due per due; i tre comandi del titolo restano icone. Nel mockup 14 la finestra stretta + non ha l'anteprima grande. +- **Arresti e Avvisi** restano in fondo alla pagina come prima della tappa D1; «Diagnostica» resta nella riga del titolo. +- **Sistemato la sera del 25/11** (i quattro punti visti nelle prime schermate del 25/11), ora come nei mockup: + - «Mostra tutta (N)» della coda ha il margine interno delle righe (14 px ai lati, 10–11 sopra e sotto), con la riga + di separazione sopra. + - Nella striscia della giornata le sessioni sono barre di quasi tutta l'altezza (l'80% circa, un po' irregolari come + nel mockup 06), non più segni di pochi pixel; vale anche per la striscia più alta delle altre pagine. + - A 860 × 900 l'anteprima non prende più tutta la larghezza (vedi sopra): pagina compressa, cronologia nel primo + schermo. `DashboardInterfaceTests` lo controlla a 860 × 900 (solo nella CI, con Chromium). + - L'icona della Dashboard (`layout-dashboard`) è ridisegnata in casa: un riquadro con un tachimetro, ben diversa dai + quattro quadrati uguali della Libreria (`layout-grid`). +- **Ancora diverso dai mockup:** la striscia resta più bassa del mockup 06; a 860 px la legenda della striscia va a capo + sotto il riassunto della giornata; le barre delle sessioni più brevi sono larghe 3 px come prima. +- **Dimostrazione.** Come per Attività l'anteprima compone tre immagini della libreria finta; righe, miniature e + numeri vengono dal mondo dimostrativo (alcune righe «Scaricato» della dimostrazione non hanno miniature perché nel + mondo finto i loro elementi non sono stati scoperti nel tempo di quella riga). + +### «Raggruppa i post» / «Tutte le foto» (tappa D1, issue #59, dal 25 novembre 2026) + +L'interruttore di §4.6 (§10.3 «Schermate della tappa D1») è composto dai mockup 01 e 12, che non lo hanno. Le +schermate `01-libreria`, `01-*` e `12-*` mostrano «Raggruppa i post», il predefinito, e non sono state rifatte; +`01-libreria-tutte-le-foto.png` (presa il 25/11 con il programma delle schermate da Windows) mostra «Tutte le foto» ed +è stata messa accanto al mockup 01. Le prove dell'interfaccia (`LibraryModeInterfaceTests`) girano solo nella CI e qui +non sono state eseguite; la scheda account con «Tutte le foto» non ha una schermata. Differenze: + +- **Controllo a due voci** (`.gruppo` dell'appendice B, come i controlli segmentati delle impostazioni) nella riga degli + strumenti, fra l'icona dell'elenco CSV e il cursore della grandezza nella Libreria, prima di «Seleziona» nella scheda + account. Icone `layers` (raggruppa) e `layout-grid` (tutte le foto). Nella Libreria, sotto i 1680 px di finestra, + restano solo le icone (la riga del mockup 01 a 1440 px non ha posto per i due testi); nella scheda account sotto i + 1000 px. Nome e suggerimento restano sui pulsanti. In «In evidenza» della scheda account non c'è. +- **Tessere di un file.** Stesse misure e righe giustificate del mosaico; il segno in alto a destra di un file di una + serie è «2/4» con l'icona `layers` al posto del numero dei file. Un file non ancora scaricato non ha tessera. +- **Intestazioni.** La riga del giorno conta i file («Oggi martedì 13 ottobre, 23 file nuovi», «9 file»), il titolo + della Libreria dice «61.034 file in 48.212 elementi di 38 account»; nella scheda account numeri e linguette restano + elementi. +- **Selezione.** La barra dice «3 file scelti, di 2 elementi» ed «Elimina 2 elementi»; la conferma aggiunge «3 file + scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file». +- **Visualizzatore** (mockup 02): si apre sul file della tessera; in alto «Libreria, file 12 di 61.034». + ### Carattere e icone (dal 18 novembre 2026) Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre diff --git a/docs/stato.md b/docs/stato.md index 5b77c90..a125e65 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -1,12 +1,94 @@ # Stato Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché. -Aggiornato il 17 novembre 2026 (tappa S4 di #36), versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno +Aggiornato il 26 novembre 2026 (catena della 0.3.0 spinta, in unione in `main` una richiesta per volta), 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 +**26 novembre 2026: la catena della 0.3.0 è spinta e si unisce in `main`** (#58, #59, #36). Sette rami, ognuno con +l'unione del precedente, ciascuno con la sua richiesta di unione (#60 … #66). Si uniscono in `main` in questo ordine, +uno alla volta, ciascuno dopo la sua verifica verde nella CI (`docs/processo.md`); `main` è protetto e rifiuta un ramo +indietro, quindi dopo ogni unione il ramo seguente riceve `main` («aggiorna il ramo») e una verifica nuova. #60 +(E0) è unita. Le esecuzioni di `main` intermedie si annullano: conta quella dopo l'ultima unione. + +Correzioni di questa sessione, venute dalla CI: in S4b un `let saved` dichiarato due volte in `connection.js` fermava +la pagina Collegamento (11 prove d'interfaccia), ora `stored`, con la prova di sintassi degli script; il lavoro +«installatore» (e «windows» e la release di `rilascio.yml`) gira sull'immagine del runner senza ICU, ora con +`DOTNET_SYSTEM_GLOBALIZATION_INVARIANT` e una prova che lo pretende (riga in `decisioni.md`); nella costruzione +dell'immagine Docker manca `docs/`, quindi le due prove che lo leggono si saltano lì (`Repository.Docs`); la prova +d'interfaccia di «Tutte le foto» sotto «Video» ora cerca con l'API un video in seconda posizione e accetta la copertina +di un video mancante (la demo non ha i file dei video). Una prova di Collegamento in H.264 è caduta una volta +(about:blank invece di `/benvenuto`) ed è passata alla ripetizione: la corsa è descritta in #67, non corretta. +L'esecuzione 448 di HEVC si è fermata per ore nelle prove senza uscita: non diagnosticata, si guarda alla prossima. + +1. `documenti/esportazione-e-regole` (E0): specifica, `CLAUDE.md` e decisioni per l'esportazione (#58), la regola + «niente componenti esterni», le risposte di Alberto del 18 e del 25 novembre e la tappa D1 nei documenti. +2. `funzione/sessione-s4b` (S4b di #36): la sessione salvata si copia anche alla chiusura della finestra su Windows e + alla fine del permesso di guida; in Docker **lasciare la pagina del browser** (o la vista remota di Collegamento, o + chiuderne la scheda) mentre Alberto guida copia la sessione e restituisce il browser, dopo 5 secondi di grazia; + «Serve «Ho finito»», scelta per la copia incompleta, stato in Collegamento. +3. `funzione/codec-immagini` (C1): lettori e scrittori di casa JPEG (anche aritmetico, 12 bit e senza perdita), PNG, + WebP, GIF, BMP, con EXIF, ICC e XMP; miniature e impronte sopra di essi; **SkiaSharp è uscito**. Un'immagine + troncata o rovinata dice «File danneggiato o incompleto» nel visualizzatore e ha la tessera neutra (risposta 3 del + 25 novembre). +4. `funzione/decoder-h264` (C2, C3, C5): contenitori ISO BMFF e Matroska, rimuxaggio e scrittore MP4, decodificatore + H.264 di casa su tutti i flussi di conformità presenti (campi, PAFF, MBAFF, FMO, ASO, SP/SI, partizioni, 4:2:2, + 4:4:4, 4:0:0, fino a 14 bit, senza perdita, MVC, SVC con le qualità MGS); lettori ASF (WMV), FLV e MPEG-PS; + **ffmpeg e ffprobe sono usciti**. +5. `funzione/decoder-hevc` (C4): decodificatore HEVC di casa, Main, Main 10, Main Still Picture e RExt, tutti i 146 + flussi di conformità coincidono; HEVC nella catena dei media (fotogrammi, miniature) e foto HEIC/HEIF decodificate in + casa; HEVC anche nei flussi di programma MPEG. +6. `funzione/senza-terzi` (C6 e unione della catena): CI senza Node né azioni, solo comandi di casa; installatore di + Windows scritto in casa al posto di NSIS; caratteri di sistema al posto di Archivo; icone SVG disegnate in casa al + posto di Lucide; immagine Docker con solo Chromium, Xvfb e ciò che serve a .NET, Febe processo 1 senza `tini`, emoji + tenute e Liberation fuori (risposta 2); correzioni della revisione della catena; documenti allineati (5b7b37a). +7. `funzione/dashboard` (D1, #59): la **Dashboard** al posto di Attività (prima voce, pagina iniziale, `/` e + `/attivita` vi portano, anteprima del browser sempre visibile e compressa anche a 860 px, miniature nella cronologia + con l'anteprima ingrandita, benvenuto compatto al primo avvio finché non c'è un account); **«Cosa scaricare + prima»** generale e per account (pesi 16/8/4/2/1 sulle visite dopo il giro, storie segnalate davanti, coda dei file + nell'ordine con un posto su otto al file più vecchio, reel riconosciuti dalla scheda Reel o da `product_type` + «clips», migrazione `0002`); **«Raggruppa i post» / «Tutte le foto»** in Libreria e nella scheda account. + +Ultimi tre commit di `funzione/dashboard` (questa sessione): unione di `funzione/senza-terzi` (l'allineamento dei +documenti, tutte le righe di `decisioni.md` dei due lati tenute); Dashboard compressa (anteprima accanto allo stato con +le sue proporzioni, barre alte nella striscia, margine di «Mostra tutta», icona `layout-dashboard` ridisegnata come un +tachimetro, schermate 06, 11 e 14 rifatte, prova d'interfaccia a 860 × 900); documenti di D1 allineati al costruito +(§4.6, §6.5, §7.2, §7.9, §8.3, §10.3, §15, appendice C, guida) e benvenuto compatto della Dashboard. + +Poi le correzioni della revisione di D1: la prova di accesso aspettava ancora `/libreria` per un «torna» mancante (ora +`/dashboard`, letto dal modulo `return-path.js`); §6.0 e §6.5/§7.2 dicono proposte i 5 secondi di grazia in Docker e il +posto su otto della coda, con le domande 20 e 21 di §16; §4.6 cita la conferma di «Elimina» com'è costruita e dice che +in «In evidenza» l'interruttore manca e che «Tutte le foto» mostra solo i file in libreria; il messaggio d'esempio di §0, +il rimando del mockup 06 e due righe di `prove-dal-vivo.md` non nominano più Attività. + +- Controlli sul ramo `funzione/dashboard`, su Windows, dopo quelle correzioni: `dotnet build -warnaserror` 0 avvisi, + 0 errori; `dotnet test tests/Febe.Tests` 2817 superate, 96 saltate, 0 non superate su 2913; `dotnet test + tests/Febe.Tests.Windows` 24 superate su 24. Le prove saltate sono quelle che vogliono Chromium e Xvfb in Linux + (interfaccia nel browser, browser vero), che girano solo nella CI. +- **Non verificato**: la CI completa non è ancora verde su tutti i rami dopo l'aggiornamento con `main`; l'immagine Docker non è stata costruita; le + prove d'interfaccia con Chromium (comprese quelle nuove della Dashboard) girano solo nella CI; nessun file HEIC, HEVC, + WMV o FLV vero è stato provato, solo i flussi di conformità e i file costruiti dalle prove; MVC non è uguale al bit + ai riferimenti e SVC è parziale; le schermate sono confrontate con i mockup a occhio. Niente su Instagram (regola 1). +- **Domande per Alberto**: + - i 5 secondi di grazia in Docker prima che lasciare la pagina del browser copi la sessione vanno bene (§16 domanda + 20)? + - i pesi dei tipi 16, 8, 4, 2, 1 di «Cosa scaricare prima» (proposta, da tarare con la simulazione)? + - le raccolte in evidenza subito dopo le storie nell'ordine predefinito (§16 domanda 19)? + - nella coda dei file basta il posto su otto al file più vecchio (nessun file aspetta per sempre) o serve un vero + minimo per tipo (oggi un tipo trovato dopo un arretrato più vecchio aspetta che finisca; §16 domanda 21)? + - un HEIC danneggiato ha solo la tessera neutra e non è mai segnato «File danneggiato o incompleto»: va bene? + - i due MP4 minuscoli di `tools/Febe.SitoDiProva/Risorse` sono stati generati una volta con ffmpeg: rifarli con lo + scrittore MP4 di casa o tenerli? + - la pagina `Attivita-e-arresti` del wiki va tolta o fatta rimandare a `Dashboard-e-arresti` alla prossima + pubblicazione della guida (`docs/guida/Sviluppo.md`, «La guida»). +- Il commit 34fe5e9 di `funzione/dashboard` ha un BOM all'inizio dell'oggetto (vedi `docs/decisioni.md`): si tiene. +- **Prossima tappa** dopo D1 (§15): **E1 Schema**, la migrazione `0003` con le tabelle dell'esportazione e le + impostazioni `esportazione.*`, senza cambi di comportamento; poi E2 (copie esterne, con la sua scheda nella + Dashboard), E3, E4, E5. + **17 novembre 2026: la sessione salvata cifrata, copiata a «Ho finito»** (#36, tappa S4, ramo `funzione/sessione-salvata`, unito in `main` con verifica verde). @@ -451,7 +533,7 @@ protezione di `main` sono in `docs/processo.md`. di un account (H1–H4, H6, H11). In alternativa la sonda (parte A). 2. **Prima sessione dal vivo** con il profilo Prudente su un profilo pubblico (parte B): già possibile per giro dei seguiti, controllo del profilo, storico e post singolo. Da guardare: i file in Libreria (H5, H7), «Tu» riconosciuto - (H10), nessun «formato non riconosciuto» in Attività. + (H10), nessun «formato non riconosciuto» nella Dashboard. 3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a icona e con lo schermo bloccato, C2 (installatore della 0.1.2 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore vero. @@ -491,7 +573,7 @@ protezione di `main` sono in `docs/processo.md`. - Nessuna di queste modifiche è stata provata con Instagram: la prima sessione dal vivo (parte B) dirà se i dati del primo schermo arrivano nel documento o con XHR, se i file video hanno l'audio (H5) e se si scaricano (H7). - I blocchi JSON dei documenti di Instagram non si sono mai visti (il HAR non aveva documenti): forma e ordine ignoti. - Le regole di testo di `segnali.json` ora li guardano uno per uno; un falso segnale si vedrebbe in Attività. + Le regole di testo di `segnali.json` ora li guardano uno per uno; un falso segnale si vedrebbe nella Dashboard. - Visualizzatore senza identificativo nell'indirizzo (le raccolte): un clic «avanti» che la pagina ignora non si vede, e il conteggio salverebbe un contenuto non mostrato; una foto che il sito lascia da sola fa restare indietro il conteggio. Da misurare quando i bersagli ci saranno. Con le storie l'indirizzo dice quale storia è a video, se diff --git a/docs/windows.md b/docs/windows.md index 85dd089..a40929f 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -72,7 +72,7 @@ Windows (ipotesi S3, da confermare: vedi sotto). - Quando non ti serve **non è chiusa né ridotta a icona**: è aperta ma spostata fuori dallo schermo, perché il browser deve continuare a caricare e scorrere anche quando non lo guardi (ipotesi S2). Non ha un pulsante nella barra delle applicazioni. -- La porti in primo piano dalla finestra di Febe: «Apri il browser» (Attività, striscia rossa di un arresto) o +- La porti in primo piano dalla finestra di Febe: «Apri il browser» (Dashboard, striscia rossa di un arresto) o «Portalo in primo piano» (Collegamento). - **Mentre la usi il motore resta fermo.** Quando hai finito, chiudila (la X o «Ho finito» nel Collegamento): torna fuori vista e il motore può ripartire. Dopo una verifica, «Riprendi» si accende solo dopo che hai usato il browser. @@ -200,8 +200,8 @@ tentativo, quel tentativo lo trova già in funzione e non ne apre un secondo. Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve: -- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di - Attività. La parte che non dipende dall'installazione è già una prova automatica su Windows (sotto). +- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima della + Dashboard. La parte che non dipende dall'installazione è già una prova automatica su Windows (sotto). - **S2** — la stessa sessione con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato; poi, se serve, `composizione` e `edge`. - **S3** — accesso a mano, «Esci», riapertura, riavvio di Windows: il collegamento deve restare. diff --git a/src/Febe.App/LiveBrowserPreview.cs b/src/Febe.App/LiveBrowserPreview.cs index 862f57f..624a9ba 100644 --- a/src/Febe.App/LiveBrowserPreview.cs +++ b/src/Febe.App/LiveBrowserPreview.cs @@ -6,13 +6,13 @@ using Febe.Web.Engine; namespace Febe.App; /// -/// Preview of the browser for the Attività page (mockup 06): one still frame taken with Page.captureScreenshot when the -/// page asks, at most every few seconds. Reading what the browser shows is not an action toward the site. On the empty -/// rest page there is nothing to show. The same in both shells. +/// Preview of the browser for the Dashboard (spec §7.9, mockup 06): one still frame taken with Page.captureScreenshot +/// when the page asks, at most one a second however many pages ask. Reading what the browser shows is not an action +/// toward the site. On the empty rest page there is nothing to show. The same in both shells. /// public sealed class LiveBrowserPreview(IFebeBrowser browser, IClock clock) : IBrowserPreview { - private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(4); + private static readonly TimeSpan MinimumAge = TimeSpan.FromSeconds(1); private readonly SemaphoreSlim _gate = new(1, 1); private BrowserFrame? _last; diff --git a/src/Febe.Core/Alerts/AlertModels.cs b/src/Febe.Core/Alerts/AlertModels.cs index 90b36ac..10a97c8 100644 --- a/src/Febe.Core/Alerts/AlertModels.cs +++ b/src/Febe.Core/Alerts/AlertModels.cs @@ -94,7 +94,7 @@ public static class AlertEventCodes /// public static class AlertCatalog { - /// Codes shown in the «Avvisi» list of Attività: the alerts and the failed deliveries. + /// Codes shown in the «Avvisi» list of the Dashboard: the alerts and the failed deliveries. public static IReadOnlyList Codes { get; } = [ EngineEventCodes.ChallengeStop, @@ -193,7 +193,7 @@ public static class AlertCatalog /// /// The engine's sentence without its first words when they repeat the title: «Instagram ha chiesto di rallentare - /// (segnale http-429). Ho chiuso…» becomes «Ho chiuso…» (the signal stays in the stops of Attività). + /// (segnale http-429). Ho chiuso…» becomes «Ho chiuso…» (the signal stays in the stops of the Dashboard). /// private static string WithoutTitle(string message, string title) { diff --git a/src/Febe.Core/Alerts/AlertService.cs b/src/Febe.Core/Alerts/AlertService.cs index cf40aec..9a76a2e 100644 --- a/src/Febe.Core/Alerts/AlertService.cs +++ b/src/Febe.Core/Alerts/AlertService.cs @@ -43,7 +43,7 @@ public sealed record AlertServiceOptions /// stops and resumes, backfills completed, unknown formats, suspended recipes) and checks the free space of the /// library and the Data folder; each alert goes to the channels switched on in Impostazioni ▸ Notifiche (Windows /// notification on the desktop, Telegram when token and chat are set). The red strip of the interface is not its -/// job: the engine snapshot always shows a stop, and every alert is a line of the «Avvisi» list in Attività. +/// job: the engine snapshot always shows a stop, and every alert is a line of the «Avvisi» list of the Dashboard. /// /// Same kind and key within : not sent again (the times are kept in the /// settings, so a restart does not send it again either). diff --git a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs index 3467753..cb3a838 100644 --- a/src/Febe.Core/Collection/Downloads/DownloadQueue.cs +++ b/src/Febe.Core/Collection/Downloads/DownloadQueue.cs @@ -74,6 +74,16 @@ public sealed record DownloadOptions /// How many pending files are read from the database at a time. public int BatchSize { get; init; } = 200; + /// + /// «Cosa scaricare prima» never makes a file wait for ever (spec §6.5, §7.2): one file in this many is the one that + /// has waited longest, whatever its kind; the others follow the order. Every file in the queue becomes the longest + /// waiting sooner or later (new files are always younger), so every file is downloaded in the end, even when the + /// daily data budget ends each day before the queue does. It is not a share per kind: the place goes to the oldest + /// file of the whole queue, so a kind found after an older backlog of another kind waits until that backlog is done + /// (taggati found after thousands of older posts come after them). 0 or 1: the order alone. + /// + public int LongestWaitingShare { get; init; } = 8; + /// When idle, how long to wait before looking at the database again (a ends it earlier). public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1); } @@ -242,10 +252,15 @@ public sealed class DownloadQueue var now = _clock.Now; var waiting = _retryAt.Count(r => r.Value > now); var window = (int)Math.Min(10_000L, (long)_options.BatchSize + attempted.Count + waiting); - var batch = (await _storage.Media.ListPendingDownloadsAsync(window, ct).ConfigureAwait(false)) - .Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now)) - .Take(_options.BatchSize) - .ToList(); + // «Cosa scaricare prima» (spec §6.5, §7.2), general and per account, read at every batch so that a change + // counts from the next one; one file in LongestWaitingShare is the longest waiting, whatever its kind. + var order = await DownloadOrder.LoadQueueOrderAsync(_storage, ct).ConfigureAwait(false); + bool Ready(PendingDownload p) => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now); + var ordered = (await _storage.Media.ListPendingDownloadsAsync(window, order, ct).ConfigureAwait(false)).Where(Ready).ToList(); + var longest = _options.LongestWaitingShare > 1 && ordered.Count > 0 + ? (await _storage.Media.ListLongestWaitingDownloadsAsync(window, ct).ConfigureAwait(false)).Where(Ready).ToList() + : []; + var batch = ComposeBatch(ordered, longest, _options.BatchSize, _options.LongestWaitingShare); if (batch.Count == 0) { break; @@ -269,6 +284,51 @@ public sealed class DownloadQueue return tally.ToReport(); } + /// + /// A batch of at most files (spec §6.5, §7.2): in the order of «Cosa scaricare prima», except + /// that every -th place goes to the file that has waited longest and is not in the batch yet, + /// whatever its kind. A file is never taken twice; when one list runs out the other fills the places. + /// + /// The waiting files in the order of «Cosa scaricare prima». + /// The same files, the longest waiting first. + /// Places in the batch. + /// One place in this many for the longest waiting; 0 or 1 for the order alone. + internal static List ComposeBatch(IReadOnlyList ordered, IReadOnlyList longest, int size, int share) + { + var batch = new List(Math.Max(0, Math.Min(size, ordered.Count + longest.Count))); + var taken = new HashSet(); + int nextOrdered = 0, nextLongest = 0; + PendingDownload? Next(IReadOnlyList list, ref int index) + { + while (index < list.Count) + { + var candidate = list[index++]; + if (taken.Add(candidate.Media.Id)) + { + return candidate; + } + } + + return null; + } + + while (batch.Count < size) + { + var oldestTurn = share > 1 && batch.Count % share == share - 1; + var next = oldestTurn + ? Next(longest, ref nextLongest) ?? Next(ordered, ref nextOrdered) + : Next(ordered, ref nextOrdered) ?? Next(longest, ref nextLongest); + if (next is null) + { + break; + } + + batch.Add(next); + } + + return batch; + } + private bool IsDue(long mediaId, DateTimeOffset now) { if (!_retryAt.TryGetValue(mediaId, out var at)) diff --git a/src/Febe.Core/Collection/Readers/ReadMapping.cs b/src/Febe.Core/Collection/Readers/ReadMapping.cs index 318b442..40bda0a 100644 --- a/src/Febe.Core/Collection/Readers/ReadMapping.cs +++ b/src/Febe.Core/Collection/Readers/ReadMapping.cs @@ -26,6 +26,7 @@ public static class ReadMapping AuthorInstagramId = foreignAuthor ? item.Owner?.Id : null, DiscoveredAt = now, ExpiresAt = kind == EntryKind.Story ? item.ExpiresAt ?? item.TakenAt.AddHours(24) : null, + IsReel = kind == EntryKind.Post && item.IsReel, }; } diff --git a/src/Febe.Core/Collection/Readers/ReadModels.cs b/src/Febe.Core/Collection/Readers/ReadModels.cs index 702669a..6a2df60 100644 --- a/src/Febe.Core/Collection/Readers/ReadModels.cs +++ b/src/Febe.Core/Collection/Readers/ReadModels.cs @@ -90,9 +90,12 @@ public sealed record ContentItem /// Order of appearance in the response, from 0. public int Order { get; init; } + /// The response marks it as a reel, or it was found in the Reel tab (spec §7.2, «Cosa scaricare prima»). + public bool IsReel { get; init; } + private bool PrintMembers(StringBuilder builder) { - builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, Files = {Files.Count}, IsComplete = {IsComplete}"); + builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, IsReel = {IsReel}, Files = {Files.Count}, IsComplete = {IsComplete}"); return true; } } diff --git a/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs b/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs index 236c441..9f8d03c 100644 --- a/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs +++ b/src/Febe.Core/Collection/Readers/ReaderVocabulary.cs @@ -87,6 +87,12 @@ public sealed record ContentKeys /// Video duration in seconds (on the node or on the video version). public VocabularyKeys Duration { get; init; } = VocabularyKeys.None; + + /// The type of the content as the site names it (a text): a post is a reel when it is one of . + public VocabularyKeys ProductType { get; init; } = VocabularyKeys.None; + + /// The values of that mean «reel» (spec §7.2, «Cosa scaricare prima»). Empty: never told. + public IReadOnlyList ReelTypes { get; init; } = []; } /// Keys of one version of a file (one size of an image, one rendition of a video). @@ -356,6 +362,8 @@ public sealed record ReaderVocabulary Pinned = K(c.Pinned), ExpiresAt = K(c.ExpiresAt), Duration = K(c.Duration), + ProductType = K(c.ProductType), + ReelTypes = [.. (c.ReelTypes ?? []).Where(v => !string.IsNullOrWhiteSpace(v)).Select(v => v.Trim()).Distinct(StringComparer.Ordinal)], }, Version = new VersionKeys { Url = K(v.Url), Width = K(v.Width), Height = K(v.Height), HasAudio = K(v.HasAudio) }, Profile = new ProfileKeys @@ -448,6 +456,10 @@ internal sealed class ContentDto public List? ExpiresAt { get; set; } public List? Duration { get; set; } + + public List? ProductType { get; set; } + + public List? ReelTypes { get; set; } } internal sealed class VersionDto diff --git a/src/Febe.Core/Collection/Readers/ShapeReader.cs b/src/Febe.Core/Collection/Readers/ShapeReader.cs index d8a76c3..ffc2662 100644 --- a/src/Febe.Core/Collection/Readers/ShapeReader.cs +++ b/src/Febe.Core/Collection/Readers/ShapeReader.cs @@ -335,6 +335,8 @@ public sealed class ShapeReader IsComplete = complete, HighlightId = highlightId, Order = walk.Contents.Count, + IsReel = _v.Content.ReelTypes.Count > 0 && AsText(Get(_v.Content.ProductType, node)) is { } type + && _v.Content.ReelTypes.Contains(type, StringComparer.Ordinal), }; } diff --git a/src/Febe.Core/Collection/Recipes/CollectionWriter.cs b/src/Febe.Core/Collection/Recipes/CollectionWriter.cs index a76e621..5d7de3b 100644 --- a/src/Febe.Core/Collection/Recipes/CollectionWriter.cs +++ b/src/Febe.Core/Collection/Recipes/CollectionWriter.cs @@ -158,6 +158,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) if (known is not null) { await RefreshFilesAsync(known, item, fromHighlight: false, ct).ConfigureAwait(false); + known = await MarkReelAsync(known, item, ct).ConfigureAwait(false); return (new SaveResult(SaveOutcome.Known, known), 0, 0); } @@ -175,6 +176,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) InstagramId = item.Id, Code = imported.Code ?? item.Code, Caption = imported.Caption ?? item.Caption, + IsReel = imported.IsReel || (kind == EntryKind.Post && item.IsReel), }; await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false); return (new SaveResult(SaveOutcome.Enriched, enriched), 0, 0); @@ -186,7 +188,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false); if (!added.Created) { - return (new SaveResult(SaveOutcome.Known, added.Stored.Entry), 0, 0); + return (new SaveResult(SaveOutcome.Known, await MarkReelAsync(added.Stored.Entry, item, ct).ConfigureAwait(false)), 0, 0); } if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged) @@ -197,6 +199,22 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) return (new SaveResult(SaveOutcome.Created, added.Stored.Entry), media.Count(m => m.State == MediaState.ToDownload), media.Count(m => m.State == MediaState.Skipped)); } + /// + /// A known post that the content now marks as a reel (the Reel tab, or the response) becomes one, for the queue of + /// the files (spec §7.2); a reel never goes back to a plain post. Returns the entry as stored. + /// + private async Task MarkReelAsync(Entry known, ContentItem item, CancellationToken ct) + { + if (known.Kind != EntryKind.Post || known.IsReel || !item.IsReel || known.State == EntryState.Deleted) + { + return known; + } + + // Only the flag is written: the queue may be changing the state of the same entry at this moment. + await storage.Entries.MarkReelAsync(known.Id, ct).ConfigureAwait(false); + return known with { IsReel = true }; + } + /// /// Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256). A /// picture already known whose file expired or failed takes the fresh address just read: the identity is the path @@ -278,6 +296,8 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock) await storage.Entries.UpdateAsync(latest with { Code = latest.Code ?? item.Code, Caption = latest.Caption ?? item.Caption }, ct).ConfigureAwait(false); } + await MarkReelAsync(entry, item, ct).ConfigureAwait(false); + return changed; } diff --git a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs index 24adad9..27ca44f 100644 --- a/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs +++ b/src/Febe.Core/Collection/Recipes/RecipeRunner.Profile.cs @@ -20,6 +20,9 @@ public sealed partial class RecipeRunner public bool IsGrid => TabTarget is null; + /// The Reel tab: every post it gives is a reel (). + public bool MarksReels => TabTarget == SiteTargets.ProfileTabReels; + /// The grid and the reels come newest first (pinned posts aside); the order of tagged posts is not known. public bool IsChronological => Kind != EntryKind.Tagged; @@ -434,7 +437,7 @@ public sealed partial class RecipeRunner run.Finished = true; if (walk.IsGrid) { - // «Storico completato» in Attività, and the new state of the account, are the engine's: one line per + // «Storico completato» in the Dashboard, and the new state of the account, are the engine's: one line per // history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished). await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false); await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false); @@ -566,7 +569,9 @@ public sealed partial class RecipeRunner } } - var saved = await Writer.SaveAsync(account, item, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false); + // What the Reel tab gives is a reel, whatever the response says (spec §7.2, «Cosa scaricare prima»). + var content = walk.MarksReels && !item.IsReel ? item with { IsReel = true } : item; + var saved = await Writer.SaveAsync(account, content, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false); if (saved.Outcome == SaveOutcome.Created) { run.NewEntries++; diff --git a/src/Febe.Core/Config/lettori.instagram.json b/src/Febe.Core/Config/lettori.instagram.json index e42e9b3..d798e87 100644 --- a/src/Febe.Core/Config/lettori.instagram.json +++ b/src/Febe.Core/Config/lettori.instagram.json @@ -3,7 +3,7 @@ "status": "confermato", "note": "Vocabolario dei lettori per Instagram, compilato il 25 ottobre 2026 sulle risposte reali che il browser di Alberto ha ricevuto il 21 ottobre (file HAR) e completato il 12 novembre con quelle del secondo HAR (scheda del profilo, post del profilo, raccolte del profilo, storie), ripulite con «febe-sonda ripulisci» e conservate in tests/Febe.Tests/campioni/instagram (regola 10). Ogni concetto dice da quali campioni viene; quelli senza riscontro restano vuoti o sono segnati come indizio. I dati di storie e raccolte arrivano come «text/javascript», non come JSON dichiarato: la cattura li legge lo stesso (DataResponses). «viewer»: xdt_viewer.user, visto in raccolta-in-evidenza, descrive l'account collegato con il solo identificativo, senza nome; nel blocco incorporato nella pagina iniziale (vassoio-storie, 12 novembre) ha anche username e profile_pic_url, e il lettore lo legge come Viewer (H10, da provare con la raccolta vera).", "content": { - "note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video).", + "note": "Un contenuto (XDTMediaDict): post, reel, storia o contenuto di una raccolta. Visti in post-video (/api/v1/media/…/info/), raccolta-in-evidenza, raccolta-pagina-successiva, post-del-profilo (reel e serie) e storie-di-un-profilo. Le griglie delle schede Reel e Con tag (reel-del-profilo, con-tag) sono anteprime senza taken_at né video_versions: non sono contenuti, il contenuto intero arriva da post-del-profilo o da /api/v1/media/…/info/. «user» dei contenuti di una storia ha solo l'identificativo, senza nome: l'autore si eredita dalla raccolta o dalla serie di storie che li contiene. La didascalia è un oggetto con il testo in «text». Serie (carousel_media, media_type 8): i figli sono contenuti con le loro image_versions2 e video_versions, visti in post-del-profilo (6 foto) e serie-con-video (20 figli, uno video). product_type dice il tipo del contenuto: «clips» per i reel (post-video, post-del-profilo, reel-del-profilo, con-tag), «feed», «carousel_container», «carousel_item» e «story» per gli altri; serve solo a «Cosa scaricare prima» (un post segnato «clips» conta come reel nella coda dei file).", "id": ["pk"], "code": ["code"], "takenAt": ["taken_at"], @@ -15,7 +15,9 @@ "owner": ["user", "owner"], "pinned": [], "expiresAt": ["expiring_at"], - "duration": ["video_duration"] + "duration": ["video_duration"], + "productType": ["product_type"], + "reelTypes": ["clips"] }, "version": { "note": "Una versione: candidates di image_versions2 (url, width, height, da 10 a 14 per contenuto) e video_versions (type 101, 102, 103 e url; dimensioni solo nei post, non nelle storie). Se il video ha l'audio lo dice il contenuto (has_audio), non la versione: hasAudio resta vuoto e ogni versione conta come file completo (H5 da confermare scaricando).", diff --git a/src/Febe.Core/Domain/Account.cs b/src/Febe.Core/Domain/Account.cs index 065f590..3106649 100644 --- a/src/Febe.Core/Domain/Account.cs +++ b/src/Febe.Core/Domain/Account.cs @@ -119,6 +119,13 @@ public sealed record Account public AccountLimits Limits { get; init; } = new(); + /// + /// «Cosa scaricare prima» of this account (spec §4.4, §7.2, tappa D1): the stored text of its own order (the Italian + /// names of the five kinds, read by Febe.Core.Engine.DownloadOrder.Parse). Null: «Come le impostazioni + /// generali». + /// + public string? DownloadOrder { get; init; } + /// /// Folder of the account. Null means the default <Libreria>/<username>; a relative path is relative /// to the library (a renamed account keeps its old folder this way); an absolute path may be outside the library. diff --git a/src/Febe.Core/Domain/DownloadKind.cs b/src/Febe.Core/Domain/DownloadKind.cs new file mode 100644 index 0000000..b483d26 --- /dev/null +++ b/src/Febe.Core/Domain/DownloadKind.cs @@ -0,0 +1,23 @@ +namespace Febe.Core.Domain; + +/// +/// A type of «Cosa scaricare prima» (spec §7.2, tappa D1): the kinds of recipes of §6.3, grouped as Alberto names them. +/// The order of the kinds is Febe.Core.Engine.DownloadOrder. +/// +public enum DownloadKind +{ + /// «Storie»: Storie di un account. + Stories, + + /// «Evidenza»: Raccolta in evidenza. + Highlights, + + /// «Post»: Controllo del profilo and Storico, profile pictures included. + Posts, + + /// «Reel»: Reel, and in the queue the posts Febe knows to be reels (). + Reels, + + /// «Taggati»: Taggati. + Tagged, +} diff --git a/src/Febe.Core/Domain/Entry.cs b/src/Febe.Core/Domain/Entry.cs index 2149591..02a13cc 100644 --- a/src/Febe.Core/Domain/Entry.cs +++ b/src/Febe.Core/Domain/Entry.cs @@ -50,6 +50,13 @@ public sealed record Entry /// For stories: when the story stops being available on the site (downloads give them precedence). public DateTimeOffset? ExpiresAt { get; init; } + /// + /// A post that Febe knows to be a reel (spec §7.2, tappa D1): found in the Reel tab, or marked so in the response. + /// Only for ; once known it stays (the store never clears it). It weighs only on the queue of the files («Cosa + /// scaricare prima»): a reel is a post everywhere else. + /// + public bool IsReel { get; init; } + /// The value of the {codice} placeholder (spec §4.3) for this entry. /// SHA-256 of the file, needed for profile pictures (first eight hex digits). public string NameCode(string? sha256 = null) => Kind switch diff --git a/src/Febe.Core/Domain/Media.cs b/src/Febe.Core/Domain/Media.cs index 10b0a0a..9ca6613 100644 --- a/src/Febe.Core/Domain/Media.cs +++ b/src/Febe.Core/Domain/Media.cs @@ -76,7 +76,11 @@ public sealed record Media public sealed record MediaLocation(Media Media, Entry Entry, string Username); /// A file waiting for the download queue (spec §6.5), with what the queue needs to order it. -public sealed record PendingDownload(Media Media, long AccountId, EntryKind Kind, DateTimeOffset PublishedAt, DateTimeOffset? ExpiresAt); +public sealed record PendingDownload(Media Media, long AccountId, EntryKind Kind, DateTimeOffset PublishedAt, DateTimeOffset? ExpiresAt) +{ + /// The entry is a post Febe knows to be a reel (): «Reel» in «Cosa scaricare prima». + public bool IsReel { get; init; } +} /// What the safe writer and the hashing produced for a file now on disk. /// Path relative to the account folder, '/' separated. diff --git a/src/Febe.Core/Engine/DownloadOrder.cs b/src/Febe.Core/Engine/DownloadOrder.cs new file mode 100644 index 0000000..c360b7a --- /dev/null +++ b/src/Febe.Core/Engine/DownloadOrder.cs @@ -0,0 +1,171 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Engine; + +/// +/// «Cosa scaricare prima» (spec §7.2, tappa D1): an order of the five kinds, stored in (general) +/// or in (an account's own) as their Italian names separated by commas. It weighs the +/// next visit after the Giro dei seguiti (the weight of a kind is , multiplied by the weight of the +/// account) and the order of the queue of the files (spec §6.5). It never adds a visit, never brings one forward and +/// never makes the order fixed: it only weighs the choices the engine already makes among the work that is due and +/// allowed. +/// +public sealed class DownloadOrder +{ + /// The general order (Impostazioni → Limiti e comportamento). + public const string SettingKey = "scaricamento.ordine"; + + /// The weights of the positions, first to last (spec §7.2 table, «Peso di un tipo nella scelta»). + public static readonly IReadOnlyList Weights = [16, 8, 4, 2, 1]; + + private static readonly (DownloadKind Kind, string Name)[] Names = + [ + (DownloadKind.Stories, "storie"), + (DownloadKind.Highlights, "evidenza"), + (DownloadKind.Posts, "post"), + (DownloadKind.Reels, "reel"), + (DownloadKind.Tagged, "taggati"), + ]; + + private DownloadOrder(IReadOnlyList kinds) => Kinds = kinds; + + /// Storie, evidenza, post, reel, taggati (spec §7.2, §16 question 19). + public static DownloadOrder Default { get; } = new([DownloadKind.Stories, DownloadKind.Highlights, DownloadKind.Posts, DownloadKind.Reels, DownloadKind.Tagged]); + + /// The five kinds, first to last. + public IReadOnlyList Kinds { get; } + + /// True when this is the order of . + public bool IsDefault => Kinds.SequenceEqual(Default.Kinds); + + /// The Italian name of a kind, as stored and as the interface sends it. + public static string NameOf(DownloadKind kind) => Names.First(n => n.Kind == kind).Name; + + /// The names of the five kinds, first to last, as the interface shows them. + public IReadOnlyList ToNames() => [.. Kinds.Select(NameOf)]; + + /// + /// Reads a stored order. Unknown names are left out, a kind named twice counts once and the kinds missing are added + /// at the end in the default order, so any text gives the five kinds; null or empty gives . + /// + public static DownloadOrder Parse(string? text) + { + if (string.IsNullOrWhiteSpace(text)) + { + return Default; + } + + var kinds = new List(); + foreach (var part in text.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + foreach (var (kind, name) in Names) + { + if (string.Equals(name, part, StringComparison.OrdinalIgnoreCase) && !kinds.Contains(kind)) + { + kinds.Add(kind); + } + } + } + + kinds.AddRange(Default.Kinds.Where(k => !kinds.Contains(k))); + return new DownloadOrder(kinds); + } + + /// Builds an order from the names the interface sends; the same rules as . + public static DownloadOrder From(IEnumerable names) => Parse(string.Join(',', names)); + + /// The stored text: the five names, comma separated. + public override string ToString() => string.Join(',', Kinds.Select(NameOf)); + + /// + /// The order that applies to an account: its own when it has one (spec §4.4, «Un ordine suo»), otherwise + /// («Come le impostazioni generali»). + /// + public static DownloadOrder For(Account? account, DownloadOrder general) + { + ArgumentNullException.ThrowIfNull(general); + return account?.DownloadOrder is { } own && !string.IsNullOrWhiteSpace(own) ? Parse(own) : general; + } + + /// 0 for the first kind, 4 for the last. + public int Position(DownloadKind kind) + { + for (var i = 0; i < Kinds.Count; i++) + { + if (Kinds[i] == kind) + { + return i; + } + } + + return Kinds.Count - 1; + } + + /// 16, 8, 4, 2 or 1 by the position of the kind. + public double Weight(DownloadKind kind) => Weights[Position(kind)]; + + /// + /// The kind of a task of the engine (spec §7.2); null for the work that no kind weighs: the Giro dei seguiti, which + /// stays first, and the reading of the following list. + /// + public static DownloadKind? KindOf(EngineTaskKind task) => task switch + { + EngineTaskKind.AccountStories => DownloadKind.Stories, + EngineTaskKind.HighlightCheck => DownloadKind.Highlights, + EngineTaskKind.ProfileCheck or EngineTaskKind.Backfill or EngineTaskKind.SinglePost => DownloadKind.Posts, + EngineTaskKind.ReelsCheck => DownloadKind.Reels, + EngineTaskKind.TaggedCheck => DownloadKind.Tagged, + _ => null, + }; + + /// + /// The kind of a file in the queue (spec §6.5, §7.2): a post counts as a reel when Febe knows that it is one + /// (), otherwise as a post; profile pictures go with the posts. + /// + public static DownloadKind KindOf(EntryKind entry, bool isReel = false) => entry switch + { + EntryKind.Story => DownloadKind.Stories, + EntryKind.Highlight => DownloadKind.Highlights, + EntryKind.Tagged => DownloadKind.Tagged, + EntryKind.Post when isReel => DownloadKind.Reels, + _ => DownloadKind.Posts, + }; + + /// The general order stored in the settings. + public static async Task LoadAsync(ISettingsStore settings, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + return Parse(await settings.GetAsync(SettingKey, ct).ConfigureAwait(false)); + } + + /// Stores the general order; the default is stored as no value (the setting is absent). + public static Task SaveAsync(ISettingsStore settings, DownloadOrder order, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(settings); + ArgumentNullException.ThrowIfNull(order); + return settings.SetAsync(SettingKey, order.IsDefault ? null : order.ToString(), ct); + } + + /// + /// The order of the queue of the files (spec §6.5): the general order and the own order of each account that has + /// one, read fresh so that a change counts from the next batch. + /// + public static async Task LoadQueueOrderAsync(IFebeStorage storage, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(storage); + var general = await LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var own = await storage.Accounts.ListDownloadOrdersAsync(ct).ConfigureAwait(false); + var accounts = new Dictionary>(own.Count); + foreach (var (accountId, text) in own) + { + var order = Parse(text); + if (!order.Kinds.SequenceEqual(general.Kinds)) + { + accounts[accountId] = order.Kinds; + } + } + + return new DownloadQueueOrder(general.Kinds, accounts); + } +} diff --git a/src/Febe.Core/Engine/EngineHost.cs b/src/Febe.Core/Engine/EngineHost.cs index 53171ea..0e0fedd 100644 --- a/src/Febe.Core/Engine/EngineHost.cs +++ b/src/Febe.Core/Engine/EngineHost.cs @@ -66,7 +66,7 @@ public sealed class EngineHost : IAsyncDisposable public EngineServices Services => _s; - /// What the interface shows of the engine (Attività, sidebar, account settings panel). + /// What the interface shows of the engine (Dashboard, sidebar, account settings panel). public IEngineMonitor Monitor { get; } /// Recipes suspended after repeated unrecognized formats, with when. diff --git a/src/Febe.Core/Engine/Monitor.cs b/src/Febe.Core/Engine/Monitor.cs index b50be18..cb0360a 100644 --- a/src/Febe.Core/Engine/Monitor.cs +++ b/src/Febe.Core/Engine/Monitor.cs @@ -524,7 +524,16 @@ public sealed class EngineMonitor : IEngineMonitor var recent = _host.RecentActions(10); if (recent.Count > 0) { - views.AddRange(recent.Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false))); + views.AddRange(recent.Select(r => new RecentActionView( + r.At, + ItalianText.Clock(r.At, zone), + r.Title, + r.Detail, + r.Badge, + false, + r.NewEntries > 0 ? r.AccountId : null, // none for the Giro dei seguiti: what arrived of every account + r.NewEntries > 0 ? r.StartedAt : null, + r.NewEntries))); return views; } diff --git a/src/Febe.Core/Engine/MonitorModels.cs b/src/Febe.Core/Engine/MonitorModels.cs index 972286a..2c0c532 100644 --- a/src/Febe.Core/Engine/MonitorModels.cs +++ b/src/Febe.Core/Engine/MonitorModels.cs @@ -136,8 +136,22 @@ public sealed record BudgetView( /// The engine is stopped or paused. public sealed record QueueItem(long TaskId, EngineTaskKind Kind, long? AccountId, string Title, string Detail, DateTimeOffset? Around, string When, bool IsManual, bool Suspended); -/// A line of «Appena fatto». -public sealed record RecentActionView(DateTimeOffset At, string Time, string Title, string Detail, string? Badge, bool InProgress); +/// A line of the history of the Dashboard («Appena fatto»). +/// Account of the recipe, when it has one and saved something: with and +/// it tells the page which entries arrived, for their thumbnails (spec §7.9, tappa D1). +/// When the recipe started, when it saved something; with no account (the Giro dei seguiti) the +/// thumbnails are what arrived of every account in that time. +/// Entries saved by the recipe. +public sealed record RecentActionView( + DateTimeOffset At, + string Time, + string Title, + string Detail, + string? Badge, + bool InProgress, + long? AccountId = null, + DateTimeOffset? From = null, + int NewEntries = 0); /// A recipe suspended after repeated unrecognized formats. public sealed record SuspendedRecipeView(RecipeKind Recipe, string Name, DateTimeOffset Since); diff --git a/src/Febe.Core/Engine/RecentActions.cs b/src/Febe.Core/Engine/RecentActions.cs index 53d6d7c..d70c92a 100644 --- a/src/Febe.Core/Engine/RecentActions.cs +++ b/src/Febe.Core/Engine/RecentActions.cs @@ -8,6 +8,8 @@ namespace Febe.Core.Engine; /// «2 storie nuove», «Nessuna novità». /// How it ended. /// New entries found. +/// When it started: the entries of the account discovered from then to are +/// the ones it saved (thumbnails of the Dashboard, spec §7.9). public sealed record RecentAction( DateTimeOffset At, RecipeKind Recipe, @@ -15,7 +17,8 @@ public sealed record RecentAction( string Title, string Detail, RecipeStatus Status, - int NewEntries) + int NewEntries, + DateTimeOffset? StartedAt = null) { /// Short label of the outcome for a badge («Scaricato», «Rimandato»...); null when nothing to say. public string? Badge => Status switch diff --git a/src/Febe.Core/Engine/SessionComposer.cs b/src/Febe.Core/Engine/SessionComposer.cs index 92136d9..5c0abf8 100644 --- a/src/Febe.Core/Engine/SessionComposer.cs +++ b/src/Febe.Core/Engine/SessionComposer.cs @@ -84,23 +84,39 @@ internal sealed class SessionComposer await RunSweepAsync(sweepTask, accounts, state, ct).ConfigureAwait(false); } - // 3. Stories: flagged by the stories bar first, then the due ones (visits of profiles not followed included). + // 3. The work that is due: stories flagged by the stories bar first, then, drawn one after the other with the + // weight of the account times the weight of its kind in «Cosa scaricare prima» (spec §7.2, tappa D1), the other + // stories (visits of profiles not followed included) and, except in a light session, the expired profile checks, + // highlight collections and other planned work. The order weighs the choices, it does not add any. if (!Over(state, ct)) { var now = Clock.Now; var window = await WindowLengthAsync(now, ct).ConfigureAwait(false); + var order = await DownloadOrder.LoadAsync(Store.Settings, ct).ConfigureAwait(false); due = await Store.Tasks.PeekDueAsync(now, 1000, ct).ConfigureAwait(false); await RunManualTasksAsync(due, accounts, state, ct).ConfigureAwait(false); var storyWork = due.Where(t => !t.IsManual && IsStoryWork(t, accounts, now)).ToList(); var flagged = storyWork.Where(t => t.Priority >= Options.FlaggedStoriesPriority); - var rest = storyWork.Where(t => t.Priority < Options.FlaggedStoriesPriority); - foreach (var task in Weighted(flagged, accounts, now, window).Concat(Weighted(rest, accounts, now, window))) + var rest = storyWork.Where(t => t.Priority < Options.FlaggedStoriesPriority).ToList(); + var other = light + ? [] + : due.Where(t => !t.IsManual + && t.Kind is not (EngineTaskKind.FollowingSweep or EngineTaskKind.Backfill or EngineTaskKind.AccountStories) + && !storyWork.Contains(t)).ToList(); + var storyIds = rest.Select(t => t.Id).ToHashSet(); + foreach (var task in Weighted(flagged, accounts, now, window, order).Concat(Weighted(rest.Concat(other), accounts, now, window, order))) { if (Over(state, ct)) { break; } + // A profile already opened in this session is not opened again for the other work: it waits for the next one. + if (!storyIds.Contains(task.Id) && task.Priority < Options.FlaggedStoriesPriority && task.AccountId is { } visited && state.Visited.Contains(visited)) + { + continue; + } + await RunScheduledAsync(task, accounts, state, ct).ConfigureAwait(false); } @@ -133,28 +149,7 @@ internal sealed class SessionComposer } } - // 4. Expired profile checks, highlight collections and other planned work. - if (!light && !Over(state, ct)) - { - var now = Clock.Now; - var window = await WindowLengthAsync(now, ct).ConfigureAwait(false); - due = await Store.Tasks.PeekDueAsync(now, 1000, ct).ConfigureAwait(false); - await RunManualTasksAsync(due, accounts, state, ct).ConfigureAwait(false); - var other = due.Where(t => !t.IsManual - && t.Kind is not (EngineTaskKind.FollowingSweep or EngineTaskKind.Backfill or EngineTaskKind.AccountStories) - && !(t.AccountId is { } id && state.Visited.Contains(id))); - foreach (var task in Weighted(other, accounts, now, window)) - { - if (Over(state, ct)) - { - break; - } - - await RunScheduledAsync(task, accounts, state, ct).ConfigureAwait(false); - } - } - - // 5. A few pages of history on one account. + // 4. A few pages of history on one account. if (!light && !Over(state, ct)) { await RunBackfillAsync(state, ct).ConfigureAwait(false); @@ -470,21 +465,27 @@ internal sealed class SessionComposer && (account.NextStoriesCheckAt is null || account.NextStoriesCheckAt <= now); } - private IEnumerable Weighted(IEnumerable tasks, Dictionary accounts, DateTimeOffset now, TimeSpan window) + private IEnumerable Weighted(IEnumerable tasks, Dictionary accounts, DateTimeOffset now, TimeSpan window, DownloadOrder order) { var items = new List<(EngineTask, double)>(); foreach (var task in tasks) { - if (task.AccountId is { } id && accounts.TryGetValue(id, out var account)) + // The visit of a profile not followed whose stories are due is story work (spec §7.2): it weighs as stories. + var kind = task.Kind == EngineTaskKind.ProfileCheck && IsStoryWork(task, accounts, now) + ? DownloadKind.Stories + : DownloadOrder.KindOf(task.Kind); + var owner = task.AccountId is { } ownerId ? accounts.GetValueOrDefault(ownerId) : null; + var kindWeight = kind is { } k ? DownloadOrder.For(owner, order).Weight(k) : 1; + if (owner is { } account) { var interval = task.Kind == EngineTaskKind.AccountStories ? CheckPolicy.StoryInterval(account, window, Options.MinimumStoryChecksPerDay) : VisitInterval(account, window); - items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval))); + items.Add((task, CheckPolicy.SelectionWeight(account, now - task.DueAt, interval) * kindWeight)); } else { - items.Add((task, 2)); + items.Add((task, 2 * kindWeight)); } } @@ -907,6 +908,7 @@ internal sealed class SessionComposer } state.Recipes++; + var startedAt = Clock.Now; _s.Runtime.Activity = ActivityText(request.Kind, account); _s.Events.Publish(EngineNotificationKind.ActivityChanged); RecipeOutcome outcome; @@ -946,7 +948,7 @@ internal sealed class SessionComposer await _queueGate.WaitAsync(CancellationToken.None).ConfigureAwait(false); try { - await ApplyOutcomeAsync(task, request, account, outcome, state).ConfigureAwait(false); + await ApplyOutcomeAsync(task, request, account, outcome, state, startedAt).ConfigureAwait(false); } finally { @@ -978,7 +980,7 @@ internal sealed class SessionComposer } } - private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state) + private async Task ApplyOutcomeAsync(EngineTask? task, RecipeRequest request, Account? account, RecipeOutcome outcome, SessionState state, DateTimeOffset startedAt) { // Bookkeeping always completes, even when the session has just been cancelled. Independent writes are queued // together (the single writer keeps their order and commits them in one transaction). @@ -1132,7 +1134,7 @@ internal sealed class SessionComposer } var (title, detail) = Describe(kind, account, outcome); - _recent.Add(new RecentAction(now, kind, account?.Id, title, detail, outcome.Status, outcome.NewEntries)); + _recent.Add(new RecentAction(now, kind, account?.Id, title, detail, outcome.Status, outcome.NewEntries, startedAt)); var severity = outcome.Status switch { RecipeStatus.Completed => outcome.NewEntries > 0 ? EventSeverity.Success : EventSeverity.Info, @@ -1225,7 +1227,7 @@ internal sealed class SessionComposer /// /// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one - /// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their + /// «storico completato» line of the Dashboard, which is also the alert (spec §13.3). The recipes write no line of their /// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account /// as it is now. /// @@ -1290,7 +1292,7 @@ internal sealed class SessionComposer await _s.Events.WriteAsync( EventSeverity.Error, EngineEventCodes.RecipeSuspended, - $"«{ItalianText.Capitalize(RecipeName(kind))}» è sospeso dopo {ItalianText.Number(threshold)} problemi di fila: Instagram potrebbe essere cambiato. Serve un campione nuovo con la modalità sonda; poi si riattiva da Attività.", + $"«{ItalianText.Capitalize(RecipeName(kind))}» è sospeso dopo {ItalianText.Number(threshold)} problemi di fila: Instagram potrebbe essere cambiato. Serve un campione nuovo con la modalità sonda; poi si riattiva dalla Dashboard («Riattiva»).", account?.Id, ct: ct).ConfigureAwait(false); } diff --git a/src/Febe.Core/Storage/DownloadQueueOrder.cs b/src/Febe.Core/Storage/DownloadQueueOrder.cs new file mode 100644 index 0000000..4979463 --- /dev/null +++ b/src/Febe.Core/Storage/DownloadQueueOrder.cs @@ -0,0 +1,15 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Storage; + +/// +/// The order of «Cosa scaricare prima» for the queue of the files (spec §6.5, §7.2): the five kinds first to last, in +/// general and for the accounts with an order of their own. Built by Febe.Core.Engine.DownloadOrder.LoadQueueOrderAsync. +/// +/// The general order. +/// The own order of an account, by its local key; the others follow . +public sealed record DownloadQueueOrder(IReadOnlyList General, IReadOnlyDictionary> Accounts) +{ + /// The order for every account: , no account with its own. + public static DownloadQueueOrder Everywhere(IReadOnlyList general) => new(general, new Dictionary>()); +} diff --git a/src/Febe.Core/Storage/IAccountStore.cs b/src/Febe.Core/Storage/IAccountStore.cs index db210a1..61b6a42 100644 --- a/src/Febe.Core/Storage/IAccountStore.cs +++ b/src/Febe.Core/Storage/IAccountStore.cs @@ -19,6 +19,12 @@ public interface IAccountStore /// All accounts, ordered by user name. Task> ListAsync(CancellationToken ct = default); + /// + /// The stored text of «Cosa scaricare prima» of the accounts that have an order of their own (spec §4.4), by local + /// key; the accounts that follow the general order are left out. Read by the queue of the files at every batch. + /// + Task> ListDownloadOrdersAsync(CancellationToken ct = default); + /// All accounts with their counts; «new» counts are entries discovered at or after . Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default); diff --git a/src/Febe.Core/Storage/IEngineStores.cs b/src/Febe.Core/Storage/IEngineStores.cs index 2facda6..26f004f 100644 --- a/src/Febe.Core/Storage/IEngineStores.cs +++ b/src/Febe.Core/Storage/IEngineStores.cs @@ -17,7 +17,7 @@ public interface ITaskStore /// Pending tasks due at : highest priority first, then earliest due, then oldest. Task> PeekDueAsync(DateTimeOffset now, int limit, CancellationToken ct = default); - /// Pending tasks by due time (the queue shown in Attività, «verso le»). + /// Pending tasks by due time (the queue shown in the Dashboard, «verso le»). Task> ListPendingAsync(int limit, CancellationToken ct = default); /// Pending → Running, atomically. False if the task was not pending any more. diff --git a/src/Febe.Core/Storage/IEntryStore.cs b/src/Febe.Core/Storage/IEntryStore.cs index 82900ff..bc61bbc 100644 --- a/src/Febe.Core/Storage/IEntryStore.cs +++ b/src/Febe.Core/Storage/IEntryStore.cs @@ -43,6 +43,12 @@ public interface IEntryStore /// Replaces the mutable fields of an entry (Instagram identifier, code, caption, author, state, dates). Task UpdateAsync(Entry entry, CancellationToken ct = default); + /// + /// Marks a post as a reel (spec §7.2, «Cosa scaricare prima»), writing only that flag; other kinds are left as they are. + /// A reel never goes back to a plain post: keeps the flag once set. + /// + Task MarkReelAsync(long entryId, CancellationToken ct = default); + Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default); /// Recomputes the state of an entry from its files (). @@ -60,6 +66,13 @@ public interface IEntryStore /// Entries of an account ordered by publication time, newest first (account tabs, collection pipeline). Task> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default); + /// + /// What a recipe saved (spec §7.9, thumbnails of the history of the Dashboard): the entries Febe downloaded (never + /// the imported ones) discovered in [from, to], of the account or, with null, of every account (the Giro dei + /// seguiti), newest first, at most , with how many there are in all. + /// + Task ListDiscoveredAsync(long? accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default); + /// Entries of (account, kind) discovered in [from, to): per-account daily backfill limit. Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default); @@ -68,9 +81,17 @@ public interface IEntryStore Task GetLibraryTotalsAsync(LibraryFilter filter, CancellationToken ct = default); - /// Entries per local calendar day in Alberto's zone, newest day first. - Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default); + /// + /// Entries (or, with , files) per local calendar day in Alberto's zone, newest day + /// first. A day without files is left out in that mode. In that mode the files are those in the library + /// (downloaded or imported), the tiles of «Tutte le foto», with «Foto» and «Video» only the files of that kind; their + /// total is the sum of the days (one pass over the files, not a second count). + /// + Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default); /// Tiles for given entries, in the given order (e.g. the items of a highlight collection). Task> GetTilesAsync(IReadOnlyList entryIds, CancellationToken ct = default); } + +/// Entries saved by a recipe: the first ones, newest first, and how many in all. +public sealed record ArrivedEntries(IReadOnlyList EntryIds, int Total); diff --git a/src/Febe.Core/Storage/IMediaStore.cs b/src/Febe.Core/Storage/IMediaStore.cs index 7ff7546..cd0d70b 100644 --- a/src/Febe.Core/Storage/IMediaStore.cs +++ b/src/Febe.Core/Storage/IMediaStore.cs @@ -30,6 +30,20 @@ public interface IMediaStore /// Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default); + /// + /// Files waiting to be downloaded in the order of «Cosa scaricare prima» (spec §6.5, §7.2): for each file the position + /// of its kind (a post Febe knows to be a reel counts as a reel) in the order of its account, which is the account's + /// own when it has one, else the general one; within a position the ones that expire first, then the oldest + /// waiting, then entry and position (stable). + /// + Task> ListPendingDownloadsAsync(int limit, DownloadQueueOrder order, CancellationToken ct = default); + + /// + /// Files waiting to be downloaded, the longest waiting first (discovery, then entry and position), whatever their + /// kind: the share of the queue that keeps the later kinds of «Cosa scaricare prima» from waiting for ever. + /// + Task> ListLongestWaitingDownloadsAsync(int limit, CancellationToken ct = default); + /// Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»). Task CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default); diff --git a/src/Febe.Core/Storage/LibraryQueries.cs b/src/Febe.Core/Storage/LibraryQueries.cs index c36bb49..b180f76 100644 --- a/src/Febe.Core/Storage/LibraryQueries.cs +++ b/src/Febe.Core/Storage/LibraryQueries.cs @@ -56,8 +56,25 @@ public sealed record LibraryFilter public IReadOnlyList? States { get; init; } } -/// Keyset position in the library order (publication time descending, then id descending). -public readonly record struct LibraryCursor(DateTimeOffset PublishedAt, long EntryId) +/// +/// «Raggruppa i post» or «Tutte le foto» (spec §4.6): one tile per entry, the default, or one tile per file of the +/// library (videos included), in the same order: publication of the entry, then position in the series. +/// +public enum MosaicMode +{ + /// «Raggruppa i post»: one tile per entry, with its cover. + Grouped, + + /// «Tutte le foto»: one tile per file present in the library (downloaded or imported). + Files, +} + +/// +/// Keyset position in the library order (publication time descending, then id descending). With +/// continues inside the entry: the window goes on after the file at +/// that position (0: before every file of the entry). ignores it. +/// +public readonly record struct LibraryCursor(DateTimeOffset PublishedAt, long EntryId, int Position = 0) { /// A cursor that starts the older direction at a given instant (to jump to a date). public static LibraryCursor At(DateTimeOffset instant) => new(instant, long.MaxValue); @@ -81,13 +98,18 @@ public sealed record LibraryQuery public LibraryDirection Direction { get; init; } = LibraryDirection.Older; + /// One tile per entry (default) or per file. + public MosaicMode Mode { get; init; } = MosaicMode.Grouped; + /// Maximum tiles (1–1000). public int Limit { get; init; } = 200; } /// -/// One tile of the mosaic: an entry with its cover file (the file at the lowest position). -/// is the thumbnail key. +/// One tile of the mosaic: an entry with its cover file (the file at the lowest position). With +/// the tile is one file of the entry: the cover columns describe that file and +/// is its position in the series (null for an entry tile). is the +/// thumbnail key. /// public sealed record LibraryTile( long EntryId, @@ -104,7 +126,8 @@ public sealed record LibraryTile( int? CoverHeight, TimeSpan? CoverDuration, string? CoverSha256, - bool CoverHasThumbnail); + bool CoverHasThumbnail, + int? FilePosition = null); /// /// A window of tiles, always in display order (newest first). and continue diff --git a/src/Febe.Data/Migrations/0002_ordine_scaricamento.sql b/src/Febe.Data/Migrations/0002_ordine_scaricamento.sql new file mode 100644 index 0000000..497a245 --- /dev/null +++ b/src/Febe.Data/Migrations/0002_ordine_scaricamento.sql @@ -0,0 +1,19 @@ +-- Febe, schema version 2: «Cosa scaricare prima» (tappa D1, issue #59; spec §7.2, §4.4, §8.3). +-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner. +-- Only columns and indexes are added: no behaviour changes for the data already stored. + +-- The order of «Cosa scaricare prima» of the account: the Italian names of the five kinds, comma separated +-- («storie,evidenza,post,reel,taggati»). NULL: «Come le impostazioni generali» (setting scaricamento.ordine). +ALTER TABLE account ADD COLUMN download_order TEXT; + +-- A post that Febe knows to be a reel (found in the Reel tab, or marked so in the response): it counts as a reel in +-- the queue of the files. 0 for every post stored before, which Febe cannot tell apart without asking the site again. +ALTER TABLE entry ADD COLUMN is_reel INTEGER NOT NULL DEFAULT 0 CHECK (is_reel IN (0, 1)); + +-- What a recipe saved, for the thumbnails of the history of the Dashboard (spec §7.9): the entries discovered in the +-- few minutes of the recipe, of one account or of all (the Giro dei seguiti), read by range whatever the library's size. +CREATE INDEX ix_entry_discovered ON entry (discovered_at); + +-- «Tutte le foto» (spec §4.6): the files of an entry that are in the library, and of which kind, read from the index +-- alone, so the counts of the days and the total of the files stay within the times of the scale test (200,000 entries). +CREATE INDEX ix_media_entry_files ON media (entry_id, state, kind); diff --git a/src/Febe.Data/Stores/AccountStore.cs b/src/Febe.Data/Stores/AccountStore.cs index 1dd8aaf..24de29f 100644 --- a/src/Febe.Data/Stores/AccountStore.cs +++ b/src/Febe.Data/Stores/AccountStore.cs @@ -12,9 +12,9 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore + "a.unreachable_reason, a.keep_updated, a.frequency, a.custom_post_interval_min, a.custom_story_interval_min, a.content_types, " + "a.history_depth, a.history_last_posts, a.history_from, a.backfill_posts_per_day, a.max_video_bytes, a.story_videos, a.folder, " + "a.backfill_cursor, a.backfill_completed_at, a.post_count, a.last_profile_check_at, a.next_profile_check_at, " - + "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at"; + + "a.last_stories_check_at, a.next_stories_check_at, a.notices, a.previous_username, a.renamed_at, a.format_unrecognized_at, a.added_at, a.download_order"; - internal const int ColumnCount = 34; + internal const int ColumnCount = 35; private static readonly string Visible = string.Join(", ", EntryStateRules.Visible.Select(s => $"'{s}'")); @@ -57,6 +57,7 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore RenamedAt = r.GetTimeOrNull(o + 31), FormatUnrecognizedAt = r.GetTimeOrNull(o + 32), AddedAt = r.GetTime(o + 33), + DownloadOrder = r.GetTextOrNull(o + 34), }; private static void Bind(SqliteCommand c, Account a) @@ -93,13 +94,16 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore .With("@previous_username", Sql.Text(a.PreviousUsername)) .With("@renamed_at", Sql.Time(a.RenamedAt)) .With("@format_unrecognized_at", Sql.Time(a.FormatUnrecognizedAt)) - .With("@added_at", Sql.Time(a.AddedAt)); + .With("@added_at", Sql.Time(a.AddedAt)) + .With("@download_order", Sql.Text(NormalizeOrder(a.DownloadOrder))); } private static string? Normalize(string? instagramId) => string.IsNullOrWhiteSpace(instagramId) ? null : instagramId.Trim(); private static string NormalizeUsername(string username) => username.Trim().TrimStart('@'); + private static string? NormalizeOrder(string? order) => string.IsNullOrWhiteSpace(order) ? null : order.Trim(); + private static void Validate(Account account) { ArgumentNullException.ThrowIfNull(account); @@ -153,6 +157,21 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore }, ct); + public Task> ListDownloadOrdersAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + using var r = c.Command("SELECT id, download_order FROM account WHERE download_order IS NOT NULL").ExecuteReader(); + var orders = new Dictionary(); + while (r.Read()) + { + orders[r.GetInt64(0)] = r.GetString(1); + } + + return orders; + }, + ct); + public Task> ListSummariesAsync(DateTimeOffset newSince, CancellationToken ct = default) => db.ReadAsync>( c => @@ -261,12 +280,12 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore unreachable_reason, keep_updated, frequency, custom_post_interval_min, custom_story_interval_min, content_types, history_depth, history_last_posts, history_from, backfill_posts_per_day, max_video_bytes, story_videos, folder, backfill_cursor, backfill_completed_at, post_count, last_profile_check_at, next_profile_check_at, - last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at) + last_stories_check_at, next_stories_check_at, notices, previous_username, renamed_at, format_unrecognized_at, added_at, download_order) VALUES (@instagram_id, @username, @display_name, @is_private, @is_followed, @is_mine, @state, @state_changed_at, @unreachable_reason, @keep_updated, @frequency, @custom_post_interval_min, @custom_story_interval_min, @content_types, @history_depth, @history_last_posts, @history_from, @backfill_posts_per_day, @max_video_bytes, @story_videos, @folder, @backfill_cursor, @backfill_completed_at, @post_count, @last_profile_check_at, @next_profile_check_at, - @last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at) + @last_stories_check_at, @next_stories_check_at, @notices, @previous_username, @renamed_at, @format_unrecognized_at, @added_at, @download_order) """); Bind(c, account); try @@ -305,7 +324,7 @@ internal sealed class AccountStore(FebeDatabase db) : IAccountStore last_profile_check_at = @last_profile_check_at, next_profile_check_at = @next_profile_check_at, last_stories_check_at = @last_stories_check_at, next_stories_check_at = @next_stories_check_at, notices = @notices, previous_username = @previous_username, renamed_at = @renamed_at, format_unrecognized_at = @format_unrecognized_at, - added_at = @added_at + added_at = @added_at, download_order = @download_order WHERE id = @id """); Bind(c, account); diff --git a/src/Febe.Data/Stores/EntryMapping.cs b/src/Febe.Data/Stores/EntryMapping.cs index 7c3d245..d6ee406 100644 --- a/src/Febe.Data/Stores/EntryMapping.cs +++ b/src/Febe.Data/Stores/EntryMapping.cs @@ -9,9 +9,9 @@ internal static class EntryMapping { public const string EntryColumns = "e.id, e.account_id, e.kind, e.instagram_id, e.code, e.published_at, e.caption, e.author_username, e.author_instagram_id, " - + "e.state, e.provenance, e.discovered_at, e.downloaded_at, e.deleted_at, e.expires_at"; + + "e.state, e.provenance, e.discovered_at, e.downloaded_at, e.deleted_at, e.expires_at, e.is_reel"; - public const int EntryColumnCount = 15; + public const int EntryColumnCount = 16; public const string MediaColumns = "m.id, m.entry_id, m.position, m.kind, m.instagram_id, m.width, m.height, m.duration_ms, m.state, m.relative_path, m.bytes, " @@ -54,6 +54,7 @@ internal static class EntryMapping DownloadedAt = r.GetTimeOrNull(o + 12), DeletedAt = r.GetTimeOrNull(o + 13), ExpiresAt = r.GetTimeOrNull(o + 14), + IsReel = r.GetBool(o + 15), }; public static Media ReadMedia(SqliteDataReader r, int o = 0) => new() @@ -112,6 +113,7 @@ internal static class EntryMapping .With("@downloaded_at", Sql.Time(e.DownloadedAt)) .With("@deleted_at", Sql.Time(e.DeletedAt)) .With("@expires_at", Sql.Time(e.ExpiresAt)) + .With("@is_reel", Sql.Bool(e.Kind == EntryKind.Post && e.IsReel)) .With("@search_text", TextSearch.ForEntry(e.Caption, e.AuthorUsername)); public static void BindMedia(SqliteCommand c, Media m) => diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index 0e831c6..f41213f 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -110,7 +110,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore UPDATE entry SET instagram_id = @instagram_id, code = @code, published_at = @published_at, caption = @caption, author_username = @author_username, author_instagram_id = @author_instagram_id, state = @state, provenance = @provenance, discovered_at = @discovered_at, downloaded_at = @downloaded_at, - deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text + deleted_at = @deleted_at, expires_at = @expires_at, search_text = @search_text, + is_reel = max(is_reel, @is_reel) WHERE id = @id """); BindEntry(c, entry); @@ -130,6 +131,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore ct); } + public Task MarkReelAsync(long entryId, CancellationToken ct = default) => + db.WriteAsync(w => w.Command("UPDATE entry SET is_reel = 1 WHERE id = @id AND kind = 'Post'").With("@id", entryId).ExecuteNonQuery(), ct); + public Task SetStateAsync(long entryId, EntryState state, CancellationToken ct = default) => db.WriteAsync( w => @@ -197,6 +201,36 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore ct); } + // The window of a recipe is a few minutes: the range on ix_entry_discovered (migration 0002) reads only those rows, + // whatever the size of the library or of the account. + private const string ArrivedWhere = """ + discovered_at >= @f AND discovered_at <= @t AND (@a IS NULL OR account_id = @a) AND provenance = @p AND state <> 'Deleted' + """; + + public Task ListDiscoveredAsync(long? accountId, DateTimeOffset from, DateTimeOffset to, int limit, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var ids = new List(); + using (var r = c.Command($""" + SELECT id FROM entry WHERE {ArrivedWhere} + ORDER BY discovered_at DESC, id DESC LIMIT @l + """).With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@p", Sql.Enum(Provenance.Downloaded)) + .With("@l", (long)Math.Clamp(limit, 1, 100)).ExecuteReader()) + { + while (r.Read()) + { + ids.Add(r.GetInt64(0)); + } + } + + var total = (int)c.Command($""" + SELECT COUNT(*) FROM entry WHERE {ArrivedWhere} + """).With("@a", accountId).With("@f", Sql.Time(from)).With("@t", Sql.Time(to)).With("@p", Sql.Enum(Provenance.Downloaded)).ScalarInt64(); + return new ArrivedEntries(ids, total); + }, + ct); + public Task CountDiscoveredAsync(long accountId, EntryKind kind, DateTimeOffset from, DateTimeOffset to, CancellationToken ct = default) => db.ReadAsync( c => (int)c.Command(""" @@ -208,6 +242,11 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore { ArgumentNullException.ThrowIfNull(query); var limit = Math.Clamp(query.Limit, 1, 1000); + if (query.Mode == MosaicMode.Files) + { + return db.ReadAsync(c => QueryFiles(c, query, limit), ct); + } + return db.ReadAsync( c => { @@ -284,7 +323,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore c => { var command = c.Command(string.Empty); - var where = BuildWhere(c, command, filter); + var where = BuildWhere(c, command, filter, aggregate: true); command.CommandText = $"SELECT COUNT(*), COUNT(DISTINCT e.account_id) FROM entry e WHERE {where}"; using var r = command.ExecuteReader(); r.Read(); @@ -293,7 +332,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore ct); } - public Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, CancellationToken ct = default) + public Task> CountLibraryByDayAsync(LibraryFilter filter, TimeZoneInfo zone, MosaicMode mode = MosaicMode.Grouped, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(filter); ArgumentNullException.ThrowIfNull(zone); @@ -303,8 +342,15 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore // Stream the publication times in index order and fold them into local days here: no time zone logic // in SQL, no sort, and the day bounds are computed once per day rather than once per entry. var command = c.Command(string.Empty); - var where = BuildWhere(c, command, filter); - command.CommandText = $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"; + var files = mode == MosaicMode.Files; + var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true); + var counts = files ? FileCounts(c, filter) : null; + var perEntry = files && counts is null; + command.CommandText = !files + ? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at" + : perEntry + ? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at" + : $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at"; var days = new List(); long dayStart = long.MaxValue, dayEnd = long.MinValue; DateOnly day = default; @@ -326,7 +372,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore (dayStart, dayEnd, count) = (Sql.Time(start), Sql.Time(end), 0); } - count++; + count += !files ? 1 : perEntry ? r.GetInt32(1) : counts!.GetValueOrDefault(r.GetInt64(1)); } } @@ -369,6 +415,243 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore return entryIds.Where(byId.ContainsKey).Select(id => byId[id]).ToList(); } + // --------------------------------------------------------------------------------------------- «Tutte le foto» + + /// The files of «Tutte le foto» on media m: those in the library, of the kind of «Foto» or «Video». + private static string FileTerms(LibraryFilter filter) => + // The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index. + "+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch + { + LibraryKindFilter.Photos => " AND m.kind = 'Photo'", + LibraryKindFilter.Videos => " AND m.kind = 'Video'", + _ => string.Empty, + }; + + /// + /// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a + /// count per entry would cost a subquery for each of 200,000 rows (over a second), this a tenth of that. With a + /// filter on accounts the entries are few and are counted one by one instead (null). + /// + private static Dictionary? FileCounts(SqliteConnection c, LibraryFilter filter) + { + if (filter.AccountIds is { Count: > 0 }) + { + return null; + } + + using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id"); + var counts = new Dictionary(); + using var r = command.ExecuteReader(); + while (r.Read()) + { + counts[r.GetInt64(0)] = r.GetInt32(1); + } + + return counts; + } + + /// + /// The entries whose files a count of «Tutte le foto» adds up: for «Foto» and «Video» every post, since the kind of + /// the files already decides (a post without videos adds 0) and the EXISTS per post of the grouped filter would cost + /// a second over 200,000 entries. + /// + private static LibraryFilter EntriesOfFiles(LibraryFilter filter) => + filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter; + + /// A correlated count of the files of «Tutte le foto» of the entry e. + private static string FilesOfEntry(LibraryFilter filter) => + $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})"; + + /// + /// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as + /// the grouped mosaic (so it stays as fast over 200,000 entries), then their files are read by key and laid out in + /// order, entry by entry and each by position. More entries are read only when those had too few files. + /// + private static LibraryPage QueryFiles(SqliteConnection c, LibraryQuery query, int limit) + { + var newer = query.Direction == LibraryDirection.Newer; + var wanted = limit + 1; + var files = new List(wanted); + var cursor = query.Cursor; + var from = cursor; + // The first read includes the entry of the cursor, for its files after (or before) the cursor's position. + var inclusive = true; + while (files.Count < wanted) + { + var keys = EntryKeys(c, query.Filter, from, newer, inclusive, wanted); + if (keys.Count == 0) + { + break; + } + + var byEntry = FilesOf(c, keys.Select(k => k.Id).ToList(), query.Filter); + foreach (var (id, _) in keys) + { + if (!byEntry.TryGetValue(id, out var list)) + { + continue; + } + + for (var i = 0; i < list.Count && files.Count < wanted; i++) + { + var file = list[newer ? list.Count - 1 - i : i]; + if (cursor is { } at && at.EntryId == id && (newer ? file.Position >= at.Position : file.Position <= at.Position)) + { + continue; + } + + files.Add(file); + } + + if (files.Count == wanted) + { + break; + } + } + + if (keys.Count < wanted) + { + break; + } + + from = new LibraryCursor(Sql.ToTime(keys[^1].PublishedAt), keys[^1].Id); + inclusive = false; + } + + var moreInDirection = files.Count > limit; + if (moreInDirection) + { + files.RemoveAt(files.Count - 1); + } + + if (newer) + { + files.Reverse(); + } + + var entries = TilesOf(c, files.Select(f => f.EntryId).Distinct().ToList()).ToDictionary(t => t.EntryId); + var tiles = new List(files.Count); + foreach (var f in files) + { + if (entries.TryGetValue(f.EntryId, out var entry)) + { + tiles.Add(entry with + { + CoverMediaId = f.MediaId, + CoverKind = f.Kind, + CoverWidth = f.Width, + CoverHeight = f.Height, + CoverDuration = f.Duration, + CoverSha256 = f.Sha256, + CoverHasThumbnail = f.HasThumbnail, + FilePosition = f.Position, + }); + } + } + + if (tiles.Count == 0) + { + return new LibraryPage(tiles, null, null); + } + + var first = new LibraryCursor(tiles[0].PublishedAt, tiles[0].EntryId, tiles[0].FilePosition ?? 0); + var last = new LibraryCursor(tiles[^1].PublishedAt, tiles[^1].EntryId, tiles[^1].FilePosition ?? 0); + bool hasOlder, hasNewer; + if (newer) + { + hasNewer = moreInDirection; + hasOlder = FileExists(c, query.Filter, last, older: true); + } + else + { + hasOlder = moreInDirection; + hasNewer = cursor is not null && FileExists(c, query.Filter, first, older: false); + } + + return new LibraryPage(tiles, hasOlder ? last : null, hasNewer ? first : null); + } + + /// Keys of the entries of a filter from a cursor, in the order of the direction (the grouped keyset scan). + private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit) + { + using var command = c.Command(string.Empty); + var where = BuildWhere(c, command, filter); + var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}"); + if (cursor is { } at) + { + var op = (newer, inclusive) switch { (true, true) => ">=", (true, false) => ">", (false, true) => "<=", _ => "<" }; + sql.Append(" AND (e.published_at, e.id) ").Append(op).Append(" (@cp, @ci)"); + command.With("@cp", Sql.Time(at.PublishedAt)).With("@ci", at.EntryId); + } + + var order = string.IsNullOrWhiteSpace(filter.Search) ? "e.published_at" : "+e.published_at"; + sql.Append(newer ? $" ORDER BY {order} ASC, e.id ASC" : $" ORDER BY {order} DESC, e.id DESC"); + sql.Append(" LIMIT @limit"); + command.With("@limit", (long)limit); + command.CommandText = sql.ToString(); + var keys = new List<(long, long)>(limit); + using var r = command.ExecuteReader(); + while (r.Read()) + { + keys.Add((r.GetInt64(0), r.GetInt64(1))); + } + + return keys; + } + + /// The files of «Tutte le foto» of the given entries, each list by position. + private static Dictionary> FilesOf(SqliteConnection c, IReadOnlyList entryIds, LibraryFilter filter) + { + var byEntry = new Dictionary>(entryIds.Count); + foreach (var chunk in entryIds.Chunk(500)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("f", chunk); + command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail " + + $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position"; + using var r = command.ExecuteReader(); + while (r.Read()) + { + var row = new FileRow( + r.GetInt64(0), + r.GetInt64(1), + r.GetInt32(2), + r.GetEnum(3), + r.GetInt32OrNull(4), + r.GetInt32OrNull(5), + r.GetDurationOrNull(6), + r.GetTextOrNull(7), + r.GetBool(8)); + if (!byEntry.TryGetValue(row.EntryId, out var files)) + { + byEntry[row.EntryId] = files = []; + } + + files.Add(row); + } + } + + return byEntry; + } + + /// Whether «Tutte le foto» has a file after (older) or before (newer) a cursor. + private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older) + { + using var command = c.Command(string.Empty); + var where = BuildWhere(c, command, filter); + var terms = FileTerms(filter); + command.CommandText = + $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} " + + $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) " + + $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) " + + $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))"; + command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position); + return command.ScalarInt64() != 0; + } + + /// A file of «Tutte le foto»: what its tile needs. + private readonly record struct FileRow(long EntryId, long MediaId, int Position, MediaKind Kind, int? Width, int? Height, TimeSpan? Duration, string? Sha256, bool HasThumbnail); + private static void Validate(Entry entry, IReadOnlyList media) { ArgumentNullException.ThrowIfNull(entry); @@ -396,9 +679,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore var stored = entry with { InstagramId = instagramId, State = state }; var insert = w.Command(""" INSERT INTO entry (account_id, kind, instagram_id, code, published_at, caption, author_username, author_instagram_id, state, - provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text) + provenance, discovered_at, downloaded_at, deleted_at, expires_at, search_text, is_reel) VALUES (@account_id, @kind, @instagram_id, @code, @published_at, @caption, @author_username, @author_instagram_id, @state, - @provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text) + @provenance, @discovered_at, @downloaded_at, @deleted_at, @expires_at, @search_text, @is_reel) """); BindEntry(insert, stored); insert.ExecuteNonQuery(); @@ -447,8 +730,22 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore } /// The WHERE clause of a library filter on entry e; parameters are added to . - internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter) + /// + /// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and + /// «Video» then test the key of each post, on a covering index, against one list of the entries that have such + /// files, read once from ix_media_entry_files (under two tenths of a second over 200,000 entries), instead of an + /// EXISTS per post (over a second: each post needs its table row). A window keeps the EXISTS: it stops after a few + /// hundred posts in index order. + /// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two. + /// + internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false) { + var byList = aggregate && filter.AccountIds is not { Count: > 0 }; + // The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index): + // looking up each entry of the list by key would read its table row, 0.85 s for «Foto» over 200,000 entries. + string FilesOfKind(string kind) => byList + ? $"+e.kind = 'Post' AND +e.id IN (SELECT mk.entry_id FROM media mk WHERE mk.kind = '{kind}')" + : $"e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = '{kind}')"; var parts = new List(); var states = filter.States is { Count: > 0 } s ? s : EntryStateRules.Visible; // The unary + keeps SQLite from using the state and kind indexes for these broad terms: the keyset scan of the @@ -458,9 +755,11 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore parts.Add(filter.Kind switch { LibraryKindFilter.All => "+e.kind IN ('Post', 'Story', 'Highlight', 'Tagged')", - LibraryKindFilter.Posts => "e.kind = 'Post'", - LibraryKindFilter.Photos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Photo')", - LibraryKindFilter.Videos => "e.kind = 'Post' AND EXISTS (SELECT 1 FROM media mk WHERE mk.entry_id = e.id AND mk.kind = 'Video')", + // Like «Tutto», a broad term: on the kind index every post would need its table row for the state (most of + // the library); the publication index already holds kind and state. + LibraryKindFilter.Posts => "+e.kind = 'Post'", + LibraryKindFilter.Photos => FilesOfKind("Photo"), + LibraryKindFilter.Videos => FilesOfKind("Video"), LibraryKindFilter.Stories => "e.kind = 'Story'", LibraryKindFilter.Highlights => "(e.kind = 'Highlight' OR EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id))", LibraryKindFilter.Tagged => "e.kind = 'Tagged'", diff --git a/src/Febe.Data/Stores/MediaStore.cs b/src/Febe.Data/Stores/MediaStore.cs index 8ad209b..c3e7607 100644 --- a/src/Febe.Data/Stores/MediaStore.cs +++ b/src/Febe.Data/Stores/MediaStore.cs @@ -1,3 +1,5 @@ +using System.Globalization; +using System.Text; using Febe.Core.Domain; using Febe.Core.Storage; using static Febe.Data.Stores.EntryMapping; @@ -81,21 +83,85 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore ct); public Task> ListPendingDownloadsAsync(int limit, CancellationToken ct = default) => + ListPendingAsync(limit, "(e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at", ct); + + public Task> ListPendingDownloadsAsync(int limit, DownloadQueueOrder order, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(order); + + // Only enum names and integer keys go into the text of the query, never text from outside. The accounts with the + // same own order share one branch (at most 120 orders exist), so the expression stays short with many accounts. + var rank = new StringBuilder(); + var groups = order.Accounts + .GroupBy(a => string.Join(',', a.Value), StringComparer.Ordinal) + .Select(g => (Kinds: g.First().Value, Ids: g.Select(a => a.Key).Order().ToList())) + .ToList(); + if (groups.Count > 0) + { + rank.Append("CASE"); + foreach (var (kinds, ids) in groups) + { + rank.Append(" WHEN e.account_id IN (").AppendJoin(',', ids.Select(id => id.ToString(CultureInfo.InvariantCulture))).Append(") THEN "); + AppendRank(rank, kinds); + } + + rank.Append(" ELSE "); + AppendRank(rank, order.General); + rank.Append(" END"); + } + else + { + AppendRank(rank, order.General); + } + + return ListPendingAsync(limit, $"{rank}, e.expires_at IS NULL, e.expires_at, e.discovered_at", ct); + } + + public Task> ListLongestWaitingDownloadsAsync(int limit, CancellationToken ct = default) => + ListPendingAsync(limit, "e.discovered_at", ct); + + /// The position of the kind of entry e in : 0 for the first, 5 for a kind left out. + private static void AppendRank(StringBuilder rank, IReadOnlyList kinds) + { + string Position(DownloadKind kind) + { + for (var i = 0; i < kinds.Count; i++) + { + if (kinds[i] == kind) + { + return i.ToString(CultureInfo.InvariantCulture); + } + } + + return kinds.Count.ToString(CultureInfo.InvariantCulture); + } + + rank.Append("(CASE WHEN e.kind = 'Story' THEN ").Append(Position(DownloadKind.Stories)) + .Append(" WHEN e.kind = 'Highlight' THEN ").Append(Position(DownloadKind.Highlights)) + .Append(" WHEN e.kind = 'Tagged' THEN ").Append(Position(DownloadKind.Tagged)) + .Append(" WHEN e.kind = 'Post' AND e.is_reel = 1 THEN ").Append(Position(DownloadKind.Reels)) + .Append(" ELSE ").Append(Position(DownloadKind.Posts)).Append(" END)"); + } + + private Task> ListPendingAsync(int limit, string order, CancellationToken ct) => db.ReadAsync>( c => { using var r = c.Command($""" - SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at + SELECT {MediaColumns}, e.account_id, e.kind, e.published_at, e.expires_at, e.is_reel FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.state = 'ToDownload' AND e.state <> 'Deleted' - ORDER BY (e.kind = 'Story') DESC, e.expires_at IS NULL, e.expires_at, e.discovered_at, m.entry_id, m.position + ORDER BY {order}, m.entry_id, m.position LIMIT @limit """).With("@limit", (long)Math.Clamp(limit, 1, 10_000)).ExecuteReader(); var list = new List(); while (r.Read()) { var o = MediaColumnCount; - list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3))); + list.Add(new PendingDownload(ReadMedia(r), r.GetInt64(o), r.GetEnum(o + 1), r.GetTime(o + 2), r.GetTimeOrNull(o + 3)) + { + IsReel = r.GetBool(o + 4), + }); } return list; diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs index cd9472c..a5deb82 100644 --- a/src/Febe.Desktop.Core/DesktopPlatform.cs +++ b/src/Febe.Desktop.Core/DesktopPlatform.cs @@ -94,7 +94,7 @@ public sealed class DesktopPlatform : IFebePlatform }; } - /// The token of this start: the interface window opens /?gettone=… once. Never logged. + /// The token of this start: the interface window opens /dashboard?gettone=… once. Never logged. public string AccessToken { get; } = Febe.Web.Security.AccessToken.Create(); public FebeWebOptions WebOptions { get; } @@ -105,13 +105,19 @@ public sealed class DesktopPlatform : IFebePlatform /// The hosting actually used (after a missing Edge fell back to the window). public BrowserHosting? Hosting { get; private set; } - /// The address the interface window opens once: the token becomes a cookie and leaves the address. + /// + /// The address the interface window opens once: the Dashboard, Febe's start page (spec §7.9, §12, tappa D1). The + /// token becomes a cookie and leaves the address, which stays /dashboard. + /// public Uri FirstAddress(Uri address) { ArgumentNullException.ThrowIfNull(address); - return new Uri(address, "/?" + Febe.Web.Security.AccessToken.QueryName + "=" + Uri.EscapeDataString(AccessToken)); + return new Uri(address, StartPage + "?" + Febe.Web.Security.AccessToken.QueryName + "=" + Uri.EscapeDataString(AccessToken)); } + /// The page the interface window opens on. + public const string StartPage = "/dashboard"; + public IReadOnlyList CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck) { ArgumentNullException.ThrowIfNull(options); diff --git a/src/Febe.Desktop/LEGGIMI.md b/src/Febe.Desktop/LEGGIMI.md index 062927d..31bf213 100644 --- a/src/Febe.Desktop/LEGGIMI.md +++ b/src/Febe.Desktop/LEGGIMI.md @@ -11,7 +11,7 @@ vero, in `tests/Febe.Tests.Windows` (`dotnet test tests/Febe.Tests.Windows`). Gu |---|---| | `Program.cs` | Riga di comando (`DesktopCommandLine`), cartella dei dati, istanza unica: un secondo avvio chiede al primo di mostrarsi ed esce | | `DesktopApplication.cs` | Avvio: area di notifica, spostamento della cartella dei dati se chiesto, `FebeApp` con `DesktopPlatform`, finestra principale; «Esci», fine sessione di Windows | -| `MainWindow.cs` | La finestra con l'interfaccia (WebView2 di WPF, cartella `Dati\interfaccia`): apre `/?gettone=…` una volta, ogni altro indirizzo va al browser predefinito | +| `MainWindow.cs` | La finestra con l'interfaccia (WebView2 di WPF, cartella `Dati\interfaccia`): apre `/dashboard?gettone=…` una volta, ogni altro indirizzo va al browser predefinito | | `Browser/WebView2Host.cs` | `IBrowserHost` di Windows: finestra «Browser di Febe», ambiente e controllo WebView2 in `Dati\browser`, CDP con `WebView2CdpSession`, fuori vista e in primo piano (S2), chi guida | | `Browser/WebView2Browser.cs` | `IFebeBrowser` per la composizione: avvio con nuovi tentativi, ripartenza dopo un arresto del processo, «Scollega» | | `Browser/BrowserWindow.cs` | La finestra «Browser di Febe»: pagina a misura fissa, barra con Indietro, Ricarica e indirizzo; chiudere = fuori vista | diff --git a/src/Febe.Desktop/MainWindow.cs b/src/Febe.Desktop/MainWindow.cs index 8dfb6ab..b762a1c 100644 --- a/src/Febe.Desktop/MainWindow.cs +++ b/src/Febe.Desktop/MainWindow.cs @@ -9,9 +9,10 @@ namespace Febe.Desktop; /// /// The main window (spec §12): a WebView2 showing the interface served in this process on 127.0.0.1. It opens -/// /?gettone=… once — the token of this start becomes an HttpOnly cookie and leaves the address — and never -/// leaves the interface: any other address opens in Alberto's default browser. Its WebView2 has a user data folder of -/// its own (Dati\interfaccia), separate from the browser of Instagram. +/// /dashboard?gettone=… once, on the start page (spec §7.9) — the token of this start becomes an HttpOnly +/// cookie and leaves the address — and never leaves the interface: any other address opens in Alberto's default +/// browser. Its WebView2 has a user data folder of its own (Dati\interfaccia), separate from the browser of +/// Instagram. /// internal sealed class MainWindow : Window { diff --git a/src/Febe.Server/DemoCommand.cs b/src/Febe.Server/DemoCommand.cs index adf4a25..7beff49 100644 --- a/src/Febe.Server/DemoCommand.cs +++ b/src/Febe.Server/DemoCommand.cs @@ -54,7 +54,7 @@ internal static class DemoCommand } await using var running = demo; - var address = new Uri(demo.Address, "/libreria"); + var address = new Uri(demo.Address, "/dashboard"); 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, alvolante; tema: ?tema=chiaro o scuro; veste: ?veste=desktop o docker.").ConfigureAwait(false); diff --git a/src/Febe.Web/Api/AccountSettingsMapper.cs b/src/Febe.Web/Api/AccountSettingsMapper.cs index 40c0a51..a7e7cae 100644 --- a/src/Febe.Web/Api/AccountSettingsMapper.cs +++ b/src/Febe.Web/Api/AccountSettingsMapper.cs @@ -38,7 +38,8 @@ public static class AccountSettingsMapper account.Limits.BackfillPostsPerDay, account.Limits.MaxVideoBytes is { } bytes ? Math.Round(bytes / 1024d / 1024d, 1) : null, account.Limits.StoryVideos, - account.Folder); + account.Folder, + account.DownloadOrder is { } own ? DownloadOrder.Parse(own).ToNames() : null); } /// @@ -144,6 +145,7 @@ public static class AccountSettingsMapper StoryVideos = dto.StoryVideos, }, Folder = folder, + DownloadOrder = dto.DownloadOrder is { Count: > 0 } names ? DownloadOrder.From(names).ToString() : null, State = state, StateChangedAt = changedAt, }; diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index ac0444c..41afc54 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -310,7 +310,8 @@ public static class AccountsApi account.Folder is null, account.State == AccountState.ArchiveOnly && account.InstagramId is null && account.IsMine is false ? null : InstagramLinks.Profile(account.Username), highlights, - AccountSettingsMapper.MaxBackfillPerDay); + AccountSettingsMapper.MaxBackfillPerDay, + (await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).ToNames()); } /// «Con queste impostazioni», recomputed at every change of the form (spec §4.4). diff --git a/src/Febe.Web/Api/ActivityApi.cs b/src/Febe.Web/Api/ActivityApi.cs index 7873d4f..22f7d12 100644 --- a/src/Febe.Web/Api/ActivityApi.cs +++ b/src/Febe.Web/Api/ActivityApi.cs @@ -15,7 +15,7 @@ using Microsoft.AspNetCore.Routing; namespace Febe.Web.Api; /// -/// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the +/// What the Dashboard (before: Attività) needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the /// stops, the still frame of the browser, the probable duplicates waiting for Alberto, the diagnostic report. /// public static class ActivityApi @@ -23,6 +23,15 @@ public static class ActivityApi /// Days of stops shown by the page. public const int HistoryDays = 14; + /// Thumbnails of a line of the history (spec §7.9: at most eight, «+12» for the rest). + public const int ArrivedShown = 8; + + /// The most the arrows of the enlarged preview walk through in one line. + public const int ArrivedLimit = 60; + + private static bool TryTime(string text, out DateTimeOffset at) => + DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out at); + /// /// «Esporta il rapporto di diagnostica» (issue #39, spec §7.9): the traces of the engine sessions of the last two /// weeks as a JSON file to send, with no data value in it. Also answered with a configuration problem, where the @@ -38,6 +47,31 @@ public static class ActivityApi endpoints.MapGet("/api/alerts", async (IFebeStorage storage, IClock clock, CancellationToken ct) => ApiHttp.Json(await AlertsAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AlertListDto)); + // The thumbnails of a line of the history (spec §7.9): asked by the page only when the line is in view. Without + // «account» (the Giro dei seguiti saves posts of many accounts), what arrived of every account in that time. + endpoints.MapGet("/api/activity/arrived", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var query = context.Request.Query; + var accountText = query["account"].ToString(); + long? account = null; + if (accountText.Length > 0) + { + account = long.TryParse(accountText, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : throw new BadRequestException("Account non valido."); + } + + if (!TryTime(query["from"].ToString(), out var from) + || !TryTime(query["to"].ToString(), out var to) + || to < from) + { + throw new BadRequestException("Indica inizio e fine."); + } + + var limit = int.TryParse(query["limit"].ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out var n) ? Math.Clamp(n, 1, ArrivedLimit) : ArrivedShown; + var arrived = await storage.Entries.ListDiscoveredAsync(account, from, to, limit, ct).ConfigureAwait(false); + var tiles = await storage.Entries.GetTilesAsync(arrived.EntryIds, ct).ConfigureAwait(false); + return ApiHttp.Json(new ArrivedDto([.. tiles.Select(t => LibraryApi.Tile(t, clock.LocalZone))], arrived.Total), FebeJsonContext.Default.ArrivedDto); + }); + endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) => { var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false); diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs index 5d23a0b..f8bc906 100644 --- a/src/Febe.Web/Api/ApiMapping.cs +++ b/src/Febe.Web/Api/ApiMapping.cs @@ -136,8 +136,18 @@ public static class ApiMapping return local.Hour.ToString(CultureInfo.InvariantCulture) + ":" + local.Minute.ToString("00", CultureInfo.InvariantCulture); } - public static string Cursor(LibraryCursor cursor) => - cursor.PublishedAt.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + "." + cursor.EntryId.ToString(CultureInfo.InvariantCulture); + /// «ms.entry», with «Tutte le foto» «ms.entry.position» (the window goes on after that file). + public static string Cursor(LibraryCursor cursor, MosaicMode mode = MosaicMode.Grouped) => + cursor.PublishedAt.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + "." + cursor.EntryId.ToString(CultureInfo.InvariantCulture) + + (mode == MosaicMode.Files ? "." + cursor.Position.ToString(CultureInfo.InvariantCulture) : string.Empty); + + /// «mode»: grouped (default, «Raggruppa i post») or files («Tutte le foto»). + public static MosaicMode Mode(string? text) => (text ?? string.Empty).ToLowerInvariant() switch + { + "" or "grouped" => MosaicMode.Grouped, + "files" => MosaicMode.Files, + _ => throw new BadRequestException("Modo del mosaico sconosciuto."), + }; public static LibraryCursor? ParseCursor(string? text) { @@ -146,15 +156,18 @@ public static class ApiMapping return null; } - var dot = text.IndexOf('.', StringComparison.Ordinal); - if (dot <= 0 - || !long.TryParse(text.AsSpan(0, dot), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) - || !long.TryParse(text.AsSpan(dot + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out var id)) + var parts = text.Split('.'); + var position = 0; + if (parts.Length is < 2 or > 3 + || !long.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) + || !long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var id) + || (parts.Length == 3 && (!int.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out position) || position < 0)) + || ms < -62135596800000 || ms > 253402300799999) { throw new BadRequestException("Posizione nella libreria non valida."); } - return new LibraryCursor(DateTimeOffset.FromUnixTimeMilliseconds(ms), id); + return new LibraryCursor(DateTimeOffset.FromUnixTimeMilliseconds(ms), id, position); } /// diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index 71faf7d..62662d9 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -41,7 +41,10 @@ public sealed record PreferencesDto(string Theme); /// The cover of a tile. is the thumbnail key (null: neutral tile). public sealed record CoverDto(long MediaId, string Kind, int? Width, int? Height, double? Duration, string? Thumb); -/// A tile of the mosaic: one entry. +/// +/// A tile of the mosaic: one entry, or with «Tutte le foto» one file of it (the cover is that file and +/// its place in the series; null for an entry tile). +/// public sealed record TileDto( long Id, long AccountId, @@ -53,15 +56,20 @@ public sealed record TileDto( string Provenance, string State, int Files, - CoverDto? Cover); + CoverDto? Cover, + int? Position = null); /// A window of tiles; cursors continue it (null: nothing more that way). public sealed record LibraryPageDto(IReadOnlyList Tiles, string? Older, string? Newer); +/// What a line of the history of the Dashboard saved (spec §7.9): the first tiles and how many in all. +public sealed record ArrivedDto(IReadOnlyList Tiles, int Total); + /// A day of the mosaic: its count and the cursor that starts at its end. public sealed record DayDto(string Day, int Count, string Cursor); -public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList Days); +/// Days of the mosaic with the totals; only with «Tutte le foto» (the files of the entries). +public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList Days, int? Files = null); public sealed record AccountBriefDto(long Id, string Username, string? DisplayName, bool IsPrivate, bool IsFollowed, bool IsMine, string State, string? Avatar); @@ -148,7 +156,10 @@ public sealed record AccountListDto(long Now, AccountCountsDto Counts, IReadOnly public sealed record AccountStatsDto(int Entries, int Posts, int Stories, int HighlightItems, int Tagged, int ProfilePictures, int Collections, long Bytes, int PendingFiles); -/// The editable settings of an account (mockup 05). +/// +/// The editable settings of an account (mockup 05). is «Cosa scaricare prima» (spec §4.4): +/// the names of the five kinds first to last for «Un ordine suo», null or empty for «Come le impostazioni generali». +/// public sealed record AccountSettingsDto( bool KeepUpdated, string Frequency, @@ -161,7 +172,8 @@ public sealed record AccountSettingsDto( int BackfillPerDay, double? MaxVideoMb, bool StoryVideos, - string? Folder); + string? Folder, + IReadOnlyList? DownloadOrder = null); public sealed record PlanLineDto(string Key, string Title, string Text); @@ -187,7 +199,8 @@ public sealed record AccountDetailDto( bool FolderIsDefault, string? InstagramUrl, IReadOnlyList Highlights, - int MaxBackfillPerDay); + int MaxBackfillPerDay, + IReadOnlyList? GeneralDownloadOrder = null); public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message); @@ -272,7 +285,7 @@ public sealed record ProfileSearchHitDto(string InstagramId, string Username, st /// "connected", "notConnected", "verification", "disconnected". public sealed record ConnectionDto(string State, string? Username, string? DisplayName, string? Avatar); -/// The engine for the sidebar, the stop strip and the Attività page. +/// The engine for the sidebar, the stop strip and the Dashboard. public sealed record EngineDto(long Now, EngineSnapshot Snapshot, ConnectionDto Connection, bool CanResume); public sealed record ResumeDto(bool Resumed, string Message); diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index 1edd824..636764e 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -55,6 +55,7 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(IncidentListDto))] [JsonSerializable(typeof(AlertListDto))] [JsonSerializable(typeof(BrowserPreviewDto))] +[JsonSerializable(typeof(ArrivedDto))] [JsonSerializable(typeof(DuplicateCountsDto))] [JsonSerializable(typeof(GeneralSettingsDto))] [JsonSerializable(typeof(GeneralSettingsRequest))] diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 2fb98cb..7eca9cb 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -31,15 +31,18 @@ public static class LibraryApi var zone = clock.LocalZone; var now = clock.Now; var filter = ApiMapping.Filter(context.Request.Query, zone); + var mode = ApiMapping.Mode(context.Request.Query["mode"]); var totals = await storage.Entries.GetLibraryTotalsAsync(filter, ct).ConfigureAwait(false); - var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, ct).ConfigureAwait(false); + var days = await storage.Entries.CountLibraryByDayAsync(filter, zone, mode, ct).ConfigureAwait(false); + // The files of «Tutte le foto» are the sum of their days: one pass over the media table per request. + int? files = mode == MosaicMode.Files ? days.Sum(d => d.Count) : null; var list = days.Select(d => { var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone); - return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0))); + return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode)); }).ToList(); return ApiHttp.Json( - new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list), + new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files), FebeJsonContext.Default.LibraryDaysDto); }); @@ -49,20 +52,22 @@ public static class LibraryApi var zone = clock.LocalZone; var limit = int.TryParse(query["limit"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var l) ? Math.Clamp(l, 1, MaxWindow) : 200; var direction = string.Equals(query["direction"], "newer", StringComparison.OrdinalIgnoreCase) ? LibraryDirection.Newer : LibraryDirection.Older; + var mode = ApiMapping.Mode(query["mode"]); var page = await storage.Entries.QueryLibraryAsync( new LibraryQuery { Filter = ApiMapping.Filter(query, zone), Cursor = ApiMapping.ParseCursor(query["cursor"]), Direction = direction, + Mode = mode, Limit = limit, }, ct).ConfigureAwait(false); return ApiHttp.Json( new LibraryPageDto( page.Tiles.Select(t => Tile(t, zone)).ToList(), - page.Older is { } older ? ApiMapping.Cursor(older) : null, - page.Newer is { } newer ? ApiMapping.Cursor(newer) : null), + page.Older is { } older ? ApiMapping.Cursor(older, mode) : null, + page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null), FebeJsonContext.Default.LibraryPageDto); }); @@ -209,7 +214,8 @@ public static class LibraryApi tile.CoverHeight, tile.CoverDuration?.TotalSeconds, tile.CoverHasThumbnail && tile.CoverSha256 is not null ? tile.CoverSha256 : tile.CoverKind == MediaKind.Video ? "video" : null) - : null); + : null, + tile.FilePosition); } public static async Task EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) diff --git a/src/Febe.Web/Api/Part2Dtos.cs b/src/Febe.Web/Api/Part2Dtos.cs index b9e03aa..8c45f25 100644 --- a/src/Febe.Web/Api/Part2Dtos.cs +++ b/src/Febe.Web/Api/Part2Dtos.cs @@ -1,6 +1,6 @@ namespace Febe.Web.Api; -// JSON shapes of the second part of the interface (Attività, Impostazioni, Importa, Collegamento, Browser, doppioni). +// JSON shapes of the second part of the interface (Dashboard, Impostazioni, Importa, Collegamento, Browser, doppioni). // Same conventions as Dtos.cs: English camelCase names, Italian texts, times as Unix milliseconds or LocalTimeDto. // ---------------------------------------------------------------- connection (PROTOCOLLO.md) @@ -64,7 +64,7 @@ public sealed record IncidentDto( public sealed record IncidentListDto(IReadOnlyList Items, int ThrottlesLastWeek, string? Advice); /// -/// A line of the «Avvisi» list of Attività (spec §13.3): an alert or a failed delivery. : +/// A line of the «Avvisi» list of the Dashboard (spec §13.3): an alert or a failed delivery. : /// verification, disconnection, throttleStop, throttleEnd, backfillDone, unknownFormat, recipeSuspended, diskLow, /// deliveryFailed. : error, warning, success, info. /// @@ -164,10 +164,14 @@ public sealed record LimitsDto( bool GradualStart, IReadOnlyList ActiveDays, LimitRulesDto Rules, - IReadOnlyList Stops); + IReadOnlyList Stops, + IReadOnlyList? DownloadOrder = null); -/// Saves the limits; is read when is custom. -public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList ActiveDays); +/// +/// Saves the limits; is read when is custom. is +/// «Cosa scaricare prima» (spec §7.2), the names of the five kinds first to last; null keeps the stored order. +/// +public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList ActiveDays, IReadOnlyList? DownloadOrder = null); // ---------------------------------------------------------------- settings: notifications (spec §13.3) diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs index 453999e..baee7ae 100644 --- a/src/Febe.Web/Api/SettingsApi.cs +++ b/src/Febe.Web/Api/SettingsApi.cs @@ -128,7 +128,7 @@ public static class SettingsApi // ------------------------------------------------------------------------------------------ Limiti e comportamento endpoints.MapGet("/api/settings/limits", async (IFebeStorage storage, CancellationToken ct) => - ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto)); + ApiHttp.Json(await LimitsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.LimitsDto)); endpoints.MapPut("/api/settings/limits", async (HttpContext context, IFebeStorage storage, IEngineSettingsControl engine, CancellationToken ct) => { @@ -142,7 +142,13 @@ public static class SettingsApi } await engine.ApplyAsync(settings, ct).ConfigureAwait(false); - return ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto); + if (body.DownloadOrder is { } names) + { + // The engine reads the order at every session and the queue at every batch: nothing else to tell them. + await DownloadOrder.SaveAsync(storage.Settings, DownloadOrder.From(names), ct).ConfigureAwait(false); + } + + return ApiHttp.Json(await LimitsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.LimitsDto); }); // ------------------------------------------------------------------------------------------ Notifiche @@ -364,6 +370,14 @@ public static class SettingsApi // ---------------------------------------------------------------------------------------------- Limiti + /// The limits with «Cosa scaricare prima» (spec §7.2), as stored. + private static async Task LimitsAsync(IFebeStorage storage, CancellationToken ct) + { + var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var order = await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + return Limits(settings) with { DownloadOrder = [.. order.Kinds.Select(DownloadOrder.NameOf)] }; + } + public static LimitsDto Limits(EngineSettings settings) { ArgumentNullException.ThrowIfNull(settings); diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs index cc9b876..2d9ed64 100644 --- a/src/Febe.Web/Demo/DemoEngine.cs +++ b/src/Febe.Web/Demo/DemoEngine.cs @@ -351,7 +351,7 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora } list.AddRange(world.Recent.Where(r => r.At <= (scene == DemoScene.Stopped ? stopAt : now)) - .Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false))); + .Select(r => new RecentActionView(r.At, ItalianText.Clock(r.At, zone), r.Title, r.Detail, r.Badge, false, r.AccountId, r.From, r.NewEntries))); return list.Take(10).ToList(); } } diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs index f0c0b11..60b86f0 100644 --- a/src/Febe.Web/Demo/DemoSeeder.cs +++ b/src/Febe.Web/Demo/DemoSeeder.cs @@ -11,7 +11,9 @@ namespace Febe.Web.Demo; public sealed record DemoSession(DateTimeOffset Start, DateTimeOffset End, int ProfilesOpened, int StoriesViewed, int HistoryPages, long Bytes, int NewEntries); /// A line of «Appena fatto». -public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge); +/// A line of the history of the demo; and when it saved something +/// (its thumbnails on the Dashboard, spec §7.9). +public sealed record DemoAction(DateTimeOffset At, string Title, string Detail, string? Badge, long? AccountId = null, DateTimeOffset? From = null, int NewEntries = 0); /// Everything the demo engine needs to tell a coherent day (spec §10.6: «i conteggi tornano, gli orari sono plausibili»). public sealed class DemoWorld @@ -117,7 +119,7 @@ public static class DemoSeeder new("tuo.profilo", "Il tuo profilo", false, false, AccountState.UpToDate, 420, 980, 140, 5, 402, 4, [DemoSubject.Hills, DemoSubject.Sea, DemoSubject.Food, DemoSubject.Portrait, DemoSubject.Room, DemoSubject.Sunset, DemoSubject.CityNight]) { Mine = true }, new("marta.demo", "Marta B.", true, true, AccountState.UpToDate, 810, 312, 92, 6, 40, 4, [DemoSubject.Portrait, DemoSubject.Flowers, DemoSubject.Food, DemoSubject.Room, DemoSubject.Sunset, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Houses, DemoSubject.Hills]) { Imported = 30, Tagging = true }, new("studio.lumen.demo", "Studio Lumen", false, false, AccountState.Backfilling, 340, 8, 4, 4, 0, 3, [DemoSubject.Room, DemoSubject.Portrait, DemoSubject.Bokeh, DemoSubject.Leaves]) { PostCount = 1280, BackfillToday = 300 }, - new("luca.viaggi.demo", "Luca in viaggio", false, true, AccountState.UpToDate, 1900, 1000, 208, 8, 0, 4, [DemoSubject.Mountains, DemoSubject.Sea, DemoSubject.Road, DemoSubject.Hills, DemoSubject.Houses, DemoSubject.Sunset]) { Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories, ProfilePictures = 2 }, + new("luca.viaggi.demo", "Luca in viaggio", false, true, AccountState.UpToDate, 1900, 1000, 208, 8, 0, 4, [DemoSubject.Mountains, DemoSubject.Sea, DemoSubject.Road, DemoSubject.Hills, DemoSubject.Houses, DemoSubject.Sunset]) { Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories, ProfilePictures = 2, DownloadOrder = "post,reel,storie,evidenza,taggati" }, new("nonna.pina.demo", "Pina", true, true, AccountState.UpToDate, 150, 50, 14, 2, 0, 3, [DemoSubject.Food, DemoSubject.Flowers, DemoSubject.Room, DemoSubject.Portrait]) { Types = ContentTypes.PostPhotos | ContentTypes.Stories | ContentTypes.Highlights }, new("circolo.foto.demo", "Circolo fotografico", false, true, AccountState.Backfilling, 2060, 0, 11, 3, 0, 4, [DemoSubject.Mountains, DemoSubject.CityNight, DemoSubject.Sea, DemoSubject.Hills, DemoSubject.Bokeh, DemoSubject.Houses, DemoSubject.Road]) { PostCount = 2410, BackfillToday = 150, Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Highlights | ContentTypes.Tagged | ContentTypes.ProfilePicture }, new("giulia.corre.demo", "Giulia", false, true, AccountState.UpToDate, 600, 230, 46, 3, 0, 3, [DemoSubject.Road, DemoSubject.Hills, DemoSubject.Mountains, DemoSubject.Portrait, DemoSubject.Sea]) { ProfilePictures = 3, Types = ContentTypes.PostPhotos | ContentTypes.PostVideos | ContentTypes.Stories | ContentTypes.Highlights }, @@ -360,6 +362,9 @@ public static class DemoSeeder ExpiresAt = item.Kind == EntryKind.Story ? item.Published + TimeSpan.FromHours(24) : null, }; var media = Media(item, entry, spec, account, folder, collectionTitle, layout, zone, pool, random); + + // A downloaded post with a single video is shown as a reel (spec §7.2: Febe knows it from the Reel tab). + entry = entry with { IsReel = item.Kind == EntryKind.Post && !item.Imported && media.Count == 1 && media[0].Kind == MediaKind.Video }; pending.Add(new NewEntry(entry, media)); created.Add((account.Id, item.Kind, item.Discovered, media.Sum(m => m.Bytes ?? 0), media.Count, item.Backfill)); entriesCount += item.Kind == EntryKind.ProfilePicture ? 0 : 1; @@ -492,7 +497,7 @@ public static class DemoSeeder withNews == 0 ? "Giro dei profili che segui: nessuna novità" : $"Giro dei profili che segui: {withNews} contenuti nuovi", null)); } - // The alerts of the last days (Attività, «Avvisi»): the throttle of three days ago (as DemoIncidentHistory) and + // The alerts of the last days (Dashboard, «Avvisi»): the throttle of three days ago (as DemoIncidentHistory) and // its end, and the backfills completed in the last two weeks. var throttle = LocalCalendar.StartOfDay(today.AddDays(-3), zone) + TimeSpan.FromHours(18.4); var throttleEnd = throttle + TimeSpan.FromHours(1); @@ -563,7 +568,16 @@ public static class DemoSeeder var split = e.Message.IndexOf(": ", StringComparison.Ordinal); var title = split > 0 ? e.Message[..split] : e.Message; var detail = split > 0 ? e.Message[(split + 2)..] : string.Empty; - return new DemoAction(e.At, title, Capitalize(detail), e.Severity == EventSeverity.Success ? "Scaricato" : null); + if (e.Severity != EventSeverity.Success || e.AccountId is not { } accountId) + { + return new DemoAction(e.At, title, Capitalize(detail), e.Severity == EventSeverity.Success ? "Scaricato" : null); + } + + // What this visit found: the entries of the account discovered after its previous visit (at most an hour back). + var previous = events.Where(x => x.AccountId == accountId && x.At < e.At).Select(x => x.At).Append(e.At - TimeSpan.FromHours(1)).Max(); + var from = previous.AddMilliseconds(1); + var found = created.Count(c => c.AccountId == accountId && c.Discovered >= from && c.Discovered <= e.At); + return new DemoAction(e.At, title, Capitalize(detail), "Scaricato", found > 0 ? accountId : null, found > 0 ? from : null, found); }) .ToList(); @@ -630,6 +644,9 @@ public static class DemoSeeder public ContentTypes? Types { get; init; } public Frequency Frequency { get; init; } = Frequency.Normal; + + /// «Cosa scaricare prima» of its own (spec §4.4); null: «Come le impostazioni generali». + public string? DownloadOrder { get; init; } } private static ContentTypes DefaultTypes(AccountSpec spec) => @@ -663,6 +680,7 @@ public static class DemoSeeder ContentTypes = spec.State == AccountState.ArchiveOnly ? ContentTypes.None : spec.Types ?? DefaultTypes(spec), PostCount = spec.PostCount ?? (spec.State == AccountState.ArchiveOnly ? null : spec.Posts), BackfillCompletedAt = spec.State == AccountState.Backfilling || spec.State == AccountState.ArchiveOnly ? null : added + TimeSpan.FromDays(4), + DownloadOrder = spec.DownloadOrder, AddedAt = added, }; } @@ -842,9 +860,14 @@ public static class DemoSeeder _ => video ? (random.NextDouble() < 0.7 ? PictureShape.Story : PictureShape.Portrait) : PickShape(random), }; + // «Tutte le foto» (spec §4.6): about one series of three files or more in five has a video in second place, as on + // Instagram. Decided from the entry's own identifier, so the rest of the demo world (drawn from the same random + // sequence) stays as it was; its length and weight too. + var seriesVideo = !video && count >= 3 && entry.InstagramId is { Length: > 0 } id && id[^1] is '3' or '7'; for (var n = 1; n <= count; n++) { - var isVideo = video && n == 1; + var inSeries = seriesVideo && n == 2; + var isVideo = (video && n == 1) || inSeries; var picture = pool.Pick(n == 1 ? subject : spec.Themes[random.Next(spec.Themes.Length)], n == 1 || !video ? shape : PickShape(random), random); var extension = isVideo ? ".mp4" : ".jpg"; var relative = layout.RelativePathFor(folder, LibraryNaming.Default.For(entry.Kind), NamingValues.For(account.Username, entry, n, extension, collection, picture.Sha256), zone); @@ -854,10 +877,10 @@ public static class DemoSeeder Kind = isVideo ? MediaKind.Video : MediaKind.Photo, Width = picture.Width, Height = picture.Height, - Duration = isVideo ? TimeSpan.FromSeconds(item.Kind is EntryKind.Story or EntryKind.Highlight ? random.Next(5, 16) : random.Next(8, 95)) : null, + Duration = inSeries ? TimeSpan.FromSeconds(9 + (count * 4)) : isVideo ? TimeSpan.FromSeconds(item.Kind is EntryKind.Story or EntryKind.Highlight ? random.Next(5, 16) : random.Next(8, 95)) : null, State = item.Imported ? MediaState.Imported : MediaState.Downloaded, RelativePath = relative, - Bytes = isVideo ? random.Next(2_000_000, 38_000_000) : picture.Bytes, + Bytes = inSeries ? 6_000_000 + (count * 900_000) : isVideo ? random.Next(2_000_000, 38_000_000) : picture.Bytes, Sha256 = picture.Sha256, PerceptualHash = isVideo ? null : picture.PerceptualHash, HasThumbnail = true, diff --git a/src/Febe.Web/Engine/BrowserPreview.cs b/src/Febe.Web/Engine/BrowserPreview.cs index 1280f62..1a15ca5 100644 --- a/src/Febe.Web/Engine/BrowserPreview.cs +++ b/src/Febe.Web/Engine/BrowserPreview.cs @@ -1,13 +1,13 @@ namespace Febe.Web.Engine; -/// A still frame of Febe's browser for the Attività page (mockup 06: one frame every few seconds, not a video). +/// A still frame of Febe's browser for the Dashboard (mockup 06: one frame every few seconds, not a video). /// The frame, JPEG encoded. /// Address of the page, without query string. /// When the frame was taken. public sealed record BrowserFrame(byte[] Jpeg, string? Url, DateTimeOffset At); /// -/// The latest frame of Febe's browser, for the preview of the Attività page. Implemented by the composition over the +/// The latest frame of Febe's browser, for the preview of the Dashboard. Implemented by the composition over the /// browser host (Docker: the screencast of the remote view; Windows: the WebView2). Taking frames is never an action /// toward the site: it reads what the browser already shows. /// diff --git a/src/Febe.Web/Engine/DiagnosticSource.cs b/src/Febe.Web/Engine/DiagnosticSource.cs index 9b72e67..35ec218 100644 --- a/src/Febe.Web/Engine/DiagnosticSource.cs +++ b/src/Febe.Web/Engine/DiagnosticSource.cs @@ -3,7 +3,7 @@ using Febe.Core.Collection.Diagnostics; namespace Febe.Web.Engine; /// -/// The traces of the diagnostic report (issue #39) for «Esporta il rapporto di diagnostica» in Attività: the finished +/// The traces of the diagnostic report (issue #39) for «Esporta il rapporto di diagnostica» in the Dashboard: the finished /// ones of the last two weeks and the ones in progress, oldest first. They hold no data value /// (). /// diff --git a/src/Febe.Web/Engine/EngineBridge.cs b/src/Febe.Web/Engine/EngineBridge.cs index 1c08302..dce2b72 100644 --- a/src/Febe.Web/Engine/EngineBridge.cs +++ b/src/Febe.Web/Engine/EngineBridge.cs @@ -100,7 +100,7 @@ public sealed class OfflineEngine(IClock clock) : IEngineMonitor, IEngineControl /// Pieces for building snapshots outside (offline engine, demo). public static class SnapshotParts { - /// The four main budgets in the order of the Attività page. + /// The four main budgets in the order of the Dashboard. public static readonly ActionKind[] Main = [ActionKind.ProfileOpen, ActionKind.StoryView, ActionKind.BackfillPage, ActionKind.DataDownload]; /// Every category in the order of the table of spec §7.5. diff --git a/src/Febe.Web/Engine/IncidentHistory.cs b/src/Febe.Web/Engine/IncidentHistory.cs index bdcc45a..d360590 100644 --- a/src/Febe.Web/Engine/IncidentHistory.cs +++ b/src/Febe.Web/Engine/IncidentHistory.cs @@ -3,7 +3,7 @@ using Febe.Core.Storage; namespace Febe.Web.Engine; -/// The stops of the last days for the Attività page (spec §7.6: «nella cronologia della pagina Attività»). +/// The stops of the last days for the Dashboard (spec §7.6 still says «nella cronologia della pagina Attività», the page before it). public interface IIncidentHistory { /// Incidents that started in [from, to), newest first. diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 2b09937..b83f3b0 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -84,7 +84,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri | Veste | Opzioni | Effetto | |---|---|---| | Docker | `Edition = Docker`, `Access = Password`, `Password = FEBE_PASSWORD`, `AllowedHosts` = nomi con cui si raggiunge il server (anche `nome:*`), `FebeListen.Any(8480)` | Pagina `/accesso`, cookie `febe_sessione` HttpOnly SameSite=Strict, blocco dopo 5 errori per client e 20 in tutto in 15 minuti. Senza password risponde solo alla pagina dell'errore (indirizzi delle pagine, file dell'interfaccia, `GET /api/capabilities` e `/api/preferences`, `/salute`); tutto il resto, vista remota compresa, 503 | -| Windows | `Edition = Desktop`, `Access = Token`, `AccessToken = AccessToken.Create()`, `AllowedHosts = FebeWebOptions.LoopbackHosts(porta)`, `FebeListen.Loopback(0)` | La finestra apre `/?gettone=…` una volta: il gettone diventa un cookie HttpOnly Strict e sparisce dall'indirizzo. Anche l'intestazione `X-Febe-Gettone` vale | +| Windows | `Edition = Desktop`, `Access = Token`, `AccessToken = AccessToken.Create()`, `AllowedHosts = FebeWebOptions.LoopbackHosts(porta)`, `FebeListen.Loopback(0)` | La finestra apre `/dashboard?gettone=…` una volta: il gettone diventa un cookie HttpOnly Strict e sparisce dall'indirizzo. Anche l'intestazione `X-Febe-Gettone` vale | | Prove e dimostrazione | `Access = None` | Solo su 127.0.0.1 | Sempre attivi: nome Host in elenco (altrimenti 400), Origin uguale all'Host per ogni comando, per `/api/eventi` e @@ -107,8 +107,8 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `GET /api/engine`, `POST /api/engine/pause`, `/resume` | Istantanea del motore, collegamento, `canResume` | | `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser | | `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s), commento ogni 25 s | -| `GET /api/library/days` | Totali e giorni con conteggio e cursore (per la finestra del mosaico) | -| `GET /api/library?cursor=&direction=older\|newer&limit=` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q` | +| `GET /api/library/days?mode=grouped\|files` | Totali (sempre elementi: `entries`, `accounts`) e giorni con conteggio e cursore (per la finestra del mosaico); con `mode=files` («Tutte le foto») i giorni contano i file presenti in libreria e `files` è la loro somma (altrimenti `null`). Un altro valore di `mode` dà 400. Stessi filtri di `/api/library` | +| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | | `GET /api/library/tiles?ids=` | Tessere per chiave | | `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) | | `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) | @@ -119,10 +119,11 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `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 | -| `POST /api/engine/recipes/{ricetta}/resume` | «Riattiva» una ricetta sospesa dopo tre problemi di fila (`IEngineControl.ResumeRecipeAsync`: metodo con un'implementazione predefinita che risponde «non era sospesa», così le altre implementazioni non cambiano). Attività mostra le ricette sospese da `snapshot.suspendedRecipes` | -| `GET /api/alerts` | Avvisi degli ultimi 14 giorni (§13.3, sezione «Avvisi» di Attività): righe della cronologia con i codici di `AlertCatalog.Codes`, compresi gli avvisi non arrivati | +| `POST /api/engine/recipes/{ricetta}/resume` | «Riattiva» una ricetta sospesa dopo tre problemi di fila (`IEngineControl.ResumeRecipeAsync`: metodo con un'implementazione predefinita che risponde «non era sospesa», così le altre implementazioni non cambiano). La Dashboard mostra le ricette sospese da `snapshot.suspendedRecipes` | +| `GET /api/alerts` | Avvisi degli ultimi 14 giorni (§13.3, sezione «Avvisi» della Dashboard): righe della cronologia con i codici di `AlertCatalog.Codes`, compresi gli avvisi non arrivati | | `GET /api/engine/diagnostica` | «Esporta il rapporto di diagnostica» (issue #39, §7.9): file JSON `febe-diagnostica-aaaa-mm-gg.json` (giorno locale) in allegato, `no-store`, UTF-8 senza BOM, da `DiagnosticReport.Write` con le tracce di `IDiagnosticSource`. Nessun valore dei dati: solo conteggi, misure, orari, codici da elenchi chiusi e forme degli indirizzi. In testa `righeRovinate`, `erroriRegistratore`, `fileIlleggibili` e `sessioniSenzaFine` (`IDiagnosticSource.GatherAsync`). Risponde anche con un problema di configurazione (`ConfigurationGateMiddleware.AllowedApi`), con gli elenchi vuoti: il motore non è partito | -| `GET /api/browser/preview`, `GET /api/browser/preview/frame` | Anteprima del browser in Attività: indirizzo e immagine JPEG (`no-store`, 404 se non c'è) | +| `GET /api/browser/preview`, `GET /api/browser/preview/frame` | Anteprima del browser nella Dashboard: indirizzo e immagine JPEG (`no-store`, 404 se non c'è), al più un fotogramma nuovo al secondo | +| `GET /api/activity/arrived?account=&from=&to=&limit=` | Miniature di una riga della cronologia della Dashboard (§7.9): gli elementi scaricati da Febe (mai gli importati) scoperti fra `from` e `to`, dell'account o, senza `account`, di tutti (righe del Giro dei seguiti); tessere come la Libreria, al più `limit` (8, fino a 60), e `total` | | `GET /api/duplicates/count`, `GET /api/duplicates?after=`, `POST /api/duplicates/{pairId}` (`{ decision, applyToAll }`) | Doppioni dopo uno scaricamento (§9.5): `keepLarger`, `keepExisting`, `keepBoth`; niente si decide da solo | | `GET/PUT /api/settings/general`, `POST /api/settings/naming-preview`, `/pick-folder`, `/data-folder` | Cartelle (cambio della libreria solo desktop), schema dei nomi con anteprima, tema, avvio, area di notifica | | `GET/PUT /api/settings/limits` | Profilo di prudenza, orari, sessioni, tetti, avvio graduale; le regole di §7.5 rispondono 400 con i messaggi italiani | @@ -170,7 +171,7 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da ### Una pagina nuova -1. Una riga in `js/routes.js`: `{ pattern: /^\/attivita\/?$/, nav: 'attivita', page: () => import('./pages/activity.js') }` +1. Una riga in `js/routes.js`: `{ pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') }` (i gruppi con nome del `pattern` arrivano in `route.params`; `data` aggiunge valori fissi). 2. Il modulo esporta `export default { async mount(page, route) { … } }`. `route` ha `path`, `params`, `query` (`URLSearchParams`). Se `mount` restituisce una funzione, viene chiamata quando si lascia la pagina. @@ -184,12 +185,13 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da `onEngine`/`onLibrary` non si iscrivono e `onLeave` esegue subito la funzione. Dopo un `await` controlla `page.signal.aborted` prima di prendere risorse che durano (il browser, una vista remota, un timer). La striscia rossa di arresto (mockup 11) la mette la cornice su ogni pagina, da sola. -4. Pagine della seconda parte: `pages/activity.js` (`/attivita`, con `day-strip.js` per la striscia del giorno), +4. Pagine della seconda parte: `pages/dashboard.js` (`/dashboard`, prima `/attivita`, con `day-strip.js` per la striscia del giorno), `pages/settings.js` (`/impostazioni/{generali|limiti|collegamento|notifiche|dati|informazioni}`, un modulo `settings-*.js` per sezione; `connection.js` per il collegamento), `pages/browser.js` (`/browser`, vista remota della veste Docker, `remote-view.js` parla con `/api/vista` secondo `Connection/PROTOCOLLO.md`), `pages/import.js` (`/importa`, `?passo=1|3`, `?id=N`), `pages/duplicates.js` (`/doppioni`), `pages/compare.js` (confronto dei doppioni, - usato da Importa e da `/doppioni`), `pages/welcome.js` (primo avvio, dalla libreria vuota e non collegata), + usato da Importa e da `/doppioni`), `pages/welcome.js` (primo avvio: il benvenuto della libreria vuota e non collegata, e quello compatto + della Dashboard finché non c'è nessun account), `pages/problems.js` (pagina di errore quando `caps().problems` non è vuoto). `pages/placeholder.js` ora dice solo «Pagina non trovata». @@ -209,7 +211,12 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da Pezzi riusabili delle pagine: `pages/mosaic.js` (`Mosaic`: righe giustificate o griglia 9:16, finestre per giorno, virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `pages/viewer.js` (`openViewer`), -`pages/accounts.js` (`checkNow`, `removeAccount`, `accountMenu`, `stateLine`), `pages/library.js` (`confirmDelete`). +`pages/accounts.js` (`checkNow`, `removeAccount`, `accountMenu`, `stateLine`), `pages/library.js` (`confirmDelete`, +`selectionBar`: la barra della selezione, che con «Tutte le foto» dice file ed elementi), `pages/mosaic.js` anche +`storedMode` e `modeSwitch` («Raggruppa i post» / «Tutte le foto», ricordato per pagina nella memoria locale del +browser), `pages/download-order.js` (`orderEditor`: l'elenco da trascinare di «Cosa scaricare prima», con Su/Giù e i +tipi spenti attenuati, usato da Limiti e comportamento e dalla scheda account; `kindName`, `orderOrDefault`, +`DEFAULT_ORDER`). ### Testi, stile, accessibilità diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 29b12cf..51d9c86 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -331,6 +331,12 @@ input[type=range].cursore::-moz-range-thumb{width:14px;height:14px;border-radius input[type=range].cursore:focus-visible{outline:2px solid var(--accento);outline-offset:3px} .grandezza{display:flex;align-items:center;gap:8px;color:var(--testo-2)} .btn.solo-icona{padding:0 8px} +/* «Raggruppa i post» / «Tutte le foto» (spec §4.6): the two voices of .gruppo; in the crowded row of the Libreria only + the icons until the window is wide, in every row below 1000 px (name and tooltip stay on the buttons). */ +.modo-mosaico{flex:none} +.modo-mosaico > button{padding:0 10px} +@media (max-width:1679px){ .modo-mosaico.compatto .voce{display:none} .modo-mosaico.compatto > button{padding:0 8px} } +@media (max-width:1000px){ .modo-mosaico .voce{display:none} .modo-mosaico > button{padding:0 8px} } /* Libreria: when the tools do not fit in one row (a duplicates link, a narrow screen above 1000 px) the group on the right goes to a second row instead of squeezing the kind chips into a column. */ @media (min-width:1001px){ @@ -654,7 +660,74 @@ a.stato:hover{border-color:var(--bordo-forte)} /* ---------- attività ---------- */ .attivita{display:flex;flex-direction:column;gap:24px;padding-bottom:8px} .attivita > div:empty{display:none} -[data-pagina=attivita] .arresto .riprendi-arresto{display:none} +[data-pagina=dashboard] .arresto .riprendi-arresto{display:none} +/* Dashboard (spec §7.9, tappa D1): compact, preview always visible at the top with what is happening and the budgets */ +.dashboard{gap:18px} +.cruscotto{display:flex;align-items:flex-start;gap:20px;padding:14px 16px} +/* The preview keeps its proportions (420 × 236 at most) and shrinks with the page, staying beside the status down to + the phone, so that preview, status, budgets and the start of the history fit the first screen (spec §7.9) */ +.cruscotto .anteprima{width:clamp(220px,38%,420px)} +.cruscotto .anteprima .quadro{height:auto;aspect-ratio:420/236} +.cruscotto-lato{flex:1;min-width:0;align-self:stretch;display:flex;flex-direction:column;justify-content:space-between;gap:14px;container-type:inline-size} +@container (max-width:600px){ + .cruscotto-lato .tetti{grid-template-columns:repeat(2,minmax(0,1fr))} + .cruscotto-lato .tetto:nth-child(3){border-left:0} + .cruscotto-lato .tetto:nth-child(n+3){border-top:1px solid var(--bordo)} + .cruscotto-lato .blocco-tetti .tetto{padding:7px 12px 8px;gap:4px} +} +.cruscotto-lato .ora-testo .cosa{margin-top:8px} +.blocco-tetti .testa-blocco{margin-bottom:6px} +.blocco-tetti h2{margin:0;font-size:14px;font-weight:650} +.blocco-tetti .tetti{border:1px solid var(--bordo);border-radius:8px} +.blocco-tetti .tetto{padding:9px 12px 10px;gap:5px} +.blocco-tetti .tetto .valore b{font-size:17px} +.oggi-basso .testa-blocco{row-gap:6px} +.oggi-basso .testa-blocco h2{margin:0} +.oggi-basso .striscia{height:30px} +.oggi-basso .striscia .freno{top:4px;bottom:4px} +.storia-coda{grid-template-columns:minmax(0,1.6fr) minmax(0,1fr)} +.elenco-attivita.stretto li{min-height:46px;padding:8px 14px} +.storia-righe li{align-items:flex-start} +.btn.collegamento.piede-elenco{display:block;width:100%;padding:10px 14px 11px;text-align:left;border-top:1px solid var(--bordo);border-radius:0 0 var(--r-pannello) var(--r-pannello)} +.miniature{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px;min-height:44px} +.miniatura{position:relative;width:44px;height:44px;padding:0;border:0;border-radius:3px;overflow:hidden;background:var(--rialzo);cursor:zoom-in;flex:none} +.miniatura img{display:block;width:100%;height:100%;object-fit:cover} +.miniatura .vuota{display:flex;width:100%;height:100%;align-items:center;justify-content:center;color:var(--testo-3)} +.miniatura .segni{position:absolute;top:2px;right:2px;display:flex;gap:2px;color:#fff;font-size:9.5px;text-shadow:0 0 3px rgba(0,0,0,.7)} +.miniatura .anello svg.ic{width:11px;height:11px} +.miniatura:focus-visible{outline:2px solid var(--accento);outline-offset:1px} +.miniature-altre{display:inline-flex;align-items:center;justify-content:center;width:44px;height:44px;border-radius:3px;background:var(--rialzo);color:var(--testo-2);font-size:12px} +.anteprima-cronologia{width:min(860px,calc(100vw - 32px));border-radius:14px} +.anteprima-scena{display:flex;align-items:center;gap:10px} +.anteprima-palco{flex:1;min-width:0;height:min(62vh,560px);display:flex;align-items:center;justify-content:center;background:#161616;border-radius:8px;overflow:hidden} +.anteprima-palco img,.anteprima-palco video{max-width:100%;max-height:100%;object-fit:contain} +.anteprima-neutra{display:flex;flex-direction:column;align-items:center;gap:8px;color:rgba(255,255,255,.7);font-size:13px} +.anteprima-dida{display:flex;flex-wrap:wrap;gap:6px 12px;margin-top:10px;font-size:13px} +.btn.tondo{width:36px;height:36px;padding:0;border-radius:50%;justify-content:center;flex:none} +/* «Cosa scaricare prima» (spec §7.2) */ +.ordine-tipi{list-style:none;margin:0;padding:0} +.riga-ordine{display:flex;align-items:center;gap:12px;padding:8px 12px;border-bottom:1px solid var(--bordo);background:var(--superficie)} +.riga-ordine:last-child{border-bottom:0} +.riga-ordine.trascinata{opacity:.55} +.riga-ordine .maniglia{cursor:grab;color:var(--testo-3);display:inline-flex} +.riga-ordine .posizione{width:16px;color:var(--testo-2)} +.riga-ordine .destra{margin-left:auto;display:flex;gap:4px} +.riga-sotto{display:flex;align-items:center;gap:12px;margin-top:8px} +.riga-ordine.spenta b,.riga-ordine.spenta .posizione{color:var(--testo-3)} +.ordine-account{margin-top:10px} +@media (max-width:1000px){ + .storia-coda{grid-template-columns:minmax(0,1fr)} +} +@media (max-width:560px){ + /* On the phone one column: the preview at the top, whole width but lower, then what is happening and the budgets */ + .cruscotto{flex-direction:column;align-items:stretch;padding:12px;gap:14px} + .cruscotto .anteprima{width:100%} + .cruscotto .anteprima .quadro{aspect-ratio:auto;height:196px} + .miniatura,.miniature-altre{width:40px;height:40px} + .miniature{min-height:40px} + .anteprima-palco{height:min(52vh,460px)} + .anteprima-scena .btn.tondo{width:30px;height:30px} +} .ora-pannello{display:flex;align-items:center;gap:24px;padding:18px 18px 18px 24px;min-height:142px} .ora-testo{flex:1;min-width:0} .ora-testo .riga{display:flex;align-items:center;gap:10px} @@ -927,6 +1000,13 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento .marchio-benvenuto svg{width:52px;height:52px} .bottoni-benvenuto{display:flex;gap:12px;margin-top:14px;flex-wrap:wrap;justify-content:center} .nota-benvenuto{font-size:12.5px;margin-top:18px!important} +/* The first start on the Dashboard (spec §7.9): the same welcome, compact, above the cockpit */ +.benvenuto-compatto{display:flex;align-items:flex-start;gap:18px;padding:18px 20px} +.benvenuto-compatto .marchio-benvenuto svg{width:40px;height:40px} +.benvenuto-compatto h2{margin:2px 0 6px;font-size:17px;font-weight:650} +.benvenuto-compatto p{margin:0;color:var(--testo-2);line-height:1.5;font-size:13.5px} +.benvenuto-compatto .bottoni-benvenuto{justify-content:flex-start;margin-top:12px;gap:10px} +.benvenuto-compatto .nota-benvenuto{margin-top:10px!important;font-size:12.5px} .pagina-problemi{max-width:720px;margin:0 auto;padding:40px 24px;display:flex;flex-direction:column;gap:14px;min-height:100vh} .problemi-testa{display:flex;align-items:center;gap:10px;margin-bottom:12px} .problemi-testa .marchio-piccolo svg{width:26px;height:26px;display:block} diff --git a/src/Febe.Web/wwwroot/icone/activity.svg b/src/Febe.Web/wwwroot/icone/chevron-up.svg similarity index 74% rename from src/Febe.Web/wwwroot/icone/activity.svg rename to src/Febe.Web/wwwroot/icone/chevron-up.svg index 0ce6185..c6973da 100644 --- a/src/Febe.Web/wwwroot/icone/activity.svg +++ b/src/Febe.Web/wwwroot/icone/chevron-up.svg @@ -1,3 +1,3 @@ - + diff --git a/src/Febe.Web/wwwroot/icone/grip-vertical.svg b/src/Febe.Web/wwwroot/icone/grip-vertical.svg new file mode 100644 index 0000000..047c3f0 --- /dev/null +++ b/src/Febe.Web/wwwroot/icone/grip-vertical.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/Febe.Web/wwwroot/icone/layout-dashboard.svg b/src/Febe.Web/wwwroot/icone/layout-dashboard.svg new file mode 100644 index 0000000..886599e --- /dev/null +++ b/src/Febe.Web/wwwroot/icone/layout-dashboard.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/Febe.Web/wwwroot/js/core/engine.js b/src/Febe.Web/wwwroot/js/core/engine.js index b2d786c..e5062c9 100644 --- a/src/Febe.Web/wwwroot/js/core/engine.js +++ b/src/Febe.Web/wwwroot/js/core/engine.js @@ -1,5 +1,5 @@ // The engine and the library as seen by the pages: one event stream (/api/eventi) for the whole interface. -// «motore» carries the snapshot (sidebar, stop strip, Attività); «libreria» says the library changed. +// «motore» carries the snapshot (sidebar, stop strip, Dashboard); «libreria» says the library changed. import { api, eventsUrl } from './api.js'; import { caps } from './context.js'; diff --git a/src/Febe.Web/wwwroot/js/core/return-path.js b/src/Febe.Web/wwwroot/js/core/return-path.js index 775a9c6..3253ccb 100644 --- a/src/Febe.Web/wwwroot/js/core/return-path.js +++ b/src/Febe.Web/wwwroot/js/core/return-path.js @@ -6,9 +6,9 @@ const SAFE = /^\/(?![\/\\])[^\\\s\u0000-\u001f\u007f-\u009f]*$/; -export const DEFAULT_PAGE = '/libreria'; +export const DEFAULT_PAGE = '/dashboard'; -/** The absolute address to open after the login, on only; the library when is missing or unsafe. */ +/** The absolute address to open after the login, on only; the Dashboard when is missing or unsafe. */ export function returnAddress(value, origin) { const fallback = new URL(DEFAULT_PAGE, origin).href; if (typeof value !== 'string' || value.length > 2048 || !SAFE.test(value)) { diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js index 354f002..7f5c357 100644 --- a/src/Febe.Web/wwwroot/js/core/shell.js +++ b/src/Febe.Web/wwwroot/js/core/shell.js @@ -1,5 +1,5 @@ -// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Libreria, Account, Attività, Importa, -// separator, Impostazioni, and the status box always visible at the bottom; on the right the page: title row, +// The frame of every page (spec §10.2): fixed 228 px sidebar with brand, Dashboard (the start page, tappa D1), Libreria, +// Account, Importa, separator, Impostazioni, and the status box always visible at the bottom; on the right the page: title row, // optional tools row, scrolling content, fixed bar for the actions that save. The red strip (mockup 11) appears under // the title of every page while the engine is stopped and needs Alberto. Also the router of the addresses. @@ -12,9 +12,9 @@ import { avatar, showError, toast, closeMenu } from './ui.js'; import { routes } from '../routes.js'; const NAV = [ + { key: 'dashboard', href: '/dashboard', icon: 'layout-dashboard' }, { key: 'libreria', href: '/libreria', icon: 'layout-grid' }, { key: 'account', href: '/account', icon: 'users' }, - { key: 'attivita', href: '/attivita', icon: 'activity' }, { key: 'importa', href: '/importa', icon: 'folder-input' }, 'stacco', { key: 'impostazioni', href: '/impostazioni', icon: 'settings' }, @@ -37,13 +37,13 @@ export function buildShell(root) { navLinks[item.key] = a; return a; }); - statusBox = h('a.stato', { href: withCarried('/attivita'), 'aria-label': t('stato.riquadro') }); + statusBox = h('a.stato', { href: withCarried('/dashboard'), 'aria-label': t('stato.riquadro') }); main = h('main.pagina', { id: 'contenuto', tabindex: '-1' }); fill(root, h('a.salta', { href: '#contenuto' }, t('app.salta')), h('div.app', h('aside.barra', - h('a.marchio', { href: withCarried('/libreria') }, brand(), h('b', t('app.nome'))), + h('a.marchio', { href: withCarried('/dashboard') }, brand(), h('b', t('app.nome'))), h('nav.nav', { 'aria-label': t('nav.principale') }, links), h('div.molla'), statusBox), @@ -82,7 +82,7 @@ function renderStatus(state) { h('div.conto', h('span', t('stato.profiliOggi')), h('span', `${meter.usedText} ${meter.limitText}`)), who); statusBox.title = s.details && s.details.length ? s.details.join(' ') : s.headline; - const attention = navLinks.attivita; + const attention = navLinks.dashboard; if (attention) { const dot = attention.querySelector('.punto'); if (s.banner && !dot) attention.append(h('span.punto', { role: 'img', 'aria-label': t('nav.fermo') })); diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js index 8c25139..91bb51e 100644 --- a/src/Febe.Web/wwwroot/js/pages/account.js +++ b/src/Febe.Web/wwwroot/js/pages/account.js @@ -11,8 +11,9 @@ import { navigate, setQuery } from '../core/shell.js'; import { t, number, decimal, dayName, shortDay, capitalize } from '../core/text.js'; import { avatar, checkbox, confirmDialog, menu, segmented, showError, toast, toggle } from '../core/ui.js'; import { accountLabels, accountMenu, checkNow, openProfile } from './accounts.js'; -import { confirmDelete } from './library.js'; -import { Mosaic, justify, tileElement, defaultDayLabel } from './mosaic.js'; +import { confirmDelete, selectionBar } from './library.js'; +import { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitch, storedMode } from './mosaic.js'; +import { kindName, orderEditor, orderOrDefault } from './download-order.js'; import { openViewer } from './viewer.js'; const KINDS = [ @@ -108,6 +109,12 @@ async function contentsTab(page, route, detail) { let kind = available.find((k) => k.key === route.query.get('tipo')) || available.find((k) => s[k.stat] > 0) || available[0]; let period = route.query.get('periodo') || ''; let mosaic = null; + // «Raggruppa i post» / «Tutte le foto» (spec §4.6): one choice for the views of every account, apart from the Libreria. + let mode = storedMode('account'); + const modes = modeSwitch('account', (value) => { + mode = value; + show(); + }); // «In evidenza» is drawn by its own code: its listeners go when another chip is chosen. The token tells a view // still loading that another one took its place. let highlightCleanup = null; @@ -115,7 +122,7 @@ async function contentsTab(page, route, detail) { const chips = h('div.filtri', { role: 'group', 'aria-label': t('scheda.linguette.contenuti') }); const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '150px' } }); const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona'))); - page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', selectButton))); + page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', modes, selectButton))); const host = h('div'); fill(page.body, host); @@ -130,6 +137,8 @@ async function contentsTab(page, route, detail) { }, t(k.label), h('i', number(s[k.stat]))))); fill(periodButton, h('span.val', period ? t(`libreria.periodi.${period}`) : t('libreria.periodi.qualsiasi')), icon('chevron-down', 's')); selectButton.hidden = kind.key === 'evidenza'; + // «In evidenza» is drawn by collection, one tile per item (almost always a single story): no switch there. + modes.hidden = kind.key === 'evidenza'; } periodButton.addEventListener('click', () => menu(periodButton, @@ -158,26 +167,25 @@ async function contentsTab(page, route, detail) { page.saveBar(null); return; } - const n = selected.size; - page.saveBar(h('div', { style: { display: 'contents' } }, - h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')), - h('div.destra', - h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')), - h('button.btn', { type: 'button', disabled: !n, onclick: async () => { - try { - await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv'); - toast(t('selezione.esportato')); - } catch (error) { - showError(error); - } - } }, icon('file-down'), t('selezione.esporta')), - h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: async () => { - const removed = await confirmDelete([...mosaic.selected]); - if (removed) { - mosaic.removeTiles(removed); - setSelecting(false); - } - } }, icon('trash-2'), t('selezione.elimina', { n }))))); + page.saveBar(selectionBar(mosaic, selected, { + cancel: () => setSelecting(false), + exportSelected: async () => { + try { + await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv'); + toast(t('selezione.esportato')); + } catch (error) { + showError(error); + } + }, + deleteSelected: async () => { + const { ids, files } = mosaic.selectedEntries(); + const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null); + if (removed) { + mosaic.removeTiles(removed); + setSelecting(false); + } + }, + })); } function setSelecting(on) { @@ -210,9 +218,10 @@ async function contentsTab(page, route, detail) { host, query: query(), mode: kind.grid ? 'grid' : 'justified', + files: mode === 'files', rowHeight, signal: page.signal, - dayLabel: kind.grid ? storiesDayLabel : defaultDayLabel, + dayLabel: mode === 'files' ? filesDayLabel : kind.grid ? storiesDayLabel : defaultDayLabel, onOpen: (tile) => openViewer({ tile, source: mosaic, origin: `@${detail.account.username}`, onDeleted: (ids) => mosaic.removeTiles(ids) }), onSelection: drawSelection, onEmpty: () => fill(host, h('div.vuoto-pagina', icon(kind.grid ? 'circle-dashed' : 'image'), h('p', t('scheda.nessunContenuto')))), @@ -325,6 +334,7 @@ function settingsTab(page, detail) { function changed() { drawSaveBar(); recompute(); + drawOrder(); } // Tieni aggiornato. @@ -361,6 +371,37 @@ function settingsTab(page, detail) { return box; })); + // Cosa scaricare prima (spec §4.4, §7.2): «Come le impostazioni generali» or an order of its own, which starts from the + // general one. The kinds switched off in «Cosa scaricare» stay in the list, attenuated. + const general = orderOrDefault(detail.generalDownloadOrder); + const KIND_TYPES = { storie: ['stories'], evidenza: ['highlights'], post: ['photos', 'videos'], reel: ['videos'], taggati: ['tagged'] }; + const orderBox = h('div.ordine-account'); + const order = orderEditor({ + read: () => form.downloadOrder, + write: (next) => { form.downloadOrder = next; }, + changed, + off: (kind) => !(KIND_TYPES[kind] || []).some((key) => form.types[key]), + label: t('impAccount.ordineScelta'), + }); + const orderChoice = segmented({ + // The list is «Ordine dei tipi per questo account»; the two-way choice has the name of the section. + label: t('impAccount.ordine'), + value: Array.isArray(form.downloadOrder) && form.downloadOrder.length ? 'own' : 'general', + options: [{ value: 'general', label: t('impAccount.ordineGenerale') }, { value: 'own', label: t('impAccount.ordineSuo') }], + onchange: (v) => { + form.downloadOrder = v === 'own' ? [...general] : null; + changed(); + }, + }); + function drawOrder() { + if (Array.isArray(form.downloadOrder) && form.downloadOrder.length) { + order.draw(); + fill(orderBox, h('div.pannello', order.list), order.status); + } else { + fill(orderBox, h('p.nota', t('impAccount.ordineOra', { ordine: general.map(kindName).join(', ') }))); + } + } + drawOrder(); // Limiti. const depth = h('select', { id: 'profondita' }, ['all', 'lastPosts', 'fromDate'].map((d) => h('option', { value: d, selected: form.depth === d }, t(`impAccount.profondita.${d}`)))); const lastPosts = h('input', { type: 'number', min: '1', step: '1', value: form.lastPosts ?? 100, id: 'ultimi', inputmode: 'numeric' }); @@ -417,6 +458,7 @@ function settingsTab(page, detail) { h('div.sezione', keep, h('p.aiuto', { style: { margin: '6px 0 0 46px' } }, t('impAccount.tieniAiuto'))), h('div.sezione', h('h2.sez', t('impAccount.frequenza')), h('div.frequenza', frequency, frequencyNote), customFields), h('div.sezione', h('h2.sez', t('impAccount.cosa')), h('p.aiuto', t('impAccount.cosaAiuto')), types), + h('div.sezione', h('h2.sez', t('impAccount.ordine')), h('p.aiuto', t('impAccount.ordineAiuto')), orderChoice, orderBox), h('div.sezione', h('h2.sez', t('impAccount.limiti')), h('p.aiuto', t('impAccount.limitiAiuto')), h('div.riga-campi', h('div', h('label.etichetta', { for: 'profondita' }, t('impAccount.quanto')), h('label.campo.scelta', depth, icon('chevron-down', 's'))), diff --git a/src/Febe.Web/wwwroot/js/pages/activity.js b/src/Febe.Web/wwwroot/js/pages/activity.js deleted file mode 100644 index c7b351a..0000000 --- a/src/Febe.Web/wwwroot/js/pages/activity.js +++ /dev/null @@ -1,395 +0,0 @@ -// Attività (mockups 06 and 11, spec §7.9): what the engine is doing now with a still frame of the browser every few -// seconds, the strip of the day, «Limiti di oggi» with the four main budgets and «Tutti i tetti», the queue with -// «verso le» times, «Appena fatto» with the outcomes, the stops of the last days and the alerts (spec §13.3: also the -// ones that are not stops, like a backfill completed or a disk almost full). It updates by itself from the event -// stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame. - -import { api, download, withCarried } from '../core/api.js'; -import { h, icon, fill } from '../core/dom.js'; -import { dotOf, refreshEngine } from '../core/engine.js'; -import { openBrowser } from '../core/shell.js'; -import { t, at, capitalize } from '../core/text.js'; -import { dialog, label, showError, toast } from '../core/ui.js'; -import { dayStrip } from './day-strip.js'; - -const STOPPED = ['StoppedForVerification', 'Disconnected']; - -export default { - async mount(page) { - page.title(t('attivita.titolo')); - const notice = h('div'); - const now = h('section.ora-pannello.pannello'); - const preview = previewBox(page); - const today = h('section.blocco'); - const budgets = h('section.blocco'); - const lists = h('div.due-colonne'); - const suspended = h('div'); - const incidents = h('section.blocco'); - const alerts = h('section.blocco', { hidden: true }); - // On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11). - page.root.dataset.pagina = 'attivita'; - fill(page.body, h('div.attivita', now, suspended, today, budgets, lists, notice, incidents, alerts)); - - let latest = null; - page.onEngine((state) => { - latest = state; - drawActions(page, state); - drawNow(now, preview, state); - drawToday(today, state); - drawBudgets(budgets, state); - drawLists(lists, state); - drawSuspended(suspended, state); - preview.update(state); - }); - - async function loadSide() { - try { - const [counts, history, recent] = await Promise.all([ - api('/api/duplicates/count', { signal: page.signal }), - api('/api/engine/incidents', { signal: page.signal }), - api('/api/alerts', { signal: page.signal }), - ]); - drawNotice(notice, counts); - drawIncidents(incidents, history); - drawAlerts(alerts, recent); - } catch (error) { - if (error.name !== 'AbortError') showError(error); - } - } - await loadSide(); - if (page.signal.aborted) return; - page.onLibrary(() => loadSide()); - const timer = setInterval(() => { - if (latest && document.visibilityState === 'visible') loadSide(); - }, 60000); - page.onLeave(() => clearInterval(timer)); - }, -}; - -// ------------------------------------------------------------------------------------------------- title actions - -function drawActions(page, state) { - const s = state.snapshot; - const resume = async () => { - try { - const result = await api('/api/engine/resume', { method: 'POST' }); - toast(result.message, result.resumed ? '' : 'errore'); - refreshEngine(); - } catch (error) { - showError(error); - } - }; - const pause = async () => { - try { - const result = await api('/api/engine/pause', { method: 'POST' }); - toast(result.message); - refreshEngine(); - } catch (error) { - showError(error); - } - }; - const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume); - const first = needsResume - ? h('button.btn', { - type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume, - title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'), - }, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi'))) - : h('button.btn', { - type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'), - }, icon('pause'), h('span.testo-btn', t('attivita.pausa'))); - page.actions( - first, - h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))), - diagnosticsButton(), - ); -} - -// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click -// may be gone by the end: the flag, not the button, says whether an export is running. -let exporting = false; - -/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */ -function diagnosticsButton() { - const button = h('button.btn', { - type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting, - }, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica'))); - button.onclick = async () => { - if (exporting) return; - exporting = true; - button.disabled = true; - try { - await download('/api/engine/diagnostica', null, 'febe-diagnostica.json'); - toast(t('attivita.diagnosticaEsportata')); - } catch (error) { - showError(error); - } finally { - exporting = false; - // The button on the page now, which may not be this one. - for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false; - } - }; - button.dataset.diagnostica = ''; - return button; -} - -// ------------------------------------------------------------------------------------------------- now - -function drawNow(box, preview, state) { - const s = state.snapshot; - const dot = dotOf(s.mode); - const [first, ...rest] = s.details || []; - fill(box, - h('div.ora-testo', - h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)), - first ? h('p.cosa', first) : null, - rest.length ? h('p.dettaglio', rest.join(' ')) : null, - s.reductionNote ? h('p.dettaglio', s.reductionNote) : null), - preview.element); -} - -/** The still frame of the browser: one image every few seconds, never a video (mockup 06). */ -function previewBox(page) { - const address = h('span.indirizzo.dati'); - const image = h('img', { alt: t('attivita.anteprima'), hidden: true }); - const placeholder = h('div.segnaposto-anteprima'); - const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder)); - let mode = null; - let frameUrl = null; - let timer = 0; - let stopped = false; - - function placeholderFor(m) { - if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/']; - if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null]; - if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null]; - if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null]; - return ['moon', t('attivita.anteprimaVuota'), 'about:blank']; - } - - async function load() { - clearTimeout(timer); - if (stopped) return; - try { - const result = await api('/api/browser/preview', { signal: page.signal }); - if (result.hasFrame && result.frame) { - if (result.frame !== frameUrl) { - frameUrl = result.frame; - image.src = withCarried(result.frame); - } - image.hidden = false; - placeholder.hidden = true; - address.textContent = shortUrl(result.url); - } else { - showPlaceholder(); - } - } catch (error) { - if (error.name === 'AbortError') return; - showPlaceholder(); - } - const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode); - timer = setTimeout(load, busy ? 5000 : 30000); - } - - function showPlaceholder() { - frameUrl = null; - image.hidden = true; - image.removeAttribute('src'); - const [name, text, url] = placeholderFor(mode); - fill(placeholder, icon(name, 'l'), h('span', text)); - placeholder.hidden = false; - address.textContent = url ? shortUrl(url) : ''; - } - - page.onLeave(() => { - stopped = true; - clearTimeout(timer); - }); - - return { - element, - update(state) { - const changed = state.snapshot.mode !== mode; - mode = state.snapshot.mode; - if (changed) load(); - }, - }; -} - -function shortUrl(url) { - if (!url) return ''; - return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, ''); -} - -// ------------------------------------------------------------------------------------------------- strip - -function drawToday(box, state) { - const s = state.snapshot; - const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) }); - fill(box, - h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend), - strip, hours); -} - -// ------------------------------------------------------------------------------------------------- budgets - -function drawBudgets(box, state) { - const s = state.snapshot; - const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled'; - const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine; - fill(box, - h('div.testa-blocco', - h('h2', t('attivita.limiti')), - h('span.muto', profile), - s.reductionNote ? label(s.reductionNote, 'ambra') : null, - h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))), - h('div.tetti.pannello', s.mainBudgets.map((b) => budgetCard(b, frozen)))); -} - -function budgetCard(b, frozen) { - const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : ''; - return h('div.tetto', - h('span.nome', b.label), - h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)), - h(`div.misura${meterClass}`, { - role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday), - }, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })), - h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note)); -} - -function allBudgets(state) { - const s = state.snapshot; - const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled'; - const cell = (used, limit, text, ratio, amber) => h('td', - h('div.cella-tetto', - h('span.dati', text), - limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null)); - dialog({ - title: t('attivita.tetti.titolo'), - className: 'tutti-tetti', - build: (close) => ({ - body: h('div.contenuto', - h('p.aiuto', t('attivita.tetti.aiuto')), - h('table.tab', - h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))), - h('tbody', s.allBudgets.map((b) => h('tr', - h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)), - b.limitPerHour == null - ? h('td.muto', '—') - : cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8), - cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))), - footer: h('footer', - h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')), - h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))), - }), - }); -} - -// ------------------------------------------------------------------------------------------------- queue and latest actions - -function badgeKind(text) { - const v = String(text || '').toLowerCase(); - if (v.includes('in corso')) return 'accento'; - if (v.includes('scaricat') || v.includes('nuov')) return 'verde'; - if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso'; - if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra'; - return ''; -} - -function drawLists(box, state) { - const s = state.snapshot; - const queue = s.queue.length - ? h('ul.elenco-attivita', s.queue.map((q) => h('li', - h('span.quando.dati', q.when), - h('div.chi-cosa', h('b', q.title), h('span', q.detail)), - q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null))) - : h('p.vuoto-elenco', t('attivita.codaVuota')); - const recent = s.recentActions.length - ? h('ul.elenco-attivita', s.recentActions.map((r) => h('li', - h('span.quando.dati', r.time), - h('div.chi-cosa', h('b', r.title), h('span', r.detail)), - r.badge ? label(r.badge, badgeKind(r.badge)) : null))) - : h('p.vuoto-elenco', t('attivita.fattoVuoto')); - fill(box, - h('section', h('h2', t('attivita.coda')), h('div.pannello', queue)), - h('section', h('h2', t('attivita.fatto')), h('div.pannello', recent))); -} - -// ------------------------------------------------------------------------------------------------- side information - -function drawNotice(box, counts) { - if (!counts || !counts.download) { - box.replaceChildren(); - return; - } - fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'), - h('span', t('attivita.doppioni', { n: counts.download })), - h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi')))); -} - -/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */ -function drawSuspended(box, state) { - const items = state.snapshot.suspendedRecipes || []; - if (!items.length) { - box.replaceChildren(); - return; - } - fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } }, - icon('octagon-alert', 's'), - h('span', t('attivita.sospesa', { nome: r.name })), - h('button.btn.piccolo', { - type: 'button', - onclick: async () => { - try { - const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' }); - toast(result.message, result.resumed ? '' : 'errore'); - refreshEngine(); - } catch (error) { - showError(error); - } - }, - }, t('attivita.riattiva'))))); -} - -const ALERT_LOOK = { - error: { icon: 'octagon-alert', label: 'rosso' }, - warning: { icon: 'triangle-alert', label: 'ambra' }, - success: { icon: 'circle-check', label: 'verde' }, - info: { icon: 'bell', label: '' }, -}; - -/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */ -function drawAlerts(box, recent) { - const items = (recent && recent.items) || []; - box.hidden = !items.length; - if (!items.length) { - box.replaceChildren(); - return; - } - fill(box, - h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))), - h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => { - const look = ALERT_LOOK[i.level] || ALERT_LOOK.info; - return h('li', - h('span.quando.dati', capitalize(at(i.at))), - h('div.chi-cosa', h('b', i.title), h('span', i.message)), - label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon)); - })))); -} - -function drawIncidents(box, history) { - const items = history.items || []; - fill(box, - h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))), - history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null, - items.length - ? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li', - h('span.quando.dati', capitalize(at(i.at))), - h('div.chi-cosa', - h('b', i.title, ' ', h('span.codice.dati', i.signal)), - h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))), - i.open - ? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso') - : h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : ''))))) - : h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti'))); -} - diff --git a/src/Febe.Web/wwwroot/js/pages/browser.js b/src/Febe.Web/wwwroot/js/pages/browser.js index ad0b7d8..581aea0 100644 --- a/src/Febe.Web/wwwroot/js/pages/browser.js +++ b/src/Febe.Web/wwwroot/js/pages/browser.js @@ -37,7 +37,7 @@ export default { // «Ho finito» gives the browser back on the server whatever the answer. lease.settled(); toast(result.message, result.connected ? '' : 'errore'); - if (result.connected) navigate('/attivita'); + if (result.connected) navigate('/dashboard'); else fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message))); }; page.saveBar(h('div', { style: { display: 'contents' } }, diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard.js b/src/Febe.Web/wwwroot/js/pages/dashboard.js new file mode 100644 index 0000000..8602f18 --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/dashboard.js @@ -0,0 +1,730 @@ +// Dashboard (spec §7.9, §10.2, tappa D1; before it was Attività, mockups 06 and 11): the start page, where Alberto stays +// while the engine works. Compact, to fit the top of a 1440 × 900 window without scrolling: at the top the preview of +// the browser, always visible and refreshed at every new frame (at most one a second), with beside it what the engine +// is doing now and the four main budgets in one row («Tutti i tetti» for the others); then the strip of the day, lower; +// then in two columns the history with the thumbnails of what arrived (loaded only when the line is in view, at most +// eight with «+N»; a click opens a light enlarged preview) and the queue with «verso le» times, cut to the first rows +// with «Mostra tutta». Below: the stops of the last days and the alerts (spec §13.3). It updates by itself from the +// event stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame. + +import { api, download, withCarried } from '../core/api.js'; +import { h, icon, fill } from '../core/dom.js'; +import { dotOf, refreshEngine } from '../core/engine.js'; +import { openBrowser } from '../core/shell.js'; +import { t, at, capitalize, dayName, duration } from '../core/text.js'; +import { dialog, label, showError, toast } from '../core/ui.js'; +import { dayStrip } from './day-strip.js'; +import { openViewer } from './viewer.js'; +import { compactWelcome } from './welcome.js'; + +const STOPPED = ['StoppedForVerification', 'Disconnected']; +// Rows of the queue shown before «Mostra tutta»; thumbnails of a line of the history before «+N» (spec §7.9). +const QUEUE_ROWS = 5; +const THUMBS = 8; + +export default { + async mount(page) { + page.title(t('attivita.titolo')); + const notice = h('div'); + const now = h('div.ora-testo'); + const preview = previewBox(page); + const today = h('section.blocco.oggi-basso'); + const budgets = h('section.blocco-tetti'); + const history = historyBox(page); + const queue = queueBox(); + const suspended = h('div'); + const incidents = h('section.blocco'); + const alerts = h('section.blocco', { hidden: true }); + const first = firstStart(page); + // On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11). + page.root.dataset.pagina = 'dashboard'; + fill(page.body, h('div.attivita.dashboard', + first.element, + h('section.cruscotto.pannello', preview.element, h('div.cruscotto-lato', now, budgets)), + suspended, today, + h('div.due-colonne.storia-coda', history.element, queue.element), + notice, incidents, alerts)); + + let latest = null; + page.onEngine((state) => { + latest = state; + drawActions(page, state); + drawNow(now, state); + drawToday(today, state); + drawBudgets(budgets, state); + history.draw(state); + queue.draw(state); + drawSuspended(suspended, state); + preview.update(state); + first.draw(state); + }); + + async function loadSide() { + first.check(); + try { + const [counts, history, recent] = await Promise.all([ + api('/api/duplicates/count', { signal: page.signal }), + api('/api/engine/incidents', { signal: page.signal }), + api('/api/alerts', { signal: page.signal }), + ]); + drawNotice(notice, counts); + drawIncidents(incidents, history); + drawAlerts(alerts, recent); + } catch (error) { + if (error.name !== 'AbortError') showError(error); + } + } + await loadSide(); + if (page.signal.aborted) return; + page.onLibrary(() => loadSide()); + const timer = setInterval(() => { + if (latest && document.visibilityState === 'visible') loadSide(); + }, 60000); + page.onLeave(() => clearInterval(timer)); + }, +}; + +// ------------------------------------------------------------------------------------------------- first start + +/** + * The first start (spec §7.9, §10.3): / opens the Dashboard, so while there is no account a compact welcome sits above + * the cockpit with the ways to begin of the Library's welcome. Asked again with the side information (every minute, + * and when the library changes) only while it is shown, so that it goes away once an account is there. + */ +function firstStart(page) { + const element = h('div'); + let empty = null; // unknown until the accounts answer + let state = null; + let shown = null; + + function draw(latest) { + if (latest) state = latest; + const kind = !empty || !state ? null : state.connection && state.connection.state === 'notConnected' ? 'collegati' : 'aggiungi'; + if (kind === shown) return; + shown = kind; + if (kind) fill(element, compactWelcome(kind === 'aggiungi')); + else element.replaceChildren(); + } + + async function check() { + if (empty === false) return; + try { + const result = await api('/api/accounts', { signal: page.signal }); + empty = !(result.accounts && result.accounts.length); + } catch (error) { + if (error.name === 'AbortError') return; + } + draw(null); + } + + return { element, draw, check }; +} + +// ------------------------------------------------------------------------------------------------- title actions + +function drawActions(page, state) { + const s = state.snapshot; + const resume = async () => { + try { + const result = await api('/api/engine/resume', { method: 'POST' }); + toast(result.message, result.resumed ? '' : 'errore'); + refreshEngine(); + } catch (error) { + showError(error); + } + }; + const pause = async () => { + try { + const result = await api('/api/engine/pause', { method: 'POST' }); + toast(result.message); + refreshEngine(); + } catch (error) { + showError(error); + } + }; + const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume); + const first = needsResume + ? h('button.btn', { + type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume, + title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'), + }, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi'))) + : h('button.btn', { + type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'), + }, icon('pause'), h('span.testo-btn', t('attivita.pausa'))); + page.actions( + first, + h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))), + diagnosticsButton(), + ); +} + +// True while a report is being exported. The title row is rebuilt at every engine update, so the button of the click +// may be gone by the end: the flag, not the button, says whether an export is running. +let exporting = false; + +/** «Diagnostica»: the report of the last two weeks of sessions, with no name in it, to send after a test gone wrong (#39). */ +function diagnosticsButton() { + const button = h('button.btn', { + type: 'button', title: t('attivita.esportaDiagnostica'), 'aria-label': t('attivita.esportaDiagnostica'), disabled: exporting, + }, icon('file-down'), h('span.testo-btn', t('attivita.diagnostica'))); + button.onclick = async () => { + if (exporting) return; + exporting = true; + button.disabled = true; + try { + await download('/api/engine/diagnostica', null, 'febe-diagnostica.json'); + toast(t('attivita.diagnosticaEsportata')); + } catch (error) { + showError(error); + } finally { + exporting = false; + // The button on the page now, which may not be this one. + for (const shown of document.querySelectorAll('[data-diagnostica]')) shown.disabled = false; + } + }; + button.dataset.diagnostica = ''; + return button; +} + +// ------------------------------------------------------------------------------------------------- now + +function drawNow(box, state) { + const s = state.snapshot; + const dot = dotOf(s.mode); + const [first, ...rest] = s.details || []; + fill(box, + h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)), + first ? h('p.cosa', first) : null, + rest.length ? h('p.dettaglio', rest.join(' ')) : null, + s.reductionNote ? h('p.dettaglio', s.reductionNote) : null); +} + +/** + * The preview of the browser, always visible (spec §7.9): the page the browser of Febe is looking at, frames and never + * a video. While the engine works it asks every second and swaps the picture only when the frame is new (the server + * takes at most one a second, however many pages ask); otherwise every 30 seconds. Out of a session it says why it + * is still. A hidden tab asks nothing. + */ +function previewBox(page) { + const address = h('span.indirizzo.dati'); + const image = h('img', { alt: t('attivita.anteprima'), hidden: true }); + const placeholder = h('div.segnaposto-anteprima'); + const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder)); + let mode = null; + let frameUrl = null; + let timer = 0; + let stopped = false; + + function placeholderFor(m) { + if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/']; + if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null]; + if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null]; + if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null]; + return ['moon', t('attivita.anteprimaVuota'), 'about:blank']; + } + + async function load() { + clearTimeout(timer); + if (stopped) return; + try { + const result = await api('/api/browser/preview', { signal: page.signal }); + if (result.hasFrame && result.frame) { + if (result.frame !== frameUrl) { + frameUrl = result.frame; + image.src = withCarried(result.frame); + } + image.hidden = false; + placeholder.hidden = true; + address.textContent = shortUrl(result.url); + } else { + showPlaceholder(); + } + } catch (error) { + if (error.name === 'AbortError') return; + showPlaceholder(); + } + const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode); + timer = setTimeout(() => { + if (document.visibilityState === 'visible') load(); + else waiting = true; + }, busy ? 1000 : 30000); + } + + // Back to a visible tab: at once, instead of after the next interval. + let waiting = false; + const onVisible = () => { + if (document.visibilityState === 'visible' && waiting) { + waiting = false; + load(); + } + }; + document.addEventListener('visibilitychange', onVisible); + + function showPlaceholder() { + frameUrl = null; + image.hidden = true; + image.removeAttribute('src'); + const [name, text, url] = placeholderFor(mode); + fill(placeholder, icon(name, 'l'), h('span', text)); + placeholder.hidden = false; + address.textContent = url ? shortUrl(url) : ''; + } + + page.onLeave(() => { + stopped = true; + clearTimeout(timer); + document.removeEventListener('visibilitychange', onVisible); + }); + + return { + element, + update(state) { + const changed = state.snapshot.mode !== mode; + mode = state.snapshot.mode; + if (changed) load(); + }, + }; +} + +function shortUrl(url) { + if (!url) return ''; + return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, ''); +} + +// ------------------------------------------------------------------------------------------------- strip + +function drawToday(box, state) { + const s = state.snapshot; + const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) }); + fill(box, + h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend), + strip, hours); +} + +// ------------------------------------------------------------------------------------------------- budgets + +function drawBudgets(box, state) { + const s = state.snapshot; + const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled'; + const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine; + fill(box, + h('div.testa-blocco', + h('h2', t('attivita.limiti')), + h('span.muto', profile), + h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))), + h('div.tetti', s.mainBudgets.map((b) => budgetCard(b, frozen)))); +} + +function budgetCard(b, frozen) { + const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : ''; + return h('div.tetto', + h('span.nome', b.label), + h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)), + h(`div.misura${meterClass}`, { + role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday), + }, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })), + h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note)); +} + +function allBudgets(state) { + const s = state.snapshot; + const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled'; + const cell = (used, limit, text, ratio, amber) => h('td', + h('div.cella-tetto', + h('span.dati', text), + limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null)); + dialog({ + title: t('attivita.tetti.titolo'), + className: 'tutti-tetti', + build: (close) => ({ + body: h('div.contenuto', + h('p.aiuto', t('attivita.tetti.aiuto')), + h('table.tab', + h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))), + h('tbody', s.allBudgets.map((b) => h('tr', + h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)), + b.limitPerHour == null + ? h('td.muto', '—') + : cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8), + cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))), + footer: h('footer', + h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')), + h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))), + }), + }); +} + +// ------------------------------------------------------------------------------------------------- queue and latest actions + +function badgeKind(text) { + const v = String(text || '').toLowerCase(); + if (v.includes('in corso')) return 'accento'; + if (v.includes('scaricat') || v.includes('nuov')) return 'verde'; + if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso'; + if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra'; + return ''; +} + +/** The queue with «verso le» times, cut to the first rows; «Mostra tutta» opens it whole until the page is left. */ +function queueBox() { + const element = h('section.coda'); + let whole = false; + let last = null; + function draw(state) { + last = state; + const items = state.snapshot.queue; + const shown = whole ? items : items.slice(0, QUEUE_ROWS); + const list = items.length + ? h('ul.elenco-attivita.stretto', shown.map((q) => h('li', + h('span.quando.dati', q.when), + h('div.chi-cosa', h('b', q.title), h('span', q.detail)), + q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null))) + : h('p.vuoto-elenco', t('attivita.codaVuota')); + const more = items.length > QUEUE_ROWS + ? h('button.btn.collegamento.piede-elenco', { + type: 'button', + 'aria-expanded': String(whole), + onclick: () => { + whole = !whole; + draw(last); + }, + }, whole ? t('attivita.mostraMeno') : t('attivita.mostraTutta', { n: items.length })) + : null; + fill(element, h('h2', t('attivita.coda')), h('div.pannello', list, more)); + } + return { element, draw }; +} + +/** + * The history of the activity (spec §7.9): the last recipe runs with their outcome; a line that saved something shows + * the thumbnails of what arrived, asked to the server only when the line comes into view and kept while the page is + * open, so that the engine updates never ask again for the same line. + */ +function historyBox(page) { + const element = h('section.storia'); + const arrived = new Map(); + const watcher = 'IntersectionObserver' in window + ? new IntersectionObserver((entries) => { + for (const e of entries) { + if (!e.isIntersecting) continue; + watcher.unobserve(e.target); + loadThumbs(e.target); + } + }, { rootMargin: '200px 0px' }) + : null; + page.onLeave(() => watcher && watcher.disconnect()); + + function keyOf(r) { + return `${r.accountId || ''}|${r.from}|${r.at}`; + } + + async function loadThumbs(holder) { + const key = holder.dataset.chiave; + const known = arrived.get(key); + if (known && known.result) { + paint(holder, known); + return; + } + if (known && known.loading) return; + const item = { loading: true, result: null, line: holder.line }; + arrived.set(key, item); + try { + item.result = await api(`/api/activity/arrived?${arrivedQuery(holder.line, THUMBS)}`, { signal: page.signal }); + } catch (error) { + if (error.name === 'AbortError') return; + item.result = { tiles: [], total: 0 }; + } finally { + item.loading = false; + } + // The line may have been drawn again meanwhile: paint the holder that is on the page now. + const shown = element.querySelector(`[data-chiave="${CSS.escape(key)}"]`); + if (shown) paint(shown, item); + } + + function paint(holder, item) { + const { tiles, total } = item.result; + // The holder keeps the room of a row of thumbnails while it waits (an element with no size is never in view). + if (!tiles.length) { + holder.replaceChildren(); + holder.hidden = true; + return; + } + const rest = Math.max(0, total - tiles.length); + fill(holder, + tiles.map((tile, i) => thumb(tile, () => openPreview(page, item.line, tiles, total, i))), + rest > 0 ? h('span.miniature-altre.dati', { title: t('attivita.altreArrivate', { n: rest }) }, `+${rest}`) : null); + } + + function draw(state) { + const items = state.snapshot.recentActions; + if (!items.length) { + fill(element, h('h2', t('attivita.fatto')), h('div.pannello', h('p.vuoto-elenco', t('attivita.fattoVuoto')))); + return; + } + const list = h('ul.elenco-attivita.storia-righe', items.map((r) => { + let holder = null; + if (r.from && r.newEntries > 0) { + holder = h('div.miniature', { dataset: { chiave: keyOf(r) }, 'aria-label': t('attivita.arrivate', { n: r.newEntries }), role: 'group' }); + holder.line = r; + const known = arrived.get(keyOf(r)); + if (known && known.result) paint(holder, known); + else if (watcher) watcher.observe(holder); + else loadThumbs(holder); + } + return h('li', + h('span.quando.dati', r.time), + h('div.chi-cosa', h('b', r.title), r.detail ? h('span', r.detail) : null, holder), + r.badge ? label(r.badge, badgeKind(r.badge)) : null); + })); + fill(element, h('h2', t('attivita.fatto')), h('div.pannello', list)); + // Lines no longer shown are forgotten, so that a long day does not keep every answer. + const keys = new Set(items.filter((r) => r.from).map(keyOf)); + for (const key of arrived.keys()) if (!keys.has(key)) arrived.delete(key); + } + + return { element, draw }; +} + +/** + * The question for what a line of the history saved: the recipe's account and time; a line without an account (the + * Giro dei seguiti saves posts of many accounts) asks for what arrived of every account in that time. + */ +function arrivedQuery(line, limit) { + const query = new URLSearchParams({ from: line.from, to: line.at, limit: String(limit) }); + if (line.accountId) query.set('account', String(line.accountId)); + return query; +} + +/** A small tile of the history: the thumbnail of §8.4 with the marks of the mosaic (video length, ring of stories). */ +function thumb(tile, onOpen) { + const cover = tile.cover; + const marks = []; + if (tile.kind === 'story') marks.push(h('span.anello', icon('circle-dashed', 'xs'))); + if (cover && cover.kind === 'video') marks.push(h('span.durata', duration(cover.duration || 0))); + const what = t(`libreria.tipiTessera.${tile.kind}`); + return h('button.miniatura', { + type: 'button', + onclick: onOpen, + 'aria-label': t('attivita.apriAnteprima', { tipo: what, account: tile.username }), + title: `${what}, @${tile.username}`, + }, + cover && cover.thumb + ? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' }) + : h('span.vuota', icon('image', 'xs')), + marks.length ? h('span.segni', marks) : null); +} + +/** + * The enlarged preview of a line of the history (spec §7.9): a light dialog over the page, without leaving it. The + * photo or the video (without sound), account, kind, date, arrows between the files of that line, Esc that closes; + * «Apri nella Libreria» opens the viewer of §4.6 on that entry, «Apri l'account» its tab. A damaged or incomplete file + * shows the neutral tile. The files of an entry are asked only when the arrows reach it. + */ +async function openPreview(page, line, firstTiles, total, startIndex) { + let tiles = firstTiles; + // More entries than the thumbnails: the arrows walk all of them (up to the server's limit). + if (total > firstTiles.length) { + try { + const all = await api(`/api/activity/arrived?${arrivedQuery(line, 60)}`, { signal: page.signal }); + if (all.tiles.length) tiles = all.tiles; + } catch (error) { + if (error.name === 'AbortError') return; + } + } + const entries = new Map(); + let entryIndex = Math.max(0, tiles.findIndex((x) => x.id === firstTiles[startIndex].id)); + let fileIndex = 0; + let token = 0; + const stage = h('div.anteprima-palco'); + const caption = h('div.anteprima-dida'); + const position = h('span.dati.muto'); + const prev = h('button.btn.nudo.tondo', { type: 'button', 'aria-label': t('vis.precedente'), onclick: () => step(-1) }, icon('chevron-left')); + const next = h('button.btn.nudo.tondo', { type: 'button', 'aria-label': t('vis.successivo'), onclick: () => step(1) }, icon('chevron-right')); + let closeDialog = null; + // «Apri l'account» follows the arrows: a line of the Giro dei seguiti holds entries of many accounts. + const accountLink = h('a.btn', { onclick: () => closeDialog() }, icon('user'), t('attivita.apriAccount')); + + async function entryOf(i) { + const id = tiles[i].id; + if (!entries.has(id)) entries.set(id, api(`/api/entries/${id}`, { signal: page.signal }).catch(() => null)); + return entries.get(id); + } + + async function show() { + const mine = ++token; + const tile = tiles[entryIndex]; + accountLink.href = withCarried(`/account/${tile.accountId}/contenuti`); + const entry = await entryOf(entryIndex); + if (mine !== token) return; + const media = entry && entry.media.length ? entry.media[Math.min(fileIndex, entry.media.length - 1)] : null; + const thumbUrl = media && media.thumb ? `/api/thumbnails/${media.thumb}` : tile.cover && tile.cover.thumb ? `/api/thumbnails/${tile.cover.thumb}` : null; + if (!media || media.damaged || !media.available) { + fill(stage, h('div.anteprima-neutra', icon('image', 'l'), + media && media.damaged ? h('p', t('vis.danneggiato')) : media && !media.available ? h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante')) : null)); + } else if (media.kind === 'video') { + const video = h('video', { src: `/api/media/${media.id}/file`, poster: thumbUrl, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata' }); + video.muted = true; // spec §10.3: videos start without sound + fill(stage, video); + } else { + fill(stage, h('img', { src: `/api/media/${media.id}/file`, alt: `@${tile.username}` })); + } + const files = entry ? entry.media.length : 1; + fill(caption, + h('b', `@${tile.username}`), + h('span', t(`libreria.tipiTessera.${tile.kind}`)), + h('span.muto', `${capitalize(dayName(tile.day, ''))}, ${tile.time}`), + files > 1 ? h('span.muto', t('attivita.fileDi', { n: fileIndex + 1, di: files })) : null); + position.textContent = t('attivita.elementoDi', { n: entryIndex + 1, di: tiles.length }); + prev.disabled = entryIndex === 0 && fileIndex === 0; + next.disabled = entryIndex === tiles.length - 1 && fileIndex >= files - 1; + } + + async function step(delta) { + const entry = await entryOf(entryIndex); + const files = entry ? entry.media.length : 1; + if (delta > 0) { + if (fileIndex < files - 1) fileIndex += 1; + else if (entryIndex < tiles.length - 1) { + entryIndex += 1; + fileIndex = 0; + } else return; + } else if (fileIndex > 0) fileIndex -= 1; + else if (entryIndex > 0) { + entryIndex -= 1; + const before = await entryOf(entryIndex); + fileIndex = before ? Math.max(0, before.media.length - 1) : 0; + } else return; + show(); + } + + function onKey(event) { + if (event.key === 'ArrowLeft') { + event.preventDefault(); + step(-1); + } else if (event.key === 'ArrowRight') { + event.preventDefault(); + step(1); + } + } + + const list = { + position: (id) => { + const i = tiles.findIndex((x) => x.id === id); + return i < 0 ? null : { index: i, total: tiles.length }; + }, + neighbor: async (id, delta) => { + const i = tiles.findIndex((x) => x.id === id); + return i < 0 ? null : tiles[i + delta] || null; + }, + }; + + dialog({ + title: t('attivita.anteprimaTitolo'), + className: 'anteprima-cronologia', + build: (close) => { + closeDialog = close; + // The arrows walk the files wherever the focus is in the dialog (also on its buttons); Esc is the dialog's. + document.addEventListener('keydown', onKey); + return { + onClose: () => { + token += 1; // an entry still loading draws nothing any more + document.removeEventListener('keydown', onKey); + }, + body: h('div.contenuto', h('div.anteprima-scena', prev, stage, next), caption), + footer: h('footer', + position, + h('div.destra', + accountLink, + h('button.btn.primo', { + type: 'button', + onclick: () => { + const tile = tiles[entryIndex]; + closeDialog(); + openViewer({ tile, source: list, origin: t('nav.libreria') }); + }, + }, icon('layout-grid'), t('attivita.apriLibreria')))), + }; + }, + }); + show(); +} + +// ------------------------------------------------------------------------------------------------- side information + +function drawNotice(box, counts) { + if (!counts || !counts.download) { + box.replaceChildren(); + return; + } + fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'), + h('span', t('attivita.doppioni', { n: counts.download })), + h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi')))); +} + +/** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */ +function drawSuspended(box, state) { + const items = state.snapshot.suspendedRecipes || []; + if (!items.length) { + box.replaceChildren(); + return; + } + fill(box, items.map((r) => h('div.avviso.rosso.avviso-azione', { style: { marginBottom: '10px' } }, + icon('octagon-alert', 's'), + h('span', t('attivita.sospesa', { nome: r.name })), + h('button.btn.piccolo', { + type: 'button', + onclick: async () => { + try { + const result = await api(`/api/engine/recipes/${encodeURIComponent(r.recipe)}/resume`, { method: 'POST' }); + toast(result.message, result.resumed ? '' : 'errore'); + refreshEngine(); + } catch (error) { + showError(error); + } + }, + }, t('attivita.riattiva'))))); +} + +const ALERT_LOOK = { + error: { icon: 'octagon-alert', label: 'rosso' }, + warning: { icon: 'triangle-alert', label: 'ambra' }, + success: { icon: 'circle-check', label: 'verde' }, + info: { icon: 'bell', label: '' }, +}; + +/** «Avvisi»: every alert of the last days, the same ones Telegram and Windows get. Hidden while there are none. */ +function drawAlerts(box, recent) { + const items = (recent && recent.items) || []; + box.hidden = !items.length; + if (!items.length) { + box.replaceChildren(); + return; + } + fill(box, + h('div.testa-blocco', h('h2', t('attivita.avvisi')), h('span.muto', t('attivita.avvisiAiuto', { giorni: recent.days }))), + h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => { + const look = ALERT_LOOK[i.level] || ALERT_LOOK.info; + return h('li', + h('span.quando.dati', capitalize(at(i.at))), + h('div.chi-cosa', h('b', i.title), h('span', i.message)), + label(t(`attivita.livelliAvviso.${i.level}`), look.label, look.icon)); + })))); +} + +function drawIncidents(box, history) { + const items = history.items || []; + fill(box, + h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))), + history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null, + items.length + ? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li', + h('span.quando.dati', capitalize(at(i.at))), + h('div.chi-cosa', + h('b', i.title, ' ', h('span.codice.dati', i.signal)), + h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))), + i.open + ? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso') + : h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : ''))))) + : h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti'))); +} + diff --git a/src/Febe.Web/wwwroot/js/pages/day-strip.js b/src/Febe.Web/wwwroot/js/pages/day-strip.js index 4fb8c04..7b673f4 100644 --- a/src/Febe.Web/wwwroot/js/pages/day-strip.js +++ b/src/Febe.Web/wwwroot/js/pages/day-strip.js @@ -49,10 +49,11 @@ export function dayStrip(day, { stopOpen = false } = {}) { case 'Session': case 'CurrentSession': case 'PlannedSession': { + // Bars of nearly the whole height, uneven by a few percent (mockup 06): in proportion to the strip, so that + // the lower strip of the Dashboard draws bars and not dots. const w = wobble(ms(s.start) / 60000); - const inset = 6 + Math.round(w * 4); el = h(`span.sess${s.kind === 'CurrentSession' ? '.ora' : ''}${s.kind === 'PlannedSession' ? '.prev' : ''}`, - { style: { ...style, top: `${inset}px`, bottom: `${6 + Math.round((1 - w) * 4)}px` } }); + { style: { ...style, top: `${(10 + w * 8).toFixed(1)}%`, bottom: `${(10 + (1 - w) * 8).toFixed(1)}%` } }); kinds.add(s.kind === 'PlannedSession' ? 'prossime' : 'sessione'); break; } diff --git a/src/Febe.Web/wwwroot/js/pages/download-order.js b/src/Febe.Web/wwwroot/js/pages/download-order.js new file mode 100644 index 0000000..7a65643 --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/download-order.js @@ -0,0 +1,100 @@ +// «Cosa scaricare prima» (spec §7.2, §4.4, tappa D1): the list of the five kinds that moves by dragging (mouse) or with +// «Su» and «Giù» (keyboard), shared by Impostazioni → Limiti e comportamento and by the account card → Impostazioni. +// The page keeps the order and saves it with its save bar; this module only draws and moves the rows. + +import { h, icon, fill } from '../core/dom.js'; +import { t } from '../core/text.js'; + +/** The default order of the kinds, the one the server also uses. */ +export const DEFAULT_ORDER = ['storie', 'evidenza', 'post', 'reel', 'taggati']; + +/** The Italian name of a kind («Storie», «In evidenza», ...). */ +export function kindName(kind) { + return t(`impostazioni.limiti.tipi.${kind}`); +} + +/** An order as the server sent it, or the default one when it is missing. */ +export function orderOrDefault(order) { + return Array.isArray(order) && order.length ? [...order] : [...DEFAULT_ORDER]; +} + +/** + * The editor of an order. + * @param {object} options + * @param {() => string[]} options.read the current order of the page + * @param {(order: string[]) => void} options.write stores a new order in the page + * @param {() => void} options.changed called after every move (save bar, recomputations) + * @param {(kind: string) => boolean} [options.off] kinds switched off in «Cosa scaricare»: they stay, attenuated + * @param {string} [options.label] accessible name of the list + * @returns {{ list: HTMLElement, status: HTMLElement, draw: () => void }} + */ +export function orderEditor({ read, write, changed, off = () => false, label }) { + const list = h('ol.ordine-tipi', { 'aria-label': label ?? t('impostazioni.limiti.ordine') }); + const status = h('span.vh', { 'aria-live': 'polite' }); + let dragged = null; + + function move(from, to, focus) { + const order = [...read()]; + if (to < 0 || to >= order.length || from === to) return; + const [kind] = order.splice(from, 1); + order.splice(to, 0, kind); + write(order); + draw(); + changed(); + status.textContent = t('impostazioni.limiti.ordineSpostato', { tipo: kindName(kind), n: to + 1 }); + if (focus) { + const again = list.querySelector(`[data-tipo="${kind}"] [data-verso="${focus}"]`); + if (again && !again.disabled) again.focus(); + else list.querySelector(`[data-tipo="${kind}"] button:not([disabled])`)?.focus(); + } + } + + function draw() { + const order = read(); + fill(list, order.map((kind, i) => { + const name = kindName(kind); + const switchedOff = off(kind); + const row = h(switchedOff ? 'li.riga-ordine.spenta' : 'li.riga-ordine', { draggable: 'true', dataset: { tipo: kind } }, + h('span.maniglia', { title: t('impostazioni.limiti.ordineManiglia'), 'aria-hidden': 'true' }, icon('grip-vertical', 's')), + h('span.posizione.dati', String(i + 1)), + h('b', name), + switchedOff ? h('span.muto.piccolo', t('impostazioni.limiti.ordineSpento')) : null, + kind === 'storie' && i > 0 && !switchedOff ? h('span.muto.piccolo', icon('clock', 'xs'), ' ', t('impostazioni.limiti.ordineStorie')) : null, + h('div.destra', + h('button.btn.piccolo.nudo', { + type: 'button', disabled: i === 0, dataset: { verso: 'su' }, 'aria-label': t('impostazioni.limiti.ordineSuDi', { tipo: name }), onclick: () => move(i, i - 1, 'su'), + }, icon('chevron-up', 's'), h('span.testo-btn', t('impostazioni.limiti.ordineSu'))), + h('button.btn.piccolo.nudo', { + type: 'button', disabled: i === order.length - 1, dataset: { verso: 'giu' }, 'aria-label': t('impostazioni.limiti.ordineGiuDi', { tipo: name }), onclick: () => move(i, i + 1, 'giu'), + }, icon('chevron-down', 's'), h('span.testo-btn', t('impostazioni.limiti.ordineGiu'))))); + row.addEventListener('dragstart', (event) => { + dragged = i; + row.classList.add('trascinata'); + try { + event.dataTransfer.effectAllowed = 'move'; + event.dataTransfer.setData('text/plain', kind); + } catch { + // Some browsers refuse data on a drag: the index above is enough. + } + }); + row.addEventListener('dragend', () => { + dragged = null; + row.classList.remove('trascinata'); + }); + row.addEventListener('dragover', (event) => { + if (dragged === null) return; + event.preventDefault(); + }); + row.addEventListener('drop', (event) => { + if (dragged === null) return; + event.preventDefault(); + const from = dragged; + dragged = null; + move(from, i, null); + }); + return row; + })); + } + + return { list, status, draw }; +} diff --git a/src/Febe.Web/wwwroot/js/pages/library.js b/src/Febe.Web/wwwroot/js/pages/library.js index d2b8793..042c821 100644 --- a/src/Febe.Web/wwwroot/js/pages/library.js +++ b/src/Febe.Web/wwwroot/js/pages/library.js @@ -1,6 +1,8 @@ // Libreria (mockup 01, spec §4.6): every entry by publication day, filters by kind, account, period and provenance, // search by account name and caption, tile size, multiple selection to export or delete, viewer on click. // «Esporta l'elenco» in the tools row exports what the filter shows (spec §4.8: CSV with «;», UTF-8 with BOM). +// «Raggruppa i post» / «Tutte le foto» (spec §4.6): one tile per entry or per file, remembered in this browser. With +// «Tutte le foto» the selection is of files; the CSV list and «Elimina» work on the entries they belong to. import { api, download, withCarried } from '../core/api.js'; import { caps } from '../core/context.js'; @@ -9,7 +11,7 @@ import { setQuery } from '../core/shell.js'; import { t, number, shortDay, parseDay } from '../core/text.js'; import { menu, showError, toast, confirmDialog } from '../core/ui.js'; import { engineState } from '../core/engine.js'; -import { Mosaic } from './mosaic.js'; +import { Mosaic, modeSwitch, storedMode } from './mosaic.js'; import { welcome } from './welcome.js'; import { openViewer } from './viewer.js'; @@ -73,6 +75,7 @@ export default { const today = () => caps().today || new Date().toISOString().slice(0, 10); let accounts = null; let mosaic = null; + let mode = storedMode('libreria'); page.title(t('libreria.titolo'), ''); const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q }); @@ -93,6 +96,10 @@ export default { const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') }); const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona'))); // Icon only, like the tile size: the row of the mockup has no room for one more label. + const modes = modeSwitch('libreria', (value) => { + mode = value; + apply(); + }, { compact: true }); const exportButton = h('button.btn.nudo.piccolo.solo-icona.solo-largo', { type: 'button', title: t('libreria.esportaAiuto'), 'aria-label': t('libreria.esporta') }, icon('file-down')); // Probable duplicates after a download wait for Alberto (spec §9.5): a short link to their review. const duplicates = h('a.btn.nudo.piccolo.doppioni-link', { href: withCarried('/doppioni'), hidden: true }); @@ -108,6 +115,7 @@ export default { h('div.destra', duplicates, exportButton, + modes, h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')), selectButton))); @@ -273,13 +281,7 @@ export default { page.saveBar(null); return; } - const n = selected.size; - page.saveBar(h('div', { style: { display: 'contents' } }, - h('span.nota', n ? t('selezione.scelti', { n }) : t('selezione.nessuno')), - h('div.destra', - h('button.btn.nudo', { type: 'button', onclick: () => setSelecting(false) }, t('selezione.annulla')), - h('button.btn', { type: 'button', disabled: !n, onclick: () => exportSelected() }, icon('file-down'), t('selezione.esporta')), - h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: () => deleteSelected() }, icon('trash-2'), t('selezione.elimina', { n }))))); + page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected })); } function setSelecting(on) { @@ -295,7 +297,7 @@ export default { async function exportSelected() { try { - await download('/api/entries/export', { ids: [...mosaic.selected] }, 'febe-elementi.csv'); + await download('/api/entries/export', { ids: mosaic.selectedEntries().ids }, 'febe-elementi.csv'); toast(t('selezione.esportato')); } catch (error) { showError(error); @@ -315,8 +317,8 @@ export default { } async function deleteSelected() { - const ids = [...mosaic.selected]; - const removed = await confirmDelete(ids); + const { ids, files } = mosaic.selectedEntries(); + const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null); if (removed) { mosaic.removeTiles(removed); setSelecting(false); @@ -368,11 +370,14 @@ export default { scroller: page.body, host, query: apiQuery(state, today()), + files: mode === 'files', rowHeight: Number(slider.value), signal: page.signal, onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }), onSelection: drawSelection, - onTotals: ({ entries, accounts: n }) => page.count(t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })), + onTotals: ({ entries, accounts: n, files }) => page.count(files == null + ? t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) }) + : t('libreria.quantiFile', { file: t('comune.file', { n: files }), elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })), onEmpty: drawEmpty, }); try { @@ -395,16 +400,39 @@ export default { }, }; +/** + * The bar of the selection (Libreria and account view): how many are chosen, «Esporta l'elenco» and «Elimina». With + * «Tutte le foto» it counts the files and says how many entries they belong to: those are what the actions work on. + */ +export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected }) { + const n = selected.size; + const entries = mosaic.selectedEntries().ids.length; + let note = t('selezione.nessuno'); + if (n && mosaic.files) note = t('selezione.sceltiFile', { n, elementi: t('comune.elementi', { n: entries }) }); + else if (n) note = t('selezione.scelti', { n }); + return h('div', { style: { display: 'contents' } }, + h('span.nota', note), + h('div.destra', + h('button.btn.nudo', { type: 'button', onclick: cancel }, t('selezione.annulla')), + h('button.btn', { type: 'button', disabled: !n, onclick: exportSelected }, icon('file-down'), t('selezione.esporta')), + h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: deleteSelected }, icon('trash-2'), t('selezione.elimina', { n: entries })))); +} + /** * «Elimina dalla libreria» with the confirmation of spec §4.6: by default the choice is remembered (state «eliminato», * never downloaded again); «Eliminalo e lascia che torni» forgets the entry. Returns the deleted keys, or null. + * files: with «Tutte le foto», { files: chosen files, total: files of their entries }: the confirmation says that the + * whole entries go («3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file»). */ -export async function confirmDelete(ids) { +export async function confirmDelete(ids, files = null) { const n = ids.length; + const whole = files + ? h('p', `${t('elimina.fileDi', { n: files.files, elementi: t('comune.elementi', { n }) })}: ${t('elimina.interi', { n, file: t('comune.file', { n: files.total }) })}`) + : null; const mode = await confirmDialog({ title: t('elimina.titolo', { n }), text: t('elimina.testo', { n }), - extra: h('p.aiuto', t('elimina.tornaSpiega')), + extra: h('div', whole, h('p.aiuto', t('elimina.tornaSpiega'))), buttons: [ { label: t('comune.annulla'), value: undefined, kind: 'nudo' }, { label: t('elimina.torna', { n }), value: 'allowReturn' }, diff --git a/src/Febe.Web/wwwroot/js/pages/mosaic.js b/src/Febe.Web/wwwroot/js/pages/mosaic.js index e0fe72e..a532a5c 100644 --- a/src/Febe.Web/wwwroot/js/pages/mosaic.js +++ b/src/Febe.Web/wwwroot/js/pages/mosaic.js @@ -3,11 +3,56 @@ // Fluid with 200,000 entries: the page knows only how many entries each day has (one cheap query); a day group is // fetched (keyset windows) and drawn only when it comes near the visible area, and emptied again when it goes far, // keeping its height. Changes of height above the visible area are compensated, so nothing moves under the eyes. +// «Raggruppa i post» (one tile per entry, the default) or «Tutte le foto» (spec §4.6: one tile per file, in the order of +// the entries and then of the series; the day rows count files). A tile is known by its key: the entry in the first +// mode, the file in the second; the entry stays tile.id in both. import { api } from '../core/api.js'; -import { h, icon, fill, perFrame } from '../core/dom.js'; +import { h, icon, fill, perFrame, local } from '../core/dom.js'; import { t, dayName, duration, capitalize } from '../core/text.js'; -import { avatar } from '../core/ui.js'; +import { avatar, segmented } from '../core/ui.js'; + +/** + * «Raggruppa i post» or «Tutte le foto» of a page ('libreria', or 'account' for every account), kept only in the + * local storage of this browser (spec §4.6): unlike the theme, Febe does not save it, so another browser starts + * grouped. Storage that is missing, blocked or holds anything else means grouped. + */ +export function storedMode(page) { + return local.get(`mosaico.${page}`, 'grouped') === 'files' ? 'files' : 'grouped'; +} + +/** + * The two-voice switch of the tools row; onchange(mode) after the choice is remembered, and only when the mode + * changes: the voice already chosen does nothing (the mosaic, its place and the selection stay). compact: icons only + * sooner. + */ +export function modeSwitch(page, onchange, { compact = false } = {}) { + const labels = { grouped: t('libreria.modi.grouped'), files: t('libreria.modi.files') }; + // The mode shown, kept here: without browser storage storedMode() always says grouped. + let current = storedMode(page); + const group = segmented({ + label: t('libreria.modi.etichetta'), + value: current, + options: [ + { value: 'grouped', icon: 'layers', label: h('span.voce', labels.grouped) }, + { value: 'files', icon: 'layout-grid', label: h('span.voce', labels.files) }, + ], + onchange: (value) => { + if (value === current) return; + current = value; + local.set(`mosaico.${page}`, value); + onchange(value); + }, + }); + group.classList.add('modo-mosaico'); + if (compact) group.classList.add('compatto'); + // The label may be hidden in a narrow row: the name and the tooltip stay. + for (const button of group.querySelectorAll('button')) { + button.setAttribute('aria-label', labels[button.dataset.value]); + button.title = t(`libreria.modi.${button.dataset.value}Aiuto`); + } + return group; +} const GAP = 4; const NEAR = '1400px 0px'; @@ -20,12 +65,20 @@ function aspectOf(tile) { } function older(a, b) { - // true when tile a comes after tile b in display order (published earlier, or same time and smaller id) - return a.publishedAt < b.publishedAt || (a.publishedAt === b.publishedAt && a.id < b.id); + // true when tile a comes after tile b in display order (published earlier, or same time and smaller id, or a later + // file of the same entry) + if (a.publishedAt !== b.publishedAt) return a.publishedAt < b.publishedAt; + if (a.id !== b.id) return a.id < b.id; + return (a.position || 0) > (b.position || 0); } export function cursorOf(tile) { - return `${tile.publishedAt}.${tile.id}`; + return tile.position != null ? `${tile.publishedAt}.${tile.id}.${tile.position}` : `${tile.publishedAt}.${tile.id}`; +} + +/** The key of a tile: the file with «Tutte le foto», otherwise the entry. */ +export function keyOf(tile) { + return tile.key != null ? tile.key : tile.id; } /** Justified rows: every full row exactly fills the width; the last row keeps the target height. */ @@ -72,15 +125,19 @@ export function tileElement(tile, width, height, { selected = false, today = '', const marks = []; if (tile.kind === 'story' && ring) marks.push(h('span.anello', { title: t('libreria.tipiTessera.story') }, icon('circle-dashed'))); if (cover && cover.kind === 'video') marks.push(h('span', icon('play'), duration(cover.duration || 0))); - if (tile.files > 1) marks.push(h('span', icon('layers'), String(tile.files))); + // A file of a series says its place («2/4»), an entry how many files it has. + const file = tile.position != null; + if (file && tile.files > 1) marks.push(h('span', icon('layers'), t('libreria.posizioneFile', { n: tile.position, totale: tile.files }))); + else if (!file && tile.files > 1) marks.push(h('span', icon('layers'), String(tile.files))); const when = tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : `${dayName(tile.day, today)}, ${tile.time}`; const description = [t('libreria.tessera', { tipo: t(`libreria.tipiTessera.${tile.kind}`), account: tile.username, quando: when })]; - if (tile.files > 1) description.push(t('libreria.tesseraFile', { n: tile.files })); + if (file && tile.files > 1) description.push(t('libreria.tesseraPosizione', { n: tile.position, totale: tile.files })); + else if (!file && tile.files > 1) description.push(t('libreria.tesseraFile', { n: tile.files })); if (cover && cover.kind === 'video') description.push(t('libreria.tesseraDurata', { durata: duration(cover.duration || 0) })); const el = h(`button.tess${selected ? '.scelta' : ''}`, { type: 'button', style: { width: `${width}px`, height: `${height}px` }, - dataset: { id: String(tile.id) }, + dataset: { id: String(keyOf(tile)), entry: String(tile.id) }, 'aria-label': description.join(', '), 'aria-pressed': selected ? 'true' : null, }, @@ -88,11 +145,20 @@ export function tileElement(tile, width, height, { selected = false, today = '', ? h('img', { src: `/api/thumbnails/${cover.thumb}`, alt: '', loading: 'lazy', decoding: 'async', draggable: 'false' }) : h('span.tess.vuota', { style: { width: '100%', height: '100%' } }, icon('image')), marks.length ? h('span.segno', marks) : null, - h('span.sel', { role: 'checkbox', 'aria-checked': String(selected), 'aria-label': t('libreria.scegliTessera'), title: t('libreria.scegliTessera') }, icon('check')), + h('span.sel', { role: 'checkbox', 'aria-checked': String(selected), 'aria-label': t(file ? 'libreria.scegliFile' : 'libreria.scegliTessera'), title: t(file ? 'libreria.scegliFile' : 'libreria.scegliTessera') }, icon('check')), h('span.chi', avatar(tile.username, 'p'), h('span', `@${tile.username}`), h('small', tile.day === today ? `${t('tempo.oggi')}, ${tile.time}` : tile.time))); return el; } +/** The day header of «Tutte le foto»: «Oggi martedì 13 ottobre, 23 file nuovi», «Sabato 10 ottobre 9 file». */ +export function filesDayLabel(day, count, today) { + const name = dayName(day, today); + if (day === today) return [t('tempo.Oggi'), t('libreria.giornoNuovi', { giorno: name, n: t('libreria.fileNuoviOggi', { n: count }) })]; + const yesterday = new Date(Date.parse(`${today}T12:00:00Z`) - 86400000).toISOString().slice(0, 10); + if (day === yesterday) return [t('tempo.Ieri'), t('libreria.giornoNuovi', { giorno: name, n: t('comune.file', { n: count }) })]; + return [capitalize(name), t('comune.file', { n: count })]; +} + /** The default day header: «Oggi martedì 13 ottobre, 14 nuovi elementi». */ export function defaultDayLabel(day, count, today) { const name = dayName(day, today); @@ -105,20 +171,23 @@ export function defaultDayLabel(day, count, today) { export class Mosaic { /** * scroller: the scrolling element (.corpo); host: where the groups go; query: filter as a query string; - * mode: 'justified' or 'grid' (9:16 stories); rowHeight: target height of the rows; - * onOpen(tile), onSelection(set), onTotals({ entries, accounts, today }), onEmpty(), dayLabel(day, count, today). + * mode: 'justified' or 'grid' (9:16 stories); files: «Tutte le foto» (one tile per file); rowHeight: target height; + * onOpen(tile), onSelection(set), onTotals({ entries, accounts, files, today }) (files only with «Tutte le foto»), + * onEmpty(), dayLabel(day, count, today). */ constructor(options) { this.scroller = options.scroller; this.host = options.host; - this.query = options.query || ''; + this.files = Boolean(options.files); + const filter = options.query || ''; + this.query = this.files ? `${filter}${filter ? '&' : ''}mode=files` : filter; this.mode = options.mode || 'justified'; this.rowHeight = options.rowHeight || 160; this.onOpen = options.onOpen || (() => {}); this.onSelection = options.onSelection || (() => {}); this.onTotals = options.onTotals || (() => {}); this.onEmpty = options.onEmpty || (() => {}); - this.dayLabel = options.dayLabel || defaultDayLabel; + this.dayLabel = options.dayLabel || (this.files ? filesDayLabel : defaultDayLabel); // Its own requests stop with the page and with destroy(): a mosaic replaced by a new filter never answers late // over the new one (totals, empty state, sections). this.controller = new AbortController(); @@ -131,6 +200,8 @@ export class Mosaic { this.sections = []; this.byDay = new Map(); this.selected = new Set(); + // What each chosen key belongs to ({ entry, files }), also after its day was emptied or reloaded. + this.chosen = new Map(); this.selecting = false; this.today = ''; this.avgAspect = this.mode === 'grid' ? 0.5625 : 0.95; @@ -159,7 +230,7 @@ export class Mosaic { const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); if (this.destroyed) return; this.today = data.today; - this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today }); + this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today }); this.width = this.root.clientWidth || this.host.clientWidth || 800; for (const section of this.sections) this.unobserve(section); this.sections = []; @@ -235,6 +306,7 @@ export class Mosaic { if (this.destroyed) return; const touched = new Set(); for (const tile of page.tiles) { + tile.key = this.files && tile.cover ? tile.cover.mediaId : tile.id; const target = this.byDay.get(tile.day); if (!target || target.complete) continue; const last = target.tiles[target.tiles.length - 1]; @@ -282,7 +354,7 @@ export class Mosaic { this.width = width; const rows = this.layout(section.tiles, width); const nodes = rows.map((row) => h(this.mode === 'grid' ? 'div.griglia-storie' : 'div.fila', - row.items.map((item) => tileElement(item.tile, item.width, row.height, { selected: this.selected.has(item.tile.id), today: this.today, ring: this.mode !== 'grid' })))); + row.items.map((item) => tileElement(item.tile, item.width, row.height, { selected: this.selected.has(keyOf(item.tile)), today: this.today, ring: this.mode !== 'grid' })))); this.keepView(section, () => { section.rows.style.height = ''; fill(section.rows, nodes); @@ -347,6 +419,7 @@ export class Mosaic { clearSelection() { this.selected.clear(); + this.chosen.clear(); for (const el of this.root.querySelectorAll('.tess.scelta')) this.markTile(el, false); this.onSelection(this.selected); } @@ -358,10 +431,16 @@ export class Mosaic { if (sel) sel.setAttribute('aria-checked', String(on)); } - toggle(id, el) { - const on = !this.selected.has(id); - if (on) this.selected.add(id); - else this.selected.delete(id); + toggle(key, el) { + const on = !this.selected.has(key); + if (on) { + const tile = this.findTile(key); + this.selected.add(key); + if (tile) this.chosen.set(key, { entry: tile.id, files: tile.files }); + } else { + this.selected.delete(key); + this.chosen.delete(key); + } if (el) this.markTile(el, on); if (!this.selecting && on) this.setSelecting(true); this.onSelection(this.selected); @@ -370,42 +449,57 @@ export class Mosaic { onClick(e) { const el = e.target.closest('.tess[data-id]'); if (!el) return; - const id = Number(el.dataset.id); + const key = Number(el.dataset.id); if (e.target.closest('.sel') || this.selecting) { e.preventDefault(); - this.toggle(id, el); + this.toggle(key, el); return; } - const tile = this.findTile(id); + const tile = this.findTile(key); if (tile) this.onOpen(tile); } - findTile(id) { + findTile(key) { for (const s of this.sections) { - const tile = s.tiles.find((x) => x.id === id); + const tile = s.tiles.find((x) => keyOf(x) === key); if (tile) return tile; } return null; } + /** Whether a key is a tile of the mosaic (the viewer asks it about the files of an entry). */ + has(key) { + return Boolean(this.findTile(key)); + } + + /** + * The entries of the selection: with «Tutte le foto» the posts the chosen files belong to (spec §4.6: the CSV list + * and «Elimina» work on them), with how many files those entries have in all. + */ + selectedEntries() { + const entries = new Map(); + for (const [key, info] of this.chosen) if (this.selected.has(key)) entries.set(info.entry, info.files || 0); + return { ids: [...entries.keys()], files: [...entries.values()].reduce((a, n) => a + n, 0) }; + } + // ------------------------------------------------------------------------------------------- viewer navigation - /** Position of an entry among all the entries of the filter (1-based) and the total. */ - position(id) { + /** Position of a tile (an entry, or a file) among all those of the filter (1-based) and the total. */ + position(key) { let before = 0; for (const s of this.sections) { - const i = s.tiles.findIndex((x) => x.id === id); + const i = s.tiles.findIndex((x) => keyOf(x) === key); if (i >= 0) return { index: before + i + 1, total: this.sections.reduce((a, x) => a + x.count, 0) }; before += s.count; } return { index: 0, total: this.sections.reduce((a, x) => a + x.count, 0) }; } - /** The entry before (delta −1) or after (+1) an entry, loading the next group when needed. */ - async neighbor(id, delta) { - let si = this.sections.findIndex((s) => s.tiles.some((x) => x.id === id)); + /** The tile before (delta −1) or after (+1) a tile, loading the next group when needed. */ + async neighbor(key, delta) { + let si = this.sections.findIndex((s) => s.tiles.some((x) => keyOf(x) === key)); if (si < 0) return null; - let i = this.sections[si].tiles.findIndex((x) => x.id === id) + delta; + let i = this.sections[si].tiles.findIndex((x) => keyOf(x) === key) + delta; for (;;) { const s = this.sections[si]; if (i >= 0 && i < s.tiles.length) return s.tiles[i]; @@ -421,24 +515,29 @@ export class Mosaic { } } - /** Scrolls so that an entry is visible (after the viewer moved far). */ - reveal(id) { - const el = this.root.querySelector(`.tess[data-id="${id}"]`); + /** Scrolls so that a tile is visible (after the viewer moved far). */ + reveal(key) { + const el = this.root.querySelector(`.tess[data-id="${Number(key)}"]`); if (el) el.scrollIntoView({ block: 'nearest' }); } // ------------------------------------------------------------------------------------------- changes - /** Removes entries (after a deletion) and updates the counts of their days. */ + /** Removes entries (after a deletion), with every file tile of theirs, and updates the counts of their days. */ removeTiles(ids) { const set = new Set(ids); + for (const [key, info] of [...this.chosen]) { + if (set.has(info.entry)) { + this.selected.delete(key); + this.chosen.delete(key); + } + } for (const s of [...this.sections]) { const before = s.tiles.length; s.tiles = s.tiles.filter((x) => !set.has(x.id)); const removed = before - s.tiles.length; if (!removed) continue; s.count -= removed; - for (const id of ids) this.selected.delete(id); if (s.count <= 0) { this.unobserve(s); this.keepView(s, () => s.el.remove()); @@ -460,7 +559,7 @@ export class Mosaic { async refresh() { const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); if (this.destroyed) return; - this.onTotals({ entries: data.entries, accounts: data.accounts, today: data.today }); + this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today }); // The empty state of the page took the place of the mosaic: the first new entries bring it back. if (data.days.length && !this.root.isConnected) { this.pendingNew = 0; @@ -538,7 +637,7 @@ export class Mosaic { this.pill.hidden = true; this.scroller.scrollTo({ top: 0 }); }, - }, icon('arrow-left', 's'), t('libreria.nuoviInCima', { n: this.pendingNew }))); + }, icon('arrow-left', 's'), t(this.files ? 'libreria.fileNuoviInCima' : 'libreria.nuoviInCima', { n: this.pendingNew }))); this.pill.querySelector('svg').style.transform = 'rotate(90deg)'; this.pill.hidden = false; } diff --git a/src/Febe.Web/wwwroot/js/pages/settings-limits.js b/src/Febe.Web/wwwroot/js/pages/settings-limits.js index c1a52fe..8f362ac 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-limits.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-limits.js @@ -9,6 +9,7 @@ import { h, icon, fill } from '../core/dom.js'; import { refreshEngine } from '../core/engine.js'; import { t, list, number, decimal } from '../core/text.js'; import { checkbox, confirmDialog, label, showError, toast, toggle } from '../core/ui.js'; +import { DEFAULT_ORDER, orderEditor, orderOrDefault } from './download-order.js'; import { guardChanges, heading } from './settings.js'; const PACES = ['slow', 'natural', 'brisk']; @@ -16,7 +17,7 @@ const DAY_ORDER = [1, 2, 3, 4, 5, 6, 0]; // Monday first; the API counts from Su export default async function limits(page, box) { let data = await api('/api/settings/limits', { signal: page.signal }); - const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort() }); + const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort(), order: form.order }); let form = fromData(data); let original = snapshot(); const dirty = () => snapshot() !== original; @@ -32,9 +33,30 @@ export default async function limits(page, box) { gradualStart: d.gradualStart, activeDays: new Set(d.activeDays), jitterOn: d.current.jitterMinutes > 0, + order: orderOrDefault(d.downloadOrder), }; } + // ------------------------------------------------------------------------------------------- download order + // The rows move by dragging or with «Su» and «Giù» (download-order.js); the order is saved with the save bar. + const order = orderEditor({ + read: () => form.order, + write: (next) => { form.order = next; }, + changed: () => drawSaveBar(), + }); + const orderList = order.list; + const orderStatus = order.status; + const drawOrder = order.draw; + + const orderReset = h('button.btn.collegamento', { + type: 'button', + onclick: () => { + form.order = [...DEFAULT_ORDER]; + drawOrder(); + drawSaveBar(); + }, + }, t('impostazioni.limiti.ordineMetti')); + /** Any edit turns the profile into «Su misura» (spec §7.5). */ function edited() { form.profile = 'custom'; @@ -363,7 +385,7 @@ export default async function limits(page, box) { try { data = await api('/api/settings/limits', { method: 'PUT', - body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays] }, + body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays], downloadOrder: form.order }, }); form = fromData(data); original = snapshot(); @@ -381,6 +403,7 @@ export default async function limits(page, box) { drawWindow(); drawPace(); drawTable(); + drawOrder(); drawSaveBar(); } @@ -411,7 +434,11 @@ export default async function limits(page, box) { heading(t('impostazioni.limiti.tetti'), t('impostazioni.limiti.tettiAiuto')), h('div.pannello.tabella-tetti', h('table.tab', h('thead', h('tr', h('th', t('impostazioni.limiti.colonne.attivita')), h('th', t('impostazioni.limiti.colonne.ora')), h('th', t('impostazioni.limiti.colonne.giorno')))), - table)))); + table))), + h('div.sezione', + heading(t('impostazioni.limiti.ordine'), t('impostazioni.limiti.ordineAiuto')), + h('div.pannello', orderList), + h('div.riga-sotto', orderReset, orderStatus))); } function toInt(text) { diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js index a3b302c..4a98446 100644 --- a/src/Febe.Web/wwwroot/js/pages/viewer.js +++ b/src/Febe.Web/wwwroot/js/pages/viewer.js @@ -13,11 +13,14 @@ import { confirmDelete } from './library.js'; const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' }; /** - * Opens the viewer on a tile. source: { position(id), neighbor(id, delta), reveal(id) } (the mosaic, or a plain list). - * origin: «Libreria» or the account name. onDeleted(ids): called after a deletion. + * Opens the viewer on a tile. source: { position(key), neighbor(key, delta), reveal(key) } (the mosaic, or a plain + * list), where a key is the entry. With «Tutte le foto» the source says files: true and has(key), and a key is a file: + * the viewer opens on the file of the tile and its position counts files (spec §4.6). origin: «Libreria» or the + * account name. onDeleted(ids): called with the deleted entries. */ export function openViewer({ tile, source, origin, onDeleted }) { const opener = document.activeElement; + const files = Boolean(source && source.files && source.has); let entry = null; let fileIndex = 0; let zoomed = false; @@ -77,7 +80,10 @@ export function openViewer({ tile, source, origin, onDeleted }) { if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); box.remove(); document.body.style.overflow = ''; - if (entry && source && source.reveal) source.reveal(entry.id); + if (entry && source && source.reveal) { + const key = keyAt(0); + if (key != null) source.reveal(key); + } if (opener && document.contains(opener)) opener.focus(); } @@ -87,13 +93,30 @@ export function openViewer({ tile, source, origin, onDeleted }) { zoomButton.setAttribute('aria-pressed', String(on)); } - async function load(id, index = 0) { + /** The key of the source at the edge of the entry it is left by (delta), or of the file shown when it is a tile. */ + function keyAt(delta = 0) { + if (!files) return entry.id; + const current = entry.media[fileIndex]; + if (delta === 0 && current && source.has(current.id)) return current.id; + const known = entry.media.filter((m) => source.has(m.id)); + if (!known.length) return null; + return (delta > 0 ? known[known.length - 1] : known[0]).id; + } + + async function load(id, index = 0, mediaId = null) { const mine = ++token; try { const data = await api(`/api/entries/${id}`); if (mine !== token) return; entry = data; - fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1); + const at = mediaId == null ? -1 : entry.media.findIndex((m) => m.id === mediaId); + if (at >= 0) fileIndex = at; + else fileIndex = index < 0 ? entry.media.length - 1 : Math.min(index, entry.media.length - 1); + if (files && at < 0) { + // Entered from an edge without a file named: the first (or last) file that is a tile. + const tiles = entry.media.map((m, i) => (source.has(m.id) ? i : -1)).filter((i) => i >= 0); + if (tiles.length) fileIndex = index < 0 ? tiles[tiles.length - 1] : tiles[0]; + } draw(); } catch (error) { showError(error); @@ -102,17 +125,28 @@ export function openViewer({ tile, source, origin, onDeleted }) { async function step(delta) { if (!entry) return; - const target = fileIndex + delta; + let target = fileIndex + delta; + // With «Tutte le foto» the arrows follow the tiles: the files the mosaic does not show (the photos of a post under + // «Video», the videos under «Foto», a file not in the library) are passed over, as the mosaic passes over them. + if (files) while (target >= 0 && target < entry.media.length && !source.has(entry.media[target].id)) target += delta; if (target >= 0 && target < entry.media.length) { fileIndex = target; - drawMedia(); - drawStrip(); - drawPanel(); + drawFile(); return; } if (!source || !source.neighbor) return; - const other = await source.neighbor(entry.id, delta); - if (other) await load(other.id, delta > 0 ? 0 : -1); + const key = keyAt(delta); + if (key == null) return; + const other = await source.neighbor(key, delta); + if (other) await load(other.id, delta > 0 ? 0 : -1, files && other.cover ? other.cover.mediaId : null); + } + + /** Another file of the same entry: with «Tutte le foto» the place in the source moves too. */ + function drawFile() { + if (files) drawWhere(); + drawMedia(); + drawStrip(); + drawPanel(); } function draw() { @@ -123,9 +157,13 @@ export function openViewer({ tile, source, origin, onDeleted }) { } function drawWhere() { - if (source && source.position) { - const p = source.position(entry.id); - where.textContent = p.index ? t('vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin; + // With «Tutte le foto» the place is that of the file on screen; a file that is not a tile (chosen in the series + // strip) has none, and the header says only where the viewer was opened. + const current = files && entry.media[fileIndex]; + const key = !source || !source.position ? null : !files ? keyAt(0) : current && source.has(current.id) ? current.id : null; + if (key != null) { + const p = source.position(key); + where.textContent = p.index ? t(files ? 'vis.doveFile' : 'vis.dove', { origine: origin, n: number(p.index), totale: number(p.total) }) : origin; } else where.textContent = origin; } @@ -175,9 +213,7 @@ export function openViewer({ tile, source, origin, onDeleted }) { 'aria-current': i === fileIndex ? 'true' : null, onclick: () => { fileIndex = i; - drawMedia(); - drawStrip(); - drawPanel(); + drawFile(); }, }, m.thumb ? h('img', { src: `/api/thumbnails/${m.thumb}`, alt: '', loading: 'lazy' }) : null, m.kind === 'video' ? icon('play') : null))); } @@ -254,17 +290,20 @@ export function openViewer({ tile, source, origin, onDeleted }) { async function remove() { const id = entry.id; - const following = source && source.neighbor ? (await source.neighbor(id, 1)) || (await source.neighbor(id, -1)) : null; - const removed = await confirmDelete([id]); + const after = keyAt(1); + const before = keyAt(-1); + const following = source && source.neighbor && after != null ? (await source.neighbor(after, 1)) || (await source.neighbor(before, -1)) : null; + // With «Tutte le foto» too the viewer deletes the whole entry (spec §4.6), and the confirmation says so. + const removed = await confirmDelete([id], files && entry.media.length > 1 ? { files: 1, total: entry.media.length } : null); if (!removed) return; if (onDeleted) onDeleted(removed); - if (following) await load(following.id, 0); + if (following) await load(following.id, 0, files && following.cover ? following.cover.mediaId : null); else close(); } document.addEventListener('keydown', onKey, true); document.body.append(box); closeButton.focus(); - load(tile.id, 0); + load(tile.id, 0, files && tile.cover ? tile.cover.mediaId : null); void withCarried; } diff --git a/src/Febe.Web/wwwroot/js/pages/welcome.js b/src/Febe.Web/wwwroot/js/pages/welcome.js index 6232a78..22d5bae 100644 --- a/src/Febe.Web/wwwroot/js/pages/welcome.js +++ b/src/Febe.Web/wwwroot/js/pages/welcome.js @@ -15,3 +15,22 @@ export function welcome() { h('a.btn.grande', { href: withCarried('/importa?passo=1') }, icon('folder-input', 's'), t('benvenuto.importa'))), h('p.nota-benvenuto', icon('triangle-alert', 'xs'), ' ', t('benvenuto.nota'))); } + +/** + * The first start on the Dashboard (spec §7.9, §10.3), which / opens before the Library: while there is no account, a + * compact card above the cockpit with the same ways to begin as the welcome of the Library. Not connected: «Collegati + * a Instagram» first; connected: «Aggiungi account». «Importa foto e video che hai già» in both cases. + */ +export function compactWelcome(connected) { + const first = connected + ? h('a.btn.primo', { href: withCarried('/account') }, icon('plus', 's'), t('account.aggiungi')) + : h('a.btn.primo', { href: withCarried('/impostazioni/collegamento') }, icon('key-round', 's'), t('benvenuto.collegati')); + return h('section.pannello.benvenuto-compatto', { 'aria-labelledby': 'benvenuto-dashboard' }, + h('div.marchio-benvenuto', brand()), + h('div.benvenuto-testo', + h('h2', { id: 'benvenuto-dashboard' }, t('benvenuto.titolo')), + h('p', t(connected ? 'benvenuto.dashboardCollegato' : 'benvenuto.dashboard')), + h('div.bottoni-benvenuto', first, + h('a.btn', { href: withCarried('/importa?passo=1') }, icon('folder-input', 's'), t('benvenuto.importa'))), + connected ? null : h('p.nota-benvenuto', icon('triangle-alert', 'xs'), ' ', t('benvenuto.nota')))); +} diff --git a/src/Febe.Web/wwwroot/js/routes.js b/src/Febe.Web/wwwroot/js/routes.js index cff56ac..4628b28 100644 --- a/src/Febe.Web/wwwroot/js/routes.js +++ b/src/Febe.Web/wwwroot/js/routes.js @@ -3,18 +3,20 @@ // so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md). export const routes = [ - { pattern: /^\/$/, redirect: '/libreria' }, + // The Dashboard is the start page (spec §7.9, §10.2, tappa D1); the old address of Attività leads there too. + { pattern: /^\/$/, redirect: '/dashboard' }, + { pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') }, + { pattern: /^\/attivita\/?$/, redirect: '/dashboard' }, { pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') }, { pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') }, { pattern: /^\/account\/(?\d+)(?:\/(?contenuti|impostazioni|cronologia))?\/?$/, nav: 'account', page: () => import('./pages/account.js') }, - { pattern: /^\/attivita\/?$/, nav: 'attivita', page: () => import('./pages/activity.js') }, { pattern: /^\/importa\/?$/, nav: 'importa', page: () => import('./pages/import.js') }, - { pattern: /^\/doppioni\/?$/, nav: 'attivita', page: () => import('./pages/duplicates.js') }, + { pattern: /^\/doppioni\/?$/, nav: 'dashboard', page: () => import('./pages/duplicates.js') }, { pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' }, { pattern: /^\/impostazioni\/(?
generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/, nav: 'impostazioni', page: () => import('./pages/settings.js'), }, - { pattern: /^\/browser\/?$/, nav: 'attivita', page: () => import('./pages/browser.js') }, + { pattern: /^\/browser\/?$/, nav: 'dashboard', page: () => import('./pages/browser.js') }, ]; diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index c6c9a69..1267699 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -8,9 +8,9 @@ }, "nav": { "principale": "Navigazione principale", + "dashboard": "Dashboard", "libreria": "Libreria", "account": "Account", - "attivita": "Attività", "importa": "Importa", "impostazioni": "Impostazioni", "fermo": "Serve il tuo intervento" @@ -82,6 +82,7 @@ "libreria": { "titolo": "Libreria", "quanti": "{elementi} di {account}", + "quantiFile": "{file} in {elementi} di {account}", "cerca": "Cerca per account o didascalia", "cercaBreve": "Cerca", "filtriTipo": "Tipo di contenuto", @@ -127,6 +128,8 @@ "elementiGiorno": "1 elemento|{n} elementi", "storieGiorno": "1 storia|{n} storie", "nuoviInCima": "1 nuovo elemento in cima|{n} nuovi elementi in cima", + "fileNuoviOggi": "1 file nuovo|{n} file nuovi", + "fileNuoviInCima": "1 file nuovo in cima|{n} file nuovi in cima", "vuota": "La libreria è ancora vuota", "vuotaTesto": "Aggiungi gli account da seguire: i loro contenuti arrivano qui poco per volta.", "nessuno": "Nessun elemento con questi filtri", @@ -139,8 +142,18 @@ "esportatoFiltro": "Elenco degli elementi filtrati esportato: il file CSV è nei download del browser.", "tessera": "{tipo} di @{account}, {quando}", "tesseraFile": "{n} file", + "tesseraPosizione": "file {n} di {totale}", + "posizioneFile": "{n}/{totale}", "tesseraDurata": "video di {durata}", "scegliTessera": "Scegli questo elemento", + "scegliFile": "Scegli questo file", + "modi": { + "etichetta": "Come mostrare i post", + "grouped": "Raggruppa i post", + "files": "Tutte le foto", + "groupedAiuto": "Raggruppa i post: una tessera per elemento, con il numero dei suoi file", + "filesAiuto": "Tutte le foto: una tessera per ogni foto e video, anche di un post con più file" + }, "tipiTessera": { "post": "Post", "story": "Storia", @@ -151,6 +164,7 @@ }, "selezione": { "scelti": "1 elemento scelto|{n} elementi scelti", + "sceltiFile": "1 file scelto, di {elementi}|{n} file scelti, di {elementi}", "nessuno": "Tocca le tessere per sceglierle", "esporta": "Esporta l'elenco", "elimina": "Elimina 1 elemento|Elimina {n} elementi", @@ -162,12 +176,15 @@ "testo": "I file vengono cancellati dal disco e non si recuperano. Febe ricorda la scelta: l'elemento resta nell'elenco come «eliminato» e non viene scaricato di nuovo.|I file vengono cancellati dal disco e non si recuperano. Febe ricorda la scelta: gli elementi restano nell'elenco come «eliminati» e non vengono scaricati di nuovo.", "conferma": "Elimina dalla libreria", "torna": "Eliminalo e lascia che torni|Eliminali e lascia che tornino", - "tornaSpiega": "Con «lascia che torni» Febe dimentica l'elemento: se è ancora su Instagram, al prossimo controllo lo scarica di nuovo." + "tornaSpiega": "Con «lascia che torni» Febe dimentica l'elemento: se è ancora su Instagram, al prossimo controllo lo scarica di nuovo.", + "fileDi": "1 file scelto appartiene a {elementi}|{n} file scelti appartengono a {elementi}", + "interi": "elimino l'elemento intero, {file}.|elimino gli elementi interi, {file}." }, "vis": { "etichetta": "Visualizzatore", "chiudi": "Chiudi (Esc)", "dove": "{origine}, elemento {n} di {totale}", + "doveFile": "{origine}, file {n} di {totale}", "precedente": "Precedente", "successivo": "Successivo", "ingrandisci": "Ingrandisci", @@ -430,6 +447,12 @@ "ore": "ore", "cosa": "Cosa scaricare", "cosaAiuto": "Quello che togli resta in libreria, ma non viene più aggiornato.", + "ordine": "Cosa scaricare prima", + "ordineAiuto": "Pesa sulle visite di Febe a questo account e sulla coda dei suoi file: il tipo più in alto viene di norma prima, ma non sempre. Non aggiunge controlli e non scavalca tetti, pause e frequenze.", + "ordineScelta": "Ordine dei tipi per questo account", + "ordineGenerale": "Come le impostazioni generali", + "ordineSuo": "Un ordine suo", + "ordineOra": "Ordine generale: {ordine}. Si cambia in Impostazioni → Limiti e comportamento.", "tipi": { "photos": "Foto dei post", "videos": "Video e reel", @@ -520,7 +543,7 @@ "uscita": "Esci" }, "attivita": { - "titolo": "Attività", + "titolo": "Dashboard", "pausa": "Metti in pausa", "riprendi": "Riprendi", "apriBrowser": "Apri il browser", @@ -558,8 +581,18 @@ }, "coda": "In coda", "codaVuota": "La coda è vuota.", - "fatto": "Appena fatto", + "mostraTutta": "Mostra tutta ({n})", + "mostraMeno": "Mostra meno", + "fatto": "Cronologia dell'attività", "fattoVuoto": "Nessuna azione nelle ultime ore.", + "arrivate": "1 elemento arrivato|{n} elementi arrivati", + "altreArrivate": "e 1 altro|e altri {n}", + "apriAnteprima": "Ingrandisci: {tipo} di @{account}", + "anteprimaTitolo": "Anteprima", + "fileDi": "file {n} di {di}", + "elementoDi": "{n} di {di}", + "apriAccount": "Apri l'account", + "apriLibreria": "Apri nella Libreria", "arresti": "Arresti e rallentamenti", "arrestiAiuto": "Gli ultimi 14 giorni. Le durate dei fermi sono fisse: 1 ora, 6 ore, 24 ore.", "arrestiVuoti": "Nessun arresto negli ultimi 14 giorni.", @@ -673,6 +706,18 @@ "arrestiTesto": "1 ora la prima volta, 6 ore la seconda nelle 24 ore, 24 ore la terza; poi tetti dimezzati per 48 ore.", "arrestiFissi": "Non si modificano", "salvati": "Limiti salvati: valgono da subito.", + "ordine": "Cosa scaricare prima", + "ordineAiuto": "Dopo il giro dei profili che segui, Febe sceglie più spesso il tipo che sta più in alto, e scarica prima i suoi file. Non aggiunge controlli e non scavalca tetti, pause e frequenze. Trascina le righe o usa «Su» e «Giù».", + "ordineStorie": "Le storie scadono dopo 24 ore: più in basso stanno, più è facile che scadano prima di essere scaricate.", + "ordineSpento": "spento in «Cosa scaricare»", + "ordineMetti": "Ripristina l'ordine predefinito", + "ordineManiglia": "Trascina per spostare", + "ordineSu": "Su", + "ordineGiu": "Giù", + "ordineSuDi": "Sposta su: {tipo}", + "ordineGiuDi": "Sposta giù: {tipo}", + "ordineSpostato": "{tipo}: posizione {n} di 5", + "tipi": { "storie": "Storie", "evidenza": "In evidenza", "post": "Post", "reel": "Reel", "taggati": "Taggati" }, "errori": { "pausa": "La pausa minima non può scendere sotto i {n} minuti.", "sessione": "Una sessione non può durare più di {n} minuti.", @@ -1022,7 +1067,9 @@ "testo": "Febe conserva sul tuo disco foto, video e storie degli account che scegli, e li tiene aggiornati poco per volta. Per cominciare collega il tuo account di Instagram, oppure porta in libreria le foto e i video che hai già.", "collegati": "Collegati a Instagram", "importa": "Importa foto e video che hai già", - "nota": "Scaricare con un programma è contro le condizioni d'uso di Instagram: Febe va piano per ridurre il rischio, ma non può azzerarlo." + "dashboard": "Qui vedrai Febe al lavoro: che cosa guarda, i tetti di oggi e ciò che arriva. Per cominciare collega il tuo account di Instagram, oppure porta in libreria le foto e i video che hai già.", + "dashboardCollegato": "Qui vedrai Febe al lavoro: che cosa guarda, i tetti di oggi e ciò che arriva. Per cominciare aggiungi gli account da seguire, oppure porta in libreria le foto e i video che hai già.", + "nota":"Scaricare con un programma è contro le condizioni d'uso di Instagram: Febe va piano per ridurre il rischio, ma non può azzerarlo." }, "problemi": { "titolo": "Febe non può partire", diff --git a/tests/Febe.Tests/Alerts/AlertServiceTests.cs b/tests/Febe.Tests/Alerts/AlertServiceTests.cs index 1128f8e..2194543 100644 --- a/tests/Febe.Tests/Alerts/AlertServiceTests.cs +++ b/tests/Febe.Tests/Alerts/AlertServiceTests.cs @@ -175,6 +175,8 @@ public sealed class AlertServiceTests Assert.IsTrue(bed.Outcomes.Any(o => o.Alert.Kind == AlertKind.UnknownFormat && o.Kind == AlertOutcomeKind.Repeated)); var suspended = texts.Single(t => t.StartsWith("Febe · Ricetta sospesa\n", StringComparison.Ordinal)); StringAssert.Contains(suspended, "modalità sonda"); + StringAssert.Contains(suspended, "si riattiva dalla Dashboard («Riattiva»)", "la pagina si chiama Dashboard (tappa D1)"); + Assert.IsFalse(suspended.Contains("Attività", StringComparison.Ordinal), suspended); } [TestMethod] diff --git a/tests/Febe.Tests/Collection/DownloadQueueTests.cs b/tests/Febe.Tests/Collection/DownloadQueueTests.cs index effa3dd..fc387d3 100644 --- a/tests/Febe.Tests/Collection/DownloadQueueTests.cs +++ b/tests/Febe.Tests/Collection/DownloadQueueTests.cs @@ -406,6 +406,44 @@ public sealed class DownloadQueueTests Assert.AreEqual(1, cdp.Sent.Count(c => c.Method == "IO.close")); } + [TestMethod] + public async Task TheFilesArriveInTheOrderOfEachAccountWithAShareForTheLongestWaiting() + { + // «Cosa scaricare prima» (spec §6.5, §7.2): the general order for one account, an order of its own for the other. + using var temp = new TempFolder("coda-ordine"); + await using var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001")); + var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.prova", "1002") with { DownloadOrder = "taggati,post" }); + await AddAsync(library.Db, marta, "s", EntryKind.Story, "https://cdn.esempio/m/storia.jpg"); + await AddAsync(library.Db, marta, "p", EntryKind.Post, "https://cdn.esempio/m/post.jpg"); + await AddAsync(library.Db, luca, "q", EntryKind.Post, "https://cdn.esempio/m/post-luca.jpg"); + await AddAsync(library.Db, luca, "g", EntryKind.Tagged, "https://cdn.esempio/m/taggato-luca.jpg"); + var asked = new List(); + var fetcher = new ScriptedFetcher((address, destination, ct) => + { + lock (asked) + { + asked.Add(address!.AbsolutePath); + } + + return ScriptedFetcher.PhotoByPath(address, destination, ct); + }); + + var orderOnly = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1, LongestWaitingShare = 0 }); + Assert.AreEqual(4, (await orderOnly.RunOnceAsync(CancellationToken.None)).Stored); + CollectionAssert.AreEqual(new[] { "/m/storia.jpg", "/m/taggato-luca.jpg", "/m/post-luca.jpg", "/m/post.jpg" }, asked); + + // With one place in two for the longest waiting, Marta's post, found first, is the second file. + asked.Clear(); + var older = (await library.Db.Entries.AddAsync(Make.Entry(marta.Id, "vecchio", Make.T0.AddDays(-3)) with { DiscoveredAt = Make.T0.AddDays(-2) }, [Make.Photo() with { SourceUrl = "https://cdn.esempio/m/vecchio.jpg", SourceSeenAt = Make.T0 }])).Stored.Entry; + await AddAsync(library.Db, marta, "s2", EntryKind.Story, "https://cdn.esempio/m/storia-2.jpg"); + await AddAsync(library.Db, marta, "s3", EntryKind.Story, "https://cdn.esempio/m/storia-3.jpg"); + var shared = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1, LongestWaitingShare = 2 }); + Assert.AreEqual(3, (await shared.RunOnceAsync(CancellationToken.None)).Stored); + CollectionAssert.AreEqual(new[] { "/m/storia-2.jpg", "/m/vecchio.jpg", "/m/storia-3.jpg" }, asked); + Assert.AreEqual(EntryState.Downloaded, (await library.Db.Entries.GetAsync(older.Id))!.State); + } + private static DownloadQueue Queue(TestLibrary library, TempFolder temp, IFileFetcher fetcher, SignalDetector? signals = null, DownloadOptions? options = null, IDataBudget? budget = null) => new(library.Db, library.Ingest, fetcher, budget ?? new FakeDataBudget(), library.Clock, new SeededRandom(1), options ?? new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei") }, signals); diff --git a/tests/Febe.Tests/Collection/InstagramReaderTests.cs b/tests/Febe.Tests/Collection/InstagramReaderTests.cs index 3c84908..bbbae8f 100644 --- a/tests/Febe.Tests/Collection/InstagramReaderTests.cs +++ b/tests/Febe.Tests/Collection/InstagramReaderTests.cs @@ -65,7 +65,7 @@ public sealed class InstagramReaderTests { Vocabulary.Content.Id, Vocabulary.Content.Code, Vocabulary.Content.TakenAt, Vocabulary.Content.Caption, Vocabulary.Content.Images, Vocabulary.Content.Videos, Vocabulary.Content.Children, Vocabulary.Content.ChildCount, Vocabulary.Content.Owner, Vocabulary.Content.Pinned, - Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height, + Vocabulary.Content.ExpiresAt, Vocabulary.Content.Duration, Vocabulary.Content.ProductType, Vocabulary.Version.Url, Vocabulary.Version.Width, Vocabulary.Version.Height, Vocabulary.Version.HasAudio, Vocabulary.Profile.Id, Vocabulary.Profile.Username, Vocabulary.Profile.DisplayName, Vocabulary.Profile.IsPrivate, Vocabulary.Profile.IsFollowed, Vocabulary.Profile.PostCount, Vocabulary.Profile.Picture, Vocabulary.Profile.LatestStoryAt, Vocabulary.Highlight.Id, Vocabulary.Highlight.Title, Vocabulary.Highlight.Owner, Vocabulary.Highlight.Items, Vocabulary.Highlight.Cover, @@ -82,6 +82,14 @@ public sealed class InstagramReaderTests { Assert.IsTrue(names.Contains(key), $"«{key}» non compare in nessun campione ripulito di Instagram."); } + + // The values that mean «reel» are values of the samples too (rule 9). + var samples = string.Concat(Directory.EnumerateFiles(Path.Combine(AppContext.BaseDirectory, "campioni", "instagram"), "*.json").Select(File.ReadAllText)); + Assert.IsNotEmpty(Vocabulary.Content.ReelTypes); + foreach (var value in Vocabulary.Content.ReelTypes) + { + Assert.Contains($"\"product_type\": \"{value}\"", samples, $"«{value}» non compare come product_type in nessun campione ripulito di Instagram."); + } } [TestMethod] @@ -230,6 +238,8 @@ public sealed class InstagramReaderTests Assert.AreEqual(MediaKind.Video, reel.Kind); Assert.AreEqual((720, 1280), (reel.Best.Width, reel.Best.Height)); Assert.IsNotNull(reel.Cover); + Assert.IsTrue(result.Contents[0].IsReel, "product_type «clips»: a reel for «Cosa scaricare prima»."); + Assert.IsFalse(result.Contents[1].IsReel, "product_type «carousel_container»: a series."); var series = result.Contents[1].Files; Assert.AreEqual(6, series.Count, "carousel_media: one file for each child."); diff --git a/tests/Febe.Tests/Collection/RequestRecipeTests.cs b/tests/Febe.Tests/Collection/RequestRecipeTests.cs index 780e7dc..ef42d62 100644 --- a/tests/Febe.Tests/Collection/RequestRecipeTests.cs +++ b/tests/Febe.Tests/Collection/RequestRecipeTests.cs @@ -120,7 +120,10 @@ public sealed class RequestRecipeTests CollectionAssert.AreEqual(new[] { "taggati", "reel" }, bed.Scripted!.Sent.Select(s => s.Operation).ToArray()); CollectionAssert.AreEqual(new[] { ActionKind.BackfillPage, ActionKind.BackfillPage }, bed.Governor.Requests.Select(r => r.Kind).ToArray()); Assert.AreEqual(3, (await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).Count); - Assert.AreEqual(6, (await bed.Db.Entries.ListByAccountAsync(reels.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 })).Count); + var reelPosts = await bed.Db.Entries.ListByAccountAsync(reels.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 }); + Assert.AreEqual(6, reelPosts.Count); + Assert.IsTrue(reelPosts.All(e => e.IsReel), "what the Reel tab gives is a reel («Cosa scaricare prima», spec §7.2)"); + Assert.IsTrue((await bed.Db.Entries.ListByAccountAsync(marta.Id, new EntryListOptions { Kind = EntryKind.Tagged, Limit = 100 })).All(e => !e.IsReel), "a tagged post is never a reel"); Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.taggati.{Id(marta)}.completo")); Assert.IsNotNull(await bed.Db.Settings.GetAsync($"raccolta.reel.{Id(reels)}.completo")); } diff --git a/tests/Febe.Tests/Data/LibraryFilesTests.cs b/tests/Febe.Tests/Data/LibraryFilesTests.cs new file mode 100644 index 0000000..0b33fe1 --- /dev/null +++ b/tests/Febe.Tests/Data/LibraryFilesTests.cs @@ -0,0 +1,190 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Data; + +/// +/// «Tutte le foto» (spec §4.6): one tile per file of the library, in the order of the entries and then of the series, +/// with keyset paging that may stop and start again inside a post. +/// +[TestClass] +public sealed class LibraryFilesTests +{ + [TestMethod] + public async Task EveryFileOfTheLibraryIsATileInTheOrderOfTheEntriesAndOfTheSeries() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var (carousel, single, partial, story) = await FillAsync(db); + + var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files }); + var keys = page.Tiles.Select(t => (t.EntryId, t.FilePosition)).ToList(); + CollectionAssert.AreEqual( + new (long, int?)[] { (story, 1), (carousel, 1), (carousel, 2), (carousel, 3), (partial, 1), (partial, 3), (single, 1) }, + keys, + "Newest entry first, each by position; the file still to download of the partial post is not a tile."); + Assert.IsNull(page.Older); + Assert.IsNull(page.Newer); + + // A file tile describes that file, and keeps the count of the files of its post («2/3»). + var second = page.Tiles[2]; + Assert.AreEqual(3, second.MediaCount); + Assert.AreEqual(MediaKind.Video, second.CoverKind); + Assert.AreEqual(Make.Sha(12), second.CoverSha256); + Assert.AreEqual(TimeSpan.FromSeconds(15), second.CoverDuration); + Assert.AreEqual(3, page.Tiles[5].FilePosition); + Assert.AreEqual(3, page.Tiles[5].MediaCount); + + // The grouped mosaic is what it was: one tile per entry. + var grouped = await db.Entries.QueryLibraryAsync(new LibraryQuery()); + CollectionAssert.AreEqual(new[] { story, carousel, partial, single }, grouped.Tiles.Select(t => t.EntryId).ToArray()); + Assert.IsTrue(grouped.Tiles.All(t => t.FilePosition is null)); + } + + [TestMethod] + public async Task WindowsOfTwoWalkEveryFileOnceInBothDirectionsAlsoFromInsideAPost() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + await FillAsync(db); + var all = (await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files })).Tiles.Select(Key).ToList(); + + // Older, two at a time from the top: the second window starts in the middle of the carousel. + var walked = new List(); + LibraryCursor? cursor = null; + var windows = 0; + do + { + var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 2, Cursor = cursor }); + walked.AddRange(page.Tiles.Select(Key)); + Assert.AreEqual(windows > 0, page.Newer is not null, "a window after the first has something newer"); + cursor = page.Older; + windows++; + } + while (cursor is not null); + + CollectionAssert.AreEqual(all, walked); + Assert.AreEqual(4, windows); + + // Newer, two at a time from the last file, back to the top. + var last = (await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 1000 })).Tiles[^1]; + cursor = new LibraryCursor(last.PublishedAt, last.EntryId, last.FilePosition!.Value); + var back = new List(); + while (cursor is not null) + { + var page = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 2, Cursor = cursor, Direction = LibraryDirection.Newer }); + Assert.IsNotNull(page.Older, "a window newer than a file has that file after it"); + back.InsertRange(0, page.Tiles.Select(Key)); + cursor = page.Newer; + } + + CollectionAssert.AreEqual(all.Take(all.Count - 1).ToList(), back); + } + + [TestMethod] + public async Task FiltersCountsAndDaysCountTheFiles() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var (carousel, _, _, _) = await FillAsync(db); + + // «Video» shows only the videos, «Foto» only the photos (of posts, as in the grouped mosaic). + var videos = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } }); + CollectionAssert.AreEqual(new[] { $"{carousel}.2" }, videos.Tiles.Select(Key).ToArray()); + var photos = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Photos } }); + Assert.HasCount(5, photos.Tiles); + Assert.IsTrue(photos.Tiles.All(t => t.CoverKind == MediaKind.Photo)); + + Assert.AreEqual(7, await FileTotalAsync(db, new LibraryFilter())); + Assert.AreEqual(1, await FileTotalAsync(db, new LibraryFilter { Kind = LibraryKindFilter.Videos })); + Assert.AreEqual(5, await FileTotalAsync(db, new LibraryFilter { Kind = LibraryKindFilter.Photos })); + Assert.AreEqual(1, await FileTotalAsync(db, new LibraryFilter { Kind = LibraryKindFilter.Stories })); + Assert.AreEqual(new LibraryTotals(4, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter()), "the totals stay entries"); + + var days = await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files); + CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 6), new DayCount(new DateOnly(2026, 10, 12), 1) }, days.ToArray()); + var entryDays = await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome); + CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 3), new DayCount(new DateOnly(2026, 10, 12), 1) }, entryDays.ToArray()); + + // With a filter on accounts the files are counted entry by entry: the same numbers. + var accountId = (await db.Entries.GetAsync(carousel))!.AccountId; + var other = await db.Accounts.AddAsync(Make.Account("luca.demo")); + await db.Entries.AddAsync(Make.Entry(other.Id, "o", new DateTimeOffset(2026, 10, 13, 8, 0, 0, TimeSpan.Zero)), [Make.Stored(Make.Photo(), Make.Sha(41), "o/o.jpg")]); + var mine = new LibraryFilter { AccountIds = [accountId] }; + Assert.AreEqual(7, await FileTotalAsync(db, mine)); + Assert.AreEqual(8, await FileTotalAsync(db, new LibraryFilter())); + CollectionAssert.AreEqual(days.ToArray(), (await db.Entries.CountLibraryByDayAsync(mine, TestZones.Rome, MosaicMode.Files)).ToArray()); + Assert.AreEqual(8, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files)).Sum(d => d.Count)); + Assert.AreEqual(1, await FileTotalAsync(db, mine with { Kind = LibraryKindFilter.Videos })); + + // A day whose files are all of another kind has no row in «Video». + var videoDays = await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files); + CollectionAssert.AreEqual(new[] { new DayCount(new DateOnly(2026, 10, 13), 1) }, videoDays.ToArray()); + + // The cursor at the end of a day (what the mosaic asks first for a day) starts with that day's newest file. + var dayStart = LocalCalendar.StartOfDay(new DateOnly(2026, 10, 13), TestZones.Rome); + var fromDay = await db.Entries.QueryLibraryAsync(new LibraryQuery { Mode = MosaicMode.Files, Limit = 1, Cursor = new LibraryCursor(dayStart, 0) }); + Assert.AreEqual(new DateOnly(2026, 10, 12), LocalCalendar.Today(fromDay.Tiles.Single().PublishedAt, TestZones.Rome)); + } + + [TestMethod] + public async Task GroupedPhotoAndVideoCountsAgreeWithTheirWindowsWithAndWithoutAccounts() + { + // The counts of the whole library read one list of the entries with such files, those of an account an EXISTS + // per post, the windows always the EXISTS: the same entries every way. + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var (carousel, single, partial, _) = await FillAsync(db); + var accountId = (await db.Entries.GetAsync(carousel))!.AccountId; + var other = await db.Accounts.AddAsync(Make.Account("luca.demo")); + await db.Entries.AddAsync(Make.Entry(other.Id, "v", new DateTimeOffset(2026, 10, 11, 8, 0, 0, TimeSpan.Zero)), [Make.Stored(Make.Video(), Make.Sha(51), "o/v.mp4")]); + + foreach (var (kind, mine, everyone) in new[] + { + (LibraryKindFilter.Videos, new[] { carousel }, 2), + (LibraryKindFilter.Photos, new[] { carousel, partial, single }, 3), + }) + { + var all = new LibraryFilter { Kind = kind }; + var own = all with { AccountIds = [accountId] }; + Assert.AreEqual(new LibraryTotals(everyone, kind == LibraryKindFilter.Videos ? 2 : 1), await db.Entries.GetLibraryTotalsAsync(all), $"{kind}"); + Assert.AreEqual(everyone, (await db.Entries.CountLibraryByDayAsync(all, TestZones.Rome)).Sum(d => d.Count)); + Assert.AreEqual(everyone, (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = all })).Tiles.Count); + Assert.AreEqual(new LibraryTotals(mine.Length, 1), await db.Entries.GetLibraryTotalsAsync(own), $"{kind} di un account"); + Assert.AreEqual(mine.Length, (await db.Entries.CountLibraryByDayAsync(own, TestZones.Rome)).Sum(d => d.Count)); + CollectionAssert.AreEquivalent(mine, (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = own })).Tiles.Select(t => t.EntryId).ToArray()); + } + } + + private static string Key(LibraryTile tile) => $"{tile.EntryId}.{tile.FilePosition}"; + + /// The files of «Tutte le foto» of a filter: the sum of its days, as /api/library/days gives it. + private static async Task FileTotalAsync(FebeDatabase db, LibraryFilter filter) => + (await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files)).Sum(d => d.Count); + + /// + /// A story (13 Oct, 12:00), a carousel of photo, video, photo (13 Oct, 10:00), a post with its second file still to + /// download (13 Oct, 9:00) and a single photo (12 Oct, 9:00), all of one account. + /// + private static async Task<(long Carousel, long Single, long Partial, long Story)> FillAsync(FebeDatabase db) + { + var account = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var day = new DateTimeOffset(2026, 10, 13, 0, 0, 0, TimeSpan.FromHours(2)); + var single = await db.Entries.AddAsync(Make.Entry(account.Id, "s", day.AddHours(-15)), [Make.Stored(Make.Photo(), Make.Sha(1), "p/s.jpg")]); + var partial = await db.Entries.AddAsync(Make.Entry(account.Id, "p", day.AddHours(9)), [ + Make.Stored(Make.Photo(1), Make.Sha(21), "p/p1.jpg"), + Make.Photo(2), + Make.Stored(Make.Photo(3), Make.Sha(23), "p/p3.jpg"), + ]); + var carousel = await db.Entries.AddAsync(Make.Entry(account.Id, "c", day.AddHours(10)), [ + Make.Stored(Make.Photo(1), Make.Sha(11), "p/c1.jpg"), + Make.Stored(Make.Video(2), Make.Sha(12), "p/c2.mp4"), + Make.Stored(Make.Photo(3), Make.Sha(13), "p/c3.jpg"), + ]); + var story = await db.Entries.AddAsync(Make.Entry(account.Id, "st", day.AddHours(12), EntryKind.Story), [Make.Stored(Make.Photo(), Make.Sha(31), "s/st.jpg")]); + Assert.AreEqual(EntryState.Partial, partial.Stored.Entry.State); + return (carousel.Stored.Entry.Id, single.Stored.Entry.Id, partial.Stored.Entry.Id, story.Stored.Entry.Id); + } +} diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index b60c509..3fbe074 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -22,6 +22,9 @@ public sealed class LibraryScaleTests private const double IndexBoundMs = 250; private const double AggregateBoundMs = 1500; + // «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail. + private const double FilteredAggregateBoundMs = 600; + public TestContext TestContext { get; set; } = null!; [TestMethod] @@ -109,6 +112,41 @@ public sealed class LibraryScaleTests Assert.AreEqual(new LibraryTotals(Entries, Accounts), totals); var days = await Measure("conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome)); Assert.AreEqual(Entries, days.Sum(d => d.Count)); + // «Tutte le foto» (spec §4.6): one tile per file, in the same times as the grouped mosaic. + var files = await Measure("tutte le foto: prima finestra", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files })); + Assert.HasCount(200, files.Tiles); + Assert.IsTrue(files.Tiles.All(t => t.FilePosition is not null)); + var insidePost = files.Tiles.First(t => t.MediaCount == 2 && t.FilePosition == 1); + var resumed = await Measure("tutte le foto: finestra dentro un post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery + { + Limit = 200, + Mode = MosaicMode.Files, + Cursor = new LibraryCursor(insidePost.PublishedAt, insidePost.EntryId, 1), + })); + Assert.AreEqual((insidePost.EntryId, (int?)2), (resumed.Tiles[0].EntryId, resumed.Tiles[0].FilePosition)); + var filesMiddle = await Measure("tutte le foto: finestra a metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Cursor = middleCursor })); + Assert.HasCount(200, filesMiddle.Tiles); + await Measure("tutte le foto: più recente da metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Cursor = middleCursor, Direction = LibraryDirection.Newer })); + await Measure("tutte le foto: filtro Video", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Kind = LibraryKindFilter.Videos } })); + await Measure("tutte le foto: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]] } })); + await Measure("tutte le foto: ricerca comune", AggregateBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { Search = "caffe" } })); + // The days give the total of the files too (/api/library/days): one pass over the media table per request. + var fileDays = await Measure("tutte le foto: conteggi per giorno", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter(), TestZones.Rome, MosaicMode.Files)); + Assert.AreEqual(Entries + (Entries / 5), fileDays.Sum(d => d.Count)); + var accountFiles = await Measure("tutte le foto: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]] }, TestZones.Rome, MosaicMode.Files)); + Assert.AreEqual(Enumerable.Range(0, Entries).Where(n => n % Accounts == 3).Sum(n => n % 5 == 0 ? 2 : 1), accountFiles.Sum(d => d.Count)); + // «Foto» and «Video» in the grouped mosaic: the totals and the days of a whole library must not pay an EXISTS + // per post (over a second); a list of the entries with such files keeps them near a tenth of a second. + var videoTotals = await Measure("totali del filtro Video", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos })); + var videoDays = await Measure("conteggi per giorno del filtro Video", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome)); + Assert.AreEqual(videoTotals.Entries, videoDays.Sum(d => d.Count)); + Assert.AreEqual(Enumerable.Range(0, Entries).Count(n => n % 10 >= 4 && n % 7 == 0), videoTotals.Entries); + var photoTotals = await Measure("totali del filtro Foto", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Kind = LibraryKindFilter.Photos })); + Assert.AreEqual(Enumerable.Range(0, Entries).Count(n => n % 10 >= 4 && (n % 7 != 0 || n % 5 == 0)), photoTotals.Entries); + await Measure("scheda account: Post", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } })); + await Measure("scheda account: Post, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } })); + await Measure("scheda account: conteggi dei Post", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts }, TestZones.Rome)); + await Measure("tutte le foto: conteggi del filtro Video", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files)); await Measure("è già noto? (pagina di 12)", IndexBoundMs, async () => await db.Entries.GetKnownInstagramIdsAsync(accountIds[5], EntryKind.Post, Enumerable.Range(0, 12).Select(i => $"id{5 + (i * 40)}").ToList())); await Measure("SHA-256 in tutta la libreria", IndexBoundMs, () => db.Media.FindBySha256Async(Make.Sha(150_001))); var summaries = await Measure("elenco account con conteggi", AggregateBoundMs, () => db.Accounts.ListSummariesAsync(new DateTimeOffset(2026, 10, 1, 0, 0, 0, TimeSpan.Zero))); diff --git a/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs b/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs index cbdad9d..7b04d63 100644 --- a/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs +++ b/tests/Febe.Tests/Desktop/DesktopCompositionTests.cs @@ -39,13 +39,15 @@ public sealed class DesktopCompositionTests Assert.AreEqual(HttpStatusCode.Unauthorized, anonymous.StatusCode, path); } - // The window opens /?gettone=… once: the token becomes an HttpOnly cookie and leaves the address. + // The window opens /dashboard?gettone=… once (the Dashboard is the start page, spec §7.9, §12): the token + // becomes an HttpOnly cookie and leaves the address, which stays on the Dashboard. var first = bed.Platform.FirstAddress(bed.App.Address); + Assert.AreEqual("/dashboard", first.AbsolutePath); StringAssert.StartsWith(first.Query, "?gettone="); using (var opening = await bed.Client.GetAsync(first.PathAndQuery, TestContext.CancellationToken)) { Assert.AreEqual(HttpStatusCode.Redirect, opening.StatusCode); - Assert.AreEqual("/", opening.Headers.Location?.OriginalString); + Assert.AreEqual("/dashboard", opening.Headers.Location?.OriginalString); var cookie = opening.Headers.GetValues("Set-Cookie").Single(); StringAssert.Contains(cookie, "httponly"); StringAssert.Contains(cookie, "samesite=strict"); diff --git a/tests/Febe.Tests/Docs/GuideTests.cs b/tests/Febe.Tests/Docs/GuideTests.cs index f8838a3..f5d7aef 100644 --- a/tests/Febe.Tests/Docs/GuideTests.cs +++ b/tests/Febe.Tests/Docs/GuideTests.cs @@ -21,7 +21,7 @@ public sealed partial class GuideTests "Libreria", "Importazione", "Limiti-e-comportamento", - "Attivita-e-arresti", + "Dashboard-e-arresti", "Avvisi-e-Telegram", "Copie-e-ricostruzione", "Sicurezza-e-riservatezza", @@ -45,7 +45,7 @@ public sealed partial class GuideTests ["l'interfaccia Docker non va esposta su Internet", new[] { "Sicurezza-e-riservatezza" }, new[] { "non esporre mai l'interfaccia docker su internet", "vpn", "https" }], ["in Docker la password di Instagram passa dal server", new[] { "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "la password di instagram passa dal server" }], ["il compromesso sulla sandbox di Chromium", new[] { "Installazione-Docker-e-Unraid", "Sicurezza-e-riservatezza" }, new[] { "sandbox", "seccomp", "febe_senza_sandbox=1", "compromesso" }], - ["che cosa fare dopo una verifica o un rallentamento", new[] { "Attivita-e-arresti" }, new[] { "che cosa fare dopo una verifica", "che cosa fare dopo un rallentamento", "completa la verifica a mano", "riprendi", "tre rallentamenti in sette giorni" }], + ["che cosa fare dopo una verifica o un rallentamento", new[] { "Dashboard-e-arresti" }, new[] { "che cosa fare dopo una verifica", "che cosa fare dopo un rallentamento", "completa la verifica a mano", "riprendi", "tre rallentamenti in sette giorni" }], ["dove sono le copie del database e come si ricostruisce", new[] { "Copie-e-ricostruzione" }, new[] { "/dati/copie", "%localappdata%\\febe\\copie", "febe-aaaa-mm-gg.sqlite", "ricostruisci il database dalla libreria", "_febe.jsonl" }], ["esportazione CSV dell'elenco (§4.8)", new[] { "Libreria" }, new[] { "esporta l'elenco", "`;`", "utf-8 con bom" }], ["Telegram: BotFather e identificativo della chat (§13.3)", new[] { "Avvisi-e-Telegram" }, new[] { "@botfather", "/newbot", "getupdates", "\"chat\":{\"id\":", "invia una prova" }], diff --git a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs index bc9c508..dcda8a1 100644 --- a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs +++ b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs @@ -153,7 +153,22 @@ public sealed partial class SpecificationConsistencyTests ["«Cosa scaricare prima» pesa visite e coda senza cambiare il resto", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine", new[] { "storie, evidenza, post, reel, taggati", "dopo il giro dei seguiti, che resta sempre primo", "visite del motore nella sessione", "coda dei file", "«come le impostazioni generali», il predefinito", "il governatore e i tetti", "le frequenze", "composizione casuale delle sessioni", "non le rende fisse", "§16 domanda 19" }], ["«Cosa scaricare prima» c'è anche per account", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): «Come", new[] { "«come le impostazioni generali» (predefinito)", "trascinando", "§7.2, §6.5" }], ["la coda dei file segue «Cosa scaricare prima»", "6. Coda dedicata", new[] { "«cosa scaricare prima»", "prima i file del tipo che viene primo", "le foto del profilo vanno con i post" }], - ["il peso di un tipo ha i suoi numeri", "| Peso di un tipo nella scelta", new[] { "16, 8, 4, 2, 1", "proposta" }], + ["il peso di un tipo ha i suoi numeri", "| Peso di un tipo nella scelta", new[] { "16, 8, 4, 2, 1", "proposta", "da confermare con alberto", "le visite senza account (giro, elenco dei seguiti) restano fuori" }], + ["la coda riserva un posto al file più vecchio, non una quota per tipo", "6. Coda dedicata", new[] { "un posto su otto", "che aspetta da più tempo in tutta la coda", "nessun file aspetti per sempre", "non è una quota per tipo", "aspetta che quell'arretrato finisca" }], + ["un reel si riconosce dalla scheda Reel o da product_type", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine", new[] { "percorrendo la scheda reel", "`product_type` «clips»", "un taggato non è mai un reel", "dopo le storie segnalate dalla barra delle storie, che restano davanti", "un posto su otto va al file che aspetta da più tempo" }], + ["la scelta del mosaico resta nel browser, il tema no", "- **«Raggruppa i post» o «Tutte le foto»**", new[] { "solo nel browser in cui si fa", "a differenza del tema", "`febe.mosaico.libreria`", "non passa a un altro browser" }], + ["l'interfaccia di programmazione di «Tutte le foto»", "- **«Raggruppa i post» o «Tutte le foto»**", new[] { "`mode=grouped|files`", "dà 400", "`ms.elemento.posizione`", "il campo `files`", "con `grouped` è `null`" }], + ["la Dashboard resta compressa anche in una finestra media", "Si aggiorna da sola con gli eventi del server", new[] { "accanto allo stato", "1440 × 900 e a 860 × 900", "l'inizio della cronologia stanno nel primo schermo", "al telefono una colonna sola" }], + ["al primo avvio la Dashboard ha il benvenuto compatto", "**Primo avvio.**", new[] { "`/` apre la dashboard", "finché non c'è nessun account", "«collegati a instagram»", "«importa foto e video che hai già»", "«aggiungi account»", "sparisce da solo" }], + ["gli arresti finiscono nella cronologia della Dashboard", "- Ogni arresto finisce nella tabella `incident`", new[] { "cronologia della dashboard" }], + ["D1 ha la migrazione 0002", "| **D1 Dashboard e ordine** |", new[] { "migrazione `0002`", "`account.download_order`", "`entry.is_reel`", "`ix_entry_discovered`", "`ix_media_entry_files`" }], + ["E1 prende la migrazione 0003", "| **E1 Schema** |", new[] { "migrazione `0003`", "la `0002` è di d1" }], + ["le tabelle dell'esportazione vanno nella 0003", "| `export_destination`", new[] { "migrazione `0003`" }], + ["gli indici di D1 sono nello schema", "- Indici su (account, data di pubblicazione)", new[] { "`0002`", "`ix_entry_discovered`", "`ix_media_entry_files`" }], + ["le dipendenze dicono chi ha la 0002", "Dipendenze: C1", new[] { "la migrazione `0002` è di d1", "e1 prende la `0003`" }], + ["l'icona della Dashboard è layout-dashboard", "| Navigazione |", new[] { "`layout-dashboard`", "`layout-grid`" }], + ["la freccia «Su» è fra le icone", "| Frecce |", new[] { "`chevron-up`" }], + ["la maniglia è fra le icone", "| Azioni |", new[] { "`grip-vertical`" }], ["la Dashboard è il cruscotto e la pagina iniziale", "La **Dashboard**", new[] { "cruscotto del motore", "pagina iniziale", "`/dashboard`", "`/attivita`", "la finestra di febe per windows si apre lì", "compatta" }], ["la Dashboard mostra sempre l'anteprima del browser", "- **l'anteprima del browser, sempre visibile**", new[] { "che scorre", "mai nascosta dietro un clic" }], ["la cronologia ha le miniature e l'anteprima ingrandita", "- la **cronologia dell'attività**", new[] { "miniature", "anteprima ingrandita", "«apri nella libreria»", "«apri l'account»" }], @@ -166,8 +181,46 @@ public sealed partial class SpecificationConsistencyTests ["il glossario ha «Cosa scaricare prima»", "| Cosa scaricare prima |", new[] { "`downloadorder`" }], ["il glossario ha «Raggruppa i post»", "| Raggruppa i post |", new[] { "tessera per elemento" }], ["il glossario ha «Tutte le foto»", "| Tutte le foto |", new[] { "tessera per file" }], + ["i 5 secondi di grazia in Docker sono una proposta", "**Quando si copia**", new[] { "i 5 secondi di grazia sono una proposta, §16 domanda 20", "alberto ha detto solo che lasciare la pagina copia la sessione" }], + ["§16 chiede dei 5 secondi di grazia", "| 20 |", new[] { "5 secondi di grazia", "docker", "alberto non ha detto una durata" }], + ["il posto su otto della coda è una proposta", "6. Coda dedicata", new[] { "come proposta (§16 domanda 21: alberto ha chiesto solo l'ordine)" }], + ["§7.2 dice che il posto su otto è una proposta", "- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine", new[] { "(§6.5; una proposta, §16 domanda 21)" }], + ["§16 chiede del posto su otto", "| 21 |", new[] { "un posto su otto", "un minimo per tipo", "alberto ha chiesto solo l'ordine" }], + ["«Tutte le foto» mostra solo i file in libreria e manca in «In evidenza»", "- **«Raggruppa i post» o «Tutte le foto»**", new[] { "scheda account, tranne «in evidenza», disegnata per raccolta", "ha una tessera solo un file presente in libreria", "un file ancora da scaricare, fallito o saltato no", "con i filtri «foto» e «video» si vedono solo i file di quel tipo" }], + ["la scheda account ha l'interruttore tranne in «In evidenza»", "- Scheda dell'account con gli elementi divisi", new[] { "«raggruppa i post» / «tutte le foto» in ogni linguetta tranne «in evidenza»" }], + ["il mockup 12 dà l'interruttore tranne in «In evidenza»", "- **«Raggruppa i post» / «Tutte le foto»** (§4.6), dal mockup 01", new[] { "scheda account (mockup 12), tranne «in evidenza»" }], + ["la riga del mockup 06 rimanda alle schermate di D1", "| `06-attivita.png` |", new[] { "superato dalla dashboard (qui sotto, «schermate della tappa d1»)" }], ]; + /// + /// The confirmation of «Elimina» with «Tutte le foto» that spec §4.6 quotes is the text the interface builds from + /// testi/it.json (library.js: «elimina.fileDi», then «: », then «elimina.interi»), with 3 files of 2 entries, 9 files. + /// + [TestMethod] + public void TheSpecificationQuotesTheDeleteConfirmationTheInterfaceBuilds() + { + using var texts = System.Text.Json.JsonDocument.Parse(Read("src", "Febe.Web", "wwwroot", "testi", "it.json")); + string Plural(string section, string key) => texts.RootElement.GetProperty(section).GetProperty(key).GetString()!.Split('|')[1]; + var entries = Plural("comune", "elementi").Replace("{n}", "2", StringComparison.Ordinal); + var files = Plural("comune", "file").Replace("{n}", "9", StringComparison.Ordinal); + var built = Plural("elimina", "fileDi").Replace("{n}", "3", StringComparison.Ordinal).Replace("{elementi}", entries, StringComparison.Ordinal) + + ": " + Plural("elimina", "interi").Replace("{n}", "2", StringComparison.Ordinal).Replace("{file}", files, StringComparison.Ordinal); + Assert.AreEqual("3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file.", built, "i testi di it.json"); + var line = Read("docs", "SPECIFICA.md").Split('\n').First(l => l.StartsWith("- **«Raggruppa i post» o «Tutte le foto»**", StringComparison.Ordinal)); + StringAssert.Contains(line, $"«{built}»", "§4.6 cita la conferma com'è costruita"); + } + + /// docs/stato.md writes down the results of the checks (CLAUDE.md, spec rule 14), never a pointer to a session. + [TestMethod] + public void TheStatusFileWritesDownTheResultsOfTheChecks() + { + var text = GuideTests.Normalize(Read("docs", "stato.md")); + Assert.DoesNotContain("vedi il resoconto della sessione", text, "i risultati dei controlli vanno scritti in docs/stato.md"); + var checks = text[text.IndexOf("controlli sul ramo `funzione/dashboard`", StringComparison.Ordinal)..]; + checks = checks[..checks.IndexOf("non verificato", StringComparison.Ordinal)]; + StringAssert.Contains(checks, "superate", "il resoconto dei controlli di funzione/dashboard ha i conteggi"); + } + private static string Root() => Directory.GetParent(GuideTests.GuideFolder())!.Parent!.FullName; private static string Read(params string[] parts) => File.ReadAllText(Path.Combine([Root(), .. parts])); @@ -329,6 +382,62 @@ public sealed partial class SpecificationConsistencyTests Assert.IsEmpty(problems, string.Join("\n", problems)); } + [TestMethod] + public void EveryIconOfAppendixCIsDrawnAndActivityIsGone() + { + var spec = Read("docs", "SPECIFICA.md"); + var start = spec.IndexOf("## Appendice C", StringComparison.Ordinal); + var end = spec.IndexOf("## Appendice D", StringComparison.Ordinal); + Assert.IsTrue(start >= 0 && end > start, "l'appendice C"); + var rows = spec[start..end].Split('\n').Where(l => l.StartsWith("| ", StringComparison.Ordinal) && !l.StartsWith("| Uso", StringComparison.Ordinal)); + var named = rows.SelectMany(r => IconName().Matches(r.Split('|')[2]).Select(m => m.Groups["name"].Value)).ToList(); + Assert.IsGreaterThan(50, named.Count, "l'elenco delle icone"); + var folder = Path.Combine(Root(), "src", "Febe.Web", "wwwroot", "icone"); + var missing = named.Where(n => !File.Exists(Path.Combine(folder, n + ".svg"))).ToList(); + Assert.IsEmpty(missing, $"icone nominate nell'appendice C senza disegno: {string.Join(", ", missing)}"); + CollectionAssert.DoesNotContain(named, "activity", "`activity` è uscita con la Dashboard"); + Assert.IsFalse(File.Exists(Path.Combine(folder, "activity.svg"))); + } + + /// + /// D1 is built: no document still says what happens «until D1 is merged», and the old page is not called by its name + /// (the file names of the mockups keep «attivita», as they are; the example prompt of §0 builds a screen that exists). + /// + [TestMethod] + public void NoDocumentWaitsForD1OrCallsTheDashboardAttivita() + { + var root = Root(); + var files = CurrentDocuments.Append("docs/prove-dal-vivo.md").Select(f => Path.Combine([root, .. f.Split('/')])) + .Concat(Directory.EnumerateFiles(GuideTests.GuideFolder(), "*.md")) + .ToList(); + string[] waiting = ["d1 non è unita", "d1 non è ancora unita", "finché la tappa d1 non", "nella vecchia attività", "(di attività, se d1"]; + string[] oldPage = + [ + "pagina attività", "in attività", "nella pagina attività", "(attività)", "(attività,", "anteprima di attività", + "righe gialle o rosse di attività", "«avviso non inviato» di attività", "la schermata «attività»", + ]; + var problems = new List(); + foreach (var file in files) + { + var text = GuideTests.Normalize(File.ReadAllText(file)); + var name = Path.GetRelativePath(root, file); + problems.AddRange(waiting.Where(p => text.Contains(p, StringComparison.Ordinal)).Select(p => $"{name} dice ancora «{p}»")); + problems.AddRange(oldPage.Where(p => text.Contains(p, StringComparison.Ordinal)).Select(p => $"{name} chiama ancora la Dashboard «{p}»")); + } + + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + + [TestMethod] + public void TheGuideSaysToRemoveTheOldWikiPage() + { + var text = GuideTests.Normalize(File.ReadAllText(Path.Combine(GuideTests.GuideFolder(), "Sviluppo.md"))); + StringAssert.Contains(text, "`attivita-e-arresti`"); + StringAssert.Contains(text, "va tolta"); + StringAssert.Contains(text, "rimanda a [dashboard e arresti](dashboard-e-arresti)"); + Assert.IsFalse(File.Exists(Path.Combine(GuideTests.GuideFolder(), "Attivita-e-arresti.md")), "la pagina vecchia non è più fra i sorgenti"); + } + [TestMethod] public void EveryPackageIsAllowedByTheRule() { @@ -382,6 +491,9 @@ public sealed partial class SpecificationConsistencyTests return line; } + [GeneratedRegex(@"`(?[a-z0-9-]+)`")] + private static partial Regex IconName(); + [GeneratedRegex("[^\"]+)\"")] private static partial Regex PackageVersion(); diff --git a/tests/Febe.Tests/Engine/DownloadOrderTests.cs b/tests/Febe.Tests/Engine/DownloadOrderTests.cs new file mode 100644 index 0000000..69624f8 --- /dev/null +++ b/tests/Febe.Tests/Engine/DownloadOrderTests.cs @@ -0,0 +1,323 @@ +using Febe.Core.Collection.Downloads; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; +using Febe.Tests.Engine.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Engine; + +/// +/// «Cosa scaricare prima» (spec §7.2, §6.5, tappa D1): the order of the kinds, its weight on the visits after the Giro dei +/// seguiti (on the virtual clock, with a fixed seed) and on the queue of the files. +/// +[TestClass] +public sealed class DownloadOrderTests +{ + private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); + + [TestMethod] + public void TheDefaultOrderIsStoriesHighlightsPostsReelsTagged() + { + Assert.AreEqual("storie,evidenza,post,reel,taggati", DownloadOrder.Default.ToString()); + Assert.IsTrue(DownloadOrder.Parse(null).IsDefault); + Assert.IsTrue(DownloadOrder.Parse(" ").IsDefault); + Assert.AreEqual(16, DownloadOrder.Default.Weight(DownloadKind.Stories)); + Assert.AreEqual(8, DownloadOrder.Default.Weight(DownloadKind.Highlights)); + Assert.AreEqual(4, DownloadOrder.Default.Weight(DownloadKind.Posts)); + Assert.AreEqual(2, DownloadOrder.Default.Weight(DownloadKind.Reels)); + Assert.AreEqual(1, DownloadOrder.Default.Weight(DownloadKind.Tagged)); + } + + [TestMethod] + [DataRow("taggati,post", "taggati,post,storie,evidenza,reel")] + [DataRow("POST, post ,qualcosa,reel", "post,reel,storie,evidenza,taggati")] + [DataRow("reel,taggati,post,evidenza,storie", "reel,taggati,post,evidenza,storie")] + public void AnyStoredTextGivesTheFiveKindsOnce(string stored, string expected) + { + var order = DownloadOrder.Parse(stored); + Assert.AreEqual(expected, order.ToString()); + Assert.HasCount(5, order.Kinds); + Assert.AreEqual(order.ToString(), DownloadOrder.Parse(order.ToString()).ToString()); + } + + [TestMethod] + public void EveryTaskAndEntryKindHasItsPlace() + { + Assert.IsNull(DownloadOrder.KindOf(EngineTaskKind.FollowingSweep), "il giro resta primo, nessun tipo lo pesa"); + Assert.IsNull(DownloadOrder.KindOf(EngineTaskKind.FollowingList)); + Assert.AreEqual(DownloadKind.Stories, DownloadOrder.KindOf(EngineTaskKind.AccountStories)); + Assert.AreEqual(DownloadKind.Highlights, DownloadOrder.KindOf(EngineTaskKind.HighlightCheck)); + Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EngineTaskKind.ProfileCheck)); + Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EngineTaskKind.Backfill)); + Assert.AreEqual(DownloadKind.Reels, DownloadOrder.KindOf(EngineTaskKind.ReelsCheck)); + Assert.AreEqual(DownloadKind.Tagged, DownloadOrder.KindOf(EngineTaskKind.TaggedCheck)); + Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EntryKind.ProfilePicture), "le foto del profilo vanno con i post"); + Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EntryKind.Post)); + Assert.AreEqual(DownloadKind.Reels, DownloadOrder.KindOf(EntryKind.Post, isReel: true), "un post che Febe sa essere un reel conta come reel"); + Assert.AreEqual(DownloadKind.Tagged, DownloadOrder.KindOf(EntryKind.Tagged, isReel: true), "un taggato resta un taggato"); + Assert.AreEqual(DownloadKind.Stories, DownloadOrder.KindOf(EntryKind.Story)); + Assert.AreEqual(DownloadKind.Highlights, DownloadOrder.KindOf(EntryKind.Highlight)); + } + + [TestMethod] + public void AnAccountWithoutAnOrderOfItsOwnFollowsTheGeneralOne() + { + var general = DownloadOrder.Parse("post,storie"); + var account = Make.Account("marta.demo"); + Assert.AreSame(general, DownloadOrder.For(account, general), "«Come le impostazioni generali»"); + Assert.AreSame(general, DownloadOrder.For(account with { DownloadOrder = " " }, general)); + Assert.AreSame(general, DownloadOrder.For(null, general)); + Assert.AreEqual("taggati,reel,storie,evidenza,post", DownloadOrder.For(account with { DownloadOrder = "taggati,reel" }, general).ToString(), "«Un ordine suo»"); + Assert.AreEqual(16, DownloadOrder.For(account with { DownloadOrder = "taggati,reel" }, general).Weight(DownloadKind.Tagged)); + } + + [TestMethod] + public async Task TheQueueOfTheFilesFollowsTheOrder() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var a = await db.Accounts.AddAsync(Make.Account("marta.demo")); + await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo(1), Make.Photo(2)]); + await db.Entries.AddAsync(Make.Entry(a.Id, "storia", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(2) }, [Make.Video()]); + await db.Entries.AddAsync(Make.Entry(a.Id, "taggato", Make.T0, EntryKind.Tagged), [Make.Photo()]); + + var standard = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Default)); + CollectionAssert.AreEqual(new[] { EntryKind.Story, EntryKind.Post, EntryKind.Post, EntryKind.Tagged }, standard.Select(p => p.Kind).ToArray()); + + var tagged = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Parse("taggati,post,storie"))); + CollectionAssert.AreEqual(new[] { EntryKind.Tagged, EntryKind.Post, EntryKind.Post, EntryKind.Story }, tagged.Select(p => p.Kind).ToArray()); + Assert.AreEqual(1, tagged[1].Media.Position, "dentro un tipo l'ordine di sempre"); + Assert.AreEqual(2, tagged[2].Media.Position); + } + + [TestMethod] + public async Task AReelGoesInTheQueueAsAReelAndStaysOne() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var a = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var post = (await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo()])).Stored.Entry; + var reel = (await db.Entries.AddAsync(Make.Entry(a.Id, "reel", Make.T0) with { IsReel = true }, [Make.Video()])).Stored.Entry; + var tagged = (await db.Entries.AddAsync(Make.Entry(a.Id, "taggato", Make.T0, EntryKind.Tagged) with { IsReel = true }, [Make.Video()])).Stored.Entry; + Assert.IsTrue(reel.IsReel); + Assert.IsTrue((await db.Entries.GetAsync(reel.Id))!.IsReel, "il segno del reel resta nel database (migrazione 0002)"); + Assert.IsFalse((await db.Entries.GetAsync(tagged.Id))!.IsReel, "solo un post può essere un reel"); + + var reelsFirst = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Parse("reel,taggati,post"))); + CollectionAssert.AreEqual(new[] { reel.Id, tagged.Id, post.Id }, reelsFirst.Select(p => p.Media.EntryId).ToArray()); + Assert.IsTrue(reelsFirst[0].IsReel); + var standard = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Default)); + CollectionAssert.AreEqual(new[] { post.Id, reel.Id, tagged.Id }, standard.Select(p => p.Media.EntryId).ToArray(), "post, poi reel, poi taggati"); + + // A known post marked as a reel later becomes one; a full update with a stale copy never clears the mark. + await db.Entries.MarkReelAsync(post.Id); + Assert.IsTrue((await db.Entries.GetAsync(post.Id))!.IsReel); + await db.Entries.UpdateAsync(post with { Caption = "didascalia" }); + Assert.IsTrue((await db.Entries.GetAsync(post.Id))!.IsReel, "un reel non torna un post"); + await db.Entries.MarkReelAsync(tagged.Id); + Assert.IsFalse((await db.Entries.GetAsync(tagged.Id))!.IsReel); + } + + [TestMethod] + public async Task EachAccountHasItsOwnOrderInTheQueue() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var general = await db.Accounts.AddAsync(Make.Account("marta.demo")); + var own = await db.Accounts.AddAsync(Make.Account("luca.demo") with { DownloadOrder = "taggati,post" }); + var other = await db.Accounts.AddAsync(Make.Account("pina.demo") with { DownloadOrder = "taggati,post" }); + var same = await db.Accounts.AddAsync(Make.Account("anna.demo") with { DownloadOrder = DownloadOrder.Default.ToString() }); + Assert.AreEqual("taggati,post", (await db.Accounts.GetAsync(own.Id))!.DownloadOrder); + Assert.IsNull((await db.Accounts.GetAsync(general.Id))!.DownloadOrder); + + var story = (await db.Entries.AddAsync(Make.Entry(general.Id, "s", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(3) }, [Make.Photo()])).Stored.Entry; + var post = (await db.Entries.AddAsync(Make.Entry(general.Id, "p", Make.T0), [Make.Photo()])).Stored.Entry; + var ownPost = (await db.Entries.AddAsync(Make.Entry(own.Id, "q", Make.T0), [Make.Photo()])).Stored.Entry; + var ownTagged = (await db.Entries.AddAsync(Make.Entry(own.Id, "g", Make.T0, EntryKind.Tagged), [Make.Photo()])).Stored.Entry; + var ownStory = (await db.Entries.AddAsync(Make.Entry(own.Id, "t", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(3) }, [Make.Photo()])).Stored.Entry; + var otherTagged = (await db.Entries.AddAsync(Make.Entry(other.Id, "h", Make.T0, EntryKind.Tagged), [Make.Photo()])).Stored.Entry; + + var order = await DownloadOrder.LoadQueueOrderAsync(db); + Assert.HasCount(2, order.Accounts, "an own order equal to the general one changes nothing in the queue"); + Assert.IsFalse(order.Accounts.ContainsKey(same.Id)); + + // Positions: the story of the general account 0, the tagged of the two accounts with their own order 0, their + // post 1, their story 2, the post of the general account 2. Within a position: expiring first, then discovery. + var queue = await db.Media.ListPendingDownloadsAsync(20, order); + CollectionAssert.AreEqual( + new[] { story.Id, ownTagged.Id, otherTagged.Id, ownPost.Id, ownStory.Id, post.Id }, + queue.Select(p => p.Media.EntryId).ToArray()); + } + + [TestMethod] + public void TheLongestWaitingFileHasItsShareOfTheBatch() + { + // Ten stories that keep coming and one tagged post that has waited the longest. + var stories = Enumerable.Range(1, 10).Select(i => Pending(i, EntryKind.Story)).ToList(); + var tagged = Pending(100, EntryKind.Tagged); + var ordered = stories.Append(tagged).ToList(); + var longest = new[] { tagged }.Concat(stories).ToList(); + + var batch = DownloadQueue.ComposeBatch(ordered, longest, 8, 4); + CollectionAssert.AreEqual(new long[] { 1, 2, 3, 100, 4, 5, 6, 7 }, batch.Select(p => p.Media.Id).ToArray(), "un posto su quattro va a chi aspetta da più tempo"); + + var orderOnly = DownloadQueue.ComposeBatch(ordered, longest, 11, 0); + Assert.AreEqual(100, orderOnly[^1].Media.Id, "senza la quota il taggato viene per ultimo"); + + var all = DownloadQueue.ComposeBatch(ordered, longest, 50, 4); + Assert.HasCount(11, all, "nessun file due volte, e tutti quando c'è posto"); + Assert.AreEqual(11, all.Select(p => p.Media.Id).Distinct().Count()); + + Assert.IsEmpty(DownloadQueue.ComposeBatch([], [], 8, 4)); + CollectionAssert.AreEqual(new long[] { 100 }, DownloadQueue.ComposeBatch([], [tagged], 8, 4).Select(p => p.Media.Id).ToArray()); + } + + [TestMethod] + public void NoKindWaitsForEverEvenWhenTheFirstKindNeverEnds() + { + // Every round (a day with its data budget) brings 6 new stories and downloads only 4 files: with the order + // alone the tagged posts would wait for ever; with one place in four for the longest waiting they all arrive. + var waiting = Enumerable.Range(1, 5).Select(i => Pending(1000 + i, EntryKind.Tagged, discovered: i)).ToList(); + var next = 1L; + var rounds = 0; + while (waiting.Any(p => p.Kind == EntryKind.Tagged) && rounds++ < 100) + { + for (var i = 0; i < 6; i++) + { + waiting.Add(Pending(next, EntryKind.Story, discovered: 100 + next)); + next++; + } + + var ordered = waiting.OrderBy(p => p.Kind == EntryKind.Story ? 0 : 4).ThenBy(p => p.Media.EntryId).ToList(); + var longest = waiting.OrderBy(p => p.Media.EntryId).ToList(); + foreach (var done in DownloadQueue.ComposeBatch(ordered, longest, 4, 4)) + { + waiting.Remove(done); + } + } + + Assert.IsLessThanOrEqualTo(20, rounds, $"i taggati sono arrivati in {rounds} giri"); + } + + [TestMethod] + public void TheReservedPlaceGoesToTheOldestFileOfTheQueueNotToEachKindInTurn() + { + // A new account: 40 posts of the backfill found first, then 5 tagged posts, and 7 new posts every round. The + // share is not a minimum per kind: while older posts wait, their kind takes the reserved place too, and the + // tagged posts come only once that backlog is done. What holds is that no file waits for ever. + var waiting = Enumerable.Range(1, 40).Select(i => Pending(i, EntryKind.Post)).ToList(); + waiting.AddRange(Enumerable.Range(100, 5).Select(i => Pending(i, EntryKind.Tagged))); + var next = 1000L; + var taggedByRound = new List(); + while (waiting.Any(p => p.Kind == EntryKind.Tagged) && taggedByRound.Count < 100) + { + for (var i = 0; i < 7; i++) + { + waiting.Add(Pending(next++, EntryKind.Post)); + } + + var ordered = waiting.OrderBy(p => p.Kind == EntryKind.Post ? 0 : 1).ThenBy(p => p.Media.EntryId).ToList(); + var longest = waiting.OrderBy(p => p.Media.EntryId).ToList(); + var batch = DownloadQueue.ComposeBatch(ordered, longest, 8, 8); + var oldest = longest.First(p => !batch.Take(7).Contains(p)); + Assert.AreSame(oldest, batch[7], "il posto riservato va al file che aspetta da più tempo, di qualunque tipo"); + taggedByRound.Add(batch.Count(p => p.Kind == EntryKind.Tagged)); + foreach (var done in batch) + { + waiting.Remove(done); + } + } + + CollectionAssert.AreEqual(new[] { 0, 0, 0, 0, 0 }, taggedByRound.Take(5).ToArray(), "finché i post più vecchi aspettano, i taggati non hanno un posto loro"); + Assert.AreEqual(5, taggedByRound.Sum(), "poi arrivano tutti"); + Assert.HasCount(10, taggedByRound, "uno per giro, nel posto riservato"); + } + + [TestMethod] + public async Task TheOrderWeighsTheVisitsAfterTheSweepWithoutMakingThemFixed() + { + var standard = await FirstVisitsAsync(null); + var postsFirst = await FirstVisitsAsync("post,storie"); + + Assert.IsGreaterThan(10, postsFirst.Sessions, "abbastanza sessioni con le due cose da fare"); + Assert.IsGreaterThan(standard.PostsFirst + 0.2, postsFirst.PostsFirst, $"post per primi: {postsFirst.PostsFirst:P0} contro {standard.PostsFirst:P0}"); + Assert.IsLessThan(1.0, postsFirst.PostsFirst, "l'ordine pesa ma non diventa fisso"); + Assert.IsGreaterThan(0.0, standard.PostsFirst, "anche con le storie in cima i post vengono talvolta prima"); + Assert.IsGreaterThan(0.75, postsFirst.SweepFirst, "il giro resta di norma il primo"); + Assert.AreEqual(standard.SweepFirst, postsFirst.SweepFirst, 0.15, "la composizione delle sessioni non cambia"); + } + + [TestMethod] + public async Task TheOwnOrderOfAnAccountWeighsItsVisitsAsTheGeneralOneDoes() + { + // The accounts of the posts put «post» first in an order of their own, the general order stays the default. + var standard = await FirstVisitsAsync(null); + var own = await FirstVisitsAsync(null, postsOwnOrder: "post,storie"); + + Assert.IsGreaterThan(10, own.Sessions); + Assert.IsGreaterThan(standard.PostsFirst + 0.1, own.PostsFirst, $"post per primi: {own.PostsFirst:P0} contro {standard.PostsFirst:P0}"); + Assert.IsLessThan(1.0, own.PostsFirst, "l'ordine pesa ma non diventa fisso"); + Assert.AreEqual(standard.SweepFirst, own.SweepFirst, 0.15, "il giro resta primo, la composizione non cambia"); + } + [TestMethod] + public async Task AKindWithNothingDueIsNotVisited() + { + await using var bed = await EngineTestBed.CreateAsync(Morning); + await bed.Db.Settings.SetAsync(DownloadOrder.SettingKey, "evidenza,taggati,reel,post,storie"); + await bed.AddAccountAsync("seguito.demo", followed: true); + for (var i = 0; i < 4; i++) + { + await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos); + } + + var runner = new ScriptedRunner(bed.Governor, bed.Clock); + bed.Start(runner); + await bed.RunUntilAsync(Morning.AddDays(2)); + + Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Highlight), "nessuna raccolta in evidenza da controllare"); + Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "il resto del lavoro va avanti"); + } + + private static DownloadQueueOrder Everywhere(DownloadOrder order) => DownloadQueueOrder.Everywhere(order.Kinds); + + /// A file waiting in the queue; orders the longest waiting (here: the entry key). + private static PendingDownload Pending(long id, EntryKind kind, long? discovered = null) => + new(Make.Photo() with { Id = id, EntryId = discovered ?? id }, 1, kind, Make.T0, null); + /// + /// Three days of the engine with accounts that want only their stories and accounts that want only their posts: in + /// how many sessions with both, the first of them after the sweep was a profile check. + /// + private static async Task<(double PostsFirst, double SweepFirst, int Sessions)> FirstVisitsAsync(string? order, string? postsOwnOrder = null) + { + await using var bed = await EngineTestBed.CreateAsync(Morning, seed: 11); + if (order is not null) + { + await bed.Db.Settings.SetAsync(DownloadOrder.SettingKey, order); + } + + await bed.AddAccountAsync("seguito.demo", followed: true); + for (var i = 0; i < 6; i++) + { + await bed.AddAccountAsync($"storie{i}.demo", followed: false, Frequency.High, types: ContentTypes.Stories); + var posts = await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos); + if (postsOwnOrder is not null) + { + await bed.Db.Accounts.UpdateAsync(posts with { DownloadOrder = postsOwnOrder }); + } + } + + var runner = new ScriptedRunner(bed.Governor, bed.Clock); + bed.Start(runner); + await bed.RunUntilAsync(Morning.AddDays(3)); + + var sessions = runner.Runs.GroupBy(r => r.SessionId).ToList(); + var sweepFirst = sessions.Count(g => g.First().Request.Kind == RecipeKind.FollowingSweep) / (double)sessions.Count; + var both = sessions + .Select(g => g.Where(r => r.Request.Kind is RecipeKind.AccountStories or RecipeKind.ProfileCheck).ToList()) + .Where(v => v.Any(r => r.Request.Kind == RecipeKind.AccountStories) && v.Any(r => r.Request.Kind == RecipeKind.ProfileCheck)) + .ToList(); + var postsFirst = both.Count == 0 ? 0 : both.Count(v => v[0].Request.Kind == RecipeKind.ProfileCheck) / (double)both.Count; + return (postsFirst, sweepFirst, both.Count); + } +} diff --git a/tests/Febe.Tests/Web/DashboardApiTests.cs b/tests/Febe.Tests/Web/DashboardApiTests.cs new file mode 100644 index 0000000..f143aa1 --- /dev/null +++ b/tests/Febe.Tests/Web/DashboardApiTests.cs @@ -0,0 +1,125 @@ +using System.Net; +using System.Text.Json; +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Tests.Support; +using Febe.Tests.Web.Part2Support; +using Febe.Tests.Web.Support; + +namespace Febe.Tests.Web; + +/// +/// What the Dashboard and «Cosa scaricare prima» ask the server (spec §7.2, §7.9, tappa D1): the thumbnails of a line of +/// the history, and the order of the kinds saved with the limits. +/// +[TestClass] +public sealed class DashboardApiTests +{ + [TestMethod] + public async Task ALineOfTheHistoryGetsTheEntriesItSavedNewestFirst() + { + await using var server = await Part2.StartAsync(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.prova")); + var luca = await server.Db.Accounts.AddAsync(Make.Account("luca.prova")); + var start = Make.T0.AddHours(1); + await server.Db.Entries.AddAsync(Make.Entry(marta.Id, "prima", Make.T0) with { DiscoveredAt = start.AddMinutes(-5) }, [Make.Photo()]); + for (var i = 0; i < 3; i++) + { + await server.Db.Entries.AddAsync(Make.Entry(marta.Id, $"nuovo{i}", Make.T0) with { DiscoveredAt = start.AddSeconds(10 * (i + 1)) }, [Make.Photo()]); + } + + await server.Db.Entries.AddAsync(Make.Entry(luca.Id, "altro", Make.T0) with { DiscoveredAt = start.AddSeconds(15) }, [Make.Photo()]); + + var from = Uri.EscapeDataString(start.ToString("O")); + var to = Uri.EscapeDataString(start.AddMinutes(1).ToString("O")); + var arrived = await server.GetJsonAsync($"/api/activity/arrived?account={marta.Id}&from={from}&to={to}&limit=2"); + Assert.AreEqual(3, arrived.Int("total"), "only what that recipe saved, of that account"); + var tiles = arrived.Items("tiles").ToList(); + Assert.HasCount(2, tiles, "at most what the line shows"); + Assert.IsTrue(tiles.All(t => t.Int("accountId") == marta.Id)); + + var (status, _, _) = await server.GetAsync($"/api/activity/arrived?account={marta.Id}&from={to}&to={from}"); + Assert.AreEqual(HttpStatusCode.BadRequest, status, "the end before the start"); + (status, _, _) = await server.GetAsync($"/api/activity/arrived?account=uno&from={from}&to={to}"); + Assert.AreEqual(HttpStatusCode.BadRequest, status, "an account that is no number"); + (status, _, _) = await server.GetAsync($"/api/activity/arrived?account={marta.Id}"); + Assert.AreEqual(HttpStatusCode.BadRequest, status, "no time"); + } + + [TestMethod] + public async Task ALineOfTheGiroGetsWhatArrivedOfEveryAccountButNeverTheImportedFiles() + { + // The Giro dei seguiti saves posts of many accounts: its line has no account and shows what arrived of all of + // them in its time. What an import brought in meanwhile is not something the engine downloaded. + await using var server = await Part2.StartAsync(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.prova")); + var luca = await server.Db.Accounts.AddAsync(Make.Account("luca.prova")); + var start = Make.T0.AddHours(1); + await server.Db.Entries.AddAsync(Make.Entry(marta.Id, "uno", Make.T0) with { DiscoveredAt = start.AddSeconds(5) }, [Make.Photo()]); + await server.Db.Entries.AddAsync(Make.Entry(luca.Id, "due", Make.T0) with { DiscoveredAt = start.AddSeconds(20) }, [Make.Photo()]); + await server.Db.Entries.AddAsync(Make.Entry(luca.Id, "importato", Make.T0) with { DiscoveredAt = start.AddSeconds(30), Provenance = Provenance.Imported }, [Make.Photo()]); + await server.Db.Entries.AddAsync(Make.Entry(luca.Id, "dopo", Make.T0) with { DiscoveredAt = start.AddMinutes(5) }, [Make.Photo()]); + + var from = Uri.EscapeDataString(start.ToString("O")); + var to = Uri.EscapeDataString(start.AddMinutes(1).ToString("O")); + var all = await server.GetJsonAsync($"/api/activity/arrived?from={from}&to={to}"); + Assert.AreEqual(2, all.Int("total"), "both accounts, without the imported entry and what came after"); + CollectionAssert.AreEqual(new long[] { luca.Id, marta.Id }, all.Items("tiles").Select(t => (long)t.Int("accountId")).ToArray(), "newest first"); + + var one = await server.GetJsonAsync($"/api/activity/arrived?account={luca.Id}&from={from}&to={to}"); + Assert.AreEqual(1, one.Int("total"), "a line of one account: never the imported entry"); + } + + [TestMethod] + public async Task TheOrderOfTheKindsIsSavedWithTheLimitsAndKeptWhenNotSent() + { + await using var server = await Part2.StartAsync(); + var limits = await server.GetJsonAsync("/api/settings/limits"); + CollectionAssert.AreEqual(new[] { "storie", "evidenza", "post", "reel", "taggati" }, limits.Items("downloadOrder").Select(k => k.GetString()).ToArray()); + + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", + new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 }, downloadOrder = new[] { "taggati", "post" } }); + Assert.AreEqual(HttpStatusCode.OK, status); + CollectionAssert.AreEqual(new[] { "taggati", "post", "storie", "evidenza", "reel" }, saved.Items("downloadOrder").Select(k => k.GetString()).ToArray()); + Assert.AreEqual("taggati,post,storie,evidenza,reel", await server.Db.Settings.GetAsync(DownloadOrder.SettingKey)); + + (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", + new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 } }); + Assert.AreEqual(HttpStatusCode.OK, status); + Assert.AreEqual("taggati", saved.Items("downloadOrder").First().GetString(), "not sent: the stored order stays"); + + await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", + new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 }, downloadOrder = DownloadOrder.Default.Kinds.Select(DownloadOrder.NameOf).ToArray() }); + Assert.IsNull(await server.Db.Settings.GetAsync(DownloadOrder.SettingKey), "the default order is no stored value"); + } + + [TestMethod] + public async Task AnAccountFollowsTheGeneralOrderOrHasOneOfItsOwn() + { + await using var server = await Part2.StartAsync(); + await server.Db.Settings.SetAsync(DownloadOrder.SettingKey, "post,storie"); + var account = await server.Db.Accounts.AddAsync(Make.Account("marta.prova")); + + var detail = await server.GetJsonAsync($"/api/accounts/{account.Id}"); + Assert.AreEqual(JsonValueKind.Null, detail.GetProperty("settings").GetProperty("downloadOrder").ValueKind, "«Come le impostazioni generali»"); + CollectionAssert.AreEqual(new[] { "post", "storie", "evidenza", "reel", "taggati" }, detail.Items("generalDownloadOrder").Select(k => k.GetString()).ToArray()); + + // «Un ordine suo»: saved with the other settings, completed to the five kinds. + var settings = JsonSerializer.Deserialize>(detail.GetProperty("settings").GetRawText())!; + settings["downloadOrder"] = JsonSerializer.SerializeToElement(new[] { "reel", "taggati" }); + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings); + Assert.AreEqual(HttpStatusCode.OK, status); + CollectionAssert.AreEqual(new[] { "reel", "taggati", "storie", "evidenza", "post" }, saved.GetProperty("settings").Items("downloadOrder").Select(k => k.GetString()).ToArray()); + Assert.AreEqual("reel,taggati,storie,evidenza,post", (await server.Db.Accounts.GetAsync(account.Id))!.DownloadOrder); + + // «Tieni aggiornato» from the table keeps it; back to «Come le impostazioni generali» with null. + (status, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{account.Id}/keep-updated", new { value = false }); + Assert.AreEqual(HttpStatusCode.OK, status); + Assert.AreEqual("reel,taggati,storie,evidenza,post", (await server.Db.Accounts.GetAsync(account.Id))!.DownloadOrder); + settings = JsonSerializer.Deserialize>((await server.GetJsonAsync($"/api/accounts/{account.Id}")).GetProperty("settings").GetRawText())!; + settings["downloadOrder"] = JsonSerializer.SerializeToElement(null); + (status, _) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{account.Id}/settings", settings); + Assert.AreEqual(HttpStatusCode.OK, status); + Assert.IsNull((await server.Db.Accounts.GetAsync(account.Id))!.DownloadOrder); + } +} diff --git a/tests/Febe.Tests/Web/DashboardInterfaceTests.cs b/tests/Febe.Tests/Web/DashboardInterfaceTests.cs new file mode 100644 index 0000000..25574ff --- /dev/null +++ b/tests/Febe.Tests/Web/DashboardInterfaceTests.cs @@ -0,0 +1,87 @@ +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The Dashboard in a real browser, on the demo (spec §7.9, §10.3, tappa D1): the first item of the sidebar with its own +/// icon, the preview of the browser always visible at the top, the thumbnails of the history and the enlarged preview +/// they open (arrows, Esc, «Apri l'account», «Apri nella Libreria»), the compressed page at 860 px (preview beside the +/// status, history in the first screen) and one column on the phone. Chromium only (CI). +/// +[TestClass] +public sealed class DashboardInterfaceTests +{ + [TestMethod] + public async Task TheHistoryThumbnailsOpenALightPreviewThatTheArrowsWalkAndEscCloses() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("dashboard-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/?scena=sessione")); + await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .dashboard .cruscotto .anteprima img:not([hidden])') !== null", "Dashboard con l'anteprima del browser"); + Assert.AreEqual("#i-layout-dashboard", (await ui.EvalAsync("document.querySelector('.nav a[data-nav=dashboard] use').getAttribute('href')")).GetString(), "la sua icona"); + Assert.AreEqual("dashboard", (await ui.EvalAsync("document.querySelector('.nav a').dataset.nav")).GetString(), "prima voce"); + Assert.IsTrue((await ui.EvalAsync("(() => { const p = document.querySelector('.cruscotto .anteprima').getBoundingClientRect(); return p.top < 200 && p.bottom <= innerHeight; })()")).GetBoolean(), "l'anteprima sta in alto, intera, senza scorrere " + ui.Report()); + + // The thumbnails of a line come when it is in view; a click opens the light dialog, not the full viewer. + await ui.EvalAsync("document.querySelector('.storia').scrollIntoView()"); + // A line with two thumbnails at least, so that the arrows have somewhere to go. + const string Line = "[...document.querySelectorAll('.storia .miniature')].find((m) => m.querySelectorAll('.miniatura').length >= 2)"; + await ui.WaitAsync($"({Line}) !== undefined", "miniature della cronologia"); + await ui.EvalAsync($"({Line}).querySelector('.miniatura').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.anteprima-cronologia .anteprima-palco img, .dialogo.anteprima-cronologia .anteprima-palco video, .dialogo.anteprima-cronologia .anteprima-neutra') !== null", "anteprima ingrandita"); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis') === null")).GetBoolean(), "non il visualizzatore a tutta finestra"); + var first = (await ui.EvalAsync("document.querySelector('.anteprima-cronologia footer .dati').textContent")).GetString(); + var dida = (await ui.EvalAsync("document.querySelector('.anteprima-cronologia .anteprima-dida').textContent")).GetString(); + StringAssert.StartsWith(dida, "@"); + StringAssert.StartsWith((await ui.EvalAsync("new URL(document.querySelector('.anteprima-cronologia footer a.btn').href).pathname")).GetString(), "/account/", "«Apri l'account»"); + + // The arrows walk the files of the line also with the focus on a button of the footer. + await ui.EvalAsync("document.querySelector('.anteprima-cronologia footer button.primo').focus()"); + await ui.EvalAsync("document.activeElement.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))"); + await ui.WaitAsync($"document.querySelector('.anteprima-cronologia .anteprima-dida').textContent !== {System.Text.Json.JsonSerializer.Serialize(dida)} || document.querySelector('.anteprima-cronologia footer .dati').textContent !== {System.Text.Json.JsonSerializer.Serialize(first)}", "la freccia passa al file seguente"); + + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))"); + await ui.WaitAsync("document.querySelector('.anteprima-cronologia') === null", "Esc chiude"); + Assert.AreEqual("/dashboard", (await ui.EvalAsync("location.pathname")).GetString(), "senza lasciare la pagina"); + } + + [TestMethod] + public async Task AtEightHundredSixtyPixelsThePreviewStaysBesideTheStatusAndTheHistoryStartsInTheFirstScreen() + { + await using var ui = await UiBrowser.StartAsync(860, 900); + using var temp = new TempFolder("dashboard-stretta"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/dashboard?scena=sessione&tema=scuro")); + await ui.WaitAsync("document.querySelector('main .dashboard .cruscotto .anteprima') !== null && document.querySelector('.storia .storia-righe li') !== null", "Dashboard stretta"); + // A compressed page (spec §7.9): the preview beside the status and the budgets, with its proportions, not across + // the whole width; the first line of the history inside the first screen, without scrolling. + Assert.IsTrue((await ui.EvalAsync("(() => { const a = document.querySelector('.cruscotto .anteprima').getBoundingClientRect(); const s = document.querySelector('.cruscotto-lato').getBoundingClientRect(); return a.right <= s.left && a.top < s.bottom; })()")).GetBoolean(), "l'anteprima accanto allo stato e ai tetti " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync("(() => { const q = document.querySelector('.cruscotto .anteprima .quadro').getBoundingClientRect(); return q.width <= 420 && Math.abs(q.width / q.height - 420 / 236) < 0.05; })()")).GetBoolean(), "l'anteprima tiene le sue proporzioni, al più 420 px"); + Assert.AreEqual(0, (await ui.EvalAsync("scrollY")).GetDouble(), "la pagina parte dall'alto"); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('.storia .storia-righe li').getBoundingClientRect().bottom <= innerHeight")).GetBoolean(), "la prima riga della cronologia nel primo schermo " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync("(() => { const h = document.querySelector('.storia').getBoundingClientRect(); const q = document.querySelector('.coda').getBoundingClientRect(); return h.bottom <= q.top + 1; })()")).GetBoolean(), "cronologia e coda in una colonna"); + // «Mostra tutta (N)» of the queue keeps the inner margin of the rows. + Assert.IsTrue((await ui.EvalAsync("(() => { const b = document.querySelector('.coda .piede-elenco'); return b !== null && parseFloat(getComputedStyle(b).paddingLeft) >= 12 && parseFloat(getComputedStyle(b).paddingBottom) >= 8; })()")).GetBoolean(), "«Mostra tutta» con il margine interno"); + // The sessions of the strip are bars of nearly the whole height (mockup 06), not dots. + Assert.IsTrue((await ui.EvalAsync("(() => { const strip = document.querySelector('.oggi-basso .striscia').getBoundingClientRect(); const bars = [...document.querySelectorAll('.oggi-basso .striscia .sess')]; return bars.length > 0 && bars.every((b) => b.getBoundingClientRect().height >= strip.height * 0.6); })()")).GetBoolean(), "sessioni a barre alte"); + Assert.IsTrue((await ui.EvalAsync("document.documentElement.scrollWidth <= innerWidth")).GetBoolean(), "nessuno scorrimento orizzontale"); + } + + [TestMethod] + public async Task OnThePhoneTheDashboardIsOneColumnWithThePreviewOnTop() + { + await using var ui = await UiBrowser.StartAsync(390, 844); + using var temp = new TempFolder("dashboard-telefono"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/dashboard?scena=sessione")); + await ui.WaitAsync("document.querySelector('main .dashboard .cruscotto .anteprima') !== null && document.querySelector('.storia') !== null", "Dashboard al telefono"); + Assert.IsTrue((await ui.EvalAsync("(() => { const a = document.querySelector('.cruscotto .anteprima').getBoundingClientRect(); const s = document.querySelector('.cruscotto-lato').getBoundingClientRect(); return a.bottom <= s.top + 1; })()")).GetBoolean(), "l'anteprima sopra lo stato e i tetti"); + Assert.IsTrue((await ui.EvalAsync("document.documentElement.scrollWidth <= innerWidth")).GetBoolean(), "nessuno scorrimento orizzontale"); + } +} diff --git a/tests/Febe.Tests/Web/DemoTests.cs b/tests/Febe.Tests/Web/DemoTests.cs index 62f6244..15e75ac 100644 --- a/tests/Febe.Tests/Web/DemoTests.cs +++ b/tests/Febe.Tests/Web/DemoTests.cs @@ -163,6 +163,34 @@ public sealed class DemoTests Assert.IsGreaterThan(0, videos, "some entries are videos"); } + [TestMethod] + public async Task TutteLeFotoShowsEveryFileOfTheDemoSeriesAlsoTheirVideos() + { + // «Tutte le foto» (spec §4.6) has something to show in the demo: posts of many photos, and series with a video. + var grouped = await GetAsync("/api/library/days"); + var files = await GetAsync("/api/library/days?mode=files"); + Assert.AreEqual(grouped.Int("entries"), files.Int("entries")); + Assert.IsGreaterThan(grouped.Int("entries"), files.Int("files"), "more files than entries"); + Assert.AreEqual(files.Int("files"), files.Items("days").Sum(d => d.Int("count"))); + + var seriesVideos = 0; + string? cursor = null; + var pages = 0; + do + { + var page = await GetAsync("/api/library?mode=files&kind=videos&limit=600" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor))); + seriesVideos += page.Items("tiles").Count(t => t.Int("files") >= 3 && t.Int("position") == 2); + cursor = page.GetProperty("older").ValueKind == JsonValueKind.String ? page.Str("older") : null; + pages++; + } + while (cursor is not null && pages < 100); + + var first = await GetAsync("/api/library?mode=files&limit=600"); + var series = first.Items("tiles").Count(t => t.Int("files") > 1 && t.Int("position") == 1); + Assert.IsGreaterThan(0, series, "posts of several photos near the top"); + Assert.IsGreaterThan(0, seriesVideos, "some series have a video in second place"); + } + [TestMethod] public async Task EntriesAreDiscoveredAfterPublicationAndTheirFilesLiveInTheTemporaryFolder() { diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs index 6f2453a..83eb933 100644 --- a/tests/Febe.Tests/Web/InterfaceTests.cs +++ b/tests/Febe.Tests/Web/InterfaceTests.cs @@ -114,6 +114,24 @@ public sealed class InterfaceTests await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito chiudendo la scheda"); } + [TestMethod] + public async Task TheRootAndTheOldAttivitaOpenTheDashboardFirstInTheSidebar() + { + // Spec §7.9, §10.2 (tappa D1): the Dashboard is the start page and the first item of the sidebar. + var connection = new RecordingConnection { Status = Connected }; + await using var server = await DockerAsync(connection, new FakeRemoteViewHost()); + await using var ui = await UiBrowser.StartAsync(); + await ui.OpenAsync(new Uri(server.Address, "/")); + await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .dashboard .cruscotto .anteprima') !== null", "Dashboard da /"); + Assert.AreEqual("dashboard", (await ui.EvalAsync("document.querySelector('.nav a').dataset.nav")).GetString(), "prima voce della barra laterale"); + Assert.AreEqual("/dashboard", (await ui.EvalAsync("new URL(document.querySelector('a.stato').href).pathname")).GetString(), "il riquadro di stato rimanda alla Dashboard"); + + await ui.NavigateAsync("/libreria"); + await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await ui.NavigateAsync("/attivita"); + await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .dashboard') !== null", "Dashboard dal vecchio /attivita"); + } + [TestMethod] public async Task ABrowserPageLeftWhileLoadingNeverTakesTheBrowser() { @@ -153,7 +171,7 @@ public sealed class InterfaceTests await ui.OpenAsync(new Uri(server.Address, "/browser")); await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso"); await ui.EvalAsync("document.querySelector('.salva .btn.primo').click()"); - await ui.WaitAsync("location.pathname === '/attivita'", "Attività dopo «Ho finito»"); + await ui.WaitAsync("location.pathname === '/dashboard'", "Dashboard dopo «Ho finito»"); await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); @@ -632,7 +650,7 @@ public sealed class InterfaceTests // Attività waits for its alerts and Alberto goes back to the Libreria before they come. Issue #8: going back // after a fixed 200 ms, a slow machine had not even loaded the page yet, and the alerts were never asked. await ui.EvalAsync("window.__hold('/api/alerts')"); - await ui.NavigateAsync("/attivita"); + await ui.NavigateAsync("/dashboard"); await ui.WaitAsync("window.__started['/api/alerts'] >= 1", "Attività in attesa dei suoi avvisi"); await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)"); @@ -654,7 +672,7 @@ public sealed class InterfaceTests CollectionAssert.AreEqual(new[] { "GET /api/alerts" }, await ui.AskedAsync("/api/alerts"), "Attività, left, no longer listens to the library"); // The page that stays open still works as usual: its minute timer runs, and a change of the library reloads it. - await ui.NavigateAsync("/attivita"); + await ui.NavigateAsync("/dashboard"); await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta"); await ui.EvalAsync("window.__libraryChanged()"); await ui.WaitAsync("window.__asked.filter((r) => r.includes('/api/alerts')).length >= 3", "Attività aggiornata dopo la modifica"); diff --git a/tests/Febe.Tests/Web/LibraryFilesApiTests.cs b/tests/Febe.Tests/Web/LibraryFilesApiTests.cs new file mode 100644 index 0000000..e3ba78c --- /dev/null +++ b/tests/Febe.Tests/Web/LibraryFilesApiTests.cs @@ -0,0 +1,120 @@ +using System.Net; +using System.Text.Json; +using Febe.Core.Domain; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; + +namespace Febe.Tests.Web; + +/// +/// «Tutte le foto» through the API (spec §4.6): mode=files on the days and on the windows, one tile per file +/// with its position, cursors that go on inside a post, day rows that count files and totals that say both. +/// +[TestClass] +public sealed class LibraryFilesApiTests +{ + [TestMethod] + public async Task WindowsOfFilesWalkEveryFileOnceAndTheDaysCountThem() + { + await using var server = await WebTestServer.StartAsync(); + var (entries, files) = await FillAsync(server); + + var days = await server.GetJsonAsync("/api/library/days?mode=files"); + Assert.AreEqual(entries, days.Int("entries"), "the totals still count the entries"); + Assert.AreEqual(files, days.Int("files")); + Assert.AreEqual(files, days.Items("days").Sum(d => d.Int("count")), "the day rows count the files"); + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/library/days")).GetProperty("files").ValueKind, "grouped: no file total"); + + var seen = new List<(long Ms, long Id, int Position, long Media)>(); + string? cursor = null; + var pages = 0; + do + { + var page = await server.GetJsonAsync("/api/library?mode=files&limit=4" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor))); + foreach (var tile in page.Items("tiles")) + { + seen.Add((tile.Long("publishedAt"), tile.Long("id"), tile.Int("position"), tile.GetProperty("cover").Long("mediaId"))); + } + + cursor = page.GetProperty("older").ValueKind == JsonValueKind.Null ? null : page.Str("older"); + pages++; + } + while (cursor is not null && pages < 50); + + Assert.HasCount(files, seen); + Assert.HasCount(files, seen.Select(s => s.Media).Distinct(), "every file once"); + Assert.HasCount(entries, seen.Select(s => s.Id).Distinct()); + for (var i = 1; i < seen.Count; i++) + { + var (a, b) = (seen[i - 1], seen[i]); + Assert.IsTrue(b.Ms < a.Ms || (b.Ms == a.Ms && (b.Id < a.Id || (b.Id == a.Id && b.Position > a.Position))), "entries newest first, each by position"); + } + + // The cursor of a day starts at that day, in files. + foreach (var day in days.Items("days").Take(3)) + { + var page = await server.GetJsonAsync($"/api/library?mode=files&limit={day.Int("count")}&cursor={Uri.EscapeDataString(day.Str("cursor"))}"); + Assert.IsTrue(page.Items("tiles").All(t => t.Str("day") == day.Str("day")), day.Str("day")); + Assert.AreEqual(day.Int("count"), page.Items("tiles").Count()); + } + + // From inside a carousel: the next file of the same post, and back up. + var inside = seen.FindIndex(s => s.Position == 2); + var at = seen[inside]; + var next = await server.GetJsonAsync($"/api/library?mode=files&limit=1&cursor={at.Ms}.{at.Id}.{at.Position}"); + Assert.AreEqual(seen[inside + 1].Media, next.Items("tiles").Single().GetProperty("cover").Long("mediaId")); + var back = await server.GetJsonAsync($"/api/library?mode=files&limit=2&direction=newer&cursor={at.Ms}.{at.Id}.{at.Position}"); + CollectionAssert.AreEqual(seen.Skip(inside - 2).Take(2).Select(s => s.Media).ToList(), back.Items("tiles").Select(t => t.GetProperty("cover").Long("mediaId")).ToList()); + + // A file tile says the files of its post; the grouped tiles have no position. + var carousel = seen.First(s => s.Position == 3); + var tiles = (await server.GetJsonAsync("/api/library?mode=files&limit=200")).Items("tiles").Where(t => t.Long("id") == carousel.Id).ToList(); + Assert.IsTrue(tiles.All(t => t.Int("files") == tiles.Count)); + Assert.IsTrue((await server.GetJsonAsync("/api/library?limit=200")).Items("tiles").All(t => t.GetProperty("position").ValueKind == JsonValueKind.Null)); + } + + [TestMethod] + public async Task FiltersWorkTheSameAndBadValuesAreRefused() + { + await using var server = await WebTestServer.StartAsync(); + await FillAsync(server); + + // «Video» shows only the video files, «Foto» only the photos. + var videos = await server.GetJsonAsync("/api/library?mode=files&kind=videos&limit=200"); + Assert.IsTrue(videos.Items("tiles").All(t => t.GetProperty("cover").Str("kind") == "video")); + Assert.AreEqual(videos.Items("tiles").Count(), (await server.GetJsonAsync("/api/library/days?mode=files&kind=videos")).Int("files")); + var photos = await server.GetJsonAsync("/api/library?mode=files&kind=photos&limit=200"); + Assert.IsTrue(photos.Items("tiles").All(t => t.GetProperty("cover").Str("kind") == "photo")); + Assert.AreEqual(4, (await server.GetJsonAsync("/api/library/days?mode=files&kind=stories")).Int("files")); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?mode=gatti")).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library/days?mode=tutte")).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?mode=files&cursor=1.2.x")).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?mode=files&cursor=1.2.-1")).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, "/api/library?cursor=99999999999999999.2")).Status, "a time outside the calendar"); + } + + /// Ten posts of one to four files (the third of a series is a video) and four stories: entries and files. + private static async Task<(int Entries, int Files)> FillAsync(WebTestServer server) + { + var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var files = 0; + for (var i = 0; i < 10; i++) + { + var count = (i % 4) + 1; + var media = Enumerable.Range(1, count) + .Select(p => Make.Stored(p == 3 ? Make.Video(p) : Make.Photo(p), Make.Sha((i * 10) + p), $"p/{i}_{p}.jpg")) + .ToList(); + await server.Db.Entries.AddAsync(Make.Entry(account.Id, $"p{i}", Make.T0 - TimeSpan.FromHours(9 * i)), media); + files += count; + } + + for (var i = 0; i < 4; i++) + { + await server.Db.Entries.AddAsync(Make.Entry(account.Id, $"s{i}", Make.T0 - TimeSpan.FromHours((13 * i) + 2), EntryKind.Story), [Make.Stored(Make.Photo(), Make.Sha(500 + i), $"s/{i}.jpg")]); + files++; + } + + return (14, files); + } +} diff --git a/tests/Febe.Tests/Web/LibraryModeInterfaceTests.cs b/tests/Febe.Tests/Web/LibraryModeInterfaceTests.cs new file mode 100644 index 0000000..f6144f5 --- /dev/null +++ b/tests/Febe.Tests/Web/LibraryModeInterfaceTests.cs @@ -0,0 +1,153 @@ +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// «Raggruppa i post» / «Tutte le foto» in a real browser, on the demo (spec §4.6, tappa D1): the switch of the tools +/// row, the file tiles with their place («2/4»), the day rows in files, the viewer that opens on the file and counts +/// files, the selection of files that acts on their entries, the choice remembered per page (Libreria apart from the +/// account views) and grouped when the browser keeps nothing. Chromium only (CI). +/// +[TestClass] +public sealed class LibraryModeInterfaceTests +{ + private const string Switch = "document.querySelector('.strumenti .modo-mosaico')"; + private const string Mode = Switch + ".querySelector('[aria-checked=true]').dataset.value"; + + /// The viewer shows a video: the player, or (the demo has no video files on disk) the cover of a missing video. + private const string ShowsAVideo = "(document.querySelector('.vis .scena video') !== null || /video/i.test(document.querySelector('.vis .scena .mancante')?.textContent || ''))"; + + /// + /// Walks «Video» in «Tutte le foto» through the API, newest first, to the first video that is the second file of a + /// series whose first file is no tile there: «dal=…&al=…», from its day to the day of the tile before it, or "". + /// + private const string FindAVideoInSecondPlace = """ + (async () => { + let cursor = null; + const list = []; + for (let page = 0; page < 60; page++) { + const answer = await (await fetch('/api/library?mode=files&kind=videos&limit=500' + (cursor ? '&cursor=' + cursor : ''))).json(); + list.push(...answer.tiles); + const at = list.findIndex((t, i) => i > 0 && t.position === 2 && t.files > 1 && t.cover && t.cover.kind === 'video' + && !list.some((o) => o.id === t.id && o.position === 1)); + if (at > 0) return 'dal=' + list[at].day + '&al=' + list[at - 1].day; + if (!answer.older) return ''; + cursor = answer.older; + } + return ''; + })() + """; + + [TestMethod] + public async Task TutteLeFotoShowsTheFilesOpensTheViewerOnTheFileAndIsRememberedPerPage() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("modo-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria con l'interruttore"); + Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "predefinito «Raggruppa i post» " + ui.Report()); + Assert.AreEqual(2, (await ui.EvalAsync($"{Switch}.querySelectorAll('[role=radio]').length")).GetInt32()); + var entries = (await ui.EvalAsync("document.querySelector('.quanti')?.textContent || ''")).GetString(); + StringAssert.Contains(entries, "elementi"); + + // «Tutte le foto»: tiles of single files, those of a series with their place. + await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()"); + await ui.WaitAsync("[...document.querySelectorAll('.mosaico .tess .segno span')].some((s) => /^\\d+\\/\\d+$/.test(s.textContent))", "tessere con «2/4»"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.mosaico .giorno span')?.textContent || ''")).GetString(), "file", "la riga del giorno conta i file"); + await ui.WaitAsync("/ file in .* elementi di /.test(document.querySelector('.quanti')?.textContent || '')", "«61.034 file in 48.212 elementi di 38 account»"); + + // The viewer opens on the second file of a series and counts files. + const string Second = "[...document.querySelectorAll('.mosaico .tess')].find((t) => /^2\\/\\d+$/.test(t.querySelector('.segno span')?.textContent || ''))"; + await ui.WaitAsync($"({Second}) !== undefined", "un secondo file di una serie"); + await ui.EvalAsync($"({Second}).click()"); + await ui.WaitAsync("document.querySelector('.vis .serie button[aria-current=true]') !== null", "visualizzatore con la serie"); + Assert.AreEqual(1, (await ui.EvalAsync("[...document.querySelectorAll('.vis .serie button')].findIndex((b) => b.getAttribute('aria-current') === 'true')")).GetInt32(), "aperto sul file della tessera"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.vis .dove').textContent")).GetString(), "file", "«Libreria, file 12 di …»"); + var where = (await ui.EvalAsync("document.querySelector('.vis .dove').textContent")).GetString(); + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))"); + await ui.WaitAsync($"document.querySelector('.vis .dove').textContent !== {System.Text.Json.JsonSerializer.Serialize(where)}", "la freccia va al file seguente"); + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))"); + await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude"); + + // Selection of files: two files of one post are one entry for «Elimina». + await ui.EvalAsync("[...document.querySelectorAll('.strumenti .btn')].find((b) => b.textContent.includes('Seleziona')).click()"); + await ui.EvalAsync($"(() => {{ const t = {Second}; const entry = t.dataset.entry; const all = [...document.querySelectorAll(`.mosaico .tess[data-entry='${{entry}}']`)]; all.slice(0, 2).forEach((x) => x.click()); return all.length; }})()"); + await ui.WaitAsync("/2 file scelti, di 1 elemento/.test(document.querySelector('.salva .nota')?.textContent || '')", "«2 file scelti, di 1 elemento»"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.salva .btn.pericolo').textContent")).GetString(), "Elimina 1 elemento"); + + // Remembered for the Libreria, not for the account views. + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync($"{Switch} !== null", "Libreria di nuovo"); + Assert.AreEqual("files", (await ui.EvalAsync(Mode)).GetString(), "la Libreria ricorda «Tutte le foto»"); + await ui.OpenAsync(new Uri(demo.Address, "/account")); + await ui.WaitAsync("document.querySelector('a[href^=\"/account/\"]') !== null", "elenco degli account"); + await ui.EvalAsync("document.querySelector('a[href^=\"/account/\"]').click()"); + await ui.WaitAsync($"location.pathname.startsWith('/account/') && {Switch} !== null", "scheda account con l'interruttore"); + Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "le viste degli account hanno la loro scelta"); + } + + [TestMethod] + public async Task UnderVideoTheArrowsFollowTheTilesAndTheChosenVoiceChangesNothing() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("modo-video-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // In the demo the videos that are the second file of a post (the first a photo, no tile under «Video») are few and + // far back in time: the API finds the first one, and the Libreria opens on its days, from it to the tile before. + await ui.OpenAsync(new Uri(demo.Address, "/libreria?tipo=video")); + await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria con «Video»"); + var days = (await ui.EvalAsync(FindAVideoInSecondPlace)).GetString(); + Assert.IsFalse(string.IsNullOrEmpty(days), "la demo ha un video in seconda posizione dopo una foto"); + await ui.OpenAsync(new Uri(demo.Address, "/libreria?tipo=video&" + days)); + await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria con «Video» in quei giorni"); + await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()"); + + // That video, not the first tile. A video tile has two marks, its length and its place: the place is the one. + const string Second = "[...document.querySelectorAll('.mosaico .tess')].slice(1).find((t) => [...t.querySelectorAll('.segno span')].some((s) => /^2\\/\\d+$/.test(s.textContent.trim())))"; + await ui.WaitAsync($"({Second}) !== undefined", "un video in seconda posizione"); + + // Clicking the voice already chosen keeps the mosaic, its place and the selection. + await ui.EvalAsync("document.querySelector('.mosaico').dataset.prova = 'stesso'"); + await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()"); + Assert.AreEqual("stesso", (await ui.EvalAsync("document.querySelector('.mosaico')?.dataset.prova || ''")).GetString(), "«Tutte le foto» di nuovo non ridisegna il mosaico"); + + await ui.EvalAsync($"({Second}).click()"); + await ui.WaitAsync($"{ShowsAVideo} && /file/.test(document.querySelector('.vis .dove').textContent)", "visualizzatore sul video"); + const string Index = "Number((document.querySelector('.vis .dove').textContent.match(/file ([\\d.]+)/) || [])[1]?.replace(/\\./g, '') || 0)"; + var at = (await ui.EvalAsync(Index)).GetInt32(); + Assert.IsGreaterThan(1, at, ui.Report()); + + // Left: the photo before it is not a tile, so the viewer goes to the tile before, a video of another post. + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true }))"); + await ui.WaitAsync($"{Index} === {at - 1}", "la freccia va alla tessera precedente"); + await ui.WaitAsync(ShowsAVideo, "di nuovo un video, mai la foto filtrata"); + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))"); + await ui.WaitAsync($"{Index} === {at}", "e torna"); + Assert.IsTrue((await ui.EvalAsync(ShowsAVideo)).GetBoolean(), "un video, all'andata e al ritorno"); + } + + [TestMethod] + public async Task WithoutTheBrowserStorageTheMosaicIsGrouped() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("modo-senza-memoria"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await ui.AddInitScriptAsync("Object.defineProperty(window, 'localStorage', { configurable: true, get() { throw new DOMException('bloccato', 'SecurityError'); } });"); + + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync($"{Switch} !== null && document.querySelector('.mosaico .tess') !== null", "Libreria senza memoria del browser"); + Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), ui.Report()); + + // The choice still works for the page that is open. + await ui.EvalAsync($"{Switch}.querySelector('[data-value=files]').click()"); + await ui.WaitAsync("[...document.querySelectorAll('.mosaico .tess .segno span')].some((s) => /^\\d+\\/\\d+$/.test(s.textContent))", "«Tutte le foto» anche senza memoria"); + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync($"{Switch} !== null", "Libreria riaperta"); + Assert.AreEqual("grouped", (await ui.EvalAsync(Mode)).GetString(), "nulla da ricordare: di nuovo «Raggruppa i post»"); + } +} diff --git a/tests/Febe.Tests/Web/LoginSecurityTests.cs b/tests/Febe.Tests/Web/LoginSecurityTests.cs index adba142..075549b 100644 --- a/tests/Febe.Tests/Web/LoginSecurityTests.cs +++ b/tests/Febe.Tests/Web/LoginSecurityTests.cs @@ -104,11 +104,17 @@ public sealed class LoginSecurityTests StringAssert.Contains(accesso, "location.href = returnAddress("); Assert.DoesNotContain("startsWith('//')", accesso, "the old check let «/\\host» through"); + // Every missing or unsafe value goes to the page the module names, the Dashboard since stage D1. Read here, before + // the browser, so that the expected cases cannot drift from the module even where Chromium is missing. + const string home = "/dashboard"; + var module = File.ReadAllText(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "core", "return-path.js")); + StringAssert.Contains(module, $"export const DEFAULT_PAGE = '{home}';", "the page after the login when «torna» is missing or unsafe"); + const string origin = "http://tower:8480"; List<(string? Value, string Expected)> cases = [ - .. Foreign.Select(v => ((string?)v, origin + "/libreria")), - (null, origin + "/libreria"), + .. Foreign.Select(v => ((string?)v, origin + home)), + (null, origin + home), ("/account/12", origin + "/account/12"), ("/libreria?tipo=foto#x", origin + "/libreria?tipo=foto#x"), ("/%5Cnon-un-sito", origin + "/%5Cnon-un-sito"), diff --git a/tools/Febe.Schermate/Shots.cs b/tools/Febe.Schermate/Shots.cs index 6a7e919..9648a6e 100644 --- a/tools/Febe.Schermate/Shots.cs +++ b/tools/Febe.Schermate/Shots.cs @@ -13,6 +13,7 @@ internal static class Shots public static IReadOnlyList All { get; } = [ new("/libreria?tema=chiaro", "01-libreria.png", Step: "puntatore.js"), + new("/libreria?tema=chiaro", "01-libreria-tutte-le-foto.png", Step: "tutte-le-foto.js"), new("/libreria?tema=chiaro", "02-visualizzatore.png", Step: "visualizzatore.js"), new("/account?tema=chiaro", "03-account.png"), new("/account?tema=chiaro", "03-account-telefono.png", 390, 844), @@ -24,14 +25,15 @@ internal static class Shots new("/libreria?tema=chiaro", "14-telefono.png", 390, 844), new("/account/2/cronologia?tema=chiaro", "account-cronologia.png"), - // Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione. - new("/attivita?scena=fermo&tema=scuro", "11-attivita-fermo-tema-scuro.png"), - new("/attivita?scena=sessione&tema=chiaro", "06-attivita.png"), - new("/attivita?scena=sessione&tema=chiaro", "06-attivita-tutti-i-tetti.png", Step: "tutti-tetti.js"), - new("/attivita?scena=sessione&tema=chiaro", "14-attivita-finestra-stretta.png", 860, 900), - new("/attivita?scena=sessione&tema=chiaro", "14-attivita-telefono.png", 390, 844), - new("/attivita?scena=normale&tema=chiaro", "14-attivita-finestra-stretta-normale.png", 860, 900), - new("/attivita?scena=normale&tema=chiaro", "14-attivita-telefono-normale.png", 390, 844), + // Part 2: Dashboard (once Attività: the files keep the names of mockups 06, 11 and 14), Impostazioni, Collegamento, + // Importa, doppioni, primo avvio, errore di configurazione. + new("/dashboard?scena=fermo&tema=scuro", "11-attivita-fermo-tema-scuro.png"), + new("/dashboard?scena=sessione&tema=chiaro", "06-attivita.png"), + new("/dashboard?scena=sessione&tema=chiaro", "06-attivita-tutti-i-tetti.png", Step: "tutti-tetti.js"), + new("/dashboard?scena=sessione&tema=chiaro", "14-attivita-finestra-stretta.png", 860, 900), + new("/dashboard?scena=sessione&tema=chiaro", "14-attivita-telefono.png", 390, 844), + new("/dashboard?scena=normale&tema=chiaro", "14-attivita-finestra-stretta-normale.png", 860, 900), + new("/dashboard?scena=normale&tema=chiaro", "14-attivita-telefono-normale.png", 390, 844), new("/impostazioni/limiti?tema=chiaro", "07-limiti-e-comportamento.png", 1440, 1470), new("/impostazioni/limiti?tema=chiaro", "07-limiti-su-misura.png", Step: "su-misura.js"), new("/impostazioni/generali?tema=chiaro", "08-impostazioni-generali.png"), diff --git a/tools/Febe.Schermate/passi/tutte-le-foto.js b/tools/Febe.Schermate/passi/tutte-le-foto.js new file mode 100644 index 0000000..ed7634a --- /dev/null +++ b/tools/Febe.Schermate/passi/tutte-le-foto.js @@ -0,0 +1,5 @@ +// Switches the Libreria to «Tutte le foto» (spec §4.6): one tile per file, «2/4» on the files of a series. +await new Promise((r) => setTimeout(r, 500)); +document.querySelector('.strumenti .modo-mosaico [data-value=files]')?.click(); +await new Promise((r) => setTimeout(r, 2000)); +return document.querySelector('.quanti')?.textContent; diff --git a/tools/Febe.Schermate/passi/tutti-tetti.js b/tools/Febe.Schermate/passi/tutti-tetti.js index fc9c20c..21e3d4c 100644 --- a/tools/Febe.Schermate/passi/tutti-tetti.js +++ b/tools/Febe.Schermate/passi/tutti-tetti.js @@ -1,4 +1,4 @@ -// Opens «Tutti i tetti» on the Attività page (spec §7.4: every category, hourly and daily). +// Opens «Tutti i tetti» on the Dashboard (spec §7.4: every category, hourly and daily). await new Promise((r) => setTimeout(r, 500)); [...document.querySelectorAll('.testa-blocco .btn.collegamento')].find((b) => b.textContent.includes('tetti'))?.click(); await new Promise((r) => setTimeout(r, 600));