Rifiniture (M8): avvisi su striscia, notifiche di Windows e Telegram con controllo dello spazio su disco; «Esporta l'elenco» della libreria; avvisi e ricette sospese in Attività; guida per il wiki in docs/guida
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
50 files changed
+3980
-28
No files matched your search
@@ -0,0 +1,105 @@
|
||||
# Account e impostazioni
|
||||
|
||||
La pagina **Account** elenca i profili che Febe archivia: che cosa raccoglie per ciascuno, lo stato, l'ultimo e il
|
||||
prossimo controllo, quanti elementi sono in libreria, l'interruttore «Tieni aggiornato». Un clic sulla riga apre la
|
||||
scheda dell'account.
|
||||
|
||||
Un **elemento** è una pubblicazione (un post anche con più foto e video, una storia, un contenuto di una raccolta in
|
||||
evidenza); un **file** è ogni singola foto o video. I contatori contano elementi.
|
||||
|
||||
## Aggiungere account
|
||||
|
||||
«Aggiungi account» apre una finestra con due linguette:
|
||||
|
||||
- **Dai profili che segui:** l'elenco dei profili che segui, letto da Febe a ritmo umano e dentro i tetti. La prima
|
||||
volta va letto («Leggi l'elenco»): può servire più di una sessione, e la finestra dice a che punto è («Letti 96
|
||||
profili, continuo alla prossima sessione»). L'elenco resta in memoria con la data di lettura e si rilegge solo se lo
|
||||
chiedi. I profili già presenti in Febe sono attenuati.
|
||||
- **Per nome utente:** scrivi o incolla nomi utente o indirizzi di profilo, uno per riga (`nome.utente`,
|
||||
`@nome.utente` oppure `instagram.com/nome.utente`). Serve per i profili pubblici che non segui.
|
||||
|
||||
A destra scegli il **punto di partenza**, che poi puoi cambiare account per account:
|
||||
|
||||
| Punto di partenza | Tieni aggiornato | Che cosa scarica | Quanto indietro |
|
||||
|---|---|---|---|
|
||||
| Scarica tutto e tieni aggiornato | sì | foto, video, storie, evidenza, foto del profilo | quello che scegli in «Quanto indietro nel tempo» (tutto, ultimi 50, 200 o 1.000 post, dall'inizio dell'anno) |
|
||||
| Solo le novità da oggi | sì | gli stessi | dalla data di oggi, niente storico |
|
||||
| Solo le storie | sì | storie e storie in evidenza | — |
|
||||
|
||||
Valori comuni: frequenza Normale; «Post in cui è taggato» spento (acceso solo per il tuo profilo); storico al giorno
|
||||
secondo il profilo di prudenza (300 post con «Prudente»); nessun limite alla dimensione dei video; video delle storie
|
||||
compresi; cartella predefinita. Lo storico arriva poco per volta; i primi controlli partono alla prossima sessione,
|
||||
dentro la fascia oraria.
|
||||
|
||||
## Stati di un account
|
||||
|
||||
| Stato | Che cosa significa |
|
||||
|---|---|
|
||||
| Aggiornato | Febe lo controlla secondo la sua frequenza |
|
||||
| Storico in corso | Febe sta scaricando i contenuti passati, un po' al giorno |
|
||||
| In pausa | Messo in pausa da te, oppure scaricato una volta con «Tieni aggiornato» spento |
|
||||
| Solo archivio | Vive solo in libreria e non viene mai contattato (gli account creati dall'importazione, o quelli che congeli) |
|
||||
| Non raggiungibile | Privato e non lo segui, non esiste più, non è visibile, o ha cambiato nome |
|
||||
|
||||
Il filtro **«Da controllare»** raccoglie gli account che chiedono attenzione: non raggiungibili, con nome cambiato, con
|
||||
risposte in un formato non riconosciuto. Le etichette sono neutre: «Tu», «Seguito», «Non seguito», «Privato»,
|
||||
«Pubblico».
|
||||
|
||||
Un account è riconosciuto dal suo identificativo numerico, non dal nome. Se un profilo che segui cambia nome, Febe lo
|
||||
scopre dai dati che riceve, aggiorna il nome, tiene la cartella e lo segnala. Un profilo che non segui e cambia nome
|
||||
risulta «Non raggiungibile»: puoi indicare il nuovo nome.
|
||||
|
||||
## La scheda di un account
|
||||
|
||||
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).
|
||||
|
||||
### Impostazioni dell'account
|
||||
|
||||
- **Tieni aggiornato:** con «no» Febe fa un solo scaricamento, poi mette l'account in pausa.
|
||||
- **Frequenza dei controlli:** Bassa, Normale, Alta oppure Su misura (ogni quante ore controllare i post e l'intervallo
|
||||
massimo fra due controlli delle storie).
|
||||
|
||||
| Frequenza | Profilo che non segui: controllo | Profilo che segui: riconciliazione | Storie: al massimo ogni |
|
||||
|---|---|---|---|
|
||||
| Bassa | circa ogni 12 ore | ogni 24 ore | 8 ore |
|
||||
| Normale | circa ogni 3 ore | ogni 12 ore | 6 ore |
|
||||
| Alta | circa ogni 75 minuti | ogni 6 ore | 3 ore |
|
||||
|
||||
I profili che segui si scoprono soprattutto con il giro della pagina iniziale: il controllo del profilo serve solo a
|
||||
recuperare ciò che il giro può aver perso. Con «Storie» attivo ogni account riceve almeno tre controlli al giorno
|
||||
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.
|
||||
- **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.
|
||||
- **Cartella:** di solito una cartella con il nome dell'account dentro la libreria. Su Windows se ne può scegliere
|
||||
un'altra, anche fuori dalla libreria; in Docker le cartelle si cambiano dal contenitore.
|
||||
|
||||
Il riquadro **«Con queste impostazioni»** a destra traduce le scelte in conseguenze e si ricalcola a ogni modifica:
|
||||
ogni quanto verrà controllato davvero, quanti giorni richiede lo storico (quando il numero dei post è noto), quanto
|
||||
pesa sul tetto giornaliero. Le modifiche valgono quando premi «Salva le impostazioni».
|
||||
|
||||
### Le storie risultano viste
|
||||
|
||||
Febe salva le storie solo dopo averle **aperte** nel visualizzatore, come una visita normale: **le storie aperte da
|
||||
Febe risultano viste** e tu compari tra gli spettatori. Non esiste una visione anonima. Per un account in cui non vuoi
|
||||
comparire, spegni «Storie» (e «Storie in evidenza», che si aprono allo stesso modo).
|
||||
|
||||
## Comandi
|
||||
|
||||
- **Controlla ora:** mette quel controllo in cima alla coda. Passa comunque dai tetti: se il tetto è esaurito Febe lo
|
||||
dice e non lo fa. Fuori dalla fascia oraria chiede conferma e, avutala, esegue quel solo controllo: è l'unico caso in
|
||||
cui Febe lavora fuori fascia, perché ci sei tu.
|
||||
- **Metti in pausa / Riattiva** l'account.
|
||||
- **Apri su Instagram:** apre il profilo nel tuo browser, non in quello di Febe.
|
||||
- **Rimuovi…:** chiede sempre che cosa fare dei file. Il predefinito è **tenerli**: l'account diventa «Solo archivio» e
|
||||
non viene più contattato. «Elimina anche i file» li cancella dal disco, e non si recuperano.
|
||||
|
||||
## «Appena pubblicato» vuol dire «entro la sessione successiva»
|
||||
|
||||
Febe non lavora in tempo reale. Con il profilo «Prudente», per gli account che segui un contenuto nuovo arriva di
|
||||
norma fra 20 e 90 minuti dopo la pubblicazione, dentro la fascia oraria; per quelli che non segui, secondo la
|
||||
frequenza. Di notte Febe non lavora. Se gli account e le frequenze chiesti superano ciò che i tetti consentono, i
|
||||
controlli si diradano, non si forzano. Vedi [Limiti e comportamento](Limiti-e-comportamento).
|
||||
@@ -0,0 +1,82 @@
|
||||
# Attività e arresti
|
||||
|
||||
## La pagina Attività
|
||||
|
||||
**Attività** è il cruscotto del motore. Si aggiorna da sola.
|
||||
|
||||
- **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).
|
||||
- **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).
|
||||
- **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)).
|
||||
|
||||
Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprendi»), **«Riprendi»**, **«Apri il
|
||||
browser»**.
|
||||
|
||||
## La striscia rossa
|
||||
|
||||
Quando Febe è fermo e serve te, in cima a **tutte le pagine** compare una striscia: rossa per una verifica o una
|
||||
disconnessione, ambra per un fermo per rallentamento. Dice che cosa è successo, che cosa ha fatto Febe e che cosa devi
|
||||
fare, con «Apri il browser» e, quando serve, «Riprendi». Nella barra laterale il riquadro dello stato dice «Fermo,
|
||||
serve il tuo intervento».
|
||||
|
||||
## I tre livelli di arresto
|
||||
|
||||
| Livello | Quando | Che cosa fa Febe |
|
||||
|---|---|---|
|
||||
| **Rallentamento** | Instagram risponde «troppe richieste» (429) o chiede di attendere; pagine o risposte vuote ripetute | Chiude subito la sessione. Fermo di 1 ora la prima volta, 6 ore la seconda nelle 24 ore, 24 ore la terza. Poi tetti dimezzati per 48 ore. Riparte da solo |
|
||||
| **Verifica** | La pagina va verso una verifica, un controllo o una sospensione; avviso di comportamento automatico; richiesta di confermare l'identità | Ferma tutto e **non riparte da solo**. Striscia rossa, avvisi, pagina lasciata com'è |
|
||||
| **Disconnessione** | La pagina torna all'accesso; il cookie di sessione non c'è più | Come la verifica. **Non tenta mai di rientrare** |
|
||||
|
||||
Durante un fermo gli scaricamenti già in coda dal CDN si completano; verso il sito non parte nulla. Ogni arresto è
|
||||
registrato con data, livello, segnale e pagina.
|
||||
|
||||
## Che cosa fare dopo una verifica
|
||||
|
||||
1. **Non avere fretta.** Febe è fermo e resta fermo: non c'è nulla che peggiori aspettando.
|
||||
2. Premi **«Apri il browser»** nella striscia rossa (in Docker si apre la pagina «Browser» con la vista remota; su
|
||||
Windows la finestra «Browser di Febe» viene in primo piano). Mentre usi il browser il motore resta fermo.
|
||||
3. Nella pagina che Febe ha lasciato com'era, **completa la verifica a mano**: codice, conferma dell'identità, quello
|
||||
che Instagram chiede. Febe non risolve mai verifiche, CAPTCHA o codici in automatico.
|
||||
4. Controlla che Instagram funzioni normalmente nel browser (la tua pagina iniziale si apre), poi premi **«Ho
|
||||
finito»**.
|
||||
5. Premi **«Riprendi»**. Si attiva solo dopo che hai usato il browser.
|
||||
6. Febe riparte con l'**avvio graduale**: tetti dalla metà, che risalgono nei giorni del profilo.
|
||||
|
||||
Se le verifiche si ripetono, prima di riprendere riduci il carico: profilo più prudente, meno account, frequenze più
|
||||
basse (vedi [Limiti e comportamento](Limiti-e-comportamento)). Se Instagram ha sospeso o limitato l'account, non
|
||||
riprendere: lascia Febe in pausa.
|
||||
|
||||
## Che cosa fare dopo una disconnessione
|
||||
|
||||
1. «Apri il browser»: la pagina mostra l'accesso di Instagram.
|
||||
2. Accedi a mano (nome utente, password, eventuale codice), aspetta la pagina iniziale, «Ho finito».
|
||||
3. «Riprendi». Anche qui riparte l'avvio graduale.
|
||||
|
||||
Se non sei stato tu a chiudere la sessione (per esempio uscendo da Instagram su tutti i dispositivi), controlla la
|
||||
sicurezza del tuo account dall'app di Instagram prima di riprendere.
|
||||
|
||||
## Che cosa fare dopo un rallentamento
|
||||
|
||||
- **Niente, nell'immediato.** Febe ha già chiuso la sessione e si è fermato per il tempo fisso (1, 6 o 24 ore); poi
|
||||
riparte da solo con i tetti dimezzati per 48 ore. «Riprendi» non accorcia un rallentamento.
|
||||
- Non usare in quelle ore il browser di Febe per «recuperare» a mano.
|
||||
- Guarda **Arresti e rallentamenti**: se i rallentamenti si ripetono, la pagina lo dice. **Tre rallentamenti in sette
|
||||
giorni**: Febe propone di passare al profilo più prudente o di ridurre gli account seguiti. Fallo: i tetti sono stime,
|
||||
e un rallentamento dice che per il tuo account sono troppo alti.
|
||||
|
||||
## Formato non riconosciuto e ricette sospese
|
||||
|
||||
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
|
||||
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.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Avvisi e Telegram
|
||||
|
||||
Quando succede qualcosa che ti riguarda, Febe te lo dice. Si regola in **Impostazioni ▸ Notifiche**.
|
||||
|
||||
## Quali eventi
|
||||
|
||||
| Evento | Che cosa significa | Che cosa fare |
|
||||
|---|---|---|
|
||||
| Verifica richiesta | Instagram chiede una verifica: Febe ha fermato tutto e non riparte da solo | Apri il browser di Febe, completa la verifica, «Ho finito», «Riprendi» |
|
||||
| Disconnessione da Instagram | La sessione non c'è più: Febe ha fermato tutto e non prova a rientrare | Apri il browser, accedi a mano, «Ho finito», «Riprendi» |
|
||||
| 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à |
|
||||
|
||||
Che cosa fare, nel dettaglio: [Attività e arresti](Attivita-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
|
||||
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.
|
||||
|
||||
Gli interruttori di «Quando avvisarti» decidono che cosa ti raggiunge **fuori** da Febe; nell'interfaccia vedi
|
||||
comunque tutto.
|
||||
|
||||
## Telegram: creare il bot
|
||||
|
||||
Ti serve un bot tuo, che scrive solo a te. Si crea in un paio di minuti con **BotFather**, il bot ufficiale di
|
||||
Telegram per creare bot.
|
||||
|
||||
1. In Telegram cerca **@BotFather** (ha la spunta blu) e apri la chat. Premi **Avvia**.
|
||||
2. Scrivi `/newbot`.
|
||||
3. BotFather chiede il **nome** del bot (quello che vedi nella chat, per esempio `Febe di casa`) e poi il **nome
|
||||
utente**, che deve finire con `bot` (per esempio `febe_casa_alberto_bot`).
|
||||
4. BotFather risponde con il **gettone** (token) del bot: una riga come `123456789:AAH…` (cifre, due punti, poi una
|
||||
lunga serie di lettere). **È una password:** chi lo ha può scrivere a nome del bot. Non mandarlo a nessuno e non
|
||||
pubblicarlo.
|
||||
5. Apri la chat con il tuo nuovo bot (il collegamento è nel messaggio di BotFather), premi **Avvia** e scrivigli un
|
||||
messaggio qualsiasi, per esempio «ciao». Un bot non può scrivere per primo a chi non gli ha mai scritto.
|
||||
|
||||
## Telegram: trovare l'identificativo della chat
|
||||
|
||||
L'identificativo della chat è un numero (per una chat privata è il tuo identificativo di Telegram; per un gruppo è
|
||||
negativo, per esempio `-1001234567890`).
|
||||
|
||||
1. Dopo aver scritto al bot, apri nel **tuo** browser questo indirizzo, mettendo il gettone al posto di `GETTONE`:
|
||||
|
||||
```text
|
||||
https://api.telegram.org/botGETTONE/getUpdates
|
||||
```
|
||||
|
||||
2. Nella risposta cerca `"chat":{"id":` e copia il numero che segue (con il segno meno, se c'è).
|
||||
3. Se la risposta è vuota (`"result":[]`), scrivi un altro messaggio al bot e ricarica la pagina.
|
||||
|
||||
L'indirizzo contiene il gettone: non condividerlo e non farne schermate. Per usare un gruppo: aggiungi il bot al
|
||||
gruppo, scrivi un messaggio nel gruppo e cerca l'identificativo nello stesso modo.
|
||||
|
||||
## Telegram: collegarlo a Febe
|
||||
|
||||
1. In **Impostazioni ▸ Notifiche ▸ Telegram** incolla il **gettone del bot** e l'**identificativo della chat**.
|
||||
2. **Salva.**
|
||||
3. **«Invia una prova»**: nella chat del bot deve arrivare «Febe · Prova degli avvisi». Se non arriva, Febe dice
|
||||
perché (gettone non riconosciuto, chat non trovata, bot bloccato o mai avviato, Telegram non raggiungibile).
|
||||
|
||||
Il gettone resta nella cartella dei dati di Febe: non torna mai all'interfaccia (dopo il salvataggio il campo dice solo
|
||||
«Gettone salvato»), non finisce nei registri e non compare negli errori. Per cambiarlo scrivine uno nuovo; «Togli il
|
||||
gettone» lo cancella. Se pensi che qualcuno l'abbia visto, revocalo con BotFather (`/revoke`) e salva quello nuovo.
|
||||
|
||||
## Come sono fatti i messaggi
|
||||
|
||||
Brevi, in italiano: che cosa è successo, che cosa ha fatto Febe, che cosa devi fare. Per esempio:
|
||||
|
||||
```text
|
||||
Febe · Instagram chiede una verifica
|
||||
Ho fermato tutto alle 14:32 e non riparto da solo. Che cosa fare: apri Febe, poi il browser di Febe («Apri il
|
||||
browser»), completa la verifica a mano e premi «Riprendi».
|
||||
```
|
||||
|
||||
Contengono i nomi degli account (per esempio nello storico completato) e i dati di spazio del disco; mai didascalie,
|
||||
password, cookie, indirizzi o il gettone. Febe manda **una sola chiamata HTTPS** a `api.telegram.org` per ogni avviso,
|
||||
direttamente dal server (in Docker dal contenitore), senza librerie esterne, con un tempo massimo di 15 secondi.
|
||||
|
||||
## Niente raffiche
|
||||
|
||||
Uno stato che va e viene non ti manda lo stesso messaggio più volte. Lo stesso avviso non si ripete prima di:
|
||||
|
||||
| Avviso | Intervallo minimo |
|
||||
|---|---|
|
||||
| Verifica, disconnessione | 30 minuti |
|
||||
| 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) |
|
||||
|
||||
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
|
||||
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».
|
||||
|
||||
## Disco quasi pieno
|
||||
|
||||
Febe controlla lo spazio libero dei dischi della libreria e della cartella dei dati un minuto dopo l'avvio e poi ogni
|
||||
15 minuti. Un disco è «quasi pieno» quando restano meno di **10 GB** oppure meno del **5%** della sua capacità (la
|
||||
prima delle due condizioni che si verifica). Con il disco della libreria pieno gli scaricamenti non riescono; con
|
||||
quello dei dati pieno il database non può più salvare nulla. Se il disco non si può misurare (per esempio una
|
||||
cartella di rete su Windows), il registro lo dice una volta e per quel disco l'avviso non c'è.
|
||||
|
||||
## Notifiche di Windows
|
||||
|
||||
Nella versione per Windows, «Notifiche di Windows» mostra gli avvisi nell'angolo dello schermo; «Invia una prova» ne
|
||||
mostra una. In Docker l'interruttore è spento e segnato «Solo versione Windows».
|
||||
@@ -0,0 +1,73 @@
|
||||
# Copie e ricostruzione
|
||||
|
||||
Febe tiene due cose ben separate:
|
||||
|
||||
- la **libreria**: i tuoi file, normali, leggibili anche senza Febe, e in ogni cartella di account il file
|
||||
`_febe.jsonl` con i dati di ogni elemento;
|
||||
- la **cartella dei dati**: il database (`febe.sqlite`), che è l'indice di tutto e lo stato del motore, il profilo del
|
||||
browser con la sessione, le miniature, il registro e le **copie del database**.
|
||||
|
||||
Febe fa da solo le copie del database. **Non fa copie delle foto e dei video:** la libreria va salvata come fai con gli
|
||||
altri tuoi file (su Unraid, per esempio, con la parità dell'array e un backup a parte).
|
||||
|
||||
## Dove sono le copie del database
|
||||
|
||||
| Veste | Cartella | File |
|
||||
|---|---|---|
|
||||
| Docker | `/dati/copie` (su Unraid di solito `/mnt/user/appdata/febe/copie`) | `febe-AAAA-MM-GG.sqlite` |
|
||||
| Windows | `%LOCALAPPDATA%\Febe\copie` | `febe-AAAA-MM-GG.sqlite` |
|
||||
|
||||
- Una copia al giorno: all'avvio, se quella di oggi manca, e poi ogni notte verso le 3:20 (fuori dalla fascia di ogni
|
||||
profilo). Si tengono gli **ultimi sette giorni**; le più vecchie si cancellano da sole (solo i file con quel nome).
|
||||
- La copia si scrive con un nome temporaneo e si rinomina solo quando è completa: una copia interrotta non ha mai il
|
||||
nome definitivo.
|
||||
- In **Impostazioni ▸ Dati e copie di sicurezza** vedi l'elenco (giorno, file, peso, quando è stata fatta) e puoi
|
||||
premere **«Fai una copia adesso»**: diventa la copia di oggi, al posto di quella fatta prima oggi.
|
||||
|
||||
Una copia del database contiene tutto ciò che Febe sa: account e impostazioni, elenco degli elementi, cronologia, e
|
||||
anche le impostazioni delle notifiche **con il gettone del bot Telegram**. Non contiene la sessione di Instagram, che
|
||||
sta nel profilo del browser (`browser`); ma una copia di **tutta** la cartella dei dati la contiene: chi ha la
|
||||
cartella dei dati, o una sua copia, ha la sessione di Instagram (vedi
|
||||
[Sicurezza e riservatezza](Sicurezza-e-riservatezza)).
|
||||
|
||||
## Tornare a una copia
|
||||
|
||||
1. **Ferma Febe:** `docker stop febe` (su Unraid, Stop sul contenitore); su Windows «Esci» dal menu dell'icona
|
||||
nell'area di notifica.
|
||||
2. Nella cartella dei dati sposta da parte `febe.sqlite` (rinominalo, per esempio `febe-rovinato.sqlite`) e, se ci sono,
|
||||
`febe.sqlite-wal` e `febe.sqlite-shm`.
|
||||
3. Copia la copia scelta da `copie/` nella cartella dei dati con il nome `febe.sqlite`.
|
||||
4. Riavvia Febe. Il database si aggiorna da solo, se la copia è di una versione precedente.
|
||||
|
||||
Ciò che è successo dopo la copia (elementi scaricati, scelte fatte) non è nel database ripristinato, ma i file scaricati
|
||||
nel frattempo sono in libreria con il loro `_febe.jsonl`: una **ricostruzione** subito dopo li rimette nell'indice.
|
||||
|
||||
## Ricostruire il database dalla libreria
|
||||
|
||||
Se il database si è perso o rovinato e non hai una copia buona, Febe lo ricostruisce dalla libreria:
|
||||
**Impostazioni ▸ Dati e copie di sicurezza ▸ «Ricostruisci il database dalla libreria» ▸ «Ricostruisci…»**. Per
|
||||
confermare scrivi `ricostruisci`.
|
||||
|
||||
Che cosa fa:
|
||||
|
||||
- rilegge le cartelle degli account e i loro file `_febe.jsonl`, ricalcola SHA-256, impronte e miniature dei file sul
|
||||
disco, e rispetta le eliminazioni (un elemento eliminato «ricordando la scelta» resta eliminato);
|
||||
- **non riscarica nulla** e **non sposta, non rinomina e non cancella nessun file**;
|
||||
- gli elementi già presenti nel database restano come sono: si può lanciare anche su un database esistente;
|
||||
- mostra l'avanzamento (cartelle e file controllati) e alla fine un resoconto.
|
||||
|
||||
Che cosa non torna:
|
||||
|
||||
- gli account ricreati tornano **«In pausa»** con le impostazioni predefinite: riattivali e controlla le loro
|
||||
impostazioni;
|
||||
- la cronologia del motore, gli arresti passati e le impostazioni generali (limiti, notifiche) che stavano solo nel
|
||||
database perso.
|
||||
|
||||
Con una libreria grande può durare a lungo. È rifiutata mentre è in corso un'importazione. Se il database c'è ancora,
|
||||
fai prima una copia («Fai una copia adesso»).
|
||||
|
||||
## I file `_febe.jsonl`
|
||||
|
||||
Ogni cartella di account ha il suo `_febe.jsonl`: una riga per ogni elemento salvato e una per ogni eliminazione, sempre
|
||||
aggiunte in coda. È ciò che rende possibile la ricostruzione: **non modificarlo e non cancellarlo**, e tienilo insieme
|
||||
ai file quando sposti o copi una cartella di account.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Febe
|
||||
|
||||
Febe è un archivio personale. Scarica e conserva sul tuo disco le foto, i video e le storie degli account Instagram che
|
||||
scegli, usando il tuo account, e li tiene aggiornati nel tempo. Esiste in due vesti, con lo stesso motore e la stessa
|
||||
interfaccia: un **contenitore Docker** per il server di casa (Unraid) e un'**applicazione per Windows**.
|
||||
|
||||
Febe non costruisce richieste verso Instagram: usa un browser vero, in cui accedi tu a mano, lo fa navigare con il
|
||||
ritmo di una persona e salva ciò che la pagina stessa riceve. Per questo è più lento di uno scaricatore diretto: è
|
||||
voluto.
|
||||
|
||||
## Il rischio per il tuo account: leggilo prima
|
||||
|
||||
- **Scaricare contenuti con un programma è contro le condizioni d'uso di Instagram.** Il rischio concreto è la
|
||||
limitazione o la chiusura dell'account. Non esiste un'API ufficiale per questo uso: quelle di Meta servono solo ai
|
||||
profili aziendali.
|
||||
- **Che cosa fa Febe per ridurre il rischio:** usa un browser normale, con la tua lingua e il tuo fuso orario, senza
|
||||
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).
|
||||
- **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.
|
||||
- **Che cosa Febe non può fare:** azzerare il rischio. I tetti sono stime prudenti, non limiti pubblicati da Instagram,
|
||||
che non li pubblica. Nessuno può garantire che bastino.
|
||||
- **Le storie aperte da Febe risultano viste:** Febe guarda le storie come faresti tu, quindi risulti tra gli
|
||||
spettatori. Per un account in cui non vuoi comparire, spegni l'interruttore «Storie» (vedi
|
||||
[Account e impostazioni](Account-e-impostazioni)).
|
||||
- **Un account, un Febe:** il contenitore e la versione per Windows non vanno usati insieme sullo stesso account.
|
||||
- I contenuti restano dei loro autori. Febe è un archivio privato: non ripubblica e non condivide nulla.
|
||||
|
||||
Il consiglio pratico: comincia con un **account di prova**, il profilo **Prudente** e un solo profilo pubblico da
|
||||
seguire; passa al tuo account solo quando hai visto come si comporta.
|
||||
|
||||
## A che punto è Febe (13 ottobre 2026)
|
||||
|
||||
Questa guida descrive ciò che c'è nel programma, non ciò che si spera. Alcune cose dipendono da prove che si possono
|
||||
fare solo con Instagram o su Windows:
|
||||
|
||||
- **Raccolta da Instagram: non ancora attiva.** Le ricette, il motore, la libreria e gli scaricamenti funzionano e sono
|
||||
provati contro un sito di prova locale. Su Instagram le ricette si rifiutano di girare («la mappa dei bersagli non è
|
||||
ancora compilata») finché la sonda passiva non ha confermato le ipotesi H1–H11. Vedi
|
||||
[Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
- **Versione per Windows: in costruzione.** Vedi [Installazione su Windows](Installazione-Windows).
|
||||
- **Docker, interfaccia, importazione, avvisi (anche Telegram), copie e ricostruzione:** pronti, da provare sul tuo
|
||||
Unraid.
|
||||
|
||||
## Pagine della guida
|
||||
|
||||
| Pagina | Di che cosa parla |
|
||||
|---|---|
|
||||
| [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid) | Contenitore, volumi, variabili, profilo seccomp, aggiornamenti |
|
||||
| [Installazione su Windows](Installazione-Windows) | L'applicazione per Windows, come è progettata |
|
||||
| [Primo collegamento](Primo-collegamento) | Accedere a Instagram dal browser di Febe, scollegarsi |
|
||||
| [Account e impostazioni](Account-e-impostazioni) | Aggiungere account, punti di partenza, impostazioni per account |
|
||||
| [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 |
|
||||
| [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 |
|
||||
| [Problemi comuni](Problemi-comuni) | Che cosa vedi, che cosa fare |
|
||||
| [Ipotesi da verificare](Ipotesi-da-verificare) | Le voci H e S ancora da provare e come le provi tu |
|
||||
| [Sviluppo](Sviluppo) | Compilare, provare, dimostrazione, simulazione, sito di prova, sonda, CI e rilascio |
|
||||
|
||||
Il codice e la specifica completa sono nel repository:
|
||||
<https://gitea.encke-hake.ts.net/Alby96/Febe> (la specifica è `docs/SPECIFICA.md`).
|
||||
@@ -0,0 +1,81 @@
|
||||
# Importazione
|
||||
|
||||
**Importa** porta in libreria foto e video che hai già, anche di contenuti che su Instagram non esistono più, senza
|
||||
creare doppioni e senza toccare gli originali finché non decidi tu. Quattro passi, mostrati in alto nella pagina:
|
||||
Sorgente, Analisi, Revisione, Copia. Un'importazione alla volta.
|
||||
|
||||
## 1. Sorgente
|
||||
|
||||
- **In Docker** si importa dalle cartelle del volume `/importa`, montato **in sola lettura**: la pagina le elenca e ci
|
||||
entri con un clic. Metti lì (sul server) le cartelle da importare.
|
||||
- **Su Windows** scegli una cartella qualsiasi con «Scegli una cartella…».
|
||||
|
||||
Febe rifiuta le sorgenti che sono dentro o sopra la cartella dei dati, sopra la libreria, o dentro una cartella di
|
||||
account di Febe: una libreria non si importa in sé stessa.
|
||||
|
||||
Se la cartella sembra una **libreria di Febe**, date e codici si leggono dai suoi file `_febe.jsonl` (date esatte). Se
|
||||
sembra una **libreria di 4K Stogram**, compare l'opzione «Leggi i nomi alla maniera di 4K Stogram (ipotesi da
|
||||
verificare)»: il riconoscitore dei nomi di 4K Stogram è scritto su un ricordo, non su file veri, ed è spento per
|
||||
impostazione predefinita. Se lo usi, controlla date e codici nella revisione. Il database di 4K Stogram non viene mai
|
||||
aperto.
|
||||
|
||||
«Analizza questa cartella» passa all'analisi.
|
||||
|
||||
## 2. Analisi
|
||||
|
||||
Sola lettura: nessun file viene copiato o spostato, e nella sorgente non si scrive nemmeno un file di prova. Per ogni
|
||||
file Febe ricava: tipo dal contenuto (non solo dall'estensione), peso, SHA-256, dimensioni, impronta visiva per le
|
||||
foto, data (dal nome del file, poi dai metadati, poi dalla data di modifica), codice di Instagram se il nome lo
|
||||
contiene, account probabile dal nome della cartella, tipo probabile (storie, evidenza, taggati) dalle sottocartelle.
|
||||
|
||||
Puoi **interrompere** e **riprendere** quando vuoi, anche dopo un riavvio: l'analisi riprende da dove era rimasta.
|
||||
|
||||
## 3. Revisione
|
||||
|
||||
Quattro contatori:
|
||||
|
||||
| Esito | Che cosa significa | Che cosa succede |
|
||||
|---|---|---|
|
||||
| Nuovi | Non ci sono in libreria | Verranno copiati |
|
||||
| Già in libreria | Identici (stesso SHA-256) a un file presente in qualunque account | Saltati; il resoconto dice dove sono |
|
||||
| Doppioni probabili | Stesso codice di Instagram con file diverso, oppure stessa immagine con file diverso (impronta visiva vicina) | Decidi tu |
|
||||
| Non riconosciuti | Né foto né video | Ignorati ed elencati |
|
||||
|
||||
I doppioni si cercano anche dentro la sorgente stessa (una copia identica nella sorgente si copia una volta sola). Per
|
||||
i video vale solo lo SHA-256 (e il codice). Un file che hai eliminato «ricordando la scelta» conta come già in
|
||||
libreria: un'importazione non annulla un'eliminazione.
|
||||
|
||||
**Cartelle e account.** Una tabella lega ogni cartella della sorgente a un account: uno esistente (riconosciuto per
|
||||
identificativo o per nome), oppure un nuovo account «Solo archivio» con il nome della cartella. Una cartella senza
|
||||
account blocca solo i propri file: il pulsante finale dice quanti file importa e quanti restano fuori. Gli account
|
||||
nuovi nascono solo quando parte la copia, con «Tieni aggiornato» spento.
|
||||
|
||||
**Doppioni probabili.** Per ogni coppia vedi le due immagini con misure e peso («Più grande» sulla maggiore) e scegli:
|
||||
«Tieni il più grande e scarta l'altro», «Tieni quello già in libreria», «Tienili entrambi». Nessuna scelta è fatta in
|
||||
partenza. «Fai lo stesso per gli altri» applica la scelta ai casi simili. Se il più grande è quello da importare,
|
||||
«Tieni il più grande» sostituisce il file della libreria: il nuovo viene scritto e riletto prima che il vecchio sparisca.
|
||||
|
||||
**Copia o sposta.** Il predefinito è **Copia**: gli originali restano dove sono. Con **Sposta** ogni originale si
|
||||
cancella solo dopo che la sua copia in libreria è stata riletta e verificata con lo SHA-256; i file saltati non si
|
||||
toccano. Se la sorgente è in sola lettura, come `/importa` in Docker, «Sposta» non compare.
|
||||
|
||||
## 4. Copia
|
||||
|
||||
Ogni file viene copiato con un nome temporaneo, verificato e poi rinominato: mai una sovrascrittura. I file con data e
|
||||
codice noti prendono il nome secondo lo schema della libreria; gli altri vanno in `{account}\importati\` con il nome
|
||||
originale. Puoi interrompere e riprendere: ogni file ha il suo esito nel database.
|
||||
|
||||
Alla fine il **resoconto**: copiati (di cui spostati e sostituiti), saltati, rimasti fuori, non riusciti, per account,
|
||||
e ciò che è da guardare. «Esporta l'elenco in CSV» scarica il resoconto completo (`;`, UTF-8 con BOM). Puoi tornare
|
||||
alla revisione dei file rimasti fuori e rilanciare la copia sulla stessa importazione.
|
||||
|
||||
«Annulla l'importazione» fa dimenticare a Febe l'analisi: nessun file della sorgente viene toccato.
|
||||
|
||||
## Dopo l'importazione
|
||||
|
||||
Gli elementi importati contano come presenti. Quando Febe tiene aggiornato quell'account non li riscarica se li
|
||||
riconosce dal codice, oppure da account, tipo e data di pubblicazione entro due secondi. Se li riconosce solo dopo lo
|
||||
scaricamento: un file identico non entra due volte; uno visivamente uguale ma diverso finisce nei
|
||||
[doppioni da decidere](Libreria).
|
||||
|
||||
Le importazioni precedenti restano elencate nel passo 1 («Importazioni precedenti»), con il loro stato.
|
||||
@@ -0,0 +1,138 @@
|
||||
# Installazione con Docker e Unraid
|
||||
|
||||
La veste Docker è un solo contenitore con l'interfaccia web, il motore, un Chromium vero su un display virtuale (Xvfb)
|
||||
e la libreria su disco. La usi dal browser di casa; il browser di Febe lo vedi e lo usi dalla **vista remota** della
|
||||
pagina Impostazioni ▸ Collegamento a Instagram.
|
||||
|
||||
> **Prima di tutto.** Scaricare con un programma è contro le condizioni d'uso di Instagram: leggi il riquadro sul
|
||||
> rischio nella [pagina iniziale](Home). E leggi [Sicurezza e riservatezza](Sicurezza-e-riservatezza) prima di
|
||||
> decidere su quale rete pubblicare l'interfaccia.
|
||||
|
||||
## Che cosa serve
|
||||
|
||||
- Un server con Docker (Unraid va benissimo), processore x86-64 (l'immagine è per `linux-x64`).
|
||||
- Un **disco locale** per la cartella dei dati (su Unraid: l'appdata sul disco di cache).
|
||||
- Lo spazio per la libreria: può stare anche su una condivisione o sull'array.
|
||||
- Una password per l'interfaccia, lunga: è la sola cosa che protegge la vista remota del browser.
|
||||
|
||||
## Volumi
|
||||
|
||||
| Volume | Che cosa contiene | Dove metterlo |
|
||||
|---|---|---|
|
||||
| `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei, `seccomp.json` | Su un **disco locale** del server. Su Unraid `/mnt/user/appdata/febe`. Mai una condivisione di rete: SQLite e il profilo del browser lì si rovinano, e Febe si rifiuta di partire |
|
||||
| `/libreria` | Foto e video, una cartella per account, ognuna con il suo `_febe.jsonl` | Dove vuoi, anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo |
|
||||
| `/importa` | Cartelle da importare (pagina Importa) | **Sempre in sola lettura** (`:ro`): Febe copia, gli originali non si toccano |
|
||||
|
||||
## Variabili
|
||||
|
||||
| Variabile | Significato | Predefinito |
|
||||
|---|---|---|
|
||||
| `FEBE_PASSWORD` | Password dell'interfaccia. **Obbligatoria**: senza, il motore e il browser non partono e l'interfaccia mostra solo la pagina che spiega il problema | nessuno |
|
||||
| `FEBE_PORTA` | Porta dell'interfaccia dentro il contenitore | 8480 |
|
||||
| `TZ` | Fuso orario: fascia del motore, date nei nomi dei file, fuso dichiarato dal browser | Europe/Rome |
|
||||
| `LANG` | Lingua del contenitore e quindi del browser | it_IT.UTF-8 |
|
||||
| `PUID`, `PGID` | Utente e gruppo con cui gira Febe e di cui sono i file | 99, 100 (Unraid) |
|
||||
| `FEBE_HOST` | Facoltativa: i nomi con cui raggiungi l'interfaccia, separati da virgole (`tower.local,192.168.1.10`). Se c'è, ogni altro nome è rifiutato | qualunque nome |
|
||||
| `FEBE_PROXY_FIDATO` | `1` se davanti c'è un proxy con HTTPS che passa `X-Forwarded-Host` | spenta |
|
||||
| `FEBE_SENZA_SANDBOX` | `1` avvia Chromium senza la sua sandbox: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta |
|
||||
|
||||
La password non si passa mai sulla riga di comando e non finisce nei registri. Febe **non gira come root**: con
|
||||
`PUID=0` il contenitore si ferma con un messaggio.
|
||||
|
||||
## Porte
|
||||
|
||||
Si pubblica **solo** la porta dell'interfaccia (8480). La porta di debug del browser (9222) ascolta solo su
|
||||
`127.0.0.1` dentro il contenitore: non va mai pubblicata, e Febe si rifiuta di usare il browser se la trova aperta
|
||||
altrove.
|
||||
|
||||
## Installazione su Unraid
|
||||
|
||||
1. Dal terminale di Unraid, **una volta sola**, metti il profilo seccomp dove il modello lo cerca:
|
||||
|
||||
```sh
|
||||
mkdir -p /mnt/user/appdata/febe
|
||||
wget -O /mnt/user/appdata/febe/seccomp.json \
|
||||
https://gitea.encke-hake.ts.net/Alby96/Febe/raw/branch/main/docker/chromium/seccomp.json
|
||||
```
|
||||
|
||||
2. L'immagine è `gitea.encke-hake.ts.net/alby96/febe:latest`, sul registro di Gitea. Se Unraid non riesce a
|
||||
scaricarla, accedi al registro dal terminale: `docker login gitea.encke-hake.ts.net`.
|
||||
3. Docker ▸ Aggiungi contenitore ▸ modello da `docker/unraid/febe.xml` (o dal suo indirizzo nel repository).
|
||||
Controlla:
|
||||
- porta 8480;
|
||||
- `/dati` su `/mnt/user/appdata/febe` (disco di cache);
|
||||
- `/libreria` dove vuoi le foto; `/importa` in sola lettura;
|
||||
- **password dell'interfaccia** (obbligatoria, nascosta);
|
||||
- `TZ`, `PUID` 99, `PGID` 100 tra le impostazioni avanzate;
|
||||
- in «Extra Parameters»: `--restart=unless-stopped --stop-timeout 30 --security-opt seccomp=/mnt/user/appdata/febe/seccomp.json`.
|
||||
4. Apri `http://<IP di Unraid>:8480/`, entra con la password e segui il [Primo collegamento](Primo-collegamento).
|
||||
|
||||
## Docker Compose
|
||||
|
||||
`docker/compose.yml` nel repository è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura),
|
||||
variabili, profilo seccomp con percorso relativo al file, `restart: unless-stopped`, 30 secondi per fermarsi.
|
||||
|
||||
```sh
|
||||
FEBE_PASSWORD='una frase lunga' docker compose -f docker/compose.yml up -d
|
||||
```
|
||||
|
||||
Le cartelle si cambiano con `FEBE_DATI`, `FEBE_LIBRERIA` e `FEBE_IMPORTA` (predefinite sotto `/srv/febe`).
|
||||
|
||||
## La sandbox di Chromium
|
||||
|
||||
Chromium isola le pagine che apre in una **sandbox**. Dentro Docker la sandbox ha bisogno di creare spazi dei nomi
|
||||
utente, che il profilo seccomp predefinito di Docker vieta: con le impostazioni normali Chromium non parte affatto
|
||||
(`No usable sandbox!`).
|
||||
|
||||
- **Impostazione consigliata, già scritta nel modello di Unraid e in `compose.yml`:** il profilo seccomp dedicato di
|
||||
Febe (`docker/chromium/seccomp.json`), cioè quello di Docker più `clone` e `unshare`. Con questo profilo la sandbox
|
||||
di Chromium è completa e il resto del filtro di Docker resta attivo. **Così non c'è nessun compromesso sulla
|
||||
sandbox.**
|
||||
- L'avvio del contenitore copia il profilo in `/dati/seccomp.json` a ogni partenza; Docker però lo legge quando
|
||||
**crea** il contenitore, quindi la prima volta il file va messo a mano (passo 1 sopra).
|
||||
|
||||
Se il profilo dedicato non si può usare, ci sono due alternative, in quest'ordine:
|
||||
|
||||
1. `--security-opt seccomp=unconfined`: la sandbox di Chromium resta attiva, ma il contenitore perde tutto il filtro
|
||||
seccomp di Docker.
|
||||
2. `FEBE_SENZA_SANDBOX=1`: Chromium parte con `--no-sandbox`. **È un compromesso**: una pagina che sfruttasse un
|
||||
difetto del browser non troverebbe la sandbox di Chromium a fermarla, solo i limiti del contenitore. Si accetta
|
||||
soltanto perché quel browser visita esclusivamente Instagram, e solo se le due strade sopra non sono possibili.
|
||||
Chromium mostra anche una barra d'avviso in alto, che toglie circa 50 pixel alla pagina.
|
||||
|
||||
Febe non sceglie da solo: se Chromium non parte, il registro dice perché. La prova della sandbox è stata fatta il 13
|
||||
ottobre 2026 in un contenitore con il Chromium dell'ambiente di sviluppo; con l'immagine vera va ripetuta sul server
|
||||
(vedi [Ipotesi da verificare](Ipotesi-da-verificare), voce S5).
|
||||
|
||||
## Salute del contenitore
|
||||
|
||||
`GET /salute` risponde senza password `{"stato":"ok"}` oppure `{"stato":"problema"}` quando un problema di
|
||||
configurazione ferma Febe. L'immagine ha un controllo di salute che lo chiede ogni 30 secondi; Unraid mostra lo stato
|
||||
accanto al contenitore. Da terminale: `docker inspect --format '{{.State.Health.Status}}' febe`.
|
||||
|
||||
## Registro
|
||||
|
||||
Il registro di Febe è in `/dati/registro/febe-AAAA-MM-GG.log` (un file al giorno, quattordici giorni, al massimo 20 MB
|
||||
al giorno) e nell'output del contenitore (`docker logs febe`). Contiene azioni ed esiti, nomi utente sì; mai password,
|
||||
cookie, tasti, didascalie, corpi delle risposte, indirizzi firmati del CDN, né il gettone del bot Telegram.
|
||||
|
||||
## Arresto e aggiornamento
|
||||
|
||||
- Allo stop (`docker stop`, aggiornamento, riavvio di Unraid) Febe chiude la vista remota, ferma il motore, poi
|
||||
Chromium in modo che la sessione di Instagram resti scritta nel profilo, poi Xvfb. Lascia 30 secondi
|
||||
(`--stop-timeout 30`); di solito ne bastano pochi.
|
||||
- **Aggiornare:** scarica la nuova immagine e ricrea il contenitore (su Unraid «Force update»). `/dati` e `/libreria`
|
||||
restano; il database si aggiorna da solo all'avvio. Prima di un aggiornamento importante puoi copiare a mano
|
||||
`/dati/febe.sqlite` a contenitore fermo; le copie giornaliere sono comunque in `/dati/copie` (vedi
|
||||
[Copie e ricostruzione](Copie-e-ricostruzione)).
|
||||
- Il collegamento è fatto per sopravvivere ai riavvii e alla ricreazione del contenitore: la sessione è in
|
||||
`/dati/browser`. È provato in locale; nel contenitore vero è la voce S3 di
|
||||
[Ipotesi da verificare](Ipotesi-da-verificare), da confermare.
|
||||
|
||||
## Un account, un motore
|
||||
|
||||
Il contenitore e Febe per Windows **non vanno usati insieme sullo stesso account**: due Febe che raccolgono con lo
|
||||
stesso account sommano le visite e raddoppiano il rischio. La sessione nasce e resta nel browser del contenitore: i
|
||||
cookie non si copiano da un'altra macchina.
|
||||
|
||||
Se qualcosa non va: [Problemi comuni](Problemi-comuni).
|
||||
@@ -0,0 +1,66 @@
|
||||
# Installazione su Windows
|
||||
|
||||
> **In costruzione.** Al 13 ottobre 2026 l'applicazione per Windows (tappa M6) è in lavorazione: questa pagina
|
||||
> descrive come è progettata, dalla specifica (§12) e dalle scelte già fatte. I dettagli dell'installazione possono
|
||||
> cambiare: quando nel repository c'è `docs/windows.md`, fa fede quello. Le prove che si possono fare solo su Windows
|
||||
> (S1, S2, S3) sono ancora da fare: vedi [Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
|
||||
## Com'è fatta
|
||||
|
||||
- Un'applicazione Windows (WPF, .NET 10), **una sola istanza alla volta**, con l'icona nell'area di notifica.
|
||||
- La finestra principale mostra la stessa interfaccia della versione Docker, servita in locale solo su `127.0.0.1`,
|
||||
su una porta scelta all'avvio e protetta da un gettone che conosce solo la finestra.
|
||||
- Il browser di Instagram è una **seconda finestra**, «Browser di Febe»: un WebView2 (il motore di Edge) con una sua
|
||||
cartella dati. La apri da Collegamento e da Attività («Apri il browser» la porta in primo piano); quando non serve
|
||||
resta fuori vista ma attiva. Salvataggio delle password e compilazione automatica sono spenti.
|
||||
- Ciò che scrivi nella finestra del browser va direttamente alla pagina di Instagram: Febe non riceve la password.
|
||||
- Funzioni di Windows offerte all'interfaccia: scelta di una cartella, «Mostra nella cartella», apertura di un
|
||||
indirizzo nel tuo browser predefinito, notifiche di Windows, avvio con il sistema.
|
||||
- Chiudendo la finestra Febe resta nell'area di notifica e continua a lavorare; dal menu dell'icona: apri, metti in
|
||||
pausa, esci.
|
||||
|
||||
## Che cosa serve
|
||||
|
||||
- Windows 10 o 11 a 64 bit.
|
||||
- Il runtime WebView2: è già presente in Windows 11 e in quasi tutti i Windows 10. Se manca, Febe lo dice e indica
|
||||
dove scaricarlo.
|
||||
- Un disco locale per la cartella dei dati.
|
||||
|
||||
## Installare
|
||||
|
||||
È previsto un **programma di installazione** (costruito con NSIS) e, in alternativa, uno **zip portabile** da
|
||||
estrarre dove vuoi. Si scaricano dalla pagina delle release del repository:
|
||||
<https://gitea.encke-hake.ts.net/Alby96/Febe/releases>. Il programma è un unico eseguibile autosufficiente: non serve
|
||||
installare .NET.
|
||||
|
||||
## Dove stanno le cose
|
||||
|
||||
| Cartella | Predefinita | Che cosa contiene |
|
||||
|---|---|---|
|
||||
| Dati | `%LOCALAPPDATA%\Febe` | Database, **profilo del browser con la sessione di Instagram** (`browser\`), miniature, copie del database (`copie\`), registro |
|
||||
| Libreria | `Immagini\Febe` | Foto e video, una cartella per account |
|
||||
|
||||
- Le due cartelle si cambiano in Impostazioni ▸ Generali con «Cambia…». La nuova cartella dei dati vale dal prossimo
|
||||
avvio di Febe. Cambiando la libreria, gli account che hanno già file restano nelle loro cartelle: Febe non sposta
|
||||
nessun file; i nuovi account vanno nella cartella nuova.
|
||||
- La cartella dei dati **deve stare su un disco locale**: SQLite e il profilo del browser non reggono le condivisioni
|
||||
di rete. Se la trova in rete, Febe non avvia il motore e mostra solo la pagina che spiega il problema.
|
||||
- In Impostazioni ▸ Generali, blocco «Avvio» (solo Windows): «Avvia Febe all'accensione del computer» e «Chiudendo la
|
||||
finestra, Febe resta attivo nell'area di notifica».
|
||||
|
||||
## Il primo avvio
|
||||
|
||||
Febe si apre sulla schermata di benvenuto con due pulsanti: «Collegati a Instagram» e «Importa foto e video che hai
|
||||
già». Continua da [Primo collegamento](Primo-collegamento).
|
||||
|
||||
## Un account, un motore
|
||||
|
||||
Se usi anche il contenitore Docker, **non collegare i due Febe allo stesso account Instagram**: contenitore e desktop
|
||||
non vanno usati insieme sullo stesso account, perché due motori sommano le visite e raddoppiano il rischio. La sessione nasce nel browser di quella macchina: i cookie non si
|
||||
copiano da una macchina all'altra.
|
||||
|
||||
## Chi ha la cartella dei dati ha la sessione
|
||||
|
||||
`%LOCALAPPDATA%\Febe` contiene la sessione di Instagram: chi ha quella cartella, o una sua copia (per esempio in un
|
||||
backup del profilo di Windows), ha accesso al tuo account. Trattala come una password. Vedi
|
||||
[Sicurezza e riservatezza](Sicurezza-e-riservatezza).
|
||||
@@ -0,0 +1,62 @@
|
||||
# Ipotesi da verificare
|
||||
|
||||
Febe è costruito su alcune ipotesi che non si possono provare senza Instagram (voci **H**) o senza i due browser veri
|
||||
(voci **S**). Finché una voce non è provata, non ci si costruisce sopra: per questo la raccolta da Instagram non è
|
||||
ancora attiva. Lo stato aggiornato e i dettagli tecnici sono in `docs/sonda/esito.md` e `docs/sonda/esito-locale.md`
|
||||
nel repository; i passi precisi delle prove in `docs/prove-dal-vivo.md`.
|
||||
|
||||
Le prove dal vivo le fai **tu**, con l'**account di prova**, mai con l'account principale prima di aver visto Febe
|
||||
all'opera. Se in qualunque momento compare una verifica, un CAPTCHA o un avviso dell'account: fermati, risolvi a mano,
|
||||
annota l'ora e riferisci.
|
||||
|
||||
Legenda: **provato in locale** = misurato su una macchina di sviluppo con Chromium su un display virtuale e pagine
|
||||
locali, mai Instagram; **da provare** = serve una prova tua.
|
||||
|
||||
## Voci H: Instagram
|
||||
|
||||
Si provano tutte con la **sonda passiva** (parte A di `docs/prove-dal-vivo.md`): avvii `febe-sonda registra`, navighi
|
||||
tu in Instagram seguendo l'elenco (pagina iniziale, un profilo pubblico, un privato che segui, delle storie, una
|
||||
raccolta, le schede taggati e reel, l'elenco dei seguiti, un post), la sonda registra ciò che la pagina riceve; poi
|
||||
`febe-sonda ripulisci` e `febe-sonda verifica` sulla tua macchina, e mandi solo la cartella **ripulita**. La sonda non
|
||||
compie gesti e non apre pagine da sola.
|
||||
|
||||
| | Ipotesi | Stato | Come la provi |
|
||||
|---|---|---|---|
|
||||
| H1 | La pagina iniziale consegna i post recenti dei profili che segui con i dati completi dei file | Da provare | Sonda, pagina iniziale: scorri piano una decina di post |
|
||||
| H2 | La barra delle storie dice quali profili seguiti hanno storie attive e a quando risale l'ultima | Da provare | Sonda, pagina iniziale caricata: passa sopra la prima voce della barra |
|
||||
| H3 | La pagina di un profilo consegna identificativo, pubblico o privato, se lo segui, la prima pagina dei post con serie e video, le raccolte; scorrendo arrivano le pagine successive | Da provare | Sonda: un profilo pubblico che non segui e uno privato che segui, scorrendo 3–4 schermate |
|
||||
| H4 | Aprendo il visualizzatore arriva l'elenco delle storie con gli indirizzi dei file, e si capisce qual è l'ultima | Da provare | Sonda: apri le storie di un seguito dall'anello, guardane 2–3, chiudi con la X prima che passi all'account successivo |
|
||||
| H5 | Per i video arriva almeno un indirizzo con audio e video insieme | Da provare | Sonda: un post video e una storia video |
|
||||
| H6 | Le schede «Taggati» e «Reel» si comportano come la griglia | Da provare | Sonda: apri le due schede di un profilo e scorri |
|
||||
| H7 | I file del CDN si scaricano dal browser (`Network.loadNetworkResource`) | Provato in locale (24 MB integri); da provare con il CDN vero | Prima sessione dal vivo (parte B): i file arrivano in Libreria, stato «scaricato» |
|
||||
| H8 | I segnali di arresto si riconoscono da indirizzo e stato HTTP | Da provare (non provocarli di proposito) | Se durante la sonda compare una verifica, annota l'ora e manda la riga ripulita di `navigazioni.jsonl` |
|
||||
| H9 | Un contenuto di una raccolta in evidenza ha lo stesso identificativo che aveva come storia | Da provare | Sonda: apri una raccolta che contiene una storia ancora attiva |
|
||||
| H10 | Identificativo e nome dell'account collegato si ricavano dai dati della pagina, senza leggere i cookie | Da provare | Sonda, pagina iniziale |
|
||||
| H11 | I comandi della pagina si trovano con attributi stabili: ruolo, nome accessibile, forma del collegamento | Da provare; lo scheletro `bersagli.instagram.json` è pronto | Durante tutta la sonda: passa col puntatore sui comandi elencati prima di usarli; manda le sole righe dei comandi, con i nomi di persona sostituiti |
|
||||
|
||||
Finché H1–H11 non sono provate e la mappa dei bersagli e il vocabolario dei lettori non sono compilati sui campioni
|
||||
ripuliti, le ricette su Instagram rispondono «la mappa dei bersagli non è ancora compilata» senza aprire pagine.
|
||||
|
||||
## 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: una raccolta completa (risposte lette, scorrimento e clic arrivati, anteprima del browser in Attività 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) | Una sessione con la finestra «Browser di Febe» nascosta o coperta: le ricette finiscono e i file arrivano. Se non regge, si provano nell'ordine la composizione di WebView2 e poi 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: accedi, «Esci» dall'icona, riapri Febe, stessa verifica |
|
||||
| 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 |
|
||||
| S5 | Chromium in Docker parte con la sua sandbox | Provato in un contenitore (con il Chromium dell'ambiente di sviluppo): col profilo seccomp predefinito non parte, col profilo dedicato di Febe la sandbox è completa. **Da ripetere** con l'immagine vera | Dalla pagina Browser (vista remota) apri `chrome://sandbox` e riferisci se dice «You are adequately sandboxed» |
|
||||
| S6 | Che cosa vede la pagina: `navigator.webdriver`, visibilità, fuoco, lingua, fuso | Provato in locale per Chromium su Xvfb (`webdriver` falso, pagina visibile, `it-IT`, `Europe/Rome`); **da provare** con il Chromium di Debian e in WebView2 | La prova automatica `ThePageSeesAnOrdinaryVisibleBrowser` con `FEBE_CHROMIUM` che punta al Chromium dell'immagine (vedi [Sviluppo](Sviluppo)); per WebView2, la prova equivalente dell'app per Windows |
|
||||
|
||||
## Altre cose da provare dal vivo
|
||||
|
||||
- **Avvisi (M8):** un arresto produce striscia, notifica e messaggio Telegram sul tuo impianto. Procedura nella parte C
|
||||
di `docs/prove-dal-vivo.md`: si fa con il sito di prova, senza Instagram. Le notifiche di Windows si potranno
|
||||
provare quando c'è l'app per Windows.
|
||||
- **Telegram con il tuo bot:** «Invia una prova» in Impostazioni ▸ Notifiche. Le prove automatiche usano solo un
|
||||
Telegram finto: la chiamata vera la fai tu.
|
||||
- **Spazio libero su Unraid:** in Impostazioni ▸ Generali lo spazio libero mostrato per la libreria (spesso una
|
||||
condivisione dell'array) deve essere quello che vedi in Unraid; se non si può misurare, il registro lo dice.
|
||||
- **Esportazione CSV:** il file si apre bene con un doppio clic in Excel in italiano (colonne separate, accenti giusti).
|
||||
- **Libreria di 4K Stogram:** il riconoscitore dei nomi è un'ipotesi. Serve una ventina di nomi di file veri, con i nomi
|
||||
degli account sostituiti (domanda 4 della specifica), per riscriverlo sui dati veri.
|
||||
@@ -0,0 +1,97 @@
|
||||
# Libreria
|
||||
|
||||
La **Libreria** è il mosaico di tutti gli elementi in ordine di pubblicazione, raggruppati per giorno. Resta fluida
|
||||
anche con centinaia di migliaia di elementi: carica a finestre e le miniature si generano una volta sola.
|
||||
|
||||
## Filtri e ricerca
|
||||
|
||||
- **Tipo:** Tutto, Foto, Video, Storie, In evidenza, Taggati. «Foto» e «Video» riguardano i post (un post con almeno
|
||||
una foto, o almeno un video); storie, evidenza e taggati hanno la loro voce. «Tutto» non comprende le foto del
|
||||
profilo, che stanno nella scheda dell'account.
|
||||
- **Account**, **Periodo** (ultimi 7 o 30 giorni, quest'anno, l'anno scorso, oppure dal… al…), **Provenienza**
|
||||
(scaricati da Instagram o importati). Ogni menu mostra il nome del filtro finché non scegli un valore.
|
||||
- **Ricerca** per nome dell'account e testo della didascalia (senza distinguere maiuscole e accenti).
|
||||
- Il cursore accanto a «Seleziona» regola la grandezza delle tessere. Sulle tessere: durata per i video, numero dei file
|
||||
per i post con più file, anello tratteggiato per le storie.
|
||||
|
||||
I nuovi elementi compaiono in cima senza spostare ciò che stai guardando.
|
||||
|
||||
## 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
|
||||
(nome, dimensioni, peso, cartella) e provenienza. Azioni:
|
||||
|
||||
- **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker);
|
||||
- **Apri su Instagram**, nel tuo browser;
|
||||
- **Elimina dalla libreria**.
|
||||
|
||||
## Eliminare
|
||||
|
||||
Eliminare chiede conferma. I file vengono cancellati dal disco e non si recuperano.
|
||||
|
||||
- **«Elimina dalla libreria»** (il predefinito) ricorda la scelta: l'elemento resta nell'elenco come «eliminato» e non
|
||||
viene scaricato di nuovo.
|
||||
- **«Eliminalo e lascia che torni»**: Febe dimentica l'elemento; se è ancora su Instagram, al prossimo controllo lo
|
||||
scarica di nuovo.
|
||||
|
||||
L'eliminazione si scrive prima nel file `_febe.jsonl` dell'account, poi nel database, poi sul disco: anche una
|
||||
ricostruzione del database la rispetta.
|
||||
|
||||
**La libreria non cancella e non sostituisce mai un file da sola.** Se un contenuto sparisce da Instagram, il file
|
||||
resta. Un file si elimina o si sostituisce solo per una scelta tua.
|
||||
|
||||
## Selezione multipla
|
||||
|
||||
«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.
|
||||
|
||||
## Esportare l'elenco in CSV
|
||||
|
||||
Il pulsante con l'icona del documento nella riga degli strumenti, **«Esporta l'elenco»**, scarica in un file CSV
|
||||
l'elenco degli elementi **mostrati dai filtri di adesso** (senza filtri: tutta la libreria). Con la selezione multipla
|
||||
si esportano solo gli elementi scelti.
|
||||
|
||||
Il file si chiama `febe-elementi-AAAA-MM-GG.csv` ed è fatto per aprirsi bene in Excel con le impostazioni italiane:
|
||||
`;` come separatore, codifica UTF-8 con BOM, date e ore locali. Colonne: Account, Tipo, Data, Ora, Codice,
|
||||
Identificativo, Didascalia, Autore, Raccolte, Provenienza, Stato, File, Nomi dei file, Indirizzo. I campi che Excel
|
||||
leggerebbe come formula (che cominciano con `=`, `+`, `-`, `@`) ricevono un apostrofo davanti.
|
||||
|
||||
Il CSV contiene le didascalie: trattalo come i dati che descrive.
|
||||
|
||||
## Doppioni dopo uno scaricamento
|
||||
|
||||
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
|
||||
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.
|
||||
|
||||
## Cartelle e nomi dei file
|
||||
|
||||
- **Libreria:** dove finiscono foto e video, una cartella per account. Può stare su un disco di rete.
|
||||
- **Dati:** database, profilo del browser, miniature, registro, copie. Deve stare su un disco locale.
|
||||
|
||||
Due schemi dei nomi, in Impostazioni ▸ Generali ▸ Nomi dei file, con anteprima del risultato. Predefiniti:
|
||||
|
||||
```text
|
||||
{account}\{tipo}\{anno}\{data}_{ora}_{codice}_{n}
|
||||
{account}\evidenza\{raccolta}\{data}_{ora}_{codice}_{n}
|
||||
|
||||
marta.demo\post\2026\2026-10-10_18-22-05_DBx3kQ2_2.jpg
|
||||
marta.demo\evidenza\Estate 2025\2025-08-02_10-11-12_3391207_1.jpg
|
||||
```
|
||||
|
||||
- Segnaposto: `account`, `tipo`, `anno`, `mese`, `data`, `ora`, `codice`, `n` (posizione del file nell'elemento),
|
||||
`raccolta`. Un segnaposto sconosciuto è un errore.
|
||||
- Data e ora nei nomi sono nel tuo fuso; la data di modifica del file è quella di pubblicazione (si può spegnere).
|
||||
- I nomi sono ripuliti per Windows (caratteri vietati, nomi riservati, punti e spazi finali); un percorso oltre 240
|
||||
caratteri si accorcia prima nel nome del file, poi nelle cartelle. Un nome già occupato diventa `nome (2).ext`: mai
|
||||
una sovrascrittura.
|
||||
- Cambiare lo schema vale per i prossimi file: quelli già salvati non si rinominano.
|
||||
|
||||
Ogni cartella di account ha il suo **`_febe.jsonl`**: una riga per ogni elemento salvato (identificativi, date,
|
||||
didascalia, nomi dei file) e una per ogni eliminazione. Non va modificato né cancellato: è ciò che permette di
|
||||
ricostruire il database (vedi [Copie e ricostruzione](Copie-e-ricostruzione)). La libreria resta una cartella di file
|
||||
normali, leggibile anche senza Febe.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Limiti e comportamento
|
||||
|
||||
Febe non cerca di sembrare un utente qualsiasi: cerca di comportarsi come **te che usi Instagram dal tuo computer**.
|
||||
Stesso dispositivo, stessa rete, orari plausibili, poche visite brevi, pause lunghe, nessuna fretta. La casualità
|
||||
riguarda il comportamento (quando, quanto, in che ordine, a che velocità); l'identità del browser non cambia mai.
|
||||
|
||||
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)).
|
||||
|
||||
Si regola in **Impostazioni ▸ Limiti e comportamento**.
|
||||
|
||||
## I valori sono stime prudenti
|
||||
|
||||
Instagram non pubblica limiti ufficiali. **I valori dei profili sono stime di partenza scelte con prudenza: non sono
|
||||
limiti ufficiali e non sono misure.** Riducono il rischio di rallentamenti e verifiche, senza azzerarlo, e vanno
|
||||
ritoccati guardando che cosa succede.
|
||||
|
||||
## Profili di prudenza
|
||||
|
||||
| | Prudente | Equilibrato | Rapido |
|
||||
|---|---|---|---|
|
||||
| Fascia oraria | 07:30–23:30, spostata ogni giorno fino a ± 40 min | 07:00–24:00, ± 30 min | 06:30–00:30, ± 30 min |
|
||||
| Durata di una sessione | 2–10 min | 3–14 min | 4–18 min |
|
||||
| Pausa tra le sessioni | 20–90 min | 12–60 min | 8–40 min |
|
||||
| Home, all'ora / al giorno | 4 / 30 | 5 / 45 | 6 / 60 |
|
||||
| Profili aperti | 12 / 100 | 20 / 180 | 30 / 300 |
|
||||
| Storie viste | 50 / 300 | 80 / 500 | 120 / 800 |
|
||||
| Pagine di storico | 20 / 100 | 30 / 180 | 45 / 300 |
|
||||
| Post singoli | 10 / 60 | 15 / 100 | 20 / 160 |
|
||||
| Pagine dell'elenco dei seguiti | 15 / 60 | 20 / 90 | 30 / 150 |
|
||||
| Dati scaricati al giorno | 4 GB | 8 GB | 16 GB |
|
||||
| Storico per account al giorno | 300 post | 500 post | 800 post |
|
||||
| Avvio graduale | 7 giorni | 5 giorni | 3 giorni |
|
||||
|
||||
- **«Prudente» è il predefinito e il consigliato.** «Rapido» chiede conferma e porta l'etichetta «Più rischio»:
|
||||
recupera prima, ma rallentamenti e verifiche diventano più probabili.
|
||||
- Se cambi un valore, il profilo diventa **«Su misura»**; scegliendo un profilo torni ai suoi valori.
|
||||
- «Storico per account al giorno» è il valore di partenza del limite che ogni account ha nelle sue impostazioni.
|
||||
- Limiti di ciò che l'interfaccia accetta: pausa minima non sotto i 5 minuti; sessione non oltre i 30; fascia non oltre
|
||||
le 20 ore; nessun tetto oltre il doppio di «Rapido»; almeno un giorno attivo.
|
||||
- I limiti salvati valgono da subito, anche per il motore che sta lavorando.
|
||||
|
||||
## La giornata di Febe
|
||||
|
||||
- **Fascia oraria e giorni.** Febe lavora solo dentro la fascia, con inizio e fine spostati ogni giorno di una quantità
|
||||
casuale (mai uniforme, e lo spostamento non si riestrae a un riavvio), e solo nei giorni attivi (tutti, di partenza).
|
||||
Fuori fascia non apre nulla di sua iniziativa: è tutto fermo, come per una persona che dorme. L'unica eccezione è
|
||||
«Controlla ora» confermato da te.
|
||||
- **Sessioni e pause.** Dentro la fascia l'attività è fatta di sessioni brevi separate da pause. Durate e pause si
|
||||
estraggono ogni volta a caso dentro gli estremi del profilo (distribuzione log-normale), mai uno schema fisso.
|
||||
- **Pavimento.** La pausa minima vale sempre, anche con molto lavoro arretrato: l'arretrato si smaltisce nei giorni,
|
||||
non stringendo le pause.
|
||||
- **Avvio del programma.** La prima sessione parte fra 2 e 10 minuti dopo l'avvio. Tetti e registro delle azioni sono
|
||||
su disco: **un riavvio non azzera nulla**, e un programma che riparte più volte non produce più traffico di uno che
|
||||
resta acceso.
|
||||
- **Composizione di una sessione.** Di norma comincia con il giro della pagina iniziale (i post recenti dei profili che
|
||||
segui e la barra delle storie), prosegue con le storie, poi con i controlli dei profili scaduti, infine con qualche
|
||||
pagina di storico. Circa una sessione su tre si limita al giro e alle storie. L'ordine degli account è estratto a caso
|
||||
con pesi (frequenza e ritardo), mai lo stesso. Lo storico avanza su un solo account per sessione.
|
||||
- **Umore della sessione.** Ogni sessione ha un fattore di velocità estratto una volta: alcune sono svelte, altre lente.
|
||||
- **Riposo.** A fine sessione, nelle pause e di notte il browser sta su una pagina vuota: nessuna pagina di Instagram
|
||||
resta aperta fuori da una sessione.
|
||||
- **Lo storico non corre più veloce degli scaricamenti.** Lo storico di un account si sospende finché quell'account ha
|
||||
più di 60 file in attesa o il tetto dei dati è raggiunto: gli indirizzi dei file scadono, accumularli non serve.
|
||||
|
||||
## Tetti
|
||||
|
||||
Ogni azione verso il sito passa dal **Governatore**, che controlla nell'ordine: interruttore, fascia oraria, sessione
|
||||
in corso, tetto della categoria (giornaliero e orario), distanza minima dall'azione precedente (circa 4 secondi con il
|
||||
ritmo «naturale»), limiti dell'account. Risponde con un permesso o con un rifiuto motivato.
|
||||
|
||||
- I tetti orari valgono sugli ultimi 60 minuti, quelli giornalieri sul giorno di calendario nel tuo fuso.
|
||||
- Sopra l'80% di un tetto il segno diventa ambra. Raggiunto un tetto, quel tipo di attività si ferma fino all'ora o al
|
||||
giorno dopo; le altre proseguono.
|
||||
- Quando valgono insieme più riduzioni (avvio graduale, tetti dimezzati dopo un rallentamento) si applica la più forte,
|
||||
non il loro prodotto.
|
||||
|
||||
## 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%»).
|
||||
|
||||
## Ritmo dei gesti
|
||||
|
||||
Lento, Naturale (predefinito) o Svelto: moltiplica tutte le attese fra un gesto e l'altro. Il puntatore si muove lungo
|
||||
traiettorie curve, lo scorrimento arriva a raffiche con soste di lettura, le storie si guardano per qualche secondo;
|
||||
ogni tanto c'è una distrazione più lunga. Febe non clicca mai nulla che non sia il bersaglio di una ricetta, e se non
|
||||
trova il bersaglio si ferma e lo segnala, invece di provare a caso.
|
||||
|
||||
## Arresti
|
||||
|
||||
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).
|
||||
|
||||
## Giudicare un profilo prima di usarlo
|
||||
|
||||
La simulazione fa girare il motore per 30 giorni (o quanti vuoi) contro un mondo finto e dice sessioni al giorno,
|
||||
azioni per categoria, tempi fra pubblicazione e scoperta, giorni per uno storico di 2.000 post e superamenti dei tetti
|
||||
(devono essere zero). Vedi [Sviluppo](Sviluppo).
|
||||
@@ -0,0 +1,82 @@
|
||||
# Primo collegamento
|
||||
|
||||
Febe lavora con il tuo account Instagram attraverso il **browser di Febe**, in cui accedi tu, a mano, nella vera
|
||||
pagina di Instagram. Password e codici li scrivi tu; Febe non li conserva mai. Ciò che resta è il profilo del browser
|
||||
nella cartella dei dati, con la sessione.
|
||||
|
||||
> Usa prima un **account di prova**. Passa al tuo account principale solo dopo aver visto Febe all'opera, e sempre con
|
||||
> il profilo «Prudente» (vedi [Limiti e comportamento](Limiti-e-comportamento)).
|
||||
|
||||
## Entrare nell'interfaccia (Docker)
|
||||
|
||||
Apri `http://<server>:8480/`: la pagina «Accedi a Febe» chiede la password del contenitore (`FEBE_PASSWORD`). Dopo
|
||||
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à».
|
||||
|
||||
## Collegarsi a Instagram
|
||||
|
||||
Apri **Impostazioni ▸ Collegamento a Instagram** (o «Collegati a Instagram» dal benvenuto). Mentre sei in questa
|
||||
pagina il motore resta fermo.
|
||||
|
||||
**In Docker** la pagina carica subito la vera pagina di accesso di Instagram nella **vista remota**: il riquadro grande
|
||||
è il browser del server, che puoi usare con mouse e tastiera.
|
||||
|
||||
1. Accedi nella pagina: nome utente, password e, se l'hai attivata, la verifica in due passaggi.
|
||||
2. Aspetta la tua pagina iniziale. Se Instagram chiede di salvare l'accesso, accetta.
|
||||
3. Premi **«Ho finito»**: Febe controlla che l'accesso sia riuscito (guarda solo se il cookie di sessione esiste, senza
|
||||
leggerne il valore) e nasconde il browser.
|
||||
|
||||
**Su Windows** il browser è la finestra a parte «Browser di Febe» («Portalo in primo piano» la mostra): accedi lì, poi
|
||||
premi «Ho finito» nella finestra di Febe.
|
||||
|
||||
«Annulla» torna alle impostazioni senza collegarti.
|
||||
|
||||
## La password: due verità diverse
|
||||
|
||||
- **In Docker** la password la scrivi a distanza: i tasti passano dal server di Febe, che li inoltra al browser senza
|
||||
registrarli né salvarli. Ma attraversano la rete di casa e la memoria del server: per questo **la password di
|
||||
Instagram passa dal server**, e l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS
|
||||
(vedi [Sicurezza e riservatezza](Sicurezza-e-riservatezza)).
|
||||
- **Su Windows** la scrivi direttamente nella pagina di Instagram: Febe non la riceve e non la salva.
|
||||
|
||||
In tutti e due i casi resta solo la sessione del browser, nella cartella dei dati: **chi ha la cartella dei dati, o
|
||||
una sua copia, ha la sessione di Instagram.**
|
||||
|
||||
## Dopo il collegamento
|
||||
|
||||
- Il collegamento sopravvive ai riavvii: la sessione è nel profilo del browser (provato in locale; nel contenitore vero
|
||||
e su Windows è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)).
|
||||
- Comincia l'**avvio graduale**: per alcuni giorni i tetti partono dalla metà e risalgono piano (7 giorni con
|
||||
«Prudente»).
|
||||
- La prima sessione parte tra 2 e 10 minuti dopo l'avvio, e solo dentro la fascia oraria.
|
||||
- Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione
|
||||
chiusa.
|
||||
- Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i
|
||||
post in cui sei taggato. (Riconoscere il tuo account dai dati della pagina è l'ipotesi H10, ancora da confermare.)
|
||||
|
||||
Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostazioni).
|
||||
|
||||
## Usare il browser a mano
|
||||
|
||||
Da collegato, **«Usa il browser»** apre il browser di Febe (in Docker la pagina «Browser», con la vista remota e i
|
||||
comandi «Indietro» e «Ricarica»; su Windows la finestra). Serve per controllare qualcosa a mano. Mentre lo usi il
|
||||
motore resta fermo; quando hai finito premi «Ho finito».
|
||||
|
||||
## Scollegarsi
|
||||
|
||||
**«Scollega…»** chiede conferma, ferma il motore e cancella il profilo del browser, con la sessione. Per chiudere la
|
||||
sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna in
|
||||
Collegamento e scollega.
|
||||
|
||||
## Un account, un motore
|
||||
|
||||
Usa un solo Febe per account: il contenitore e la versione per Windows non vanno collegati insieme allo stesso
|
||||
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).
|
||||
@@ -0,0 +1,109 @@
|
||||
# Problemi comuni
|
||||
|
||||
Che cosa vedi, perché succede, che cosa fare. Quasi sempre il primo posto da guardare è il **registro**: in Docker
|
||||
`/dati/registro/febe-AAAA-MM-GG.log` e `docker logs febe`; su Windows la cartella `registro` dentro la cartella dei
|
||||
dati.
|
||||
|
||||
## Avvio e configurazione
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| L'interfaccia mostra solo la pagina «Febe non può partire» con «Manca la password dell'interfaccia» | Imposta `FEBE_PASSWORD` nel contenitore e riavvialo. Fino ad allora motore e browser restano spenti, e nessun dato è perso |
|
||||
| «La cartella dei dati è su un disco di rete» | Collega `/dati` (su Windows la cartella dei dati) a una cartella su un disco locale: su Unraid l'appdata sul disco di cache. SQLite e il profilo del browser in rete si rovinano |
|
||||
| «La cartella dei dati non è scrivibile» | Controlla `PUID`/`PGID` e i permessi della cartella sul server |
|
||||
| Il contenitore si ferma subito con un messaggio su `PUID=0` | Febe non gira come root: usa un utente normale (su Unraid 99/100) |
|
||||
| Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe/seccomp.json`: è il passo 1 dell'[installazione](Installazione-Docker-e-Unraid) |
|
||||
| Nel registro: «Il browser non parte… No usable sandbox» | Il contenitore gira senza il profilo seccomp dedicato: aggiungi `--security-opt seccomp=…` (vedi la sezione sulla sandbox in [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid)) |
|
||||
| La pagina Collegamento dice «Il browser di Febe non è disponibile» | Febe non ha avviato il suo browser: leggi il registro, riavvia; di solito è la sandbox (riga sopra) o la porta di debug occupata |
|
||||
| La porta è occupata | Cambia la porta pubblicata (o `FEBE_PORTA`) |
|
||||
| Unraid non scarica l'immagine | Accedi al registro di Gitea dal terminale: `docker login gitea.encke-hake.ts.net` |
|
||||
| Il browser rifiuta l'interfaccia con un errore 400 sul nome | `FEBE_HOST` è impostata e il nome con cui apri l'interfaccia non è nell'elenco: aggiungilo |
|
||||
| «Password sbagliata» anche con quella giusta, poi «bloccato» | Dopo 5 errori da uno stesso indirizzo (20 in tutto) l'accesso si blocca per 15 minuti: aspetta, poi riprova |
|
||||
| Su Windows: Febe dice che manca WebView2 | Installa il runtime WebView2 dal collegamento che Febe mostra |
|
||||
|
||||
## Collegamento
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| La vista remota è lenta o non risponde | La vista è un'immagine della pagina inviata dal server: aspetta qualche secondo dopo ogni clic. Se dice «La vista remota non risponde», premi «Riprova»; se si apre in un'altra finestra, la precedente si chiude da sola (una vista alla volta) |
|
||||
| «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» |
|
||||
| Dopo un riavvio Febe chiede di nuovo l'accesso | Non dovrebbe: la sessione è nel profilo del browser in `/dati/browser`. Controlla che `/dati` sia un volume persistente e non sia stato cancellato; riferisci il caso (è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)) |
|
||||
|
||||
## Il motore non scarica nulla
|
||||
|
||||
Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti):
|
||||
|
||||
1. **Raccolta da Instagram non ancora attiva.** Se in «Appena fatto» vedi «non può girare su instagram: la mappa dei
|
||||
bersagli non è ancora compilata», è lo stato attuale del progetto: le ricette su Instagram aspettano i risultati
|
||||
della sonda (ipotesi H1–H11, vedi [Ipotesi da verificare](Ipotesi-da-verificare)). Non è un guasto.
|
||||
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.
|
||||
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.
|
||||
7. L'account è **In pausa**, **Solo archivio** o **Non raggiungibile**, oppure ha «Tieni aggiornato» spento ed è già
|
||||
stato scaricato una volta.
|
||||
8. **Disco pieno:** vedi sotto.
|
||||
|
||||
## File e libreria
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| File «da scaricare» che non arrivano | Gli scaricamenti hanno un loro tetto giornaliero di dati; durante un fermo continuano solo quelli già in coda. Un indirizzo scaduto torna «da scaricare» e si recupera rileggendo il post; per le storie scadute non c'è recupero |
|
||||
| Elementi «falliti» | Dopo cinque tentativi non riusciti un file resta «fallito»; anche una storia scaduta prima dello scaricamento finisce così |
|
||||
| Nel visualizzatore: «Il file non è sul disco» | Il file è stato spostato o cancellato fuori da Febe. Rimettilo dov'era o elimina l'elemento |
|
||||
| «N doppioni da decidere» | Foto che sembrano la stessa immagine salvata due volte: decidi tu in «Doppioni da decidere» (vedi [Libreria](Libreria)) |
|
||||
| Un elemento eliminato torna | Hai usato «Eliminalo e lascia che torni»: elimina di nuovo con «Elimina dalla libreria» |
|
||||
| Il CSV si apre male in Excel | Aprilo con doppio clic (non con «Importa testo» impostando un altro separatore): è fatto per Excel in italiano, con `;` e UTF-8 con BOM |
|
||||
|
||||
## Disco quasi pieno
|
||||
|
||||
L'avviso «Disco quasi pieno» arriva quando sul disco della libreria o della cartella dei dati restano meno di 10 GB o
|
||||
meno del 5%. Libera spazio su quel disco. Per spostare la libreria: in Docker cambia il volume `/libreria` (sposta prima
|
||||
i file, con Febe fermo); su Windows usa «Cambia…» in Impostazioni ▸ Generali (i nuovi account vanno nella cartella
|
||||
nuova, quelli vecchi restano dove sono). La cartella dei dati: in Docker sposta il volume `/dati` con il contenitore
|
||||
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:
|
||||
|
||||
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à.
|
||||
|
||||
Non riattivare una ricetta solo per farla ripartire: si sospenderebbe di nuovo dopo tre tentativi.
|
||||
|
||||
## Avvisi
|
||||
|
||||
| Messaggio di «Invia una prova» | Che cosa fare |
|
||||
|---|---|
|
||||
| «Telegram non riconosce il gettone del bot» | Copia di nuovo il gettone per intero dal messaggio di BotFather |
|
||||
| «Il gettone del bot non ha la forma giusta» | Il gettone è fatto di cifre, due punti e una lunga serie di lettere, senza spazi |
|
||||
| «Telegram non trova la chat» | Controlla l'identificativo e scrivi almeno un messaggio al bot prima di riprovare |
|
||||
| «Il bot non può scriverti» | Apri la chat con il bot e premi «Avvia» (o sbloccalo; in un gruppo, aggiungilo) |
|
||||
| «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
|
||||
[Avvisi e Telegram](Avvisi-e-Telegram).
|
||||
|
||||
## Importazione
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| «Sposta» non c'è | La sorgente è in sola lettura (sempre, in Docker con `/importa`): si può solo copiare |
|
||||
| Non trovi la cartella da importare (Docker) | Deve stare dentro il volume `/importa` del contenitore |
|
||||
| La sorgente è rifiutata | È dentro o sopra la cartella dei dati, sopra la libreria o dentro una cartella di account di Febe |
|
||||
| «Importa N file» importa meno file di quanti ne hai | Le cartelle senza account e i doppioni non ancora decisi restano fuori: il pulsante dice quanti |
|
||||
| Date sbagliate su una libreria di 4K Stogram | Il riconoscitore dei nomi di 4K Stogram è un'ipotesi non verificata: rifai l'analisi senza l'opzione, o controlla date e codici nella revisione |
|
||||
|
||||
## Database
|
||||
|
||||
| Che cosa vedi | Che cosa fare |
|
||||
|---|---|
|
||||
| Il database si è rovinato o è sparito | Torna a una copia di `copie/`, oppure ricostruiscilo dalla libreria: vedi [Copie e ricostruzione](Copie-e-ricostruzione) |
|
||||
| «Ricostruisci» è rifiutato | C'è un'importazione in corso: aspetta che finisca |
|
||||
@@ -0,0 +1,88 @@
|
||||
# Sicurezza e riservatezza
|
||||
|
||||
## La sessione di Instagram sta nella cartella dei dati
|
||||
|
||||
Quando accedi a Instagram nel browser di Febe, la sessione resta nel profilo del browser, dentro la cartella dei dati
|
||||
(`/dati/browser` in Docker, `%LOCALAPPDATA%\Febe\browser` su Windows). Febe non la esporta, non la mostra e non la
|
||||
copia altrove.
|
||||
|
||||
- **Chi ha la cartella dei dati, o una sua copia, ha la sessione di Instagram**: può usare il tuo account senza
|
||||
password. Vale anche per i backup che includono quella cartella (il backup dell'appdata di Unraid, un backup del
|
||||
profilo di Windows): trattali come una password.
|
||||
- La cartella dei dati contiene anche il gettone del bot Telegram (nel database e nelle sue copie).
|
||||
- Se pensi che qualcuno abbia avuto la cartella, esci da Instagram su tutti i dispositivi dall'app e cambia la password;
|
||||
poi scollega Febe e ricollegalo.
|
||||
- I cookie non si copiano da una macchina all'altra: ogni Febe fa il suo accesso.
|
||||
|
||||
## Docker: l'interfaccia non va esposta su Internet
|
||||
|
||||
- **Non esporre mai l'interfaccia Docker su Internet** senza una VPN (per esempio WireGuard o Tailscale) o un proxy con
|
||||
HTTPS davanti.
|
||||
- **In Docker la password di Instagram passa dal server.** Dalla vista remota tasti, password e codici attraversano la
|
||||
rete di casa e la memoria del server per arrivare al browser di Febe. Non vengono registrati né conservati, ma su HTTP
|
||||
in chiaro sono leggibili da chi sta sulla stessa rete. Per questo conviene fare l'accesso da una rete di cui ti fidi,
|
||||
o attraverso la VPN o il proxy con HTTPS.
|
||||
- L'interfaccia è protetta da password (`FEBE_PASSWORD`), con un cookie di sessione non leggibile dagli script e
|
||||
limitato allo stesso sito (`HttpOnly`, `SameSite=Strict`), valido 30 giorni; dopo 5 tentativi sbagliati da uno
|
||||
stesso indirizzo, o 20 in tutto in un quarto d'ora, l'accesso si blocca per 15 minuti.
|
||||
- Ogni comando, gli eventi dal server e la vista remota controllano che la richiesta arrivi dall'interfaccia stessa
|
||||
(intestazione `Origin`): un'altra pagina aperta nel tuo browser non può comandare Febe né la vista remota.
|
||||
- `FEBE_HOST` limita i nomi con cui si raggiunge l'interfaccia (difesa in più contro il DNS rebinding);
|
||||
`FEBE_PROXY_FIDATO=1` serve dietro un proxy con HTTPS.
|
||||
- Si pubblica solo la porta dell'interfaccia; la porta di debug del browser resta dentro il contenitore, su `127.0.0.1`.
|
||||
|
||||
## Windows
|
||||
|
||||
Il server di Febe ascolta solo su `127.0.0.1` e accetta richieste solo con un gettone generato a ogni avvio, che conosce
|
||||
solo la finestra di Febe; si controllano anche `Host` e `Origin`. La password di Instagram la scrivi direttamente nella
|
||||
pagina di Instagram, nella finestra «Browser di Febe»: Febe non la riceve.
|
||||
|
||||
## La sandbox di Chromium (Docker)
|
||||
|
||||
Con il profilo seccomp dedicato di Febe (l'impostazione consigliata, già nel modello di Unraid e in `compose.yml`) la
|
||||
sandbox di Chromium è completa: **nessun compromesso**. Il compromesso esiste solo se scegli `FEBE_SENZA_SANDBOX=1`
|
||||
(`--no-sandbox`): una pagina che sfruttasse un difetto del browser non troverebbe la sandbox a fermarla, solo i limiti
|
||||
del contenitore. Si accetta solo perché quel browser visita esclusivamente Instagram, e solo se il profilo seccomp non
|
||||
si può usare. Dettagli in [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid).
|
||||
|
||||
## Il browser di Febe
|
||||
|
||||
- È un browser normale: nessuna modifica di user agent, impronta, lingua, fuso orario o intestazioni; niente modalità
|
||||
senza finestra; niente proxy; nessuna estensione «stealth».
|
||||
- Salvataggio delle password e compilazione automatica sono spenti: nel profilo resta solo la sessione.
|
||||
- Fra una sessione e l'altra sta su una pagina vuota; non segue mai collegamenti che portano fuori da Instagram.
|
||||
- Verso Instagram parla solo il browser di Febe. L'unica altra connessione verso i server di Instagram è lo
|
||||
scaricamento dei file già indicati dalla pagina, dal solo CDN (e oggi passa anch'essa dal browser).
|
||||
|
||||
## Sola lettura
|
||||
|
||||
Febe non mette «mi piace», non segue, non commenta, non scrive messaggi, non reagisce alle storie, non tocca annunci né
|
||||
suggerimenti. L'unica traccia che lascia è quella di una normale visita, **compresa la visualizzazione delle storie:
|
||||
le storie aperte da Febe risultano viste.** Un profilo privato che non ti ha accettato non si tocca.
|
||||
|
||||
## Un account, un motore
|
||||
|
||||
Il contenitore e la versione per Windows **non vanno usati insieme sullo stesso account**: due motori sommano le
|
||||
visite e il rischio.
|
||||
|
||||
## Che cosa finisce nei registri
|
||||
|
||||
Il registro contiene azioni ed esiti: nomi utente sì; didascalie, corpi delle risposte, password, cookie, tasti,
|
||||
indirizzi firmati dei file, gettoni (compreso quello di Telegram) no. Il client del browser registra solo i nomi dei
|
||||
comandi, mai i loro parametri. Il registro è nella cartella dei dati (`registro`), un file al giorno, tenuto
|
||||
quattordici giorni.
|
||||
|
||||
## Che cosa esce da Febe
|
||||
|
||||
| Verso | Che cosa | Quando |
|
||||
|---|---|---|
|
||||
| Instagram | Le visite del browser di Febe, con la tua sessione | Nelle sessioni, dentro la fascia |
|
||||
| CDN di Instagram | Lo scaricamento dei file indicati dalla pagina | Quando ci sono file in coda |
|
||||
| Telegram (`api.telegram.org`) | Il testo degli avvisi | Solo se hai configurato il bot |
|
||||
|
||||
Nient'altro: niente statistiche, niente aggiornamenti automatici, nessun carattere o icona caricato dalla rete.
|
||||
|
||||
## I contenuti restano dei loro autori
|
||||
|
||||
Febe è un archivio privato: non ripubblica e non condivide nulla. Le esportazioni CSV contengono le didascalie:
|
||||
trattale come i dati che descrivono.
|
||||
@@ -0,0 +1,155 @@
|
||||
# Sviluppo
|
||||
|
||||
Febe è scritto in C# 14 su .NET 10, in un'unica soluzione (`Febe.slnx`). L'interfaccia è HTML, CSS e JavaScript senza
|
||||
framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte prese strada facendo sono in
|
||||
`docs/decisioni.md`, lo stato del lavoro in `docs/stato.md`.
|
||||
|
||||
## Due regole prima di tutto
|
||||
|
||||
- **Nessuna prova, script o verifica contatta Instagram** (né Meta, né il loro CDN): si usa solo il sito di prova
|
||||
locale. Le prove dal vivo le lancia Alberto. Lo stesso vale per **Telegram**: le prove usano un gestore HTTP finto,
|
||||
mai `api.telegram.org`.
|
||||
- **Dipendenze a elenco chiuso** (`Directory.Packages.props`): Microsoft.Data.Sqlite, SkiaSharp (con le librerie native
|
||||
per Linux), Microsoft.Web.WebView2, MSTest. Tutto il resto viene dalla libreria di base di .NET.
|
||||
|
||||
## Com'è fatto il repository
|
||||
|
||||
| Cartella | Che cosa c'è |
|
||||
|---|---|
|
||||
| `src/Febe.Core` | Dominio e logica senza piattaforma: motore, Governatore, interruttore, ricette, lettori, libreria, importazione, avvisi (`Alerts/`) |
|
||||
| `src/Febe.Data` | SQLite, migrazioni come file SQL numerati, scrittore unico |
|
||||
| `src/Febe.Browser` | Client del protocollo DevTools, `ChromiumProcessHost`, gesti, cattura delle risposte, vista remota |
|
||||
| `src/Febe.Web` | API, eventi dal server, interfaccia in `wwwroot/` incorporata nell'assembly (vedi `src/Febe.Web/LEGGIMI.md`) |
|
||||
| `src/Febe.Server` | L'eseguibile per Linux e Docker (`febe`), con la dimostrazione e la simulazione |
|
||||
| `src/Febe.Desktop` | L'eseguibile per Windows (WPF, WebView2) |
|
||||
| `tests/Febe.Tests` | Le prove (MSTest), con i campioni ripuliti in `tests/campioni/` |
|
||||
| `tools/Febe.SitoDiProva` | Il sito locale per le prove senza Instagram |
|
||||
| `tools/Febe.Sonda` | La sonda passiva per raccogliere i campioni |
|
||||
| `tools/schermate` | Le schermate dell'interfaccia per il confronto con i mockup |
|
||||
| `docker/` | `Dockerfile`, `compose.yml`, `entrypoint.sh`, file di Chromium (criteri, profilo seccomp), modello di Unraid |
|
||||
| `docs/` | Specifica, decisioni, stato, Docker, prove dal vivo, esiti della sonda, mockup, schermate, e questa guida (`docs/guida/`) |
|
||||
|
||||
## Compilare e provare
|
||||
|
||||
```sh
|
||||
dotnet build Febe.slnx -warnaserror
|
||||
dotnet test tests/Febe.Tests
|
||||
dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Alerts"
|
||||
```
|
||||
|
||||
- Gli avvisi del compilatore sono errori. `Febe.Desktop` si compila anche da Linux (`EnableWindowsTargeting`), ma gira
|
||||
solo su Windows.
|
||||
- Le prove con un browser vero cercano Chromium in `FEBE_CHROMIUM` (o nel `PATH`) e Xvfb nel `PATH`; se mancano
|
||||
risultano inconcludenti, non fallite. Lo stesso per le prove d'insieme del server (`Febe.Tests.Server`), che avviano
|
||||
la composizione vera contro il sito di prova.
|
||||
- Il motore si prova con un orologio virtuale e un seme fisso; le prove d'insieme con un orologio compresso (10×).
|
||||
- La prova `Febe.Tests.Docs` controlla che questa guida dica tutto ciò che la specifica chiede (§15) e che ogni
|
||||
collegamento fra le pagine porti a una pagina che esiste.
|
||||
|
||||
## Dimostrazione
|
||||
|
||||
```sh
|
||||
dotnet run --project src/Febe.Server -- --demo [--porta 8480] [--fuso Europe/Rome]
|
||||
```
|
||||
|
||||
Parte senza browser e senza rete, solo su `127.0.0.1` e senza password, con una libreria temporanea di account finti
|
||||
(`.demo`), immagini generate e un motore finto; la cartella si cancella alla chiusura. Non scrive mai nella libreria
|
||||
vera e non invia messaggi Telegram.
|
||||
|
||||
- Scene: `?scena=normale`, `sessione`, `fermo`, `scollegato`, `errore`; tema `?tema=chiaro` o `scuro`; veste
|
||||
`?veste=desktop` o `docker`.
|
||||
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/importa?passo=3`, `/doppioni`.
|
||||
- Per modificare l'interfaccia senza ricompilare:
|
||||
`FEBE_INTERFACCIA=$PWD/src/Febe.Web/wwwroot dotnet run --project src/Febe.Server -- --demo`, poi basta ricaricare.
|
||||
|
||||
## Simulazione
|
||||
|
||||
```sh
|
||||
dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente [--csv resoconto.csv] [--seme 7]
|
||||
```
|
||||
|
||||
Fa girare il motore vero con l'orologio virtuale contro un mondo finto (40 account, 25 seguiti, uno con uno storico di
|
||||
2.000 post, qualche rallentamento a caso) e scrive il resoconto: sessioni al giorno, azioni per categoria al giorno e
|
||||
nell'ora peggiore, tempo medio e massimo fra pubblicazione e scoperta, giorni per lo storico, superamenti dei tetti
|
||||
(devono essere zero). Profili: `prudente`, `equilibrato`, `rapido`. È il modo per giudicare un profilo prima di usarlo.
|
||||
|
||||
## Il sito di prova
|
||||
|
||||
```sh
|
||||
dotnet run --project tools/Febe.SitoDiProva -- --porta 8481 --porta-cdn 8482
|
||||
```
|
||||
|
||||
Un sito locale con pagine spoglie e dati sintetici (`alberto.prova`, `marta.prova`, …): pagina iniziale con barra delle
|
||||
storie, profili con griglia che carica scorrendo, visualizzatore delle storie e delle raccolte, elenco dei seguiti, post
|
||||
singoli, e i casi di arresto. Non somiglia a Instagram e non ha pagine di accesso. I casi di arresto si comandano da
|
||||
fuori: `/_controllo/modo?valore=troppe-richieste|verifica|sessione-scaduta|vuoto|formato-sconosciuto|normale`.
|
||||
Dettagli in `tools/Febe.SitoDiProva/LEGGIMI.md`.
|
||||
|
||||
Il server vero contro il sito di prova (mai Instagram):
|
||||
|
||||
```sh
|
||||
FEBE_PASSWORD=prova dotnet run --project src/Febe.Server -- \
|
||||
--dati /tmp/febe/dati --libreria /tmp/febe/libreria --importa /tmp/febe/importa --ascolta 127.0.0.1 \
|
||||
--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 5
|
||||
```
|
||||
|
||||
`--sito-di-prova` accetta solo indirizzi di questo computer; `--accesso-di-prova` apre il sito una volta all'avvio,
|
||||
così il suo cookie di sessione esiste come dopo un accesso; `--prima-sessione N` fa partire la prima sessione dopo N
|
||||
secondi. Come root servono `--senza-sandbox` e, se Chromium non è nel `PATH`, `FEBE_CHROMIUM`. Per provare gli avvisi:
|
||||
imposta Telegram in Impostazioni ▸ Notifiche e chiedi al sito una verifica con `/_controllo/modo?valore=verifica`.
|
||||
|
||||
## La sonda
|
||||
|
||||
```sh
|
||||
febe-sonda registra --cartella <fuori dal repository> [--display :0 | --xvfb] [--chromium <file>]
|
||||
febe-sonda ripulisci --da <grezzi> --a <ripuliti>
|
||||
febe-sonda verifica --grezzi <grezzi> --ripuliti <ripuliti>
|
||||
```
|
||||
|
||||
(oppure `dotnet run --project tools/Febe.Sonda -- …`). È passiva: apre il browser e registra ciò che la pagina riceve
|
||||
mentre navighi tu; non compie gesti. I campioni grezzi stanno fuori dal repository, contengono dati di altre persone e
|
||||
si cancellano dopo l'uso; nel repository entrano solo i campioni ripuliti. La procedura completa è la parte A di
|
||||
`docs/prove-dal-vivo.md`; vedi anche [Ipotesi da verificare](Ipotesi-da-verificare).
|
||||
|
||||
## Schermate
|
||||
|
||||
`bash tools/schermate/tutte.sh 8490` rifà le schermate di `docs/schermate/` da una dimostrazione avviata su quella
|
||||
porta, per il confronto con i mockup (§10.7 della specifica); le differenze rimaste sono in
|
||||
`docs/schermate/differenze.md`. Lo strumento accetta solo indirizzi di questo computer.
|
||||
|
||||
## Immagine Docker
|
||||
|
||||
```sh
|
||||
docker build -f docker/Dockerfile -t febe .
|
||||
```
|
||||
|
||||
La compilazione e tutte le prove girano dentro la costruzione dell'immagine (quelle con il browser vero lì si saltano
|
||||
da sole). Vedi [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid) e `docs/docker.md`.
|
||||
|
||||
## CI e rilascio
|
||||
|
||||
Il repository è sul Gitea di casa (<https://gitea.encke-hake.ts.net/Alby96/Febe>); la CI usa Gitea Actions in
|
||||
`.gitea/workflows/`:
|
||||
|
||||
- `verifica.yml`, a ogni push e pull request: compilazione con gli avvisi come errori, tutte le prove, costruzione
|
||||
dell'immagine Docker (senza pubblicarla) e due controlli sull'immagine (Chromium presente, lingua italiana generata);
|
||||
- `rilascio.yml`, a ogni tag `vX.Y.Z`: immagine Docker sul registro di Gitea, installatore Windows e release. Al 13
|
||||
ottobre 2026 è in preparazione: se il file non c'è ancora in `.gitea/workflows/`, il rilascio non è automatico.
|
||||
|
||||
La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
|
||||
|
||||
## La guida
|
||||
|
||||
Le pagine di questa guida sono i file di `docs/guida/`, una pagina del wiki per file (`_Sidebar.md` è la navigazione).
|
||||
Il wiki di Gitea è un repository git a parte: per pubblicarla si copiano i file in
|
||||
`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`.
|
||||
|
||||
## Convenzioni
|
||||
|
||||
- Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano (glossario: appendice D della specifica).
|
||||
- Nel motore mai `DateTime.Now`, `Task.Delay` o `Random` diretti: si usano `IClock` e `IRandomSource`.
|
||||
- Mai password, cookie, tasti, gettoni o corpi di risposta nei registri; il client DevTools registra solo i nomi dei
|
||||
comandi. Gli indirizzi verso Telegram contengono il gettone del bot: non si registrano mai.
|
||||
- La libreria non cancella e non sostituisce file da sola.
|
||||
- Una scelta tecnica nuova si scrive in `docs/decisioni.md` con data e motivo.
|
||||
@@ -0,0 +1,23 @@
|
||||
**[Febe](Home)**
|
||||
|
||||
**Installare**
|
||||
- [Docker e Unraid](Installazione-Docker-e-Unraid)
|
||||
- [Windows](Installazione-Windows)
|
||||
- [Primo collegamento](Primo-collegamento)
|
||||
|
||||
**Usare Febe**
|
||||
- [Account e impostazioni](Account-e-impostazioni)
|
||||
- [Libreria](Libreria)
|
||||
- [Importazione](Importazione)
|
||||
- [Limiti e comportamento](Limiti-e-comportamento)
|
||||
- [Attività e arresti](Attivita-e-arresti)
|
||||
- [Avvisi e Telegram](Avvisi-e-Telegram)
|
||||
|
||||
**Tenere al sicuro**
|
||||
- [Copie e ricostruzione](Copie-e-ricostruzione)
|
||||
- [Sicurezza e riservatezza](Sicurezza-e-riservatezza)
|
||||
- [Problemi comuni](Problemi-comuni)
|
||||
|
||||
**Prove e sviluppo**
|
||||
- [Ipotesi da verificare](Ipotesi-da-verificare)
|
||||
- [Sviluppo](Sviluppo)
|
||||
@@ -124,3 +124,63 @@ Scopo: vedere Febe fare una sessione vera, piccola, con il profilo **Prudente**,
|
||||
|
||||
Febe si ferma da sola al primo segnale e non riparte senza «Riprendi». Non premere «Riprendi» prima di aver
|
||||
risolto a mano nel browser e di avermi riferito che cosa è successo.
|
||||
|
||||
---
|
||||
|
||||
## C. Avvisi dopo M8: un arresto produce striscia, notifica e messaggio
|
||||
|
||||
Scopo: vedere sul tuo impianto che un arresto arriva in tutti i canali (specifica §13.3, «Fatto quando» di M8). **Non
|
||||
serve Instagram e non va provocato su Instagram**: l'arresto lo produce il sito di prova locale.
|
||||
|
||||
### C1. Condizioni
|
||||
|
||||
- Un bot Telegram tuo, con gettone e identificativo della chat (procedura nella guida, pagina «Avvisi e Telegram»).
|
||||
- Una macchina con il repository, .NET 10, Chromium e Xvfb (la stessa delle prove di sviluppo). Le notifiche di
|
||||
Windows si provano quando c'è l'app per Windows (vedi C4).
|
||||
|
||||
### C2. Passi
|
||||
|
||||
1. Avvia il sito di prova e Febe contro di lui (cartelle temporanee, mai quelle vere):
|
||||
|
||||
```sh
|
||||
dotnet run --project tools/Febe.SitoDiProva -- --porta 8481 --porta-cdn 8482
|
||||
FEBE_PASSWORD=prova dotnet run --project src/Febe.Server -- \
|
||||
--dati /tmp/febe-m8/dati --libreria /tmp/febe-m8/libreria --importa /tmp/febe-m8/importa --ascolta 127.0.0.1 \
|
||||
--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 5
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```sh
|
||||
curl 'http://127.0.0.1:8481/_controllo/modo?valore=verifica'
|
||||
```
|
||||
|
||||
5. Alla prossima azione verso il sito Febe si ferma.
|
||||
|
||||
### C3. 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.
|
||||
- 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».
|
||||
**Nessuna riga** contiene il gettone o l'indirizzo di Telegram.
|
||||
- Poi: `curl 'http://127.0.0.1:8481/_controllo/modo?valore=normale'`, «Apri il browser», «Ho finito», «Riprendi».
|
||||
Ripeti il passo 4 alla sessione successiva (parte 2–10 minuti dopo «Riprendi»): la striscia torna, ma il messaggio
|
||||
Telegram **non** si ripete, perché sono passati meno di 30 minuti dal primo.
|
||||
- Facoltativo: `valore=troppe-richieste` produce «Instagram ha chiesto di rallentare» (striscia ambra e messaggio) e,
|
||||
un'ora dopo, «Fine del fermo per rallentamento».
|
||||
|
||||
### C4. Notifiche di Windows (quando c'è l'app per Windows)
|
||||
|
||||
In Impostazioni ▸ Notifiche accendi «Notifiche di Windows» e premi «Invia una prova»: la notifica compare nell'angolo
|
||||
dello schermo. La notifica di un arresto vero arriverà con la prima verifica o il primo rallentamento.
|
||||
|
||||
### C5. 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).
|
||||
- Nel contenitore su Unraid: il risultato di «Invia una prova» (dice se il contenitore raggiunge Telegram).
|
||||
@@ -0,0 +1,220 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Alerts;
|
||||
|
||||
/// <summary>The alerts of spec §13.3, one per kind of event worth telling Alberto about outside the interface.</summary>
|
||||
public enum AlertKind
|
||||
{
|
||||
/// <summary>«Verifica richiesta»: stopped, needs Alberto in the browser and «Riprendi».</summary>
|
||||
Verification,
|
||||
|
||||
/// <summary>«Disconnessione»: the Instagram session is gone, needs a new login and «Riprendi».</summary>
|
||||
Disconnection,
|
||||
|
||||
/// <summary>«Fermo per rallentamento»: timed stop after a throttle.</summary>
|
||||
ThrottleStop,
|
||||
|
||||
/// <summary>«…e ripresa»: the timed stop is over and Febe works again.</summary>
|
||||
ThrottleEnd,
|
||||
|
||||
/// <summary>«Storico di un account completato».</summary>
|
||||
BackfillDone,
|
||||
|
||||
/// <summary>«Formato non riconosciuto»: a reader met an unknown shape.</summary>
|
||||
UnknownFormat,
|
||||
|
||||
/// <summary>A recipe suspended after three problems in a row (same switch as <see cref="UnknownFormat"/>).</summary>
|
||||
RecipeSuspended,
|
||||
|
||||
/// <summary>«Disco quasi pieno»: the library or the Data folder is running out of space.</summary>
|
||||
DiskLow,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One alert: what happened (<see cref="Title"/>), what Febe did and what Alberto should do (<see cref="Message"/>),
|
||||
/// both short Italian sentences. Never contains captions, cookies, tokens or signed addresses.
|
||||
/// </summary>
|
||||
/// <param name="Kind">Which alert.</param>
|
||||
/// <param name="At">When the event happened.</param>
|
||||
/// <param name="Title">«Instagram chiede una verifica».</param>
|
||||
/// <param name="Message">«Ho fermato tutto alle 14:32 e non riparto da solo. Che cosa fare: …».</param>
|
||||
/// <param name="Key">De-duplication key inside the kind (an account, a set of folders); empty for one per kind.</param>
|
||||
/// <param name="AccountId">Account concerned, if any.</param>
|
||||
public sealed record Alert(AlertKind Kind, DateTimeOffset At, string Title, string Message, string Key = "", long? AccountId = null)
|
||||
{
|
||||
/// <summary>The text of a Telegram message: title on the first line, then the message.</summary>
|
||||
public string TelegramText => "Febe · " + Title + "\n" + Message;
|
||||
}
|
||||
|
||||
/// <summary>Outcome of one channel for one alert.</summary>
|
||||
/// <param name="Sent">The channel accepted the alert.</param>
|
||||
/// <param name="Problem">Italian reason when not sent; never contains addresses or tokens.</param>
|
||||
public sealed record AlertDelivery(bool Sent, string? Problem = null)
|
||||
{
|
||||
public static AlertDelivery Ok { get; } = new(true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A way to reach Alberto outside the interface: Telegram, Windows notifications. The red strip of the interface is not
|
||||
/// a channel: it is always there (the engine snapshot, spec §13.3).
|
||||
/// </summary>
|
||||
public interface IAlertChannel
|
||||
{
|
||||
/// <summary>Italian name for the log and the timeline: «Telegram», «notifica di Windows».</summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>The channel is available here and switched on in the settings.</summary>
|
||||
bool IsEnabled(AlertSettings settings);
|
||||
|
||||
/// <summary>Sends the alert. Never throws for delivery problems: they come back as <see cref="AlertDelivery.Problem"/>.</summary>
|
||||
Task<AlertDelivery> SendAsync(Alert alert, AlertSettings settings, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Levels of the alert service's own log lines.</summary>
|
||||
public enum AlertLogLevel
|
||||
{
|
||||
Information,
|
||||
Warning,
|
||||
}
|
||||
|
||||
/// <summary>Event codes written by the alert service (the others come from the engine, <see cref="EngineEventCodes"/>).</summary>
|
||||
public static class AlertEventCodes
|
||||
{
|
||||
/// <summary>The library or the Data folder is almost full (spec §13.3).</summary>
|
||||
public const string DiskLow = "disco-quasi-pieno";
|
||||
|
||||
/// <summary>An alert could not be delivered on a channel (never an alert itself).</summary>
|
||||
public const string DeliveryFailed = "avviso-non-inviato";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Which timeline events are alerts, their titles, texts, switches and minimum intervals. The intervals keep a
|
||||
/// flapping state from sending the same message again and again: the interface still shows every event.
|
||||
/// </summary>
|
||||
public static class AlertCatalog
|
||||
{
|
||||
/// <summary>Codes shown in the «Avvisi» list of Attività: the alerts and the failed deliveries.</summary>
|
||||
public static IReadOnlyList<string> Codes { get; } =
|
||||
[
|
||||
EngineEventCodes.ChallengeStop,
|
||||
EngineEventCodes.DisconnectStop,
|
||||
EngineEventCodes.ThrottleStop,
|
||||
EngineEventCodes.ThrottleEnd,
|
||||
EngineEventCodes.BackfillCompleted,
|
||||
EngineEventCodes.FormatUnrecognized,
|
||||
EngineEventCodes.RecipeSuspended,
|
||||
AlertEventCodes.DiskLow,
|
||||
AlertEventCodes.DeliveryFailed,
|
||||
];
|
||||
|
||||
/// <summary>The alert kind of a timeline event code, if it is one.</summary>
|
||||
public static AlertKind? KindOf(string? code) => code switch
|
||||
{
|
||||
EngineEventCodes.ChallengeStop => AlertKind.Verification,
|
||||
EngineEventCodes.DisconnectStop => AlertKind.Disconnection,
|
||||
EngineEventCodes.ThrottleStop => AlertKind.ThrottleStop,
|
||||
EngineEventCodes.ThrottleEnd => AlertKind.ThrottleEnd,
|
||||
EngineEventCodes.BackfillCompleted => AlertKind.BackfillDone,
|
||||
EngineEventCodes.FormatUnrecognized => AlertKind.UnknownFormat,
|
||||
EngineEventCodes.RecipeSuspended => AlertKind.RecipeSuspended,
|
||||
AlertEventCodes.DiskLow => AlertKind.DiskLow,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>What happened, in a few words: the title of the notification.</summary>
|
||||
public static string Title(AlertKind kind) => kind switch
|
||||
{
|
||||
AlertKind.Verification => "Instagram chiede una verifica",
|
||||
AlertKind.Disconnection => "Instagram ha chiuso la sessione",
|
||||
AlertKind.ThrottleStop => "Instagram ha chiesto di rallentare",
|
||||
AlertKind.ThrottleEnd => "Fine del fermo per rallentamento",
|
||||
AlertKind.BackfillDone => "Storico completato",
|
||||
AlertKind.UnknownFormat => "Formato non riconosciuto",
|
||||
AlertKind.RecipeSuspended => "Ricetta sospesa",
|
||||
AlertKind.DiskLow => "Disco quasi pieno",
|
||||
_ => "Avviso di Febe",
|
||||
};
|
||||
|
||||
/// <summary>The switch of Impostazioni ▸ Notifiche that governs the kind.</summary>
|
||||
public static bool IsWanted(AlertKind kind, AlertEvents events)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(events);
|
||||
return kind switch
|
||||
{
|
||||
AlertKind.Verification => events.Verification,
|
||||
AlertKind.Disconnection => events.Disconnection,
|
||||
AlertKind.ThrottleStop or AlertKind.ThrottleEnd => events.Throttle,
|
||||
AlertKind.BackfillDone => events.BackfillDone,
|
||||
AlertKind.UnknownFormat or AlertKind.RecipeSuspended => events.UnknownFormat,
|
||||
AlertKind.DiskLow => events.DiskLow,
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Minimum time between two sends of the same alert (same kind and key). A verification right after a «Riprendi»
|
||||
/// does not reach Alberto twice in half an hour: he is at the computer and the strip shows it.
|
||||
/// </summary>
|
||||
public static TimeSpan MinimumInterval(AlertKind kind) => kind switch
|
||||
{
|
||||
AlertKind.Verification or AlertKind.Disconnection => TimeSpan.FromMinutes(30),
|
||||
AlertKind.ThrottleStop or AlertKind.ThrottleEnd => TimeSpan.FromMinutes(30),
|
||||
AlertKind.BackfillDone => TimeSpan.FromHours(24),
|
||||
AlertKind.UnknownFormat or AlertKind.RecipeSuspended => TimeSpan.FromHours(6),
|
||||
AlertKind.DiskLow => TimeSpan.FromHours(20),
|
||||
_ => TimeSpan.FromHours(1),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The alert of a timeline event: the title of the kind and a message that says what Febe did and what to do.
|
||||
/// The engine's own message is reused where it carries the facts (end of a stop, account, number of posts).
|
||||
/// </summary>
|
||||
public static Alert FromEvent(AlertKind kind, EventRecord record, TimeZoneInfo zone, string? key = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(record);
|
||||
ArgumentNullException.ThrowIfNull(zone);
|
||||
var at = ItalianText.At(record.At, zone);
|
||||
var message = kind switch
|
||||
{
|
||||
AlertKind.Verification =>
|
||||
$"Ho fermato tutto {at} e non riparto da solo. Che cosa fare: apri Febe, poi il browser di Febe («Apri il browser»), completa la verifica a mano e premi «Riprendi».",
|
||||
AlertKind.Disconnection =>
|
||||
$"La sessione di Instagram non c'è più: ho fermato tutto {at} e non provo a rientrare. Che cosa fare: apri Febe, poi il browser di Febe («Apri il browser»), accedi a mano e premi «Riprendi».",
|
||||
AlertKind.ThrottleStop => WithoutTitle(record.Message, Title(kind)) + " Non devi fare nulla: riparto da solo. Se succede spesso, scegli un profilo più prudente o segui meno account.",
|
||||
AlertKind.ThrottleEnd => WithoutTitle(record.Message, Title(kind)) + " Non devi fare nulla.",
|
||||
AlertKind.BackfillDone => record.Message,
|
||||
AlertKind.UnknownFormat => record.Message
|
||||
+ " Se succede tre volte di fila, quella ricetta si sospende: allora serve un campione nuovo con la sonda (guida, «Problemi comuni»).",
|
||||
_ => record.Message,
|
||||
};
|
||||
return new Alert(kind, record.At, Title(kind), message, key ?? DefaultKey(kind, record), record.AccountId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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à).
|
||||
/// </summary>
|
||||
private static string WithoutTitle(string message, string title)
|
||||
{
|
||||
if (!message.StartsWith(title, StringComparison.Ordinal))
|
||||
{
|
||||
return message;
|
||||
}
|
||||
|
||||
var rest = message[title.Length..];
|
||||
if (rest.StartsWith(" (segnale ", StringComparison.Ordinal) && rest.IndexOf(')', StringComparison.Ordinal) is > 0 and var close)
|
||||
{
|
||||
rest = rest[(close + 1)..];
|
||||
}
|
||||
|
||||
rest = rest.TrimStart('.', ':', ' ');
|
||||
return rest.Length == 0 ? message : char.ToUpperInvariant(rest[0]) + rest[1..];
|
||||
}
|
||||
|
||||
private static string DefaultKey(AlertKind kind, EventRecord record) => kind switch
|
||||
{
|
||||
AlertKind.BackfillDone => record.AccountId?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty,
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Alerts;
|
||||
|
||||
/// <summary>Options of <see cref="AlertService"/>.</summary>
|
||||
public sealed record AlertServiceOptions
|
||||
{
|
||||
/// <summary>Folders whose disk is watched (library and Data folder); empty for none.</summary>
|
||||
public IReadOnlyList<WatchedFolder> Folders { get; init; } = [];
|
||||
|
||||
public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe();
|
||||
|
||||
public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default;
|
||||
|
||||
/// <summary>Time between two checks of the free space.</summary>
|
||||
public TimeSpan DiskCheckInterval { get; init; } = TimeSpan.FromMinutes(15);
|
||||
|
||||
/// <summary>Time from <see cref="AlertService.WatchDiskSpaceAsync"/> to the first check.</summary>
|
||||
public TimeSpan FirstDiskCheckDelay { get; init; } = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>While a disk stays almost full, the timeline line (and the alert) comes back this often.</summary>
|
||||
public TimeSpan DiskReminder { get; init; } = TimeSpan.FromHours(24);
|
||||
|
||||
/// <summary>At most one «avviso non inviato» line per channel in this time.</summary>
|
||||
public TimeSpan FailureEventInterval { get; init; } = TimeSpan.FromHours(1);
|
||||
|
||||
/// <summary>The service's own log lines (never addresses, tokens or message bodies).</summary>
|
||||
public Action<AlertLogLevel, string>? Log { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The alerts of spec §13.3. It listens to the engine's timeline (<see cref="EngineEvents"/>: the circuit breaker's
|
||||
/// 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à.
|
||||
/// <list type="bullet">
|
||||
/// <item>Same kind and key within <see cref="AlertCatalog.MinimumInterval"/>: not sent again (the times are kept in the
|
||||
/// settings, so a restart does not send it again either).</item>
|
||||
/// <item>A channel that fails writes one «avviso non inviato» line (at most one per hour per channel), with the
|
||||
/// Italian reason only: never the address, the token or the answer of the service.</item>
|
||||
/// <item>Alerts go out one at a time, in order, off the engine's threads.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class AlertService : IDisposable
|
||||
{
|
||||
private const string LastSentPrefix = "avvisi.inviato.";
|
||||
|
||||
private readonly ISettingsStore _settings;
|
||||
private readonly IClock _clock;
|
||||
private readonly EngineEvents _events;
|
||||
private readonly IReadOnlyList<IAlertChannel> _channels;
|
||||
private readonly AlertServiceOptions _options;
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, DateTimeOffset> _lastSent = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, DateTimeOffset> _lastFailureEvent = new(StringComparer.Ordinal);
|
||||
private Task _tail = Task.CompletedTask;
|
||||
private bool _attached;
|
||||
private string _diskKey = string.Empty;
|
||||
private DateTimeOffset? _diskWrittenAt;
|
||||
private bool _disposed;
|
||||
|
||||
public AlertService(ISettingsStore settings, IClock clock, EngineEvents events, IEnumerable<IAlertChannel> channels, AlertServiceOptions? options = null)
|
||||
{
|
||||
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
_events = events ?? throw new ArgumentNullException(nameof(events));
|
||||
ArgumentNullException.ThrowIfNull(channels);
|
||||
_channels = [.. channels];
|
||||
_options = options ?? new AlertServiceOptions();
|
||||
}
|
||||
|
||||
/// <summary>Raised after an alert has been handled (sent, suppressed or not wanted), for tests and diagnostics.</summary>
|
||||
public event EventHandler<AlertOutcome>? Handled;
|
||||
|
||||
/// <summary>Starts listening to the engine's timeline. Idempotent.</summary>
|
||||
public AlertService Attach()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_attached || _disposed)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
_attached = true;
|
||||
}
|
||||
|
||||
_events.Notified += OnNotified;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Raises an alert directly (not from the timeline).</summary>
|
||||
public Task RaiseAsync(Alert alert)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(alert);
|
||||
return Enqueue(alert);
|
||||
}
|
||||
|
||||
/// <summary>Waits until every alert raised so far has been handled.</summary>
|
||||
public async Task FlushAsync()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Task tail;
|
||||
lock (_gate)
|
||||
{
|
||||
tail = _tail;
|
||||
}
|
||||
|
||||
await tail.ConfigureAwait(false);
|
||||
lock (_gate)
|
||||
{
|
||||
if (ReferenceEquals(tail, _tail))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks the free space of the watched folders now. When a disk is almost full it writes a warning line in the
|
||||
/// timeline (that line becomes the alert): when the set of full disks changes, and again every
|
||||
/// <see cref="AlertServiceOptions.DiskReminder"/> while it stays so.
|
||||
/// </summary>
|
||||
public async Task<DiskCheck> CheckDiskSpaceAsync(CancellationToken ct = default)
|
||||
{
|
||||
var low = new List<(WatchedFolder, FreeSpace)>();
|
||||
var unmeasured = new List<WatchedFolder>();
|
||||
foreach (var folder in _options.Folders)
|
||||
{
|
||||
var space = _options.FreeSpace.Measure(folder.Path);
|
||||
if (space is null)
|
||||
{
|
||||
unmeasured.Add(folder);
|
||||
}
|
||||
else if (_options.Thresholds.IsLow(space))
|
||||
{
|
||||
low.Add((folder, space));
|
||||
}
|
||||
}
|
||||
|
||||
var check = new DiskCheck(low, unmeasured);
|
||||
var now = _clock.Now;
|
||||
bool write;
|
||||
lock (_gate)
|
||||
{
|
||||
if (low.Count == 0)
|
||||
{
|
||||
_diskKey = string.Empty;
|
||||
_diskWrittenAt = null;
|
||||
write = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
write = check.Key != _diskKey || _diskWrittenAt is not { } written || now - written >= _options.DiskReminder;
|
||||
if (write)
|
||||
{
|
||||
_diskKey = check.Key;
|
||||
_diskWrittenAt = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (write)
|
||||
{
|
||||
await _events.WriteAsync(EventSeverity.Warning, AlertEventCodes.DiskLow, check.Describe(), ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return check;
|
||||
}
|
||||
|
||||
/// <summary>Checks the free space periodically until <paramref name="ct"/> is cancelled (nothing to do without folders).</summary>
|
||||
public async Task WatchDiskSpaceAsync(CancellationToken ct)
|
||||
{
|
||||
if (_options.Folders.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var unmeasuredLogged = false;
|
||||
try
|
||||
{
|
||||
await _clock.Delay(_options.FirstDiskCheckDelay, ct).ConfigureAwait(false);
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var check = await CheckDiskSpaceAsync(ct).ConfigureAwait(false);
|
||||
if (check.Unmeasured.Count > 0 && !unmeasuredLogged)
|
||||
{
|
||||
unmeasuredLogged = true;
|
||||
Log(AlertLogLevel.Warning, $"Spazio libero non misurabile per: {string.Join(", ", check.Unmeasured.Select(f => f.Name))}. Per quei dischi l'avviso «Disco quasi pieno» non arriva.");
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException and not OutOfMemoryException)
|
||||
{
|
||||
Log(AlertLogLevel.Warning, $"Controllo dello spazio libero non riuscito ({ex.GetType().Name}): riprovo al prossimo giro.");
|
||||
}
|
||||
|
||||
await _clock.Delay(_options.DiskCheckInterval, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
_events.Notified -= OnNotified;
|
||||
_stop.Cancel();
|
||||
Task tail;
|
||||
lock (_gate)
|
||||
{
|
||||
tail = _tail;
|
||||
}
|
||||
|
||||
// Alerts in flight still hold the token: the source goes away once they are done.
|
||||
_ = tail.ContinueWith(_ => _stop.Dispose(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
|
||||
}
|
||||
|
||||
private void OnNotified(object? sender, EngineNotification notification)
|
||||
{
|
||||
if (notification.Kind != EngineNotificationKind.Event || notification.Event is not { } record)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (AlertCatalog.KindOf(record.Code) is not { } kind)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string? key = null;
|
||||
if (kind == AlertKind.DiskLow)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
key = _diskKey;
|
||||
}
|
||||
}
|
||||
|
||||
_ = Enqueue(AlertCatalog.FromEvent(kind, record, _clock.LocalZone, key));
|
||||
}
|
||||
|
||||
private Task Enqueue(Alert alert)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var token = _stop.Token;
|
||||
_tail = _tail.ContinueWith(_ => HandleAsync(alert, token), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default).Unwrap();
|
||||
return _tail;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleAsync(Alert alert, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var outcome = await DeliverAsync(alert, ct).ConfigureAwait(false);
|
||||
Handled?.Invoke(this, outcome);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// An alert must never stop the next one; the type alone is logged (messages may carry addresses).
|
||||
Log(AlertLogLevel.Warning, $"Avviso «{alert.Title}» non gestito ({ex.GetType().Name}).");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<AlertOutcome> DeliverAsync(Alert alert, CancellationToken ct)
|
||||
{
|
||||
var settings = await AlertSettingsStore.LoadAsync(_settings, ct).ConfigureAwait(false);
|
||||
if (!AlertCatalog.IsWanted(alert.Kind, settings.Events))
|
||||
{
|
||||
return new AlertOutcome(alert, AlertOutcomeKind.NotWanted, []);
|
||||
}
|
||||
|
||||
var channels = _channels.Where(c => c.IsEnabled(settings)).ToList();
|
||||
if (channels.Count == 0)
|
||||
{
|
||||
return new AlertOutcome(alert, AlertOutcomeKind.NoChannel, []);
|
||||
}
|
||||
|
||||
var dedupKey = LastSentPrefix + alert.Kind.ToString().ToLowerInvariant() + (alert.Key.Length == 0 ? string.Empty : "." + alert.Key);
|
||||
var now = _clock.Now;
|
||||
var last = await LastSentAsync(dedupKey, ct).ConfigureAwait(false);
|
||||
if (last is { } previous && now - previous < AlertCatalog.MinimumInterval(alert.Kind) && now >= previous)
|
||||
{
|
||||
Log(AlertLogLevel.Information, $"Avviso «{alert.Title}» non ripetuto: lo stesso è partito {ItalianText.At(previous, _clock.LocalZone)}.");
|
||||
return new AlertOutcome(alert, AlertOutcomeKind.Repeated, []);
|
||||
}
|
||||
|
||||
await RememberSentAsync(dedupKey, now, ct).ConfigureAwait(false);
|
||||
var deliveries = new List<(string Channel, AlertDelivery Delivery)>();
|
||||
foreach (var channel in channels)
|
||||
{
|
||||
AlertDelivery delivery;
|
||||
try
|
||||
{
|
||||
delivery = await channel.SendAsync(alert, settings, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
delivery = new AlertDelivery(false, $"invio non riuscito ({ex.GetType().Name})");
|
||||
}
|
||||
|
||||
deliveries.Add((channel.Name, delivery));
|
||||
if (!delivery.Sent)
|
||||
{
|
||||
await RecordFailureAsync(alert, channel.Name, delivery.Problem, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var sent = deliveries.Where(d => d.Delivery.Sent).Select(d => d.Channel).ToList();
|
||||
if (sent.Count > 0)
|
||||
{
|
||||
Log(AlertLogLevel.Information, $"Avviso «{alert.Title}» inviato: {string.Join(", ", sent)}.");
|
||||
}
|
||||
|
||||
return new AlertOutcome(alert, sent.Count > 0 ? AlertOutcomeKind.Sent : AlertOutcomeKind.Failed, deliveries);
|
||||
}
|
||||
|
||||
private async Task RecordFailureAsync(Alert alert, string channel, string? problem, CancellationToken ct)
|
||||
{
|
||||
var reason = string.IsNullOrWhiteSpace(problem) ? "invio non riuscito" : problem.TrimEnd('.');
|
||||
Log(AlertLogLevel.Warning, $"Avviso «{alert.Title}» non inviato ({channel}): {reason}.");
|
||||
var now = _clock.Now;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lastFailureEvent.TryGetValue(channel, out var last) && now - last < _options.FailureEventInterval && now >= last)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_lastFailureEvent[channel] = now;
|
||||
}
|
||||
|
||||
await _events.WriteAsync(
|
||||
EventSeverity.Warning,
|
||||
AlertEventCodes.DeliveryFailed,
|
||||
$"L'avviso «{alert.Title}» non è arrivato ({channel}): {reason}. Lo trovi comunque qui in Febe; controlla Impostazioni ▸ Notifiche e usa «Invia una prova».",
|
||||
alert.AccountId,
|
||||
ct: ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<DateTimeOffset?> LastSentAsync(string key, CancellationToken ct)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_lastSent.TryGetValue(key, out var cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
var stored = await _settings.GetInt64Async(key, ct).ConfigureAwait(false);
|
||||
return stored is { } ms ? DateTimeOffset.FromUnixTimeMilliseconds(ms) : null;
|
||||
}
|
||||
|
||||
private async Task RememberSentAsync(string key, DateTimeOffset at, CancellationToken ct)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_lastSent[key] = at;
|
||||
}
|
||||
|
||||
await _settings.SetAsync(key, at.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void Log(AlertLogLevel level, string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
_options.Log?.Invoke(level, message);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What happened to an alert.</summary>
|
||||
public enum AlertOutcomeKind
|
||||
{
|
||||
/// <summary>At least one channel accepted it.</summary>
|
||||
Sent,
|
||||
|
||||
/// <summary>Every channel failed (each failure is a timeline line).</summary>
|
||||
Failed,
|
||||
|
||||
/// <summary>The same alert left a short while ago (<see cref="AlertCatalog.MinimumInterval"/>).</summary>
|
||||
Repeated,
|
||||
|
||||
/// <summary>Its switch in Impostazioni ▸ Notifiche is off.</summary>
|
||||
NotWanted,
|
||||
|
||||
/// <summary>No channel is configured (no Telegram, no Windows notifications): only the interface shows it.</summary>
|
||||
NoChannel,
|
||||
}
|
||||
|
||||
/// <summary>An alert and what each channel did with it.</summary>
|
||||
public sealed record AlertOutcome(Alert Alert, AlertOutcomeKind Kind, IReadOnlyList<(string Channel, AlertDelivery Delivery)> Deliveries);
|
||||
@@ -98,20 +98,23 @@ public static class AlertSettingsStore
|
||||
public sealed record AlertTestResult(bool Sent, string Message);
|
||||
|
||||
/// <summary>
|
||||
/// «Invia una prova» of the Telegram alerts (spec §13.3). The real sender (one HTTPS call with <c>HttpClient</c>, no
|
||||
/// library, the address never logged because it contains the token) arrives with milestone M8 and replaces
|
||||
/// <see cref="TelegramNotAvailableYet"/>.
|
||||
/// «Invia una prova» of the Telegram alerts (spec §13.3). The real sender is <see cref="TelegramAlertChannel"/> (one
|
||||
/// HTTPS call with <c>HttpClient</c>, no library, the address never logged because it contains the token); the web
|
||||
/// layer falls back to <see cref="NoTelegramSender"/> where nothing may leave (demonstration, tests).
|
||||
/// </summary>
|
||||
public interface IAlertTestSender
|
||||
{
|
||||
Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct);
|
||||
}
|
||||
|
||||
/// <summary>Until M8: no message leaves, and the page says so plainly.</summary>
|
||||
public sealed class TelegramNotAvailableYet : IAlertTestSender
|
||||
/// <summary>
|
||||
/// No Telegram here: the demonstration and hosts without a composition (tests) never use the network. The page says
|
||||
/// so plainly; the real compositions register <see cref="TelegramAlertChannel"/>.
|
||||
/// </summary>
|
||||
public sealed class NoTelegramSender : IAlertTestSender
|
||||
{
|
||||
public const string Text =
|
||||
"Le impostazioni sono salvate, ma l'invio dei messaggi Telegram non c'è ancora in questa versione di Febe (arriva con la tappa M8): nessun messaggio è partito, nemmeno di prova.";
|
||||
"Le impostazioni sono salvate, ma questa istanza di Febe non invia messaggi Telegram (dimostrazione o prova): nessun messaggio è partito.";
|
||||
|
||||
public Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct) => Task.FromResult(new AlertTestResult(false, Text));
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using Febe.Core.Engine;
|
||||
|
||||
namespace Febe.Core.Alerts;
|
||||
|
||||
/// <summary>Free and total space of the disk that holds a folder.</summary>
|
||||
/// <param name="AvailableBytes">Space Febe can still use.</param>
|
||||
/// <param name="TotalBytes">Size of the disk.</param>
|
||||
public sealed record FreeSpace(long AvailableBytes, long TotalBytes)
|
||||
{
|
||||
/// <summary>Free share between 0 and 1 (1 when the size is unknown).</summary>
|
||||
public double Ratio => TotalBytes <= 0 ? 1 : Math.Clamp((double)AvailableBytes / TotalBytes, 0, 1);
|
||||
}
|
||||
|
||||
/// <summary>Measures the free space of the disk of a folder (tests use a fake).</summary>
|
||||
public interface IFreeSpaceProbe
|
||||
{
|
||||
/// <summary>The space of the disk that holds <paramref name="folder"/>; null when it cannot be measured.</summary>
|
||||
FreeSpace? Measure(string folder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="DriveInfo"/> on the nearest existing folder: on Linux any path of the file system (statvfs, so an Unraid
|
||||
/// user share reports its own free space), on Windows the drive of the path. Network paths that Windows cannot
|
||||
/// measure this way (\\server\share) give null: no alert rather than a wrong one.
|
||||
/// </summary>
|
||||
public sealed class DriveFreeSpaceProbe : IFreeSpaceProbe
|
||||
{
|
||||
public FreeSpace? Measure(string folder)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(folder))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var existing = Path.GetFullPath(folder);
|
||||
while (!Directory.Exists(existing))
|
||||
{
|
||||
var parent = Path.GetDirectoryName(existing);
|
||||
if (parent is null || parent == existing)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
existing = parent;
|
||||
}
|
||||
|
||||
var drive = new DriveInfo(existing);
|
||||
return new FreeSpace(drive.AvailableFreeSpace, drive.TotalSize);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.Security.SecurityException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When a disk counts as «quasi pieno»: fewer than <see cref="MinimumFreeBytes"/> free, or less than
|
||||
/// <see cref="MinimumFreeRatio"/> of the disk free, whichever comes first (10 GB or 5% by default).
|
||||
/// </summary>
|
||||
public sealed record DiskThresholds(long MinimumFreeBytes, double MinimumFreeRatio)
|
||||
{
|
||||
public static DiskThresholds Default { get; } = new(10L * 1024 * 1024 * 1024, 0.05);
|
||||
|
||||
public bool IsLow(FreeSpace space)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(space);
|
||||
return space.AvailableBytes < MinimumFreeBytes || (space.TotalBytes > 0 && space.Ratio < MinimumFreeRatio);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A folder whose disk is watched.</summary>
|
||||
/// <param name="Key">Stable key: «libreria», «dati».</param>
|
||||
/// <param name="Name">Italian name: «libreria», «cartella dei dati».</param>
|
||||
/// <param name="Path">The folder.</param>
|
||||
public sealed record WatchedFolder(string Key, string Name, string Path)
|
||||
{
|
||||
public static WatchedFolder Library(string path) => new("libreria", "libreria", path);
|
||||
|
||||
public static WatchedFolder Data(string path) => new("dati", "cartella dei dati", path);
|
||||
}
|
||||
|
||||
/// <summary>The outcome of one check of the watched folders.</summary>
|
||||
/// <param name="Low">Folders whose disk is almost full, with their space.</param>
|
||||
/// <param name="Unmeasured">Folders that could not be measured.</param>
|
||||
public sealed record DiskCheck(IReadOnlyList<(WatchedFolder Folder, FreeSpace Space)> Low, IReadOnlyList<WatchedFolder> Unmeasured)
|
||||
{
|
||||
/// <summary>The set of low folders as a key: «dati», «libreria+dati».</summary>
|
||||
public string Key => string.Join('+', Low.Select(l => l.Folder.Key));
|
||||
|
||||
/// <summary>
|
||||
/// The Italian text of the alert: how much space is left on which disk, what Febe does, what to do. Two folders on
|
||||
/// the same disk (same size and free space) are named together.
|
||||
/// </summary>
|
||||
public string Describe()
|
||||
{
|
||||
var groups = Low.GroupBy(l => (l.Space.TotalBytes, l.Space.AvailableBytes / (1024 * 1024 * 1024))).ToList();
|
||||
var parts = groups.Select(g =>
|
||||
{
|
||||
var space = g.First().Space;
|
||||
var names = string.Join(" e ", g.Select(x => "della " + x.Folder.Name));
|
||||
var percent = ItalianText.Decimal(space.Ratio * 100, 1);
|
||||
return $"sul disco {names} restano {ItalianText.Bytes(space.AvailableBytes)} liberi su {ItalianText.Bytes(space.TotalBytes)} ({percent}%)";
|
||||
});
|
||||
var text = ItalianText.Capitalize(string.Join("; ", parts)) + ".";
|
||||
var data = Low.Any(l => l.Folder.Key == "dati");
|
||||
var library = Low.Any(l => l.Folder.Key == "libreria");
|
||||
if (library)
|
||||
{
|
||||
text += " Continuo a lavorare, ma con il disco pieno gli scaricamenti non riusciranno.";
|
||||
}
|
||||
|
||||
if (data)
|
||||
{
|
||||
text += " Con il disco dei dati pieno il database non può più salvare nulla.";
|
||||
}
|
||||
|
||||
return text + " Che cosa fare: libera spazio su quel disco o sposta la cartella su un disco più capiente (guida, «Problemi comuni»).";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Core.Alerts;
|
||||
|
||||
/// <summary>How a call to Telegram went.</summary>
|
||||
public enum TelegramOutcome
|
||||
{
|
||||
Sent,
|
||||
|
||||
/// <summary>Token or chat identifier missing.</summary>
|
||||
NotConfigured,
|
||||
|
||||
/// <summary>The token does not have the shape of a bot token: nothing was sent.</summary>
|
||||
MalformedToken,
|
||||
|
||||
/// <summary>Telegram does not know the token (401, 404).</summary>
|
||||
InvalidToken,
|
||||
|
||||
/// <summary>Telegram does not know the chat (400 «chat not found»).</summary>
|
||||
ChatNotFound,
|
||||
|
||||
/// <summary>Any other 400.</summary>
|
||||
Rejected,
|
||||
|
||||
/// <summary>The bot may not write to that chat (403: blocked, never started, not in the group).</summary>
|
||||
Forbidden,
|
||||
|
||||
/// <summary>Too many messages (429).</summary>
|
||||
RateLimited,
|
||||
|
||||
/// <summary>Other answers (5xx, unexpected bodies).</summary>
|
||||
ServerError,
|
||||
|
||||
/// <summary>No answer within the timeout.</summary>
|
||||
Timeout,
|
||||
|
||||
/// <summary>No connection (DNS, network, TLS).</summary>
|
||||
Unreachable,
|
||||
}
|
||||
|
||||
/// <summary>Result of one call: the outcome and an Italian sentence that says what to do. Never contains the token.</summary>
|
||||
public sealed record TelegramResult(TelegramOutcome Outcome, string Message)
|
||||
{
|
||||
public bool Sent => Outcome == TelegramOutcome.Sent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Telegram Bot API, the only call Febe makes: one HTTPS POST to <c>https://api.telegram.org/bot<token>/sendMessage</c>
|
||||
/// with <see cref="HttpClient"/> and no library (spec §13.3). The address contains the bot token, so it is never
|
||||
/// logged, never put in a message and never part of an exception that leaves this class; response bodies are read
|
||||
/// only to tell a missing chat from other refusals, and never stored.
|
||||
/// </summary>
|
||||
public sealed partial class TelegramClient : IDisposable
|
||||
{
|
||||
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(15);
|
||||
|
||||
/// <summary>Longest text sent (Telegram accepts 4096 characters).</summary>
|
||||
public const int MaxTextLength = 3500;
|
||||
|
||||
private const int MaxBodyBytes = 64 * 1024;
|
||||
|
||||
// A string, not a base Uri: «bot123:ABC» relative to a base would read as an address with the scheme «bot123».
|
||||
private const string Api = "https://api.telegram.org/";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly TimeSpan _timeout;
|
||||
|
||||
/// <param name="handler">Tests pass a fake handler; null uses a pooled handler of its own.</param>
|
||||
/// <param name="timeout">How long a call may take (15 seconds by default).</param>
|
||||
public TelegramClient(HttpMessageHandler? handler = null, TimeSpan? timeout = null)
|
||||
{
|
||||
_timeout = timeout ?? DefaultTimeout;
|
||||
_http = handler is null
|
||||
? new HttpClient(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(10), ConnectTimeout = _timeout }, disposeHandler: true)
|
||||
: new HttpClient(handler, disposeHandler: false);
|
||||
|
||||
// The timeout is enforced with a token of our own, to tell it apart from a cancellation of the caller.
|
||||
_http.Timeout = Timeout.InfiniteTimeSpan;
|
||||
}
|
||||
|
||||
/// <summary>A bot token has the shape «digits:letters» (what BotFather gives); anything else is refused before any call.</summary>
|
||||
public static bool IsValidToken(string? token) => token is not null && TokenShape().IsMatch(token);
|
||||
|
||||
/// <summary>
|
||||
/// Sends <paramref name="text"/> (plain text, no formatting) to <paramref name="chatId"/>. Delivery problems come
|
||||
/// back as a <see cref="TelegramResult"/>; only a cancellation of <paramref name="ct"/> throws.
|
||||
/// </summary>
|
||||
public async Task<TelegramResult> SendMessageAsync(string? token, string? chatId, string text, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(chatId))
|
||||
{
|
||||
return Result(TelegramOutcome.NotConfigured);
|
||||
}
|
||||
|
||||
token = token.Trim();
|
||||
if (!IsValidToken(token))
|
||||
{
|
||||
return Result(TelegramOutcome.MalformedToken);
|
||||
}
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(_timeout);
|
||||
try
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(Api + "bot" + token + "/sendMessage", UriKind.Absolute));
|
||||
request.Content = new ByteArrayContent(Body(chatId.Trim(), text));
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
|
||||
using var response = await _http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token).ConfigureAwait(false);
|
||||
var body = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false);
|
||||
return Classify(response.StatusCode, body);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return Result(TelegramOutcome.Timeout);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
// The exception text may name the host: it is not passed on, only the outcome.
|
||||
return Result(TelegramOutcome.Unreachable);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return Result(TelegramOutcome.Unreachable);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Italian sentence for an outcome: what happened and what to do.</summary>
|
||||
public string Describe(TelegramOutcome outcome) => outcome switch
|
||||
{
|
||||
TelegramOutcome.Sent => "Messaggio inviato su Telegram.",
|
||||
TelegramOutcome.NotConfigured => "Scrivi il gettone del bot e l'identificativo della chat, salva, poi invia la prova.",
|
||||
TelegramOutcome.MalformedToken => "Il gettone del bot non ha la forma giusta (cifre, due punti, poi una lunga serie di lettere): copialo per intero dal messaggio di BotFather.",
|
||||
TelegramOutcome.InvalidToken => "Telegram non riconosce il gettone del bot: copialo di nuovo per intero dal messaggio di BotFather.",
|
||||
TelegramOutcome.ChatNotFound => "Telegram non trova la chat: controlla l'identificativo e scrivi almeno un messaggio al bot prima di riprovare.",
|
||||
TelegramOutcome.Rejected => "Telegram ha rifiutato il messaggio: controlla l'identificativo della chat.",
|
||||
TelegramOutcome.Forbidden => "Il bot non può scriverti: apri la chat con il bot su Telegram e premi «Avvia» (o sbloccalo; in un gruppo, aggiungilo), poi riprova.",
|
||||
TelegramOutcome.RateLimited => "Telegram chiede di aspettare prima di altri messaggi: riprova fra qualche minuto.",
|
||||
TelegramOutcome.ServerError => "Telegram ha risposto con un errore: riprova più tardi.",
|
||||
TelegramOutcome.Timeout => $"Telegram non ha risposto entro {Math.Max(1, Math.Ceiling(_timeout.TotalSeconds)).ToString("0", CultureInfo.InvariantCulture)} secondi: controlla la connessione a Internet di Febe e riprova.",
|
||||
TelegramOutcome.Unreachable => "Telegram non è raggiungibile: controlla la connessione a Internet di Febe (in Docker, quella del contenitore) e riprova.",
|
||||
_ => "Invio a Telegram non riuscito.",
|
||||
};
|
||||
|
||||
public void Dispose() => _http.Dispose();
|
||||
|
||||
private TelegramResult Result(TelegramOutcome outcome) => new(outcome, Describe(outcome));
|
||||
|
||||
private TelegramResult Classify(HttpStatusCode status, string body)
|
||||
{
|
||||
var code = (int)status;
|
||||
if (code is >= 200 and < 300)
|
||||
{
|
||||
return Result(OkField(body) == false ? TelegramOutcome.ServerError : TelegramOutcome.Sent);
|
||||
}
|
||||
|
||||
return Result(code switch
|
||||
{
|
||||
401 or 404 => TelegramOutcome.InvalidToken,
|
||||
400 when Description(body)?.Contains("chat not found", StringComparison.OrdinalIgnoreCase) == true => TelegramOutcome.ChatNotFound,
|
||||
400 => TelegramOutcome.Rejected,
|
||||
403 => TelegramOutcome.Forbidden,
|
||||
429 => TelegramOutcome.RateLimited,
|
||||
_ => TelegramOutcome.ServerError,
|
||||
});
|
||||
}
|
||||
|
||||
private static byte[] Body(string chatId, string text)
|
||||
{
|
||||
if (text.Length > MaxTextLength)
|
||||
{
|
||||
text = text[..MaxTextLength] + "…";
|
||||
}
|
||||
|
||||
using var stream = new MemoryStream();
|
||||
using (var json = new Utf8JsonWriter(stream))
|
||||
{
|
||||
json.WriteStartObject();
|
||||
json.WriteString("chat_id", chatId);
|
||||
json.WriteString("text", text);
|
||||
json.WriteBoolean("disable_web_page_preview", true);
|
||||
json.WriteEndObject();
|
||||
}
|
||||
|
||||
return stream.ToArray();
|
||||
}
|
||||
|
||||
private static async Task<string> ReadLimitedAsync(HttpContent content, CancellationToken ct)
|
||||
{
|
||||
var stream = await content.ReadAsStreamAsync(ct).ConfigureAwait(false);
|
||||
await using (stream.ConfigureAwait(false))
|
||||
{
|
||||
var buffer = new byte[MaxBodyBytes];
|
||||
var total = 0;
|
||||
int read;
|
||||
while (total < buffer.Length && (read = await stream.ReadAsync(buffer.AsMemory(total), ct).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
total += read;
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(buffer, 0, total);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? OkField(string body)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(body);
|
||||
return document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty("ok", out var ok) && ok.ValueKind is JsonValueKind.True or JsonValueKind.False
|
||||
? ok.GetBoolean()
|
||||
: null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Description(string body)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(body);
|
||||
return document.RootElement.ValueKind == JsonValueKind.Object && document.RootElement.TryGetProperty("description", out var d) && d.ValueKind == JsonValueKind.String
|
||||
? d.GetString()
|
||||
: null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^[0-9]{1,20}:[A-Za-z0-9_-]{10,200}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex TokenShape();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Telegram channel of the alerts and the real «Invia una prova» of Impostazioni ▸ Notifiche (spec §13.3): on when
|
||||
/// both the bot token and the chat identifier are set.
|
||||
/// </summary>
|
||||
public sealed class TelegramAlertChannel(TelegramClient client) : IAlertChannel, IAlertTestSender
|
||||
{
|
||||
/// <summary>Text of the test message.</summary>
|
||||
public const string TestText = "Febe · Prova degli avvisi\nSe leggi questo messaggio, gli avvisi di Febe arriveranno qui.";
|
||||
|
||||
private readonly TelegramClient _client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
|
||||
public string Name => "Telegram";
|
||||
|
||||
public bool IsEnabled(AlertSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return settings.TelegramConfigured;
|
||||
}
|
||||
|
||||
public async Task<AlertDelivery> SendAsync(Alert alert, AlertSettings settings, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(alert);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var result = await _client.SendMessageAsync(settings.TelegramToken, settings.TelegramChatId, alert.TelegramText, ct).ConfigureAwait(false);
|
||||
return result.Sent ? AlertDelivery.Ok : new AlertDelivery(false, result.Message);
|
||||
}
|
||||
|
||||
public async Task<AlertTestResult> SendTelegramTestAsync(AlertSettings settings, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var result = await _client.SendMessageAsync(settings.TelegramToken, settings.TelegramChatId, TestText, ct).ConfigureAwait(false);
|
||||
return result.Sent
|
||||
? new AlertTestResult(true, "Messaggio di prova inviato: controlla la chat del bot su Telegram.")
|
||||
: new AlertTestResult(false, "Nessun messaggio è partito. " + result.Message);
|
||||
}
|
||||
}
|
||||
@@ -711,7 +711,7 @@ internal sealed class SessionComposer
|
||||
}
|
||||
|
||||
await RecordRecipeFailureAsync(kind, account, EngineEventCodes.FormatUnrecognized,
|
||||
$"Formato non riconosciuto in {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
|
||||
$"Formato non riconosciuto durante {RecipeName(kind)}{Of(account)}: Instagram potrebbe aver cambiato le sue risposte.", now).ConfigureAwait(false);
|
||||
break;
|
||||
|
||||
case RecipeStatus.AccountUnreachable:
|
||||
|
||||
@@ -137,6 +137,9 @@ public sealed record EventQuery
|
||||
public DateTimeOffset? From { get; init; }
|
||||
|
||||
public DateTimeOffset? To { get; init; }
|
||||
|
||||
/// <summary>Only these codes (null: every code).</summary>
|
||||
public IReadOnlyCollection<string>? Codes { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Local copy of the list of profiles Alberto follows (spec §4.2, §8.3 <c>following</c>).</summary>
|
||||
|
||||
@@ -460,10 +460,11 @@ internal sealed class EventStore(FebeDatabase db) : IEventStore
|
||||
{
|
||||
var command = c.Command(string.Empty);
|
||||
var list = command.AddList("sv", severities);
|
||||
var codes = query.Codes is { } wanted ? $" AND code IN ({command.AddList("cd", wanted)})" : string.Empty;
|
||||
command.CommandText = $"""
|
||||
SELECT {Columns} FROM event
|
||||
WHERE (@before IS NULL OR id < @before) AND (@a IS NULL OR account_id = @a) AND severity IN ({list})
|
||||
AND (@f IS NULL OR at >= @f) AND (@t IS NULL OR at < @t)
|
||||
AND (@f IS NULL OR at >= @f) AND (@t IS NULL OR at < @t){codes}
|
||||
ORDER BY id DESC LIMIT @limit
|
||||
""";
|
||||
command.With("@before", Sql.Int(query.BeforeId)).With("@a", Sql.Int(query.AccountId))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Globalization;
|
||||
using Febe.Browser.Recipes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Collection.Downloads;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
@@ -12,9 +13,11 @@ using Febe.Web;
|
||||
using Febe.Web.Connection;
|
||||
using Febe.Web.Engine;
|
||||
using Febe.Web.Library;
|
||||
using Febe.Web.Native;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Febe.Server;
|
||||
|
||||
@@ -32,6 +35,12 @@ internal sealed record ServerHooks
|
||||
|
||||
/// <summary>How long the web host waits for open requests (events, remote view) when stopping.</summary>
|
||||
public TimeSpan ShutdownTimeout { get; init; } = TimeSpan.FromSeconds(3);
|
||||
|
||||
/// <summary>Fake Telegram (tests never reach the real API).</summary>
|
||||
public HttpMessageHandler? TelegramHandler { get; init; }
|
||||
|
||||
/// <summary>Fake free-space probe for the «Disco quasi pieno» alert.</summary>
|
||||
public IFreeSpaceProbe? FreeSpace { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -89,6 +98,9 @@ internal sealed class FebeServer : IAsyncDisposable
|
||||
|
||||
public PerceptualHashIndex? HashIndex { get; private set; }
|
||||
|
||||
/// <summary>The alerts of spec §13.3 (Telegram; Windows notifications through the shell, on the desktop).</summary>
|
||||
public AlertService? Alerts { get; private set; }
|
||||
|
||||
/// <summary>Completes when browser, pipeline and engine are running (never, with a configuration problem).</summary>
|
||||
public Task Running => _running.Task;
|
||||
|
||||
@@ -241,6 +253,8 @@ internal sealed class FebeServer : IAsyncDisposable
|
||||
Engine = engine;
|
||||
connection.AttachEngine(engine);
|
||||
browser.Host.UserDriving.Changed += (_, _) => engine.NotifyUserDrivingChanged();
|
||||
var telegram = new TelegramClient(hooks.TelegramHandler);
|
||||
var telegramChannel = new TelegramAlertChannel(telegram);
|
||||
|
||||
await StartWebAsync(hooks, s =>
|
||||
{
|
||||
@@ -258,13 +272,31 @@ internal sealed class FebeServer : IAsyncDisposable
|
||||
s.AddSingleton<IConfigurationProblems>(new StartupProblems([]));
|
||||
s.AddSingleton(Import);
|
||||
s.AddSingleton(new DailyBackup(Database, Clock, data.Backups));
|
||||
s.AddSingleton<IAlertTestSender>(telegramChannel);
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
// Alerts (spec §13.3): from the engine's timeline and the free space of the two folders, to the shell's
|
||||
// notifications (none in Docker) and Telegram. The strip of the interface is the engine snapshot's.
|
||||
Alerts = new AlertService(
|
||||
Database.Settings,
|
||||
Clock,
|
||||
services.Events,
|
||||
[new NativeShellAlertChannel(Web.Services.GetRequiredService<INativeShell>()), telegramChannel],
|
||||
new AlertServiceOptions
|
||||
{
|
||||
Folders = [WatchedFolder.Library(layout.Root), WatchedFolder.Data(data.Root)],
|
||||
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
|
||||
Log = (level, message) => _log.Write(level == AlertLogLevel.Warning ? LogLevel.Warning : LogLevel.Information, "avvisi", message),
|
||||
}).Attach();
|
||||
_disposables.Add(Alerts);
|
||||
_disposables.Add(telegram);
|
||||
|
||||
// Housekeeping in the background: temporary files of an interrupted run, the daily copy of the database.
|
||||
var lifetime = _lifetime.Token;
|
||||
_background.Add(Task.Run(() => CleanTemporaryFilesAsync(staging, layout, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, lifetime), CancellationToken.None));
|
||||
_background.Add(Task.Run(() => Alerts.WatchDiskSpaceAsync(lifetime), CancellationToken.None));
|
||||
}
|
||||
|
||||
private async Task StartWebAsync(ServerHooks hooks, Action<IServiceCollection> register)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
@@ -24,6 +26,9 @@ public static class ActivityApi
|
||||
endpoints.MapGet("/api/engine/incidents", async (IIncidentHistory history, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await IncidentsAsync(history, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.IncidentListDto));
|
||||
|
||||
endpoints.MapGet("/api/alerts", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
|
||||
ApiHttp.Json(await AlertsAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AlertListDto));
|
||||
|
||||
endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) =>
|
||||
{
|
||||
var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
|
||||
@@ -78,6 +83,37 @@ public static class ActivityApi
|
||||
return new IncidentListDto(dtos, throttles, advice);
|
||||
}
|
||||
|
||||
/// <summary>The alerts of the last <see cref="HistoryDays"/> days (at most 50), from the timeline.</summary>
|
||||
public static async Task<AlertListDto> AlertsAsync(IFebeStorage storage, IClock clock, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
var now = clock.Now;
|
||||
var zone = clock.LocalZone;
|
||||
var events = await storage.Events.ListAsync(
|
||||
new EventQuery { From = now - TimeSpan.FromDays(HistoryDays), Codes = AlertCatalog.Codes, Limit = 50 },
|
||||
ct).ConfigureAwait(false);
|
||||
var items = events.Select(e =>
|
||||
{
|
||||
var kind = AlertCatalog.KindOf(e.Code);
|
||||
return new AlertItemDto(
|
||||
e.Id,
|
||||
ApiMapping.Local(e.At, now, zone),
|
||||
kind is { } k ? JsonNamingPolicy.CamelCase.ConvertName(k.ToString()) : "deliveryFailed",
|
||||
e.Severity switch
|
||||
{
|
||||
EventSeverity.Error => "error",
|
||||
EventSeverity.Warning => "warning",
|
||||
EventSeverity.Success => "success",
|
||||
_ => "info",
|
||||
},
|
||||
kind is { } known ? AlertCatalog.Title(known) : "Avviso non inviato",
|
||||
kind is { } alert ? AlertCatalog.FromEvent(alert, e, zone).Message : e.Message,
|
||||
e.AccountId);
|
||||
}).ToList();
|
||||
return new AlertListDto(items, HistoryDays);
|
||||
}
|
||||
|
||||
public static string Level(SignalLevel level) => level switch
|
||||
{
|
||||
SignalLevel.Throttle => "throttle",
|
||||
|
||||
@@ -39,6 +39,22 @@ public static class EngineApi
|
||||
return ApiHttp.Json(new ResumeDto(result.Resumed, result.Message), FebeJsonContext.Default.ResumeDto);
|
||||
});
|
||||
|
||||
// «Riattiva» a recipe suspended after three unknown formats (or targets not found) in a row.
|
||||
endpoints.MapPost("/api/engine/recipes/{recipe}/resume", async (string recipe, IEngineControl control, CancellationToken ct) =>
|
||||
{
|
||||
if (!Enum.TryParse<RecipeKind>(recipe, ignoreCase: true, out var kind) || !Enum.IsDefined(kind))
|
||||
{
|
||||
throw new BadRequestException("Ricetta sconosciuta.");
|
||||
}
|
||||
|
||||
var resumed = await control.ResumeRecipeAsync(kind, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(
|
||||
new ResumeDto(resumed, resumed
|
||||
? "Ricetta riattivata: riprende alla prossima sessione. Se il formato è ancora sconosciuto, si sospende di nuovo dopo tre volte."
|
||||
: "Questa ricetta non era sospesa."),
|
||||
FebeJsonContext.Default.ResumeDto);
|
||||
});
|
||||
|
||||
// «Apri il browser» on Windows: the window of the browser comes to the front.
|
||||
endpoints.MapPost("/api/browser/show", async (IBrowserWindow browser, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
|
||||
@@ -48,6 +48,7 @@ namespace Febe.Web.Api;
|
||||
[JsonSerializable(typeof(BeginDrivingRequest))]
|
||||
[JsonSerializable(typeof(FinishDto))]
|
||||
[JsonSerializable(typeof(IncidentListDto))]
|
||||
[JsonSerializable(typeof(AlertListDto))]
|
||||
[JsonSerializable(typeof(BrowserPreviewDto))]
|
||||
[JsonSerializable(typeof(DuplicateCountsDto))]
|
||||
[JsonSerializable(typeof(GeneralSettingsDto))]
|
||||
|
||||
@@ -32,6 +32,16 @@ public sealed record IncidentDto(
|
||||
/// <param name="Advice">«Tre rallentamenti in sette giorni»: the proposal of spec §7.6, or null.</param>
|
||||
public sealed record IncidentListDto(IReadOnlyList<IncidentDto> Items, int ThrottlesLastWeek, string? Advice);
|
||||
|
||||
/// <summary>
|
||||
/// A line of the «Avvisi» list of Attività (spec §13.3): an alert or a failed delivery. <see cref="Kind"/>:
|
||||
/// verification, disconnection, throttleStop, throttleEnd, backfillDone, unknownFormat, recipeSuspended, diskLow,
|
||||
/// deliveryFailed. <see cref="Level"/>: error, warning, success, info.
|
||||
/// </summary>
|
||||
public sealed record AlertItemDto(long Id, LocalTimeDto At, string Kind, string Level, string Title, string Message, long? AccountId);
|
||||
|
||||
/// <summary><c>GET /api/alerts</c>: the alerts of the last <see cref="Days"/> days, newest first.</summary>
|
||||
public sealed record AlertListDto(IReadOnlyList<AlertItemDto> Items, int Days);
|
||||
|
||||
/// <summary>The preview of Febe's browser: <see cref="Frame"/> is the address of the JPEG (with a version), or null.</summary>
|
||||
public sealed record BrowserPreviewDto(bool HasFrame, string? Url, long? At, string? Frame);
|
||||
|
||||
|
||||
@@ -152,9 +152,9 @@ public static class SettingsApi
|
||||
}
|
||||
|
||||
var token = body.RemoveTelegramToken ? null : string.IsNullOrWhiteSpace(body.TelegramToken) ? stored.TelegramToken : body.TelegramToken.Trim();
|
||||
if (token is not null && (token.Length > 200 || token.Any(char.IsWhiteSpace)))
|
||||
if (token is not null && !TelegramClient.IsValidToken(token))
|
||||
{
|
||||
throw new BadRequestException("Il gettone del bot non è valido: copialo per intero dal messaggio di BotFather, senza spazi.");
|
||||
throw new BadRequestException("Il gettone del bot non è valido: copialo per intero dal messaggio di BotFather (cifre, due punti, poi una lunga serie di lettere), senza spazi.");
|
||||
}
|
||||
|
||||
var e = body.Events;
|
||||
@@ -186,7 +186,7 @@ public static class SettingsApi
|
||||
throw new BadRequestException("Scrivi il gettone del bot e l'identificativo della chat, salva, poi invia la prova.");
|
||||
}
|
||||
|
||||
var sender = d.Services.GetService(typeof(IAlertTestSender)) as IAlertTestSender ?? new TelegramNotAvailableYet();
|
||||
var sender = d.Services.GetService(typeof(IAlertTestSender)) as IAlertTestSender ?? new NoTelegramSender();
|
||||
var result = await sender.SendTelegramTestAsync(settings, ct).ConfigureAwait(false);
|
||||
return ApiHttp.Json(new AlertTestDto(result.Sent, result.Message), FebeJsonContext.Default.AlertTestDto);
|
||||
});
|
||||
@@ -522,7 +522,7 @@ public static class SettingsApi
|
||||
SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock).Notifications,
|
||||
settings.TelegramChatId,
|
||||
!string.IsNullOrWhiteSpace(settings.TelegramToken),
|
||||
sender is not null and not TelegramNotAvailableYet);
|
||||
sender is not null and not NoTelegramSender);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- Dati
|
||||
|
||||
@@ -492,6 +492,20 @@ 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
|
||||
// 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);
|
||||
events.Add(Event(throttle, EventSeverity.Warning, Core.Engine.EngineEventCodes.ThrottleStop,
|
||||
$"Instagram ha chiesto di rallentare (segnale http-429). Ho chiuso la sessione e mi fermo per 1 ora, fino {Core.Engine.ItalianText.AtDay(throttleEnd, throttle, zone)}. Poi i tetti restano dimezzati per 48 ore.", null));
|
||||
events.Add(Event(throttleEnd, EventSeverity.Info, Core.Engine.EngineEventCodes.ThrottleEnd,
|
||||
$"Fine del fermo per rallentamento. Riprendo con i tetti dimezzati fino {Core.Engine.ItalianText.AtDay(throttleEnd + TimeSpan.FromHours(48), throttleEnd, zone)}.", null));
|
||||
foreach (var (spec, account) in accounts.Where(a => a.Account.BackfillCompletedAt is { } done && done > now - TimeSpan.FromDays(14) && done < now))
|
||||
{
|
||||
events.Add(Event(account.BackfillCompletedAt!.Value, EventSeverity.Success, Core.Engine.EngineEventCodes.BackfillCompleted,
|
||||
$"Storico di @{account.Username} completato: {Core.Engine.ItalianText.Count(spec.Posts, "post", "post")} in libreria. Da ora lo tengo aggiornato.", account.Id));
|
||||
}
|
||||
|
||||
foreach (var e in events.OrderBy(e => e.At))
|
||||
{
|
||||
await storage.Events.AppendAsync(e, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -26,6 +26,12 @@ public interface IEngineControl
|
||||
|
||||
/// <summary>Accounts were added, removed or changed: the engine brings its queue in step.</summary>
|
||||
Task NotifyAccountsChangedAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// «Riattiva» a recipe suspended after three problems in a row (unknown formats, targets not found). False when it
|
||||
/// was not suspended or there is no engine.
|
||||
/// </summary>
|
||||
Task<bool> ResumeRecipeAsync(RecipeKind recipe, CancellationToken ct) => Task.FromResult(false);
|
||||
}
|
||||
|
||||
/// <summary>The commands of the interface on the real engine.</summary>
|
||||
@@ -41,6 +47,8 @@ public sealed class EngineHostControl(EngineHost host) : IEngineControl
|
||||
public Task RequestFollowingListAsync(CancellationToken ct) => host.RequestFollowingListAsync(ct);
|
||||
|
||||
public Task NotifyAccountsChangedAsync(CancellationToken ct) => host.NotifyAccountsChangedAsync(ct);
|
||||
|
||||
public Task<bool> ResumeRecipeAsync(RecipeKind recipe, CancellationToken ct) => host.ResumeRecipeAsync(recipe, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -68,7 +68,7 @@ public static class FebeWeb
|
||||
services.TryAddSingleton<IConnectionService, UnavailableConnectionService>();
|
||||
services.TryAddSingleton<IBrowserPreview, NoBrowserPreview>();
|
||||
services.TryAddSingleton<IIncidentHistory>(sp => new StoredIncidentHistory(sp.GetRequiredService<IFebeStorage>()));
|
||||
services.TryAddSingleton<IAlertTestSender, TelegramNotAvailableYet>();
|
||||
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
|
||||
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
|
||||
services.TryAddSingleton<FolderSizes>();
|
||||
services.TryAddSingleton<RebuildJob>();
|
||||
|
||||
@@ -17,7 +17,7 @@ Qui sotto le convenzioni per chi continua il lavoro (composizione di Server e De
|
||||
| `Library/` | `FebeLibrary` (archivio + disposizione, `HashIndex`, `DownloadDuplicates`), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente, `IDataFolderChange`, `FolderSizes`, `RebuildJob` |
|
||||
| `Connection/` | Contratto condiviso con il lato server del collegamento: `IConnectionService`, `IConfigurationProblems`, `PROTOCOLLO.md` (vista remota `/api/vista`); `UnavailableConnectionService` è il ripiego |
|
||||
| `Import/` | `ImportHub`: l'`ImportService` registrato dalla composizione, oppure uno costruito sulla libreria |
|
||||
| `Native/` | `INativeShell` (funzioni del sistema) e `IBrowserWindow` (finestra del browser), con le versioni «niente» |
|
||||
| `Native/` | `INativeShell` (funzioni del sistema) e `IBrowserWindow` (finestra del browser), con le versioni «niente»; `NativeShellAlertChannel`: le notifiche di Windows come canale degli avvisi |
|
||||
| `Demo/` | Modalità dimostrativa: dati finti coerenti, motore finto con scene, guscio finto |
|
||||
| `wwwroot/` | Interfaccia: HTML, CSS, moduli ES senza framework né build |
|
||||
|
||||
@@ -60,7 +60,7 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri
|
||||
| `IEngineSettingsControl` | `StoredEngineSettingsControl`: salva le impostazioni del motore nell'archivio | `new EngineHostSettingsControl(engineHost)`: le applica anche al motore che gira |
|
||||
| `IBrowserPreview` | `NoBrowserPreview` (nessuna anteprima) | Chi ha il browser: `GetLatestAsync` restituisce l'ultima schermata JPEG (`BrowserFrame`) con l'indirizzo |
|
||||
| `IIncidentHistory` | `StoredIncidentHistory` (dall'archivio) | Di solito nessuno |
|
||||
| `IAlertTestSender` (Core) | `TelegramNotAvailableYet`: nessun messaggio parte, la risposta lo dice | M8, l'invio vero dei messaggi Telegram |
|
||||
| `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione: `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` |
|
||||
| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop (M6): sposta la cartella al riavvio |
|
||||
| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) |
|
||||
|
||||
@@ -102,13 +102,15 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
|
||||
| `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/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 |
|
||||
| `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) |
|
||||
| `GET /api/accounts`, `GET /api/accounts/{id}`, `GET /{id}/history` | Elenco con conteggi, scheda, cronologia |
|
||||
| `POST /api/accounts/{id}/plan`, `PUT /{id}/settings`, `POST /{id}/keep-updated`, `/pause`, `/resume`, `/check-now`, `/remove`, `/pick-folder`, `/open-on-instagram` | Impostazioni dell'account e comandi |
|
||||
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account» |
|
||||
| `GET /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 |
|
||||
| `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/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 |
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using Febe.Core.Alerts;
|
||||
|
||||
namespace Febe.Web.Native;
|
||||
|
||||
/// <summary>
|
||||
/// Windows notifications as an alert channel (spec §12, §13.3): <see cref="INativeShell.NotifyAsync"/> with the title
|
||||
/// and the message of the alert. On when the shell can notify (the desktop) and «Notifiche di Windows» is on; in
|
||||
/// Docker <see cref="BrowserShell"/> cannot notify and the channel stays silent.
|
||||
/// </summary>
|
||||
public sealed class NativeShellAlertChannel(INativeShell shell) : IAlertChannel
|
||||
{
|
||||
private readonly INativeShell _shell = shell ?? throw new ArgumentNullException(nameof(shell));
|
||||
|
||||
public string Name => "notifica di Windows";
|
||||
|
||||
public bool IsEnabled(AlertSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return _shell.CanNotify && settings.WindowsNotifications;
|
||||
}
|
||||
|
||||
public async Task<AlertDelivery> SendAsync(Alert alert, AlertSettings settings, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(alert);
|
||||
try
|
||||
{
|
||||
await _shell.NotifyAsync(alert.Title, alert.Message, ct).ConfigureAwait(false);
|
||||
return AlertDelivery.Ok;
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
return new AlertDelivery(false, $"Windows non ha mostrato la notifica ({ex.GetType().Name})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -339,6 +339,13 @@ input[type=range].cursore::-webkit-slider-thumb{-webkit-appearance:none;width:16
|
||||
input[type=range].cursore::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:var(--superficie);border:1.5px solid var(--testo-2)}
|
||||
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}
|
||||
/* 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){
|
||||
.strumenti:has(> div > .filtri){flex-wrap:wrap;row-gap:10px}
|
||||
.strumenti .filtri{flex-wrap:nowrap;flex-shrink:0}
|
||||
}
|
||||
|
||||
/* menu a comparsa */
|
||||
.menu{position:fixed;z-index:60;min-width:200px;max-width:340px;max-height:min(420px,70vh);overflow:auto;background:var(--superficie);border:1px solid var(--bordo);border-radius:var(--r-pannello);box-shadow:var(--ombra-menu);padding:6px}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// 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, and the stops of the last days. 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.
|
||||
// «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, withCarried } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
@@ -22,10 +23,12 @@ export default {
|
||||
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, today, budgets, lists, notice, incidents));
|
||||
fill(page.body, h('div.attivita', now, suspended, today, budgets, lists, notice, incidents, alerts));
|
||||
|
||||
let latest = null;
|
||||
page.onEngine((state) => {
|
||||
@@ -35,17 +38,20 @@ export default {
|
||||
drawToday(today, state);
|
||||
drawBudgets(budgets, state);
|
||||
drawLists(lists, state);
|
||||
drawSuspended(suspended, state);
|
||||
preview.update(state);
|
||||
});
|
||||
|
||||
async function loadSide() {
|
||||
try {
|
||||
const [counts, history] = await Promise.all([
|
||||
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);
|
||||
}
|
||||
@@ -287,6 +293,56 @@ function drawNotice(box, counts) {
|
||||
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,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// 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).
|
||||
|
||||
import { api, download, withCarried } from '../core/api.js';
|
||||
import { caps } from '../core/context.js';
|
||||
@@ -91,6 +92,8 @@ export default {
|
||||
const size = local.get('libreria.tessere', 160);
|
||||
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 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 });
|
||||
api('/api/duplicates/count', { signal: page.signal }).then((counts) => {
|
||||
@@ -104,6 +107,7 @@ export default {
|
||||
filtersButton,
|
||||
h('div.destra',
|
||||
duplicates,
|
||||
exportButton,
|
||||
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
|
||||
selectButton)));
|
||||
|
||||
@@ -287,6 +291,7 @@ export default {
|
||||
}
|
||||
|
||||
selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting));
|
||||
exportButton.addEventListener('click', () => exportFiltered());
|
||||
|
||||
async function exportSelected() {
|
||||
try {
|
||||
@@ -297,6 +302,18 @@ export default {
|
||||
}
|
||||
}
|
||||
|
||||
async function exportFiltered() {
|
||||
exportButton.disabled = true;
|
||||
try {
|
||||
await download('/api/entries/export', { query: apiQuery(state, today()) }, 'febe-elementi.csv');
|
||||
toast(t(filtersActive() ? 'libreria.esportatoFiltro' : 'libreria.esportato'));
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
exportButton.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSelected() {
|
||||
const ids = [...mosaic.selected];
|
||||
const removed = await confirmDelete(ids);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Impostazioni, Notifiche (spec §13.3): which events notify, Windows notifications (desktop only), Telegram with the
|
||||
// bot token (masked, never shown again once saved, never logged) and the chat identifier, and «Invia una prova».
|
||||
// The Telegram sender arrives with milestone M8: until then the server answers plainly that nothing was sent.
|
||||
// Telegram: one HTTPS call from the server (TelegramAlertChannel); where no sender is registered (demonstration) the
|
||||
// page says that no message leaves.
|
||||
|
||||
import { api } from '../core/api.js';
|
||||
import { h, icon, fill } from '../core/dom.js';
|
||||
|
||||
@@ -131,6 +131,10 @@
|
||||
"nessunoTesto": "Cambia o togli un filtro per vedere altro.",
|
||||
"togliFiltri": "Togli i filtri",
|
||||
"doppioni": "1 doppione da decidere|{n} doppioni da decidere",
|
||||
"esporta": "Esporta l'elenco",
|
||||
"esportaAiuto": "Esporta l'elenco: un file CSV con gli elementi mostrati dai filtri di adesso, che si apre in Excel",
|
||||
"esportato": "Elenco esportato: il file CSV è nei download del browser.",
|
||||
"esportatoFiltro": "Elenco degli elementi filtrati esportato: il file CSV è nei download del browser.",
|
||||
"tessera": "{tipo} di @{account}, {quando}",
|
||||
"tesseraFile": "{n} file",
|
||||
"tesseraDurata": "video di {durata}",
|
||||
@@ -530,6 +534,11 @@
|
||||
"aperto": "In corso",
|
||||
"risolto": "Risolto {quando}",
|
||||
"fermoFino": "Fermo fino {quando}",
|
||||
"avvisi": "Avvisi",
|
||||
"sospesa": "«{nome}» è sospeso: tre risposte di fila in un formato non riconosciuto, o un comando non trovato nella pagina. Instagram potrebbe essere cambiato: serve un campione nuovo con la sonda (guida, «Problemi comuni»), poi riattivalo.",
|
||||
"riattiva": "Riattiva",
|
||||
"avvisiAiuto": "Gli ultimi {giorni} giorni: gli stessi che arrivano su Telegram e nelle notifiche, se li hai attivati in Impostazioni, Notifiche.",
|
||||
"livelliAvviso": { "error": "Fermo", "warning": "Attenzione", "success": "Fatto", "info": "Informazione" },
|
||||
"doppioni": "1 doppione probabile dopo gli ultimi scaricamenti aspetta la tua scelta.|{n} doppioni probabili dopo gli ultimi scaricamenti aspettano la tua scelta.",
|
||||
"decidi": "Decidi",
|
||||
"chiesto": "Chiesto da te"
|
||||
@@ -721,7 +730,7 @@
|
||||
"soloWindows": "Solo versione Windows",
|
||||
"prova": "Invia una prova",
|
||||
"telegram": "Telegram",
|
||||
"telegramAiuto": "Facoltativo. Crea un bot con BotFather, scrivigli un messaggio, poi copia qui il suo gettone e l'identificativo della chat.",
|
||||
"telegramAiuto": "Facoltativo. Crea un bot con BotFather, scrivigli un messaggio, poi copia qui il suo gettone e l'identificativo della chat: la guida, alla pagina «Avvisi e Telegram», spiega come.",
|
||||
"gettone": "Gettone del bot",
|
||||
"gettoneSalvato": "Gettone salvato: per cambiarlo scrivine uno nuovo",
|
||||
"gettoneVuoto": "Incolla il gettone di BotFather",
|
||||
@@ -730,7 +739,7 @@
|
||||
"chat": "Identificativo della chat",
|
||||
"chatEsempio": "Per esempio 123456789",
|
||||
"gettoneNota": "Il gettone resta nella cartella dei dati di Febe: non finisce nei registri e non viene più mostrato.",
|
||||
"nonAncora": "L'invio dei messaggi Telegram arriva con una prossima versione di Febe: per ora le impostazioni si salvano soltanto."
|
||||
"nonAncora": "Questa istanza di Febe non invia messaggi Telegram (dimostrazione o prova): le impostazioni si salvano soltanto."
|
||||
},
|
||||
"dati": {
|
||||
"cartella": "Cartella dei dati",
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Alerts;
|
||||
|
||||
/// <summary>
|
||||
/// The alerts of spec §13.3 (milestone M8): a stop reaches the strip of the interface, the Windows notification and
|
||||
/// Telegram; throttles, backfills, unknown formats and full disks are alerts too; the same alert is not repeated;
|
||||
/// the bot token never leaves the request to Telegram. Telegram is always a fake handler: never the real API.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class AlertServiceTests
|
||||
{
|
||||
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
/// <summary>M8, «Fatto quando»: un arresto simulato produce striscia, notifica e messaggio.</summary>
|
||||
[TestMethod]
|
||||
public async Task AStopForVerificationProducesTheStripTheNotificationAndTheTelegramMessage()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync();
|
||||
await using var host = new EngineHost(bed.Engine.Services, new ScriptedRunner(bed.Engine.Governor, bed.Engine.Clock));
|
||||
await using var web = await WebTestServer.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton<IFebeStorage>(bed.Engine.Db);
|
||||
s.AddSingleton<IClock>(bed.Engine.Clock);
|
||||
s.AddSingleton(host.Monitor);
|
||||
});
|
||||
|
||||
await bed.ReportAsync(SignalLevel.Challenge, "challenge-url");
|
||||
|
||||
// The strip of the interface: what the page reads from /api/engine (mockup 11).
|
||||
var engine = await web.GetJsonAsync("/api/engine");
|
||||
var snapshot = engine.GetProperty("snapshot");
|
||||
Assert.AreEqual("StoppedForVerification", snapshot.Str("mode"));
|
||||
var banner = snapshot.GetProperty("banner");
|
||||
Assert.AreEqual("Error", banner.Str("level"));
|
||||
Assert.AreEqual("Instagram chiede una verifica", banner.Str("title"));
|
||||
Assert.IsTrue(banner.Bool("needsResume"));
|
||||
StringAssert.Contains(banner.Str("message"), "«Riprendi»");
|
||||
|
||||
// The Windows notification, through the shell of the desktop.
|
||||
var notification = bed.Shell.Notifications.Single();
|
||||
Assert.AreEqual("Instagram chiede una verifica", notification.Title);
|
||||
Assert.AreEqual(
|
||||
"Ho fermato tutto alle 12:00 e non riparto da solo. Che cosa fare: apri Febe, poi il browser di Febe («Apri il browser»), completa la verifica a mano e premi «Riprendi».",
|
||||
notification.Message);
|
||||
|
||||
// One HTTPS POST to the Bot API, JSON, with the chat and the Italian text.
|
||||
var request = bed.Telegram.Requests.Single();
|
||||
Assert.AreEqual(HttpMethod.Post, request.Method);
|
||||
Assert.AreEqual($"https://api.telegram.org/bot{AlertBed.Token}/sendMessage", request.Uri.AbsoluteUri);
|
||||
Assert.AreEqual("application/json", request.ContentType);
|
||||
Assert.AreEqual(AlertBed.Chat, request.ChatId);
|
||||
Assert.AreEqual("Febe · Instagram chiede una verifica\n" + notification.Message, request.Text);
|
||||
|
||||
// The «Avvisi» list of Attività has the line too.
|
||||
var alerts = await web.GetJsonAsync("/api/alerts");
|
||||
var item = alerts.GetProperty("items").EnumerateArray().Single();
|
||||
Assert.AreEqual("verification", item.Str("kind"));
|
||||
Assert.AreEqual("error", item.Str("level"));
|
||||
Assert.AreEqual("Instagram chiede una verifica", item.Str("title"));
|
||||
|
||||
Assert.AreEqual(AlertOutcomeKind.Sent, bed.Outcomes.Single().Kind);
|
||||
StringAssert.Contains(bed.Log.All, "Avviso «Instagram chiede una verifica» inviato: notifica di Windows, Telegram.");
|
||||
var written = await bed.EverythingWrittenAsync();
|
||||
Assert.DoesNotContain(AlertBed.Token, written);
|
||||
Assert.DoesNotContain("api.telegram.org", written);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADisconnectionSaysToLogInAgain()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(windows: false);
|
||||
await bed.ReportAsync(SignalLevel.Disconnect, "cookie-mancante");
|
||||
|
||||
Assert.IsEmpty(bed.Shell.Notifications, "Windows notifications switched off");
|
||||
var text = bed.Telegram.Requests.Single().Text;
|
||||
StringAssert.StartsWith(text, "Febe · Instagram ha chiuso la sessione\n");
|
||||
StringAssert.Contains(text, "non provo a rientrare");
|
||||
StringAssert.Contains(text, "accedi a mano e premi «Riprendi»");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AThrottleStopAndItsEndAreTwoAlerts()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync();
|
||||
await using var host = new EngineHost(bed.Engine.Services, new ScriptedRunner(bed.Engine.Governor, bed.Engine.Clock));
|
||||
await bed.ReportAsync(SignalLevel.Throttle, "http-429");
|
||||
|
||||
var banner = (await host.Monitor.GetSnapshotAsync()).Banner!;
|
||||
Assert.AreEqual(BannerLevel.Warning, banner.Level);
|
||||
Assert.AreEqual("Instagram ha chiesto di rallentare", banner.Title);
|
||||
var stop = bed.Telegram.Requests.Single().Text;
|
||||
StringAssert.StartsWith(stop, "Febe · Instagram ha chiesto di rallentare\n");
|
||||
StringAssert.Contains(stop, "mi fermo per 1 ora, fino alle 13:00");
|
||||
StringAssert.Contains(stop, "Non devi fare nulla: riparto da solo.");
|
||||
|
||||
// After the hour the breaker reopens by itself: «…e ripresa».
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromHours(1));
|
||||
Assert.AreEqual(BreakerStatus.Closed, bed.Engine.Breaker.State.Status);
|
||||
await bed.Engine.Breaker.FlushAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
Assert.HasCount(2, bed.Telegram.Requests);
|
||||
var end = bed.Telegram.Requests[1].Text;
|
||||
StringAssert.StartsWith(end, "Febe · Fine del fermo per rallentamento\n");
|
||||
StringAssert.Contains(end, "tetti dimezzati");
|
||||
Assert.AreEqual("Fine del fermo per rallentamento", bed.Shell.Notifications[1].Title);
|
||||
Assert.IsNull((await host.Monitor.GetSnapshotAsync()).Banner, "the strip goes away by itself");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheBackfillOfAnAccountCompletedIsAnAlertOfItsOwn()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(start: Morning);
|
||||
var engine = bed.Engine;
|
||||
var account = await engine.AddAccountAsync("storico.demo", followed: true, state: AccountState.Backfilling, postCount: 30);
|
||||
var runner = new ScriptedRunner(engine.Governor, engine.Clock)
|
||||
{
|
||||
Script = r => r.Kind == RecipeKind.Backfill && r.AccountId == account.Id
|
||||
? new RecipeOutcome(RecipeStatus.Completed, 1, 12) { BackfillFinished = true }
|
||||
: null,
|
||||
};
|
||||
engine.Start(runner);
|
||||
await engine.RunUntilAsync(Morning.AddHours(14));
|
||||
await engine.StopAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
var backfill = bed.Telegram.Requests.Select(r => r.Text).Where(t => t.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(1, backfill);
|
||||
StringAssert.Contains(backfill[0], "Storico di @storico.demo completato");
|
||||
Assert.AreEqual(account.Id, bed.Outcomes.Single(o => o.Alert.Kind == AlertKind.BackfillDone).Alert.AccountId);
|
||||
|
||||
// Another account is another alert; the same account again within a day is not.
|
||||
var other = await engine.AddAccountAsync("altro.demo", followed: true);
|
||||
await bed.WriteEventAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di @altro.demo completato: 3 post in libreria.", other.Id);
|
||||
await bed.WriteEventAsync(EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di @storico.demo completato: 30 post in libreria.", account.Id);
|
||||
Assert.AreEqual(2, bed.Telegram.Requests.Count(r => r.Text.Contains("Storico completato", StringComparison.Ordinal)));
|
||||
Assert.AreEqual(AlertOutcomeKind.Repeated, bed.Outcomes[^1].Kind);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnknownFormatsAlertOnceAndTheSuspendedRecipeAgain()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(start: Morning);
|
||||
var engine = bed.Engine;
|
||||
await engine.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(engine.Governor, engine.Clock)
|
||||
{
|
||||
Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 1, 0) : null,
|
||||
};
|
||||
engine.Start(runner);
|
||||
await engine.RunUntilAsync(Morning.AddDays(2));
|
||||
await engine.StopAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
|
||||
var events = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.FormatUnrecognized] });
|
||||
Assert.IsGreaterThanOrEqualTo(2, events.Count, "several unknown formats in the timeline");
|
||||
var texts = bed.Telegram.Requests.Select(r => r.Text).ToList();
|
||||
var formats = texts.Where(t => t.StartsWith("Febe · Formato non riconosciuto\n", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(1, formats, "one message within six hours, however many times it happens");
|
||||
StringAssert.Contains(formats[0], "Formato non riconosciuto durante il controllo del profilo di @strano.demo");
|
||||
StringAssert.Contains(formats[0], "serve un campione nuovo con la sonda");
|
||||
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");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADiskAlmostFullIsCheckedWithThresholdsAndRemindedOnceADay()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(windows: false);
|
||||
const long GB = FakeFreeSpaceProbe.GB;
|
||||
|
||||
// 60 GB free of 1 TB: 6%, above both thresholds.
|
||||
bed.Disk.Set(AlertBed.LibraryFolder, 60 * GB, 1000 * GB);
|
||||
Assert.IsEmpty((await bed.Alerts.CheckDiskSpaceAsync()).Low);
|
||||
|
||||
// 40 GB of 1 TB: under 5%.
|
||||
bed.Disk.Set(AlertBed.LibraryFolder, 40 * GB, 1000 * GB);
|
||||
var check = await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
Assert.AreEqual("libreria", check.Key);
|
||||
var first = bed.Telegram.Requests.Single().Text;
|
||||
Assert.AreEqual(
|
||||
"Febe · Disco quasi pieno\nSul disco della libreria restano 40 GB liberi su 1.000 GB (4%). Continuo a lavorare, ma con il disco pieno gli scaricamenti non riusciranno. Che cosa fare: libera spazio su quel disco o sposta la cartella su un disco più capiente (guida, «Problemi comuni»).",
|
||||
first);
|
||||
var timeline = await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DiskLow] });
|
||||
Assert.AreEqual(EventSeverity.Warning, timeline.Single().Severity, "visible in Attività as a warning line");
|
||||
|
||||
// The same state a quarter of an hour later: no new line, no new message.
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromMinutes(15));
|
||||
await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
Assert.HasCount(1, bed.Telegram.Requests);
|
||||
|
||||
// The Data folder too (a small disk: 9 GB free of 120 GB is under 10 GB): a new set, a new alert.
|
||||
bed.Disk.Set(AlertBed.DataFolder, 9 * GB, 120 * GB);
|
||||
check = await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
Assert.AreEqual("libreria+dati", check.Key);
|
||||
Assert.HasCount(2, bed.Telegram.Requests);
|
||||
StringAssert.Contains(bed.Telegram.Requests[1].Text, "sul disco della cartella dei dati restano 9 GB liberi su 120 GB (7,5%)");
|
||||
StringAssert.Contains(bed.Telegram.Requests[1].Text, "il database non può più salvare nulla");
|
||||
|
||||
// A day later, still full: reminded once.
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromHours(24));
|
||||
await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
Assert.HasCount(3, bed.Telegram.Requests);
|
||||
|
||||
// Space freed, then only the Data folder full: a new set, a new alert.
|
||||
bed.Disk.Set(AlertBed.LibraryFolder, 500 * GB, 1000 * GB);
|
||||
bed.Disk.Set(AlertBed.DataFolder, 80 * GB, 120 * GB);
|
||||
Assert.IsEmpty((await bed.Alerts.CheckDiskSpaceAsync()).Low);
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromHours(1));
|
||||
bed.Disk.Set(AlertBed.DataFolder, 2 * GB, 120 * GB);
|
||||
await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
Assert.HasCount(4, bed.Telegram.Requests);
|
||||
StringAssert.StartsWith(bed.Telegram.Requests[3].Text, "Febe · Disco quasi pieno\nSul disco della cartella dei dati restano 2 GB");
|
||||
|
||||
// Flapping around the threshold: a new line in Attività each time, no new message within the interval.
|
||||
bed.Disk.Set(AlertBed.DataFolder, 12 * GB, 120 * GB);
|
||||
Assert.IsEmpty((await bed.Alerts.CheckDiskSpaceAsync()).Low);
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromHours(1));
|
||||
bed.Disk.Set(AlertBed.DataFolder, 9 * GB, 120 * GB);
|
||||
await bed.Alerts.CheckDiskSpaceAsync();
|
||||
await bed.Alerts.FlushAsync();
|
||||
Assert.HasCount(4, bed.Telegram.Requests);
|
||||
Assert.AreEqual(AlertOutcomeKind.Repeated, bed.Outcomes[^1].Kind);
|
||||
Assert.HasCount(5, await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DiskLow] }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TwoFoldersOnTheSameDiskAreNamedTogether()
|
||||
{
|
||||
var space = new FreeSpace(3 * FakeFreeSpaceProbe.GB, 200 * FakeFreeSpaceProbe.GB);
|
||||
var check = new DiskCheck([(WatchedFolder.Library("/l"), space), (WatchedFolder.Data("/d"), space)], []);
|
||||
StringAssert.StartsWith(check.Describe(), "Sul disco della libreria e della cartella dei dati restano 3 GB liberi su 200 GB (1,5%).");
|
||||
Assert.IsTrue(DiskThresholds.Default.IsLow(new FreeSpace(9 * FakeFreeSpaceProbe.GB, 10_000 * FakeFreeSpaceProbe.GB)));
|
||||
Assert.IsFalse(DiskThresholds.Default.IsLow(new FreeSpace(11 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB)));
|
||||
Assert.IsTrue(DiskThresholds.Default.IsLow(new FreeSpace(49 * FakeFreeSpaceProbe.GB, 1000 * FakeFreeSpaceProbe.GB)));
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheRealProbeMeasuresAnyFolderEvenOneNotYetCreated()
|
||||
{
|
||||
var probe = new DriveFreeSpaceProbe();
|
||||
var here = probe.Measure(AppContext.BaseDirectory);
|
||||
Assert.IsNotNull(here);
|
||||
Assert.IsGreaterThan(0L, here.TotalBytes);
|
||||
Assert.IsTrue(here.AvailableBytes >= 0 && here.AvailableBytes <= here.TotalBytes);
|
||||
var missing = probe.Measure(Path.Combine(AppContext.BaseDirectory, "non-ancora", "creata"));
|
||||
Assert.AreEqual(here.TotalBytes, missing?.TotalBytes, "the nearest existing folder is measured");
|
||||
Assert.IsNull(probe.Measure(string.Empty));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheDiskIsWatchedPeriodicallyOnTheClock()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(windows: false);
|
||||
bed.Disk.Set(AlertBed.DataFolder, 1 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB);
|
||||
using var cts = new CancellationTokenSource();
|
||||
var clock = bed.Engine.Clock;
|
||||
var watch = bed.Alerts.WatchDiskSpaceAsync(cts.Token);
|
||||
await WaitAsync(() => clock.PendingTimers > 0);
|
||||
Assert.IsEmpty(bed.Telegram.Requests, "the first check comes a minute after the start");
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await WaitAsync(() => bed.Telegram.Requests.Count == 1);
|
||||
StringAssert.Contains(bed.Telegram.Requests[0].Text, "cartella dei dati");
|
||||
await cts.CancelAsync();
|
||||
await watch;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSameStopFlappingIsNotRepeatedButComesBackAfterTheInterval()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync();
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync());
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
|
||||
Assert.HasCount(1, bed.Telegram.Requests, "a verification ten minutes after the first one is not sent again");
|
||||
Assert.HasCount(1, bed.Shell.Notifications);
|
||||
Assert.AreEqual(AlertOutcomeKind.Repeated, bed.Outcomes[^1].Kind);
|
||||
StringAssert.Contains(bed.Log.All, "non ripetuto");
|
||||
Assert.AreEqual(2, (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.ChallengeStop] })).Count, "the interface still shows both");
|
||||
|
||||
// Half an hour after the first one, the alert goes out again.
|
||||
Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync());
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromMinutes(25));
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
Assert.HasCount(2, bed.Telegram.Requests);
|
||||
|
||||
// A disconnection is another kind: not held back by the verification.
|
||||
Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync());
|
||||
await bed.ReportAsync(SignalLevel.Disconnect);
|
||||
Assert.HasCount(3, bed.Telegram.Requests);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARestartDoesNotSendTheSameAlertAgain()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync();
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
Assert.HasCount(1, bed.Telegram.Requests);
|
||||
|
||||
// A new alert service on the same database (a restart of the program), ten minutes later.
|
||||
bed.Alerts.Dispose();
|
||||
var outcomes = new List<AlertOutcome>();
|
||||
using var again = new AlertService(bed.Engine.Db.Settings, bed.Engine.Clock, bed.Engine.Services.Events, [new TelegramAlertChannel(bed.Client)]).Attach();
|
||||
again.Handled += (_, o) => outcomes.Add(o);
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromMinutes(10));
|
||||
Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync());
|
||||
await bed.Engine.Breaker.ReportAsync(new Signal(SignalLevel.Challenge, "di-nuovo", null, bed.Engine.Clock.Now));
|
||||
await bed.Engine.Breaker.FlushAsync();
|
||||
await again.FlushAsync();
|
||||
|
||||
Assert.HasCount(1, bed.Telegram.Requests);
|
||||
Assert.AreEqual(AlertOutcomeKind.Repeated, outcomes.Single().Kind);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task SwitchesAndMissingChannelsKeepAlertsInTheInterfaceOnly()
|
||||
{
|
||||
await using (var bed = await AlertBed.CreateAsync(events: AlertEvents.All with { Verification = false }))
|
||||
{
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
Assert.IsEmpty(bed.Telegram.Requests);
|
||||
Assert.IsEmpty(bed.Shell.Notifications);
|
||||
Assert.AreEqual(AlertOutcomeKind.NotWanted, bed.Outcomes.Single().Kind);
|
||||
Assert.AreEqual(1, (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = AlertCatalog.Codes })).Count, "still in Attività");
|
||||
}
|
||||
|
||||
await using (var bed = await AlertBed.CreateAsync(telegram: false, windows: false))
|
||||
{
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
Assert.IsEmpty(bed.Telegram.Requests);
|
||||
Assert.AreEqual(AlertOutcomeKind.NoChannel, bed.Outcomes.Single().Kind);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailedChannelIsAnEventWithoutTheTokenAndTheOtherChannelStillWorks()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync();
|
||||
bed.Telegram.Fail(HttpStatusCode.Unauthorized, "Unauthorized");
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
|
||||
Assert.HasCount(1, bed.Shell.Notifications, "the Windows notification does not depend on Telegram");
|
||||
var failure = (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] })).Single();
|
||||
Assert.AreEqual(EventSeverity.Warning, failure.Severity);
|
||||
Assert.AreEqual(
|
||||
"L'avviso «Instagram chiede una verifica» non è arrivato (Telegram): Telegram non riconosce il gettone del bot: copialo di nuovo per intero dal messaggio di BotFather. Lo trovi comunque qui in Febe; controlla Impostazioni ▸ Notifiche e usa «Invia una prova».",
|
||||
failure.Message);
|
||||
|
||||
// A second failure within the hour is logged but not written again in the timeline.
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromMinutes(40));
|
||||
Assert.IsTrue(await bed.Engine.Breaker.ResumeAsync());
|
||||
await bed.ReportAsync(SignalLevel.Throttle);
|
||||
Assert.HasCount(1, await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] }));
|
||||
Assert.AreEqual(2, bed.Log.Lines.Count(l => l.Level == AlertLogLevel.Warning && l.Message.Contains("non inviato (Telegram)", StringComparison.Ordinal)));
|
||||
|
||||
// The shell failing is recorded the same way.
|
||||
bed.Shell.Throws = true;
|
||||
bed.Telegram.Respond = null;
|
||||
bed.Engine.Clock.Advance(TimeSpan.FromHours(2));
|
||||
await bed.ReportAsync(SignalLevel.Throttle);
|
||||
var failures = await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] });
|
||||
StringAssert.Contains(failures[0].Message, "(notifica di Windows): Windows non ha mostrato la notifica");
|
||||
|
||||
var written = await bed.EverythingWrittenAsync();
|
||||
Assert.DoesNotContain(AlertBed.Token, written);
|
||||
Assert.DoesNotContain("tokendiprova", written);
|
||||
Assert.DoesNotContain("api.telegram.org", written);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ATelegramErrorThatNamesTheAddressNeverLeaksIt()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync();
|
||||
bed.Telegram.Respond = (request, _) => throw new HttpRequestException($"Connessione rifiutata verso {request.Uri.AbsoluteUri}");
|
||||
await bed.ReportAsync(SignalLevel.Disconnect);
|
||||
|
||||
var failure = (await bed.Engine.Db.Events.ListAsync(new EventQuery { Codes = [AlertEventCodes.DeliveryFailed] })).Single();
|
||||
StringAssert.Contains(failure.Message, "Telegram non è raggiungibile");
|
||||
var written = await bed.EverythingWrittenAsync();
|
||||
Assert.DoesNotContain(AlertBed.Token, written);
|
||||
Assert.DoesNotContain("api.telegram.org", written);
|
||||
Assert.DoesNotContain("tokendiprova", bed.Outcomes.Single().ToString());
|
||||
Assert.DoesNotContain(AlertBed.Token, (await AlertSettingsStore.LoadAsync(bed.Engine.Db.Settings)).ToString());
|
||||
|
||||
// «Invia una prova» answers the same way, without the address.
|
||||
var test = await new TelegramAlertChannel(bed.Client).SendTelegramTestAsync(await AlertSettingsStore.LoadAsync(bed.Engine.Db.Settings), CancellationToken.None);
|
||||
Assert.IsFalse(test.Sent);
|
||||
Assert.DoesNotContain(AlertBed.Token, test.Message);
|
||||
StringAssert.StartsWith(test.Message, "Nessun messaggio è partito. Telegram non è raggiungibile");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASlowTelegramTimesOut()
|
||||
{
|
||||
await using var bed = await AlertBed.CreateAsync(windows: false, telegramTimeout: TimeSpan.FromMilliseconds(300));
|
||||
bed.Telegram.Respond = async (_, ct) =>
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), ct);
|
||||
return FakeTelegramHandler.Answer(HttpStatusCode.OK, """{"ok":true}""");
|
||||
};
|
||||
var started = DateTime.UtcNow;
|
||||
await bed.ReportAsync(SignalLevel.Challenge);
|
||||
Assert.IsLessThan(TimeSpan.FromSeconds(10), DateTime.UtcNow - started);
|
||||
Assert.AreEqual(AlertOutcomeKind.Failed, bed.Outcomes.Single().Kind);
|
||||
StringAssert.Contains(bed.Outcomes.Single().Deliveries.Single().Delivery.Problem!, "non ha risposto entro");
|
||||
}
|
||||
|
||||
private async Task WaitAsync(Func<bool> condition)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||
while (!condition())
|
||||
{
|
||||
Assert.IsLessThan(deadline, DateTime.UtcNow, "condizione non raggiunta");
|
||||
await Task.Delay(20, TestContext.CancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Net;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Tests.Web.Part2Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
using Febe.Web.Engine;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Febe.Tests.Alerts;
|
||||
|
||||
/// <summary>The interface side of the alerts: «Invia una prova» with the real Telegram channel (fake handler), the «Avvisi» list of Attività.</summary>
|
||||
[TestClass]
|
||||
public sealed class AlertsApiTests
|
||||
{
|
||||
private const string Token = "987654321:AAHgettoneDaNonRimandareMai_42";
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheTestButtonSendsOneMessageThroughTheRealChannel()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
await using var server = await WebTestServer.StartAsync(services: s => s.AddSingleton<IAlertTestSender>(new TelegramAlertChannel(client)));
|
||||
var events = new { verification = true, disconnection = true, throttle = true, backfillDone = true, diskLow = true, unknownFormat = true };
|
||||
var (saveStatus, saveText) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
|
||||
new { events, windows = false, telegramChatId = "123456", telegramToken = Token, removeTelegramToken = false });
|
||||
Assert.AreEqual(HttpStatusCode.OK, saveStatus, saveText);
|
||||
|
||||
var settings = await server.GetJsonAsync("/api/settings/notifications");
|
||||
Assert.IsTrue(settings.Bool("telegramAvailable"), "the page no longer says that Telegram is missing");
|
||||
|
||||
var (status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, text);
|
||||
StringAssert.Contains(text, "\"sent\":true");
|
||||
Assert.DoesNotContain(Token, text);
|
||||
var request = handler.Requests.Single();
|
||||
Assert.AreEqual("123456", request.ChatId);
|
||||
Assert.AreEqual(TelegramAlertChannel.TestText, request.Text);
|
||||
|
||||
// Telegram refuses: the page gets the reason, never the token or the address.
|
||||
handler.Fail(HttpStatusCode.BadRequest, "Bad Request: chat not found");
|
||||
(status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, status);
|
||||
StringAssert.Contains(text, "\"sent\":false");
|
||||
StringAssert.Contains(text, "non trova la chat");
|
||||
Assert.DoesNotContain(Token, text);
|
||||
Assert.DoesNotContain("api.telegram.org", text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AMalformedTokenIsRefusedWhenSaved()
|
||||
{
|
||||
await using var server = await Part2.StartAsync();
|
||||
var events = new { verification = true, disconnection = true, throttle = true, backfillDone = true, diskLow = true, unknownFormat = true };
|
||||
var (status, text) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
|
||||
new { events, windows = false, telegramChatId = "123456", telegramToken = "123:abc/../altro", removeTelegramToken = false });
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, status);
|
||||
StringAssert.Contains(text, "BotFather");
|
||||
Assert.DoesNotContain("altro", text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheAlertsListOfAttivitaHasOnlyAlertsAndFailedDeliveries()
|
||||
{
|
||||
await using var server = await WebTestServer.StartAsync();
|
||||
var now = server.Clock.Now;
|
||||
async Task Add(TimeSpan ago, EventSeverity severity, string code, string message) =>
|
||||
await server.Db.Events.AppendAsync(new EventRecord { At = now - ago, Severity = severity, Code = code, Message = message });
|
||||
|
||||
await Add(TimeSpan.FromDays(20), EventSeverity.Error, EngineEventCodes.ChallengeStop, "troppo vecchio");
|
||||
await Add(TimeSpan.FromHours(5), EventSeverity.Success, EngineEventCodes.BackfillCompleted, "Storico di @marta.demo completato: 120 post in libreria.");
|
||||
await Add(TimeSpan.FromHours(4), EventSeverity.Info, "ricetta.ProfileCheck", "@marta.demo: nessuna novità");
|
||||
await Add(TimeSpan.FromHours(3), EventSeverity.Warning, AlertEventCodes.DiskLow, "Sul disco della libreria restano 8 GB liberi.");
|
||||
await Add(TimeSpan.FromHours(2), EventSeverity.Warning, AlertEventCodes.DeliveryFailed, "L'avviso «Disco quasi pieno» non è arrivato (Telegram): Telegram non è raggiungibile.");
|
||||
await Add(TimeSpan.FromHours(1), EventSeverity.Warning, EngineEventCodes.ThrottleStop, "Instagram ha chiesto di rallentare (segnale http-429).");
|
||||
|
||||
var list = await server.GetJsonAsync("/api/alerts");
|
||||
Assert.AreEqual(14, list.Int("days"));
|
||||
var items = list.GetProperty("items").EnumerateArray().ToList();
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "throttleStop", "deliveryFailed", "diskLow", "backfillDone" },
|
||||
items.Select(i => i.Str("kind")).ToArray());
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "Instagram ha chiesto di rallentare", "Avviso non inviato", "Disco quasi pieno", "Storico completato" },
|
||||
items.Select(i => i.Str("title")).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { "warning", "warning", "warning", "success" }, items.Select(i => i.Str("level")).ToArray());
|
||||
Assert.AreEqual("Sul disco della libreria restano 8 GB liberi.", items[2].Str("message"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASuspendedRecipeIsShownAndReactivatedFromAttivita()
|
||||
{
|
||||
var morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
|
||||
await using var bed = await EngineTestBed.CreateAsync(morning);
|
||||
await bed.AddAccountAsync("strano.demo", followed: false, Frequency.High);
|
||||
var runner = new ScriptedRunner(bed.Governor, bed.Clock)
|
||||
{
|
||||
Script = r => r.Kind == RecipeKind.ProfileCheck ? new RecipeOutcome(RecipeStatus.UnrecognizedFormat, 1, 0) : null,
|
||||
};
|
||||
var host = bed.Start(runner);
|
||||
await bed.RunUntilAsync(morning.AddDays(2));
|
||||
await using var server = await WebTestServer.StartAsync(services: s =>
|
||||
{
|
||||
s.AddSingleton(host.Monitor);
|
||||
s.AddSingleton<IEngineControl>(new EngineHostControl(host));
|
||||
});
|
||||
|
||||
var suspended = (await server.GetJsonAsync("/api/engine")).GetProperty("snapshot").GetProperty("suspendedRecipes").EnumerateArray().Single();
|
||||
Assert.AreEqual("ProfileCheck", suspended.Str("recipe"));
|
||||
Assert.AreEqual("Il controllo del profilo", suspended.Str("name"));
|
||||
|
||||
var (status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/engine/recipes/ProfileCheck/resume");
|
||||
Assert.AreEqual(HttpStatusCode.OK, status, text);
|
||||
StringAssert.Contains(text, "\"resumed\":true");
|
||||
Assert.IsFalse(host.SuspendedRecipes.ContainsKey(RecipeKind.ProfileCheck));
|
||||
(status, text) = await server.SendTextAsync(HttpMethod.Post, "/api/engine/recipes/ProfileCheck/resume");
|
||||
StringAssert.Contains(text, "\"resumed\":false");
|
||||
(status, _) = await server.SendTextAsync(HttpMethod.Post, "/api/engine/recipes/Inventata/resume");
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Tests.Engine.Support;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Alerts.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The engine's services on a temporary database and a virtual clock (<see cref="EngineTestBed"/>), with an
|
||||
/// <see cref="AlertService"/> listening to them: a fake desktop shell, a fake Telegram, a fake free-space probe on two
|
||||
/// folders. Telegram and Windows notifications are switched on unless asked otherwise.
|
||||
/// </summary>
|
||||
internal sealed class AlertBed : IAsyncDisposable
|
||||
{
|
||||
public const string Token = "4839574812:AAF-tokendiprova_SegretoDaNonMostrare";
|
||||
public const string Chat = "-100123456";
|
||||
public const string LibraryFolder = "/prova/libreria";
|
||||
public const string DataFolder = "/prova/dati";
|
||||
|
||||
private AlertBed(EngineTestBed engine, AlertService alerts, FakeNativeShell shell, FakeTelegramHandler telegram, FakeFreeSpaceProbe disk, AlertLogRecorder log, TelegramClient client)
|
||||
{
|
||||
Engine = engine;
|
||||
Alerts = alerts;
|
||||
Shell = shell;
|
||||
Telegram = telegram;
|
||||
Disk = disk;
|
||||
Log = log;
|
||||
Client = client;
|
||||
}
|
||||
|
||||
public EngineTestBed Engine { get; }
|
||||
|
||||
public AlertService Alerts { get; }
|
||||
|
||||
public FakeNativeShell Shell { get; }
|
||||
|
||||
public FakeTelegramHandler Telegram { get; }
|
||||
|
||||
public FakeFreeSpaceProbe Disk { get; }
|
||||
|
||||
public AlertLogRecorder Log { get; }
|
||||
|
||||
public TelegramClient Client { get; }
|
||||
|
||||
public List<AlertOutcome> Outcomes { get; } = [];
|
||||
|
||||
public static async Task<AlertBed> CreateAsync(bool telegram = true, bool windows = true, AlertEvents? events = null, TimeSpan? telegramTimeout = null, DateTimeOffset? start = null)
|
||||
{
|
||||
var engine = await EngineTestBed.CreateAsync(start);
|
||||
await AlertSettingsStore.SaveAsync(engine.Db.Settings, new AlertSettings(events ?? AlertEvents.All, windows, telegram ? Chat : null, telegram ? Token : null));
|
||||
var shell = new FakeNativeShell();
|
||||
var handler = new FakeTelegramHandler();
|
||||
var disk = new FakeFreeSpaceProbe();
|
||||
var log = new AlertLogRecorder();
|
||||
var client = new TelegramClient(handler, telegramTimeout);
|
||||
var alerts = new AlertService(
|
||||
engine.Db.Settings,
|
||||
engine.Clock,
|
||||
engine.Services.Events,
|
||||
[new NativeShellAlertChannel(shell), new TelegramAlertChannel(client)],
|
||||
new AlertServiceOptions
|
||||
{
|
||||
Folders = [WatchedFolder.Library(LibraryFolder), WatchedFolder.Data(DataFolder)],
|
||||
FreeSpace = disk,
|
||||
Log = log.Write,
|
||||
}).Attach();
|
||||
var bed = new AlertBed(engine, alerts, shell, handler, disk, log, client);
|
||||
alerts.Handled += (_, outcome) =>
|
||||
{
|
||||
lock (bed.Outcomes)
|
||||
{
|
||||
bed.Outcomes.Add(outcome);
|
||||
}
|
||||
};
|
||||
return bed;
|
||||
}
|
||||
|
||||
/// <summary>Reports a signal through the circuit breaker and waits for its incident, its event and its alert.</summary>
|
||||
public async Task ReportAsync(SignalLevel level, string code = "segnale-prova")
|
||||
{
|
||||
await Engine.Breaker.ReportAsync(new Signal(level, code, "https://sito.prova/x", Engine.Clock.Now));
|
||||
await Engine.Breaker.FlushAsync();
|
||||
await Alerts.FlushAsync();
|
||||
}
|
||||
|
||||
/// <summary>Writes a timeline event as the engine does and waits for its alert.</summary>
|
||||
public async Task WriteEventAsync(EventSeverity severity, string code, string message, long? accountId = null)
|
||||
{
|
||||
await Engine.Services.Events.WriteAsync(severity, code, message, accountId);
|
||||
await Alerts.FlushAsync();
|
||||
}
|
||||
|
||||
/// <summary>Everything the bed recorded that leaves Febe or stays on disk: log lines, events, alert texts.</summary>
|
||||
public async Task<string> EverythingWrittenAsync()
|
||||
{
|
||||
var events = await Engine.Db.Events.ListAsync(new EventQuery { Limit = 1000 });
|
||||
var settings = await Engine.Db.Settings.GetAllAsync();
|
||||
return string.Join(
|
||||
"\n",
|
||||
new[] { Log.All }
|
||||
.Concat(events.Select(e => e.Code + " " + e.Message))
|
||||
.Concat(Shell.Notifications.Select(n => n.Title + " " + n.Message))
|
||||
.Concat(Telegram.Requests.Select(r => r.Body))
|
||||
.Concat(Outcomes.SelectMany(o => o.Deliveries.Select(d => d.Delivery.Problem ?? string.Empty)))
|
||||
.Concat(settings.Where(s => s.Key != AlertSettingKeys.TelegramToken).Select(s => s.Key + "=" + s.Value)));
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Alerts.Dispose();
|
||||
Client.Dispose();
|
||||
await Engine.DisposeAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Web.Native;
|
||||
|
||||
namespace Febe.Tests.Alerts.Support;
|
||||
|
||||
/// <summary>A request that reached the fake Telegram.</summary>
|
||||
/// <param name="Method">HTTP method.</param>
|
||||
/// <param name="Uri">Full address (it contains the token: tests check it here, nowhere else).</param>
|
||||
/// <param name="ContentType">Media type of the body.</param>
|
||||
/// <param name="Body">The JSON body.</param>
|
||||
internal sealed record TelegramRequest(HttpMethod Method, Uri Uri, string? ContentType, string Body)
|
||||
{
|
||||
public string ChatId => JsonDocument.Parse(Body).RootElement.GetProperty("chat_id").GetString()!;
|
||||
|
||||
public string Text => JsonDocument.Parse(Body).RootElement.GetProperty("text").GetString()!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Telegram's Bot API, faked: records every request and answers with <see cref="Respond"/> (by default
|
||||
/// <c>200 {"ok":true}</c>). Never touches the network: the real api.telegram.org is never contacted from tests.
|
||||
/// </summary>
|
||||
internal sealed class FakeTelegramHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly ConcurrentQueue<TelegramRequest> _requests = new();
|
||||
|
||||
public Func<TelegramRequest, CancellationToken, Task<HttpResponseMessage>>? Respond { get; set; }
|
||||
|
||||
public IReadOnlyList<TelegramRequest> Requests => [.. _requests];
|
||||
|
||||
public static HttpResponseMessage Answer(HttpStatusCode status, string json) =>
|
||||
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
|
||||
/// <summary>Answers with <paramref name="status"/> and the usual error body of the Bot API.</summary>
|
||||
public void Fail(HttpStatusCode status, string description) =>
|
||||
Respond = (_, _) => Task.FromResult(Answer(status, $$"""{"ok":false,"error_code":{{(int)status}},"description":"{{description}}"}"""));
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var body = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken);
|
||||
var recorded = new TelegramRequest(request.Method, request.RequestUri!, request.Content?.Headers.ContentType?.MediaType, body);
|
||||
_requests.Enqueue(recorded);
|
||||
return Respond is { } respond
|
||||
? await respond(recorded, cancellationToken)
|
||||
: Answer(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The desktop shell, faked: it can notify and records the notifications.</summary>
|
||||
internal sealed class FakeNativeShell(bool canNotify = true) : INativeShell
|
||||
{
|
||||
private readonly ConcurrentQueue<(string Title, string Message)> _notifications = new();
|
||||
|
||||
public IReadOnlyList<(string Title, string Message)> Notifications => [.. _notifications];
|
||||
|
||||
public bool Throws { get; set; }
|
||||
|
||||
public bool CanPickFolder => false;
|
||||
|
||||
public bool CanShowInFolder => false;
|
||||
|
||||
public bool CanOpenUrl => false;
|
||||
|
||||
public bool CanNotify { get; } = canNotify;
|
||||
|
||||
public bool SupportsAutostart => false;
|
||||
|
||||
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult<string?>(null);
|
||||
|
||||
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task NotifyAsync(string title, string message, CancellationToken ct)
|
||||
{
|
||||
if (Throws)
|
||||
{
|
||||
throw new InvalidOperationException("notifiche spente");
|
||||
}
|
||||
|
||||
_notifications.Enqueue((title, message));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
|
||||
|
||||
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Free space by folder, as the test decides.</summary>
|
||||
internal sealed class FakeFreeSpaceProbe : IFreeSpaceProbe
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, FreeSpace?> _spaces = new(StringComparer.Ordinal);
|
||||
|
||||
public const long GB = 1024L * 1024 * 1024;
|
||||
|
||||
public void Set(string folder, long availableBytes, long totalBytes) => _spaces[folder] = new FreeSpace(availableBytes, totalBytes);
|
||||
|
||||
public void Unmeasurable(string folder) => _spaces[folder] = null;
|
||||
|
||||
public FreeSpace? Measure(string folder) => _spaces.TryGetValue(folder, out var space) ? space : new FreeSpace(500 * GB, 1000 * GB);
|
||||
}
|
||||
|
||||
/// <summary>The log lines of the alert service.</summary>
|
||||
internal sealed class AlertLogRecorder
|
||||
{
|
||||
private readonly ConcurrentQueue<(AlertLogLevel Level, string Message)> _lines = new();
|
||||
|
||||
public IReadOnlyList<(AlertLogLevel Level, string Message)> Lines => [.. _lines];
|
||||
|
||||
public string All => string.Join("\n", _lines.Select(l => l.Message));
|
||||
|
||||
public void Write(AlertLogLevel level, string message) => _lines.Enqueue((level, message));
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
|
||||
namespace Febe.Tests.Alerts;
|
||||
|
||||
/// <summary>The one call Febe makes to Telegram (spec §13.3), against a fake handler: never the real API.</summary>
|
||||
[TestClass]
|
||||
public sealed class TelegramClientTests
|
||||
{
|
||||
private const string Token = "123456789:AAEgettoneDiProva_moltoLungo-123";
|
||||
|
||||
[TestMethod]
|
||||
public async Task OnePostWithJsonToTheBotAddress()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
var result = await client.SendMessageAsync(" " + Token + " ", " 42 ", "Febe · Prova\nRiga «due» con accenti: è così", CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(result.Sent, result.Message);
|
||||
var request = handler.Requests.Single();
|
||||
Assert.AreEqual(HttpMethod.Post, request.Method);
|
||||
Assert.AreEqual("https", request.Uri.Scheme);
|
||||
Assert.AreEqual("api.telegram.org", request.Uri.Host);
|
||||
Assert.AreEqual($"/bot{Token}/sendMessage", request.Uri.AbsolutePath);
|
||||
Assert.AreEqual("application/json", request.ContentType);
|
||||
using var body = JsonDocument.Parse(request.Body);
|
||||
Assert.AreEqual("42", body.RootElement.GetProperty("chat_id").GetString());
|
||||
Assert.AreEqual("Febe · Prova\nRiga «due» con accenti: è così", body.RootElement.GetProperty("text").GetString());
|
||||
Assert.IsTrue(body.RootElement.GetProperty("disable_web_page_preview").GetBoolean());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(HttpStatusCode.BadRequest, "Bad Request: chat not found", TelegramOutcome.ChatNotFound, "non trova la chat")]
|
||||
[DataRow(HttpStatusCode.BadRequest, "Bad Request: message text is empty", TelegramOutcome.Rejected, "ha rifiutato il messaggio")]
|
||||
[DataRow(HttpStatusCode.Unauthorized, "Unauthorized", TelegramOutcome.InvalidToken, "non riconosce il gettone")]
|
||||
[DataRow(HttpStatusCode.NotFound, "Not Found", TelegramOutcome.InvalidToken, "non riconosce il gettone")]
|
||||
[DataRow(HttpStatusCode.Forbidden, "Forbidden: bot was blocked by the user", TelegramOutcome.Forbidden, "premi «Avvia»")]
|
||||
[DataRow(HttpStatusCode.TooManyRequests, "Too Many Requests: retry after 30", TelegramOutcome.RateLimited, "aspettare")]
|
||||
[DataRow(HttpStatusCode.BadGateway, "Bad Gateway", TelegramOutcome.ServerError, "riprova più tardi")]
|
||||
public async Task EveryRefusalHasItsItalianReason(HttpStatusCode status, string description, TelegramOutcome outcome, string words)
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
handler.Fail(status, description);
|
||||
using var client = new TelegramClient(handler);
|
||||
var result = await client.SendMessageAsync(Token, "42", "x", CancellationToken.None);
|
||||
Assert.AreEqual(outcome, result.Outcome);
|
||||
StringAssert.Contains(result.Message, words);
|
||||
Assert.DoesNotContain(description, result.Message, "Telegram's own answer is never passed on");
|
||||
Assert.DoesNotContain(Token, result.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnAnswerWithoutOkIsNotASend()
|
||||
{
|
||||
var handler = new FakeTelegramHandler { Respond = (_, _) => Task.FromResult(FakeTelegramHandler.Answer(HttpStatusCode.OK, """{"ok":false}""")) };
|
||||
using var client = new TelegramClient(handler);
|
||||
Assert.AreEqual(TelegramOutcome.ServerError, (await client.SendMessageAsync(Token, "42", "x", CancellationToken.None)).Outcome);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(null, "42", TelegramOutcome.NotConfigured)]
|
||||
[DataRow(Token, "", TelegramOutcome.NotConfigured)]
|
||||
[DataRow("123456789", "42", TelegramOutcome.MalformedToken)]
|
||||
[DataRow("123:abc/../../altro?x=1", "42", TelegramOutcome.MalformedToken)]
|
||||
[DataRow("123456789:AAE con spazi dentro", "42", TelegramOutcome.MalformedToken)]
|
||||
public async Task NothingLeavesWithoutAWellFormedTokenAndAChat(string? token, string chat, TelegramOutcome outcome)
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
var result = await client.SendMessageAsync(token, chat, "x", CancellationToken.None);
|
||||
Assert.AreEqual(outcome, result.Outcome);
|
||||
Assert.IsEmpty(handler.Requests);
|
||||
Assert.IsFalse(TelegramClient.IsValidToken(token) && outcome == TelegramOutcome.MalformedToken);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ALongTextIsShortened()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
await client.SendMessageAsync(Token, "42", new string('a', 10_000), CancellationToken.None);
|
||||
Assert.AreEqual(TelegramClient.MaxTextLength + 1, handler.Requests.Single().Text.Length);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ACancellationOfTheCallerIsNotATimeout()
|
||||
{
|
||||
var handler = new FakeTelegramHandler
|
||||
{
|
||||
Respond = async (_, ct) =>
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(30), ct);
|
||||
return FakeTelegramHandler.Answer(HttpStatusCode.OK, """{"ok":true}""");
|
||||
},
|
||||
};
|
||||
using var client = new TelegramClient(handler);
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => client.SendMessageAsync(Token, "42", "x", cts.Token), "the caller is stopping: no failure to report");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheTestMessageSaysWhereToLook()
|
||||
{
|
||||
var handler = new FakeTelegramHandler();
|
||||
using var client = new TelegramClient(handler);
|
||||
var channel = new TelegramAlertChannel(client);
|
||||
var settings = new AlertSettings(AlertEvents.All, false, "42", Token);
|
||||
var result = await channel.SendTelegramTestAsync(settings, CancellationToken.None);
|
||||
Assert.IsTrue(result.Sent);
|
||||
StringAssert.Contains(result.Message, "controlla la chat del bot");
|
||||
Assert.AreEqual(TelegramAlertChannel.TestText, handler.Requests.Single().Text);
|
||||
Assert.IsTrue(channel.IsEnabled(settings));
|
||||
Assert.IsFalse(channel.IsEnabled(settings with { TelegramChatId = null }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Febe.Tests.Docs;
|
||||
|
||||
/// <summary>
|
||||
/// The user guide (docs/guida, published as the wiki of the repository): every page exists, every link between pages
|
||||
/// points to a page that exists, and the guide says everything spec §15 lists under «Che cosa la guida deve dire per
|
||||
/// forza», on the pages where Alberto looks for it.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class GuideTests
|
||||
{
|
||||
/// <summary>The pages of the wiki, without «.md».</summary>
|
||||
public static readonly string[] Pages =
|
||||
[
|
||||
"Home",
|
||||
"Installazione-Docker-e-Unraid",
|
||||
"Installazione-Windows",
|
||||
"Primo-collegamento",
|
||||
"Account-e-impostazioni",
|
||||
"Libreria",
|
||||
"Importazione",
|
||||
"Limiti-e-comportamento",
|
||||
"Attivita-e-arresti",
|
||||
"Avvisi-e-Telegram",
|
||||
"Copie-e-ricostruzione",
|
||||
"Sicurezza-e-riservatezza",
|
||||
"Problemi-comuni",
|
||||
"Ipotesi-da-verificare",
|
||||
"Sviluppo",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// The mandatory points of spec §15: (point, pages that must say it, phrases that must all be there). Phrases are
|
||||
/// compared without case, emphasis and line breaks.
|
||||
/// </summary>
|
||||
public static IEnumerable<object[]> MandatoryPoints =>
|
||||
[
|
||||
["rischio per l'account e condizioni d'uso", new[] { "Home" }, new[] { "contro le condizioni d'uso di Instagram", "la limitazione o la chiusura dell'account" }],
|
||||
["che cosa fa Febe per ridurre il rischio", new[] { "Home" }, new[] { "che cosa fa febe per ridurre il rischio", "tetti giornalieri e orari", "al primo segnale di instagram si ferma" }],
|
||||
["che cosa Febe non fa", new[] { "Home" }, new[] { "che cosa febe non fa", "non risolve captcha", "non usa proxy", "azzerare il rischio" }],
|
||||
["le storie aperte da Febe risultano viste", new[] { "Home", "Account-e-impostazioni", "Sicurezza-e-riservatezza" }, new[] { "le storie aperte da febe risultano viste" }],
|
||||
["contenitore e desktop non insieme sullo stesso account", new[] { "Home", "Installazione-Docker-e-Unraid", "Installazione-Windows", "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "non vanno usati insieme sullo stesso account" }],
|
||||
["chi ha la cartella dei dati o una copia ha la sessione", new[] { "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "chi ha la cartella dei dati, o una sua copia, ha la sessione di instagram" }],
|
||||
["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" }],
|
||||
["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" }],
|
||||
["pagina sui problemi comuni (M8)", new[] { "Problemi-comuni" }, new[] { "formato non riconosciuto", "disco quasi pieno", "no usable sandbox", "manca la password dell'interfaccia" }],
|
||||
["ipotesi H1–H11 e S1–S6", new[] { "Ipotesi-da-verificare" }, new[] { "| h1 |", "| h11 |", "| s1 |", "| s6 |", "account di prova" }],
|
||||
];
|
||||
|
||||
public static string GuideFolder()
|
||||
{
|
||||
var folder = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (folder is not null && !File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
|
||||
{
|
||||
folder = folder.Parent;
|
||||
}
|
||||
|
||||
if (folder is null)
|
||||
{
|
||||
Assert.Inconclusive("Radice del repository non trovata.");
|
||||
}
|
||||
|
||||
var guide = Path.Combine(folder.FullName, "docs", "guida");
|
||||
var isCheckout = Directory.Exists(Path.Combine(folder.FullName, ".git")) || File.Exists(Path.Combine(folder.FullName, ".git"));
|
||||
if (!Directory.Exists(guide) && !isCheckout)
|
||||
{
|
||||
// The build of the Docker image copies the sources without docs/ (see .dockerignore).
|
||||
Assert.Inconclusive("Questa copia del repository non ha docs/ (costruzione dell'immagine Docker).");
|
||||
}
|
||||
|
||||
Assert.IsTrue(Directory.Exists(guide), guide);
|
||||
return guide;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryPageExistsWithATitle()
|
||||
{
|
||||
var guide = GuideFolder();
|
||||
foreach (var page in Pages)
|
||||
{
|
||||
var path = Path.Combine(guide, page + ".md");
|
||||
Assert.IsTrue(File.Exists(path), $"manca la pagina {page}");
|
||||
var first = File.ReadLines(path).First();
|
||||
StringAssert.StartsWith(first, "# ", $"{page}: la prima riga è il titolo");
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(Path.Combine(guide, "_Sidebar.md")), "manca _Sidebar.md");
|
||||
var unknown = Directory.EnumerateFiles(guide, "*.md")
|
||||
.Select(Path.GetFileNameWithoutExtension)
|
||||
.Where(name => name != "_Sidebar" && !Pages.Contains(name))
|
||||
.ToList();
|
||||
Assert.IsEmpty(unknown, "pagine non elencate in GuideTests.Pages: " + string.Join(", ", unknown));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryWikiLinkPointsToAnExistingPage()
|
||||
{
|
||||
var guide = GuideFolder();
|
||||
var problems = new List<string>();
|
||||
var linkedFrom = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
|
||||
foreach (var file in Directory.EnumerateFiles(guide, "*.md"))
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(file);
|
||||
var targets = new HashSet<string>(StringComparer.Ordinal);
|
||||
// Code is not a link: «`[Testo](Nome-Pagina)`» explains the format.
|
||||
var text = InlineCode().Replace(FencedCode().Replace(File.ReadAllText(file), string.Empty), string.Empty);
|
||||
foreach (Match match in Link().Matches(text))
|
||||
{
|
||||
var target = match.Groups["target"].Value;
|
||||
if (target.StartsWith("http://", StringComparison.Ordinal) || target.StartsWith("https://", StringComparison.Ordinal) || target.StartsWith("mailto:", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!WikiPage().IsMatch(target))
|
||||
{
|
||||
problems.Add($"{name}: «{target}» non è il nome di una pagina del wiki (niente .md, cartelle o ancore)");
|
||||
}
|
||||
else if (!File.Exists(Path.Combine(guide, target + ".md")) || target == "_Sidebar")
|
||||
{
|
||||
problems.Add($"{name}: «{target}» non esiste");
|
||||
}
|
||||
|
||||
targets.Add(target);
|
||||
}
|
||||
|
||||
linkedFrom[name] = targets;
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join("\n", problems));
|
||||
var fromSidebar = linkedFrom["_Sidebar"];
|
||||
var fromHome = linkedFrom["Home"];
|
||||
foreach (var page in Pages)
|
||||
{
|
||||
Assert.Contains(page, fromSidebar, $"la barra laterale non porta a {page}");
|
||||
if (page != "Home")
|
||||
{
|
||||
Assert.Contains(page, fromHome, $"l'indice della pagina iniziale non porta a {page}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DynamicData(nameof(MandatoryPoints))]
|
||||
public void TheGuideSaysWhatTheSpecificationRequires(string point, string[] pages, string[] phrases)
|
||||
{
|
||||
var guide = GuideFolder();
|
||||
foreach (var page in pages)
|
||||
{
|
||||
var text = Normalize(File.ReadAllText(Path.Combine(guide, page + ".md")));
|
||||
var missing = phrases.Where(p => !text.Contains(Normalize(p), StringComparison.Ordinal)).ToList();
|
||||
Assert.IsEmpty(missing, $"«{point}»: in {page} mancano: {string.Join(" | ", missing)}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Lower case, typographic apostrophes as plain ones, no emphasis, one space for any run of blanks.</summary>
|
||||
public static string Normalize(string text)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
var plain = text.Replace("**", string.Empty, StringComparison.Ordinal).Replace('’', '\'').ToLowerInvariant();
|
||||
return Blanks().Replace(plain, " ");
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"(?<!!)\[[^\]]*\]\((?<target>[^)\s]+)\)")]
|
||||
private static partial Regex Link();
|
||||
|
||||
[GeneratedRegex(@"^_?[A-Za-z0-9]+(-[A-Za-z0-9]+)*$")]
|
||||
private static partial Regex WikiPage();
|
||||
|
||||
[GeneratedRegex(@"\s+")]
|
||||
private static partial Regex Blanks();
|
||||
|
||||
[GeneratedRegex(@"^```.*?^```", RegexOptions.Singleline | RegexOptions.Multiline)]
|
||||
private static partial Regex FencedCode();
|
||||
|
||||
[GeneratedRegex(@"`[^`\n]*`")]
|
||||
private static partial Regex InlineCode();
|
||||
}
|
||||
@@ -7,6 +7,7 @@ using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Alerts.Support;
|
||||
using Febe.Tests.Server.Support;
|
||||
using Febe.Web.Connection;
|
||||
|
||||
@@ -38,7 +39,9 @@ public sealed partial class ServerEndToEndTests
|
||||
public async Task TheRealServerCollectsFromTheTestSiteStopsAtTheVerificationAndShowsTheBrowser()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ServerTestBed.StartAsync();
|
||||
var telegram = new FakeTelegramHandler();
|
||||
var disk = new FakeFreeSpaceProbe();
|
||||
await using var bed = await ServerTestBed.StartAsync(telegram: telegram, freeSpace: disk);
|
||||
var server = bed.Server;
|
||||
Assert.IsEmpty(server.Problems);
|
||||
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
|
||||
@@ -130,6 +133,11 @@ public sealed partial class ServerEndToEndTests
|
||||
// The site asks for a verification: at its next action toward the site the engine stops and the banner appears
|
||||
// in /api/engine. Usually still in the first session (two accounts to read in full); if that session already
|
||||
// ended, in the next one, after the minimum pause (20 minutes at 10×: two real minutes).
|
||||
// Alerts on Telegram (M8): token and chat set from Impostazioni ▸ Notifiche; the composition sends through the fake.
|
||||
const string token = "4839574812:AAF-gettoneDelServerDiProva_123";
|
||||
var events = """{"verification":true,"disconnection":true,"throttle":true,"backfillDone":true,"diskLow":true,"unknownFormat":true}""";
|
||||
await bed.JsonAsync(HttpMethod.Put, "/api/settings/notifications", $$"""{"events":{{events}},"windows":false,"telegramChatId":"42","telegramToken":"{{token}}","removeTelegramToken":false}""");
|
||||
|
||||
var servedBefore = bed.Site.Control.CdnFilesServed;
|
||||
bed.Site.Control.Set(StopMode.Challenge);
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
@@ -144,6 +152,24 @@ public sealed partial class ServerEndToEndTests
|
||||
Assert.AreEqual(ConnectionState.VerificationRequired, (await connection.GetStatusAsync(ct)).State);
|
||||
TestContext.WriteLine($"CDN: {servedBefore} file prima del fermo, {bed.Site.Control.CdnFilesServed} adesso.");
|
||||
|
||||
// The same stop reached Telegram, with the Italian text, and the «Avvisi» list of Attività.
|
||||
await ServerTestBed.WaitUntilAsync(
|
||||
() => Task.FromResult(telegram.Requests.Any(r => r.Text.StartsWith("Febe · Instagram chiede una verifica\n", StringComparison.Ordinal))),
|
||||
TimeSpan.FromSeconds(20),
|
||||
"il messaggio Telegram della verifica");
|
||||
var message = telegram.Requests.First(r => r.Text.StartsWith("Febe · Instagram chiede una verifica", StringComparison.Ordinal));
|
||||
Assert.AreEqual($"/bot{token}/sendMessage", message.Uri.AbsolutePath);
|
||||
Assert.AreEqual("42", message.ChatId);
|
||||
StringAssert.Contains(message.Text, "premi «Riprendi»");
|
||||
var alerts = await bed.JsonAsync(HttpMethod.Get, "/api/alerts");
|
||||
Assert.IsTrue(alerts.GetProperty("items").EnumerateArray().Any(i => i.GetProperty("kind").GetString() == "verification"));
|
||||
foreach (var file in Directory.EnumerateFiles(server.Data!.Logs))
|
||||
{
|
||||
var log = await ReadSharedAsync(file, ct);
|
||||
Assert.DoesNotContain(token, log, file);
|
||||
Assert.DoesNotContain("api.telegram.org", log, file);
|
||||
}
|
||||
|
||||
// The remote view: meta first, then JPEG frames; Alberto is driving while it is open.
|
||||
using (var socket = await bed.OpenRemoteViewAsync(ct))
|
||||
{
|
||||
@@ -262,4 +288,11 @@ public sealed partial class ServerEndToEndTests
|
||||
|
||||
[GeneratedRegex(@"^(post|storie|evidenza/[^/]+|taggati)/(\d{4}/)?\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_[^_/]+_\d+\.(jpg|mp4)$")]
|
||||
private static partial Regex NamePattern();
|
||||
|
||||
private static async Task<string> ReadSharedAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||
using var reader = new StreamReader(stream);
|
||||
return await reader.ReadToEndAsync(ct);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using System.Text;
|
||||
using System.Text.Json;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Server;
|
||||
using Febe.SitoDiProva;
|
||||
@@ -56,7 +57,7 @@ internal sealed class ServerTestBed : IAsyncDisposable
|
||||
|
||||
public static string? UnavailableReason() => RealBrowser.UnavailableReason();
|
||||
|
||||
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10)
|
||||
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null)
|
||||
{
|
||||
var temp = new TempFolder("server");
|
||||
var site = await TestSite.StartAsync(new TestSiteOptions());
|
||||
@@ -86,7 +87,7 @@ internal sealed class ServerTestBed : IAsyncDisposable
|
||||
FebeServer server;
|
||||
try
|
||||
{
|
||||
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null });
|
||||
server = await FebeServer.StartAsync(options, new ServerHooks { Clock = clock, Random = new SeededRandom(20261013), Console = TextWriter.Null, TelegramHandler = telegram, FreeSpace = freeSpace });
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -178,8 +178,8 @@ public sealed class SettingsApiTests
|
||||
|
||||
var (testStatus, test) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
|
||||
Assert.AreEqual(HttpStatusCode.OK, testStatus);
|
||||
Assert.IsFalse(test.Bool("sent"), "the Telegram sender arrives with M8");
|
||||
Assert.AreEqual(TelegramNotAvailableYet.Text, test.Str("message"));
|
||||
Assert.IsFalse(test.Bool("sent"), "without a composition nothing leaves (no network in tests and in the demo)");
|
||||
Assert.AreEqual(NoTelegramSender.Text, test.Str("message"));
|
||||
var (windowsStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "windows" });
|
||||
Assert.AreEqual(HttpStatusCode.BadRequest, windowsStatus);
|
||||
|
||||
|
||||
Reference in new issue
Block a user