diff --git a/docker/Dockerfile b/docker/Dockerfile index 4e3b896..0f3f2a1 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -147,6 +147,8 @@ ENV LANG=it_IT.UTF-8 \ DOTNET_gcServer=0 WORKDIR /app +# Niente /esporta qui (né nel mkdir qui sopra): un volume anonimo la farebbe sembrare montata (SPECIFICA §4.10, §11). +# Le copie esterne si accendono solo con FEBE_ESPORTA=1 (o --esporta) e una cartella del server montata su /esporta. VOLUME ["/dati", "/libreria", "/importa"] # Solo la porta dell'interfaccia. La porta di debug del browser ascolta su 127.0.0.1 dentro il contenitore e non si diff --git a/docker/compose.yml b/docker/compose.yml index c1c4c9d..c8b8af7 100644 --- a/docker/compose.yml +++ b/docker/compose.yml @@ -43,6 +43,9 @@ services: - ${FEBE_LIBRERIA:-/srv/febe/libreria}:/libreria # Cartelle da importare, sempre in sola lettura. - ${FEBE_IMPORTA:-/srv/febe/importa}:/importa:ro + # Facoltativa: la cartella delle copie esterne (specifica §4.10), con FEBE_ESPORTA: "1" qui sotto. Senza una + # cartella montata su /esporta (o sotto) Febe non scrive nulla fuori dalla libreria. Vedi docs/docker.md. + # - ${FEBE_CARTELLA_ESPORTA:-/srv/febe/esporta}:/esporta environment: FEBE_PASSWORD: ${FEBE_PASSWORD:?Imposta FEBE_PASSWORD, la password dell interfaccia} TZ: Europe/Rome @@ -55,4 +58,5 @@ services: # FEBE_SENZA_SANDBOX: "1" # solo se Chromium non parte: vedi docs/docker.md, «Sandbox» # FEBE_RACCOLTA: "pagine" # pagine (predefinito) o richieste: vedi docs/docker.md, «Variabili» # FEBE_CHIAVE_SESSIONE: ${FEBE_CHIAVE_SESSIONE} # chiave della sessione salvata fuori da /dati (openssl rand -base64 32) + # FEBE_ESPORTA: "1" # copie esterne accese, con la cartella montata su /esporta (sopra) # Chromium usa /tmp invece della memoria condivisa (--disable-dev-shm-usage): shm_size non serve. diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 7142152..1e6a9c3 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -8,7 +8,9 @@ # Sempre exec, mai un processo figlio: il server prende il posto di questo script come processo 1 del contenitore # (niente tini), riceve SIGTERM da «docker stop» e, con il runtime .NET, raccoglie i processi rimasti orfani. # Nessun ciclo di sorveglianza qui: è il lavoro di Febe.Server (niente script di shell che facciano da supervisore). -# /libreria non si cambia mai ricorsivamente (sono le foto di Alberto); /importa è in sola lettura e non si tocca. +# /libreria non si cambia mai ricorsivamente (sono le foto di Alberto); /importa è in sola lettura e non si tocca; +# di /esporta (le copie esterne, specifica §4.10) si assegna solo la radice, mai ricorsivamente, e solo se le copie +# esterne sono dichiarate (FEBE_ESPORTA=1 o --esporta). # Se /dati non si può sistemare (disco di rete, permessi) si parte lo stesso: è Febe a spiegare il problema nella sua # pagina, invece di un contenitore che si riavvia senza dire perché. set -eu @@ -63,6 +65,14 @@ if [ -d /libreria ] && [ "$(stat -c '%u' /libreria)" = "0" ]; then chown "${PUID}:${PGID}" /libreria 2>/dev/null || true fi +# /esporta: solo la radice, mai ricorsivo, e solo se le copie esterne sono dichiarate (SPECIFICA §4.10). Dentro ci +# sono file di Alberto copiati da Febe o messi da lui: non si cambiano mai. Febe non crea /esporta se manca. +case "${FEBE_ESPORTA:-}" in 1|true|sì|si|yes) esporta=1 ;; *) esporta= ;; esac +case " $* " in *" --esporta "*) esporta=1 ;; esac +if [ -n "$esporta" ] && [ -d /esporta ] && [ "$(stat -c '%u' /esporta)" = "0" ]; then + chown "${PUID}:${PGID}" /esporta 2>/dev/null || true +fi + export HOME=/dati/home echo "Febe: avvio come utente ${PUID}, gruppo ${PGID}, fuso ${TZ:-Europe/Rome}, lingua ${LANG:-it_IT.UTF-8}." exec setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups "$@" diff --git a/docker/unraid/febe.xml b/docker/unraid/febe.xml index c9d1bd9..cb324da 100644 --- a/docker/unraid/febe.xml +++ b/docker/unraid/febe.xml @@ -9,7 +9,7 @@ false http://192.168.30.23:3000/Alby96/Febe/issues http://192.168.30.23:3000/Alby96/Febe - Febe: archivio personale di foto, video e storie da Instagram. Un browser vero (Chromium su un display virtuale) visita i profili a ritmo umano, con tetti giornalieri, e salva cio' che la pagina riceve in una libreria di file sul server. Si accede una volta sola, a mano, dalla vista remota della pagina Impostazioni, Collegamento: password e codici passano dal server senza essere registrati, quindi l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS. La cartella /dati contiene la sessione di Instagram: chi ha /dati, o una sua copia, ha la sessione. Non usare il contenitore e Febe per Windows sullo stesso account. Unica variabile obbligatoria: la password dell'interfaccia. Guida: docs/docker.md nel repository. + Febe: archivio personale di foto, video e storie da Instagram. Un browser vero (Chromium su un display virtuale) visita i profili a ritmo umano, con tetti giornalieri, e salva cio' che la pagina riceve in una libreria di file sul server. Si accede una volta sola, a mano, dalla vista remota della pagina Impostazioni, Collegamento: password e codici passano dal server senza essere registrati, quindi l'interfaccia non va mai esposta su Internet senza una VPN o un proxy con HTTPS. La cartella /dati contiene la sessione di Instagram: chi ha /dati, o una sua copia, ha la sessione. Non usare il contenitore e Febe per Windows sullo stesso account. Unica variabile obbligatoria: la password dell'interfaccia. Facoltative le copie esterne: una cartella montata su /esporta e FEBE_ESPORTA=1; le copie escono dal controllo di Febe, che non le cifra e non le cancella. Guida: docs/docker.md nel repository. Backup: MediaApp:Photos http://[IP]:[PORT:8480]/ http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml @@ -26,6 +26,7 @@ /mnt/user/appdata/febe /mnt/user/Febe /mnt/user/Febe-importa + Europe/Rome 99 @@ -34,4 +35,5 @@ + diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index 33af7dc..6f63595 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -259,18 +259,18 @@ Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più ### 4.10 Esportazione -Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Finché le tappe non sono unite, l'unica esportazione è l'elenco CSV di §4.8. +Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; formati e fotogrammi con E3, video fermi con E4, l'automatica con E5. Fino a E3 ed E4 i loro comandi («Fotogrammi…», «Fotogramma», «È un video fermo?», i formati e la conversione della libreria) mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario. **Principio.** Un'esportazione copia in una cartella esterna (una **destinazione**) file che sono già in libreria: così come sono, convertiti in un altro formato o come fotogramma di un video. È solo lavoro sul disco: niente Instagram, niente CDN, niente Governatore, niente `action_log`. Un file che manca in libreria non si riscarica: la copia dice «File non presente in libreria». **Destinazioni.** -- Una **cartella di esportazione generale** (Impostazioni → Esportazione) e, per ogni account, una **cartella propria facoltativa** che la sostituisce, con l'interruttore **«Esporta questo account»** (scheda account → Impostazioni, blocco «Copie esterne», sotto «Cartella»). Ogni account ha al più una destinazione effettiva: «già copiato» è un sì o un no. +- Una **cartella di esportazione generale** (Impostazioni → Esportazione) e, per ogni account, una **cartella propria facoltativa** che la sostituisce, con l'interruttore **«Esporta questo account»** (scheda account → Impostazioni, blocco «Copie esterne», sotto «Cartella»). Ogni account ha al più una destinazione effettiva: «già copiato» è un sì o un no. **«Esporta questo account» è acceso per impostazione predefinita** (decisione di Alberto del 27 novembre 2026): un account senza scelta registrata si esporta; spento, «Copia in…» lo salta, anche quando la si chiede a mano (proposta applicata dalla tappa E2, §16 domanda 22), e la finestra lo conta fra i file «di account che non si esportano»; le copie già fatte restano. - Nella cartella generale Febe mette sempre per primo il segmento con il nome dell'account ripulito, perché gli account non si scontrino; sotto vale lo schema dei nomi della destinazione, «Come la libreria» (predefinito) oppure uno proprio, controllato come quelli di §4.7. I suffissi dei fotogrammi (`_fotogramma`, `_t0m12s340`, `_f001`) si aggiungono prima dell'accorciamento a 240 caratteri. - Ogni destinazione dice: tipi di contenuto (post foto, post video, storie, evidenza, taggati, profilo), formati delle copie, schema dei nomi, «Automatica». - Cartelle rifiutate: dentro **o contenenti** Dati, Libreria, una cartella di account (anche fuori dalla Libreria) o `/importa`; la radice di un disco o di una condivisione. Lettere di unità e percorsi UNC che puntano allo stesso posto si riconoscono con un file di prova, non confrontando i testi: un `.febe-prova-*.part` scritto e tolto come quello del punto qui sotto, **solo nella cartella candidata**, che deve già esistere, e mai in Dati, Libreria, cartelle degli account o `/importa`. Lì Febe lo cerca soltanto, in lettura: risalendo le loro cartelle madri (una di loro è dentro la candidata) e, per ogni cartella madre della candidata, allo stesso percorso relativo sotto ciascuna (la candidata è dentro una di loro). Se il file di prova non si scrive, la cartella si rifiuta. Si ricontrolla quando cambia la cartella di un account. - **La radice di una destinazione non si crea mai**: un disco o una condivisione assente non deve diventare una cartella locale. Le sottocartelle dello schema sì. Prima di ogni gruppo di copie Febe scrive e toglie un file `.febe-prova-*.part`; se non riesce, la destinazione va in pausa, lo stato si vede in Impostazioni e nella Dashboard e il giro orario riprova. Mai la striscia rossa, che resta del motore. I controlli sul disco esterno sono asincroni e brevi: una condivisione staccata non blocca l'interfaccia. -- Spazio: per le destinazioni non valgono i 10 GB / 5 % della libreria; basta spazio libero per il prossimo file più un margine. Su FAT32 conta il limite di 4 GB per file. +- Spazio: per le destinazioni non valgono i 10 GB / 5 % della libreria; basta spazio libero per il prossimo file più un margine (64 MB, proposta, §16 domanda 27). Su FAT32 conta il limite di 4 GB per file. - **Mai sovrascrivere, mai cancellare** (regola 12): si scrive con un `.part`, si verifica lo SHA-256, si rinomina su un nome libero. Togliere una destinazione toglie solo la configurazione («I file già copiati restano dove sono»); le copie registrate restano nel database, legate alla destinazione ritirata; eliminare un elemento dalla libreria non tocca le sue copie. I `.part` rimasti si tolgono solo nelle cartelle di lavori non finiti, mai con una scansione della destinazione. **Conversione del formato.** Due impostazioni distinte, **entrambe spente** per impostazione predefinita: @@ -296,14 +296,15 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo **Manuale e automatica.** - **Manuale sempre**: «Copia in…» dalla selezione, dal filtro corrente, dal visualizzatore e dalla scheda dell'account. -- **Automatica spenta** per ogni destinazione. Quando Alberto l'accende, Febe chiede che cosa fare di ciò che è già in libreria; la risposta proposta è **«Solo i nuovi»**. Un elemento nuovo entra in coda dopo la sua riga di `_febe.jsonl`; un giro di recupero all'avvio e ogni ora. +- **Automatica spenta** per ogni destinazione. Quando Alberto l'accende, Febe chiede che cosa fare di ciò che è già in libreria; la risposta proposta è **«Solo i nuovi»**. Un elemento nuovo entra in coda dopo la sua riga di `_febe.jsonl`; un giro di recupero all'avvio e ogni ora. Nella tappa E2 l'interruttore non si mostra: la scelta si registra (database e interfaccia di programmazione), ma nulla la usa fino a E5 (proposta, §16 domanda 24). **«Già copiato».** - Una riga per copia (`export_copy`). Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo** (quello del segmento con il nome dell'account nella cartella generale, o l'account della cartella propria), variante (intero, convertito, fotogramma), formato e istante del fotogramma; la riga tiene anche percorso relativo, byte e SHA-256 della copia, data, stato. Si cerca per SHA-256, non per l'identificativo di Instagram, che gli importati possono non avere: un elemento eliminato con «Eliminalo e lascia che torni» ritrova le sue copie quando torna. -- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà. +- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta: dal visualizzatore, un file alla volta, o per tutti quelli scelti con la casella «Copia di nuovo anche i N tolti o superati» della finestra «Copia in…», spenta all'apertura (proposta, §16 domanda 25). «Tolto» lo trova «Controlla le copie» (Impostazioni → Esportazione), che guarda soltanto: con la radice della destinazione irraggiungibile non segna nulla come tolto e mette la destinazione in pausa. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà. - **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato. La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione. - Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»). +- **File dovuti** (tappa E2): un file è dovuto quando è presente in libreria (scaricato o importato, con il suo SHA-256), il suo account ha «Esporta questo account» acceso e una destinazione effettiva, e il suo tipo di contenuto è fra quelli della destinazione (post foto, post video, storie, evidenza, taggati, profilo; una storia in una raccolta in evidenza è anche evidenza). Il segno sulla tessera, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» considerano solo i file dovuti (proposta, §16 domanda 26), così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. Le tre scelte del filtro dividono i file dovuti senza sovrapporsi: «Copiati» (copia corrente «Copiato»), «Tolti o superati» (l'ultima copia è «Tolto» o «Superato»), «Non ancora copiati» (tutti gli altri, «Non riuscito» compreso, che la copia successiva riprova). Un account spento non ha file dovuti. - Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo»), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie». **Casi particolari.** @@ -311,7 +312,7 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo - **Lo stesso post in due account** (il post dell'uno e il taggato dell'altro, §8.3): un'impostazione sceglie fra **«Una copia per account»**, ognuna nella sua destinazione, che è il **predefinito** (risposta di Alberto del 18 novembre 2026), e **«Una copia sola»**, nel primo account che la copia; l'altro la mostra «Copiato» con la destinazione dove sta. Lo si riconosce dallo SHA-256. - **Una storia entrata in una raccolta in evidenza** conta anche come evidenza: una destinazione con il solo tipo «evidenza» la copia. Per lo stesso account effettivo un file si copia una volta sola in una destinazione: la storia e la sua evidenza sono una copia. Con «una copia per account» (qui sopra) lo stesso SHA-256 sta invece due volte nella cartella generale, una sotto il segmento di ciascun account. -**Docker e Windows.** In Docker le destinazioni sono sottocartelle di `/esporta`, scelte da un elenco come le sorgenti di importazione (`..` rifiutato). `/esporta` è attivo **solo se dichiarato** con `--esporta` o `FEBE_ESPORTA` e solo se è davvero un punto di montaggio (letto da `/proc/self/mountinfo`): altrimenti non si scrive nulla. Nel Dockerfile non c'è una riga `VOLUME` per `/esporta`: un volume anonimo la farebbe sembrare montata e riempirebbe in silenzio il disco delle immagini di Unraid (§11). Si cambia il proprietario solo della radice, mai in modo ricorsivo. Su Windows la cartella si sceglie con il selettore nativo, anche su un percorso di rete o UNC (§12). +**Docker e Windows.** In Docker le destinazioni sono sottocartelle di `/esporta`, scelte da un elenco come le sorgenti di importazione (`..` rifiutato, come testo, prima di ogni normalizzazione; `/esporta` stessa non è una destinazione). `/esporta` è attivo **solo se dichiarato** con `--esporta` (un'opzione senza valore) o `FEBE_ESPORTA` e solo se è davvero montato: una destinazione è attiva se sta su un montaggio in `/esporta` o sotto, letto da `/proc/self/mountinfo` (il montaggio che la contiene, con il punto di montaggio più lungo, deve avere il punto in `/esporta` o in una sua sottocartella e non essere in sola lettura). Basta anche montare solo delle sottocartelle (`/esporta/usb`, `/esporta/nas`; proposta, §16 domanda 23); una cartella di `/esporta` che non sta su un montaggio si rifiuta, perché sarebbe il disco delle immagini. Altrimenti non si scrive nulla. Nel Dockerfile non c'è una riga `VOLUME` per `/esporta`, né un `mkdir`: un volume anonimo la farebbe sembrare montata e riempirebbe in silenzio il disco delle immagini di Unraid (§11). Si cambia il proprietario solo della radice, mai in modo ricorsivo, e solo quando le copie esterne sono dichiarate e la radice è di root. Su Windows la cartella si sceglie con il selettore nativo, anche su un percorso di rete o UNC (§12). **Fuori dal traguardo 0.3.0.** Ricodifica dei video (VP9, AV1, HEVC → MP4); conversione al momento dello scaricamento; unione di immagine e traccia audio dei post con musica (§4.9); un diario delle copie nelle destinazioni; la colonna «Copiato in» nel CSV. @@ -782,7 +783,7 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc | `event` | Cronologia leggibile per l'interfaccia | | `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura | | `import_run`, `import_file` | Importazioni e loro file, con esito e decisione | -| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), costruite, ancora non usate da interfaccia e motore: destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account; copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` | +| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali; `video_analysis` e `media_conversion` aspettano E4 ed E3): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` | Vincoli che contano: @@ -790,6 +791,7 @@ Vincoli che contano: - Stati di un elemento: da scaricare, scaricato, parziale, fallito, saltato, importato, eliminato. «Eliminato» resta nel database senza file, perché non venga riscaricato (§4.6). - Indici su (account, data di pubblicazione), SHA-256, impronta, stato. Dalla migrazione `0002` (tappa D1) anche `ix_entry_discovered` su `entry (discovered_at)`, per le miniature della cronologia della Dashboard (§7.9), e `ix_media_entry_files` su `media (entry_id, state, kind)`, per i conteggi di «Tutte le foto» (§4.6). - Dalla migrazione `0003` (tappa E1): l'identità di una copia è unica sulle righe correnti, «Copiato» e «Non riuscito» (`ux_export_copy_identity`); un percorso di una destinazione è tenuto al più da una copia «Copiato» o «Superato», senza distinguere le maiuscole ASCII, e un percorso «Tolto» è di nuovo libero (`ux_export_copy_path`); una copia non è mai «Superato» dal suo stesso originale (se il file della libreria torna quello di prima, la copia torna «Copiato»); una cartella senza il suo account non è mai automatica; una copia tiene identificativo e nome dell'account rimosso solo finché è senza account, e le copie orfane di un account si trovano per quelli (`ix_export_copy_orphan`); nella stessa cartella al più una conversione corrente per file e formato (`ux_media_conversion_current`); le ricerche vanno per SHA-256 (`ix_export_copy_sha256`, `ix_export_copy_superseded_by`); il filtro «Copie» su tutta la libreria legge `ix_export_copy_destination`, e le copie di una destinazione e i file di un lavoro si sfogliano per chiave senza riordinarli (`ix_export_copy_destination_id`, `ix_export_item_run`); una destinazione con copie o lavori e una riga `media` con un convertito registrato non si cancellano (`ON DELETE RESTRICT`); ogni colonna di chiave esterna delle tabelle nuove ha il suo indice. +- Dalla migrazione `0004` (tappa E2): soltanto l'indice `ix_media_sha256_entry` su `media (sha256, entry_id)` dove lo SHA-256 c'è, per il filtro «Copie» (§4.6, §4.10), che dalle copie arriva agli elementi senza leggere le righe dei file; nessuna tabella e nessuna colonna cambia. Misure in `docs/decisioni.md`. - Versione dello schema in `PRAGMA user_version`, migrazioni come file SQL numerati eseguiti all'avvio dentro una transazione. Un solo scrittore: le scritture passano da una coda. ### 8.4 Miniature e impronte @@ -980,7 +982,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I | `/dati` | Database, profilo del browser, miniature, copie. Su un disco locale del server | | `/libreria` | Foto e video | | `/importa` | Sorgenti da importare, in sola lettura | -| `/esporta` | Facoltativo, dal traguardo 0.3.0: le destinazioni delle copie esterne (§4.10), come sue sottocartelle. Attivo solo se dichiarato con `--esporta` o `FEBE_ESPORTA` e montato davvero; nel Dockerfile **nessuna** riga `VOLUME` per `/esporta` | +| `/esporta` | Facoltativo, dal traguardo 0.3.0: le destinazioni delle copie esterne (§4.10), come sue sottocartelle. Attivo solo se dichiarato con `--esporta` o `FEBE_ESPORTA` e solo per le destinazioni su un montaggio in `/esporta` o sotto (letto da `/proc/self/mountinfo`, §4.10); nel Dockerfile **nessuna** riga `VOLUME` né `mkdir` per `/esporta`; l'avvio cambia il proprietario della sola radice, se è di root e le copie sono dichiarate | | Variabile | Significato | Predefinito | |---|---|---| @@ -990,7 +992,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I | `LANG` | Lingua del contenitore e del browser | it_IT.UTF-8 | | `PUID`, `PGID` | Utente e gruppo dei file | 99, 100 | | `FEBE_RACCOLTA` | Opzione «raccolta» di §6.0: `pagine` o `richieste` (`--raccolta` sulla riga di comando vince) | `pagine` | -| `FEBE_ESPORTA` | Dal traguardo 0.3.0: attiva le copie esterne in `/esporta` (§4.10); `--esporta` sulla riga di comando vale lo stesso | spenta | +| `FEBE_ESPORTA` | Dal traguardo 0.3.0: attiva le copie esterne in `/esporta` (§4.10) con `1`, `true`, `sì`, `si` o `yes`; `--esporta` sulla riga di comando vale lo stesso. In `compose.yml` la cartella del server si sceglie con `FEBE_CARTELLA_ESPORTA`, un altro nome | spenta | | `FEBE_CHIAVE_SESSIONE` | Chiave AES-256 della sessione salvata (§13.2), 32 byte in base64; facoltativa, serve a tenerla fuori da `/dati` | `Dati/sessione/chiave.bin` | - Se `FEBE_PASSWORD` manca, o `/dati` non è scrivibile o è una condivisione di rete, il motore non parte e l'interfaccia mostra una sola pagina che spiega che cosa non va e come rimediare. Vale dal primo contenitore che costruisci, compreso quello di prova di M0: la vista remota non deve mai essere raggiungibile senza password. @@ -1004,7 +1006,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I - Applicazione WPF su .NET 10, una sola istanza alla volta, icona nell'area di notifica. - La finestra principale è un WebView2 che mostra l'interfaccia servita in locale su `127.0.0.1`, porta scelta all'avvio, e si apre sulla Dashboard (§7.9, dalla tappa D1). - Il browser di Instagram è un secondo WebView2, con una sua cartella dati, in una finestra separata «Browser di Febe». Alberto la apre da Collegamento e dalla Dashboard; quando non serve resta fuori vista ma attiva (S2). Salvataggio delle password e compilazione automatica sono disattivati nelle impostazioni del controllo. -- Funzioni native offerte all'interfaccia: scelta di una cartella (anche per le destinazioni di esportazione di §4.10, con percorsi di rete e UNC), «Mostra nella cartella», apertura di un indirizzo nel browser predefinito, notifiche di Windows, avvio con il sistema. +- Funzioni native offerte all'interfaccia: scelta di una cartella (anche per le destinazioni di esportazione di §4.10, con percorsi di rete e UNC; dalla tappa E2 spazio libero e FAT32 si leggono anche sui percorsi UNC quando Windows li dice, e una condivisione staccata mette la destinazione in pausa), «Mostra nella cartella», apertura di un indirizzo nel browser predefinito, notifiche di Windows, avvio con il sistema. - **Niente ffmpeg** (regola 13): fotogrammi, conversioni, miniature dei video importati e video fermi li fa il codice di Febe (§3), e non c'è nulla da installare a parte né un «Percorso di ffmpeg» da impostare. Un ffmpeg nel PATH non si usa: è uscito con la tappa C3 del traguardo 0.3.0. - Chiudendo la finestra Febe resta nell'area di notifica e continua a lavorare; dal menu dell'icona: apri, metti in pausa, esci. - Cartelle predefinite: dati in `%LOCALAPPDATA%\Febe`, libreria in `Immagini\Febe`. @@ -1167,6 +1169,12 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 19 | «Cosa scaricare prima»: le raccolte in evidenza vanno subito dopo le storie? Alberto ha detto storie, post, reel, taggati, senza nominarle | D1, prima di cominciare | Sì: storie, evidenza, post, reel, taggati, perché sono storie anche loro; si possono comunque spostare trascinandole | | 20 | In Docker lasciare la pagina del browser copia la sessione (risposta del 25 novembre, domanda 18) quando per 5 secondi non si riapre un'altra vista remota, così una pagina ricaricata non è lasciata: vanno bene i 5 secondi di grazia? Alberto non ha detto una durata | S4b, prima della prova dal vivo in Docker | Sì, 5 secondi: bastano a una pagina che si ricarica e non trattengono il motore | | 21 | «Cosa scaricare prima», coda dei file (§6.5): basta riservare un posto su otto al file che aspetta da più tempo in tutta la coda, così nessun file aspetta per sempre, o serve un minimo per tipo? Alberto ha chiesto solo l'ordine | D1, prima di unire | Il posto su otto, senza quote per tipo: un tipo trovato dopo un arretrato più vecchio aspetta che quell'arretrato finisca, ma nessun file aspetta per sempre | +| 22 | Copie esterne (§4.10): con «Esporta questo account» spento, «Copia in…» chiesto a mano salta anche quell'account, o l'interruttore vale solo per le copie automatiche? Alberto ha deciso solo che è acceso per impostazione predefinita (27 novembre 2026) | E2, prima di unire | Spento salta ogni copia di quell'account, anche a mano: la finestra lo dice («12 di account che non si esportano»), le copie già fatte restano e il visualizzatore le mostra. Così fa la tappa E2 | +| 23 | Copie esterne in Docker (§4.10, §11): se sono montate solo delle sottocartelle (`/esporta/usb`, `/esporta/nas`) e non `/esporta`, le copie sono attive? | E2, prima di unire | Sì: una destinazione è accettata quando sta su un montaggio in `/esporta` o sotto; una cartella di `/esporta` che non sta su un montaggio si rifiuta, perché sarebbe il disco delle immagini. Così fa la tappa E2 | +| 24 | L'interruttore «Automatica» delle destinazioni (§4.10) si mostra già nella tappa E2, anche se fino a E5 non fa nulla? | E2, prima di unire | No: nascosto fino a E5, perché un interruttore che non fa nulla inganna; il database e l'interfaccia di programmazione lo registrano già. Così fa la tappa E2 | +| 25 | Nella finestra «Copia in…» (§4.10) si offre «Copia di nuovo anche i N tolti o superati», o «Copia di nuovo» resta solo nel visualizzatore, un file alla volta? | E2, prima di unire | Si offre nella finestra, spenta all'apertura: senza la casella i tolti e i superati si saltano e si contano. Così fa la tappa E2 | +| 26 | Il conteggio della scheda dell'account, il filtro «Copie» e il segno sulla tessera (§4.10) considerano solo i file dei tipi scelti per la destinazione (con il solo «post foto», le storie non sono dovute)? | E2, prima di unire | Sì, solo i file dovuti (§4.10, «File dovuti»), così «312 su 1.204 non ancora copiati» è ciò che «Copia in…» copierebbe. Così fa la tappa E2 | +| 27 | Il margine di spazio libero delle destinazioni (§4.10, «più un margine»): quanto? | E2, prima di unire | 64 MB oltre al prossimo file. Così fa la tappa E2 | --- @@ -1544,6 +1552,7 @@ Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con | Esportazione | `Export` | Copia di file della libreria in una cartella esterna (§4.10) | | Destinazione | `ExportDestination` | La cartella esterna di un'esportazione, generale o di un account | | Copia esterna | `ExportCopy` | Un file copiato in una destinazione, con il suo stato (Copiato, Tolto, Superato, Non riuscito) | +| File dovuto | due file (`ExportFilterSql.DueFile`) | Un file che «Copia in…» copierebbe: presente in libreria, di un account che si esporta e ha una destinazione, di un tipo che la destinazione copia (§4.10) | | Fotogramma | `Frame` | Un'immagine presa da un video | | Video fermo | `StillVideo` | Video che mostra sempre la stessa immagine: basta un fotogramma | | Rimuxaggio | `Remux` | Passaggio di un video in un altro contenitore senza ricodifica | diff --git a/docs/decisioni.md b/docs/decisioni.md index 76cd305..1e4ec59 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -588,3 +588,44 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-26 | `export_item` tiene la richiesta (variante e formato chiesti), `export_copy` il risultato effettivo; il percorso di arrivo di un file si scrive nella sua transazione prima di creare il `.part`; aggiungere di nuovo gli stessi file a un lavoro non aggiunge nulla (`ux_export_item_file`, `ON CONFLICT DO NOTHING`). `AddItemsAsync` rifiuta un file senza `media_id` (in un indice unico i NULL sono tutti diversi, e lo stesso file si aggiungerebbe due volte) e `UpdateItemsAsync` non riscrive mai lavoro, file, variante, formato e istante: `ArgumentException` se cambiano; il file si toglie solo con la sua eliminazione (SET NULL) | La ripresa riaggiunge le stesse richieste; i `.part` si tolgono solo nelle cartelle dei file dei lavori non finiti (§4.10), mai con una scansione | | 2026-11-26 | Il file della libreria torna quello di prima (A→B→A, o A→B→C→A): `SupersedeCopiesAsync(B, A)` non segna mai una copia come superata dal suo stesso originale (un CHECK `superseded_by_sha256 <> source_sha256`). Le copie «Superato» di A tornano «Copiato» (la più recente per identità; le altre restano «Superato» da B, come storia) se l'identità non ha già una riga corrente, copiata di nuovo nel frattempo o non riuscita: allora restano «Superato» da B; le «Tolto» perdono solo il segno | «Tieni il più grande» confronta i pixel quando entrambe le dimensioni sono note e altrimenti i byte (`ImportPlanner.IsLarger`), quindi non è transitivo; anche una ricostruzione tiene il file sul disco. Una copia uguale byte per byte al file della libreria è copiata, non superata, e non deve restare bloccata per sempre; l'indice unico vuole al più una riga corrente per identità, e la riga corrente già presente risponde per quella copia | | 2026-11-26 | Le collisioni con gli indici unici della `0003` (cartella generale o cartella propria in uso, identità corrente e percorso di una copia, conversione corrente) arrivano a chi chiama come `DuplicateRecordException`, il tipo di `Febe.Core` già usato da `AccountStore` ed `EntryStore`, mai come `SqliteException` | `Febe.Core` non conosce Microsoft.Data.Sqlite: E2 ed E3 devono poter riconoscere il caso (per esempio un percorso già preso) senza rompere i livelli, e l'API risponderlo come conflitto invece di un errore 500 | +| 2026-11-27 | Tappa E2: **«Esporta questo account» è acceso per impostazione predefinita**. Nessuna riga in `export_account` vuol dire acceso (`ExportAccounts.IsEnabled(stored) => stored ?? true`); una riga si scrive solo quando Alberto sposta l'interruttore | Decisione di Alberto del 27 novembre 2026 (SPECIFICA §4.10). Il contratto di E1 è `GetAccountExportEnabledAsync` → `bool?` | +| 2026-11-27 | Tappa E2: con l'interruttore spento «Copia in…» salta l'account **anche a mano**, e la finestra lo conta («di account che non si esportano»). Ogni lavoro ricalcola la destinazione effettiva dei suoi file quando parte o riprende, e salta (nota `NotExported`) un file il cui account è stato spento, ha avuto una cartella sua o il cui tipo la destinazione non copia più | Proposta di §16 domanda 22: l'interruttore deve valere anche per un lavoro ripreso dopo il cambio, altrimenti «Riprendi» copierebbe ciò che Alberto ha escluso | +| 2026-11-27 | Tappa E2: **destinazione effettiva** = la cartella propria in uso dell'account, altrimenti la cartella generale in uso, altrimenti nessuna, calcolata al momento dal database. **File dovuto** = un file presente (`Downloaded`/`Imported` con SHA-256) di un account acceso con una destinazione effettiva e di un tipo che la destinazione copia. Segno sulla tessera, filtro «Copie», conteggio della scheda account e piano di «Copia in…» usano la stessa regola | SPECIFICA §4.10 («al più una destinazione effettiva») e proposta di §16 domanda 26: «312 su 1.204 non ancora copiati» deve essere ciò che «Copia in…» copierebbe | +| 2026-11-27 | Tappa E2: le tre scelte del filtro «Copie» **dividono** i file dovuti: «Non ancora copiati» = dovuto, non «Copiato» e non «Tolto o superato»; un file la cui copia corrente è «Non riuscito» è «Non ancora copiato» (la copia lo riprova), mai «Tolto o superato». Il progetto voleva «Non ancora copiati» = non «Copiato» | «Copia in…» salta tolti e superati (§4.10): il numero di «Non ancora copiati» deve essere quello che la finestra copierebbe senza la casella «Copia di nuovo» | +| 2026-11-27 | Tappa E2: nel filtro «Copie» gli identificativi (destinazioni, account, tipi di contenuto, tutti letti dal database) si scrivono **nel testo dell'SQL** come interi, invece che come parametri; `ExportFilterContext` legge prima se esistono righe «Copiato», «Non riuscito» o «Tolto/Superato» nelle destinazioni in uso, e i casi senza righe evitano gli `EXISTS` (`0`). In «Tutte le foto» la condizione sull'elemento è «esiste un suo file di quella classe» | Le condizioni compaiono più volte nella stessa istruzione, insieme ai parametri di `BuildWhere`: gli interi evitano scontri di nomi e non sono mai testo di Alberto. Con «Tutte le foto» + «Copiati» un post copiato in parte deve mostrare i suoi file copiati | +| 2026-11-27 | Tappa E2: **migrazione `0004`**, solo l'indice `ix_media_sha256_entry` su `media (sha256, entry_id)`, per il filtro «Copie». Misure con 200.000 elementi (`LibraryScaleTests`, senza statistiche e con ANALYZE, su questa macchina): la finestra di «Copiati» 249 ms senza l'indice, 161–164 ms con l'indice; «Non ancora copiati» 13–16 ms; «Tolti o superati» 33–67 ms; in «Tutte le foto» 19–168 ms. Totali e giorni: «Copiati» 0,65–0,71 s, «Non ancora copiati» 0,91–1,13 s, «Tolti o superati» 0,23–0,39 s. Le finestre stanno nei 250 ms di §15; totali e giorni del filtro «Copie» hanno un limite loro di 3 s invece dei 600 ms dei filtri «Foto» e «Video» | Senza l'indice la finestra di «Copiati» era al limite (249 ms su 250): l'elenco degli elementi con una copia leggeva la riga di ogni file trovato. Nei conteggi ogni file dovuto si confronta con le copie (240.000 file, circa 4 µs l'uno): «Copiati» si conta partendo dalle copie (un terzo del tempo di prima, 1,5 s → 0,67 s), gli altri valori con un solo passaggio sui file dietro gli elenchi degli SHA-256 delle copie (0,58 → 0,35 s su 40.000 elementi per «Non ancora copiati»). Scendere sotto i 600 ms vorrebbe uno stato delle copie per file, che E2 non aggiunge | +| 2026-11-27 | Tappa E2: «Copia di nuovo» sceglie, fra i file dell'account con lo SHA-256 della copia, uno che è sul disco; solo se nessuno c'è prende il primo (e il lavoro lo segna «non presente in libreria») | Lo stesso contenuto può stare in due elementi: prima si prendeva il primo trovato, che nella demo, secondo l'ora in cui nasce, era un video senza file sul disco, e la copia di nuovo non scriveva nulla (`ExportApiDemoCommandTests`) | +| 2026-11-27 | Tappa E2: «Copia in…» **non sceglie la destinazione**: ogni file va nella destinazione effettiva del suo account, e la finestra dice dove («In cartella generale», «In cartella di @nome») | SPECIFICA §4.10: un account ha al più una destinazione effettiva, «già copiato» è un sì o un no | +| 2026-11-27 | Tappa E2: **un `export_run` per destinazione**; un lavoro in memoria li fa in ordine (id più vecchio prima). «Interrompi» vale per il lavoro, «Riprendi» per una copia o per tutte. `StartAsync` restituisce le copie registrate **e il piano** (`ExportStart`), perché la risposta dica anche i file non esportati e quelli che mancano; mentre registra le righe il servizio è occupato (un doppio «Copia in…» non registra due volte), e se il lavoro non può partire le copie registrate diventano «Annullata» | `export_run.destination_id` è obbligatorio e `export_item` non ha la destinazione. Le note «non si esporta» e «non presente in libreria» esistono solo nel piano | +| 2026-11-27 | Tappa E2: si copiano **solo gli originali** (`Variant = Whole`, `Format = Original`). I comandi di E3 ed E4 («Fotogrammi…», «Fotogramma», «È un video fermo?», i menu dei formati, la conversione della libreria) **mancano** dall'interfaccia, non sono spenti; le chiavi di `ExportSettings` restano come le ha lasciate E1 | SPECIFICA §10.4: un pulsante dice che cosa succede; un comando grigio senza niente dietro non dice nulla, e con il solo «Originale» un menu dei formati non serve | +| 2026-11-27 | Tappa E2: **«Automatica»** si registra (archivio e interfaccia di programmazione, `Automatic`, `AutomaticSince`) ma **non si mostra**; nulla la usa fino a E5 | Proposta di §16 domanda 24: un interruttore visibile che non fa nulla ingannerebbe | +| 2026-11-27 | Tappa E2: **«Tolto» e «Superato» non si ricopiano mai da soli**: «Copia in…» li salta e li conta; si ricopiano con «Copia di nuovo» dal visualizzatore o con la casella «Copia di nuovo anche i N tolti o superati» della finestra, spenta all'apertura (la scelta del lavoro sta in `esportazione.lavoro.{id}.copia-di-nuovo`). «Copia di nuovo» su una copia la cui identità è già stata copiata di nuovo si rifiuta (400) e il visualizzatore non la offre | SPECIFICA §4.10 e §14.1; proposta di §16 domanda 25. Senza il rifiuto due clic scriverebbero due file nuovi per la stessa copia | +| 2026-11-27 | Tappa E2: **`LongWorkGate`**, una porta sola per importazione, copie esterne e ricostruzione, in tutte e due le direzioni: in Core per importazione e copie, in `RebuildJob` per la ricostruzione. Un'importazione rifiutata dalla porta non registra nessun lavoro. Il messaggio della ricostruzione rifiutata per un'importazione diventa quello della porta («…aspetta che finisca o interrompila, poi ricostruisci.») | SPECIFICA §4.10: «esportazione, importazione e ricostruzione non girano insieme»; prima solo l'interfaccia della ricostruzione guardava l'importazione | +| 2026-11-27 | Tappa E2: **niente copie durante una sessione del motore**: prima del primo file e prima di ogni file, finché `IEngineSessionState.InSession`, fase «Aspetto la fine della sessione del motore» e attesa di 5 secondi con `IClock`. Un file già in scrittura finisce | SPECIFICA §4.10: le copie lunghe partono fuori dalle sessioni del motore | +| 2026-11-27 | Tappa E2: **file di prova prima di ogni gruppo** di copie, al più 100 file o 1 GB di byte previsti; un gruppo si chiude **dopo** il file che raggiunge il limite, quindi può passare 1 GB di un file. Lo stesso controllo rifà la prova d'identità delle cartelle e, in Docker, la regola dei montaggi; se fallisce la destinazione va in pausa (`paused_at`, `last_error`) e la copia «In pausa», mai la striscia rossa | SPECIFICA §4.10. I byte di un file si sanno solo quando si legge la sua riga | +| 2026-11-27 | Tappa E2: **controllo delle cartelle** = prima i controlli sul testo (vuota, non completa, `..`, fuori da `/esporta`, `/esporta` stessa, montaggio, mancante, non cartella, collegamento, radice, troppo lunga, dentro o contenente Dati, Libreria, una cartella di account o `/importa`), poi la prova d'identità con `.febe-prova-<12 esadecimali>.part` nella sola candidata, asincrona, con 10 secondi al massimo. Le cartelle protette passano come `ProtectedFolder` con il tipo; `ExportDestinations.RecheckAsync` (cartelle di account) e `RecheckAgainstAsync` (una libreria nuova) hanno due nomi perché `RecheckAsync(null)` sarebbe ambiguo | SPECIFICA §4.10, «Cartelle rifiutate». Il tipo serve al messaggio («dentro la cartella di @nome») | +| 2026-11-27 | Tappa E2: cambiare la cartella di un account o la libreria si **rifiuta** solo quando **aggiunge** un conflitto con una destinazione (una destinazione già in conflitto resta alla sua pausa); dopo una ricostruzione riuscita `RebuildJob` ricontrolla le destinazioni e mette in pausa quelle in conflitto (`RecheckAndPauseAsync`); un errore di quel ricontrollo si ignora | Ogni gruppo di copie rifà comunque la prova della cartella prima di scrivere; il livello web non ha un registro in cui scrivere l'errore | +| 2026-11-27 | Tappa E2: in Docker le copie leggono **`/proc/self/mountinfo`**, non `/proc/self/mounts`, attraverso `IExportMounts` (`FindContaining` e `All`). Una destinazione è attiva quando le copie sono dichiarate (`--esporta`, un'opzione senza valore, o `FEBE_ESPORTA` letto con `Flag`) e il montaggio che la contiene (punto di montaggio più lungo) ha il punto in `/esporta` o sotto e non è in sola lettura; bastano anche dei montaggi sotto `/esporta`. `..` si rifiuta come testo, prima di `GetFullPath` | `mountinfo` dà il campo *root* (il montaggio è la radice del suo file system?) e il punto di montaggio esatto. Proposta di §16 domanda 23: una cartella di `/esporta` fuori dai montaggi sarebbe il disco delle immagini. `All()` serve a dire se c'è almeno un montaggio in `/esporta` o sotto | +| 2026-11-27 | Tappa E2: **radice di un disco o di una condivisione**: su Windows `Path.GetPathRoot` uguale al percorso completo (`C:\`, `\\srv\share`); su Linux `/`, oppure esattamente un punto di montaggio il cui *root* in `mountinfo` è `/` | SPECIFICA §4.10, «Cartelle rifiutate» | +| 2026-11-27 | Tappa E2: **spazio** prima di ogni file: byte liberi (se si misurano) almeno il file più **64 MiB**, altrimenti pausa con il motivo. FAT32 (`FAT32`/`FAT` su Windows, `vfat`/`msdos`/`fat` su Linux): un file oltre 4 GiB − 1 è «Non riuscito» (`TooLargeForFileSystem`) e la copia prosegue. Spazio non misurabile: nessun controllo, e un errore «disco pieno» (HResult 0x80070070/0x80070027, errno 28) mette in pausa. Su Windows `WindowsExportDisk` legge spazio e file system con `GetDiskFreeSpaceExW` e `GetVolumeInformationW`, così anche sui percorsi UNC | SPECIFICA §4.10 («più un margine»); proposta di §16 domanda 27. `DriveInfo` non regge i percorsi UNC | +| 2026-11-27 | Tappa E2: `SafeFileWriter` riceve due opzioni, spente per chi c'era prima: **`RequireExistingRoot`** (`ExportRootMissingException` prima di qualunque `CreateDirectory`; le sottocartelle sì) e **`VerifyFromDisk`** (dopo `Flush(true)` il `.part` si rilegge dal disco e se ne rifà lo SHA-256 prima del confronto con la libreria e del cambio di nome; se non coincide il nostro `.part` si toglie). Resta una gara: la radice sparisce fra il controllo e `CreateDirectory`; su Windows un disco o una condivisione assenti danno errore comunque, e in Docker un montaggio non sparisce dentro un contenitore acceso | SPECIFICA §4.10: «la radice di una destinazione non si crea mai»; una copia rovinata dal disco non deve mai prendere il nome definitivo | +| 2026-11-27 | Tappa E2: **percorsi delle copie**: «Come la libreria» = gli schemi **attuali** della libreria rifatti con `NamingScheme.Render`; un file con `media.relative_path` in `importati/` tiene quel percorso solo se la destinazione non ha uno schema suo per quell'uso; nella cartella generale prima `WindowsFileNames.SanitizeSegment(username)`; `FitPath(root, segmenti, 240)` per ultimo. Una storia in una raccolta in evidenza usa lo schema delle raccolte (la prima per posizione) **solo** se la destinazione copia «In evidenza» e non «Storie» | SPECIFICA §4.10 e §4.7 | +| 2026-11-27 | Tappa E2: la data del file di una copia segue `libreria.data-file-pubblicazione` (`SafeWriteOptions.LastWriteTime = entry.PublishedAt`) | SPECIFICA §4.10: la stessa regola di conversioni e fotogrammi | +| 2026-11-27 | Tappa E2: l'avanzamento arriva all'interfaccia **interrogando** (1 secondo durante una copia, 5 altrimenti), come l'importazione. Quando le copie finiscono `ExportService.JobFinished` fa pubblicare `LibraryChange(…, "export")`, e tessere e filtro si aggiornano con l'evento `libreria` | Il modello esistente di `import.js`; l'evento non era nel progetto e serve al livello web | +| 2026-11-27 | Tappa E2: **«Controlla le copie»** è il controllo dei «Tolto»: guarda se i file «Copiato» di una destinazione ci sono ancora e segna «Tolto» quelli che mancano, senza toccare nulla. Prima di segnare «Tolto» (anche durante una copia) Febe controlla che la radice della destinazione esista ancora; se non esiste rifà la prova e mette in pausa | Un disco staccato non deve mai trasformare le copie in «Tolto» | +| 2026-11-27 | Tappa E2: **«Superato»** nasce in quattro punti: `ImportCopier.ReplaceAsync` (dopo `MarkStoredAsync`), `LibraryIngest.RecordAsync` (dopo un `MarkStoredAsync` riuscito, con lo SHA-256 di prima), `DownloadDuplicateReview.DecideAsync` («Tieni il più grande», dopo la rimozione del perdente) e `LibraryRebuilder` (SHA-256 del diario diverso da quello sul disco, applicato dopo l'ultima scrittura della cartella), tutti con `ExportSupersession.FileChangedAsync`. Il posto riempito di un'importazione passa da `LibraryIngest.RecordAsync` e non ha un aggancio suo | SPECIFICA §4.10: il file della libreria è cambiato. `ImportCopier.ImportAsync` salva con `LibraryIngest.SaveMediaAsync → RecordAsync` | +| 2026-11-27 | Tappa E2: **adozione per percorso**: un file allo stesso percorso con stessa dimensione **e** stesso SHA-256 si adotta se il percorso è libero nel database o è di una riga orfana con lo stesso SHA-256 (che si ricollega); se è di un'altra identità non si prende e si scrive su un nome libero. Una copia ripresa dopo un arresto guarda anche «nome (2).ext», «(3)»… del percorso registrato fino al primo che manca. Dopo una scrittura su un nome libero, una riga di un'altra identità che teneva ancora quel percorso (il suo file non c'era più) diventa «Tolto» prima della registrazione; un `DuplicateRecordException` alla registrazione lascia il file scritto dov'è e il file «Non riuscito» (`PathTaken`) | SPECIFICA §4.10, «Adozione per percorso», e la regola 12: nulla si toglie. L'indice unico dei percorsi rifiuterebbe altrimenti la riga nuova | +| 2026-11-27 | Tappa E2: con **«Una copia sola»** una copia altrove conta solo se è di **un altro** account e il suo file sta in una destinazione in uso. Un file che il piano incontra due volte (stessa destinazione, account e SHA-256, o stesso SHA-256 con «Una copia sola») è «già copiato» e ha comunque la sua riga nel lavoro. `BytesTotal` dell'avanzamento si calcola all'inizio di ogni copia leggendo i file in attesa; senza byte la barra va per file | SPECIFICA §4.10, «Lo stesso post in due account» e «la storia e la sua evidenza sono una copia» | +| 2026-11-27 | Tappa E2: i `.part` rimasti si tolgono **solo** nelle cartelle dei file in attesa o non riusciti, con un percorso, di una copia non finita (`ExportLeftovers`, senza ricorsione, con un tempo massimo per cartella). All'avvio le copie rimaste «In corso» diventano «Interrotta» e il registro dice quante sono: si riprendono dalla Dashboard, mai da sole | SPECIFICA §4.10: «mai con una scansione della destinazione». Alberto decide quando il disco è di nuovo collegato | +| 2026-11-27 | Tappa E2: piccole scelte dell'archivio e del motore: `ListCandidatesAsync` per un account prende solo gli elementi negli stati visibili (`EntryStateRules.Visible`); `GetCopyStatesAsync` legge solo le righe intere e originali; `CreateAsync`/`UpdateAsync` restituiscono `DestinationSaveResult` (destinazione e avvisi); `UpdateAsync` con la stessa cartella non rifà il controllo (un disco staccato non blocca il cambio di un'etichetta) e tiene pausa, errore e `AutomaticSince`; i segni per elementi e file senza file dovuti mancano dai dizionari; `ExportSelection.Filter(LibraryFilter LibraryFilter, MosaicMode Mode)`; `ExportEnvironment.ResolveSource` facoltativo, con `ResolveSourcePath` che ricade sullo schema della libreria | Senza il filtro degli stati ogni elemento eliminato sarebbe «File non presente in libreria»; le altre sono questioni di nomi e di forma delle API | +| 2026-11-27 | Tappa E2, livello web: in più al progetto `ExportService.RetryDestinationAsync`, `ExportDestinations.RecheckAndPauseAsync`, `IExportStore.GetEntryCopyCountsAsync` (il «2/3» vuole i numeri), `ExportRootOptions.ShownAs` (la dimostrazione in veste Docker mostra `/esporta` e non la cartella temporanea); `ExportJobDto` con il piano e un messaggio, `ExportOverviewDto` con gli schemi della libreria, `ExportDestinationDto` con `Orphan` e `FormerUsername`, `ExportRunDto` con `Running`; `naming-preview` dice gli errori nella risposta come `/api/settings/naming-preview`. La dimostrazione semina le copie da `DemoHost` dopo l'importazione, con il motore vero | L'interfaccia non può arrivare a `ExportPause` né all'ambiente; stesso codice della pagina dei nomi della libreria | +| 2026-11-27 | Tappa E2, interfaccia: la Dashboard ha le schede **«Motore»** ed **«Esportazione»** (`/dashboard/esportazione`, caricata a richiesta); l'avviso delle copie da riprendere sta nella scheda Motore con gli altri avvisi, sotto i riquadri, così la disposizione del motore a 860 × 900 non cambia. Il resoconto è un dialogo, non una pagina; `toast` riceve un collegamento facoltativo; in Docker un clic sul nome sceglie la cartella e la freccia la apre; l'etichetta di una destinazione è il nome della cartella; nella scheda account filtro «Copie» e «Copia in…» compaiono solo se l'account ha una destinazione | SPECIFICA §10.3; le prove della disposizione della Dashboard restano valide | +| 2026-11-27 | Tappa E2, Docker: niente `VOLUME` né `mkdir` per `/esporta` nel Dockerfile (con un commento che dice perché) e nessun valore di `FEBE_ESPORTA` nell'immagine; l'avvio assegna a `PUID:PGID` la sola cartella `/esporta`, senza ricorsione, solo se le copie sono dichiarate (`FEBE_ESPORTA` con i valori di `Flag`, o `--esporta` fra gli argomenti) e la cartella è di root. In `compose.yml` la cartella del server si chiama `FEBE_CARTELLA_ESPORTA`, non `FEBE_ESPORTA`; `compose.yml` e il modello di Unraid hanno `/esporta` facoltativa (commentata, o vuota fra le impostazioni avanzate) | SPECIFICA §4.10 e §11: un volume anonimo farebbe sembrare `/esporta` montata; dentro ci sono file di Alberto. Lo stesso nome per due cose diverse confonderebbe | +| 2026-11-27 | Tappa E2, revisione: il **nome libero** si sceglie prima di scrivere ed è libero **sul disco e nel database**: «nome (2).ext», «(3)»… finché uno non manca sul disco e non è tenuto da una riga viva; una riga che tiene un nome il cui file **registrato** non c'è più (si guarda il suo percorso, non quello scelto: l'indice confronta senza maiuscole) diventa «Tolto». Dopo la scrittura la stessa regola si riapplica al nome davvero scritto. Precisa la riga «adozione per percorso» qui sopra | Con la scelta dopo la scrittura una riga orfana su «nome (2)» faceva fallire la registrazione (`PathTaken`) con il file già scritto; un nome che differisce solo per le maiuscole toglieva la copia buona | +| 2026-11-27 | Tappa E2, revisione: una copia **«Superato»** il cui file torna identico nella libreria (stesso SHA-256) torna «Copiato» se non c'è un'altra copia corrente né una riga non riuscita della stessa identità; altrimenti diventa «Tolto» e il file si registra come adottato. «Copia di nuovo» cerca il file prima con lo SHA-256 che l'ha superata, poi con quello della copia | Gli indici unici rifiutavano l'adozione (la riga «Superato» tiene percorso e identità); la regola 12 vuole che nulla si tolga dal disco | +| 2026-11-27 | Tappa E2, revisione: il **controllo delle copie** rilegge la radice prima di ogni pagina e, prima di segnare «Tolto», riguarda ogni file mancante; se la radice non risponde più (cartella assente o oltre il tempo massimo) il controllo si ferma e la destinazione va in pausa, senza segnare nulla. Anche la copia, con la radice assente, riguarda il percorso registrato prima di dire «Tolto» | Un disco staccato a metà controllo faceva sembrare tolti tutti i file seguenti | +| 2026-11-27 | Tappa E2, revisione: una copia di più destinazioni interrotta (o finita con un errore) lascia **«Interrotta»** le copie che non erano ancora partite, riprendibili dalla Dashboard; il permesso dei lavori lunghi (`LongWorkGate`) si prende **prima** di preparare il piano e passa al lavoro, così fra controllo e avvio non entra un'importazione | Le copie in coda restavano «In corso» per sempre; prima il permesso si prendeva solo all'avvio del lavoro | +| 2026-11-27 | Tappa E2, revisione: su Linux lo spostamento del `.part` sul nome finale usa `renameat2(RENAME_NOREPLACE)` e, dove manca, `link` + `unlink` (`NoReplaceRename`, P/Invoke della libc, nessuna libreria); se nessuno dei due è disponibile resta il controllo di prima. Su Windows `File.Move` senza sovrascrittura è già atomico | Fra `File.Exists` e `File.Move(overwrite: true)` un file comparso nel frattempo veniva sostituito: la regola 11 lo vieta | +| 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file | +| 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella | +| 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie | diff --git a/docs/docker.md b/docs/docker.md index b61d1f4..0722a0e 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -88,6 +88,7 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»). | `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), con la raccolta `richieste` la sessione salvata cifrata e la sua chiave (`sessione/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | Su un **disco locale** del server. Su Unraid: `/mnt/user/appdata/febe` (la cartella delle applicazioni sul disco di cache). 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, con `_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 | +| `/esporta` | **Facoltativo.** Le destinazioni delle copie esterne (specifica §4.10), come sue sottocartelle | Un disco USB, una condivisione o un'altra cartella del server montata su `/esporta`, oppure una o più cartelle montate **sotto** `/esporta` (`/esporta/usb`, `/esporta/nas`). Attivo solo con `FEBE_ESPORTA=1` (o `--esporta`) **e** un montaggio: altrimenti Febe non scrive nulla. Nel Dockerfile **nessuna** riga `VOLUME` per `/esporta`, vedi «Copie esterne» sotto | ## Variabili @@ -103,6 +104,7 @@ gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»). | `FEBE_SENZA_SANDBOX` | `1` avvia Chromium con `--no-sandbox`: è il compromesso descritto sotto, da usare solo se il profilo seccomp non si può usare | spenta | | `FEBE_CHROMIUM`, `FEBE_PORTA_DEBUG`, `FEBE_DISPLAY` | Avanzate: eseguibile di Chromium, porta di debug (sempre su 127.0.0.1), display di Xvfb | `/usr/bin/chromium`, 9222, `:99` | | `FEBE_RACCOLTA` | Come le ricette leggono il sito (specifica §6.0): `pagine` con il browser, come sempre; `richieste` con il client del sito e la sessione copiata a «Ho finito». Vale solo se il catalogo del sito ha operazioni configurate: con Instagram, per ora, `richieste` non cambia nulla. `--raccolta` sulla riga di comando vince | `pagine` | +| `FEBE_ESPORTA` | Facoltativa: `1` (o `true`, `sì`, `si`, `yes`) accende le copie esterne in `/esporta` (specifica §4.10); `--esporta` sulla riga di comando vale lo stesso. Senza un montaggio in `/esporta` o sotto, resta spenta comunque. In `compose.yml` la cartella del server si sceglie con `FEBE_CARTELLA_ESPORTA`, un nome diverso apposta | spenta | | `FEBE_CHIAVE_SESSIONE` | Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (`openssl rand -base64 32`) o 64 cifre esadecimali. Senza, Febe crea una volta `/dati/sessione/chiave.bin`, leggibile solo dal proprietario. Impostala se vuoi la chiave fuori da `/dati` (così una copia di `/dati` da sola non apre la sessione); se la cambi, la sessione salvata non si legge più e basta rifare l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega | `/dati/sessione/chiave.bin` | La password dell'interfaccia e la chiave della sessione non si passano mai sulla riga di comando e non finiscono nei @@ -119,8 +121,35 @@ dentro il contenitore: non va mai pubblicata, e Febe si rifiuta di usare il brow L'avvio crea, se mancano, il gruppo `PGID` e l'utente `PUID`, assegna `/dati` a quell'utente (la prima volta, o quando cambi PUID/PGID: allora anche il contenuto) e passa a quell'utente con `setpriv`. `/libreria` non viene mai cambiata -ricorsivamente: se Febe non riesce a scriverci, il registro lo dice. Febe **non gira come root**: con `PUID=0` il -contenitore si ferma con un messaggio. +ricorsivamente: se Febe non riesce a scriverci, il registro lo dice. Di `/esporta`, solo quando le copie esterne sono +dichiarate (`FEBE_ESPORTA=1` o `--esporta`), l'avvio assegna all'utente la sola cartella `/esporta` se appartiene a +root (appena creata da Docker), **mai** il suo contenuto: dentro ci sono file di Alberto. Febe **non gira come root**: +con `PUID=0` il contenitore si ferma con un messaggio. + +## Copie esterne (`/esporta`) + +Le destinazioni delle copie esterne (specifica §4.10, guida «Copie esterne») in Docker sono sottocartelle di +`/esporta`, scelte in Impostazioni ▸ Esportazione da un elenco come le sorgenti di importazione (`..` e `/esporta` +stessa rifiutati). Le copie sono attive solo se: + +1. sono **dichiarate**: `FEBE_ESPORTA=1` oppure `--esporta`; +2. la cartella scelta sta su un **montaggio** il cui punto di montaggio è `/esporta` o una sua sottocartella, letto da + `/proc/self/mountinfo` (che dice punto di montaggio, radice del file system e opzioni). Basta anche montare solo + delle sottocartelle (`/esporta/usb`, `/esporta/nas`): una cartella di `/esporta` che non sta su nessun montaggio si + rifiuta, perché sarebbe il disco delle immagini; +3. il montaggio non è in sola lettura. + +Altrimenti Febe non scrive nulla: Impostazioni ▸ Esportazione dice perché, nessuna cartella si può scegliere, e una +cartella già scelta va in pausa alla copia successiva. Per questo nell'immagine non c'è né `VOLUME` né `mkdir` per +`/esporta`: un volume anonimo la farebbe sembrare montata e riempirebbe in silenzio il disco delle immagini di Unraid. +All'avvio il registro dice «copie esterne in /esporta» oppure «copie esterne spente (/esporta non dichiarata)» o +«(/esporta non montata)»; dichiarata ma non montata è anche un avviso nel registro, non un problema di configurazione: +Febe parte lo stesso. + +La radice di una destinazione non si crea mai e le copie non sovrascrivono né cancellano nulla (la guida spiega come +funzionano). Su Unraid, un disco montato con Unassigned Devices **dopo** l'avvio del contenitore non si vede dentro +il contenitore senza la propagazione dei montaggi: riavvia il contenitore, oppure nel modello imposta il modo di +accesso di «Copie esterne (/esporta)» a «RW/Slave». ## Sandbox di Chromium (S5) @@ -191,6 +220,8 @@ Febe non sceglie da solo: se Chromium non parte, il registro dice perché e rima - porta 8480; - `/dati` su `/mnt/user/appdata/febe` (disco di cache); - `/libreria` dove vuoi le foto; `/importa` in sola lettura; + - facoltativi, tra le impostazioni avanzate: «Copie esterne (/esporta)», la cartella del server per le copie + esterne (vuota: niente copie), e `FEBE_ESPORTA` a `1`. Equivale a `-v /mnt/disks/usb/febe:/esporta -e FEBE_ESPORTA=1`; - **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`. @@ -201,7 +232,8 @@ Febe non sceglie da solo: se Chromium non parte, il registro dice perché e rima ## Docker Compose -`docker/compose.yml` è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura), variabili, profilo +`docker/compose.yml` è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura, e `/esporta` +commentato), variabili, profilo seccomp con percorso relativo al file (`chromium/seccomp.json`, fuori da `/dati`), `restart: unless-stopped`, 30 secondi per fermarsi. `init: true` non serve (il processo 1 è Febe) e nemmeno `shm_size` (Chromium usa `/tmp` al posto della memoria condivisa). Anche qui il registro `192.168.30.23:3000` deve stare fra gli `insecure-registries` del Docker. @@ -218,6 +250,15 @@ tar -xzf febe-compose-X.Y.Z.tar.gz && cd febe-compose-X.Y.Z FEBE_PASSWORD='una frase lunga' docker compose up -d ``` +Per le copie esterne togli il commento alle due righe di `compose.yml`: + +```yaml + volumes: + - ${FEBE_CARTELLA_ESPORTA:-/srv/febe/esporta}:/esporta + environment: + FEBE_ESPORTA: "1" +``` + ## Salute `GET /salute` risponde senza password `{"stato":"ok"}` (200) oppure `{"stato":"problema"}` (503) quando un problema di @@ -235,6 +276,11 @@ c'è curl). Unraid mostra lo stato accanto al contenitore; da terminale: `docker | Unraid non crea il contenitore: «opening seccomp profile … no such file» | Manca `/mnt/user/appdata/febe-seccomp.json`: passo 2 dell'installazione | | Unraid non scarica l'immagine: «http: server gave HTTP response to HTTPS client» | Il registro `192.168.30.23:3000` non è fra gli `insecure-registries`: passo 1 dell'installazione | | La porta è occupata | Cambia la porta pubblicata (o `FEBE_PORTA`) | +| Impostazioni ▸ Esportazione: «Le copie esterne in Docker sono spente…» | Le copie non sono dichiarate: `FEBE_ESPORTA=1` (o `--esporta`) e una cartella del server montata su `/esporta`, poi ricrea il contenitore | +| «/esporta è dichiarata ma non è montata…» (anche nel registro all'avvio) | `FEBE_ESPORTA=1` c'è, ma su `/esporta` (o sotto) non è montato nulla: aggiungi il montaggio e ricrea il contenitore. Finché manca, Febe non scrive nulla | +| «… non è su una cartella montata in /esporta» | Ci sono montaggi sotto `/esporta`, ma la cartella scelta non sta su nessuno: scegline una dentro un montaggio | +| «… è montata in sola lettura» | Il montaggio di `/esporta` ha `:ro` (su Unraid un modo di accesso «RO»): rendilo scrivibile e ricrea il contenitore | +| Le copie finiscono in una cartella vuota del server invece che sul disco USB | Il disco è stato montato dopo l'avvio del contenitore: riavvia il contenitore o usa «RW/Slave» (vedi «Copie esterne») | Il registro di Febe è in `/dati/registro/febe-AAAA-MM-GG.log` e nell'output del contenitore (`docker logs febe`). Contiene azioni ed esiti, nomi utente sì; mai password, cookie, tasti, didascalie, corpi delle risposte né indirizzi diff --git a/docs/guida/Account-e-impostazioni.md b/docs/guida/Account-e-impostazioni.md index 13944b8..e8898da 100644 --- a/docs/guida/Account-e-impostazioni.md +++ b/docs/guida/Account-e-impostazioni.md @@ -146,6 +146,9 @@ I numeri dell'intestazione e delle linguette restano elementi. 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. +- **Copie esterne** (sotto «Cartella»): **«Esporta questo account»**, acceso finché non lo spegni, e la cartella delle + copie dell'account, quella generale o una sua; con «Copia in…» e il conto dei file non ancora copiati. Vale subito, + senza «Salva le impostazioni». Vedi [Copie esterne](Esportazione). 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 diff --git a/docs/guida/Dashboard-e-arresti.md b/docs/guida/Dashboard-e-arresti.md index 5539ff3..3845597 100644 --- a/docs/guida/Dashboard-e-arresti.md +++ b/docs/guida/Dashboard-e-arresti.md @@ -35,6 +35,10 @@ solo appena aggiungi un account. Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprendi»), **«Riprendi»**, **«Apri il browser»**, **«Diagnostica»** (vedi sotto). +La Dashboard ha due schede: **Motore**, tutto quello che c'è qui sopra, ed **Esportazione**, con le +[copie esterne](Esportazione) in corso, da riprendere e già fatte. Le copie non fermano il motore e non usano Instagram; +quando una copia aspetta di essere ripresa, la scheda Motore lo dice con un avviso. + ## Il rapporto di diagnostica Se una prova va storta (Febe si ferma, non trova nulla, scarica meno del previsto) e vuoi farla guardare a qualcuno, diff --git a/docs/guida/Esportazione.md b/docs/guida/Esportazione.md new file mode 100644 index 0000000..feebaf0 --- /dev/null +++ b/docs/guida/Esportazione.md @@ -0,0 +1,183 @@ +# Copie esterne + +Le **copie esterne** sono copie dei file della libreria in cartelle fuori da Febe: un disco USB, una chiavetta, una +cartella di rete, un'altra cartella del server. La libreria non cambia: Febe legge i suoi file e li copia così come +sono, byte per byte. Non riscarica nulla e non apre Instagram: è solo lavoro sul disco. + +In questa versione (tappa E2) si copiano gli **originali**. Le copie in un altro formato e i fotogrammi dei video +arrivano con la tappa E3, l'analisi dei video fermi con la E4, le copie automatiche con la E5: fino ad allora quei +comandi non ci sono. + +> **Le copie esterne escono dal controllo di Febe.** Chi ha la cartella di una copia, o il disco su cui sta, ha quei +> file, comprese le foto e i video di altre persone. Febe non le cifra, non le cancella e, dopo averle scritte, ne sa +> soltanto ciò che ha registrato nel suo database. Nelle cartelle delle copie Febe non scrive diari, identificativi o +> didascalie: solo i file, con i nomi dello schema. Tratta quel disco come tratti la libreria. + +## Dove vanno le copie + +- **Cartella generale** (Impostazioni ▸ Esportazione): vale per tutti gli account. Dentro, Febe mette sempre per primo + una cartella con il nome dell'account, così due account non si scontrano (`Disco USB/marta.demo/…`). +- **Cartella di un account** (scheda dell'account ▸ Impostazioni ▸ blocco **«Copie esterne»**, sotto «Cartella»): + «Scegli una cartella sua…» la mette al posto di quella generale per quell'account, senza la cartella con il nome + dell'account. «Usa la cartella generale» torna a quella generale. +- Ogni account ha al più una cartella delle copie: la sua, se c'è, altrimenti quella generale. Per questo un file è + «copiato» oppure no, senza vie di mezzo. «Copia in…» non chiede dove: ogni file va nella cartella del suo account, e + la finestra lo dice («In cartella generale», «In cartella di @marta.demo»). +- **«Esporta questo account»**, nello stesso blocco, è **acceso** per ogni account finché non lo spegni (decisione di + Alberto del 27 novembre 2026). Spento, l'account non si copia più: «Copia in…» lo salta, sempre, anche quando lo + chiedi tu a mano, e la finestra lo conta fra i file «di account che non si esportano». Le copie già fatte restano dove + sono e il visualizzatore continua a mostrarle. + +Per ogni cartella scegli **che cosa copiare** (post foto, post video, storie, in evidenza, taggati, foto del profilo) e +**i nomi dei file**: + +- **«Come la libreria»** (di solito): gli schemi di Impostazioni ▸ Generali, quelli di adesso, anche quando li cambi; +- **«Uno schema suo»**: tre schemi solo per quella cartella (file, raccolte in evidenza, foto del profilo), con le + stesse regole e gli stessi segnaposto della libreria ([Libreria](Libreria), «Cartelle e nomi dei file»). Il + «Risultato» mostra subito dove andrebbero alcuni file. + +Una storia entrata in una raccolta in evidenza conta anche come evidenza: una cartella con il solo tipo «In evidenza» la +copia, con lo schema delle raccolte. Un percorso troppo lungo si accorcia a 240 caratteri, cartella compresa. I file +importati senza data tengono il nome che avevano in libreria (`importati/…`). + +## Le cartelle che si possono scegliere + +- La cartella **deve esistere già**: Febe non la crea mai. Un disco staccato o una condivisione assente non devono + diventare una cartella sul disco del computer o del server. Le sottocartelle dello schema, invece, Febe le crea. +- Non vanno bene: una cartella **dentro o che contiene** la cartella dei dati, la libreria, la cartella di un account + (anche fuori dalla libreria) o la cartella da importare; la **radice di un disco o di una condivisione** (`E:\`, + `\\nas\foto`): scegli una cartella dentro. +- Lo stesso posto raggiunto per due strade (una lettera di unità e un percorso di rete, per esempio) si riconosce con un + piccolo file di prova, `.febe-prova-….part`, che Febe scrive e toglie subito **solo nella cartella scelta**. Se quel + file non si scrive, la cartella si rifiuta. +- Su Windows la cartella si sceglie con «Scegli…», la finestra di Windows: vanno bene anche una cartella di rete o un + percorso UNC (`\\nas\foto\febe`). In Docker si sceglie dall'elenco delle sottocartelle di `/esporta` (vedi sotto). +- Le regole valgono anche dopo: Febe rifiuta una nuova cartella di un account, o una nuova libreria, che finirebbe + dentro una cartella delle copie o la conterrebbe; dopo una ricostruzione del database ricontrolla le cartelle delle + copie, e quella che non va più bene va in pausa. + +**Togli la cartella** toglie solo la scelta: i file già copiati restano dove sono, e le loro copie restano registrate. +Cambiare cartella vale lo stesso: le copie fatte restano in quella di prima, e nella nuova si ricomincia (i file già +presenti si riconoscono, vedi «Adozione»). Una cartella con un lavoro di copia non finito non si cambia: finiscilo o +annullalo prima, dalla Dashboard. + +## «Copia in…» + +«Copia in…» si apre da quattro posti: + +1. dalla **selezione**, in Libreria e nella scheda di un account: «Seleziona», scegli le tessere, «Copia in…» nella + barra in basso; +2. dal **filtro di adesso**: il pulsante con l'icona del documento apre un menu con «Esporta l'elenco (CSV)» e «Copia + i file in…», che copia ciò che i filtri mostrano; +3. dal **visualizzatore**: «Copia in…» nel pannello File; +4. dalla **scheda dell'account**, blocco «Copie esterne»: tutti i file dell'account. + +«Copia in…» e il filtro «Copie» compaiono solo quando c'è almeno una cartella delle copie (nella scheda di un account, +quando quell'account ne ha una). + +La finestra conta prima di copiare: quanti file, quanti già copiati (saltati), quanti tolti o superati (saltati), quanti +di account che non si esportano, quanti non presenti in libreria, circa quanto spazio, e lo spazio libero di ogni +cartella. **«Copia di nuovo anche i N tolti o superati»** è spenta: accendila se vuoi riscriverli (vedi «Stati»). +«Copia N file» fa partire il lavoro e la finestra si chiude: le copie vanno avanti da sole e si seguono nella Dashboard. + +Si copiano solo i **file dovuti**: i file presenti in libreria di un account che si esporta e ha una cartella delle +copie, del tipo che quella cartella copia. Il segno sulle tessere, il filtro «Copie», il conteggio della scheda +dell'account e «Copia in…» contano tutti e soli questi file, così «312 su 1.204 non ancora copiati» è proprio ciò che +«Copia in…» copierebbe. + +## Come Febe scrive una copia + +- Prima di ogni gruppo di copie (al più 100 file o 1 GB) Febe scrive e toglie un file di prova nella cartella. Se non + ci riesce (disco staccato, condivisione assente, cartella sparita) la cartella **va in pausa**: lo dicono + Impostazioni ▸ Esportazione e la Dashboard, e la copia aspetta. Non c'è mai la striscia rossa, che resta del motore. +- Serve lo spazio per il prossimo file più un margine di 64 MB; i 10 GB / 5 % della libreria qui non valgono. Senza + spazio la cartella va in pausa. Su un disco **FAT32** un file oltre 4 GB non si può scrivere: diventa «Non riuscito» + e la copia prosegue con gli altri. +- Ogni file si scrive con un nome temporaneo `.part`, si rilegge dal disco e se ne confronta lo SHA-256 con quello + della libreria, poi prende il nome definitivo. **Febe non sovrascrive mai un file**: se il nome è occupato da un altro + file, scrive `nome (2).jpg` e lascia l'altro com'è. Non cancella e non sposta nulla nelle cartelle delle copie; i + `.part` rimasti da una copia interrotta li toglie solo nelle cartelle di quel lavoro, mai frugando nel resto. +- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione». +- Non si copia durante una sessione del motore: la copia aspetta che la sessione finisca («Aspetto la fine della + sessione del motore»). Copie, importazione e ricostruzione del database non girano insieme: mentre una lavora, le + altre due aspettano che finisca o che la interrompi. + +### Adozione + +Se nel posto dove andrebbe la copia c'è già un file **identico** (stesso SHA-256 dell'originale), Febe lo adotta come +copia invece di scriverne un secondo: succede dopo un database perso o ricostruito, con un backup vecchio della +cartella, con due Febe sulla stessa cartella. La sola dimensione non basta mai: un file diverso con la stessa +dimensione resta com'è, e la copia va su un nome libero. + +## Stati di una copia + +| Stato | Che cosa vuol dire | +|---|---| +| **Copiato** | Il file è nella cartella, uguale all'originale | +| **Tolto** | Il file non c'è più nella cartella (l'hai spostato o cancellato tu, o il disco è un altro). Lo trova «Controlla le copie» in Impostazioni ▸ Esportazione, che guarda soltanto e non tocca nessun file. Con il disco staccato non segna nulla come tolto: mette la cartella in pausa | +| **Superato** | Il file della libreria è cambiato dopo la copia: «Tieni il più grande» fra due doppioni, un'importazione che sostituisce, una ricostruzione che trova un altro file. La copia vecchia resta | +| **Non riuscito** | La copia non si è potuta fare (per esempio il limite di FAT32): la prossima «Copia in…» ci riprova | + +**Tolto e Superato non si ricopiano mai da soli.** «Copia di nuovo», nel pannello File del visualizzatore accanto alla +riga della copia, oppure la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…», scrive un file nuovo, e +la copia vecchia resta dov'è. Eliminare un elemento dalla libreria non tocca le sue copie. + +Dove si vede: + +- un piccolo **segno sulla tessera** (solo se c'è almeno una cartella delle copie), con «2/3» per un post copiato in + parte; +- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «Tolto da…», + «Superato in…», con «Copia di nuovo»; +- il conteggio nella **scheda dell'account** («312 su 1.204 non ancora copiati», i tolti o superati, i non riusciti); +- il filtro **«Copie»** in Libreria e nella scheda dell'account: Tutti, Non ancora copiati, Copiati, Tolti o superati. + Resta nell'indirizzo della pagina (`?copie=non-copiati`). + +## Lo stesso post in due account + +Quando lo stesso file è il post di un account e il taggato di un altro, Impostazioni ▸ Esportazione sceglie: + +- **«Una copia per account»** (di solito): una copia per ciascun account, ognuna nella sua cartella; nella cartella + generale lo stesso file sta due volte, sotto il nome di ciascun account; +- **«Una copia sola»**: si copia una volta, nel primo account che lo copia; l'altro lo mostra «Copiato» con la cartella + dove sta. + +## La Dashboard, scheda Esportazione + +La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportazione`). + +- **In corso:** la copia al lavoro, con la barra, quanti file e byte, il file di adesso e **«Interrompi»**. I file già + copiati restano. +- **Da riprendere:** le cartelle in pausa con il motivo e **«Riprova»**; le copie interrotte o in pausa con + **«Riprendi»** (riparte dai file che mancano) e **«Annulla»** (i file già copiati restano, gli altri non si copiano); + **«Riprendi tutte»**. Una copia interrotta da un arresto di Febe si ritrova qui al riavvio: non riparte da sola. +- **Ultimi lavori**, ognuno con il suo **«Resoconto»**: copiati, già presenti e riconosciuti, già copiati, saltati, non + presenti in libreria, non riusciti, per account, e i file da guardare con il motivo. + +Quando ci sono copie da riprendere o cartelle in pausa, la scheda Motore lo dice con un avviso. + +## In Docker: `/esporta` + +Nel contenitore le cartelle delle copie sono **sottocartelle di `/esporta`**, e le copie esterne sono spente finché +non fai due cose: + +1. monti una cartella del server su `/esporta` (per esempio un disco USB o una condivisione), oppure una o più + cartelle **sotto** `/esporta` (`/esporta/usb`, `/esporta/nas`); +2. imposti `FEBE_ESPORTA=1` (o avvii con `--esporta`). + +Senza il montaggio Febe non scrive nulla: una cartella di `/esporta` che non sta su un montaggio sarebbe il disco delle +immagini di Docker, e lo riempirebbe in silenzio. Per questo l'immagine non ha un volume per `/esporta`. In Impostazioni +▸ Esportazione scegli la cartella dall'elenco: un clic sul nome la sceglie, la freccia apre le sue sottocartelle. +`/esporta` stessa non si può scegliere, e nemmeno `..`. Una cartella montata in sola lettura si rifiuta. All'avvio il +contenitore assegna all'utente di Febe solo la cartella `/esporta`, se appartiene a root, mai il suo contenuto. Il +registro dice all'avvio «copie esterne in /esporta» oppure perché sono spente. Come si monta: +[Installazione con Docker e Unraid](Installazione-Docker-e-Unraid). + +## Su Windows: dischi e cartelle di rete + +Su Windows va bene qualunque cartella che esiste, anche su un disco esterno, una cartella di rete o un percorso UNC. +Se il disco si stacca o la condivisione non risponde durante una copia, la cartella va in pausa senza bloccare +l'interfaccia (i controlli sul disco esterno aspettano al più pochi secondi); quando il disco torna, «Riprova» o +«Riprendi» nella Dashboard. Lo spazio libero di una condivisione non sempre si può misurare: allora Febe se ne accorge +quando il disco dice che è pieno, e mette la cartella in pausa. + +Se qualcosa non va: [Problemi comuni](Problemi-comuni), «Copie esterne». diff --git a/docs/guida/Home.md b/docs/guida/Home.md index 982157a..342918a 100644 --- a/docs/guida/Home.md +++ b/docs/guida/Home.md @@ -47,6 +47,8 @@ fare solo con Instagram o su Windows: [Installazione su Windows](Installazione-Windows). - **Docker, interfaccia, importazione, avvisi (anche Telegram), copie e ricostruzione:** pronti, da provare sul tuo Unraid. +- **Copie esterne degli originali (tappa E2, 27 novembre 2026):** pronte, da provare dal vivo su Unraid con + `/esporta` montata e su Windows con una cartella di rete. Vedi [Copie esterne](Esportazione). ## Pagine della guida @@ -58,6 +60,7 @@ fare solo con Instagram o su Windows: | [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 | +| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», stati delle copie, `/esporta` in Docker | | [Limiti e comportamento](Limiti-e-comportamento) | Profili di prudenza, tetti, fascia oraria, ritmo delle sessioni | | [Dashboard e arresti](Dashboard-e-arresti) | La Dashboard, pagina iniziale e cruscotto del motore; che cosa fare dopo una verifica o un rallentamento | | [Avvisi e Telegram](Avvisi-e-Telegram) | Striscia, notifiche di Windows, messaggi Telegram con un bot tuo | diff --git a/docs/guida/Installazione-Docker-e-Unraid.md b/docs/guida/Installazione-Docker-e-Unraid.md index 8798a7e..76ea370 100644 --- a/docs/guida/Installazione-Docker-e-Unraid.md +++ b/docs/guida/Installazione-Docker-e-Unraid.md @@ -22,6 +22,7 @@ pagina Impostazioni ▸ Collegamento a Instagram. | `/dati` | Database (`febe.sqlite`), **profilo del browser con la sessione di Instagram** (`browser/`), con la raccolta `richieste` la sessione salvata cifrata e la sua chiave (`sessione/`), miniature, copie giornaliere del database (`copie/`, sette giorni), registro (`registro/`, quattordici giorni), file temporanei | 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 | +| `/esporta` | **Facoltativo.** Le cartelle delle [copie esterne](Esportazione): Febe ci copia i file della libreria | Un disco USB, una condivisione, un'altra cartella del server; oppure più cartelle montate **sotto** `/esporta` (`/esporta/usb`, `/esporta/nas`). Serve anche `FEBE_ESPORTA=1`. Senza un montaggio Febe non scrive nulla lì | ## Variabili @@ -37,11 +38,28 @@ pagina Impostazioni ▸ Collegamento a Instagram. | `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 | | `FEBE_RACCOLTA` | Come Febe legge il sito: `pagine` con il browser, come sempre; `richieste` con le richieste dirette e la sessione copiata quando premi «Ho finito». Con Instagram, per ora, `richieste` non cambia nulla: lasciala vuota | `pagine` | | `FEBE_CHIAVE_SESSIONE` | Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (`openssl rand -base64 32`). Senza, Febe crea una volta `/dati/sessione/chiave.bin`, leggibile solo dal proprietario. Mettila qui se vuoi la chiave fuori da `/dati`; se la cambi, rifai l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega | `/dati/sessione/chiave.bin` | +| `FEBE_ESPORTA` | Facoltativa: `1` accende le [copie esterne](Esportazione) in `/esporta`, che deve anche essere montata (o avere cartelle montate sotto). `--esporta` sulla riga di comando vale lo stesso | spenta | La password e la chiave della sessione non si passano mai sulla riga di comando e non finiscono nei registri; Febe le toglie dall'ambiente del browser e degli altri programmi che avvia. Febe **non gira come root**: con `PUID=0` il contenitore si ferma con un messaggio. +### Le copie esterne in `/esporta` + +L'immagine non ha un volume per `/esporta`, di proposito: un volume anonimo la farebbe sembrare montata e riempirebbe +in silenzio il disco delle immagini di Docker. Febe scrive soltanto in una cartella che sta su un montaggio in +`/esporta` o sotto, e soltanto con `FEBE_ESPORTA=1`; altrimenti Impostazioni ▸ Esportazione dice perché le copie sono +spente e non si sceglie nessuna cartella. All'avvio il contenitore assegna all'utente `PUID` solo la cartella +`/esporta`, se è di root, mai il suo contenuto. + +- **Unraid:** nel modello, tra le impostazioni avanzate, «Copie esterne (/esporta)» con la cartella del server (per + esempio il disco USB in `/mnt/disks/…`) e `FEBE_ESPORTA` a `1`. Se il disco si monta dopo l'avvio del contenitore + (un disco USB collegato più tardi), riavvia il contenitore o scegli per quella cartella il modo di accesso «RW/Slave», + così il contenitore vede il disco e non la cartella vuota che c'era sotto. +- **Compose:** in `compose.yml` togli il commento alla riga di `/esporta` (la cartella si cambia con + `FEBE_CARTELLA_ESPORTA`) e a `FEBE_ESPORTA: "1"`. +- Una cartella montata in sola lettura (`:ro`) si rifiuta: Febe non potrebbe copiarci nulla. + ## Porte Si pubblica **solo** la porta dell'interfaccia (8480). La porta di debug del browser (9222) ascolta solo su @@ -68,6 +86,8 @@ altrove. - porta 8480; - `/dati` su `/mnt/user/appdata/febe` (disco di cache); - `/libreria` dove vuoi le foto; `/importa` in sola lettura; + - facoltativi, tra le impostazioni avanzate: «Copie esterne (/esporta)» e `FEBE_ESPORTA` a `1`, per le + [copie esterne](Esportazione); - **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`. @@ -91,7 +111,8 @@ tar -xzf febe-compose-X.Y.Z.tar.gz && cd febe-compose-X.Y.Z FEBE_PASSWORD='una frase lunga' docker compose up -d ``` -Le cartelle si cambiano con `FEBE_DATI`, `FEBE_LIBRERIA` e `FEBE_IMPORTA` (predefinite sotto `/srv/febe`). +Le cartelle si cambiano con `FEBE_DATI`, `FEBE_LIBRERIA` e `FEBE_IMPORTA` (predefinite sotto `/srv/febe`). Per le +copie esterne togli il commento alla riga di `/esporta` (cartella in `FEBE_CARTELLA_ESPORTA`) e a `FEBE_ESPORTA: "1"`. ## La sandbox di Chromium diff --git a/docs/guida/Libreria.md b/docs/guida/Libreria.md index 797fa25..1243d7e 100644 --- a/docs/guida/Libreria.md +++ b/docs/guida/Libreria.md @@ -74,7 +74,8 @@ elimina il post. Lo stesso vale per «Elimina dalla libreria» nel visualizzator 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. +si esportano solo gli elementi scelti. Quando c'è una cartella delle [copie esterne](Esportazione), il pulsante apre un +menu con «Esporta l'elenco (CSV)» e «Copia i file in…», e accanto agli altri filtri compare il filtro «Copie». 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, diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 1853ae7..ce3a02a 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -126,10 +126,36 @@ Gli avvisi che non sono arrivati sono elencati nella Dashboard ▸ Avvisi come | 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 | +| «C'è una copia nelle cartelle esterne al lavoro…» | Copie, importazione e ricostruzione non girano insieme: aspetta che la copia finisca, o interrompila dalla Dashboard, scheda Esportazione | + +## Copie esterne + +Vedi anche [Copie esterne](Esportazione). + +| Che cosa vedi | Che cosa fare | +|---|---| +| Docker: «Le copie esterne in Docker sono spente: si accendono con FEBE_ESPORTA=1…» | Imposta `FEBE_ESPORTA=1` e monta una cartella del server su `/esporta` (su Unraid: «Copie esterne (/esporta)» tra le impostazioni avanzate; con Compose la riga commentata di `/esporta`), poi ricrea il contenitore | +| Docker: «/esporta è dichiarata ma non è montata…» | `/esporta` non è montata, né c'è una cartella montata sotto: Febe non scrive nulla. Monta la cartella del server e ricrea il contenitore. Il registro lo dice all'avvio («copie esterne spente (/esporta non montata)») | +| Docker: «… non è su una cartella montata in /esporta» | Ci sono cartelle montate sotto `/esporta`, ma quella scelta non sta su nessuna: scegline una dentro un montaggio | +| Docker: «… è montata in sola lettura» | Togli `:ro` (su Unraid il modo di accesso deve permettere la scrittura) e ricrea il contenitore | +| Docker: «Scegli una sottocartella di /esporta» o ««..» non è ammesso» | `/esporta` stessa non si sceglie: crea una cartella dentro (dal server) e sceglila dall'elenco | +| Docker: i file copiati non sono sul disco USB, ma in una cartella del server | Il disco è stato montato dopo l'avvio del contenitore, che vede la cartella vuota di prima: riavvia il contenitore o usa il modo di accesso «RW/Slave» (vedi l'[installazione](Installazione-Docker-e-Unraid)) | +| «La cartella … non esiste. Febe non crea mai la cartella di una destinazione…» | Crea tu la cartella, o collega il disco, poi sceglila di nuovo. Febe non la crea apposta: un disco staccato non deve diventare una cartella sul disco del computer | +| «… è la radice di un disco o di una condivisione» | Scegli una cartella dentro quel disco o quella condivisione | +| La cartella è rifiutata perché è dentro o contiene la libreria, i dati, la cartella di un account o quella da importare | Scegli una cartella fuori da tutte queste, e che non ne contenga nessuna. Vale anche quando ci arrivi per un'altra strada (lettera di unità o percorso di rete): Febe se ne accorge con il file di prova | +| Una cartella «In pausa: … non è raggiungibile…» | Il disco è staccato o la condivisione non risponde: ricollegalo, poi «Riprova» in Impostazioni ▸ Esportazione o «Riprendi» nella Dashboard, scheda Esportazione. I file già copiati restano; nessuna copia diventa «Tolto» finché la cartella non si raggiunge | +| «Su … restano … serve più spazio, con un margine di 64 MB» o «non c'è più spazio» | Libera spazio sul disco delle copie, poi «Riprendi» | +| Un video «Non riuscito»: «su un disco FAT32 un file non può superare 4 GB» | Il disco è formattato FAT32: per i file più grandi serve un disco exFAT o NTFS. Gli altri file si copiano lo stesso | +| Nella cartella c'è `nome (2).jpg` accanto a `nome.jpg` | Nel posto della copia c'era già un altro file: Febe non sovrascrive mai, scrive su un nome libero e lascia l'altro com'è | +| Un file risulta «Tolto» | Non è più nella cartella: l'hai spostato o cancellato fuori da Febe. Non si ricopia da solo: «Copia di nuovo» nel visualizzatore, o la casella «Copia di nuovo anche i N tolti o superati» in «Copia in…» | +| La copia resta su «Aspetto la fine della sessione del motore» | È voluto: durante una sessione del motore non si copia. Riparte da sola appena la sessione finisce | +| «C'è un lavoro di copia non finito verso questa cartella…» | Prima di cambiare la cartella, riprendi o annulla quel lavoro nella Dashboard, scheda Esportazione | +| «Copia in…» dice «N di account che non si esportano» | Quegli account hanno «Esporta questo account» spento (scheda dell'account ▸ Impostazioni ▸ «Copie esterne») | +| «Copia in…» o il filtro «Copie» non ci sono | Manca una cartella delle copie: scegline una in Impostazioni ▸ Esportazione (o nella scheda dell'account) | ## 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 | +| «Ricostruisci» è rifiutato | C'è un'importazione o una copia nelle cartelle esterne in corso: aspetta che finisca, o interrompila | diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index 2206a50..c4ee796 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -115,3 +115,8 @@ Nient'altro: niente statistiche, niente aggiornamenti automatici, nessun caratte Febe è un archivio privato: non ripubblica e non condivide nulla. Le esportazioni CSV contengono le didascalie: trattale come i dati che descrivono. + +Le [copie esterne](Esportazione) escono dal controllo di Febe: chi ha la cartella delle copie, o il disco su cui sta, +ha quei file, foto e video di altre persone compresi. Febe non le cifra e non le cancella; nelle cartelle delle copie +non scrive diari, identificativi o didascalie, solo i file. Una chiavetta o un disco con le copie va trattato come la +libreria. diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 27e551b..de821e8 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -124,6 +124,11 @@ 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`. +- Copie esterne: `/impostazioni/esportazione` (con `?veste=docker` la nota su `/esporta` e la scelta dall'elenco), + `/dashboard/esportazione`, `/libreria?copie=non-copiati` (anche `copiati` e `tolti`). La dimostrazione ha una cartella + generale «Disco USB», una cartella sua «Studio Lumen» per @studio.lumen.demo, @il.porto.demo che non si esporta, copie + in ogni stato (copiate, una tolta, una superata, una non riuscita) e una copia interrotta da riprendere, tutte scritte + dal motore vero in una cartella `esporta` dentro quella temporanea; «Scegli…» propone la cartella «Chiavetta». - Per modificare l'interfaccia senza ricompilare: `FEBE_INTERFACCIA=$PWD/src/Febe.Web/wwwroot dotnet run --project src/Febe.Server -- --demo`, poi basta ricaricare. diff --git a/docs/guida/_Sidebar.md b/docs/guida/_Sidebar.md index 6184e3e..64f7c71 100644 --- a/docs/guida/_Sidebar.md +++ b/docs/guida/_Sidebar.md @@ -9,6 +9,7 @@ - [Account e impostazioni](Account-e-impostazioni) - [Libreria](Libreria) - [Importazione](Importazione) +- [Copie esterne](Esportazione) - [Limiti e comportamento](Limiti-e-comportamento) - [Dashboard e arresti](Dashboard-e-arresti) - [Avvisi e Telegram](Avvisi-e-Telegram) diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md index dd22530..d053d8c 100644 --- a/docs/prove-dal-vivo.md +++ b/docs/prove-dal-vivo.md @@ -546,3 +546,83 @@ lo documenta, e nemmeno chi li mette nella richiesta. Che cosa riferire: i tre nomi esatti, «sì/no» per ciascun campo nella richiesta, «uguali/diversi» e «cambiano/non cambiano». Se i nomi sono diversi, il catalogo va corretto prima di configurare qualunque operazione. + +--- + +## F. Copie esterne (tappa E2): Docker con `/esporta`, FAT32, cartella di rete su Windows + +Scopo: vedere sul tuo impianto ciò che le prove automatiche non possono fare (specifica §4.10, §11, §12): un montaggio +vero su Unraid, un disco FAT32 vero, una condivisione che si stacca. **Non serve Instagram**: le copie leggono solo +file già in libreria. Basta una libreria con qualche post (anche importato) e, per F3, un video di più di 4 GB. + +Prima di ogni parte: annota quanti file ci sono nella cartella delle copie e la loro dimensione totale, così alla +fine puoi dire se qualcosa è stato sovrascritto o tolto. Febe non deve mai cancellare, spostare o sovrascrivere nulla +in quelle cartelle, né crearne la cartella scelta. + +### F1. Docker su Unraid, `/esporta` non montata + +1. Con il contenitore come oggi (nessun montaggio su `/esporta`, nessuna `FEBE_ESPORTA`), apri Impostazioni ▸ + Esportazione. Atteso: «Le copie esterne in Docker sono spente: si accendono con FEBE_ESPORTA=1 (o --esporta) e una + cartella del server montata su /esporta.», nessuna cartella da scegliere. Nel registro dell'avvio: «copie esterne + spente (/esporta non dichiarata)». +2. Aggiungi solo `FEBE_ESPORTA=1` (nel modello, impostazioni avanzate) e ricrea il contenitore, **senza** montare + nulla. Atteso: «/esporta è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del + server su /esporta.»; nel registro un avviso e «copie esterne spente (/esporta non montata)»; Febe parte lo stesso. +3. Dal terminale di Unraid: `docker exec febe ls -la /esporta`. Atteso: la cartella non c'è (l'immagine non la crea), + oppure è vuota. Nessun file è stato scritto nel disco delle immagini. + +### F2. Docker su Unraid, `/esporta` montata + +1. Crea sul server una cartella per le copie, per esempio `/mnt/user/Febe-copie`, e dentro una sottocartella + `disco`. Nel modello: «Copie esterne (/esporta)» → `/mnt/user/Febe-copie`, `FEBE_ESPORTA` → `1`; ricrea il + contenitore. Atteso nel registro: «copie esterne in /esporta». Atteso su `/mnt/user/Febe-copie`: proprietario + `99:100` se prima era `root`; il contenuto (la sottocartella `disco`) **non** cambia proprietario. +2. Impostazioni ▸ Esportazione ▸ «Scegli una cartella…»: l'elenco mostra `disco`. Prova anche a scrivere `..` o a + scegliere `/esporta` stessa: atteso il rifiuto con il motivo. Scegli `disco`, tipi «Post foto» e «Post video», + «Come la libreria», salva. +3. In Libreria scegli qualche post, «Copia in…»: la finestra dice quanti file, «In cartella generale», lo spazio libero. + «Copia N file», poi Dashboard ▸ scheda Esportazione: la copia finisce con «Completata»; «Resoconto». +4. Sul server: i file sono in `/mnt/user/Febe-copie/disco//…`, con le date di pubblicazione; nessun `.part` + rimasto; nessun file di prova `.febe-prova-*`. Le tessere copiate hanno il segno. +5. Rifai «Copia in…» sugli stessi post: atteso «N già copiati, saltati», nessun file nuovo. +6. Cancella a mano un file copiato dal server, poi «Controlla le copie»: quel file diventa «Tolto» nel visualizzatore, + con «Copia di nuovo». Premilo: nasce un file nuovo, nessun altro file cambia. +7. Facoltativo, sotto-montaggi: togli il montaggio di `/esporta` e monta invece la cartella su `/esporta/usb`. Atteso: + le copie restano attive e si sceglie solo dentro `usb`. +8. Facoltativo, disco staccato: con un disco USB montato con Unassigned Devices al posto della cartella, smontalo + **mentre una copia lavora**. Atteso: la cartella va «In pausa» con il motivo (Impostazioni e Dashboard), nessuna + striscia rossa, nessun file scritto altrove, nessuna copia segnata «Tolto». Rimonta il disco (riavvia il contenitore, + o usa «RW/Slave»), poi «Riprendi»: la copia finisce i file che mancavano. + +### F3. Un disco USB FAT32 e un file oltre 4 GB + +1. Su Windows (o su Unraid con F2), scegli come cartella generale una cartella di una chiavetta o di un disco **FAT32**. + Atteso nella finestra della cartella: «Disco FAT32: i file oltre 4 GB non si copiano.» +2. «Copia in…» su un account con un video di più di 4 GB e qualche foto. Atteso: le foto si copiano; il video è «Non + riuscito» con «su un disco FAT32 un file non può superare 4 GB», la copia **non** si ferma e il resoconto lo elenca + fra i file da guardare. Sulla chiavetta non resta nessun `.part`. + +### F4. Febe per Windows, cartella di rete UNC staccata durante una copia + +1. Su Febe per Windows scegli come cartella generale una cartella di una condivisione con il percorso UNC + (`\\nas\condivisione\febe`, che esiste già). Atteso: accettata; lo spazio libero compare se Windows lo dice. +2. Prova a scegliere la radice della condivisione (`\\nas\condivisione`): atteso il rifiuto «… è la radice di un disco + o di una condivisione…». Se hai anche una lettera di unità per la stessa condivisione, prova a scegliere come cartella + di un account la stessa cartella attraverso la lettera: atteso il rifiuto (il file di prova la riconosce). +3. Avvia «Copia in…» su abbastanza file da durare qualche minuto. Durante la copia **stacca la rete** (o ferma la + condivisione). Atteso, entro pochi secondi: la cartella «In pausa: … non è raggiungibile…», la finestra di Febe + resta reattiva, nessuna copia «Tolto», nessuna cartella creata su `C:`. +4. Ricollega la rete, poi Dashboard ▸ scheda Esportazione ▸ «Riprendi». Atteso: la copia riprende dai file che + mancavano e finisce; i file già copiati non si riscrivono; resta al più il `.part` del file interrotto, e solo fino a + «Riprendi», che lo toglie. +5. Facoltativo: esci da Febe durante una copia e riaprilo. Atteso: la copia è «Interrotta» nella scheda Esportazione e + non riparte da sola; nel registro «N copie interrotte dall'arresto precedente…». + +### F5. Che cosa riferire + +- Per ogni passo «come atteso» oppure il testo esatto di ciò che hai visto, con l'ora. +- Il conteggio dei file della cartella delle copie prima e dopo (F2, F4): solo file in più, mai meno o cambiati. +- Le righe del registro dell'avvio che parlano di copie esterne (F1, F2) e quelle della pausa (F2 passo 8, F4). +- In F2 passo 1 l'esito di `stat -c '%u:%g' /mnt/user/Febe-copie /mnt/user/Febe-copie/disco` dal terminale di Unraid. +- Se un file è finito nel posto sbagliato (per esempio nella cartella vuota del server con il disco smontato): il + percorso, e lascia il file dov'è. diff --git a/docs/schermate/15-impostazioni-esportazione-docker.png b/docs/schermate/15-impostazioni-esportazione-docker.png new file mode 100644 index 0000000..91cf9c4 Binary files /dev/null and b/docs/schermate/15-impostazioni-esportazione-docker.png differ diff --git a/docs/schermate/15-impostazioni-esportazione.png b/docs/schermate/15-impostazioni-esportazione.png new file mode 100644 index 0000000..1b8cb3c Binary files /dev/null and b/docs/schermate/15-impostazioni-esportazione.png differ diff --git a/docs/schermate/16-destinazione.png b/docs/schermate/16-destinazione.png new file mode 100644 index 0000000..d6e8965 Binary files /dev/null and b/docs/schermate/16-destinazione.png differ diff --git a/docs/schermate/17-account-copie-esterne.png b/docs/schermate/17-account-copie-esterne.png new file mode 100644 index 0000000..13b57fe Binary files /dev/null and b/docs/schermate/17-account-copie-esterne.png differ diff --git a/docs/schermate/18-copia-in.png b/docs/schermate/18-copia-in.png new file mode 100644 index 0000000..f4b9616 Binary files /dev/null and b/docs/schermate/18-copia-in.png differ diff --git a/docs/schermate/19-libreria-copie.png b/docs/schermate/19-libreria-copie.png new file mode 100644 index 0000000..05c5fc9 Binary files /dev/null and b/docs/schermate/19-libreria-copie.png differ diff --git a/docs/schermate/20-visualizzatore-copie.png b/docs/schermate/20-visualizzatore-copie.png new file mode 100644 index 0000000..ece700b Binary files /dev/null and b/docs/schermate/20-visualizzatore-copie.png differ diff --git a/docs/schermate/21-dashboard-esportazione.png b/docs/schermate/21-dashboard-esportazione.png new file mode 100644 index 0000000..e4f2190 Binary files /dev/null and b/docs/schermate/21-dashboard-esportazione.png differ diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md index 51d71ee..7b5bb79 100644 --- a/docs/schermate/differenze.md +++ b/docs/schermate/differenze.md @@ -41,6 +41,14 @@ solo per l'interfaccia di Febe (§10.7). | `doppioni-download.png` | `/doppioni` | confronto di `miniature/09-importa-revisione.png` (§9.5) | | `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) | | `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) | +| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione` (presa il 27/11 da Windows, come le righe seguenti) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` | +| `15-impostazioni-esportazione-docker.png` | `/impostazioni/esportazione?veste=docker`, con la nota su `/esporta` | come sopra | +| `16-destinazione.png` | `/impostazioni/esportazione`, «Modifica…» della cartella generale, «Uno schema suo» con il primo schema cambiato (passo `destinazione.js`), 1440 × 1000 | composta dal mockup 08 («Nomi dei file», «Risultato») e dai dialoghi di `miniature/13-foglio-di-stile.png` | +| `17-account-copie-esterne.png` | `/account/3/impostazioni` (@studio.lumen.demo, cartella sua), scorsa fino a «Cartella» (passo `account-copie.js`), 1440 × 1000 | composta da `miniature/05-account-impostazioni.png` | +| `18-copia-in.png` | `/libreria`, menu dell'icona CSV → «Copia i file in…» su tutta la libreria (passo `copia-in.js`) | composta dai dialoghi del 13 e da `miniature/09-importa-revisione.png` | +| `19-libreria-copie.png` | `/libreria?copie=copiati`, menu dell'icona CSV aperto (passo `menu-csv.js`) | composta da `docs/mockup/01-libreria.png` | +| `20-visualizzatore-copie.png` | `/libreria?copie=tolti`, la prima foto con «Copia di nuovo» (passo `visualizzatore-copie.js`) | composta da `miniature/02-visualizzatore.png` | +| `21-dashboard-esportazione.png` | `/dashboard/esportazione` | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) | ## Differenze che restano @@ -208,6 +216,77 @@ non sono state eseguite; la scheda account con «Tutte le foto» non ha una sche scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file». - **Visualizzatore** (mockup 02): si apre sul file della tessera; in alto «Libreria, file 12 di 61.034». +### Esportazione (tappa E2, issue #58, dal 27 novembre 2026) + +Le schermate dell'esportazione (§10.3 «Schermate dell'esportazione») non hanno un mockup: sono composte dai mockup +esistenti (decisione di Alberto del 18 novembre 2026), come dice la tabella. Le otto schermate `15-…` – `21-…` sono state +prese il 27/11 con il programma delle schermate da Windows (`tools/Febe.Schermate`, browser senza finestra, scala 1,25), +una alla volta con `una`, su una dimostrazione appena avviata (`--demo --porta 8490`), nell'ordine della tabella; nessun +passo avvia una copia, quindi le copie restano quelle preparate dalla dimostrazione. Misure: 1440 × 900, e 1440 × 1000 +per la finestra della destinazione e per la scheda account (come il mockup 05). Poi sono state messe accanto ai mockup +da cui nascono. Le prove dell'interfaccia (`ExportInterfaceTests`: impostazioni e nota Docker, finestra della +destinazione, blocco dell'account, «Copia in…» dalla selezione, filtro «Copie» e segno sulle tessere, righe del +visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui non sono state eseguite. Differenze: + +- **Formati e conversione non ci sono (E3).** La tappa E2 copia solo gli originali: la finestra della destinazione non + ha la parte dei formati, Impostazioni → Esportazione non ha «Formati predefiniti delle copie» né «Conversione della + libreria», e il riepilogo di «Copia in…» non ha mai «3 HEIC copiati come sono» né «con perdita». I controlli mancano, + non sono spenti: un controllo grigio senza niente dietro non dice che cosa succede (§10.4). +- **«Automatica» non c'è (E5).** La scelta si conserva ma non si mostra, con la domanda «Solo i nuovi»: senza il giro + orario della tappa E5 un interruttore acceso non farebbe nulla. +- **«Fotogrammi…» e «Fotogramma» non ci sono (E3)**: né nella barra della selezione della Libreria e della scheda + account, né nel visualizzatore. Neppure la finestra «Fotogrammi…». +- **«È un video fermo?» non c'è (E4)** nel visualizzatore. +- **Segno sulla tessera** (voluto, §4.10): l'ultimo dei segni in alto a destra, un riquadro scuro con l'icona `copy` + quando i file dovuti dell'elemento sono tutti copiati, con «2/3» quando lo sono solo in parte. Nel mockup 01 non c'è. + Le tessere degli account che non hanno una cartella delle copie, o che non si esportano, non hanno il segno. +- **Dashboard con due schede, «Motore» ed «Esportazione»**, sotto il titolo, con lo stile delle linguette della scheda + account (mockup 05 e 12): la scheda «Motore» è la Dashboard di sempre, senza differenze; la scheda «Esportazione» ha + «In corso», «Da riprendere» e «Ultimi lavori», in una colonna larga al più 980 px (come la cronologia dell'account, + non a tutta larghezza come il mockup 06). Le righe di «Ultimi lavori» sono quelle della cronologia del mockup 06, + con l'etichetta di stato e «Resoconto», che apre un dialogo (mockup 13), non una pagina. La schermata non mostra la + barra di avanzamento: nella dimostrazione una copia finisce subito. +- **«Copia in…» non sceglie la cartella** (decisione D5 della tappa): ogni file va nella cartella del suo account, e il + dialogo dice dove con una riga per cartella («In Disco USB (…)», «cartella generale · 969 file · 3,4 GB · liberi + 1.676,4 GB»), nello stile dell'elenco delle cartelle dell'importazione (mockup 09). La casella «Copia di nuovo anche i + N tolti o superati» è spenta all'apertura. +- **Impostazioni → Esportazione** (mockup 08 e 07): campo della cartella generale con l'icona del disco, «Modifica…» e + «Togli la cartella» (pulsante senza bordo) al posto di «Cambia…»; lo spazio libero non sta accanto al campo come nel + mockup 08 ma nella riga di controllo della finestra della destinazione e in «Copia in…». Sotto il campo i tipi e gli + schemi, poi i conteggi con «Controlla le copie». In Docker in alto c'è la nota azzurra su `/esporta`, e la finestra + della destinazione sfoglia le sottocartelle di `/esporta` al posto del campo con «Scegli…» (non c'è una schermata). +- **Scheda account → Copie esterne** (mockup 05): un blocco sotto «Cartella» con l'interruttore «Esporta questo + account», poi il nome del tipo di cartella sopra il campo («Nella sua cartella», «Nella cartella generale»), il campo + con «Modifica…» e «Usa la cartella generale» (o «Scegli una cartella sua…»), e la riga «371 su 648 non ancora + copiati» con «Copia in…». +- **Visualizzatore** (mockup 02): nel pannello File una riga «Copia» per ogni copia («Tolto da Disco USB il 24 + novembre», «Copiato in Studio Lumen il 27 novembre · intero»), con «Copia di nuovo» sotto il valore per una copia tolta + o superata; «Copia in…» fra i pulsanti in fondo al pannello. +- **Libreria** (mockup 01): il filtro «Copie» è un menu a pastiglia dopo «Provenienza», visibile solo quando c'è almeno + una cartella delle copie; scelto, dice la scelta («Copiati»). L'icona CSV apre un menu con «Esporta l'elenco (CSV)» e + «Copia i file in…» invece di scaricare subito l'elenco. +- **Contenuti dimostrativi.** La dimostrazione usa le stesse immagini in molti elementi, e un file è «già copiato» se + il suo contenuto (SHA-256) è già nella cartella: per questo i numeri sembrano strani. «Copia in…» su tutta la libreria + dice «28.751 già copiati, saltati»; la tabella delle cartelle degli account dice «13 copiati» per @studio.lumen.demo + mentre il suo blocco dice «371 su 648 non ancora copiati»; il filtro «Tolti o superati» trova 28 elementi. Alcuni + video della dimostrazione non hanno il file («Il video non è sul disco»). I percorsi sono quelli della cartella + temporanea della dimostrazione. +- **Sistemato il 27/11** dopo il confronto, ora come nei mockup: + - la riga dei tipi e degli schemi sotto il campo della cartella generale stava attaccata al campo: ora ha 8 px sopra, + come le note sotto i campi del mockup 08; + - in Docker la nota azzurra su `/esporta` e l'avviso ambra «1 copia da riprendere» si toccavano: ora sono separati + da 10 px; + - nella scheda «Esportazione» della Dashboard il titolo «In corso» stava attaccato alle linguette: ora c'è spazio + sopra (18 px); + - le icone dei pulsanti dentro un avviso prendevano il colore dell'avviso (il triangolo di «Riprendi», pulsante blu, + era ambra): ora hanno il colore del testo del pulsante, in tutta l'interfaccia; + - nel blocco «Copie esterne» il campo diceva «Nella sua cartella: B:\…\esporta…» e il nome della cartella, la parte + utile, finiva tagliato: il tipo di cartella è andato sopra il campo, come le etichette del mockup 08; + - «Copia di nuovo» del visualizzatore è allineato alla colonna dei valori. +- **Senza schermata:** il menu «Copie» aperto, «Copia in…» nella barra della selezione, dalla scheda account e dal + visualizzatore, la finestra della destinazione in Docker, il «Resoconto», una copia in corso con Interrompi, una + cartella in pausa con «Riprova», il tema scuro, la finestra stretta e il telefono. + ### Carattere e icone (dal 18 novembre 2026) Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre diff --git a/docs/stato.md b/docs/stato.md index 8b35351..b547af4 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -1,14 +1,67 @@ # Stato Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché. -Aggiornato il 26 novembre 2026 (tappa E1 Schema unita in `main` con #69; prima, catena della 0.3.0 unita in `main`, -#60 … #66), versione 0.1.2 in +Aggiornato il 27 novembre 2026 (tappa E2 Copie esterne; prima, E1 Schema unita in `main` con #69 e la catena della +0.3.0, #60 … #66), versione 0.1.2 in `main` (il tag `v0.1.2` non è stato creato). **Le attività stanno su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto fra le sessioni; ciò che è da fare si legge nelle issue aperte. ## In breve +**27 novembre 2026: tappa E2 «Copie esterne» dell'esportazione** (#58). Decisione di Alberto di oggi: «Esporta questo +account» senza una scelta registrata (nessuna riga in `export_account`) è **acceso**. Le altre sei domande della tappa +sono in §16 (righe 22–27) con la proposta adottata, da confermare. + +- **Motore** (`src/Febe.Core/Export/`): destinazioni (cartella generale e cartelle degli account; la destinazione di un + account è la sua cartella, se c'è, altrimenti la generale), controlli delle cartelle (mai dentro o sopra Libreria, + Dati, `/importa` o la cartella di un account, anche per alias: giunzioni, collegamenti, `subst`, unità di rete, bind + mount; prova con un file sonda), piano, copia verificata (`.part` riletto dal disco, poi un nome libero, mai una + sostituzione: su Linux `renameat2` con `RENAME_NOREPLACE`), adozione dei file già presenti, «Tolto» e «Superato» + (mai ricopiati da soli: solo con «Copia di nuovo»), «Una copia sola» con una regola sola per filtro, conteggi, piano, + visualizzatore e copia, resoconti, ripresa dopo un arresto. Solo originali: le conversioni sono di E3. Import, + copie e ricostruzione si escludono a vicenda (`LongWorkGate`); niente copie durante una sessione del motore; sonda + della cartella prima di ogni gruppo di 100 file o 1 GiB; margine di 64 MiB e limite di 4 GiB su FAT32. +- **Docker**: `/esporta` vale solo se dichiarato (`FEBE_ESPORTA` e un mount a `/esporta` o sotto, letto da + `/proc/self/mountinfo`); l'avvio cambia proprietario solo alla radice di `/esporta`, solo se dichiarata e di root, mai + in modo ricorsivo. `compose.yml` e il modello Unraid hanno le righe commentate. +- **API e interfaccia**: Impostazioni › Esportazione (cartelle, schema dei nomi, «Una copia sola» o «Una per account»; + «Automatica» registrata ma nascosta fino a E5), interruttore «Esporta questo account» e conteggio nella pagina + dell'account, «Copia in…» da selezione, account e visualizzatore, filtro «Copie» e segni sulle tessere della + Libreria, righe delle copie nel visualizzatore con «Copia di nuovo», scheda «Esportazione» della Dashboard con + avanzamento, Interrompi, Riprendi, Riprova e Resoconto. Modalità dimostrativa con copie già fatte. +- **Migrazione `0004_esportazione_filtro.sql`**: solo l'indice `ix_media_sha256_entry`. Misure a 200.000 elementi: le + finestre del filtro «Copie» entro 250 ms («Copiati» da 249 a circa 162 ms); totali e giorni da 0,23 a 1,13 s, sotto un + limite loro di 3 s (ogni file dovuto si classifica; righe in `decisioni.md`). +- **Revisione a più lenti** prima dell'unione: 22 rilievi confermati e corretti (commit `36ad5c6`). I più seri: un disco + staccato a metà di «Controlla le copie» segnava «Tolto» fino a 1000 copie buone (ora la radice si prova prima di ogni + pagina e ogni mancante si riguarda); «Interrompi» con più cartelle lasciava le corse seguenti «in corso» per sempre; + un alias di una sottocartella della Libreria era accettato come destinazione; una riga vecchia sul nome libero + faceva fallire la registrazione della copia. Le tre prove cadute nella CI (esecuzione 487) erano fra questi. +- Documenti: SPECIFICA §4.10, §8.3, §11, §12, §16 righe 22–27, glossario; guida `Esportazione.md`; `docker.md`, + `windows.md`, `prove-dal-vivo.md` parte F; otto schermate nuove (15–21) con il confronto in + `docs/schermate/differenze.md`; righe del 27/11 in `decisioni.md`. +- Controlli, su Windows: `dotnet build -warnaserror` 0 avvisi, 0 errori; `dotnet test tests/Febe.Tests` 3031 superate, + 103 ignorate (Chromium e Xvfb, e quelle di Linux come root: solo nella CI), 0 non superate; `dotnet test + tests/Febe.Tests.Windows` 24 superate. +- **Non verificato**: + - un `/esporta` vero su Unraid e una cartella di rete (UNC) vera su Windows; `WindowsExportDisk` non è provato; + - un disco montato su Unraid dopo l'avvio del contenitore: senza «RW/Slave» il contenitore vede la cartella vuota di + sotto, che è un mount, e Febe vi scriverebbe. Il codice non lo riconosce; è scritto nella guida e in + `prove-dal-vivo.md` F2.8; + - su Windows le giunzioni sotto la cartella scelta che portano nella Libreria non si cercano (su Linux i mount sì); + - lo spazio esaurito riconosciuto dal codice d'errore del sistema (non si provoca in modo portabile; il margine e + FAT32 sono provati con un disco finto); + - nessuna schermata di: menu «Copie» aperto, «Copia in…» dalla barra della selezione, dall'account e dal + visualizzatore, cartella in Docker, Resoconto, copia in corso con Interrompi, cartella in pausa con Riprova, tema + scuro, finestra stretta, telefono (elenco in `differenze.md`); + - le correzioni d'interfaccia della revisione (visualizzatore dopo «Copia di nuovo», conteggio stabile nella + finestra di «Copia in…», un solo ciclo di lettura nella Dashboard) non hanno prove loro: le ha viste solo la CI; + - nella dimostrazione alcuni numeri non tornano fra loro (le stesse immagini di esempio stanno in più elementi, e la + copia segue lo SHA-256), e ogni riga di copia del visualizzatore finisce con «· intero». +- **Prossima tappa**: E3 «Formati e fotogrammi» (conversione delle copie e della libreria, `media_conversion`) oppure E5 + «Esportazione automatica», a scelta di Alberto. + **26 novembre 2026: tappa E1 «Schema» dell'esportazione** (#58, unita in `main` con #69). Nessun cambio di comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue. @@ -46,7 +99,7 @@ comportamento: nulla in interfaccia, motore o API usa ancora ciò che segue. nome; le due riesecuzioni verdi: E1 non tocca nulla di quel progetto). Togliendo dalla `0003` quattro CHECK (file dei convertiti, byte della copia, account rimosso solo sulle orfane, «Automatica» booleana) cadono le prove che li riguardano. - **Lasciato a E2 ed E3**: - - il valore predefinito di «Esporta questo account» (nessuna riga in `export_account` oggi: lo sceglie E2); + - il valore predefinito di «Esporta questo account» (deciso il 27/11: acceso); - E3 deve togliere i file convertiti e le righe di `media_conversion` prima di cancellare una riga `media` (`ON DELETE RESTRICT`): oggi `LibraryDeletion` e la rimozione di un account con un convertito registrato falliscono, ed è voluto (nessun convertito resta sul disco senza traccia); diff --git a/docs/windows.md b/docs/windows.md index a40929f..2d02e8b 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -130,6 +130,7 @@ disinstallato. | Programma | `%LOCALAPPDATA%\Programs\Febe\Febe.exe` | Dove l'hai copiato, per la versione portabile | | **Dati di Febe** | `%LOCALAPPDATA%\Febe` | Database `febe.sqlite`, **profilo del browser con la sessione di Instagram** (`browser\`), dati della finestra dell'interfaccia (`interfaccia\`), miniature, copie del database (`copie\`, sette giorni), registro (`registro\`, quattordici giorni) | | **Libreria** | `Immagini\Febe` | Foto e video, una cartella per account, con `_febe.jsonl` | +| Copie esterne (facoltative) | Le cartelle che scegli in Impostazioni ▸ Esportazione e nella scheda di un account | Copie dei file della libreria (specifica §4.10): un disco esterno, una chiavetta, una cartella di rete o un percorso UNC (`\\nas\foto\febe`). Si scelgono con «Scegli…», la finestra di Windows | - **Chi ha la cartella dei dati, o una sua copia, ha la sessione di Instagram.** Trattala come una password: niente copie su chiavette, cartelle condivise o servizi di sincronizzazione (OneDrive, Dropbox…). `%LOCALAPPDATA%` non è @@ -143,6 +144,14 @@ disinstallato. cartella e cancella la vecchia (che conteneva una copia della sessione). Se qualcosa va storto la vecchia cartella resta quella in uso, intatta, e la copia parziale viene tolta. Per farlo subito: Esci e riapri Febe. La cartella scelta è scritta in `HKEY_CURRENT_USER\Software\Febe` (`CartellaDati`); con `--dati` decide invece la riga di comando. +- **Cartelle delle copie esterne** (guida «Copie esterne»): devono esistere già (Febe non le crea mai: un disco + staccato non deve diventare una cartella sul disco `C:`), fuori dalla cartella dei dati, dalla libreria, dalle + cartelle degli account e da quella da importare, e non la radice di un disco o di una condivisione (`E:\`, + `\\nas\foto`). Una lettera di unità e un percorso UNC che portano allo stesso posto si riconoscono con un file di + prova `.febe-prova-….part`, scritto e tolto solo nella cartella scelta. Le cartelle di rete vanno bene: spazio libero + e FAT32 si leggono anche lì quando Windows li dice; se una condivisione non risponde, la cartella va in pausa senza + bloccare la finestra, e la copia riprende con «Riprendi» nella Dashboard, scheda Esportazione. Febe non sovrascrive, + non sposta e non cancella nulla in quelle cartelle, e non le cifra: le copie escono dal suo controllo. ## Riga di comando @@ -299,3 +308,7 @@ sulla CI per Linux. | Il collegamento risulta perso dopo un riavvio | È l'ipotesi S3: riferiscilo (parte C di `docs/prove-dal-vivo.md`) con l'ora e il registro di quel giorno | | Il browser sembra fermo mentre è fuori vista | È l'ipotesi S2: prova `Febe.exe --browser composizione`, poi `--browser edge`, e riferisci | | Il registro | `%LOCALAPPDATA%\Febe\registro\febe-AAAA-MM-GG.log`: azioni ed esiti, mai password, cookie, tasti o contenuti | +| Copie esterne: «La cartella … non esiste. Febe non crea mai la cartella di una destinazione…» | Collega il disco (o crea la cartella), poi sceglila di nuovo | +| Copie esterne: una cartella di rete «In pausa: … non è raggiungibile…» | La condivisione non risponde o il computer non è in rete: ricollegala, poi «Riprova» in Impostazioni ▸ Esportazione o «Riprendi» nella Dashboard, scheda Esportazione. Nessuna copia diventa «Tolto» mentre la cartella non si raggiunge | +| Copie esterne: «non c'è più spazio» su una condivisione | Lo spazio libero di alcune condivisioni non si misura prima: Febe se ne accorge quando il disco è pieno e mette la cartella in pausa. Libera spazio, poi «Riprendi» | +| Copie esterne: un video «Non riuscito» su una chiavetta | La chiavetta è FAT32, che non tiene file oltre 4 GB: usa un disco exFAT o NTFS | diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index ef7f100..b7ac062 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -11,6 +11,7 @@ using Febe.Core.Collection.Requests; using Febe.Core.Collection.Search; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Library; using Febe.Core.Security; @@ -182,6 +183,7 @@ public sealed class FebeApp : IAsyncDisposable // The same services as a normal start, on the empty temporary database, so that every endpoint can be built; // the configuration gate answers 503 before any of them runs. + var longWork = new LongWorkGate(); Import = new ImportService(new ImportEnvironment { Storage = Database, @@ -190,9 +192,12 @@ public sealed class FebeApp : IAsyncDisposable Clock = Clock, Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")), DataFolder = data.Root, + Gate = longWork, }); await StartWebAsync(hooks, services => { + services.AddSingleton(longWork); + services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false)); services.AddSingleton(Database); services.AddSingleton(library); services.AddSingleton(Clock); @@ -217,7 +222,15 @@ public sealed class FebeApp : IAsyncDisposable var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false); var libraryRoot = o.LibraryFolderFromSettings ? settings.LibraryRoot : o.LibraryFolder; var importRoot = o.ImportFolder is { } import ? Path.GetFullPath(import) : null; - Log.Info("avvio", $"Febe {typeof(FebeApp).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(libraryRoot)}{(importRoot is null ? string.Empty : ", importazioni da " + importRoot)}, fuso {o.ZoneId}, lingua {o.Language}."); + var exportRoot = hooks.ExportMounts is { } mounts ? o.ExportRoot with { Mounts = mounts } : o.ExportRoot; + var exportState = ExportRoots.Evaluate(exportRoot); + Log.Info("avvio", $"Febe {typeof(FebeApp).Assembly.GetName().Version?.ToString(3)}: dati in {data.Root}, libreria in {Path.GetFullPath(libraryRoot)}{(importRoot is null ? string.Empty : ", importazioni da " + importRoot)}{ExportLogText(exportRoot, exportState)}, fuso {o.ZoneId}, lingua {o.Language}."); + if (exportRoot is { Root: not null, Declared: true } && !exportState.Active) + { + // Not a configuration problem: the engine starts, the copies stay off until the folder is mounted. + Log.Warn("avvio", exportState.Problem ?? ExportRoots.NotDeclaredText); + } + if (o.TestSite is not null) { Log.Warn("avvio", $"Modalità di sviluppo: il browser lavora sul sito di prova {o.TestSite.Authority}, non su Instagram."); @@ -236,6 +249,9 @@ public sealed class FebeApp : IAsyncDisposable var library = new FebeLibrary(Database, data, layout, Clock, hashes); var staging = Path.Combine(data.Root, "temporanei"); + // One gate for import, copies to external folders and rebuild: they never run together (spec §4.10). + var longWork = new LongWorkGate(); + // Import (spec §9). Docker: sources under /importa, read-only, over the fixed library; what was running when // Febe stopped becomes «interrotto». Windows: the web layer's ImportHub builds the service over the library // and builds it again when the library folder changes in Impostazioni (any source folder, native picker). @@ -255,6 +271,7 @@ public sealed class FebeApp : IAsyncDisposable SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), DataFolder = data.Root, + Gate = longWork, }); LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false)); } @@ -321,6 +338,10 @@ public sealed class FebeApp : IAsyncDisposable await StartWebAsync(hooks, s => { + s.AddSingleton(longWork); + s.AddSingleton(exportRoot); + s.AddSingleton(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts)); + s.AddSingleton(new RuntimeSessionState(services.Runtime)); s.AddSingleton(Database); s.AddSingleton(library); s.AddSingleton(Clock); @@ -350,6 +371,11 @@ public sealed class FebeApp : IAsyncDisposable await Web.Services.GetRequiredService().GetAsync(ct).ConfigureAwait(false); } + // Copies to external folders (spec §4.10): built now, so that a copy interrupted by the last stop is marked at once. + var exports = Web.Services.GetRequiredService(); + await exports.GetAsync(ct).ConfigureAwait(false); + LogRecoveredExports(exports.Recovered); + // Alerts (spec §13.3): from the engine's timeline and the free space of the two folders, to the shell's // notifications (the desktop's; in Docker the shell cannot notify and the channel stays silent) and Telegram. // The strip of the interface is the engine snapshot's. The library folder is read at every check: on Windows @@ -839,6 +865,25 @@ public sealed class FebeApp : IAsyncDisposable } } + private void LogRecoveredExports(int recovered) + { + if (recovered > 0) + { + Log.Info("esportazione", recovered == 1 + ? "Una copia interrotta dall'arresto precedente: si riprende dalla Dashboard, scheda Esportazione." + : $"{recovered.ToString(CultureInfo.InvariantCulture)} copie interrotte dall'arresto precedente: si riprendono dalla Dashboard, scheda Esportazione."); + } + } + + /// The part of the start-up line about the copies to external folders (Docker only). + private static string ExportLogText(ExportRootOptions root, ExportRootState state) => root.Root switch + { + null => string.Empty, + var folder when state.Active => ", copie esterne in " + folder, + var folder when !root.Declared => $", copie esterne spente ({folder} non dichiarata)", + var folder => $", copie esterne spente ({folder} non montata)", + }; + private void LogRecovered(int recovered) { if (recovered > 0) diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs index 0187a55..955bc86 100644 --- a/src/Febe.App/IFebePlatform.cs +++ b/src/Febe.App/IFebePlatform.cs @@ -1,6 +1,7 @@ using Febe.Browser.Recipes; using Febe.Core.Abstractions; using Febe.Core.Alerts; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Security; using Febe.Core.Storage; @@ -108,6 +109,12 @@ public sealed record FebeAppOptions /// Docker: the read-only root of the import sources (/importa). Null: any folder, chosen with the picker. public string? ImportFolder { get; init; } + /// + /// Where the copies to external folders may go (spec §4.10, tappa E2). Docker: the subfolders of /esporta, and only + /// when declared (--esporta) and mounted. Windows: any folder, chosen with the picker. + /// + public ExportRootOptions ExportRoot { get; init; } = ExportRootOptions.AnyFolder; + /// Time zone of the engine, of file names and (Docker) of the browser. public string ZoneId { get; init; } = "Europe/Rome"; @@ -163,4 +170,10 @@ public sealed record FebeAppHooks /// Fake free-space probe for the «Disco quasi pieno» alert. public IFreeSpaceProbe? FreeSpace { get; init; } + + /// Fake mount table for /esporta (it replaces the one of ). + public IExportMounts? ExportMounts { get; init; } + + /// Fake free space and file size limit of the export folders. + public IExportDisk? ExportDisk { get; init; } } diff --git a/src/Febe.Core/Abstractions/LongWorkGate.cs b/src/Febe.Core/Abstractions/LongWorkGate.cs new file mode 100644 index 0000000..92dd75a --- /dev/null +++ b/src/Febe.Core/Abstractions/LongWorkGate.cs @@ -0,0 +1,106 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Febe.Core.Abstractions; + +/// The long pieces of work that never run together (spec §4.10: «esportazione, importazione e ricostruzione non girano insieme»). +public enum LongWorkKind +{ + /// An import job: analysis or copy (spec §9). + Import, + + /// A job of copies to external folders (spec §4.10). + Export, + + /// «Ricostruisci il database dalla libreria» (spec §8.5). + Rebuild, +} + +/// +/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole +/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing +/// it twice releases nothing more. +/// +public sealed class LongWorkGate +{ + private readonly Lock _lock = new(); + private Lease? _holder; + + /// Who holds the gate, or null when it is free. + public LongWorkKind? Busy + { + get + { + lock (_lock) + { + return _holder?.Kind; + } + } + } + + /// + /// Takes the gate for . False, with set, when another job (of any + /// kind, the same one included) holds it. + /// + public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith) + { + lock (_lock) + { + if (_holder is { } holder) + { + lease = null; + busyWith = holder.Kind; + return false; + } + + var taken = new Lease(this, kind); + _holder = taken; + lease = taken; + busyWith = null; + return true; + } + } + + /// The Italian answer when cannot start because is running. + public static string BusyMessage(LongWorkKind wanted, LongWorkKind busy) => (wanted, busy) switch + { + (LongWorkKind.Import, LongWorkKind.Import) => "C'è già un'importazione al lavoro: aspetta che finisca o interrompila.", + (LongWorkKind.Export, LongWorkKind.Export) => "C'è già una copia al lavoro: aspetta che finisca o interrompila.", + (LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.", + (_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.", + (_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.", + _ => "La ricostruzione del database è in corso: aspetta che finisca.", + }; + + private static string Verb(LongWorkKind kind) => kind switch + { + LongWorkKind.Import => "importa", + LongWorkKind.Export => "copia", + _ => "ricostruisci", + }; + + private void Release(Lease lease) + { + lock (_lock) + { + if (ReferenceEquals(_holder, lease)) + { + _holder = null; + } + } + } + + private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable + { + private int _disposed; + + public LongWorkKind Kind { get; } = kind; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + gate.Release(this); + } + } + } +} diff --git a/src/Febe.Core/Export/EngineSessionState.cs b/src/Febe.Core/Export/EngineSessionState.cs new file mode 100644 index 0000000..e99b3ed --- /dev/null +++ b/src/Febe.Core/Export/EngineSessionState.cs @@ -0,0 +1,29 @@ +using Febe.Core.Engine; + +namespace Febe.Core.Export; + +/// Whether the engine is in a session now: copies never run during one (spec §4.10, decision D11 of tappa E2). +public interface IEngineSessionState +{ + bool InSession { get; } +} + +/// No engine (tests, a start with problems): never in a session. +public sealed class NoEngineSession : IEngineSessionState +{ + public static readonly NoEngineSession Instance = new(); + + private NoEngineSession() + { + } + + public bool InSession => false; +} + +/// The session of the running engine. +public sealed class RuntimeSessionState(EngineRuntime runtime) : IEngineSessionState +{ + private readonly EngineRuntime _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); + + public bool InSession => _runtime.CurrentSession is not null; +} diff --git a/src/Febe.Core/Export/ExportAccounts.cs b/src/Febe.Core/Export/ExportAccounts.cs new file mode 100644 index 0000000..36776b8 --- /dev/null +++ b/src/Febe.Core/Export/ExportAccounts.cs @@ -0,0 +1,31 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Export; + +/// «Esporta questo account» (spec §4.10). +public static class ExportAccounts +{ + /// On when Alberto never chose: decision of Alberto, 27 November 2026 (D1 of tappa E2). + public const bool DefaultEnabled = true; + + /// The switch of an account from its stored choice (null: none recorded). + public static bool IsEnabled(bool? stored) => stored ?? DefaultEnabled; +} + +/// +/// The effective destination of an account (D2): its own folder in use, otherwise the general folder in use, otherwise +/// none; with the switch «Esporta questo account». +/// +public sealed record EffectiveDestination(long AccountId, ExportDestination? Destination, bool Enabled) +{ + /// The account's own folder. + public bool IsOwn => Destination?.Scope == ExportScope.Account; + + public bool HasDestination => Destination is not null; + + /// The switch is on and there is a destination: files of the account may be copied (D3). + public bool Exports => Enabled && Destination is not null; + + /// The account's files of this content type are copied (D3, D4). + public bool Wants(ContentTypes type) => Exports && (Destination!.ContentTypes & type) != ContentTypes.None; +} diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs new file mode 100644 index 0000000..0084b56 --- /dev/null +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -0,0 +1,755 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// One export job towards one destination (spec §4.10 «Come si copia»; decisions D11, D12, D16, D17 of tappa E2): +/// +/// before each group of files (at most files, or until +/// bytes are reached) the destination is checked with a probe file; a failed +/// check pauses the destination and the job, never the red strip; +/// each file is written to a .part in its final folder, hashed while writing, read back from the disk and +/// compared, compared with the library's SHA-256, then renamed to a free name: nothing is ever overwritten, and no +/// other file of the destination is deleted or moved; +/// a file already at the planned path with the same SHA-256 is adopted, not written again; +/// «Tolto» and «Superato» are never copied again by themselves, only with «Copia di nuovo»; +/// nothing is copied during an engine session: the job waits; +/// resumable: every file has its state, and the target path is recorded before its .part exists. +/// +/// +public sealed class ExportCopier(ExportEnvironment env) +{ + private const int PageSize = 500; + private const int MaxSiblings = 1000; + private const int MaxPath = WindowsFileNames.MaxPathLength; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// + /// Runs (or resumes) a job. A destination that does not answer pauses it (returns, does not throw). On cancellation + /// the job becomes «interrotto» and is thrown. + /// + /// No such job. + /// The job already ended. + public async Task CopyAsync(long runId, IProgress? progress = null, CancellationToken ct = default) + { + var store = _env.Storage.Exports; + var none = CancellationToken.None; + var run = await store.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + if (run.State is not (ExportRunState.Running or ExportRunState.Interrupted or ExportRunState.Paused)) + { + throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere."); + } + + var destination = await store.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false); + if (destination is null || destination.IsRetired) + { + run = run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now, LastError = ExportText.RetiredDestination }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false); + return run; + } + + run = run with { State = ExportRunState.Running, LastError = null }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + var x = new RunContext(run, destination, progress); + try + { + x.Report(_env, ExportPhase.Preparing, null); + await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + var layout = _env.Layout(); + var library = await LibrarySettings.LoadAsync(_env.Storage.Settings, layout.Root, ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + x.Naming = library.Naming; + x.SetFileTime = library.SetFileTimeToPublication; + x.OneOnly = settings.SamePost == SamePostCopies.OneOnly; + x.CopyAgain = await ExportRunSettings.GetCopyAgainAsync(_env.Storage.Settings, runId, ct).ConfigureAwait(false); + x.Effective = await new ExportDestinations(_env).ResolveAllAsync(ct).ConfigureAwait(false); + var summary = await store.GetRunSummaryAsync(runId, ct).ConfigureAwait(false); + x.FilesTotal = summary.Total; + x.FilesDone = summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending); + x.ByState = new Dictionary(summary.ByState); + x.BytesTotal = await PendingBytesAsync(runId, ct).ConfigureAwait(false); + + var groupFiles = 0; + long groupBytes = 0; + long after = 0; + while (true) + { + var page = await store.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + foreach (var item in page) + { + ct.ThrowIfCancellationRequested(); + if (groupFiles == 0 && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return await PauseAsync(x, problem).ConfigureAwait(false); + } + + await WaitOutsideSessionAsync(x, ct).ConfigureAwait(false); + var result = await ProcessItemAsync(x, item, ct).ConfigureAwait(false); + if (result.Pause is { } pause) + { + return await PauseAsync(x, pause).ConfigureAwait(false); + } + + x.FilesDone++; + x.BytesDone += result.Bytes; + x.ByState[ExportItemState.Pending] = Math.Max(0, x.ByState.GetValueOrDefault(ExportItemState.Pending) - 1); + x.ByState[result.State] = x.ByState.GetValueOrDefault(result.State) + 1; + groupFiles++; + groupBytes += result.Bytes; + if (groupFiles >= Math.Max(1, _env.GroupFiles) || groupBytes >= _env.GroupBytes) + { + groupFiles = 0; + groupBytes = 0; + } + + x.Report(_env, ExportPhase.Copying, result.Path); + } + } + + var final = await store.GetRunSummaryAsync(runId, none).ConfigureAwait(false); + run = run with { State = ExportRunState.Completed, CompletedAt = _env.Clock.Now, LastError = null }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + await _env.Storage.Events.AppendAsync( + new EventRecord + { + At = _env.Clock.Now, + Code = "esportazione-completata", + Message = ExportText.CompletionMessage(final, x.Destination), + Severity = final.ByState.GetValueOrDefault(ExportItemState.Failed) > 0 ? EventSeverity.Warning : EventSeverity.Success, + AccountId = x.Destination.AccountId, + }, + none).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, none).ConfigureAwait(false); + x.ByState = new Dictionary(final.ByState); + x.Report(_env, ExportPhase.Finished, null); + return run; + } + catch (Exception ex) + { + var cancelled = ex is OperationCanceledException && ct.IsCancellationRequested; + run = run with { State = ExportRunState.Interrupted, LastError = cancelled ? null : ExportText.ErrorText(ex) }; + await store.UpdateRunAsync(run, none).ConfigureAwait(false); + throw; + } + } + + /// + /// Checks a destination before a group of copies: the mount rule in Docker, then the folder check with its probe + /// file and the identity test (WP1.3). Returns why it cannot be written, or null; a success clears its pause. + /// + internal async Task CheckDestinationAsync(ExportDestination destination, CancellationToken ct) + { + if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mount) + { + return mount; + } + + var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false); + var verdict = await _env.CreateFolderCheck().CheckAsync(destination.RootPath, context, ct).ConfigureAwait(false); + return verdict.Problem switch + { + null => null, + { Kind: ExportFolderProblemKind.Missing or ExportFolderProblemKind.NotResponding } => + $"{ExportDestinations.Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati, poi riprendi.", + { } problem => problem.Message, + }; + } + + private async Task ProbeAsync(RunContext x, CancellationToken ct) + { + var problem = await CheckDestinationAsync(x.Destination, ct).ConfigureAwait(false); + if (problem is null && (x.Destination.PausedAt is not null || x.Destination.LastError is not null)) + { + x.Destination = await ExportPause.ClearAsync(_env, x.Destination).ConfigureAwait(false); + } + + return problem; + } + + private async Task PauseAsync(RunContext x, string message) + { + x.Destination = await ExportPause.PauseAsync(_env, x.Destination, message).ConfigureAwait(false); + var run = x.Run with { State = ExportRunState.Paused, LastError = message }; + await _env.Storage.Exports.UpdateRunAsync(run, CancellationToken.None).ConfigureAwait(false); + x.Report(_env, ExportPhase.Finished, null); + return run; + } + + private async Task WaitOutsideSessionAsync(RunContext x, CancellationToken ct) + { + while (_env.Session.InSession) + { + x.Report(_env, ExportPhase.WaitingForSession, null); + await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false); + } + } + + private async Task PendingBytesAsync(long runId, CancellationToken ct) + { + long total = 0; + long after = 0; + while (true) + { + var page = await _env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, State = ExportItemState.Pending, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + return total; + } + + after = page[^1].Id; + foreach (var item in page) + { + if (item.MediaId is { } id && await _env.Storage.Media.GetAsync(id, ct).ConfigureAwait(false) is { Bytes: { } bytes }) + { + total += bytes; + } + } + } + } + + private async Task ProcessItemAsync(RunContext x, ExportItem item, CancellationToken ct) + { + var storage = _env.Storage; + var exports = storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + var root = destination.RootPath; + + // a. No longer in the library. + if (item.AccountId is not { } accountId || await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is not { } account) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.AccountRemoved, LastError = null }, 0, null).ConfigureAwait(false); + } + + var media = item.MediaId is { } mediaId ? await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) : null; + var entry = media is null ? null : await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false); + var source = media is { Sha256.Length: 64, RelativePath: not null } && EntryStateRules.IsPresent(media.State) && entry?.AccountId == accountId + ? _env.ResolveSourcePath(account, media) + : null; + if (source is null || media is null || entry is null) + { + return await FinishAsync(item with { State = ExportItemState.Missing, Note = ExportText.Notes.SourceMissing, LastError = null }, 0, null).ConfigureAwait(false); + } + + // The account may have been switched off, or got another folder, or the destination stopped taking this type + // since the job was planned (decisions D2, D3 of tappa E2): «Esporta questo account» off skips every copy. + var (title, inHighlight) = await HighlightAsync(entry, ct).ConfigureAwait(false); + if (!x.Effective.TryGetValue(accountId, out var effective) || effective.Destination?.Id != destination.Id + || !effective.Wants(ExportPaths.TypeOf(entry.Kind, media.Kind, inHighlight))) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.NotExported, LastError = null }, media.Bytes ?? 0, null).ConfigureAwait(false); + } + + // b. The file may have changed since the job was planned. + var sha = media.Sha256!; + if (!string.Equals(item.SourceSha256, sha, StringComparison.Ordinal)) + { + item = item with { SourceSha256 = sha }; + } + + var bytes = media.Bytes ?? _env.FileSystem.FileLength(source) ?? 0; + var identity = new ExportCopyIdentity(destination.Id, accountId, sha, ExportVariant.Whole, ExportFormat.Original, null); + var file = new FileContext(account, entry, media, source, sha, bytes, identity, title, inHighlight); + + // c. Already copied, removed, superseded, copied for another account, or failed before. + var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); + ExportCopy? failed = null; + if (current is { State: ExportCopyState.Copied }) + { + if (current.RelativePath is { } copied && Exists(root, copied)) + { + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = copied, Note = null, LastError = null }, bytes, copied).ConfigureAwait(false); + } + + // The file is not there: «Tolto», unless the whole destination went away meanwhile. A root that was away + // for a moment and answers the probe again is asked once more for the file before it is called «Tolto». + if (!Directory.Exists(root)) + { + if (await ProbeAsync(x, ct).ConfigureAwait(false) is { } gone) + { + return ItemResult.Paused(gone); + } + + if (current.RelativePath is { } back && Exists(root, back)) + { + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = current.Id, RelativePath = back, Note = null, LastError = null }, bytes, back).ConfigureAwait(false); + } + } + + await exports.UpdateCopyAsync(current with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, none).ConfigureAwait(false); + if (!x.CopyAgain) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Removed, CopyId = current.Id, LastError = null }, bytes, current.RelativePath).ConfigureAwait(false); + } + } + else if (current is { State: ExportCopyState.Failed }) + { + failed = current; + } + else if (!x.CopyAgain) + { + var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false); + if (latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded }) + { + var note = latest.State == ExportCopyState.Removed ? ExportText.Notes.Removed : ExportText.Notes.Superseded; + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = note, CopyId = latest.Id, LastError = null }, bytes, latest.RelativePath).ConfigureAwait(false); + } + + if (await exports.FindReplacedCopyAsync(destination.Id, accountId, sha, ct).ConfigureAwait(false) is { } replaced) + { + return await FinishAsync(item with { State = ExportItemState.Skipped, Note = ExportText.Notes.Superseded, CopyId = replaced.Id, LastError = null }, bytes, replaced.RelativePath).ConfigureAwait(false); + } + } + + if (x.OneOnly + && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, accountId, ct).ConfigureAwait(false) is { RelativePath: { } elsewherePath } elsewhere + && await x.DestinationAsync(storage, elsewhere.DestinationId, ct).ConfigureAwait(false) is { IsRetired: false } where + && Exists(where.RootPath, elsewherePath)) + { + return await FinishAsync( + item with { State = ExportItemState.AlreadyCopied, Note = ExportText.Notes.CopiedForAnotherAccount, CopyId = elsewhere.Id, LastError = null }, + bytes, + null).ConfigureAwait(false); + } + + return await WriteAsync(x, item, file, failed, ct).ConfigureAwait(false); + } + + /// d. and e.: the path, the limits of the disk, adoption, the safe write and its record. + private async Task WriteAsync(RunContext x, ExportItem item, FileContext file, ExportCopy? failed, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var destination = x.Destination; + var root = destination.RootPath; + + string planned; + try + { + planned = ExportPaths.RelativePathFor( + destination, + ExportPaths.Segments(destination, x.Naming!, file.Account, file.Entry, file.Media, file.HighlightTitle, file.InHighlight, _env.Clock.LocalZone), + MaxPath); + } + catch (PathTooLongException ex) + { + return await FailAsync(item, file, failed, ex.Message, null).ConfigureAwait(false); + } + + if (_env.Disk.MaxFileBytes(root) is { } max && file.Bytes > max) + { + return await FailAsync(item, file, failed, ExportText.TooLarge(file.Bytes), ExportText.Notes.TooLargeForFileSystem).ConfigureAwait(false); + } + + if (_env.Disk.FreeBytes(root) is { } free && free < file.Bytes + ExportSpace.Margin) + { + return ItemResult.Paused(ExportText.NoSpace(destination, free, Path.GetFileName(planned), file.Bytes)); + } + + // Adoption by path: the planned file, and after a crash the name it was given («nome (2).jpg», …). + foreach (var candidate in AdoptionCandidates(root, planned, item.RelativePath)) + { + var full = LibraryLayout.FullPath(root, candidate); + if (_env.FileSystem.FileLength(full) != file.Bytes + || !string.Equals(await _env.FileSystem.ComputeSha256Async(full, ct).ConfigureAwait(false), file.Sha256, StringComparison.Ordinal)) + { + continue; + } + + var holder = await exports.FindCopyByPathAsync(destination.Id, candidate, ct).ConfigureAwait(false); + if (holder is null || (holder.AccountId is null && string.Equals(holder.SourceSha256, file.Sha256, StringComparison.Ordinal))) + { + return await RecordAsync(item, file, failed, holder, candidate, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + } + + if (holder.Identity == file.Identity) + { + if (holder.State == ExportCopyState.Superseded) + { + // Our own bytes, recorded as superseded (the file came back to the library without the change that + // would have revived the row): the copy is copied, not superseded, and must not stay stuck. + return await ReviveAsync(item, file, failed, holder, candidate).ConfigureAwait(false); + } + + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = candidate, Note = null, LastError = null }, file.Bytes, candidate).ConfigureAwait(false); + } + + // The same bytes, recorded for another copy: not ours to take. + } + + // The name the record can take: free on the disk and in the database. A path recorded for another copy whose + // file is gone is free again («Tolto»); one whose file is there under another letter case (a case-sensitive + // disk) is not, and the next numbered name is tried. + var chosen = await ChooseNameAsync(destination, planned, ct).ConfigureAwait(false); + + // The intent, in its own transaction, before the .part exists (WP1.8 cleans only the folders of items). + item = item with { RelativePath = planned }; + await exports.UpdateItemsAsync([item], none).ConfigureAwait(false); + + SavedFile saved; + try + { + var directory = planned.Contains('/', StringComparison.Ordinal) ? planned[..planned.LastIndexOf('/')] : string.Empty; + await using var content = _env.FileSystem.OpenRead(file.Source); + saved = (await new SafeFileWriter(MaxPath).SaveAsync( + content, + root, + directory, + (digest, _) => string.Equals(digest.Sha256, file.Sha256, StringComparison.Ordinal) + ? ValueTask.FromResult(chosen) + : throw new ContentChangedException("Il file della libreria non corrisponde a quello registrato."), + new SafeWriteOptions + { + RequireExistingRoot = true, + VerifyFromDisk = true, + LastWriteTime = x.SetFileTime ? file.Entry.PublishedAt : null, + }, + ct).ConfigureAwait(false))!; + } + catch (ContentChangedException ex) + { + return await FailAsync(item, file, failed, ex.Message, ExportText.Notes.SourceChanged).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + if (IsDiskFull(ex)) + { + return ItemResult.Paused(_env.Disk.FreeBytes(root) is { } left + ? ExportText.NoSpace(destination, left, Path.GetFileName(planned), file.Bytes) + : ExportText.DiskFull(destination)); + } + + if ((ex is ExportRootMissingException or DirectoryNotFoundException || !Directory.Exists(root)) && await ProbeAsync(x, ct).ConfigureAwait(false) is { } problem) + { + return ItemResult.Paused(problem); // the item stays pending + } + + return await FailAsync(item, file, failed, ExportText.ErrorText(ex), null).ConfigureAwait(false); + } + + var taken = string.Equals(saved.RelativePath, planned, StringComparison.Ordinal) ? null : ExportText.Notes.NameTaken; + + // The writer moved the file onto a name where no file was: a row still holding that path is stale (decision of + // 2026-11-27), also when the name is the one chosen, since a row could appear meanwhile. + await ReleaseStalePathAsync(destination, saved.RelativePath, justWritten: true, ct).ConfigureAwait(false); + return await RecordAsync(item, file, failed, null, saved.RelativePath, saved.Bytes, ExportCopyOrigin.Written, taken).ConfigureAwait(false); + } + + /// + /// The first of the planned path and its numbered names (numbered as the writer numbers them) that is free on the + /// disk and free, or stale, in the database; the planned path when none is found (the writer then decides). + /// + private async Task ChooseNameAsync(ExportDestination destination, string planned, CancellationToken ct) + { + for (var attempt = 1; attempt <= MaxSiblings; attempt++) + { + string name; + try + { + name = ExportPaths.NumberedName(destination.RootPath, planned, attempt, MaxPath); + } + catch (PathTooLongException) + { + break; + } + + if (Exists(destination.RootPath, name)) + { + continue; // the writer would not take it either + } + + if (await ReleaseStalePathAsync(destination, name, justWritten: false, ct).ConfigureAwait(false)) + { + return name; + } + } + + return planned; + } + + /// + /// A Copied or Superseded row on this path (matched without regard to case, as its unique index) whose file is not + /// there becomes «Tolto». The row's own stored path is the one tested: on a case-sensitive disk another letter case + /// is another file. With this job has just written the file at exactly + /// , where no file was, so a row with exactly that path is stale without a look. Returns + /// whether the path is free in the database now. + /// + private async Task ReleaseStalePathAsync(ExportDestination destination, string path, bool justWritten, CancellationToken ct) + { + var held = await _env.Storage.Exports.FindCopyByPathAsync(destination.Id, path, ct).ConfigureAwait(false); + if (held is null) + { + return true; + } + + var stale = held.RelativePath is not { } stored + || (justWritten && string.Equals(stored, path, StringComparison.Ordinal)) + || !Exists(destination.RootPath, stored); + if (!stale) + { + return false; + } + + await _env.Storage.Exports.UpdateCopyAsync(held with { State = ExportCopyState.Removed, StateChangedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + return true; + } + + /// + /// A Superseded row of this very identity whose bytes are at its path: it becomes the Copied row again. When the + /// identity has a current «Non riuscito» row, that one becomes the Copied row and the old one stays as history. + /// + private async Task ReviveAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy holder, string path) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var now = _env.Clock.Now; + if (failed is null && await exports.FindCurrentCopyAsync(file.Identity, none).ConfigureAwait(false) is null) + { + await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Copied, SupersededBySha256 = null, MediaId = file.Media.Id, StateChangedAt = now }, none).ConfigureAwait(false); + return await FinishAsync(item with { State = ExportItemState.AlreadyCopied, CopyId = holder.Id, RelativePath = path, Note = null, LastError = null }, file.Bytes, path).ConfigureAwait(false); + } + + await exports.UpdateCopyAsync(holder with { State = ExportCopyState.Removed, StateChangedAt = now }, none).ConfigureAwait(false); + return await RecordAsync(item, file, failed, null, path, file.Bytes, ExportCopyOrigin.Adopted, null).ConfigureAwait(false); + } + + /// Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names. + private IEnumerable AdoptionCandidates(string root, string planned, string? previous) + { + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + if (seen.Add(planned) && Exists(root, planned)) + { + yield return planned; + } + + if (previous is null) + { + yield break; + } + + for (var attempt = 1; attempt <= MaxSiblings; attempt++) + { + string name; + try + { + name = ExportPaths.NumberedName(root, previous, attempt, MaxPath); + } + catch (PathTooLongException) + { + yield break; + } + + if (!Exists(root, name)) + { + yield break; // the writer takes the first free name: nothing of ours after it + } + + if (seen.Add(name)) + { + yield return name; + } + } + } + + private async Task RecordAsync(ExportItem item, FileContext file, ExportCopy? failed, ExportCopy? orphan, string path, long bytes, ExportCopyOrigin origin, string? note) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + var now = _env.Clock.Now; + ExportCopy copy; + try + { + if (failed is not null) + { + copy = failed with + { + State = ExportCopyState.Copied, + Origin = origin, + RelativePath = path, + Bytes = bytes, + CopySha256 = file.Sha256, + CopiedAt = now, + StateChangedAt = now, + LastError = null, + MediaId = file.Media.Id, + }; + await exports.UpdateCopyAsync(copy, none).ConfigureAwait(false); + } + else if (orphan is not null) + { + copy = await exports.RelinkOrphanCopyAsync(orphan.Id, file.Identity.AccountId, file.Media.Id, now, none).ConfigureAwait(false); + } + else + { + copy = await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = file.Identity.DestinationId, + AccountId = file.Identity.AccountId, + MediaId = file.Media.Id, + SourceSha256 = file.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportCopyState.Copied, + Origin = origin, + RelativePath = path, + Bytes = bytes, + CopySha256 = file.Sha256, + CopiedAt = now, + }, + none).ConfigureAwait(false); + } + } + catch (DuplicateRecordException) + { + // Taken meanwhile by another record. The file written stays where it is: nothing is ever removed. + return await FinishAsync(item with { State = ExportItemState.Failed, Note = ExportText.Notes.PathTaken, LastError = ExportText.Note(ExportText.Notes.PathTaken) }, file.Bytes, path).ConfigureAwait(false); + } + + var state = origin == ExportCopyOrigin.Adopted ? ExportItemState.Adopted : ExportItemState.Copied; + return await FinishAsync(item with { State = state, CopyId = copy.Id, RelativePath = path, Note = note, LastError = null }, file.Bytes, path).ConfigureAwait(false); + } + + /// f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on. + private async Task FailAsync(ExportItem item, FileContext file, ExportCopy? failed, string error, string? note) + { + var exports = _env.Storage.Exports; + var none = CancellationToken.None; + long? copyId = failed?.Id; + try + { + if (failed is not null) + { + await exports.UpdateCopyAsync(failed with { LastError = error, StateChangedAt = _env.Clock.Now, MediaId = file.Media.Id }, none).ConfigureAwait(false); + } + else + { + copyId = (await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = file.Identity.DestinationId, + AccountId = file.Identity.AccountId, + MediaId = file.Media.Id, + SourceSha256 = file.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportCopyState.Failed, + CopiedAt = _env.Clock.Now, + LastError = error, + }, + none).ConfigureAwait(false)).Id; + } + } + catch (DuplicateRecordException) + { + // The identity got a current row meanwhile: that one tells the state. + } + + return await FinishAsync(item with { State = ExportItemState.Failed, Note = note, LastError = error, CopyId = copyId }, file.Bytes, item.RelativePath).ConfigureAwait(false); + } + + private async Task FinishAsync(ExportItem item, long bytes, string? path) + { + await _env.Storage.Exports.UpdateItemsAsync([item], CancellationToken.None).ConfigureAwait(false); + return new ItemResult(item.State, bytes, path, null); + } + + private async Task<(string? Title, bool InHighlight)> HighlightAsync(Entry entry, CancellationToken ct) + { + if (entry.Kind is not (EntryKind.Story or EntryKind.Highlight)) + { + return (null, false); + } + + var collections = await _env.Storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false); + return (collections.FirstOrDefault()?.Title, collections.Count > 0); + } + + private bool Exists(string root, string relativePath) + { + try + { + return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath)); + } + catch (ArgumentException) + { + return false; + } + } + + /// «Disco pieno»: ERROR_DISK_FULL or ERROR_HANDLE_DISK_FULL on Windows, ENOSPC elsewhere. + internal static bool IsDiskFull(Exception ex) => + ex is IOException io + && (io.HResult is unchecked((int)0x80070070) or unchecked((int)0x80070027) or 28 + || io.Message.Contains("No space left on device", StringComparison.OrdinalIgnoreCase)); + + private sealed record FileContext(Account Account, Entry Entry, Media Media, string Source, string Sha256, long Bytes, ExportCopyIdentity Identity, string? HighlightTitle, bool InHighlight); + + /// What happened to an item; stops the job with the destination paused. + private sealed record ItemResult(ExportItemState State, long Bytes, string? Path, string? Pause) + { + public static ItemResult Paused(string message) => new(ExportItemState.Pending, 0, null, message); + } + + private sealed class RunContext(ExportRun run, ExportDestination destination, IProgress? progress) + { + private readonly Dictionary _destinations = []; + + public ExportRun Run { get; } = run; + + public ExportDestination Destination { get; set; } = destination; + + public LibraryNaming? Naming { get; set; } + + public bool SetFileTime { get; set; } = true; + + public bool OneOnly { get; set; } + + public bool CopyAgain { get; set; } + + public IReadOnlyDictionary Effective { get; set; } = new Dictionary(); + + public int FilesDone { get; set; } + + public int FilesTotal { get; set; } + + public long BytesDone { get; set; } + + public long BytesTotal { get; set; } + + public Dictionary ByState { get; set; } = []; + + public async Task DestinationAsync(IFebeStorage storage, long id, CancellationToken ct) + { + if (!_destinations.TryGetValue(id, out var row)) + { + _destinations[id] = row = await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false); + } + + return row; + } + + public void Report(ExportEnvironment env, ExportPhase phase, string? current) => + progress?.Report(new ExportProgress( + Run.Id, + phase, + FilesDone, + FilesTotal, + BytesDone, + Math.Max(BytesTotal, BytesDone), + current, + ExportDestinations.Label(Destination), + new Dictionary(ByState), + env.Clock.Now)); + } +} diff --git a/src/Febe.Core/Export/ExportDestinations.cs b/src/Febe.Core/Export/ExportDestinations.cs new file mode 100644 index 0000000..52a8131 --- /dev/null +++ b/src/Febe.Core/Export/ExportDestinations.cs @@ -0,0 +1,402 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// What Alberto sets for a destination (Impostazioni → Esportazione, scheda account → «Copie esterne»). +/// General folder or own folder of an account. +/// The account of an own folder; null for the general folder. +/// The folder as chosen (Docker: relative to /esporta, or a full path inside it). +/// Name shown; null: the last segment of the folder. +/// At least one type. +/// General scheme; null: «Come la libreria». +/// Scheme of highlight collections; null: «Come la libreria». +/// Scheme of profile pictures; null: «Come la libreria». +/// «Automatica»: stored only in tappa E2 (tappa E5 acts on it). +/// «Solo i nuovi» when «Automatica» is turned on. +public sealed record DestinationSpec( + ExportScope Scope, + long? AccountId, + string Path, + string? Label, + ContentTypes ContentTypes, + string? NamingScheme, + string? HighlightNamingScheme, + string? ProfileNamingScheme, + bool Automatic = false, + bool OnlyNew = true); + +/// A saved destination and the warnings of its naming schemes (shown, they do not block). +public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList Warnings); + +/// A destination in use that now overlaps a protected folder (WP1.10 of tappa E2). +public sealed record ExportFolderConflict(ExportDestination Destination, ExportFolderProblem Problem); + +/// What Impostazioni and the Dashboard show of a destination. +/// The stored row (paused or not). +/// The folder answered now (and, in Docker, sits on a usable mount). +/// Why it is not reachable, or the error of its pause; null when fine. +/// Copies per state, every state present. +/// Free space when reachable and measurable. +public sealed record ExportDestinationStatus( + ExportDestination Destination, + bool Reachable, + string? Problem, + IReadOnlyDictionary Counts, + long? FreeBytes); + +/// +/// Destinations and the switch «Esporta questo account» (spec §4.10 «Destinazioni»), for the API. No file is touched +/// here except through (its probe, only in the candidate folder). +/// +public sealed class ExportDestinations(ExportEnvironment env) +{ + /// The answer to «Togli la cartella». + public const string RetiredText = "Cartella tolta. I file già copiati restano dove sono."; + + /// A destination with an unfinished job cannot be retired nor moved. + public const string UnfinishedRunText = "C'è un lavoro di copia non finito verso questa cartella: finiscilo o annullalo, poi cambia cartella."; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// The name shown for a destination: its label, or the last segment of its folder. + public static string Label(ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(destination); + if (!string.IsNullOrWhiteSpace(destination.Label)) + { + return destination.Label.Trim(); + } + + var trimmed = ExportPaths.Trim(destination.RootPath); + var name = System.IO.Path.GetFileName(trimmed); + return string.IsNullOrEmpty(name) ? trimmed : name; + } + + /// The effective destination of an account (D2) with its switch (D1). + public async Task ResolveAsync(long accountId, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var own = await exports.GetAccountDestinationAsync(accountId, ct).ConfigureAwait(false); + var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false); + var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(accountId, ct).ConfigureAwait(false)); + return new EffectiveDestination(accountId, destination, enabled); + } + + /// The effective destination of every account, with one read of each table. + public async Task> ResolveAllAsync(CancellationToken ct) + { + var accounts = await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false); + var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + var switches = await _env.Storage.Exports.ListAccountExportSwitchesAsync(ct).ConfigureAwait(false); + var general = destinations.FirstOrDefault(d => d.Scope == ExportScope.General); + var own = destinations.Where(d => d.Scope == ExportScope.Account && d.AccountId is not null).ToDictionary(d => d.AccountId!.Value); + return accounts.ToDictionary( + a => a.Id, + a => new EffectiveDestination( + a.Id, + own.GetValueOrDefault(a.Id) ?? general, + ExportAccounts.IsEnabled(switches.TryGetValue(a.Id, out var on) ? on : null))); + } + + /// + /// Adds a destination after checking folder (WP1.3), content types and naming schemes. + /// + /// The folder cannot be a destination. + /// Types, schemes, scope or account are not valid (Italian message). + public async Task CreateAsync(DestinationSpec spec, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(spec); + var account = await CheckScopeAsync(spec, ct).ConfigureAwait(false); + var warnings = ValidateSettings(spec); + if (spec.Scope == ExportScope.General && await _env.Storage.Exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false) is not null) + { + throw new ArgumentException("C'è già una cartella generale: cambiala invece di aggiungerne un'altra.", nameof(spec)); + } + + if (account is not null && await _env.Storage.Exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false) is not null) + { + throw new ArgumentException(OwnFolderInUse(account), nameof(spec)); + } + + var full = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false); + var now = _env.Clock.Now; + var row = Build(spec, full, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null }; + try + { + return new DestinationSaveResult(await _env.Storage.Exports.AddDestinationAsync(row, ct).ConfigureAwait(false), warnings); + } + catch (DuplicateRecordException) + { + throw new ArgumentException( + account is null ? "C'è già una cartella generale: cambiala invece di aggiungerne un'altra." : OwnFolderInUse(account), + nameof(spec)); + } + } + + /// + /// Changes a destination. The same folder updates the row; another folder retires it and adds a new row (the copies + /// stay with the retired one), refused while an unfinished job writes to it. + /// + /// No such destination. + /// The new folder cannot be a destination. + /// Types, schemes, scope or account are not valid. + /// An unfinished job uses the old folder. + public async Task UpdateAsync(long id, DestinationSpec spec, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(spec); + var exports = _env.Storage.Exports; + var stored = await exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata."); + if (stored.IsRetired) + { + throw new ArgumentException("Questa cartella è stata tolta: non si modifica più.", nameof(id)); + } + + if (stored.Scope != spec.Scope || stored.AccountId != spec.AccountId) + { + throw new ArgumentException("Una cartella generale resta generale, e la cartella di un account resta di quell'account.", nameof(spec)); + } + + var warnings = ValidateSettings(spec); + var now = _env.Clock.Now; + string? full = null; + try + { + full = ExportRoots.Resolve(_env.Root, spec.Path); + } + catch (ExportFolderException) + { + // Not the same folder: the full check below gives the reason. + } + + if (full is not null && ExportPaths.Same(full, stored.RootPath)) + { + var since = !spec.Automatic ? null + : stored.Automatic ? stored.AutomaticSince + : spec.OnlyNew ? now : (DateTimeOffset?)null; + var updated = Build(spec, stored.RootPath, stored.CreatedAt) with + { + Id = stored.Id, + AutomaticSince = since, + PausedAt = stored.PausedAt, + LastError = stored.LastError, + }; + await exports.UpdateDestinationAsync(updated, ct).ConfigureAwait(false); + return new DestinationSaveResult(updated, warnings); + } + + if (stored.IsOrphan) + { + throw new ArgumentException("La cartella di un account rimosso non si cambia: toglila, oppure ridalla all'account quando torna.", nameof(spec)); + } + + await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false); + var newFolder = await CheckedFolderAsync(spec.Path, ct).ConfigureAwait(false); + + // Two transactions, as the store wants: the old folder is retired with its copies, then the new one is added. + await exports.RetireDestinationAsync(id, now, CancellationToken.None).ConfigureAwait(false); + var row = Build(spec, newFolder, now) with { AutomaticSince = spec.Automatic && spec.OnlyNew ? now : null }; + return new DestinationSaveResult(await exports.AddDestinationAsync(row, CancellationToken.None).ConfigureAwait(false), warnings); + } + + /// «Togli la cartella»: only the configuration goes; copies and files stay (). + /// No such destination. + /// An unfinished job uses it. + public async Task RetireAsync(long id, CancellationToken ct) + { + var stored = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata."); + if (stored.IsRetired) + { + return; + } + + await EnsureNoUnfinishedRunAsync(id, ct).ConfigureAwait(false); + await _env.Storage.Exports.RetireDestinationAsync(id, _env.Clock.Now, ct).ConfigureAwait(false); + } + + /// «Esporta questo account». + /// No such account. + public async Task SetAccountEnabledAsync(long accountId, bool enabled, CancellationToken ct) + { + _ = await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Account {accountId} non trovato."); + await _env.Storage.Exports.SetAccountExportEnabledAsync(accountId, enabled, ct).ConfigureAwait(false); + } + + /// Checks a folder for the dialog, before saving (WP1.3). + public async Task CheckFolderAsync(string candidate, CancellationToken ct) + { + var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false); + return await _env.CreateFolderCheck().CheckAsync(candidate, context, ct).ConfigureAwait(false); + } + + /// + /// Checks again every destination in use against the protected folders, with + /// (an account folder about to be saved). Only overlaps are conflicts: an unreachable folder is checked anyway at the + /// start of its next group of copies. + /// + public Task> RecheckAsync(IReadOnlyList? extraAccountFolders, CancellationToken ct) => + RecheckAgainstAsync(extraAccountFolders?.Select(f => new ProtectedFolder(f, ProtectedFolderKind.Account, null)).ToList(), ct); + + /// As , with folders of any kind (a new library root is ). + public async Task> RecheckAgainstAsync(IReadOnlyList? extra, CancellationToken ct) + { + var destinations = await _env.Storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + if (destinations.Count == 0) + { + return []; + } + + var context = await _env.FolderContextAsync(extra, ct).ConfigureAwait(false); + var check = _env.CreateFolderCheck(); + var verdicts = await Task.WhenAll(destinations.Select(async d => (Destination: d, Verdict: await check.CheckAsync(d.RootPath, context, ct).ConfigureAwait(false)))) + .ConfigureAwait(false); + return verdicts + .Where(v => v.Verdict.Problem is { IsOverlap: true }) + .Select(v => new ExportFolderConflict(v.Destination, v.Verdict.Problem!)) + .ToList(); + } + + /// + /// After a rebuild of the database (WP1.10 of tappa E2): every destination in use that now overlaps a protected + /// folder is paused with the reason. Nothing is interactive there. Returns the conflicts. + /// + public async Task> RecheckAndPauseAsync(CancellationToken ct) + { + var conflicts = await RecheckAsync(null, ct).ConfigureAwait(false); + foreach (var conflict in conflicts) + { + await ExportPause.PauseAsync(_env, conflict.Destination, conflict.Problem.Message).ConfigureAwait(false); + } + + return conflicts; + } + + /// Whether a destination answers now, its pause, its copies and its free space. + /// No such destination. + public async Task StatusAsync(long id, CancellationToken ct) + { + var destination = await _env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Destinazione di esportazione {id} non trovata."); + var counts = await _env.Storage.Exports.CountCopiesAsync(id, ct).ConfigureAwait(false); + if (destination.IsRetired) + { + return new ExportDestinationStatus(destination, false, "Questa cartella è stata tolta.", counts, null); + } + + if (ExportRoots.MountProblem(_env.Root, destination.RootPath) is { } mountProblem) + { + return new ExportDestinationStatus(destination, false, mountProblem, counts, null); + } + + bool reachable; + try + { + reachable = await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + reachable = false; + } + + if (!reachable) + { + return new ExportDestinationStatus( + destination, + false, + $"{Label(destination)} non è raggiungibile: controlla che il disco o la condivisione siano collegati.", + counts, + null); + } + + long? free; + try + { + free = await Task.Run(() => _env.Disk.FreeBytes(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + free = null; + } + + return new ExportDestinationStatus(destination, true, destination.PausedAt is not null ? destination.LastError : null, counts, free); + } + + private async Task CheckScopeAsync(DestinationSpec spec, CancellationToken ct) + { + if (spec.Scope == ExportScope.General) + { + return spec.AccountId is null + ? null + : throw new ArgumentException("La cartella generale non è di un account.", nameof(spec)); + } + + if (spec.AccountId is not { } accountId) + { + throw new ArgumentException("Scegli l'account di questa cartella.", nameof(spec)); + } + + return await _env.Storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) + ?? throw new ArgumentException("Questo account non c'è più.", nameof(spec)); + } + + /// Content types and naming schemes; returns the warnings of the schemes. + private static List ValidateSettings(DestinationSpec spec) + { + if (spec.ContentTypes == ContentTypes.None || (spec.ContentTypes & ~ContentTypes.All) != ContentTypes.None) + { + throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec)); + } + + var errors = new List(); + var warnings = new List(); + void Check(string? text, NamingSchemeUse use) + { + if (Clean(text) is not { } scheme) + { + return; + } + + var validation = NamingScheme.Validate(scheme, use); + errors.AddRange(validation.Errors.Select(e => NamingPreview.Prefix(use) + e)); + warnings.AddRange(validation.Warnings.Select(w => NamingPreview.Prefix(use) + w)); + } + + Check(spec.NamingScheme, NamingSchemeUse.General); + Check(spec.HighlightNamingScheme, NamingSchemeUse.Highlight); + Check(spec.ProfileNamingScheme, NamingSchemeUse.ProfilePicture); + return errors.Count > 0 ? throw new ArgumentException(string.Join(" ", errors), nameof(spec)) : warnings; + } + + private async Task CheckedFolderAsync(string path, CancellationToken ct) + { + var verdict = await CheckFolderAsync(path, ct).ConfigureAwait(false); + return verdict.Problem is { } problem ? throw new ExportFolderException(problem.Message, problem.Kind) : verdict.FullPath; + } + + private async Task EnsureNoUnfinishedRunAsync(long destinationId, CancellationToken ct) + { + var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); + if (unfinished.Any(r => r.DestinationId == destinationId)) + { + throw new InvalidOperationException(UnfinishedRunText); + } + } + + private static ExportDestination Build(DestinationSpec spec, string root, DateTimeOffset createdAt) => new() + { + Scope = spec.Scope, + AccountId = spec.AccountId, + Label = Clean(spec.Label), + RootPath = root, + ContentTypes = spec.ContentTypes, + NamingScheme = Clean(spec.NamingScheme), + HighlightNamingScheme = Clean(spec.HighlightNamingScheme), + ProfileNamingScheme = Clean(spec.ProfileNamingScheme), + Automatic = spec.Automatic, + CreatedAt = createdAt, + }; + + private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + + private static string OwnFolderInUse(Account account) => $"@{account.Username} ha già una cartella sua: cambiala invece di aggiungerne un'altra."; +} diff --git a/src/Febe.Core/Export/ExportDisk.cs b/src/Febe.Core/Export/ExportDisk.cs new file mode 100644 index 0000000..7a1e948 --- /dev/null +++ b/src/Febe.Core/Export/ExportDisk.cs @@ -0,0 +1,82 @@ +using Febe.Core.Alerts; + +namespace Febe.Core.Export; + +/// Free space and the largest file a destination's disk accepts (a seam: tests give their own). +public interface IExportDisk +{ + /// Bytes free for Febe on the disk of ; null when it cannot be measured. + long? FreeBytes(string root); + + /// The largest file the file system accepts (FAT32: 4 GB − 1); null when there is no known limit. + long? MaxFileBytes(string root); +} + +/// Limits of the space check before each copy (spec §4.10 «Spazio»). +public static class ExportSpace +{ + /// The margin left free after the next file (decision of Alberto, question Q6 of tappa E2): 64 MiB. + public const long Margin = 64L * 1024 * 1024; + + /// The largest file on FAT32: 4 GiB − 1 byte. + public const long Fat32Limit = (4L * 1024 * 1024 * 1024) - 1; + + private static readonly HashSet FatTypes = new(StringComparer.OrdinalIgnoreCase) { "FAT32", "FAT", "vfat", "msdos", "fat" }; + + /// True for the names Windows (DriveFormat) and Linux (mount type) give to FAT file systems. + public static bool IsFat(string? fileSystem) => fileSystem is not null && FatTypes.Contains(fileSystem); +} + +/// +/// The real disks: free space through (a UNC share gives null: the Windows edition +/// registers its own measure), the FAT32 limit from the drive format on Windows and from the mount type on Linux. +/// +public sealed class SystemExportDisk(IExportMounts mounts) : IExportDisk +{ + private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts)); + + public long? FreeBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + return new DriveFreeSpaceProbe().Measure(root)?.AvailableBytes; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return null; + } + } + + public long? MaxFileBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + string? type; + if (OperatingSystem.IsWindows()) + { + var drive = Path.GetPathRoot(Path.GetFullPath(root)); + type = string.IsNullOrEmpty(drive) || drive.StartsWith(@"\\", StringComparison.Ordinal) ? null : new DriveInfo(drive).DriveFormat; + } + else + { + type = _mounts.FindContaining(Path.GetFullPath(root))?.FileSystemType; + } + + return ExportSpace.IsFat(type) ? ExportSpace.Fat32Limit : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException or System.Security.SecurityException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Export/ExportEnvironment.cs b/src/Febe.Core/Export/ExportEnvironment.cs new file mode 100644 index 0000000..ad90087 --- /dev/null +++ b/src/Febe.Core/Export/ExportEnvironment.cs @@ -0,0 +1,147 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// What the export needs from the rest of Febe (spec §4.10). Built once by the composition (the web layer's export +/// hub); the layout is a function because on Windows the library folder can change while Febe runs. +/// +public sealed record ExportEnvironment +{ + public required IFebeStorage Storage { get; init; } + + /// The library folder and account folders now. + public required Func Layout { get; init; } + + /// The Data folder: a destination may not overlap it. + public required string DataFolder { get; init; } + + public required IClock Clock { get; init; } + + /// Docker /importa: a destination may not overlap it. Null on Windows. + public string? ImportRoot { get; init; } + + /// Where destinations may be chosen (Docker: /esporta). + public ExportRootOptions Root { get; init; } = ExportRootOptions.AnyFolder; + + /// + /// The full path of a library file present on disk, or null. Null: the library layout (as the web layer's + /// LibraryFileResolver). Use . + /// + public Func? ResolveSource { get; init; } + + /// Reading and hashing files (library files and files found in a destination). + public IExportFileSystem FileSystem { get; init; } = ExportFileSystem.Instance; + + /// Free space and the FAT32 limit of a destination. + public IExportDisk Disk { get; init; } = new SystemExportDisk(new ProcMountInfo()); + + /// Copies never run during an engine session. + public IEngineSessionState Session { get; init; } = NoEngineSession.Instance; + + /// Shared with import and rebuild: never together (spec §4.10). Null: nothing else to keep out (tests). + public LongWorkGate? Gate { get; init; } + + /// Time allowed to a check of a destination folder (a disconnected share must not block). + public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10); + + /// Writes the probe file of a folder check (a seam: tests make it fail or hang); null: the real file. + public Action? WriteProbe { get; init; } + + /// How often a waiting job looks whether the engine session ended. + public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5); + + /// A group of copies, checked with a probe before it starts: at most this many files… + public int GroupFiles { get; init; } = 100; + + /// …or this many planned bytes, whichever comes first. + public long GroupBytes { get; init; } = 1L << 30; + + /// The checker of destination folders of this environment. + public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe); + + /// The protected folders now (Data, library, account folders, /importa) and the extra ones. + public Task FolderContextAsync(IReadOnlyList? extra, CancellationToken ct) => + ExportFolderCheck.ContextAsync(Storage, Layout(), DataFolder, ImportRoot, Root, extra, ct); + + /// The full path of a library file present on disk, or null ( or the layout). + public string? ResolveSourcePath(Account account, Media media) + { + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(media); + if (ResolveSource is { } resolve) + { + return resolve(account, media); + } + + if (media.RelativePath is null || !EntryStateRules.IsPresent(media.State)) + { + return null; + } + + try + { + var path = Layout().FullPath(account, media.RelativePath); + return FileSystem.FileExists(path) ? path : null; + } + catch (ArgumentException) + { + return null; + } + } +} + +/// File operations of the export (a seam, like IImportFileSystem). +public interface IExportFileSystem +{ + /// Opens a file for reading only. + Stream OpenRead(string path); + + /// SHA-256 (lowercase hex) of a file as it is on disk now. + Task ComputeSha256Async(string path, CancellationToken ct); + + bool FileExists(string path); + + /// Size of a file, or null when it is not there. + long? FileLength(string path); +} + +/// The real file system. +public sealed class ExportFileSystem : IExportFileSystem +{ + private const int BufferSize = 128 * 1024; + + private ExportFileSystem() + { + } + + public static ExportFileSystem Instance { get; } = new(); + + public Stream OpenRead(string path) => + new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + + public async Task ComputeSha256Async(string path, CancellationToken ct) + { + await using var stream = OpenRead(path); + return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } + + public bool FileExists(string path) => File.Exists(path); + + public long? FileLength(string path) + { + try + { + var info = new FileInfo(path); + return info.Exists ? info.Length : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Export/ExportFolderCheck.cs b/src/Febe.Core/Export/ExportFolderCheck.cs new file mode 100644 index 0000000..04a6433 --- /dev/null +++ b/src/Febe.Core/Export/ExportFolderCheck.cs @@ -0,0 +1,450 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// Why a folder cannot be a destination (spec §4.10 «Cartelle rifiutate»). +public enum ExportFolderProblemKind +{ + Empty, + NotFullyQualified, + OutsideExportRoot, + ExportRootItself, + ParentSegment, + NotMounted, + ReadOnlyMount, + Missing, + NotAFolder, + Link, + RootOfDisk, + PathTooLong, + InsideProtected, + ContainsProtected, + SameAsProtected, + ProbeFailed, + NotResponding, +} + +/// A refused folder: the kind and the Italian message that says why and what to do. +public sealed record ExportFolderProblem(ExportFolderProblemKind Kind, string Message) +{ + /// The folder overlaps Data, Libreria, an account folder or /importa (the conflicts of a re-check). + public bool IsOverlap => Kind is ExportFolderProblemKind.InsideProtected or ExportFolderProblemKind.ContainsProtected or ExportFolderProblemKind.SameAsProtected; +} + +/// The outcome of a folder check. +/// The full path of the candidate (as typed when it could not be resolved). +/// Null when the folder is accepted. +public sealed record ExportFolderVerdict(string FullPath, ExportFolderProblem? Problem) +{ + public bool Accepted => Problem is null; +} + +/// What a protected folder is. +public enum ProtectedFolderKind +{ + /// The Data folder. + Data, + + /// The library folder. + Library, + + /// The folder of an account (inside the library or outside it). + Account, + + /// The root of the import sources (Docker /importa). + Import, +} + +/// A folder a destination may neither be, sit inside nor contain. +/// Full path. +/// What it is (for the message). +/// The account of an account folder, when known. +public sealed record ProtectedFolder(string Path, ProtectedFolderKind Kind, string? Username) +{ + /// «la cartella dei dati di Febe», «la cartella dell'account @x»… + public string Description => Kind switch + { + ProtectedFolderKind.Data => "la cartella dei dati di Febe", + ProtectedFolderKind.Library => "la cartella della libreria", + ProtectedFolderKind.Import => "la cartella delle importazioni", + _ => Username is { Length: > 0 } name ? $"la cartella dell'account @{name}" : "la cartella di un account", + }; +} + +/// The folders a candidate is checked against, and where destinations may be chosen. +public sealed record ExportFolderContext(IReadOnlyList Protected, ExportRootOptions Root); + +/// A folder or path that cannot be used as a destination; the message (Italian) says why. The API answers 400. +public sealed class ExportFolderException : IOException +{ + public ExportFolderException() + { + } + + public ExportFolderException(string message) + : base(message) + { + } + + public ExportFolderException(string message, Exception innerException) + : base(message, innerException) + { + } + + public ExportFolderException(string message, ExportFolderProblemKind kind) + : base(message) => Kind = kind; + + /// The kind of refusal, when known. + public ExportFolderProblemKind? Kind { get; } +} + +/// +/// Checks a candidate destination folder (spec §4.10, decision D13 of tappa E2): textual checks first, then the +/// identity test with a probe file written and removed only in the candidate, so that a drive letter and a UNC +/// path to the same place are recognised. In Data, Libreria, the account folders and /importa the probe is only +/// looked for, read-only. Everything that touches the disk runs in the background with a timeout (10 s by default): a +/// disconnected share never blocks the caller. +/// +/// The mount table (the root of a file system is refused). +/// Time allowed to the checks on disk; 10 s when null. +/// +/// Writes the probe file at the full path given (a seam: tests make it fail or hang); null writes «Febe» in a new file. +/// +public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null, Action? writeProbe = null) +{ + /// Prefix of the probe file (a temporary file of : .febe-prova-*.part). + public const string ProbePrefix = SafeFileWriter.TempPrefix + "prova-"; + + private readonly IExportMounts _mounts = mounts ?? throw new ArgumentNullException(nameof(mounts)); + private readonly TimeSpan _timeout = timeout ?? TimeSpan.FromSeconds(10); + private readonly Action _writeProbe = writeProbe ?? WriteProbeFile; + + /// A new probe file name: .febe-prova-<12 hex>.part. + public static string NewProbeName() => ProbePrefix + Guid.NewGuid().ToString("N")[..12] + SafeFileWriter.TempSuffix; + + /// + /// The protected folders: Data, the library, the folder of every account (outside the library too), the extra + /// folders (an account folder or a library root about to be saved) and the import root. + /// + public static async Task ContextAsync( + IFebeStorage storage, + LibraryLayout layout, + string dataFolder, + string? importRoot, + ExportRootOptions root, + IReadOnlyList? extra = null, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(layout); + ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder); + ArgumentNullException.ThrowIfNull(root); + var folders = new List + { + new(Full(dataFolder), ProtectedFolderKind.Data, null), + new(Full(layout.Root), ProtectedFolderKind.Library, null), + }; + foreach (var account in await storage.Accounts.ListAsync(ct).ConfigureAwait(false)) + { + string folder; + try + { + folder = Full(layout.AccountFolder(account)); + } + catch (ArgumentException) + { + continue; // an unusable stored folder protects nothing + } + + folders.Add(new ProtectedFolder(folder, ProtectedFolderKind.Account, account.Username)); + } + + foreach (var folder in extra ?? []) + { + folders.Add(folder with { Path = Full(folder.Path) }); + } + + if (importRoot is { Length: > 0 }) + { + folders.Add(new ProtectedFolder(Full(importRoot), ProtectedFolderKind.Import, null)); + } + + return new ExportFolderContext(folders, root); + } + + /// + /// Checks . Never throws for a refused folder (the verdict says why); only + /// cancels it. + /// + public async Task CheckAsync(string candidate, ExportFolderContext context, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(context); + if (string.IsNullOrWhiteSpace(candidate)) + { + return new ExportFolderVerdict(candidate ?? string.Empty, new ExportFolderProblem(ExportFolderProblemKind.Empty, "Scegli la cartella in cui copiare i file.")); + } + + string full; + try + { + full = ExportRoots.Resolve(context.Root, candidate); + } + catch (ExportFolderException ex) + { + return new ExportFolderVerdict(candidate, new ExportFolderProblem(ex.Kind ?? ExportFolderProblemKind.NotFullyQualified, ex.Message)); + } + + try + { + return await Task.Run(() => CheckOnDisk(full, context, ct), ct).WaitAsync(_timeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return new ExportFolderVerdict(full, new ExportFolderProblem( + ExportFolderProblemKind.NotResponding, + $"La cartella non risponde entro {_timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova.")); + } + } + + private ExportFolderVerdict CheckOnDisk(string full, ExportFolderContext context, CancellationToken ct) + { + var o = context.Root; + var shown = ExportRoots.DisplayPath(o, full); + ExportFolderVerdict Refuse(ExportFolderProblemKind kind, string message) => new(full, new ExportFolderProblem(kind, message)); + + if (ExportRoots.MountCheck(o, full) is { } mountProblem) + { + return new ExportFolderVerdict(full, mountProblem); + } + + if (File.Exists(full)) + { + return Refuse(ExportFolderProblemKind.NotAFolder, $"{shown} è un file: scegli una cartella."); + } + + if (!Directory.Exists(full)) + { + return Refuse( + ExportFolderProblemKind.Missing, + $"La cartella {shown} non esiste. Febe non crea mai la cartella di una destinazione: creala tu, o collega il disco, poi sceglila di nuovo."); + } + + if (o.Root is not null && new DirectoryInfo(full).LinkTarget is not null) + { + return Refuse(ExportFolderProblemKind.Link, "La cartella scelta è un collegamento: scegli la cartella a cui punta."); + } + + if (IsRootOfDisk(full)) + { + return Refuse( + ExportFolderProblemKind.RootOfDisk, + $"{shown} è la radice di un disco o di una condivisione: scegli una sua cartella, così i file di Febe non si mescolano al resto."); + } + + try + { + WindowsFileNames.FitPath(full, ["x"]); + } + catch (PathTooLongException) + { + return Refuse( + ExportFolderProblemKind.PathTooLong, + $"Il percorso di {shown} è troppo lungo: i nomi dei file non ci starebbero nei {WindowsFileNames.MaxPathLength} caratteri. Scegli una cartella con un percorso più corto."); + } + + // Textual overlap first: it needs no write. + foreach (var folder in context.Protected) + { + if (Overlap(full, folder.Path, shown, folder) is { } problem) + { + return new ExportFolderVerdict(full, problem); + } + } + + // Then where the folders really are (links, junctions, drive aliases, bind mounts), read-only; the probe stays + // for what this cannot see (a share that points back to this computer). + if (IdentityOverlap(full, shown, context.Protected) is { } aliased) + { + return new ExportFolderVerdict(full, aliased); + } + + ct.ThrowIfCancellationRequested(); + return ProbeIdentity(full, shown, context.Protected); + } + + /// + /// The identity comparison (decision of 2026-11-27): the candidate is a protected folder, or inside one, when its + /// is; it contains one when the protected folder's location is inside the candidate's, or + /// inside (or around) what a mount below the candidate shows. + /// + private ExportFolderProblem? IdentityOverlap(string full, string shown, IReadOnlyList protectedFolders) + { + if (FolderIdentity.Locate(full, _mounts, out var real) is not { } candidate || real is null) + { + return null; + } + + var below = _mounts.All() + .Where(m => !ExportPaths.Same(m.MountPoint, real) && ExportPaths.IsSameOrInside(m.MountPoint, real)) + .Select(FolderIdentity.Of) + .OfType() + .ToList(); + foreach (var folder in protectedFolders) + { + if (FolderIdentity.Locate(folder.Path, _mounts) is not { } location) + { + continue; + } + + if (candidate.IsSame(location)) + { + return Same(shown, folder); + } + + if (candidate.IsSameOrInside(location)) + { + return Inside(shown, folder); + } + + if (location.IsSameOrInside(candidate) || below.Any(b => location.IsSameOrInside(b) || b.IsSameOrInside(location))) + { + return Contains(shown, folder); + } + } + + return null; + } + + private static ExportFolderProblem? Overlap(string full, string protectedPath, string shown, ProtectedFolder folder) + { + if (ExportPaths.Same(full, protectedPath)) + { + return Same(shown, folder); + } + + if (ExportPaths.IsSameOrInside(full, protectedPath)) + { + return Inside(shown, folder); + } + + return ExportPaths.IsSameOrInside(protectedPath, full) ? Contains(shown, folder) : null; + } + + private static ExportFolderProblem Same(string shown, ProtectedFolder folder) => + new(ExportFolderProblemKind.SameAsProtected, $"{shown} è {folder.Description}: scegli un'altra cartella."); + + private static ExportFolderProblem Inside(string shown, ProtectedFolder folder) => + new(ExportFolderProblemKind.InsideProtected, $"{shown} è dentro {folder.Description}: scegli una cartella fuori."); + + private static ExportFolderProblem Contains(string shown, ProtectedFolder folder) => + new(ExportFolderProblemKind.ContainsProtected, $"{shown} contiene {folder.Description}: scegli una cartella che non la contenga."); + + /// + /// The identity test of spec §4.10: a probe written in the candidate only, then looked for (never written) up the + /// parents of each protected folder (the candidate contains it, or is it) and, for each parent of the candidate, at the + /// same relative path under each protected folder (the candidate is inside it). + /// + private ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList protectedFolders) + { + var name = NewProbeName(); + var probe = Path.Combine(full, name); + try + { + try + { + _writeProbe(probe); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + var reason = ex is UnauthorizedAccessException ? "accesso negato" : ex.Message; + return new ExportFolderVerdict(full, new ExportFolderProblem( + ExportFolderProblemKind.ProbeFailed, + $"Febe non riesce a scrivere in {shown} ({reason}): controlla i permessi o che il disco non sia in sola lettura.")); + } + + foreach (var folder in protectedFolders) + { + // (a) The candidate is the protected folder, or one of its parents, under another name. + for (var ancestor = folder.Path; ancestor is not null; ancestor = Path.GetDirectoryName(ancestor)) + { + if (Exists(Path.Combine(ancestor, name))) + { + var problem = ExportPaths.Same(ancestor, folder.Path) ? Same(shown, folder) : Contains(shown, folder); + return new ExportFolderVerdict(full, problem); + } + } + } + + // (b) The candidate is inside a protected folder under another name: for each parent M of the candidate, + // the probe would appear at F/ for the protected folder F that is M. + for (var parent = Path.GetDirectoryName(full); parent is not null; parent = Path.GetDirectoryName(parent)) + { + var relative = Path.GetRelativePath(parent, full); + foreach (var folder in protectedFolders) + { + if (Exists(Path.Combine(folder.Path, relative, name))) + { + return new ExportFolderVerdict(full, Inside(shown, folder)); + } + } + } + + return new ExportFolderVerdict(full, null); + } + finally + { + try + { + File.Delete(probe); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: a probe left behind is a temporary file of Febe, harmless. + } + } + } + + private static void WriteProbeFile(string path) + { + using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None); + stream.Write("Febe"u8); + stream.Flush(flushToDisk: true); + } + + private static bool Exists(string path) + { + try + { + return File.Exists(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return false; + } + } + + /// + /// Decision D15: on Windows the path is its own root (C:\, \\srv\share); on Linux it is / or + /// exactly a mount point that shows the root of its file system. + /// + private bool IsRootOfDisk(string full) + { + if (OperatingSystem.IsWindows()) + { + var root = Path.GetPathRoot(full); + return !string.IsNullOrEmpty(root) && ExportPaths.Same(root, full); + } + + if (full == "/") + { + return true; + } + + var mount = _mounts.FindContaining(full); + return mount is not null && string.Equals(ExportPaths.Trim(mount.MountPoint), full, StringComparison.Ordinal) && mount.Root == "/"; + } + + private static string Full(string path) => ExportPaths.Trim(Path.GetFullPath(path)); +} diff --git a/src/Febe.Core/Export/ExportLeftovers.cs b/src/Febe.Core/Export/ExportLeftovers.cs new file mode 100644 index 0000000..8e6ea22 --- /dev/null +++ b/src/Febe.Core/Export/ExportLeftovers.cs @@ -0,0 +1,89 @@ +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// The .part files a crash left in a destination (spec §4.10): removed only in the folders where the items of +/// an unfinished job were to be written, never by a scan of the destination, never in a folder of no item. Only our +/// own temporary names (.febe-*.part, the probes included) are touched. +/// +public static class ExportLeftovers +{ + private const int PageSize = 1000; + + /// Removes our temporary files in the folders of the items of . Returns how many. + public static async Task CleanAsync(ExportEnvironment env, ExportRun run, ExportDestination destination, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(run); + ArgumentNullException.ThrowIfNull(destination); + if (ExportRoots.MountProblem(env.Root, destination.RootPath) is not null || !await AnswersAsync(env, destination.RootPath, ct).ConfigureAwait(false)) + { + return 0; + } + + var folders = new HashSet(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + long after = 0; + while (true) + { + var page = await env.Storage.Exports.ListItemsAsync(new ExportItemQuery { RunId = run.Id, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + foreach (var item in page) + { + if (item.RelativePath is { } relative && item.State is ExportItemState.Pending or ExportItemState.Failed) + { + try + { + if (Path.GetDirectoryName(LibraryLayout.FullPath(destination.RootPath, relative)) is { } folder) + { + folders.Add(folder); + } + } + catch (ArgumentException) + { + // A path that would leave the root: nothing of ours can be there. + } + } + } + } + + var removed = 0; + foreach (var folder in folders) + { + ct.ThrowIfCancellationRequested(); + try + { + removed += await Task.Run(() => SafeFileWriter.CleanupTemporaryFiles(folder, recursive: false), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return removed; // the disk stopped answering: the next resume tries again + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: a leftover .part takes some space, nothing more. + } + } + + return removed; + } + + private static async Task AnswersAsync(ExportEnvironment env, string root, CancellationToken ct) + { + try + { + return await Task.Run(() => Directory.Exists(root), ct).WaitAsync(env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return false; + } + } +} diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs new file mode 100644 index 0000000..e21e4bb --- /dev/null +++ b/src/Febe.Core/Export/ExportModels.cs @@ -0,0 +1,122 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// What a «Copia in…» is asked for (spec §4.10 «Manuale sempre»). +public abstract record ExportSelection +{ + private ExportSelection() + { + } + + /// Files by id: a selection of «Tutte le foto», a file of the viewer. + public sealed record Media(IReadOnlyList MediaIds) : ExportSelection; + + /// Entries by id: a grouped selection, an entry of the viewer. + public sealed record Entries(IReadOnlyList EntryIds) : ExportSelection; + + /// The current filter («Copia i file in…» of the CSV menu). + public sealed record Filter(LibraryFilter LibraryFilter, MosaicMode Mode) : ExportSelection; + + /// Every file of an account (the account card). + public sealed record Account(long AccountId) : ExportSelection; +} + +/// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked. +public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual); + +/// +/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective +/// destination of its account (D5). +/// +/// Files to write. +/// Their bytes. +/// Already in their destination (or, with «Una copia sola», copied for another account). +/// +/// «Tolti o superati»: never copied again by themselves. With they are also +/// counted in and , since they will be written. +/// +/// «Esporta questo account» off, no destination, or a content type the destination does not take. +/// «File non presente in libreria». +/// Each destination that gets files, with whether it answers now. +/// +/// A folder of the copies exists (the general one or one of an account, in use): when nothing is to copy, the dialog +/// says «no folder» only when this is false, not because no destination gets files. +/// +public sealed record ExportPlan( + int Files, + long Bytes, + int AlreadyCopied, + int RemovedOrSuperseded, + int NotExported, + int Missing, + IReadOnlyList Destinations, + bool HasDestination = true) +{ + public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []); +} + +/// A destination of a plan. +/// The account of an own folder; null for the general folder. +/// Files to write there. +/// The destination is paused (its last check failed). +/// Why it cannot be written now (not reachable, not mounted, paused), in Italian; null when fine. +/// Free space, when it can be measured. +public sealed record ExportPlanDestination( + long DestinationId, + string Label, + string RootPath, + ExportScope Scope, + string? Username, + int Files, + long Bytes, + bool Paused, + string? Problem, + long? FreeBytes); + +/// What the export job is doing. +public enum ExportPhase +{ + Preparing, + + /// «Controlla le copie». + Checking, + + /// An engine session is running: copies wait for it to end (decision D11). + WaitingForSession, + + Copying, + + Finished, +} + +/// Progress of the export job, for the progress card (polled, D20). +/// The job's run being worked on; null for «Controlla le copie» and when nothing ever ran. +/// Bytes of the files still pending when the run (re)started, plus those done since; 0 when unknown. +public sealed record ExportProgress( + long? RunId, + ExportPhase Phase, + int FilesDone, + int FilesTotal, + long BytesDone, + long BytesTotal, + string? CurrentFile, + string? DestinationLabel, + IReadOnlyDictionary ByState, + DateTimeOffset UpdatedAt) +{ + /// 0..1: by bytes when known, otherwise by files. + public double Fraction => BytesTotal > 0 + ? Math.Clamp((double)BytesDone / BytesTotal, 0, 1) + : FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0; +} + +/// What ExportService.StartAsync did: one run per destination (D6), and the plan it followed. +public sealed record ExportStart(IReadOnlyList Runs, ExportPlan Plan); + +/// What «Riprova» of a paused destination did: the reason it is still paused (null: it answers), and the jobs resumed. +public sealed record ExportRetry(string? Problem, IReadOnlyList Resumed); + +/// The export job ended (however it ended): the runs it worked on, and whether copies may have changed. +public sealed record ExportJobFinished(IReadOnlyList RunIds, bool CopiesChanged); diff --git a/src/Febe.Core/Export/ExportNamingPreview.cs b/src/Febe.Core/Export/ExportNamingPreview.cs new file mode 100644 index 0000000..70bbb93 --- /dev/null +++ b/src/Febe.Core/Export/ExportNamingPreview.cs @@ -0,0 +1,35 @@ +using Febe.Core.Domain; +using Febe.Core.Library; + +namespace Febe.Core.Export; + +/// +/// The «Risultato» tree of a destination's naming (spec §4.10 «Nomi dei file»): the library preview rendered with the +/// destination's schemes, «Come la libreria» (null) taking the library's. In the general folder each file sits under +/// its account segment. +/// +public static class ExportNamingPreview +{ + public static NamingPreview Build( + ExportScope scope, + string? general, + string? highlight, + string? profile, + LibraryNaming library, + TimeZoneInfo zone, + string sampleAccount = "nome.utente") + { + ArgumentNullException.ThrowIfNull(library); + var preview = NamingPreview.Build(general ?? library.General.Text, highlight ?? library.Highlight.Text, profile ?? library.ProfilePicture.Text, zone, sampleAccount); + if (scope != ExportScope.General) + { + return preview; + } + + var segment = WindowsFileNames.SanitizeSegment(sampleAccount); + return preview with + { + Folders = preview.Folders.Select(f => f with { Path = [segment, .. f.Path] }).ToList(), + }; + } +} diff --git a/src/Febe.Core/Export/ExportPaths.cs b/src/Febe.Core/Export/ExportPaths.cs new file mode 100644 index 0000000..d085b1f --- /dev/null +++ b/src/Febe.Core/Export/ExportPaths.cs @@ -0,0 +1,145 @@ +using System.Globalization; +using Febe.Core.Domain; +using Febe.Core.Library; + +namespace Febe.Core.Export; + +/// Paths and content types of the export (spec §4.10). +public static class ExportPaths +{ + /// Folders compare without case on Windows (and its shares), exactly elsewhere, as the import does. + public static StringComparison PathComparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + /// True when is or inside it, as text (full paths). + public static bool IsSameOrInside(string path, string folder) + { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(folder); + var p = Trim(path); + var f = Trim(folder); + return string.Equals(p, f, PathComparison) + || p.StartsWith(f.EndsWith(Path.DirectorySeparatorChar) || f.EndsWith(Path.AltDirectorySeparatorChar) ? f : f + Path.DirectorySeparatorChar, PathComparison); + } + + /// The same folder, as text. + public static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison); + + /// A full path without its trailing separator (a root such as C:\ or / keeps it). + public static string Trim(string path) + { + ArgumentNullException.ThrowIfNull(path); + return path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path; + } + + /// + /// The content type of a file (decision D4 of tappa E2): a post photo or video, a story (also a highlight when the + /// story is in a collection), a highlight, a tagged post, a profile picture. The «Copie» filter repeats it in SQL. + /// + public static ContentTypes TypeOf(EntryKind kind, MediaKind media, bool inHighlight) => kind switch + { + EntryKind.Post => media == MediaKind.Photo ? ContentTypes.PostPhotos : ContentTypes.PostVideos, + EntryKind.Story => inHighlight ? ContentTypes.Stories | ContentTypes.Highlights : ContentTypes.Stories, + EntryKind.Highlight => ContentTypes.Highlights, + EntryKind.Tagged => ContentTypes.Tagged, + EntryKind.ProfilePicture => ContentTypes.ProfilePicture, + _ => ContentTypes.None, + }; + + /// Folder of imported files without a known date or code (as the import names it). + public const string ImportedFolder = "importati"; + + /// + /// The path of a copy below the destination root, as sanitized segments, before + /// (decision D18 of tappa E2). «Come la libreria» (a null scheme) renders the library's current scheme again, except + /// for a file the import left in importati/, which keeps its path. A story in a highlight collection takes the + /// highlight scheme only when the destination takes highlights and not stories. In the general folder the account + /// segment comes first. + /// + public static IReadOnlyList Segments( + ExportDestination d, + LibraryNaming library, + Account account, + Entry entry, + Media media, + string? highlightTitle, + bool inHighlight, + TimeZoneInfo zone) + { + ArgumentNullException.ThrowIfNull(d); + ArgumentNullException.ThrowIfNull(library); + ArgumentNullException.ThrowIfNull(account); + ArgumentNullException.ThrowIfNull(entry); + ArgumentNullException.ThrowIfNull(media); + ArgumentNullException.ThrowIfNull(zone); + var stored = media.RelativePath is { Length: > 0 } path + ? LibraryLayout.ToStored(path) + : throw new ArgumentException("Il file non è nella libreria: non ha un percorso.", nameof(media)); + + var renderAs = entry.Kind == EntryKind.Story && inHighlight + && d.ContentTypes.HasFlag(ContentTypes.Highlights) && !d.ContentTypes.HasFlag(ContentTypes.Stories) + ? EntryKind.Highlight + : entry.Kind; + var use = UseOf(renderAs); + var text = use switch + { + NamingSchemeUse.Highlight => d.HighlightNamingScheme, + NamingSchemeUse.ProfilePicture => d.ProfileNamingScheme, + _ => d.NamingScheme, + }; + + IReadOnlyList segments; + if (text is null && stored.StartsWith(ImportedFolder + "/", StringComparison.Ordinal)) + { + segments = stored.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(WindowsFileNames.SanitizeSegment).ToList(); + } + else + { + var scheme = (text is null ? null : NamingScheme.Validate(text, use).Scheme) ?? library.For(renderAs); + var extension = Path.GetExtension(stored).TrimStart('.').ToLowerInvariant(); + var values = NamingValues.For( + account.Username, + entry with { Kind = renderAs }, + media.Position, + extension, + renderAs == EntryKind.Highlight ? highlightTitle : null, + media.Sha256); + segments = scheme.Render(values, zone); + } + + return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments; + } + + /// The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root. + /// Even shortened, the path does not fit. + public static string RelativePathFor(ExportDestination d, IReadOnlyList segments, int maxPath = WindowsFileNames.MaxPathLength) + { + ArgumentNullException.ThrowIfNull(d); + return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath)); + } + + /// + /// The name the safe writer gives a file at its -th try when the planned name is taken + /// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. + /// + public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength) + { + ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); + var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries); + if (attempt <= 1) + { + return string.Join('/', segments); + } + + var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); + var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}")); + return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath)); + } + + /// The scheme that names an entry kind. + public static NamingSchemeUse UseOf(EntryKind kind) => kind switch + { + EntryKind.Highlight => NamingSchemeUse.Highlight, + EntryKind.ProfilePicture => NamingSchemeUse.ProfilePicture, + _ => NamingSchemeUse.General, + }; +} diff --git a/src/Febe.Core/Export/ExportPause.cs b/src/Febe.Core/Export/ExportPause.cs new file mode 100644 index 0000000..cf2fdf6 --- /dev/null +++ b/src/Febe.Core/Export/ExportPause.cs @@ -0,0 +1,70 @@ +using Febe.Core.Domain; + +namespace Febe.Core.Export; + +/// +/// The pause of a destination (spec §4.10): its probe could not be written, it is not reachable, or the disk is full. +/// The state shows in Impostazioni and in the Dashboard and the next check clears it. Never the red strip: the event +/// esportazione-in-pausa is not an alert of the engine. +/// +public static class ExportPause +{ + /// Code of the event written once when a destination goes into pause. + public const string PausedEventCode = "esportazione-in-pausa"; + + /// + /// Pauses a destination with an Italian reason (read-modify-write on the stored row; a retired row is left as it + /// is). The event is written only on the transition from running to paused. Returns the stored row. + /// + public static async Task PauseAsync(ExportEnvironment env, ExportDestination destination, string message) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(destination); + ArgumentException.ThrowIfNullOrWhiteSpace(message); + var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; + if (stored.IsRetired) + { + return stored; + } + + var wasPaused = stored.PausedAt is not null; + if (wasPaused && string.Equals(stored.LastError, message, StringComparison.Ordinal)) + { + return stored; + } + + var paused = stored with { PausedAt = stored.PausedAt ?? env.Clock.Now, LastError = message }; + await env.Storage.Exports.UpdateDestinationAsync(paused, CancellationToken.None).ConfigureAwait(false); + if (!wasPaused) + { + await env.Storage.Events.AppendAsync( + new EventRecord + { + At = env.Clock.Now, + Code = PausedEventCode, + Severity = EventSeverity.Warning, + Message = $"{ExportDestinations.Label(paused)} in pausa: {message}", + AccountId = paused.AccountId, + }, + CancellationToken.None).ConfigureAwait(false); + } + + return paused; + } + + /// Clears the pause of a destination after a check succeeded. Returns the stored row. + public static async Task ClearAsync(ExportEnvironment env, ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(destination); + var stored = await env.Storage.Exports.GetDestinationAsync(destination.Id, CancellationToken.None).ConfigureAwait(false) ?? destination; + if (stored.IsRetired || (stored.PausedAt is null && stored.LastError is null)) + { + return stored; + } + + var cleared = stored with { PausedAt = null, LastError = null }; + await env.Storage.Exports.UpdateDestinationAsync(cleared, CancellationToken.None).ConfigureAwait(false); + return cleared; + } +} diff --git a/src/Febe.Core/Export/ExportPlanner.cs b/src/Febe.Core/Export/ExportPlanner.cs new file mode 100644 index 0000000..f087ef2 --- /dev/null +++ b/src/Febe.Core/Export/ExportPlanner.cs @@ -0,0 +1,238 @@ +using System.Runtime.CompilerServices; +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the +/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are +/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog. +/// +public sealed class ExportPlanner(ExportEnvironment env) +{ + private const int PageSize = 2000; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// The plan of a request, for the «Copia in…» dialog. + public async Task PlanAsync(ExportJobRequest request, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(request); + var destinations = new ExportDestinations(_env); + var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + var tally = new PlanTally(); + await foreach (var file in EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) + { + tally.Add(file); + } + + return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false); + } + + /// + /// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an + /// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with + /// «Una copia sola» the same file counts once across accounts. + /// + internal async IAsyncEnumerable EnumerateAsync( + ExportJobRequest request, + IReadOnlyDictionary effective, + ExportSettings settings, + [EnumeratorCancellation] CancellationToken ct) + { + var exports = _env.Storage.Exports; + var oneOnly = settings.SamePost == SamePostCopies.OneOnly; + var seen = new HashSet<(long Destination, long Account, string Sha256)>(); + long after = 0; + while (true) + { + var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false); + if (page.Count == 0) + { + yield break; + } + + after = page[^1].MediaId; + var keys = new Dictionary>(); + foreach (var c in page) + { + if (Due(c, effective) is { } destination) + { + if (!keys.TryGetValue(destination, out var set)) + { + keys[destination] = set = []; + } + + set.Add((c.AccountId, c.Sha256!)); + } + } + + var states = new Dictionary>(); + foreach (var (destination, set) in keys) + { + states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false); + } + + foreach (var c in page) + { + if (!IsPresent(c)) + { + yield return new PlannedFile(c, null, PlannedCopy.Missing); + continue; + } + + if (Due(c, effective) is not { } destination) + { + yield return new PlannedFile(c, null, PlannedCopy.NotExported); + continue; + } + + var sha = c.Sha256!; + var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha); + var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null; + PlannedFile planned; + if (state == ExportCopyState.Copied) + { + planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + } + else if (state is ExportCopyState.Removed or ExportCopyState.Superseded) + { + planned = request.CopyAgain + ? new PlannedFile(c, destination, PlannedCopy.Write, Again: true) + : new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded); + } + else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null) + { + planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied); + } + else + { + planned = new PlannedFile(c, destination, PlannedCopy.Write); + } + + if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key)) + { + planned = planned with { Action = PlannedCopy.AlreadyCopied, Again = false }; + } + + yield return planned; + } + } + } + + /// A file present in the library, with its SHA-256 and path. + internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath); + + /// The destination a present file goes to (D3), or null when it is not exported. + private static long? Due(ExportCandidate c, IReadOnlyDictionary effective) => + IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight)) + ? e.Destination!.Id + : null; +} + +/// A candidate with what the plan does with it. +/// Where it goes; null when not exported or missing. +/// Written although «Tolto» or «Superato», because «Copia di nuovo» was asked. +internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false); + +internal enum PlannedCopy +{ + Write, + AlreadyCopied, + RemovedOrSuperseded, + NotExported, + Missing, +} + +/// Counts of a plan while its files go by. +internal sealed class PlanTally +{ + private readonly Dictionary _byDestination = []; + + public int Files { get; private set; } + + public long Bytes { get; private set; } + + public int AlreadyCopied { get; private set; } + + public int RemovedOrSuperseded { get; private set; } + + public int NotExported { get; private set; } + + public int Missing { get; private set; } + + public void Add(PlannedFile file) + { + switch (file.Action) + { + case PlannedCopy.Missing: + Missing++; + return; + case PlannedCopy.NotExported: + NotExported++; + return; + case PlannedCopy.AlreadyCopied: + AlreadyCopied++; + break; + case PlannedCopy.RemovedOrSuperseded: + RemovedOrSuperseded++; + break; + case PlannedCopy.Write: + var bytes = file.Candidate.Bytes ?? 0; + Files++; + Bytes += bytes; + if (file.Again) + { + RemovedOrSuperseded++; + } + + var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value); + _byDestination[file.DestinationId.Value] = (f + 1, b + bytes); + return; + } + + _byDestination.TryAdd(file.DestinationId!.Value, (0, 0)); + } + + /// The plan. With each destination is asked whether it answers now. + public async Task BuildAsync( + ExportEnvironment env, + ExportDestinations destinations, + IReadOnlyDictionary effective, + bool checkDestinations, + CancellationToken ct) + { + var rows = effective.Values.Where(e => e.Destination is not null).Select(e => e.Destination!).DistinctBy(d => d.Id).ToDictionary(d => d.Id); + var accounts = (await env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + var list = new List(); + foreach (var (id, (files, bytes)) in _byDestination.OrderBy(d => rows.TryGetValue(d.Key, out var r) && r.Scope == ExportScope.General ? 0 : 1).ThenBy(d => d.Key)) + { + var d = rows.TryGetValue(id, out var row) ? row : await env.Storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false); + if (d is null) + { + continue; + } + + string? problem = null; + long? free = null; + if (checkDestinations) + { + var status = await destinations.StatusAsync(id, ct).ConfigureAwait(false); + problem = status.Problem; + free = status.FreeBytes; + } + + problem ??= d.PausedAt is not null ? d.LastError : null; + var username = d.AccountId is { } a ? accounts.GetValueOrDefault(a) : null; + list.Add(new ExportPlanDestination(d.Id, ExportDestinations.Label(d), d.RootPath, d.Scope, username, files, bytes, d.PausedAt is not null, problem, free)); + } + + var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0; + return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any); + } + + /// Destinations that get a run: those with files to write, already copied, or «tolti o superati». + public IReadOnlyCollection Destinations => _byDestination.Keys; +} diff --git a/src/Febe.Core/Export/ExportReports.cs b/src/Febe.Core/Export/ExportReports.cs new file mode 100644 index 0000000..c8bc328 --- /dev/null +++ b/src/Febe.Core/Export/ExportReports.cs @@ -0,0 +1,106 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// The report of an export job (spec §4.10): counts, per account, and the files that need a look. +/// At most lines: failed, missing, and skipped files with a note. +public sealed record ExportReport( + ExportRun Run, + ExportDestination Destination, + int Total, + IReadOnlyDictionary ByState, + long BytesCopied, + IReadOnlyList Accounts, + IReadOnlyList Problems); + +/// The files of one account in a job («Copiato» counts written and adopted files). +public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); + +/// A file of the report, with its reason in Italian. +public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text); + +/// Builds the report of a job from the database (no CSV in E2: §4.10 leaves «Copiato in» in the CSV out of 0.3.0). +public sealed class ExportReports(ExportEnvironment env) +{ + public const int MaxProblems = 200; + + private const int PageSize = 1000; + + /// A name for files whose account was removed. + public const string RemovedAccount = "account rimosso"; + + private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env)); + + /// No such job. + public async Task BuildAsync(long runId, CancellationToken ct = default) + { + var exports = _env.Storage.Exports; + var run = await exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + var destination = await exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Destinazione di esportazione {run.DestinationId} non trovata."); + var summary = await exports.GetRunSummaryAsync(runId, ct).ConfigureAwait(false); + var names = (await _env.Storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + string Name(long? id) => id is { } a && names.TryGetValue(a, out var n) ? n : RemovedAccount; + + var accounts = new Dictionary(); + var problems = new List(); + long bytes = 0; + long after = 0; + while (true) + { + var page = await exports.ListItemsAsync(new ExportItemQuery { RunId = runId, AfterId = after, Limit = PageSize }, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + foreach (var item in page) + { + var key = item.AccountId ?? 0; + if (!accounts.TryGetValue(key, out var row)) + { + accounts[key] = row = new int[4]; + } + + switch (item.State) + { + case ExportItemState.Copied or ExportItemState.Adopted: + row[0]++; + if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b }) + { + bytes += b; + } + + break; + case ExportItemState.AlreadyCopied: + row[1]++; + break; + case ExportItemState.Skipped or ExportItemState.Missing: + row[2]++; + break; + case ExportItemState.Failed: + row[3]++; + break; + } + + var problem = item.State is ExportItemState.Failed or ExportItemState.Missing + || (item.State == ExportItemState.Skipped && item.Note is not null); + if (problem && problems.Count < MaxProblems) + { + var text = item.State == ExportItemState.Failed + ? item.LastError ?? ExportText.Note(item.Note) ?? ExportText.State(item.State) + : ExportText.Note(item.Note) ?? ExportText.State(item.State); + problems.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, text)); + } + } + } + + var perAccount = accounts + .Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3])) + .OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase) + .ToList(); + return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems); + } +} diff --git a/src/Febe.Core/Export/ExportRoot.cs b/src/Febe.Core/Export/ExportRoot.cs new file mode 100644 index 0000000..82b531e --- /dev/null +++ b/src/Febe.Core/Export/ExportRoot.cs @@ -0,0 +1,344 @@ +using Febe.Core.Import; +using Febe.Core.Library; + +namespace Febe.Core.Export; + +/// A mounted file system, as the export needs it (spec §4.10 «Docker e Windows»). +/// Where it is mounted. +/// Folder of its file system shown there (/: the root of that file system). +/// File system type (vfat for FAT32). +/// Mounted read-only. +/// +/// The device of its file system (major:minor in mountinfo), or null when unknown: with it the identity +/// test of the folder check sees a bind mount of a folder of the library (decision of 2026-11-27). +/// +public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly, string? Device = null); + +/// The mount table (a seam: tests give their own; Linux reads /proc/self/mountinfo). +public interface IExportMounts +{ + /// The mount that holds a full path, or null (always null on Windows). + ExportMount? FindContaining(string fullPath); + + /// Every mount (empty on Windows). + IReadOnlyList All(); +} + +/// The mounts of this process from /proc/self/mountinfo, read at each call (it is small). +public sealed class ProcMountInfo(Func? read = null) : IExportMounts +{ + private readonly Func _read = read ?? MountInfoTable.ReadProcSelf; + + public ExportMount? FindContaining(string fullPath) + { + ArgumentNullException.ThrowIfNull(fullPath); + var mounts = Read(); + return mounts.Count == 0 ? null : Map(MountInfoTable.FindContaining(mounts, fullPath)); + } + + public IReadOnlyList All() => Read().Select(m => Map(m)!).ToList(); + + private IReadOnlyList Read() + { + try + { + return _read() is { } content ? MountInfoTable.Parse(content) : []; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return []; + } + } + + private static ExportMount? Map(MountInfoEntry? m) => m is null ? null : new ExportMount(m.MountPoint, m.Root, m.FileSystemType, m.ReadOnly, m.Device); +} + +/// +/// Where destinations may be chosen. Docker: subfolders of /esporta, only when it is declared +/// (--esporta, FEBE_ESPORTA) and the destination sits on a mount at /esporta or below it (decision of +/// Alberto, question Q2 of tappa E2). Windows: any folder, through the native picker. +/// +public sealed record ExportRootOptions +{ + /// Docker: the full path of /esporta. Null: any folder. + public string? Root { get; init; } + + /// --esporta or FEBE_ESPORTA (always true without a root). + public bool Declared { get; init; } + + /// The mount table. + public IExportMounts Mounts { get; init; } = new ProcMountInfo(); + + /// How the page names (the demo shows «/esporta» for its temporary folder); null: as it is. + public string? ShownAs { get; init; } + + /// Windows (and development): any folder. + public static ExportRootOptions AnyFolder { get; } = new() { Declared = true }; + + /// Docker: destinations under . + public static ExportRootOptions Docker(string root, bool declared, IExportMounts? mounts = null) + { + ArgumentException.ThrowIfNullOrWhiteSpace(root); + return new ExportRootOptions { Root = ExportPaths.Trim(Path.GetFullPath(root)), Declared = declared, Mounts = mounts ?? new ProcMountInfo() }; + } +} + +/// Whether copies to external folders can be written at all, and why not. +/// True: destinations may be created and written. +/// Docker: the root (/esporta); null on Windows. +/// Italian text of the reason when not active. +public sealed record ExportRootState(bool Active, string? Root, string? Problem); + +/// The rules of the export root (spec §4.10, §11): /esporta in Docker, any folder on Windows. +public static class ExportRoots +{ + /// Copies to external folders are switched off in Docker (not declared). + public const string NotDeclaredText = + "Le copie esterne in Docker sono spente: si accendono con FEBE_ESPORTA=1 (o --esporta) e una cartella del server montata su /esporta."; + + /// Whether the root is usable: always without a root; in Docker declared and with a mount at or below it. + public static ExportRootState Evaluate(ExportRootOptions o) + { + ArgumentNullException.ThrowIfNull(o); + if (o.Root is not { } root) + { + return new ExportRootState(true, null, null); + } + + if (!o.Declared) + { + return new ExportRootState(false, root, NotDeclaredText); + } + + return o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root)) + ? new ExportRootState(true, root, null) + : new ExportRootState(false, root, NotMountedText(o)); + } + + /// + /// Null when a destination may be written as far as the mounts are concerned (always on Windows); otherwise the + /// Italian reason: not declared, not on a mount at or below the root, or a read-only mount. + /// + public static string? MountProblem(ExportRootOptions o, string destinationFullPath) => MountCheck(o, destinationFullPath)?.Message; + + internal static ExportFolderProblem? MountCheck(ExportRootOptions o, string destinationFullPath) + { + ArgumentNullException.ThrowIfNull(o); + ArgumentException.ThrowIfNullOrWhiteSpace(destinationFullPath); + if (o.Root is not { } root) + { + return null; + } + + if (!o.Declared) + { + return new ExportFolderProblem(ExportFolderProblemKind.NotMounted, NotDeclaredText); + } + + var full = ExportPaths.Trim(Path.GetFullPath(destinationFullPath)); + var mount = o.Mounts.FindContaining(full); + if (mount is null || !ExportPaths.IsSameOrInside(ExportPaths.Trim(mount.MountPoint), root)) + { + return new ExportFolderProblem( + ExportFolderProblemKind.NotMounted, + o.Mounts.All().Any(m => ExportPaths.IsSameOrInside(ExportPaths.Trim(m.MountPoint), root)) + ? $"{DisplayPath(o, full)} non è su una cartella montata in {DisplayPath(o, root)}: Febe non ci scrive nulla. Scegli una cartella dentro un montaggio di {DisplayPath(o, root)}." + : NotMountedText(o)); + } + + return mount.ReadOnly + ? new ExportFolderProblem(ExportFolderProblemKind.ReadOnlyMount, $"{DisplayPath(o, full)} è montata in sola lettura: Febe non può copiarci nulla.") + : null; + } + + /// + /// Subfolders offered by the picker in Docker: is relative to the root, and so are the + /// returned paths. Without a root it is an absolute folder. Links, hidden and system folders are skipped. + /// + /// The folder cannot be browsed. + public static IReadOnlyList Browse(ExportRootOptions o, string? relative) + { + var folder = BrowsedFolder(o, relative); + return [.. Subfolders(o, folder).Select(s => s.Choice with { HasSubfolders = HasSubfolders(s.FullPath) })]; + } + + /// + /// for the web picker, never blocking it (spec §4.10 «I controlli sul disco esterno sono asincroni + /// e brevi»): the listing of the folder gets , and each subfolder gets as much in parallel to + /// tell whether it has subfolders, so a dead share mounted below the folder shows without the arrow instead of + /// hiding the healthy ones. + /// + /// The folder cannot be browsed, or does not answer in time. + public static Task> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, CancellationToken ct) => + BrowseAsync(o, relative, timeout, HasSubfolders, ct); + + /// with the look into a subfolder given (a seam for tests). + internal static async Task> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, Func hasSubfolders, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(hasSubfolders); + var folder = BrowsedFolder(o, relative); + IReadOnlyList subfolders; + try + { + subfolders = await Task.Run(() => Subfolders(o, folder), ct).WaitAsync(timeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + throw new ExportFolderException( + $"La cartella {DisplayPath(o, folder)} non risponde entro {timeout.TotalSeconds:0} secondi: controlla che il disco o la condivisione siano collegati, poi riprova.", + ExportFolderProblemKind.NotResponding); + } + + async Task LookAsync(Subfolder s) + { + try + { + return s.Choice with { HasSubfolders = await Task.Run(() => hasSubfolders(s.FullPath), ct).WaitAsync(timeout, ct).ConfigureAwait(false) }; + } + catch (TimeoutException) + { + return s.Choice; // it does not answer: shown, without the arrow + } + } + + return await Task.WhenAll(subfolders.Select(LookAsync)).ConfigureAwait(false); + } + + private static string BrowsedFolder(ExportRootOptions o, string? relative) + { + ArgumentNullException.ThrowIfNull(o); + string folder; + if (o.Root is { } root) + { + folder = string.IsNullOrWhiteSpace(relative) ? root : Resolve(o, relative, allowRoot: true); + } + else if (string.IsNullOrWhiteSpace(relative) || !Path.IsPathFullyQualified(relative)) + { + throw new ExportFolderException("Scegli la cartella da sfogliare con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified); + } + else + { + folder = ExportPaths.Trim(Path.GetFullPath(relative)); + } + + return folder; + } + + /// The subfolders of a folder, sorted, without looking into them. + private static List Subfolders(ExportRootOptions o, string folder) + { + if (!Directory.Exists(folder)) + { + throw new ExportFolderException($"La cartella {DisplayPath(o, folder)} non esiste.", ExportFolderProblemKind.Missing); + } + + try + { + return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false)) + .Order(StringComparer.Ordinal) + .Select(d => new Subfolder(d, new SourceFolderChoice(Path.GetFileName(d), o.Root is { } r ? LibraryLayout.ToStored(Path.GetRelativePath(r, d)) : d, false))) + .ToList(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new ExportFolderException($"Febe non riesce a leggere {DisplayPath(o, folder)}: controlla che il disco sia collegato.", ExportFolderProblemKind.Missing); + } + } + + /// The folder has a subfolder to open (false when it cannot be read). + private static bool HasSubfolders(string folder) + { + try + { + return Directory.EnumerateDirectories(folder, "*", ImportSources.Enumeration(recursive: false)).Any(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// A subfolder found by the picker, with its full path. + private sealed record Subfolder(string FullPath, SourceFolderChoice Choice); + + /// + /// The full path of a chosen folder: in Docker the root plus a relative path (or a full path inside the root), never + /// the root itself, never with «..»; without a root a fully qualified path. + /// + /// The path cannot be a destination; the message says why. + public static string Resolve(ExportRootOptions o, string chosen) => Resolve(o, chosen, allowRoot: false); + + /// The path shown to Alberto: in Docker «/esporta/usb»; elsewhere the full path. + public static string DisplayPath(ExportRootOptions o, string full) + { + ArgumentNullException.ThrowIfNull(o); + ArgumentNullException.ThrowIfNull(full); + if (o.Root is { } root && ExportPaths.IsSameOrInside(full, root)) + { + var relative = Path.GetRelativePath(root, full); + var shown = o.ShownAs ?? LibraryLayout.ToStored(root); + return relative == "." ? shown : shown.TrimEnd('/') + "/" + LibraryLayout.ToStored(relative); + } + + return full; + } + + private static string Resolve(ExportRootOptions o, string chosen, bool allowRoot) + { + ArgumentNullException.ThrowIfNull(o); + if (string.IsNullOrWhiteSpace(chosen)) + { + throw new ExportFolderException("Scegli la cartella in cui copiare i file.", ExportFolderProblemKind.Empty); + } + + var display = o.Root is { } shown ? DisplayPath(o, shown) : null; + + // Refused as text, before any normalisation: «..» never walks out of the list the picker shows. + if (chosen.Split('/', '\\').Any(s => s == "..")) + { + throw new ExportFolderException( + display is null ? "«..» non è ammesso: scegli la cartella con il suo percorso completo." : $"«..» non è ammesso: scegli una sottocartella di {display} dall'elenco.", + ExportFolderProblemKind.ParentSegment); + } + + if (o.Root is not { } root) + { + if (!Path.IsPathFullyQualified(chosen)) + { + throw new ExportFolderException("Scegli la cartella con il suo percorso completo.", ExportFolderProblemKind.NotFullyQualified); + } + + return ExportPaths.Trim(FullPath(chosen)); + } + + var full = ExportPaths.Trim(Path.IsPathFullyQualified(chosen) ? FullPath(chosen) : FullPath(Path.Combine(root, chosen.TrimStart('/', '\\')))); + if (!ExportPaths.IsSameOrInside(full, root)) + { + throw new ExportFolderException( + $"In Docker le copie vanno solo in una sottocartella di {display}: monta lì una cartella del server e sceglila dall'elenco.", + ExportFolderProblemKind.OutsideExportRoot); + } + + if (!allowRoot && ExportPaths.Same(full, root)) + { + throw new ExportFolderException($"Scegli una sottocartella di {display}: {display} stessa non è una destinazione.", ExportFolderProblemKind.ExportRootItself); + } + + return full; + } + + private static string FullPath(string path) + { + try + { + return Path.GetFullPath(path); + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + throw new ExportFolderException("Il percorso scelto non è valido: scegli di nuovo la cartella.", ExportFolderProblemKind.NotFullyQualified); + } + } + + private static string NotMountedText(ExportRootOptions o) => + $"{DisplayPath(o, o.Root!)} è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del server su {DisplayPath(o, o.Root!)}."; +} diff --git a/src/Febe.Core/Export/ExportRunSettings.cs b/src/Febe.Core/Export/ExportRunSettings.cs new file mode 100644 index 0000000..de8e04b --- /dev/null +++ b/src/Febe.Core/Export/ExportRunSettings.cs @@ -0,0 +1,26 @@ +using System.Globalization; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// Settings of one export job (like ImportRunSettings): a row of the setting table each, so the schema +/// stays as E1 left it. Cleared when the job completes, is cancelled or deleted. +/// +internal static class ExportRunSettings +{ + public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo"); + + /// «Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9). + public static async Task GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct) + { + var text = await store.GetAsync(CopyAgainKey(runId), ct).ConfigureAwait(false); + return string.Equals(text?.Trim(), "1", StringComparison.Ordinal); + } + + public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) => + store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct); + + public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) => + store.SetAsync(CopyAgainKey(runId), null, ct); +} diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs new file mode 100644 index 0000000..16896a1 --- /dev/null +++ b/src/Febe.Core/Export/ExportService.cs @@ -0,0 +1,765 @@ +using System.Diagnostics; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// The copies to external folders for the interface (spec §4.10): one background job at a time, never together with +/// an import or a rebuild (), never during an engine session. A «Copia in…» makes one job +/// record per destination (decision D6 of tappa E2) and the job works on them in order. Every state lives in the +/// database: after a restart call once; «Riprendi» is always Alberto's. +/// +public sealed class ExportService : IAsyncDisposable +{ + private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila."; + private const int ItemBatch = 2000; + private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250); + + private readonly ExportEnvironment _env; + private readonly Lock _gate = new(); + private Job? _job; + private ExportProgress? _current; + private long _lastPublished; + private Task _cleanup = Task.CompletedTask; + private bool _starting; + + public ExportService(ExportEnvironment env) + { + ArgumentNullException.ThrowIfNull(env); + _env = env; + Destinations = new ExportDestinations(env); + Planner = new ExportPlanner(env); + Copier = new ExportCopier(env); + Reports = new ExportReports(env); + } + + /// Progress of the running job, at most four times a second and at every change of phase (pool thread). + public event EventHandler? ProgressChanged; + + /// The job ended, however it ended (pool thread): the interface refreshes tiles and filter. + public event EventHandler? JobFinished; + + public ExportDestinations Destinations { get; } + + public ExportPlanner Planner { get; } + + public ExportCopier Copier { get; } + + public ExportReports Reports { get; } + + /// The runs of the running job; empty when idle (and for «Controlla le copie», which has none). + public IReadOnlyList ActiveRunIds + { + get + { + lock (_gate) + { + return _job is { Task.IsCompleted: false } job ? job.RunIds : []; + } + } + } + + /// A job is running. + public bool IsBusy + { + get + { + lock (_gate) + { + return _starting || _job is { Task.IsCompleted: false }; + } + } + } + + /// The last error of a background job that could not be stored with its run (normally null). + public string? LastJobError { get; private set; } + + /// + /// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the + /// .part files of unfinished jobs are removed in the background, only in their items' folders. Never resumes + /// by itself. Returns how many jobs became interrupted. + /// + public async Task RecoverAsync(CancellationToken ct = default) + { + var active = ActiveRunIds; + var recovered = 0; + var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); + foreach (var run in unfinished) + { + if (run.State == ExportRunState.Running && !active.Contains(run.Id)) + { + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false); + recovered++; + } + } + + var toClean = unfinished.Where(r => !active.Contains(r.Id)).ToList(); + lock (_gate) + { + _cleanup = Task.Run(() => CleanLeftoversAsync(toClean)); + } + + return recovered; + } + + /// The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers). + public Task PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct); + + /// + /// «Copia in…»: records one job per destination that gets files, with its items, and starts copying in the + /// background. Files not exported or missing are only counted in the returned plan. When nothing is due, no job is + /// recorded and nothing starts. + /// + /// A copy, an import or a rebuild is running. + public async Task StartAsync(ExportJobRequest request, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(request); + var held = new LeaseHolder(); + lock (_gate) + { + EnsureIdle(); + + // The long-work gate is held from the plan on (§4.10 «esportazione, importazione e ricostruzione non girano + // insieme»): a rebuild or an import cannot start while the runs and their items are being recorded. + if (_env.Gate is { } gate) + { + if (!gate.TryEnter(LongWorkKind.Export, out var lease, out var busy)) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value)); + } + + held.Lease = lease; + } + + _starting = true; // a second «Copia in…» meanwhile records nothing + } + + try + { + return await StartReservedAsync(request, held, ct).ConfigureAwait(false); + } + finally + { + lock (_gate) + { + _starting = false; + } + + held.Lease?.Dispose(); // not handed to a job: nothing to copy, or the start failed + } + } + + private async Task StartReservedAsync(ExportJobRequest request, LeaseHolder held, CancellationToken ct) + { + var effective = await Destinations.ResolveAllAsync(ct).ConfigureAwait(false); + var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false); + var tally = new PlanTally(); + var runs = new Dictionary(); + var pending = new List(); + var exports = _env.Storage.Exports; + try + { + await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false)) + { + tally.Add(file); + if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported) + { + continue; + } + + if (!runs.TryGetValue(destination, out var run)) + { + run = await exports.CreateRunAsync( + new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now }, + CancellationToken.None).ConfigureAwait(false); + runs[destination] = run; + if (request.CopyAgain) + { + await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false); + } + } + + pending.Add(new ExportItem + { + RunId = run.Id, + MediaId = file.Candidate.MediaId, + AccountId = file.Candidate.AccountId, + SourceSha256 = file.Candidate.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportItemState.Pending, + }); + if (pending.Count >= ItemBatch) + { + await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false); + pending.Clear(); + } + } + + if (pending.Count > 0) + { + await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false); + } + } + catch + { + await StopRunsAsync(runs.Values).ConfigureAwait(false); + throw; + } + + var plan = await tally.BuildAsync(_env, Destinations, effective, checkDestinations: false, CancellationToken.None).ConfigureAwait(false); + var ordered = runs.Values.OrderBy(r => r.Id).ToList(); + if (ordered.Count == 0) + { + return new ExportStart([], plan); + } + + try + { + lock (_gate) + { + _starting = false; + StartCopyJob(ordered.Select(r => r.Id).ToList(), held.Lease); + held.Lease = null; // the job owns it now + } + } + catch + { + await StopRunsAsync(ordered).ConfigureAwait(false); + throw; + } + + return new ExportStart(ordered, plan); + } + + /// + /// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a + /// paused one checks its destination first and pauses again if it still does not answer). + /// + public async Task> ResumeAsync(IReadOnlyList? runIds = null, CancellationToken ct = default) + { + EnsureIdle(); + var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false); + List chosen; + if (runIds is null) + { + chosen = unfinished.ToList(); + } + else + { + chosen = []; + foreach (var id in runIds.Distinct()) + { + var run = unfinished.FirstOrDefault(r => r.Id == id); + if (run is null) + { + _ = await _env.Storage.Exports.GetRunAsync(id, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {id} non trovato."); + throw new InvalidOperationException("Questo lavoro di copia è già finito: non c'è niente da riprendere."); + } + + chosen.Add(run); + } + } + + chosen = chosen.OrderBy(r => r.Id).ToList(); + if (chosen.Count > 0) + { + StartCopyJob(chosen.Select(r => r.Id).ToList()); + } + + return chosen; + } + + /// «Interrompi»: stops the running job and waits until its states are saved. + public async Task InterruptAsync(CancellationToken ct = default) + { + Job? job; + lock (_gate) + { + job = _job is { Task.IsCompleted: false } j ? j : null; + } + + if (job is null) + { + return; + } + + await job.Cancellation.CancelAsync().ConfigureAwait(false); + await job.Task.WaitAsync(ct).ConfigureAwait(false); + } + + /// + /// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our + /// .part files in its folders go; no other file is touched, and the copies made stay. + /// + public async Task DiscardAsync(long runId, CancellationToken ct = default) + { + if (ActiveRunIds.Contains(runId)) + { + await InterruptAsync(ct).ConfigureAwait(false); + } + + var run = await _env.Storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException($"Lavoro di copia {runId} non trovato."); + if (run.State is ExportRunState.Completed or ExportRunState.Cancelled) + { + return; + } + + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, runId, CancellationToken.None).ConfigureAwait(false); + if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false) is { } destination) + { + await ExportLeftovers.CleanAsync(_env, run, destination, ct).ConfigureAwait(false); + } + } + + /// + /// «Controlla le copie»: a job without a record (not resumable, idempotent) that looks for every Copied or + /// Superseded copy of a destination and marks «Tolto» those whose file is gone. Never touches a file. + /// + public async Task CheckCopiesAsync(long destinationId, CancellationToken ct = default) + { + EnsureIdle(); + var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata."); + if (destination.IsRetired) + { + throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da controllare."); + } + + StartJob([], (progress, token) => CheckJobAsync(destination, progress, token)); + } + + /// + /// «Riprova» of a paused destination: checks it with its probe (WP1.3). Still not writable: it stays paused with the + /// new reason, returned. Writable: the pause goes and, when no other long work runs, its paused jobs resume (oldest + /// first); otherwise they wait for «Riprendi». + /// + /// No such destination. + /// The destination was retired. + public async Task RetryDestinationAsync(long destinationId, CancellationToken ct = default) + { + var destination = await _env.Storage.Exports.GetDestinationAsync(destinationId, ct).ConfigureAwait(false) + ?? throw new KeyNotFoundException($"Destinazione di esportazione {destinationId} non trovata."); + if (destination.IsRetired) + { + throw new InvalidOperationException("Questa cartella è stata tolta: non c'è niente da riprovare."); + } + + if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem) + { + await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false); + return new ExportRetry(problem, []); + } + + await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false); + var paused = (await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)) + .Where(r => r.DestinationId == destinationId && r.State == ExportRunState.Paused) + .Select(r => r.Id) + .ToList(); + if (paused.Count == 0 || IsBusy || _env.Gate?.Busy is not null) + { + return new ExportRetry(null, []); + } + + return new ExportRetry(null, await ResumeAsync(paused, ct).ConfigureAwait(false)); + } + + /// The progress of the running job, or a snapshot of the newest job. + public async Task GetProgressAsync(CancellationToken ct = default) + { + lock (_gate) + { + if (_job is { Task.IsCompleted: false } && _current is { } current) + { + return current; + } + } + + var newest = (await _env.Storage.Exports.ListRecentRunsAsync(1, ct).ConfigureAwait(false)).FirstOrDefault(); + return newest is null + ? new ExportProgress(null, ExportPhase.Finished, 0, 0, 0, 0, null, null, new Dictionary(), _env.Clock.Now) + : await SnapshotAsync(newest, ct).ConfigureAwait(false); + } + + /// Waits for the running job (if any) to end, however it ends. + public async Task WaitAsync(CancellationToken ct = default) + { + Job? job; + Task cleanup; + lock (_gate) + { + job = _job; + cleanup = _cleanup; + } + + if (job is not null) + { + await job.Task.WaitAsync(ct).ConfigureAwait(false); + } + + await cleanup.WaitAsync(ct).ConfigureAwait(false); + } + + public async ValueTask DisposeAsync() + { + Job? job; + Task cleanup; + lock (_gate) + { + job = _job; + cleanup = _cleanup; + } + + if (job is not null) + { + await job.Cancellation.CancelAsync().ConfigureAwait(false); + await job.Task.ConfigureAwait(false); + job.Cancellation.Dispose(); + } + + await cleanup.ConfigureAwait(false); + } + + private async Task SnapshotAsync(ExportRun run, CancellationToken ct) + { + var summary = await _env.Storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false); + var destination = await _env.Storage.Exports.GetDestinationAsync(run.DestinationId, ct).ConfigureAwait(false); + var phase = run.State == ExportRunState.Running && IsBusy ? ExportPhase.Copying : ExportPhase.Finished; + return new ExportProgress( + run.Id, + phase, + summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending), + summary.Total, + 0, + 0, + null, + destination is null ? null : ExportDestinations.Label(destination), + summary.ByState, + _env.Clock.Now); + } + + private async Task CheckJobAsync(ExportDestination destination, IProgress progress, CancellationToken ct) + { + var exports = _env.Storage.Exports; + var label = ExportDestinations.Label(destination); + var counts = await exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + var total = counts.GetValueOrDefault(ExportCopyState.Copied) + counts.GetValueOrDefault(ExportCopyState.Superseded); + void Report(ExportPhase phase, int done) => + progress.Report(new ExportProgress(null, phase, done, total, 0, 0, null, label, new Dictionary(), _env.Clock.Now)); + + Report(ExportPhase.Checking, 0); + if (await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) is { } problem) + { + await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false); + Report(ExportPhase.Finished, 0); + return; + } + + await ExportPause.ClearAsync(_env, destination).ConfigureAwait(false); + var done = 0; + var removed = 0; + foreach (var state in new[] { ExportCopyState.Copied, ExportCopyState.Superseded }) + { + long after = 0; + while (true) + { + while (_env.Session.InSession) + { + Report(ExportPhase.WaitingForSession, done); + await _env.Clock.Delay(_env.SessionPoll, ct).ConfigureAwait(false); + } + + var page = await exports.ListCopiesAsync(destination.Id, state, after, 1000, ct).ConfigureAwait(false); + if (page.Count == 0) + { + break; + } + + after = page[^1].Id; + if (!await RootAnswersAsync(destination, ct).ConfigureAwait(false)) + { + await PauseCheckAsync(destination, label, ct).ConfigureAwait(false); + Report(ExportPhase.Finished, done); + return; + } + + var missing = new List(); + foreach (var copy in page) + { + ct.ThrowIfCancellationRequested(); + if (copy.RelativePath is not { } path || !FileExists(destination.RootPath, path)) + { + missing.Add(copy); + } + } + + // The disk may have gone away while the page was read (decision of 2026-11-27, §4.10): the root is asked + // again after the files and before anything is marked, and a missing file is looked for once more. + if (missing.Count > 0 && !await RootAnswersAsync(destination, ct).ConfigureAwait(false)) + { + await PauseCheckAsync(destination, label, ct).ConfigureAwait(false); + Report(ExportPhase.Finished, done); + return; + } + + var gone = missing + .Where(copy => copy.RelativePath is not { } path || !FileExists(destination.RootPath, path)) + .Select(copy => copy.Id) + .ToList(); + removed += await exports.MarkCopiesRemovedAsync(gone, _env.Clock.Now, CancellationToken.None).ConfigureAwait(false); + done += page.Count; + Report(ExportPhase.Checking, done); + } + } + + await _env.Storage.Events.AppendAsync( + new EventRecord + { + At = _env.Clock.Now, + Code = "esportazione-controllo", + Message = ExportText.CheckMessage(done, removed, destination), + Severity = removed > 0 ? EventSeverity.Warning : EventSeverity.Success, + AccountId = destination.AccountId, + }, + CancellationToken.None).ConfigureAwait(false); + Report(ExportPhase.Finished, done); + } + + /// The root of the destination is there, asked within the folder-check time (a dead share must not block). + private async Task RootAnswersAsync(ExportDestination destination, CancellationToken ct) + { + try + { + return await Task.Run(() => Directory.Exists(destination.RootPath), ct).WaitAsync(_env.FolderCheckTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return false; + } + } + + /// The disk went away during «Controlla le copie»: nothing is «Tolto» because of that, the destination pauses. + private async Task PauseCheckAsync(ExportDestination destination, string label, CancellationToken ct) + { + var problem = await Copier.CheckDestinationAsync(destination, ct).ConfigureAwait(false) ?? $"{label} non è raggiungibile."; + await ExportPause.PauseAsync(_env, destination, problem).ConfigureAwait(false); + } + + private bool FileExists(string root, string relativePath) + { + try + { + return _env.FileSystem.FileExists(LibraryLayout.FullPath(root, relativePath)); + } + catch (ArgumentException) + { + return false; + } + } + + private async Task CleanLeftoversAsync(IReadOnlyList runs) + { + foreach (var run in runs) + { + try + { + if (await _env.Storage.Exports.GetDestinationAsync(run.DestinationId).ConfigureAwait(false) is { } destination) + { + await ExportLeftovers.CleanAsync(_env, run, destination, CancellationToken.None).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // Best effort: the resume of that job cleans again. + } + } + } + + private async Task StopRunsAsync(IEnumerable runs) + { + foreach (var run in runs) + { + try + { + // The job never started: nothing was copied, there is nothing to resume. + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled, CompletedAt = _env.Clock.Now }, CancellationToken.None).ConfigureAwait(false); + await ExportRunSettings.ClearAsync(_env.Storage.Settings, run.Id, CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // RecoverAsync makes it «interrotto» at the next start. + } + } + } + + private void EnsureIdle() + { + if (IsBusy) + { + throw new InvalidOperationException(BusyText); + } + + if (_env.Gate?.Busy is { } busy) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy)); + } + } + + private void StartCopyJob(IReadOnlyList runIds, IDisposable? lease = null) => + StartJob( + runIds, + async (progress, token) => + { + var next = 0; + try + { + for (; next < runIds.Count; next++) + { + token.ThrowIfCancellationRequested(); + try + { + await Copier.CopyAsync(runIds[next], progress, token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested) + { + // Stored with the run (Interrupted, with its error); the next destination still gets its files. + LastJobError = ExportText.ErrorText(ex); + } + } + } + finally + { + // «Interrompi» (or «Annulla», or the end of Febe) stopped the job before its later destinations: those + // runs were recorded as running and nothing runs them now. They become «interrotto», resumable, as + // RecoverAsync would make them at the next start. + await InterruptQueuedAsync(runIds.Skip(next)).ConfigureAwait(false); + } + }, + lease); + + /// Runs of a stopped job that were never reached and are still recorded as running become «interrotto». + private async Task InterruptQueuedAsync(IEnumerable runIds) + { + foreach (var runId in runIds) + { + try + { + if (await _env.Storage.Exports.GetRunAsync(runId, CancellationToken.None).ConfigureAwait(false) is { State: ExportRunState.Running } run) + { + await _env.Storage.Exports.UpdateRunAsync(run with { State = ExportRunState.Interrupted, LastError = null }, CancellationToken.None).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // RecoverAsync makes it «interrotto» at the next start. + } + } + } + + /// Starts a job; is a lease of the gate already taken (the job owns it once started). + private void StartJob(IReadOnlyList runIds, Func, CancellationToken, Task> work, IDisposable? held = null) + { + lock (_gate) + { + if (_job is { Task.IsCompleted: false }) + { + throw new InvalidOperationException(BusyText); + } + + var lease = held; + if (lease is null && _env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Export, out lease, out var busy)) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value)); + } + + _job?.Cancellation.Dispose(); + var cancellation = new CancellationTokenSource(); + var reporter = new Reporter(this); + LastJobError = null; + _current = new ExportProgress(runIds.Count > 0 ? runIds[0] : null, runIds.Count > 0 ? ExportPhase.Preparing : ExportPhase.Checking, 0, 0, 0, 0, null, null, new Dictionary(), _env.Clock.Now); + var task = Task.Run(async () => + { + try + { + await work(reporter, cancellation.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + // Interrupted: the states were saved by the job. + } + catch (Exception ex) + { + LastJobError = ExportText.ErrorText(ex); + } + finally + { + try + { + var last = _current is { } c ? c with { Phase = ExportPhase.Finished, UpdatedAt = _env.Clock.Now } : null; + if (last is not null) + { + Publish(last, force: true); + } + } + finally + { + lease?.Dispose(); + } + + try + { + JobFinished?.Invoke(this, new ExportJobFinished(runIds, CopiesChanged: true)); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + // A handler failed: the job is over all the same. + } + } + }); + _job = new Job(runIds, cancellation, task); + } + } + + private void Publish(ExportProgress progress, bool force) + { + lock (_gate) + { + _current = progress; + } + + var now = Stopwatch.GetTimestamp(); + var last = Interlocked.Read(ref _lastPublished); + if (!force && Stopwatch.GetElapsedTime(last, now) < ProgressInterval) + { + return; + } + + Interlocked.Exchange(ref _lastPublished, now); + ProgressChanged?.Invoke(this, progress); + } + + private sealed record Job(IReadOnlyList RunIds, CancellationTokenSource Cancellation, Task Task); + + /// A lease of the long-work gate on its way from to the job. + private sealed class LeaseHolder + { + public IDisposable? Lease { get; set; } + } + + private sealed class Reporter(ExportService owner) : IProgress + { + private (ExportPhase, long?)? _phase; + + public void Report(ExportProgress value) + { + var key = (value.Phase, value.RunId); + var changed = _phase != key; + _phase = key; + owner.Publish(value, changed); + } + } +} diff --git a/src/Febe.Core/Export/ExportSupersession.cs b/src/Febe.Core/Export/ExportSupersession.cs new file mode 100644 index 0000000..77377a7 --- /dev/null +++ b/src/Febe.Core/Export/ExportSupersession.cs @@ -0,0 +1,36 @@ +using Febe.Core.Domain; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// «Superato» (spec §4.10): the library file of an account changed («Tieni il più grande», a slot filled again with +/// other bytes, a rebuild that found other bytes on disk), so its copies are of a file the library no longer has. The +/// copies stay where they are; they are only marked, and the new file is never copied by itself. +/// +public static class ExportSupersession +{ + /// + /// Marks the copies of the account's old file as superseded by the new one. A no-op when the old SHA-256 is null or + /// equal to the new one, or when a present file of that account still has the old SHA-256. Writes are not + /// cancellable: the library already changed. + /// + public static async Task FileChangedAsync(IFebeStorage storage, long accountId, string? oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentException.ThrowIfNullOrWhiteSpace(newSha256); + if (oldSha256 is not { Length: 64 } || newSha256.Length != 64 || string.Equals(oldSha256, newSha256, StringComparison.OrdinalIgnoreCase)) + { + return 0; + } + + var old = oldSha256.ToLowerInvariant(); + var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false); + if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State))) + { + return 0; + } + + return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false); + } +} diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs new file mode 100644 index 0000000..384dfc1 --- /dev/null +++ b/src/Febe.Core/Export/ExportText.cs @@ -0,0 +1,138 @@ +using Febe.Core.Domain; +using Febe.Core.Engine; +using Febe.Core.Storage; + +namespace Febe.Core.Export; + +/// +/// Texts of the copies to external folders for Alberto (spec §4.10, §10.4): sentence case, dots for thousands, the same +/// names everywhere. Notes are stored in export_item.note as English codes () and shown with +/// . +/// +public static class ExportText +{ + /// The codes of export_item.note. + public static class Notes + { + public const string SourceMissing = "SourceMissing"; + public const string AccountRemoved = "AccountRemoved"; + public const string Removed = "Removed"; + public const string Superseded = "Superseded"; + public const string CopiedForAnotherAccount = "CopiedForAnotherAccount"; + public const string SourceChanged = "SourceChanged"; + public const string TooLargeForFileSystem = "TooLargeForFileSystem"; + public const string NameTaken = "NameTaken"; + public const string PathTaken = "PathTaken"; + public const string NotExported = "NotExported"; + } + + /// Name of the state of a file of a job. + public static string State(ExportItemState state) => state switch + { + ExportItemState.Pending => "In attesa", + ExportItemState.Copied => "Copiato", + ExportItemState.Adopted => "Adottato", + ExportItemState.AlreadyCopied => "Già copiato", + ExportItemState.Skipped => "Saltato", + ExportItemState.Missing => "File non presente in libreria", + ExportItemState.Failed => "Non riuscito", + _ => state.ToString(), + }; + + /// Name of the state of a copy. + public static string CopyState(ExportCopyState state) => state switch + { + ExportCopyState.Copied => "Copiato", + ExportCopyState.Removed => "Tolto", + ExportCopyState.Superseded => "Superato", + ExportCopyState.Failed => "Non riuscito", + _ => state.ToString(), + }; + + /// The Italian text of a note code; null for none; an unknown code is shown as it is. + public static string? Note(string? code) => code switch + { + null or "" => null, + Notes.SourceMissing => "File non presente in libreria", + Notes.AccountRemoved => "L'account è stato rimosso", + Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)", + Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo", + Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)", + Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato", + Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta", + Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero", + Notes.PathTaken => "Percorso preso nel frattempo: riprova", + Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella", + _ => code, + }; + + /// «1 file copiato», «1.204 file copiati». + public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many; + + /// The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.» + public static string CompletionMessage(ExportRunSummary summary, ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(summary); + ArgumentNullException.ThrowIfNull(destination); + int Of(ExportItemState s) => summary.ByState.GetValueOrDefault(s); + var parts = new List { Count(Of(ExportItemState.Copied) + Of(ExportItemState.Adopted), "file copiato", "file copiati") }; + if (Of(ExportItemState.AlreadyCopied) > 0) + { + parts.Add(Count(Of(ExportItemState.AlreadyCopied), "già copiato", "già copiati")); + } + + if (Of(ExportItemState.Skipped) > 0) + { + parts.Add(Count(Of(ExportItemState.Skipped), "saltato", "saltati")); + } + + if (Of(ExportItemState.Missing) > 0) + { + parts.Add(Count(Of(ExportItemState.Missing), "non presente in libreria", "non presenti in libreria")); + } + + if (Of(ExportItemState.Failed) > 0) + { + parts.Add(Count(Of(ExportItemState.Failed), "non riuscito", "non riusciti")); + } + + return $"Copia in {ExportDestinations.Label(destination)} finita: {string.Join(", ", parts)}."; + } + + /// The event of «Controlla le copie». + public static string CheckMessage(int checkedCopies, int removed, ExportDestination destination) + { + ArgumentNullException.ThrowIfNull(destination); + var text = $"Controllate {ItalianText.Number(checkedCopies)} copie in {ExportDestinations.Label(destination)}: "; + return text + (removed == 0 ? "ci sono tutte." : $"{Count(removed, "non c'è più (tolta)", "non ci sono più (tolte)")}."); + } + + /// The space is not enough for the next file (decision D16). + public static string NoSpace(ExportDestination destination, long free, string file, long bytes) => + $"Su {ExportDestinations.Label(destination)} restano {ItalianText.Bytes(free)}: per copiare {file} ({ItalianText.Bytes(bytes)}) serve più spazio, " + + $"con un margine di {ItalianText.Bytes(ExportSpace.Margin)}. Libera spazio, poi riprendi."; + + /// The disk said it is full. + public static string DiskFull(ExportDestination destination) => + $"Su {ExportDestinations.Label(destination)} non c'è più spazio: libera spazio, poi riprendi."; + + /// A file over the FAT32 limit. + public static string TooLarge(long bytes) => + $"Il file pesa {ItalianText.Bytes(bytes)}: su un disco FAT32 un file non può superare 4 GB."; + + /// The destination was retired while a job used it. + public const string RetiredDestination = "La cartella è stata tolta."; + + /// An error for Alberto, without paths of secrets: the message of a file error, or a generic sentence. + public static string ErrorText(Exception ex) + { + ArgumentNullException.ThrowIfNull(ex); + return ex switch + { + ExportFolderException folder => folder.Message, + IOException io => $"Errore di lettura o scrittura: {io.Message}", + UnauthorizedAccessException => "Febe non ha il permesso di scrivere nella cartella: controlla i permessi.", + _ => $"Errore inatteso ({ex.GetType().Name}): riprova; se si ripete, segnalalo.", + }; + } +} diff --git a/src/Febe.Core/Export/FolderIdentity.cs b/src/Febe.Core/Export/FolderIdentity.cs new file mode 100644 index 0000000..d07212d --- /dev/null +++ b/src/Febe.Core/Export/FolderIdentity.cs @@ -0,0 +1,162 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Febe.Core.Export; + +/// +/// Where a folder really is, whatever name it was reached by: the folder check compares these, read-only, besides its +/// probe file (decision of 2026-11-27, widening spec §4.10 «Cartelle rifiutate»). +/// +/// Windows: the final path of the folder (GetFinalPathNameByHandle on a handle opened without any access +/// right), which resolves junctions, symbolic links, subst drives and mapped drives (to their UNC path); +/// Linux: the real path (realpath, every symbolic link resolved), then, through the mount table, the +/// device of its file system and the folder of that file system it is (a bind mount of a folder of the library in Docker +/// is the same device, inside the root of the library's mount). +/// +/// +/// The device of the file system (major:minor), or null: then is a full path. +/// With a device, the folder within its file system ('/' separated); else the real full path. +internal sealed record FolderLocation(string? Device, string Path) +{ + /// This folder is . + public bool IsSame(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.Same(Path, other.Path) : string.Equals(Path, other.Path, ExportPaths.PathComparison)); + + /// This folder is or inside it. + public bool IsSameOrInside(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.IsSameOrInside(Path, other.Path) : InsidePosix(Path, other.Path)); + + private bool Comparable(FolderLocation other) => string.Equals(Device, other.Device, StringComparison.Ordinal); + + private static bool InsidePosix(string path, string folder) + { + if (string.Equals(path, folder, ExportPaths.PathComparison) || folder == "/") + { + return true; + } + + return path.StartsWith(folder.TrimEnd('/') + "/", ExportPaths.PathComparison); + } +} + +/// Finds the of a folder (see there). +internal static class FolderIdentity +{ + private const uint FileShareAll = 0x1 | 0x2 | 0x4; + private const uint OpenExisting = 3; + private const uint FileFlagBackupSemantics = 0x02000000; + + /// The location of an existing folder, or null when it cannot be told (missing, unreadable). + public static FolderLocation? Locate(string fullPath, IExportMounts mounts) => Locate(fullPath, mounts, out _); + + /// The location of an existing folder and its real path, or null when it cannot be told. + public static FolderLocation? Locate(string fullPath, IExportMounts mounts, out string? real) + { + ArgumentNullException.ThrowIfNull(mounts); + real = RealPath(fullPath); + if (real is null) + { + return null; + } + + if (mounts.FindContaining(real) is { Device: { Length: > 0 } device } mount) + { + var relative = Path.GetRelativePath(mount.MountPoint, real).Replace('\\', '/'); + var root = mount.Root.TrimEnd('/'); + return new FolderLocation(device, relative == "." ? (root.Length == 0 ? "/" : root) : $"{root}/{relative}"); + } + + return new FolderLocation(null, real); + } + + /// The location of what a mount shows, when its device is known. + public static FolderLocation? Of(ExportMount mount) => + mount.Device is { Length: > 0 } device ? new FolderLocation(device, mount.Root.Length > 1 ? mount.Root.TrimEnd('/') : mount.Root) : null; + + /// The path of the folder with every link (and on Windows every drive alias) resolved, or null. + internal static string? RealPath(string fullPath) + { + try + { + if (!Directory.Exists(fullPath)) + { + return null; + } + + if (OperatingSystem.IsWindows()) + { + return FinalPathWindows(fullPath); + } + + return RealPathUnix(fullPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException + or EntryPointNotFoundException or DllNotFoundException) + { + return null; + } + } + + private static string? FinalPathWindows(string fullPath) + { + // No access right is asked: only the identity of the folder is read, and nothing is ever written there. + using var handle = CreateFileW(fullPath, 0, FileShareAll, IntPtr.Zero, OpenExisting, FileFlagBackupSemantics, IntPtr.Zero); + if (handle.IsInvalid) + { + return null; + } + + var buffer = new char[1024]; + var length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0); + if (length >= buffer.Length) + { + buffer = new char[length + 1]; + length = GetFinalPathNameByHandleW(handle, buffer, (uint)buffer.Length, 0); + } + + if (length == 0 || length >= buffer.Length) + { + return null; + } + + var path = new string(buffer, 0, (int)length); + if (path.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase)) + { + path = @"\\" + path[8..]; + } + else if (path.StartsWith(@"\\?\", StringComparison.Ordinal)) + { + path = path[4..]; + } + + return ExportPaths.Trim(path); + } + + private static string? RealPathUnix(string fullPath) + { + var resolved = RealPathNative(fullPath, IntPtr.Zero); + if (resolved == IntPtr.Zero) + { + return null; + } + + try + { + return Marshal.PtrToStringUTF8(resolved) is { Length: > 0 } path ? ExportPaths.Trim(path) : null; + } + finally + { + Free(resolved); + } + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFileW(string fileName, uint desiredAccess, uint shareMode, IntPtr securityAttributes, uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern uint GetFinalPathNameByHandleW(SafeFileHandle file, [Out] char[] filePath, uint length, uint flags); + + [DllImport("libc", EntryPoint = "realpath", SetLastError = true)] + private static extern IntPtr RealPathNative([MarshalAs(UnmanagedType.LPUTF8Str)] string path, IntPtr resolved); + + [DllImport("libc", EntryPoint = "free")] + private static extern void Free(IntPtr pointer); +} diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 1a75ac2..e053946 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -1,5 +1,6 @@ using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; @@ -545,6 +546,9 @@ public sealed class ImportCopier(ImportEnvironment env) media.State, env.Clock.Now, none).ConfigureAwait(false); + + // The copies of the old file in external folders are now «Superato» (spec §4.10): never copied again by themselves. + await ExportSupersession.FileChangedAsync(env.Storage, account.Id, media.Sha256, saved.Sha256, env.Clock.Now, none).ConfigureAwait(false); await context.Ingest.TryAppendJournalAsync(entry.Id, none).ConfigureAwait(false); if (entry.InstagramId is null && string.IsNullOrWhiteSpace(entry.Code) && !string.Equals(oldRelative, saved.RelativePath, StringComparison.Ordinal)) { diff --git a/src/Febe.Core/Import/ImportEnvironment.cs b/src/Febe.Core/Import/ImportEnvironment.cs index 25e8e00..3018f48 100644 --- a/src/Febe.Core/Import/ImportEnvironment.cs +++ b/src/Febe.Core/Import/ImportEnvironment.cs @@ -58,6 +58,12 @@ public sealed record ImportEnvironment /// Reading, hashing and deleting source files. public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance; + /// + /// The gate shared with the export and the rebuild (spec §4.10: they never run together). Null: no other long work + /// to keep out (tests, the import alone). + /// + public LongWorkGate? Gate { get; init; } + /// Files analysed at the same time (hashing and decoding). public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4); diff --git a/src/Febe.Core/Import/ImportService.cs b/src/Febe.Core/Import/ImportService.cs index 0c17708..44d543d 100644 --- a/src/Febe.Core/Import/ImportService.cs +++ b/src/Febe.Core/Import/ImportService.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Storage; @@ -283,6 +284,12 @@ public sealed class ImportService : IAsyncDisposable { throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila."); } + + // Checked up front too, so a refused start records nothing; StartJob takes the gate for real. + if (_env.Gate?.Busy is { } busy) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy)); + } } private void StartJob(long runId, ImportPhase phase, Func, CancellationToken, Task> work) @@ -294,6 +301,12 @@ public sealed class ImportService : IAsyncDisposable throw new InvalidOperationException("C'è già un'importazione al lavoro: aspetta che finisca o interrompila."); } + IDisposable? lease = null; + if (_env.Gate is { } gate && !gate.TryEnter(LongWorkKind.Import, out lease, out var busy)) + { + throw new InvalidOperationException(LongWorkGate.BusyMessage(LongWorkKind.Import, busy!.Value)); + } + _job?.Cancellation.Dispose(); var cancellation = new CancellationTokenSource(); var reporter = new Reporter(this); @@ -322,6 +335,10 @@ public sealed class ImportService : IAsyncDisposable { // The database is closing: nothing to publish. } + finally + { + lease?.Dispose(); + } } }); _job = new Job(runId, phase, cancellation, task); diff --git a/src/Febe.Core/Library/DownloadDuplicateReview.cs b/src/Febe.Core/Library/DownloadDuplicateReview.cs index 81ce928..75e13e6 100644 --- a/src/Febe.Core/Library/DownloadDuplicateReview.cs +++ b/src/Febe.Core/Library/DownloadDuplicateReview.cs @@ -1,5 +1,6 @@ using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -174,6 +175,11 @@ public sealed class DownloadDuplicateReview( if (ok) { removed++; + if (decision == DuplicateDecision.KeepLarger && loser == item.Existing && item.Candidate.Sha256 is { } larger) + { + // «Tieni il più grande» replaced the file already there: its copies in external folders are «Superato». + await ExportSupersession.FileChangedAsync(storage, item.Existing.AccountId, item.Existing.Sha256, larger, clock.Now, CancellationToken.None).ConfigureAwait(false); + } } else if (problem is not null) { diff --git a/src/Febe.Core/Library/LibraryIngest.cs b/src/Febe.Core/Library/LibraryIngest.cs index cc883d0..45b8dc3 100644 --- a/src/Febe.Core/Library/LibraryIngest.cs +++ b/src/Febe.Core/Library/LibraryIngest.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Globalization; using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -319,6 +320,10 @@ public sealed class LibraryIngest( throw new EntryDeletedException(); } + // A slot that had other bytes (a rebuild left the journal's SHA-256 on a file to download again, an import + // filled it): the copies of the old file in external folders are now «Superato» (spec §4.10). + await ExportSupersession.FileChangedAsync(storage, account.Id, media.Sha256, saved.Sha256, now, CancellationToken.None).ConfigureAwait(false); + var pairs = new List(); if (hash is { } h && hashIndex is not null) { diff --git a/src/Febe.Core/Library/LibraryRebuilder.cs b/src/Febe.Core/Library/LibraryRebuilder.cs index 341893e..a7915aa 100644 --- a/src/Febe.Core/Library/LibraryRebuilder.cs +++ b/src/Febe.Core/Library/LibraryRebuilder.cs @@ -1,6 +1,7 @@ using System.Security.Cryptography; using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; namespace Febe.Core.Library; @@ -202,6 +203,14 @@ public sealed class LibraryRebuilder( } await FlushAsync(account, batch, report, ct).ConfigureAwait(false); + + // Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10). + foreach (var (old, now) in report.Changed) + { + await ExportSupersession.FileChangedAsync(storage, account.Id, old, now, clock.Now, CancellationToken.None).ConfigureAwait(false); + } + + report.Changed.Clear(); CountUntracked(folder, allItems, report); } @@ -554,6 +563,7 @@ public sealed class LibraryRebuilder( report.FilesVerified++; if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal)) { + report.Changed.Add((media.Sha256, check.Sha256)); report.HashMismatches++; report.Note($"Contenuto diverso da quello registrato: {file.Path}"); } @@ -738,6 +748,9 @@ public sealed class LibraryRebuilder( public int InvalidLines { get; set; } + /// (journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato». + public List<(string Old, string New)> Changed { get; } = []; + public void Note(string note) { if (_notes.Count < MaxNotes) diff --git a/src/Febe.Core/Library/MountInfo.cs b/src/Febe.Core/Library/MountInfo.cs new file mode 100644 index 0000000..bda7e95 --- /dev/null +++ b/src/Febe.Core/Library/MountInfo.cs @@ -0,0 +1,117 @@ +namespace Febe.Core.Library; + +/// +/// One line of /proc/self/mountinfo (proc(5)): unlike /proc/self/mounts it says which folder of its file +/// system a mount shows (: / when the mount is the root of that file system) and gives the exact +/// mount point, which the export needs for /esporta (spec §4.10, §11). +/// +/// Mount id. +/// Id of the parent mount. +/// Folder of the file system shown at the mount point (/: its root). +/// Where it is mounted, unescaped. +/// Per-mount options (rw, ro, noatime…). +/// File system type (ext4, vfat, cifs…). +/// Mount source (/dev/sdb1, //server/share…), unescaped. +/// The device of the file system, major:minor (field 3): two mounts with the same device show +/// folders of one file system, so tells whether one is inside the other. +public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList Options, string FileSystemType, string Source, string? Device = null) +{ + /// The mount is read-only (ro, as for a Docker volume mounted with :ro). + public bool ReadOnly => Options.Contains("ro", StringComparer.Ordinal); +} + +/// Reads /proc/self/mountinfo. +public static class MountInfoTable +{ + private const string MountInfoPath = "/proc/self/mountinfo"; + + /// + /// Parses the content of /proc/self/mountinfo: fields 0-5, then optional fields up to the separator «-», then + /// file system type and source. Malformed lines are skipped; nothing throws. + /// + public static IReadOnlyList Parse(string content) + { + ArgumentNullException.ThrowIfNull(content); + var entries = new List(); + foreach (var raw in content.Split('\n')) + { + var fields = raw.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (fields.Length < 9 + || !int.TryParse(fields[0], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var id) + || !int.TryParse(fields[1], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var parent)) + { + continue; + } + + var separator = Array.IndexOf(fields, "-", 6); + if (separator < 0 || separator + 2 >= fields.Length) + { + continue; + } + + var root = MountTable.Unescape(fields[3]); + var point = MountTable.Unescape(fields[4]); + if (!root.StartsWith('/') || !point.StartsWith('/')) + { + continue; + } + + entries.Add(new MountInfoEntry( + id, + parent, + root, + point, + fields[5].Split(',', StringSplitOptions.RemoveEmptyEntries), + fields[separator + 1], + MountTable.Unescape(fields[separator + 2]), + fields[2])); + } + + return entries; + } + + /// + /// The mount that holds a path: the longest mount point that is the path itself or one of its parents (ordinal + /// comparison; a later mount over the same point wins, as the kernel shows the last one). Null when none matches. + /// + public static MountInfoEntry? FindContaining(IReadOnlyList mounts, string fullPath) + { + ArgumentNullException.ThrowIfNull(mounts); + ArgumentNullException.ThrowIfNull(fullPath); + var path = fullPath.Length > 1 ? fullPath.TrimEnd('/') : fullPath; + MountInfoEntry? best = null; + var bestLength = -1; + foreach (var mount in mounts) + { + var point = mount.MountPoint.Length > 1 ? mount.MountPoint.TrimEnd('/') : mount.MountPoint; + var contains = point == "/" + || string.Equals(path, point, StringComparison.Ordinal) + || path.StartsWith(point + "/", StringComparison.Ordinal); + if (contains && point.Length >= bestLength) + { + best = mount; + bestLength = point.Length; + } + } + + return best; + } + + /// The content of /proc/self/mountinfo on Linux; null elsewhere or when it cannot be read. + public static string? ReadProcSelf() + { + if (!OperatingSystem.IsLinux()) + { + return null; + } + + try + { + return File.Exists(MountInfoPath) ? File.ReadAllText(MountInfoPath) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } +} diff --git a/src/Febe.Core/Library/NoReplaceRename.cs b/src/Febe.Core/Library/NoReplaceRename.cs new file mode 100644 index 0000000..895570b --- /dev/null +++ b/src/Febe.Core/Library/NoReplaceRename.cs @@ -0,0 +1,108 @@ +using System.Runtime.InteropServices; + +namespace Febe.Core.Library; + +/// What did. +internal enum NoReplaceOutcome +{ + /// The file has its new name. + Moved, + + /// The new name exists: nothing changed. + Taken, + + /// The file system cannot do it atomically: nothing changed, the caller checks and moves. + Unsupported, +} + +/// +/// An atomic rename that never replaces an existing name, on Linux and the other Unix systems (rule 12: Febe never +/// overwrites a file). On Unix File.Move(overwrite: false) checks and then calls rename(2), which replaces: another +/// program, or another Febe writing to the same folder (spec §4.10 «due istanze sulla stessa cartella»), could create the +/// name in between. Only the platform's own C library is called (BCL interop, no external component). +/// +/// Linux: renameat2(…, RENAME_NOREPLACE); EEXIST means the name is taken; +/// without it (an older kernel, a file system that refuses the flag, another Unix): link then +/// unlink of the temporary name, where link refuses an existing name with EEXIST; +/// without hard links either (vfat, some CIFS mounts): . +/// +/// Not for Windows, where MoveFileEx without MOVEFILE_REPLACE_EXISTING already refuses an existing name. +/// +internal static class NoReplaceRename +{ + private const int AtFdCwd = -100; + private const uint RenameNoReplace = 1; + private const int Eexist = 17; // the same value on Linux, macOS and the BSDs + + private static volatile bool _noRenameAt2; + private static volatile bool _noLink; + + /// Renames to unless that name exists. + public static NoReplaceOutcome TryMove(string source, string destination) + { + ArgumentException.ThrowIfNullOrEmpty(source); + ArgumentException.ThrowIfNullOrEmpty(destination); + if (OperatingSystem.IsWindows()) + { + return NoReplaceOutcome.Unsupported; + } + + if (OperatingSystem.IsLinux() && !_noRenameAt2) + { + try + { + if (RenameAt2(AtFdCwd, source, AtFdCwd, destination, RenameNoReplace) == 0) + { + return NoReplaceOutcome.Moved; + } + + if (Marshal.GetLastPInvokeError() == Eexist) + { + return NoReplaceOutcome.Taken; + } + + // EINVAL (the file system refuses the flag), ENOSYS (an older kernel) or another error: try a link. + } + catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException) + { + _noRenameAt2 = true; // a C library without renameat2 + } + } + + if (_noLink) + { + return NoReplaceOutcome.Unsupported; + } + + try + { + if (Link(source, destination) == 0) + { + _ = Unlink(source); // when this fails the caller's clean-up removes the temporary name + return NoReplaceOutcome.Moved; + } + + // EPERM, ENOTSUP, EXDEV…: no hard links here. The caller checks and moves, and reports a real error itself. + return Marshal.GetLastPInvokeError() == Eexist ? NoReplaceOutcome.Taken : NoReplaceOutcome.Unsupported; + } + catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException) + { + _noLink = true; + return NoReplaceOutcome.Unsupported; + } + } + + [DllImport("libc", EntryPoint = "renameat2", SetLastError = true)] + private static extern int RenameAt2( + int oldDirectory, + [MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath, + int newDirectory, + [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath, + uint flags); + + [DllImport("libc", EntryPoint = "link", SetLastError = true)] + private static extern int Link([MarshalAs(UnmanagedType.LPUTF8Str)] string oldPath, [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath); + + [DllImport("libc", EntryPoint = "unlink", SetLastError = true)] + private static extern int Unlink([MarshalAs(UnmanagedType.LPUTF8Str)] string path); +} diff --git a/src/Febe.Core/Library/SafeFileWriter.cs b/src/Febe.Core/Library/SafeFileWriter.cs index fc4c65c..244e9f9 100644 --- a/src/Febe.Core/Library/SafeFileWriter.cs +++ b/src/Febe.Core/Library/SafeFileWriter.cs @@ -27,6 +27,21 @@ public sealed record SafeWriteOptions /// Bytes written so far. public IProgress? Progress { get; init; } + + /// + /// The root folder must already exist: before anything is created (spec §4.10 + /// «La radice di una destinazione non si crea mai»: a missing disk or share must not become a local folder). + /// Subfolders are still created. The root could vanish between the check and the creation of a subfolder: on Windows + /// a missing drive or share throws anyway, and in Docker a mount cannot vanish inside a running container. + /// + public bool RequireExistingRoot { get; init; } + + /// + /// After the flush, read the temporary file back from the disk and compare its SHA-256 with the one computed while + /// writing, before the final name is decided (copies to external disks, spec §4.10). On a mismatch the temporary file + /// is removed and an says so. + /// + public bool VerifyFromDisk { get; init; } } /// The content exceeded ; nothing was kept. @@ -47,6 +62,24 @@ public sealed class FileTooLargeException : IOException } } +/// The root folder of a write with does not exist; nothing was created. +public sealed class ExportRootMissingException : DirectoryNotFoundException +{ + public ExportRootMissingException() + { + } + + public ExportRootMissingException(string message) + : base(message) + { + } + + public ExportRootMissingException(string message, Exception innerException) + : base(message, innerException) + { + } +} + /// /// Writes library files safely (spec §6.5 point 4, rule 12): /// @@ -136,6 +169,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL options ??= new SafeWriteOptions(); var root = Path.GetFullPath(rootFolder); var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory); + if (options.RequireExistingRoot && !Directory.Exists(root)) + { + throw new ExportRootMissingException($"La cartella {root} non c'è: Febe non la crea, perché un disco o una condivisione assente non deve diventare una cartella locale."); + } + Directory.CreateDirectory(tempFolder); var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix); using var reservation = ReserveTemporaryFile(tempPath); @@ -144,6 +182,10 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL { var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); + if (options.VerifyFromDisk) + { + await VerifyFromDiskAsync(tempPath, digest, ct).ConfigureAwait(false); + } var desired = await decide(digest, ct).ConfigureAwait(false); if (desired is null) @@ -247,6 +289,22 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset())); } + /// Reads the temporary file back and compares its SHA-256 with the one computed while writing. + private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct) + { + string onDisk; + await using (var stream = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + onDisk = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false)); + } + + if (!string.Equals(onDisk, digest.Sha256, StringComparison.Ordinal)) + { + TryDelete(tempPath); // our own temporary file: the caller's finally would remove it too + throw new IOException("La copia scritta sul disco non corrisponde: il disco potrebbe avere problemi."); + } + } + /// Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root. private static List Segments(string relativePath) { @@ -272,11 +330,33 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); // On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces: - // two writers of this process could overwrite each other. The check and the rename are therefore done under - // one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name. + // another writer (of this process, another Febe on the same export folder, another program) could take the + // name in between. On Unix the move is therefore an atomic rename that refuses an existing name + // (NoReplaceRename); only where the file system cannot do that, the check and the move are done under one + // lock, which still keeps the writers of this process apart. On Windows the move itself refuses an existing + // name. lock (MoveGate) { - if (File.Exists(finalPath) || Directory.Exists(finalPath)) + if (Directory.Exists(finalPath)) + { + continue; + } + + if (!OperatingSystem.IsWindows()) + { + var outcome = NoReplaceRename.TryMove(tempPath, finalPath); + if (outcome == NoReplaceOutcome.Moved) + { + return finalPath; + } + + if (outcome == NoReplaceOutcome.Taken) + { + continue; + } + } + + if (File.Exists(finalPath)) { continue; } diff --git a/src/Febe.Core/Storage/IExportStore.cs b/src/Febe.Core/Storage/IExportStore.cs index 77f3241..c8f1b81 100644 --- a/src/Febe.Core/Storage/IExportStore.cs +++ b/src/Febe.Core/Storage/IExportStore.cs @@ -1,4 +1,5 @@ using Febe.Core.Domain; +using Febe.Core.Export; namespace Febe.Core.Storage; @@ -169,6 +170,108 @@ public interface IExportStore /// Removes a job with its items. Only records: copies stay. Task DeleteRunAsync(long runId, CancellationToken ct = default); + + // Tappa E2: the copies to external folders ---------------------------------------------------------------------- + + /// Every recorded «Esporta questo account», in one read: only accounts with a row (absent = the default). + Task> ListAccountExportSwitchesAsync(CancellationToken ct = default); + + /// + /// The newest Superseded or Removed row of (destination, account) whose is + /// this SHA-256: the library file that took the place of a copied one, never copied again by itself. + /// + Task FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default); + + /// + /// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general + /// folder or the own folder of an account still in Febe), of an account still in Febe; with + /// , of an account other than that one, so a newer row of the account itself never + /// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»). + /// + Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default); + + /// + /// The state of whole copies (, ) of (account, + /// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row + /// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256 + /// (). Pairs without any are absent. + /// + Task> GetCopyStatesAsync( + long destinationId, + IReadOnlyCollection<(long AccountId, string Sha256)> keys, + CancellationToken ct = default); + + /// «Controlla le copie»: Copied or Superseded rows become Removed («Tolto», state time ) in one transaction. Returns the rows changed. + Task MarkCopiesRemovedAsync(IReadOnlyList copyIds, DateTimeOffset at, CancellationToken ct = default); + + /// + /// The library files of a «Copia in…», by media id, a page at a time (after ), present + /// or not: the plan decides. An account gives the files of its entries in the library (visible states); a filter + /// the files of its entries (with «Tutte le foto», only the files it shows). + /// + Task> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default); + + /// Jobs for the Dashboard: newest first, at most . + Task> ListRecentRunsAsync(int limit, CancellationToken ct = default); + + /// + /// The mark of each tile of a page (decision D3 of tappa E2): of the files of the entry that are due (present, of an + /// account with «Esporta questo account» on, a destination and a content type it takes), how many are copied in + /// the account's effective destination. Entries without due files are absent. + /// + Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default); + + /// + /// As , with the numbers behind the mark (the «1/3» of «Copiato in parte»): the due + /// files of each entry and how many of them are copied. Entries without due files are absent. + /// + Task> GetEntryCopyCountsAsync(IReadOnlyList entryIds, CancellationToken ct = default); + + /// The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent. + Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default); + + /// The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2). + Task CountAccountFilesAsync(long accountId, CancellationToken ct = default); +} + +/// A library file a «Copia in…» may copy (one row per media, with what the plan needs of its entry). +public sealed record ExportCandidate( + long MediaId, + long EntryId, + long AccountId, + EntryKind EntryKind, + MediaKind MediaKind, + MediaState State, + string? Sha256, + long? Bytes, + string? RelativePath, + int Position, + bool InHighlight); + +/// The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato». +public enum ExportMark +{ + None, + Partly, + Copied, +} + +/// The due files of an entry and how many are copied (decision D3 of tappa E2). +public sealed record ExportEntryCopies(int Due, int Copied) +{ + /// «Non ancora copiato» (none), «Copiato in parte», «Copiato». + public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly; +} + +/// Counts of the due files of an account (decision D3 of tappa E2). +/// Files that go to the account's effective destination. +/// Due files «Copia in…» would copy: neither copied nor «Tolti o superati» (failed ones included). +/// Due files whose copy was removed from the destination or superseded: never copied again by themselves. +/// Due files whose last copy failed (also counted in ). +public sealed record ExportAccountCounts(int Due, int NotCopied, int RemovedOrSuperseded, int Failed) +{ + /// Due files copied. + public int Copied => Due - NotCopied - RemovedOrSuperseded; } /// A page of the items of an export job. diff --git a/src/Febe.Core/Storage/LibraryQueries.cs b/src/Febe.Core/Storage/LibraryQueries.cs index b180f76..f78171e 100644 --- a/src/Febe.Core/Storage/LibraryQueries.cs +++ b/src/Febe.Core/Storage/LibraryQueries.cs @@ -30,6 +30,22 @@ public enum LibraryKindFilter Posts, } +/// +/// The «Copie» filter (spec §4.6, §4.10), over the files that are due (decision D3 of tappa E2): «Non ancora copiati», +/// «Copiati», «Tolti o superati». Null: «Tutti». +/// +public enum LibraryCopiesFilter +{ + /// «Non ancora copiati»: an entry with a due file that «Copia in…» would copy (a failed copy included). + NotCopied, + + /// «Copiati»: an entry whose due files are all copied in their effective destination. + Copied, + + /// «Tolti o superati»: an entry with a due file whose copy was removed or superseded (never copied again by itself). + RemovedOrSuperseded, +} + /// Filters of the library mosaic and of the account tabs (spec §4.6). public sealed record LibraryFilter { @@ -54,6 +70,9 @@ public sealed record LibraryFilter /// Entry states shown. Null means (entries with files). public IReadOnlyList? States { get; init; } + + /// «Copie» (null: «Tutti»). With «Tutte le foto» it applies to each file. + public LibraryCopiesFilter? Copies { get; init; } } /// diff --git a/src/Febe.Data/Migrations/0004_esportazione_filtro.sql b/src/Febe.Data/Migrations/0004_esportazione_filtro.sql new file mode 100644 index 0000000..bac0423 --- /dev/null +++ b/src/Febe.Data/Migrations/0004_esportazione_filtro.sql @@ -0,0 +1,8 @@ +-- Febe, schema version 4: the «Copie» filter of the library (tappa E2 of 0.3.0, issue #58; spec §4.6, §4.10, §8.3). +-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner. +-- Only an index is added: no table, column or data changes. + +-- The «Copie» filter joins the copies of the destinations in use to the files of the library by SHA-256, for the list +-- of the entries that have a copy («Copiati»): with the entry in the index the join never reads the row of the file. +-- Over 200,000 entries the window of «Copiati» took 249 ms without it, at the bound of 250 ms (docs/decisioni.md). +CREATE INDEX ix_media_sha256_entry ON media (sha256, entry_id) WHERE sha256 IS NOT NULL; diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index f41213f..fa2cd42 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -343,13 +343,16 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore // in SQL, no sort, and the day bounds are computed once per day rather than once per entry. var command = c.Command(string.Empty); var files = mode == MosaicMode.Files; - var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true); var counts = files ? FileCounts(c, filter) : null; + // With the counts of every entry the «Copie» term of the entries adds nothing (an entry without files + // of the class counts 0) and would test each file a second time, once per entry. + var entries = !files ? filter : counts is null ? EntriesOfFiles(filter) : EntriesOfFiles(filter) with { Copies = null }; + var where = BuildWhere(c, command, entries, aggregate: true, files: files); var perEntry = files && counts is null; command.CommandText = !files ? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at" : perEntry - ? $"SELECT e.published_at, {FilesOfEntry(filter)} FROM entry e WHERE {where} ORDER BY e.published_at" + ? $"SELECT e.published_at, {FilesOfEntry(c, filter)} FROM entry e WHERE {where} ORDER BY e.published_at" : $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at"; var days = new List(); long dayStart = long.MaxValue, dayEnd = long.MinValue; @@ -417,15 +420,25 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore // --------------------------------------------------------------------------------------------- «Tutte le foto» - /// The files of «Tutte le foto» on media m: those in the library, of the kind of «Foto» or «Video». - private static string FileTerms(LibraryFilter filter) => + /// + /// The files of «Tutte le foto» on media m: those in the library, of the kind of «Foto» or «Video», and of the + /// class of the «Copie» filter. With «Copie» the term reads the entry e of the file too (account and kind), so + /// the caller must have it in scope (). + /// + /// The connection (for the export tables of «Copie»). + /// The filter. + /// The terms are read on every file of the library (the counts per entry): see ExportFilterSql.FileTerm. + internal static string FileTerms(SqliteConnection c, LibraryFilter filter, bool bulk = false) => // The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index. "+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch { LibraryKindFilter.Photos => " AND m.kind = 'Photo'", LibraryKindFilter.Videos => " AND m.kind = 'Video'", _ => string.Empty, - }; + } + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty); + + /// The file terms of this filter read the entry of the file (the «Copie» filter). + private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null; /// /// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a @@ -439,7 +452,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore return null; } - using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM media m WHERE {FileTerms(filter)} GROUP BY m.entry_id"); + var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m"; + using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter, bulk: true)} GROUP BY m.entry_id"); var counts = new Dictionary(); using var r = command.ExecuteReader(); while (r.Read()) @@ -459,8 +473,8 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter; /// A correlated count of the files of «Tutte le foto» of the entry e. - private static string FilesOfEntry(LibraryFilter filter) => - $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})"; + private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) => + $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(c, filter)})"; /// /// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as @@ -575,7 +589,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore private static List<(long Id, long PublishedAt)> EntryKeys(SqliteConnection c, LibraryFilter filter, LibraryCursor? cursor, bool newer, bool inclusive, int limit) { using var command = c.Command(string.Empty); - var where = BuildWhere(c, command, filter); + var where = BuildWhere(c, command, filter, files: true); var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}"); if (cursor is { } at) { @@ -607,8 +621,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore { using var command = c.Command(string.Empty); var list = command.AddList("f", chunk); + var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m"; command.CommandText = "SELECT m.entry_id, m.id, m.position, m.kind, m.width, m.height, m.duration_ms, m.sha256, m.has_thumbnail " - + $"FROM media m WHERE m.entry_id IN ({list}) AND {FileTerms(filter)} ORDER BY m.entry_id, m.position"; + + $"FROM {from} WHERE m.entry_id IN ({list}) AND {FileTerms(c, filter)} ORDER BY m.entry_id, m.position"; using var r = command.ExecuteReader(); while (r.Read()) { @@ -638,11 +653,16 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older) { using var command = c.Command(string.Empty); - var where = BuildWhere(c, command, filter); - var terms = FileTerms(filter); + var where = BuildWhere(c, command, filter, files: true); + var terms = FileTerms(c, filter); + var position = older ? ">" : "<"; + // With «Copie» the file terms read the entry: the first branch then joins it instead of testing it apart. + var first = NeedsEntry(filter) + ? $"SELECT EXISTS (SELECT 1 FROM media m JOIN entry e ON e.id = m.entry_id WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} AND {where}) " + : $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {position} @xn AND {terms} " + + $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "; command.CommandText = - $"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} " - + $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) " + first + $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) " + $"AND EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {terms}))"; command.With("@xp", Sql.Time(cursor.PublishedAt)).With("@xi", cursor.EntryId).With("@xn", (long)cursor.Position); @@ -730,6 +750,13 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore } /// The WHERE clause of a library filter on entry e; parameters are added to . + /// The connection (for the accounts of a search and the export tables of «Copie»). + /// The command that gets the parameters. + /// The filter. + /// + /// «Tutte le foto»: «Copie» keeps an entry when one of its files is of the chosen class, rather than judging the entry + /// as a whole (all its due files copied, for «Copiati»). + /// /// /// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and /// «Video» then test the key of each post, on a covering index, against one list of the entries that have such @@ -738,7 +765,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore /// hundred posts in index order. /// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two. /// - internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false) + internal static string BuildWhere(SqliteConnection c, SqliteCommand command, LibraryFilter filter, bool aggregate = false, bool files = false) { var byList = aggregate && filter.AccountIds is not { Count: > 0 }; // The unary + on kind and key keeps SQLite on a covering index of entry (kind, state and account in the index): @@ -790,6 +817,12 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore command.With("@prov", Sql.Enum(provenance)); } + if (filter.Copies is { } copies) + { + var export = ExportFilterSql.Load(c); + parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies, byList)); + } + var term = TextSearch.Normalize(filter.Search); if (term.Length > 0) { diff --git a/src/Febe.Data/Stores/ExportFilterSql.cs b/src/Febe.Data/Stores/ExportFilterSql.cs new file mode 100644 index 0000000..82983b4 --- /dev/null +++ b/src/Febe.Data/Stores/ExportFilterSql.cs @@ -0,0 +1,310 @@ +using System.Globalization; +using System.Text; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Microsoft.Data.Sqlite; + +namespace Febe.Data.Stores; + +/// +/// What the «Copie» filter, the tile marks and the account counts need of the export tables, read once per query: +/// the destinations in use, the switches that are off, «Una copia sola», and whether any copy, failure or removed or +/// superseded row exists at all (so the common cases pay nothing for what is not there). +/// +internal sealed record ExportFilterContext( + long? GeneralId, + ContentTypes GeneralTypes, + IReadOnlyList<(long AccountId, long DestinationId, ContentTypes Types)> Own, + IReadOnlySet Off, + SamePostCopies SamePost, + bool HasCopies, + bool HasFailed, + bool HasHistory) +{ + public bool HasDestination => GeneralId is not null || Own.Count > 0; + + public IEnumerable InUse => (GeneralId is { } g ? [g] : Array.Empty()).Concat(Own.Select(o => o.DestinationId)); +} + +/// +/// The SQL of decision D3 of tappa E2 on media m joined to its entry e: a file is due when it is +/// present, its account has «Esporta questo account» on and an effective destination (its own folder in use, else the +/// general folder in use), and that destination takes its content type (D4). The values (ids and content types) are +/// integers from the database and are written into the text, so the terms can be repeated in one statement without +/// parameters colliding. +/// +internal static class ExportFilterSql +{ + private const string Present = "m.sha256 IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')"; + + /// The content type of a file as a bit of , as . + internal const string TypeOfFile = + "(CASE e.kind WHEN 'Post' THEN (CASE m.kind WHEN 'Photo' THEN 1 ELSE 2 END) " + + "WHEN 'Story' THEN (4 | (CASE WHEN EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id) THEN 8 ELSE 0 END)) " + + "WHEN 'Highlight' THEN 8 WHEN 'Tagged' THEN 16 WHEN 'ProfilePicture' THEN 32 ELSE 0 END)"; + + /// Reads the context of one query. + public static ExportFilterContext Load(SqliteConnection c) + { + long? general = null; + var generalTypes = ContentTypes.None; + var own = new List<(long, long, ContentTypes)>(); + using (var r = c.Command("SELECT id, scope, account_id, content_types FROM export_destination WHERE removed_at IS NULL").ExecuteReader()) + { + while (r.Read()) + { + if (r.GetString(1) == nameof(ExportScope.General)) + { + general = r.GetInt64(0); + generalTypes = (ContentTypes)r.GetInt32(3); + } + else if (r.GetInt64OrNull(2) is { } account) + { + own.Add((account, r.GetInt64(0), (ContentTypes)r.GetInt32(3))); + } + } + } + + var off = new HashSet(); + using (var r = c.Command("SELECT account_id FROM export_account WHERE enabled = 0").ExecuteReader()) + { + while (r.Read()) + { + off.Add(r.GetInt64(0)); + } + } + + var samePost = c.Command("SELECT value FROM setting WHERE key = @k").With("@k", ExportSettingKeys.SamePost).ExecuteScalar() is string value + && string.Equals(value, nameof(SamePostCopies.OneOnly), StringComparison.Ordinal) + ? SamePostCopies.OneOnly + : SamePostCopies.OnePerAccount; + + if (general is null && own.Count == 0) + { + return new ExportFilterContext(null, ContentTypes.None, own, off, samePost, false, false, false); + } + + var inUse = string.Join(", ", (general is { } g ? [g] : Array.Empty()).Concat(own.Select(o => o.Item2)).Select(Literal)); + bool Any(string states) => c.Command( + $"SELECT EXISTS (SELECT 1 FROM export_copy WHERE destination_id IN ({inUse}) AND state IN ({states}))").ScalarInt64() != 0; + return new ExportFilterContext(general, generalTypes, own, off, samePost, Any("'Copied'"), Any("'Failed'"), Any("'Removed', 'Superseded'")); + } + + /// The file m of entry e is due (D3). + public static string DueFile(ExportFilterContext x) + { + if (!x.HasDestination) + { + return "0"; + } + + var general = x.GeneralId is null ? "0" : TypeTerm(x.GeneralTypes); + var branches = new StringBuilder(); + foreach (var (account, _, types) in x.Own) + { + branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {(x.Off.Contains(account) ? "0" : TypeTerm(types))}"); + } + + foreach (var account in x.Off.Where(a => x.Own.All(o => o.AccountId != a))) + { + branches.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN 0"); + } + + var destination = branches.Length == 0 ? general : $"(CASE e.account_id{branches} ELSE {general} END)"; + return destination == "1" ? $"({Present})" : $"({Present} AND {destination})"; + } + + /// + /// The file is copied in its effective destination, or, with «Una copia sola», copied for another account still in + /// Febe in a destination in use: the rule of the plan and of the copy (decision of 2026-11-27, «una copia altrove conta + /// solo se è di un altro account»). A copy of the same account in a folder that is no longer its effective one, and a + /// copy whose account was removed, do not count. + /// + public static string Copied(ExportFilterContext x) + { + if (!x.HasCopies) + { + return "0"; + } + + return x.SamePost == SamePostCopies.OneOnly + ? $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND {OneOnlyMatch(x)})" + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant <> 'Frame')"; + } + + /// «Una copia sola»: a copy c counts for the file of e (in a destination in use, tested apart). + private static string OneOnlyMatch(ExportFilterContext x) => + $"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))"; + + /// The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again. + public static string Failed(ExportFilterContext x) => !x.HasFailed + ? "0" + : $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')"; + + /// + /// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was + /// superseded (or removed) by this file. Never copied again by itself (D9). Two EXISTS, one per index. + /// + /// The context of the query. + /// The term is evaluated on every file of the library (see ). + public static string Replaced(ExportFilterContext x, bool bulk = false) => !x.HasHistory + ? "0" + : $"({History(x, bulk)} AND NOT {CopiedTerm(x, bulk)} AND NOT {Failed(x)})"; + + /// + /// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). The same partition + /// as NOT Copied AND NOT Replaced, without testing the copy twice. + /// + /// The context of the query. + /// The term is evaluated on every file of the library (see ). + public static string NotCopied(ExportFilterContext x, bool bulk = false) + { + if (!x.HasHistory) + { + return $"(NOT {CopiedTerm(x, bulk)})"; + } + + return x.HasFailed + ? $"(NOT {CopiedTerm(x, bulk)} AND ({Failed(x)} OR NOT {History(x, bulk)}))" + : $"(NOT {CopiedTerm(x, bulk)} AND NOT {History(x, bulk)})"; + } + + /// The term of «Tutte le foto» on m (with e its entry): a due file of the chosen class. + /// The context of the query. + /// The class. + /// + /// The term is evaluated on every file of the library (the counts of «Tutte le foto», the lists of the totals and + /// days) rather than on the few files of a window: each EXISTS then sits behind a list of the SHA-256 of the copies + /// of the destinations in use, read once from ix_export_copy_destination, so most files are settled by that list + /// without a lookup of their own (WP5b of tappa E2, measured over 200,000 entries). + /// + public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter, bool bulk = false) => filter switch + { + LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {CopiedTerm(x, bulk)})", + LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x, bulk)})", + LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x, bulk)})", + _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), + }; + + /// + /// The term of the grouped mosaic on entry e. «Copiati»: every due file copied, behind a list of the entries + /// with a copy (materialized once, a superset); «Non ancora copiati»: a due file to copy; «Tolti o superati»: a due + /// file removed or superseded, behind the list of the entries with such a row. + /// + /// The context of the query. + /// The class. + /// + /// A count over the whole library (totals, days) rather than a window: «Copiati» and «Non ancora copiati» then read + /// one list of the entries of the due files of the class, in a single pass over the files with the + /// bulk terms, instead of an EXISTS per entry (about three times faster over 200,000 entries). + /// A window keeps the EXISTS: it stops after a few hundred entries in index order. + /// + public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter, bool aggregate = false) + { + if (!x.HasDestination) + { + return "0"; + } + + string Files(string term) => $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {DueFile(x)} AND {term})"; + string List(string term) => $"(SELECT m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id WHERE {DueFile(x)} AND {term})"; + var withCopy = $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) " + + "AND c.state = 'Copied' AND c.variant <> 'Frame')"; + return filter switch + { + LibraryCopiesFilter.Copied when !x.HasCopies => "0", + LibraryCopiesFilter.Copied when aggregate => CopiedEntries(x), + LibraryCopiesFilter.Copied => $"{withCopy} AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}", + LibraryCopiesFilter.NotCopied when aggregate => $"+e.id IN {List(NotCopied(x, bulk: true))}", + LibraryCopiesFilter.NotCopied => Files(NotCopied(x)), + LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory + ? "0" + : $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 IN (c.source_sha256, c.superseded_by_sha256) " + + $"WHERE c.destination_id IN ({InUse(x)}) AND c.state IN ('Removed', 'Superseded')) AND {Files(Replaced(x))}", + _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), + }; + } + + /// With «Tutte le foto» an entry qualifies when one of its files does. + public static string EntryOfFiles(ExportFilterContext x, LibraryCopiesFilter filter) => + x.HasDestination ? $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {FileTerm(x, filter)})" : "0"; + + /// The effective destination of the account of e: its own folder, else the general one (NULL: none). + public static string DestinationOf(ExportFilterContext x) + { + var general = x.GeneralId is { } g ? Literal(g) : "NULL"; + if (x.Own.Count == 0) + { + return general; + } + + var builder = new StringBuilder("(CASE e.account_id"); + foreach (var (account, destination, _) in x.Own) + { + builder.Append(CultureInfo.InvariantCulture, $" WHEN {account} THEN {destination}"); + } + + return builder.Append(CultureInfo.InvariantCulture, $" ELSE {general} END)").ToString(); + } + + /// + /// «Copiati» over the whole library, from the copies rather than from the files: the copied due files of each entry, + /// counted from the Copied rows of the destinations in use (CROSS JOIN keeps that order, with or without ANALYZE), + /// equal to its due files. The same rows as per file; a third of the time of a pass over every + /// file of 200,000 entries. + /// + private static string CopiedEntries(ExportFilterContext x) + { + var match = x.SamePost == SamePostCopies.OneOnly + ? $" AND {OneOnlyMatch(x)}" + : $" AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id"; + return "+e.id IN (SELECT m.entry_id FROM export_copy c CROSS JOIN media m CROSS JOIN entry e " + + $"WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND m.sha256 = c.source_sha256 AND e.id = m.entry_id{match} " + + $"AND {DueFile(x)} GROUP BY m.entry_id " + + $"HAVING COUNT(DISTINCT m.id) = (SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {DueFile(x)}))"; + } + + /// + /// Copied (); in bulk behind the list of the SHA-256 copied in a destination in use (a superset: + /// any account, any variant), so a file never copied anywhere needs no lookup of its own. + /// + private static string CopiedTerm(ExportFilterContext x, bool bulk) => !x.HasCopies + ? "0" + : bulk + ? $"(m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied') AND {Copied(x)})" + : Copied(x); + + /// + /// The removed or superseded part of : a copy of this very file in the effective destination + /// was removed or superseded (whether or not it names the file that replaced it: the file can be back in the library + /// in another entry), or a copy was superseded (or removed) by this file. The same rows as the plan reads + /// (GetCopyStatesAsync), so filter, marks, counts and plan agree (D3). In bulk each EXISTS sits behind its list + /// of SHA-256. + /// + private static string History(ExportFilterContext x, bool bulk) + { + var destination = DestinationOf(x); + var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " + + "AND c.state IN ('Removed', 'Superseded'))"; + var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " + + "AND c.state IN ('Superseded', 'Removed'))"; + if (!bulk) + { + return $"({removed} OR {superseded})"; + } + + var inUse = InUse(x); + return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state IN ('Removed', 'Superseded')) AND {removed}) " + + $"OR (m.sha256 IN (SELECT c.superseded_by_sha256 FROM export_copy c WHERE c.superseded_by_sha256 IS NOT NULL AND c.destination_id IN ({inUse})) AND {superseded}))"; + } + + private static string InUse(ExportFilterContext x) => string.Join(", ", x.InUse.Select(Literal)); + + private static string TypeTerm(ContentTypes types) => + (types & ContentTypes.All) == ContentTypes.All ? "1" + : (types & ContentTypes.All) == ContentTypes.None ? "0" + : string.Create(CultureInfo.InvariantCulture, $"(({TypeOfFile} & {(int)(types & ContentTypes.All)}) <> 0)"); + + private static string Literal(long value) => value.ToString(CultureInfo.InvariantCulture); +} diff --git a/src/Febe.Data/Stores/ExportStore.cs b/src/Febe.Data/Stores/ExportStore.cs index 23fff09..fbde21a 100644 --- a/src/Febe.Data/Stores/ExportStore.cs +++ b/src/Febe.Data/Stores/ExportStore.cs @@ -1,4 +1,6 @@ +using System.Globalization; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; using Microsoft.Data.Sqlite; @@ -868,4 +870,346 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery(); }, ct); + + // Tappa E2 ------------------------------------------------------------------------------------------------------- + + /// SQLite allows 999 parameters per statement: id lists go in chunks below that. + private const int IdChunk = 900; + + internal const string ReplacedCopySql = $""" + SELECT {CopyColumns} FROM export_copy + WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') + ORDER BY id DESC LIMIT 1 + """; + + internal const string CopiedElsewhereSql = $""" + SELECT {CopyColumns} FROM export_copy + WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL + AND (@a IS NULL OR account_id <> @a) + AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL)) + ORDER BY id DESC LIMIT 1 + """; + + internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit"; + + /// The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256. + internal static string CopyStatesSql(string shaList) => $""" + SELECT account_id, source_sha256, state, id FROM export_copy + WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original' + """; + + /// + /// The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by). +state + /// keeps the planner off ix_export_copy_destination, which without statistics it took to read every Superseded and + /// Removed copy of the destination for each chunk of SHA-256. + /// + internal static string ReplacedStatesSql(string shaList) => $""" + SELECT account_id, superseded_by_sha256, state, id FROM export_copy + WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND +state IN ('Superseded', 'Removed') + """; + + private const string CandidateColumns = + "m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, " + + "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)"; + + private static ExportCandidate ReadCandidate(SqliteDataReader r) => new( + r.GetInt64(0), + r.GetInt64(1), + r.GetInt64(2), + r.GetEnum(3), + r.GetEnum(4), + r.GetEnum(5), + r.GetTextOrNull(6), + r.GetInt64OrNull(7), + r.GetTextOrNull(8), + r.GetInt32(9), + r.GetBool(10)); + + public Task> ListAccountExportSwitchesAsync(CancellationToken ct = default) => + db.ReadAsync>( + c => + { + var switches = new Dictionary(); + using var r = c.Command("SELECT account_id, enabled FROM export_account").ExecuteReader(); + while (r.Read()) + { + switches[r.GetInt64(0)] = r.GetBool(1); + } + + return switches; + }, + ct); + + public Task FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync( + c => ReadFirst(c.Command(ReplacedCopySql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy), + ct); + } + + public Task FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default) + { + var sha = ExportValues.Sha(sha256, nameof(sha256)); + return db.ReadAsync( + c => ReadFirst( + c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).With("@a", Sql.Int(exceptAccountId)), + ReadCopy), + ct); + } + + public Task> GetCopyStatesAsync( + long destinationId, + IReadOnlyCollection<(long AccountId, string Sha256)> keys, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(keys); + var wanted = keys.Select(k => (k.AccountId, Sha256: ExportValues.Sha(k.Sha256, nameof(keys)))).ToHashSet(); + return db.ReadAsync>( + c => + { + // Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row + // replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here. + var current = new Dictionary<(long, string), ExportCopyState>(); + var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); + var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>(); + void Keep(Dictionary<(long, string), (long Id, ExportCopyState State)> into, (long, string) key, long id, ExportCopyState state) + { + if (!into.TryGetValue(key, out var seen) || seen.Id < id) + { + into[key] = (id, state); + } + } + + void Read(Func sql, string[] chunk, Action<(long, string), ExportCopyState, long> add) + { + using var command = c.Command(string.Empty).With("@d", destinationId); + command.CommandText = sql(command.AddList("h", chunk)); + using var r = command.ExecuteReader(); + while (r.Read()) + { + var key = (r.GetInt64(0), r.GetString(1)); + if (wanted.Contains(key)) + { + add(key, r.GetEnum(2), r.GetInt64(3)); + } + } + } + + foreach (var chunk in wanted.Select(k => k.Sha256).Distinct(StringComparer.Ordinal).Chunk(IdChunk)) + { + Read(CopyStatesSql, chunk, (key, state, id) => + { + if (state is ExportCopyState.Copied or ExportCopyState.Failed) + { + current[key] = state; + } + else + { + Keep(newest, key, id, state); + } + }); + Read(ReplacedStatesSql, chunk, (key, state, id) => Keep(replaced, key, id, state)); + } + + var result = new Dictionary<(long AccountId, string Sha256), ExportCopyState>(); + foreach (var key in wanted) + { + if (current.TryGetValue(key, out var state)) + { + result[key] = state; + } + else if (newest.TryGetValue(key, out var history)) + { + result[key] = history.State; + } + else if (replaced.TryGetValue(key, out var by)) + { + result[key] = by.State; + } + } + + return result; + }, + ct); + } + + public Task MarkCopiesRemovedAsync(IReadOnlyList copyIds, DateTimeOffset at, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(copyIds); + if (copyIds.Count == 0) + { + return Task.FromResult(0); + } + + return db.WriteAsync( + w => + { + var changed = 0; + foreach (var chunk in copyIds.Distinct().Chunk(IdChunk)) + { + // The write context keeps one prepared command per SQL text: the text names its parameters, so a + // second chunk of the same size reuses the command with new values (one built on an empty text and + // filled in afterwards would be the first chunk's command again, its parameters still there). + var names = string.Join(", ", chunk.Select((_, i) => string.Create(CultureInfo.InvariantCulture, $"@i{i}"))); + // A Superseded row keeps the SHA-256 of the file that replaced it: still never copied again by itself. + var command = w.Command($"UPDATE export_copy SET state = 'Removed', state_changed_at = @at WHERE id IN ({names}) AND state IN ('Copied', 'Superseded')") + .With("@at", Sql.Time(at)); + for (var i = 0; i < chunk.Length; i++) + { + command.With(string.Create(CultureInfo.InvariantCulture, $"@i{i}"), chunk[i]); + } + + changed += command.ExecuteNonQuery(); + } + + return changed; + }, + ct); + } + + public Task> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(selection); + var n = Math.Clamp(limit, 1, 10_000); + return db.ReadAsync>( + c => + { + List Page(Func where) + { + using var command = c.Command(string.Empty).With("@after", afterMediaId).With("@n", (long)n); + var terms = where(command); + command.CommandText = $"SELECT {CandidateColumns} FROM media m JOIN entry e ON e.id = m.entry_id WHERE {terms} AND m.id > @after ORDER BY m.id LIMIT @n"; + return ReadAll(command, ReadCandidate); + } + + // Id lists go in chunks: each chunk gives its first n files after the key, and the first n of all of them are + // the page. + List ByIds(IReadOnlyList ids, string column) => + ids.Distinct().Chunk(IdChunk) + .SelectMany(chunk => Page(command => $"{column} IN ({command.AddList("x", chunk)})")) + .OrderBy(x => x.MediaId) + .Take(n) + .ToList(); + + return selection switch + { + ExportSelection.Media media => ByIds(media.MediaIds, "m.id"), + ExportSelection.Entries entries => ByIds(entries.EntryIds, "m.entry_id"), + ExportSelection.Account account => Page(command => + { + command.With("@acc", account.AccountId); + return $"e.account_id = @acc AND +e.state IN ({command.AddList("st", EntryStateRules.Visible.Select(s => s.ToString()))})"; + }), + ExportSelection.Filter filter => Page(command => + { + var where = EntryStore.BuildWhere(c, command, filter.LibraryFilter, aggregate: true, files: filter.Mode == MosaicMode.Files); + // «Tutte le foto»: only the files the mosaic shows (EntryStore.FileTerms, on m with its entry e). + return filter.Mode == MosaicMode.Files ? $"{where} AND {EntryStore.FileTerms(c, filter.LibraryFilter)}" : where; + }), + _ => throw new ArgumentOutOfRangeException(nameof(selection)), + }; + }, + ct); + } + + public Task> ListRecentRunsAsync(int limit, CancellationToken ct = default) => + db.ReadAsync>( + c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun), + ct); + + public async Task> GetEntryMarksAsync(IReadOnlyList entryIds, CancellationToken ct = default) => + (await GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false)).ToDictionary(p => p.Key, p => p.Value.Mark); + + public Task> GetEntryCopyCountsAsync(IReadOnlyList entryIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(entryIds); + return db.ReadAsync>( + c => + { + var marks = new Dictionary(); + var x = ExportFilterSql.Load(c); + if (!x.HasDestination || entryIds.Count == 0) + { + return marks; + } + + foreach (var chunk in entryIds.Distinct().Chunk(IdChunk)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("x", chunk); + command.CommandText = $""" + SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END) + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)} + GROUP BY m.entry_id + """; + using var r = command.ExecuteReader(); + while (r.Read()) + { + marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2)); + } + } + + return marks; + }, + ct); + } + + public Task> GetFileMarksAsync(IReadOnlyList mediaIds, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(mediaIds); + return db.ReadAsync>( + c => + { + var marks = new Dictionary(); + var x = ExportFilterSql.Load(c); + if (!x.HasDestination || mediaIds.Count == 0) + { + return marks; + } + + foreach (var chunk in mediaIds.Distinct().Chunk(IdChunk)) + { + using var command = c.Command(string.Empty); + var list = command.AddList("x", chunk); + command.CommandText = $""" + SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id + WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)} + """; + using var r = command.ExecuteReader(); + while (r.Read()) + { + marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None; + } + } + + return marks; + }, + ct); + } + + public Task CountAccountFilesAsync(long accountId, CancellationToken ct = default) => + db.ReadAsync( + c => + { + var x = ExportFilterSql.Load(c); + if (!x.HasDestination) + { + return new ExportAccountCounts(0, 0, 0, 0); + } + + using var command = c.Command($""" + SELECT COUNT(*), + ifnull(SUM(CASE WHEN {ExportFilterSql.NotCopied(x)} THEN 1 ELSE 0 END), 0), + ifnull(SUM(CASE WHEN {ExportFilterSql.Replaced(x)} THEN 1 ELSE 0 END), 0), + ifnull(SUM(CASE WHEN {ExportFilterSql.Failed(x)} AND NOT {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END), 0) + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE e.account_id = @a AND {ExportFilterSql.DueFile(x)} + """).With("@a", accountId); + using var r = command.ExecuteReader(); + r.Read(); + return new ExportAccountCounts(r.GetInt32(0), r.GetInt32(1), r.GetInt32(2), r.GetInt32(3)); + }, + ct); } diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs index a5deb82..686eb1f 100644 --- a/src/Febe.Desktop.Core/DesktopPlatform.cs +++ b/src/Febe.Desktop.Core/DesktopPlatform.cs @@ -61,6 +61,12 @@ public interface IDesktopShell /// desktop framework of .NET (no package). Tests on Linux pass AES-256-GCM with a key made at run time. /// ISessionProtector SessionProtector { get; } + + /// + /// Free space and file system of the folders of the copies (spec §4.10), network shares included; null: the + /// shared measure (drive letters only). + /// + Febe.Core.Export.IExportDisk? ExportDisk => null; } /// @@ -176,6 +182,10 @@ public sealed class DesktopPlatform : IFebePlatform services.AddSingleton(_shell.Native); services.AddSingleton(new DesktopBrowserWindow()); services.AddSingleton(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed)); + if (_shell.ExportDisk is { } disk) + { + services.AddSingleton(disk); + } } public void RegisterProblemServices(IServiceCollection services, FebeApp app) diff --git a/src/Febe.Desktop/DesktopShell.cs b/src/Febe.Desktop/DesktopShell.cs index 03c1ebb..c6a83fb 100644 --- a/src/Febe.Desktop/DesktopShell.cs +++ b/src/Febe.Desktop/DesktopShell.cs @@ -21,6 +21,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel public ISessionProtector SessionProtector { get; } = new DpapiSessionProtector(); + public Febe.Core.Export.IExportDisk? ExportDisk { get; } = new Native.WindowsExportDisk(); + public string? WebView2Version() { try diff --git a/src/Febe.Desktop/Native/WindowsExportDisk.cs b/src/Febe.Desktop/Native/WindowsExportDisk.cs new file mode 100644 index 0000000..6f76465 --- /dev/null +++ b/src/Febe.Desktop/Native/WindowsExportDisk.cs @@ -0,0 +1,79 @@ +using System.Runtime.InteropServices; +using System.Text; +using Febe.Core.Export; + +namespace Febe.Desktop.Native; + +/// +/// The disks of the copies to external folders on Windows (spec §4.10 «Spazio»): free space and file system of drive +/// letters and of network shares (\\nas\foto), which does not measure. Only reads: the +/// free space for the current user (quotas included) and the name of the file system (FAT32: no file over 4 GB). +/// +internal sealed class WindowsExportDisk : IExportDisk +{ + public long? FreeBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + var folder = Path.GetFullPath(root); + return GetDiskFreeSpaceExW(EnsureTrailingSeparator(folder), out var available, out _, out _) + ? (long)Math.Min(available, long.MaxValue) + : null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) + { + return null; + } + } + + public long? MaxFileBytes(string root) + { + if (string.IsNullOrWhiteSpace(root)) + { + return null; + } + + try + { + var volume = Path.GetPathRoot(Path.GetFullPath(root)); + if (string.IsNullOrEmpty(volume)) + { + return null; + } + + var name = new StringBuilder(64); + return GetVolumeInformationW(EnsureTrailingSeparator(volume), null, 0, out _, out _, out _, name, name.Capacity) + && ExportSpace.IsFat(name.ToString()) + ? ExportSpace.Fat32Limit + : null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or IOException) + { + return null; + } + } + + private static string EnsureTrailingSeparator(string path) => + path.EndsWith(Path.DirectorySeparatorChar) ? path : path + Path.DirectorySeparatorChar; + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetDiskFreeSpaceExW(string directory, out ulong freeForCaller, out ulong total, out ulong free); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetVolumeInformationW( + string rootPath, + StringBuilder? volumeName, + int volumeNameSize, + out uint serialNumber, + out uint maxComponentLength, + out uint flags, + StringBuilder fileSystemName, + int fileSystemNameSize); +} diff --git a/src/Febe.Server/ServerCommand.cs b/src/Febe.Server/ServerCommand.cs index 94fdc98..64ece6b 100644 --- a/src/Febe.Server/ServerCommand.cs +++ b/src/Febe.Server/ServerCommand.cs @@ -10,12 +10,12 @@ namespace Febe.Server; internal static class ServerCommand { public const string Usage = - "Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--porta 8480] [--ascolta 0.0.0.0]\n" + "Uso: febe [--dati /dati] [--libreria /libreria] [--importa /importa] [--esporta] [--porta 8480] [--ascolta 0.0.0.0]\n" + " [--porta-debug 9222] [--display :99] [--chromium percorso] [--senza-sandbox]\n" + " [--sito-di-prova http://127.0.0.1:8481 [--cdn-di-prova http://127.0.0.2:8482] [--accesso-di-prova]] [--prima-sessione secondi]\n" + " [--raccolta pagine|richieste]\n" + "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM,\n" - + " FEBE_RACCOLTA, FEBE_CHIAVE_SESSIONE.\n" + + " FEBE_RACCOLTA, FEBE_CHIAVE_SESSIONE, FEBE_ESPORTA.\n" + "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute."; public static async Task RunAsync(string[] args, TextWriter output, TextWriter error) diff --git a/src/Febe.Server/ServerOptions.cs b/src/Febe.Server/ServerOptions.cs index 0f57a94..cc076d8 100644 --- a/src/Febe.Server/ServerOptions.cs +++ b/src/Febe.Server/ServerOptions.cs @@ -66,6 +66,15 @@ internal sealed record ServerOptions /// Import sources, read-only (/importa). public string ImportFolder { get; init; } = "/importa"; + /// + /// --esporta or FEBE_ESPORTA=1: the copies to external folders are switched on (spec §4.10). They are + /// written only below , and only when a folder of the server is mounted there. + /// + public bool ExportDeclared { get; init; } + + /// Root of the copies to external folders (/esporta); not on the command line, tests change it. + public string ExportFolder { get; init; } = "/esporta"; + /// FEBE_HOST: names the interface is reached with (comma separated). Empty: any name. public IReadOnlyList Hosts { get; init; } = []; @@ -125,6 +134,7 @@ internal sealed record ServerOptions LibraryFolder = LibraryFolder, LibraryFolderFromSettings = false, ImportFolder = ImportFolder, + ExportRoot = Core.Export.ExportRootOptions.Docker(Path.GetFullPath(ExportFolder), ExportDeclared), ZoneId = ZoneId, Zone = Zone, Language = Language, @@ -236,6 +246,7 @@ internal sealed record ServerOptions Hosts = SplitHosts(Env("FEBE_HOST")), TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"), NoSandbox = Flag("FEBE_SENZA_SANDBOX"), + ExportDeclared = Flag("FEBE_ESPORTA"), ChromiumPath = Env("FEBE_CHROMIUM"), DebugPort = debugPort, Display = Env("FEBE_DISPLAY") ?? DefaultDisplay, @@ -305,6 +316,9 @@ internal sealed record ServerOptions case "--senza-sandbox": options = options with { NoSandbox = true }; break; + case "--esporta": + options = options with { ExportDeclared = true }; + break; case "--sito-di-prova": case "--cdn-di-prova": { @@ -400,7 +414,7 @@ internal sealed record ServerOptions var key = SessionKey is not null ? "impostata" : SessionKeyProblem is not null ? "non valida" : "assente"; return string.Create( CultureInfo.InvariantCulture, - $"ServerOptions {{ Dati = {DataFolder}, Libreria = {LibraryFolder}, Porta = {Port}, Sito = {Site.Name}, Raccolta = {CollectionRouteNames.Name(Collection)}, {ChildProcessEnvironment.PasswordVariable} = {password}, {Core.Security.SessionKey.EnvironmentVariable} = {key} }}"); + $"ServerOptions {{ Dati = {DataFolder}, Libreria = {LibraryFolder}, Porta = {Port}, Sito = {Site.Name}, Raccolta = {CollectionRouteNames.Name(Collection)}, Copie esterne = {(ExportDeclared ? "dichiarate" : "spente")}, {ChildProcessEnvironment.PasswordVariable} = {password}, {Core.Security.SessionKey.EnvironmentVariable} = {key} }}"); } /// The time zone named by TZ, or null when unknown. diff --git a/src/Febe.Web/Api/AccountsApi.cs b/src/Febe.Web/Api/AccountsApi.cs index 41afc54..ac8d073 100644 --- a/src/Febe.Web/Api/AccountsApi.cs +++ b/src/Febe.Web/Api/AccountsApi.cs @@ -4,9 +4,11 @@ using Febe.Core.Collection.Recipes; using Febe.Core.Collection.Search; using Febe.Core.Domain; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Web.Engine; +using Febe.Web.Export; using Febe.Web.Library; using Febe.Web.Native; using Microsoft.AspNetCore.Builder; @@ -23,8 +25,8 @@ public static class AccountsApi endpoints.MapGet("/api/accounts", async (IFebeStorage storage, IClock clock, CancellationToken ct) => ApiHttp.Json(await ListAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountListDto)); - endpoints.MapGet("/api/accounts/{id:long}", async (long id, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) => - ApiHttp.Json(await DetailAsync(id, storage, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto)); + endpoints.MapGet("/api/accounts/{id:long}", async (long id, HttpContext context, IFebeStorage storage, FebeLibrary library, ExportHub exports, IClock clock, CancellationToken ct) => + ApiHttp.Json(await DetailAsync(id, storage, library, clock, exports.RootFor(context), ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto)); endpoints.MapPost("/api/accounts/{id:long}/plan", async (long id, HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) => { @@ -35,17 +37,32 @@ public static class AccountsApi }); endpoints.MapPut("/api/accounts/{id:long}/settings", async (long id, HttpContext context, IFebeStorage storage, FebeLibrary library, FebeWebOptions options, - INativeShell shell, IBrowserWindow browser, IEngineControl engine, LibraryChanges changes, IClock clock, CancellationToken ct) => + INativeShell shell, IBrowserWindow browser, IEngineControl engine, LibraryChanges changes, ExportHub exports, IClock clock, CancellationToken ct) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AccountSettingsDto).ConfigureAwait(false); var account = await GetAsync(storage, id, ct).ConfigureAwait(false); var readOnly = SystemApi.Capabilities(context, options, shell, browser, clock).FoldersReadOnly; var folder = ResolveFolder(account, body.Folder, library, readOnly); var edited = AccountSettingsMapper.Apply(account, body, clock.LocalZone, clock.Now, folder); + await RefuseExportConflictAsync(account, edited, library, exports, ct).ConfigureAwait(false); await storage.Accounts.UpdateAsync(edited, ct).ConfigureAwait(false); await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false); changes.Publish(new LibraryChange(clock.Now, id, "account")); - return ApiHttp.Json(await DetailAsync(id, storage, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto); + return ApiHttp.Json(await DetailAsync(id, storage, library, clock, exports.RootFor(context), ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto); + }); + + // «Esporta questo account» (spec §4.4, tappa E2): acts at once. Off, no copy of the account is made, not even + // with «Copia in…» (decision of 25 November 2026); the copies already made stay where they are. + endpoints.MapPost("/api/accounts/{id:long}/export-enabled", async (long id, HttpContext context, IFebeStorage storage, ExportHub exports, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.SwitchRequest).ConfigureAwait(false); + var account = await GetAsync(storage, id, ct).ConfigureAwait(false); + var service = await exports.GetAsync(ct).ConfigureAwait(false); + await service.Destinations.SetAccountEnabledAsync(id, body.Value, ct).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, id, "export")); + return ApiHttp.Message(body.Value + ? $"{ItalianText.Handle(account.Username)} si copia nelle cartelle di esportazione." + : $"{ItalianText.Handle(account.Username)} non si copia più nelle cartelle di esportazione. Le copie già fatte restano dove sono."); }); // «Tieni aggiornato» of the table: acts at once. @@ -273,7 +290,7 @@ public static class AccountsApi account.PreviousUsername); } - public static async Task DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) + public static async Task DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, ExportRootOptions exportRoot, CancellationToken ct) { ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(library); @@ -311,7 +328,32 @@ public static class AccountsApi account.State == AccountState.ArchiveOnly && account.InstagramId is null && account.IsMine is false ? null : InstagramLinks.Profile(account.Username), highlights, AccountSettingsMapper.MaxBackfillPerDay, - (await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).ToNames()); + (await DownloadOrder.LoadAsync(storage.Settings, ct).ConfigureAwait(false)).ToNames(), + await ExportApi.AccountAsync(storage, account, exportRoot, clock, ct).ConfigureAwait(false)); + } + + /// + /// A new folder of an account may not sit inside, or contain, a folder of the copies (spec §4.10): the change is + /// refused and nothing is saved. + /// + private static async Task RefuseExportConflictAsync(Account account, Account edited, FebeLibrary library, ExportHub exports, CancellationToken ct) + { + var before = library.Layout.AccountFolder(account); + var after = library.Layout.AccountFolder(edited); + if (string.Equals(Path.TrimEndingDirectorySeparator(before), Path.TrimEndingDirectorySeparator(after), StringComparison.Ordinal)) + { + return; + } + + var service = await exports.GetAsync(ct).ConfigureAwait(false); + // Only what the new folder adds: a destination already in conflict is paused by its own check. + var already = (await service.Destinations.RecheckAsync(null, ct).ConfigureAwait(false)).Select(c => c.Destination.Id).ToHashSet(); + var conflicts = await service.Destinations.RecheckAsync([after], ct).ConfigureAwait(false); + if (conflicts.FirstOrDefault(c => !already.Contains(c.Destination.Id)) is { } conflict) + { + throw new BadRequestException( + $"La cartella scelta per {ItalianText.Handle(edited.Username)} è dentro (o contiene) la cartella di esportazione «{ExportDestinations.Label(conflict.Destination)}»: scegline un'altra."); + } } /// «Con queste impostazioni», recomputed at every change of the form (spec §4.4). diff --git a/src/Febe.Web/Api/ApiMapping.cs b/src/Febe.Web/Api/ApiMapping.cs index f8bc906..6f9df0b 100644 --- a/src/Febe.Web/Api/ApiMapping.cs +++ b/src/Febe.Web/Api/ApiMapping.cs @@ -218,9 +218,19 @@ public static class ApiMapping _ => throw new BadRequestException("Provenienza sconosciuta."), }; + LibraryCopiesFilter? copies = query["copies"].ToString().ToLowerInvariant() switch + { + "" => null, + "notcopied" => LibraryCopiesFilter.NotCopied, + "copied" => LibraryCopiesFilter.Copied, + "removedorsuperseded" => LibraryCopiesFilter.RemovedOrSuperseded, + _ => throw new BadRequestException("Filtro delle copie sconosciuto."), + }; + var search = query["q"].ToString().Trim(); return new LibraryFilter { + Copies = copies, Kind = kind, AccountIds = accounts, From = from, diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index 62662d9..fe62860 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -43,7 +43,9 @@ public sealed record CoverDto(long MediaId, string Kind, int? Width, int? Height /// /// A tile of the mosaic: one entry, or with «Tutte le foto» one file of it (the cover is that file and -/// its place in the series; null for an entry tile). +/// its place in the series; null for an entry tile). : the mark of the copies +/// to external folders, copied or partly (with of , the +/// «1/3»), null when nothing is copied or no destination is in use. /// public sealed record TileDto( long Id, @@ -57,7 +59,10 @@ public sealed record TileDto( string State, int Files, CoverDto? Cover, - int? Position = null); + int? Position = null, + string? Copies = null, + int? CopiesDone = null, + int? CopiesDue = null); /// A window of tiles; cursors continue it (null: nothing more that way). public sealed record LibraryPageDto(IReadOnlyList Tiles, string? Older, string? Newer); @@ -69,7 +74,7 @@ public sealed record ArrivedDto(IReadOnlyList Tiles, int Total); public sealed record DayDto(string Day, int Count, string Cursor); /// Days of the mosaic with the totals; only with «Tutte le foto» (the files of the entries). -public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList Days, int? Files = null); +public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList Days, int? Files = null, bool HasDestinations = false); public sealed record AccountBriefDto(long Id, string Username, string? DisplayName, bool IsPrivate, bool IsFollowed, bool IsMine, string State, string? Avatar); @@ -86,7 +91,8 @@ public sealed record MediaDto( string? Thumb, bool Available, string State, - bool Damaged = false); + bool Damaged = false, + IReadOnlyList? Copies = null); /// Everything the viewer shows of an entry. public sealed record EntryDto( @@ -106,7 +112,8 @@ public sealed record EntryDto( LocalTimeDto? Downloaded, IReadOnlyList Highlights, string? InstagramUrl, - IReadOnlyList Media); + IReadOnlyList Media, + bool CanCopy = false); public sealed record EntryIdsRequest(IReadOnlyList Ids, string? Mode); @@ -200,7 +207,8 @@ public sealed record AccountDetailDto( string? InstagramUrl, IReadOnlyList Highlights, int MaxBackfillPerDay, - IReadOnlyList? GeneralDownloadOrder = null); + IReadOnlyList? GeneralDownloadOrder = null, + ExportAccountDto? Export = null); public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message); diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs new file mode 100644 index 0000000..a922b45 --- /dev/null +++ b/src/Febe.Web/Api/ExportApi.cs @@ -0,0 +1,755 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Web.Export; +using Febe.Web.Library; +using Febe.Web.Native; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.WebUtilities; + +namespace Febe.Web.Api; + +/// +/// The copies to external folders (spec §4.10, §10.3, tappa E2) over : destinations and +/// their folders, «Copia in…» (plan, then start), the progress for the Dashboard tab «Esportazione», jobs, reports and +/// «Copia di nuovo». Every command passes the Origin check of the security middleware like any other. Nothing here +/// touches a file of a destination except through the service (its probe, its copies): no file is ever deleted, moved +/// or overwritten. +/// +public static class ExportApi +{ + /// Title of the native folder picker for a destination. + public const string PickTitle = "Scegli la cartella delle copie"; + + /// The most files a «Copia in…» can name one by one (a larger choice goes through the filter). + public const int MaxIds = 50_000; + + private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10); + + public static void Map(IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + + endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var root = hub.RootFor(context); + var d = SettingsApi.Deps.From(services); + var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock); + var state = ExportRoots.Evaluate(root); + var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false); + var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); + var mapped = new List(destinations.Count); + foreach (var destination in destinations) + { + var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + mapped.Add(Destination(destination, names, counts, root, clock)); + } + + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var active = service.ActiveRunIds; + var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id)); + var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; + return ApiHttp.Json( + new ExportOverviewDto( + new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder), + SamePost(settings.SamePost), + mapped.FirstOrDefault(x => x.Scope == "general"), + [.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)], + active, + unfinished, + new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders)), + FebeJsonContext.Default.ExportOverviewDto); + }); + + endpoints.MapPut("/api/export/settings", async (HttpContext context, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false); + var samePost = body.SamePost?.Trim().ToLowerInvariant() switch + { + "oneperaccount" => SamePostCopies.OnePerAccount, + "oneonly" => SamePostCopies.OneOnly, + _ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."), + }; + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + await (settings with { SamePost = samePost }).SaveAsync(storage.Settings, ct).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message(samePost == SamePostCopies.OneOnly + ? "Fatto: lo stesso post in due account si copia una volta sola." + : "Fatto: lo stesso post in due account si copia una volta per ciascun account."); + }); + + endpoints.MapGet("/api/export/folders", async (string? path, HttpContext context, ExportHub hub, CancellationToken ct) => + { + await hub.GetAsync(ct).ConfigureAwait(false); + var root = hub.RootFor(context); + if (root.Root is not { } rootFolder) + { + throw new BadRequestException("Qui la cartella si sceglie con la finestra del sistema."); + } + + if (ExportRoots.Evaluate(root) is { Active: false, Problem: { } problem }) + { + throw new BadRequestException(problem); + } + + var relative = string.IsNullOrWhiteSpace(path) ? string.Empty : path.Trim().Trim('/', '\\').Replace('\\', '/'); + // Never on the request thread without a limit: a dead share below /esporta must not hang the picker. + var folders = await GuardAsync(() => ExportRoots.BrowseAsync(root, relative.Length == 0 ? null : relative, DiskTimeout, ct)).ConfigureAwait(false); + string? parent = relative.Length == 0 ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty; + var full = relative.Length == 0 ? rootFolder : Path.Combine(rootFolder, LibraryLayout.ToPlatform(relative)); + return ApiHttp.Json( + new ExportFolderListDto(relative, parent, ExportRoots.DisplayPath(root, full), [.. folders.Select(f => new SourceFolderDto(f.Name, f.Path, f.HasSubfolders))]), + FebeJsonContext.Default.ExportFolderListDto); + }); + + endpoints.MapPost("/api/export/pick-folder", async (HttpContext context, ExportHub hub, IFebeStorage storage, INativeShell shell, CancellationToken ct) => + { + var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.ExportPickRequest, new ExportPickRequest(null)).ConfigureAwait(false); + if (!shell.CanPickFolder || hub.RootFor(context).Root is not null) + { + throw new BadRequestException("Qui la cartella delle copie si sceglie dall'elenco delle cartelle di /esporta."); + } + + // The picker opens on the folder of the destination being changed (from the database, never from the page). + string? initial = null; + if (body.DestinationId is { } id && await storage.Exports.GetDestinationAsync(id, ct).ConfigureAwait(false) is { } destination + && await ExistsAsync(destination.RootPath, ct).ConfigureAwait(false)) + { + initial = destination.RootPath; + } + + var picked = await shell.PickFolderAsync(PickTitle, initial, ct).ConfigureAwait(false); + return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto); + }); + + endpoints.MapPost("/api/export/check-folder", async (HttpContext context, ExportHub hub, IExportDisk disk, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + EnsureActive(hub); + var verdict = await GuardAsync(() => service.Destinations.CheckFolderAsync(body.Path ?? string.Empty, ct)).ConfigureAwait(false); + long? free = null; + var fat = false; + if (verdict.Accepted) + { + free = await MeasureAsync(() => disk.FreeBytes(verdict.FullPath), ct).ConfigureAwait(false); + fat = await MeasureAsync(() => disk.MaxFileBytes(verdict.FullPath), ct).ConfigureAwait(false) is { } max && max <= ExportSpace.Fat32Limit; + } + + return ApiHttp.Json( + new ExportFolderCheckDto(verdict.Accepted, verdict.FullPath, Display(hub.RootFor(context), verdict.FullPath), verdict.Problem?.Message, free, fat), + FebeJsonContext.Default.ExportFolderCheckDto); + }); + + endpoints.MapPost("/api/export/naming-preview", async (HttpContext context, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportNamingPreviewRequest).ConfigureAwait(false); + var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming; + var sample = await SettingsApi.SampleAccountAsync(storage, ct).ConfigureAwait(false); + var preview = ExportNamingPreview.Build(ParseScope(body.Scope), Clean(body.General), Clean(body.Highlight), Clean(body.Profile), naming, clock.LocalZone, sample); + return ApiHttp.Json(SettingsApi.Preview(preview), FebeJsonContext.Default.NamingPreviewDto); + }); + + endpoints.MapPost("/api/export/destinations", async (HttpContext context, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportDestinationRequest).ConfigureAwait(false); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + EnsureActive(hub); + var saved = await GuardAsync(() => service.Destinations.CreateAsync(Spec(body), ct)).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, saved.Destination.AccountId, "export")); + return ApiHttp.Json(await SavedAsync(storage, saved, hub.RootFor(context), clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportDestinationSavedDto); + }); + + endpoints.MapPut("/api/export/destinations/{id:long}", async (long id, HttpContext context, ExportHub hub, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportDestinationRequest).ConfigureAwait(false); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + EnsureActive(hub); + var saved = await GuardAsync(() => service.Destinations.UpdateAsync(id, Spec(body), ct)).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, saved.Destination.AccountId, "export")); + return ApiHttp.Json(await SavedAsync(storage, saved, hub.RootFor(context), clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportDestinationSavedDto); + }); + + endpoints.MapDelete("/api/export/destinations/{id:long}", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(async () => + { + await service.Destinations.RetireAsync(id, ct).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message(ExportDestinations.RetiredText); + }); + + endpoints.MapGet("/api/export/destinations/{id:long}/status", async (long id, HttpContext context, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var status = await GuardAsync(() => service.Destinations.StatusAsync(id, ct)).ConfigureAwait(false); + var names = await UsernamesAsync(storage, ct).ConfigureAwait(false); + return ApiHttp.Json( + Destination(status.Destination, names, status.Counts, hub.RootFor(context), clock, status.Reachable, status.FreeBytes, status.Problem), + FebeJsonContext.Default.ExportDestinationDto); + }); + + endpoints.MapPost("/api/export/destinations/{id:long}/resume", async (long id, ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var retry = await GuardAsync(() => service.RetryDestinationAsync(id, ct)).ConfigureAwait(false); + if (retry.Problem is { } problem) + { + throw new BadRequestException(problem); + } + + return ApiHttp.Message(retry.Resumed.Count > 0 + ? "La cartella risponde di nuovo: la copia riprende." + : "La cartella risponde di nuovo."); + }); + + endpoints.MapPost("/api/export/destinations/{id:long}/check", async (long id, ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(async () => + { + await service.CheckCopiesAsync(id, ct).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + return ApiHttp.Message("Controllo delle copie avviato: segui l'avanzamento nella Dashboard, scheda Esportazione. Nessun file viene toccato."); + }); + + endpoints.MapPost("/api/export/plan", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyJobRequestDto).ConfigureAwait(false); + var request = Request(body, clock); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var plan = await GuardAsync(() => service.PlanAsync(request, ct)).ConfigureAwait(false); + return ApiHttp.Json(Plan(plan, hub.RootFor(context)), FebeJsonContext.Default.ExportPlanDto); + }); + + endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyJobRequestDto).ConfigureAwait(false); + var request = Request(body, clock); + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var start = await GuardAsync(() => service.StartAsync(request, ct)).ConfigureAwait(false); + return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); + }); + + endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) => + { + var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyAgainRequest).ConfigureAwait(false); + var copy = await storage.Exports.GetCopyAsync(body.CopyId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa copia non è più registrata."); + if (copy.State is not (ExportCopyState.Removed or ExportCopyState.Superseded)) + { + throw new BadRequestException("Si copia di nuovo solo un file tolto dalla destinazione o superato."); + } + + if (copy.AccountId is not { } accountId) + { + throw new BadRequestException("L'account di questa copia è stato rimosso: non c'è niente da copiare di nuovo."); + } + + // The file the library has now: the one that took the place of the copied one, else the copied one itself + // (it can be back in the library in another entry while the one that replaced it went). + string? sha = null; + List present = []; + foreach (var candidate in new[] { copy.SupersededBySha256, copy.SourceSha256 }.OfType().Distinct(StringComparer.Ordinal)) + { + present = (await storage.Media.FindBySha256Async(candidate, ct).ConfigureAwait(false)) + .Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State)) + .ToList(); + if (present.Count > 0) + { + sha = candidate; + break; + } + } + + if (sha is null) + { + throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo."); + } + + if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c => + c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant)) + { + throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella."); + } + + // Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two + // entries, and the first one found may be a file the library lost (it would end «non presente in libreria»). + var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); + var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0]; + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false); + return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); + }); + + endpoints.MapGet("/api/export/progress", async (ExportHub hub, IFebeStorage storage, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var progress = await service.GetProgressAsync(ct).ConfigureAwait(false); + var error = service.LastJobError; + if (error is null && progress.RunId is { } runId && await storage.Exports.GetRunAsync(runId, ct).ConfigureAwait(false) is { } run) + { + error = run.LastError; + } + + return ApiHttp.Json( + new ExportProgressDto( + progress.RunId, + Phase(progress.Phase), + progress.Fraction, + progress.FilesDone, + progress.FilesTotal, + progress.BytesDone, + progress.BytesTotal, + progress.CurrentFile, + progress.DestinationLabel, + ItemCounts(progress.ByState), + service.IsBusy, + error), + FebeJsonContext.Default.ExportProgressDto); + }); + + endpoints.MapGet("/api/export/runs", async (int? limit, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var runs = await storage.Exports.ListRecentRunsAsync(Math.Clamp(limit ?? 20, 1, 100), ct).ConfigureAwait(false); + var labels = await LabelsAsync(storage, ct).ConfigureAwait(false); + var active = service.ActiveRunIds; + var list = new List(runs.Count); + foreach (var run in runs) + { + var summary = await storage.Exports.GetRunSummaryAsync(run.Id, ct).ConfigureAwait(false); + list.Add(Run(run, summary, labels, clock, active.Contains(run.Id))); + } + + return ApiHttp.Json>(list, FebeJsonContext.Default.IReadOnlyListExportRunDto); + }); + + endpoints.MapPost("/api/export/interrupt", async (ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await service.InterruptAsync(ct).ConfigureAwait(false); + return ApiHttp.Message("Interrotta: quello che è stato copiato resta, e riprendi da qui quando vuoi."); + }); + + endpoints.MapPost("/api/export/runs/{id:long}/resume", async (long id, ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(() => service.ResumeAsync([id], ct)).ConfigureAwait(false); + return ApiHttp.Message("Copia ripresa: segui l'avanzamento qui."); + }); + + endpoints.MapPost("/api/export/resume", async (ExportHub hub, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var resumed = await GuardAsync(() => service.ResumeAsync(null, ct)).ConfigureAwait(false); + return ApiHttp.Message(resumed.Count switch + { + 0 => "Non c'è nessuna copia da riprendere.", + 1 => "Copia ripresa: segui l'avanzamento qui.", + var n => $"{Core.Engine.ItalianText.Number(n)} copie riprese, una cartella alla volta: segui l'avanzamento qui.", + }); + }); + + endpoints.MapPost("/api/export/runs/{id:long}/discard", async (long id, ExportHub hub, LibraryChanges changes, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + await GuardAsync(async () => + { + await service.DiscardAsync(id, ct).ConfigureAwait(false); + return true; + }).ConfigureAwait(false); + changes.Publish(new LibraryChange(clock.Now, null, "export")); + return ApiHttp.Message("Annullata. I file già copiati restano dove sono."); + }); + + endpoints.MapGet("/api/export/runs/{id:long}/report", async (long id, ExportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) => + { + var service = await hub.GetAsync(ct).ConfigureAwait(false); + var report = await GuardAsync(() => service.Reports.BuildAsync(id, ct)).ConfigureAwait(false); + var labels = await LabelsAsync(storage, ct).ConfigureAwait(false); + var summary = new ExportRunSummary(report.Total, report.ByState); + return ApiHttp.Json( + new ExportReportDto( + Run(report.Run, summary, labels, clock, service.ActiveRunIds.Contains(id)), + ItemCounts(report.ByState), + report.BytesCopied, + [.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed))], + [.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]), + FebeJsonContext.Default.ExportReportDto); + }); + } + + // ---------------------------------------------------------------------------------------------- mapping + + public static string Scope(ExportScope scope) => scope == ExportScope.General ? "general" : "account"; + + public static string SamePost(SamePostCopies copies) => copies == SamePostCopies.OneOnly ? "oneOnly" : "onePerAccount"; + + /// The wire names of the content types of a destination, in the order of the dialog. + public static IReadOnlyList TypeNames(ContentTypes types) + { + var names = new List(6); + foreach (var (type, name) in TypeTable) + { + if ((types & type) != ContentTypes.None) + { + names.Add(name); + } + } + + return names; + } + + public static string CopyState(ExportCopyState state) => state switch + { + ExportCopyState.Copied => "copied", + ExportCopyState.Removed => "removed", + ExportCopyState.Superseded => "superseded", + _ => "failed", + }; + + public static string RunState(ExportRunState state) => state switch + { + ExportRunState.Running => "running", + ExportRunState.Interrupted => "interrupted", + ExportRunState.Paused => "paused", + ExportRunState.Completed => "completed", + _ => "cancelled", + }; + + public static string ItemState(ExportItemState state) => state switch + { + ExportItemState.Pending => "pending", + ExportItemState.Copied => "copied", + ExportItemState.Adopted => "adopted", + ExportItemState.AlreadyCopied => "alreadyCopied", + ExportItemState.Skipped => "skipped", + ExportItemState.Missing => "missing", + _ => "failed", + }; + + /// Copies per state with every state present. + public static IReadOnlyDictionary CopyCounts(IReadOnlyDictionary counts) + { + ArgumentNullException.ThrowIfNull(counts); + return Enum.GetValues().ToDictionary(CopyState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal); + } + + /// Files of a job per state with every state present. + public static IReadOnlyDictionary ItemCounts(IReadOnlyDictionary counts) + { + ArgumentNullException.ThrowIfNull(counts); + return Enum.GetValues().ToDictionary(ItemState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal); + } + + /// The path of a folder as shown to Alberto (relative to /esporta in Docker). + public static string Display(ExportRootOptions root, string fullPath) + { + ArgumentNullException.ThrowIfNull(root); + try + { + return string.IsNullOrWhiteSpace(fullPath) ? fullPath ?? string.Empty : ExportRoots.DisplayPath(root, fullPath); + } + catch (ArgumentException) + { + return fullPath; + } + } + + public static ExportDestinationDto Destination( + ExportDestination destination, + IReadOnlyDictionary usernames, + IReadOnlyDictionary counts, + ExportRootOptions root, + IClock clock, + bool? reachable = null, + long? freeBytes = null, + string? problem = null) + { + ArgumentNullException.ThrowIfNull(destination); + ArgumentNullException.ThrowIfNull(usernames); + ArgumentNullException.ThrowIfNull(clock); + var now = clock.Now; + return new ExportDestinationDto( + destination.Id, + Scope(destination.Scope), + destination.AccountId, + destination.AccountId is { } a && usernames.TryGetValue(a, out var name) ? name : null, + ExportDestinations.Label(destination), + destination.RootPath, + Display(root, destination.RootPath), + TypeNames(destination.ContentTypes), + destination.NamingScheme, + destination.HighlightNamingScheme, + destination.ProfileNamingScheme, + destination.Automatic, + destination.PausedAt is { } paused ? ApiMapping.Local(paused, now, clock.LocalZone) : null, + problem ?? (destination.PausedAt is not null ? destination.LastError : null), + CopyCounts(counts), + reachable, + freeBytes, + destination.IsOrphan, + destination.RemovedAccountUsername); + } + + /// A destination with its counts, read from the database. + public static async Task DestinationAsync(IFebeStorage storage, ExportDestination destination, ExportRootOptions root, IClock clock, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(destination); + var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false); + var names = new Dictionary(); + if (destination.AccountId is { } accountId && await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false) is { } account) + { + names[accountId] = account.Username; + } + + return Destination(destination, names, counts, root, clock); + } + + /// «Copie esterne» of the account card (decisions D1-D3 of tappa E2). + public static async Task AccountAsync(IFebeStorage storage, Account account, ExportRootOptions root, IClock clock, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(account); + var exports = storage.Exports; + var own = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false); + var destination = own ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false); + var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false)); + var counts = await exports.CountAccountFilesAsync(account.Id, ct).ConfigureAwait(false); + return new ExportAccountDto( + enabled, + own is not null, + destination is null ? null : await DestinationAsync(storage, destination, root, clock, ct).ConfigureAwait(false), + counts.Due, + counts.NotCopied, + counts.RemovedOrSuperseded, + counts.Failed); + } + + public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root) + { + ArgumentNullException.ThrowIfNull(plan); + return new ExportPlanDto( + plan.Files, + plan.Bytes, + plan.AlreadyCopied, + plan.RemovedOrSuperseded, + plan.NotExported, + plan.Missing, + [.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))], + plan.HasDestination); + } + + /// The request of a «Copia in…»: exactly one selection. + public static ExportJobRequest Request(CopyJobRequestDto body, IClock clock) + { + ArgumentNullException.ThrowIfNull(body); + ArgumentNullException.ThrowIfNull(clock); + var chosen = (body.MediaIds is { Count: > 0 } ? 1 : 0) + (body.EntryIds is { Count: > 0 } ? 1 : 0) + (body.Query is not null ? 1 : 0) + (body.AccountId is not null ? 1 : 0); + if (chosen != 1) + { + throw new BadRequestException("Scegli che cosa copiare: dei file, degli elementi, i risultati del filtro o un account."); + } + + ExportSelection selection; + if (body.MediaIds is { Count: > 0 } media) + { + selection = new ExportSelection.Media(Ids(media)); + } + else if (body.EntryIds is { Count: > 0 } entries) + { + selection = new ExportSelection.Entries(Ids(entries)); + } + else if (body.Query is { } query) + { + var parsed = new QueryCollection(QueryHelpers.ParseQuery(query)); + var mode = ApiMapping.Mode(body.Mode ?? parsed["mode"].ToString()); + selection = new ExportSelection.Filter(ApiMapping.Filter(parsed, clock.LocalZone), mode); + } + else + { + selection = new ExportSelection.Account(body.AccountId!.Value); + } + + return new ExportJobRequest(selection, body.CopyAgain); + } + + // ---------------------------------------------------------------------------------------------- helpers + + private static readonly (ContentTypes Type, string Name)[] TypeTable = + [ + (ContentTypes.PostPhotos, "postFoto"), + (ContentTypes.PostVideos, "postVideo"), + (ContentTypes.Stories, "storie"), + (ContentTypes.Highlights, "evidenza"), + (ContentTypes.Tagged, "taggati"), + (ContentTypes.ProfilePicture, "profilo"), + ]; + + private static ContentTypes ParseTypes(IReadOnlyList? names) + { + var types = ContentTypes.None; + foreach (var name in names ?? []) + { + var match = TypeTable.FirstOrDefault(t => string.Equals(t.Name, name?.Trim(), StringComparison.OrdinalIgnoreCase)); + if (match.Name is null) + { + throw new BadRequestException("Tipo di contenuto sconosciuto."); + } + + types |= match.Type; + } + + return types; + } + + private static ExportScope ParseScope(string? text) => text?.Trim().ToLowerInvariant() switch + { + "general" or "generale" => ExportScope.General, + "account" => ExportScope.Account, + _ => throw new BadRequestException("Tipo di cartella sconosciuto: generale o di un account."), + }; + + private static DestinationSpec Spec(ExportDestinationRequest body) => new( + ParseScope(body.Scope), + body.AccountId, + body.Path ?? string.Empty, + Clean(body.Label), + ParseTypes(body.Types), + Clean(body.NamingScheme), + Clean(body.HighlightNamingScheme), + Clean(body.ProfileNamingScheme), + body.Automatic, + body.OnlyNew); + + private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim(); + + private static List Ids(IReadOnlyList ids) => + ids.Count > MaxIds ? throw new BadRequestException("Troppi file in una volta: copia con il filtro della libreria.") : [.. ids.Distinct()]; + + private static string Phase(ExportPhase phase) => phase switch + { + ExportPhase.Preparing => "preparing", + ExportPhase.Checking => "checking", + ExportPhase.WaitingForSession => "waitingForSession", + ExportPhase.Copying => "copying", + _ => "finished", + }; + + private static ExportJobDto Job(ExportStart start, ExportRootOptions root) => new( + [.. start.Runs.Select(r => r.Id)], + Plan(start.Plan, root), + start.Runs.Count == 0 + ? "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria." + : "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione."); + + private static ExportRunDto Run(ExportRun run, ExportRunSummary summary, IReadOnlyDictionary labels, IClock clock, bool running) + { + var now = clock.Now; + return new ExportRunDto( + run.Id, + run.DestinationId, + labels.TryGetValue(run.DestinationId, out var label) ? label : "Cartella tolta", + run.Kind == ExportRunKind.Recognize ? "recognize" : "copy", + run.Origin == ExportRunOrigin.Automatic ? "automatic" : "manual", + RunState(run.State), + ApiMapping.Local(run.StartedAt, now, clock.LocalZone), + run.CompletedAt is { } done ? ApiMapping.Local(done, now, clock.LocalZone) : null, + run.LastError, + summary.Total, + summary.Total - summary.ByState.GetValueOrDefault(ExportItemState.Pending), + running); + } + + private static async Task SavedAsync(IFebeStorage storage, DestinationSaveResult saved, ExportRootOptions root, IClock clock, CancellationToken ct) => + new(await DestinationAsync(storage, saved.Destination, root, clock, ct).ConfigureAwait(false), saved.Warnings); + + private static async Task> UsernamesAsync(IFebeStorage storage, CancellationToken ct) => + (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + + /// Names of every destination, retired ones included (old jobs keep their name). + private static async Task> LabelsAsync(IFebeStorage storage, CancellationToken ct) => + (await storage.Exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false)).ToDictionary(d => d.Id, ExportDestinations.Label); + + /// Docker with /esporta not declared or not mounted: nothing can be written (decision D14 of tappa E2). + private static void EnsureActive(ExportHub hub) + { + if (ExportRoots.Evaluate(hub.Root) is { Active: false, Problem: { } problem }) + { + throw new BadRequestException(problem); + } + } + + /// A measure of a disk that may not answer (a disconnected share): null after the timeout. + private static async Task MeasureAsync(Func measure, CancellationToken ct) + where T : struct + { + try + { + return await Task.Run(measure, ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return null; + } + } + + private static async Task ExistsAsync(string folder, CancellationToken ct) + { + try + { + return await Task.Run(() => Directory.Exists(folder), ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false); + } + catch (TimeoutException) + { + return false; + } + } + + // ---------------------------------------------------------------------------------------------- errors + + /// The export's own exceptions become Italian answers: 400 for a refused request, 404 for something missing. + internal static T Guard(Func action) + { + try + { + return action(); + } + catch (Exception ex) when (Translate(ex) is { } translated) + { + throw translated; + } + } + + internal static async Task GuardAsync(Func> action) + { + try + { + return await action().ConfigureAwait(false); + } + catch (Exception ex) when (Translate(ex) is { } translated) + { + throw translated; + } + } + + private static Exception? Translate(Exception ex) => ex switch + { + ExportFolderException => new BadRequestException(ex.Message, ex), + DuplicateRecordException => new BadRequestException(ex.Message, ex), + KeyNotFoundException => new NotFoundException(ex.Message, ex), + ArgumentException a => new BadRequestException(ApiErrorMiddleware.CleanMessage(a), ex), + InvalidOperationException => new BadRequestException(ex.Message, ex), + _ => null, + }; +} diff --git a/src/Febe.Web/Api/ExportDtos.cs b/src/Febe.Web/Api/ExportDtos.cs new file mode 100644 index 0000000..56b1111 --- /dev/null +++ b/src/Febe.Web/Api/ExportDtos.cs @@ -0,0 +1,220 @@ +namespace Febe.Web.Api; + +// JSON shapes of the copies to external folders (spec §4.10, tappa E2). Same conventions as Dtos.cs: English camelCase +// names, Italian texts, times as LocalTimeDto. Names of states and types on the wire: +// scope «general»|«account»; types «postFoto», «postVideo», «storie», «evidenza», «taggati», «profilo»; +// copy states «copied», «removed», «superseded», «failed»; job states «running», «interrupted», «paused», «completed», +// «cancelled»; file states «pending», «copied», «adopted», «alreadyCopied», «skipped», «missing», «failed». + +/// +/// Where copies can go. : destinations are subfolders of (the page +/// lists them); otherwise any folder, with the native picker when . +/// false: nothing can be written, says why. +/// +public sealed record ExportRootDto(bool Docker, bool Active, string? Root, string? Problem, bool PickFolder); + +/// The library's naming schemes, to prefill «Uno schema suo», and the placeholders. +public sealed record ExportSchemesDto(string General, string Highlight, string Profile, IReadOnlyList Placeholders); + +/// +/// A destination. is the folder as shown («/esporta/usb» in Docker). +/// are the wire names of the content types; null schemes are «Come la libreria». : the reason +/// of its pause (or, with /status, why it does not answer now). : copies per state +/// (copied, removed, superseded, failed). and +/// only from /status. : an own folder whose account was +/// removed («era di @»). +/// +public sealed record ExportDestinationDto( + long Id, + string Scope, + long? AccountId, + string? Username, + string Label, + string RootPath, + string Display, + IReadOnlyList Types, + string? NamingScheme, + string? HighlightNamingScheme, + string? ProfileNamingScheme, + bool Automatic, + LocalTimeDto? PausedAt, + string? Problem, + IReadOnlyDictionary Counts, + bool? Reachable = null, + long? FreeBytes = null, + bool Orphan = false, + string? FormerUsername = null); + +/// +/// GET /api/export: Impostazioni → Esportazione and the notice of the Dashboard. : +/// onePerAccount or oneOnly. : interrupted or paused jobs («Riprendi»). +/// +public sealed record ExportOverviewDto( + ExportRootDto Root, + string SamePost, + ExportDestinationDto? General, + IReadOnlyList Own, + IReadOnlyList ActiveRunIds, + int UnfinishedRuns, + ExportSchemesDto Library); + +/// PUT /api/export/settings: «Lo stesso post in due account», onePerAccount or oneOnly. +public sealed record ExportSettingsRequest(string SamePost); + +/// Docker: the subfolders of a folder of /esporta. is "" for the root. +public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList Folders); + +/// POST /api/export/pick-folder: the destination being changed, to open the picker on its folder. +public sealed record ExportPickRequest(long? DestinationId); + +/// The check of a candidate folder (before saving). : files over 4 GB cannot go there. +public sealed record ExportFolderCheckDto(bool Accepted, string FullPath, string Display, string? Problem, long? FreeBytes, bool Fat32); + +/// The «Risultato» of a destination's naming. : general or account; null schemes are the library's. +public sealed record ExportNamingPreviewRequest(string Scope, string? General, string? Highlight, string? Profile); + +/// +/// A destination to add or change. : in Docker the folder relative to /esporta (as listed), +/// elsewhere the full path. : wire names, at least one. Null or empty schemes: «Come la +/// libreria». «Automatica» is stored only (tappa E5 acts on it). +/// +public sealed record ExportDestinationRequest( + string Scope, + long? AccountId, + string Path, + string? Label, + IReadOnlyList Types, + string? NamingScheme, + string? HighlightNamingScheme, + string? ProfileNamingScheme, + bool Automatic = false, + bool OnlyNew = true); + +/// A saved destination (a change of folder gives a new id) and the warnings of its schemes. +public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList Warnings); + +/// +/// What a «Copia in…» copies: exactly one of (files of «Tutte le foto» or the viewer), +/// (a grouped selection), (the filter of the Libreria, as its query +/// string, with grouped or files) or (every file of +/// the account). : «Copia di nuovo anche i tolti o superati». +/// +public sealed record CopyJobRequestDto( + IReadOnlyList? MediaIds, + IReadOnlyList? EntryIds, + string? Query, + string? Mode, + long? AccountId, + bool CopyAgain = false); + +/// A destination of a plan. : why it cannot be written now (paused, not reachable). +public sealed record ExportPlanDestinationDto( + long Id, + string Label, + string Display, + string Scope, + string? Username, + int Files, + long Bytes, + bool Paused, + string? Problem, + long? FreeBytes); + +/// +/// The summary of «Copia in…» (spec §10.3). /: what will be written +/// (with «Copia di nuovo» the tolti/superati too). : of accounts that are not exported +/// (switch off, no destination, type not taken). : not in the library. +/// +public sealed record ExportPlanDto( + int Files, + long Bytes, + int AlreadyCopied, + int RemovedOrSuperseded, + int NotExported, + int Missing, + IReadOnlyList Destinations, + bool HasDestination = true); + +/// The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed. +public sealed record ExportJobDto(IReadOnlyList RunIds, ExportPlanDto Plan, string Message); + +/// «Copia di nuovo» of a copy «Tolto» or «Superato» (the viewer). +public sealed record CopyAgainRequest(long CopyId); + +/// +/// GET /api/export/progress, polled by the Dashboard tab. : preparing, checking, +/// waitingForSession, copying, finished. : files of the job per state. +/// +public sealed record ExportProgressDto( + long? RunId, + string Phase, + double Fraction, + int FilesDone, + int FilesTotal, + long BytesDone, + long BytesTotal, + string? CurrentFile, + string? Destination, + IReadOnlyDictionary ByState, + bool Running, + string? Error); + +/// An export job. : copy or recognize; : manual or automatic. +public sealed record ExportRunDto( + long Id, + long DestinationId, + string Destination, + string Kind, + string Origin, + string State, + LocalTimeDto StartedAt, + LocalTimeDto? CompletedAt, + string? Error, + int Total, + int Done, + bool Running = false); + +/// The files of one account in a job ( counts written and adopted files). +public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed); + +/// A file of the report that needs a look, with its reason in Italian. +public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text); + +/// The report of a job (at most 200 problems). +public sealed record ExportReportDto( + ExportRunDto Run, + IReadOnlyDictionary ByState, + long BytesCopied, + IReadOnlyList Accounts, + IReadOnlyList Problems); + +/// +/// A copy of a file of the viewer (spec §4.6, §4.10). : copied, removed, superseded, failed; +/// : whole (tappa E2 copies originals only). : with «Una copia +/// sola», the account it was copied for when it is another one. : «Copia di nuovo». +/// +public sealed record MediaCopyDto( + long CopyId, + string Destination, + bool DestinationRetired, + string State, + string Variant, + string? Format, + long? FrameAtMs, + LocalTimeDto At, + string? ForAccount, + bool CanCopyAgain); + +/// +/// «Copie esterne» of the account card. : the effective one (its own folder, else the +/// general folder), null when there is none. Counts are of due files (decision D3 of tappa E2): with the switch off +/// they are zero. +/// +public sealed record ExportAccountDto( + bool Enabled, + bool HasOwnFolder, + ExportDestinationDto? Destination, + int Due, + int NotCopied, + int RemovedOrSuperseded, + int Failed); diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs index 636764e..afb1c94 100644 --- a/src/Febe.Web/Api/FebeJsonContext.cs +++ b/src/Febe.Web/Api/FebeJsonContext.cs @@ -88,4 +88,21 @@ namespace Febe.Web.Api; [JsonSerializable(typeof(ImportModeRequest))] [JsonSerializable(typeof(ImportPlanDto))] [JsonSerializable(typeof(ImportReportDto))] +[JsonSerializable(typeof(ExportOverviewDto))] +[JsonSerializable(typeof(ExportSettingsRequest))] +[JsonSerializable(typeof(ExportFolderListDto))] +[JsonSerializable(typeof(ExportPickRequest))] +[JsonSerializable(typeof(ExportFolderCheckDto))] +[JsonSerializable(typeof(ExportNamingPreviewRequest))] +[JsonSerializable(typeof(ExportDestinationRequest))] +[JsonSerializable(typeof(ExportDestinationSavedDto))] +[JsonSerializable(typeof(ExportDestinationDto))] +[JsonSerializable(typeof(CopyJobRequestDto))] +[JsonSerializable(typeof(ExportPlanDto))] +[JsonSerializable(typeof(ExportJobDto))] +[JsonSerializable(typeof(CopyAgainRequest))] +[JsonSerializable(typeof(ExportProgressDto))] +[JsonSerializable(typeof(IReadOnlyList))] +[JsonSerializable(typeof(ExportReportDto))] +[JsonSerializable(typeof(ExportAccountDto))] public sealed partial class FebeJsonContext : JsonSerializerContext; diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 7eca9cb..1e2bee4 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Runtime.CompilerServices; using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Library; using Febe.Core.Storage; using Febe.Web.Library; @@ -41,8 +42,9 @@ public static class LibraryApi var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone); return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode)); }).ToList(); + var hasDestinations = await HasDestinationsAsync(storage, ct).ConfigureAwait(false); return ApiHttp.Json( - new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files), + new LibraryDaysDto(now.ToUnixTimeMilliseconds(), ApiMapping.Day(LocalCalendar.Today(now, zone)), totals.Entries, totals.Accounts, list, files, hasDestinations), FebeJsonContext.Default.LibraryDaysDto); }); @@ -65,7 +67,7 @@ public static class LibraryApi ct).ConfigureAwait(false); return ApiHttp.Json( new LibraryPageDto( - page.Tiles.Select(t => Tile(t, zone)).ToList(), + await TilesAsync(storage, page.Tiles, zone, ct).ConfigureAwait(false), page.Older is { } older ? ApiMapping.Cursor(older, mode) : null, page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null), FebeJsonContext.Default.LibraryPageDto); @@ -76,7 +78,7 @@ public static class LibraryApi { var ids = ParseIds(context.Request.Query["ids"].ToString()); var tiles = await storage.Entries.GetTilesAsync(ids, ct).ConfigureAwait(false); - return ApiHttp.Json(new LibraryPageDto(tiles.Select(t => Tile(t, clock.LocalZone)).ToList(), null, null), FebeJsonContext.Default.LibraryPageDto); + return ApiHttp.Json(new LibraryPageDto(await TilesAsync(storage, tiles, clock.LocalZone, ct).ConfigureAwait(false), null, null), FebeJsonContext.Default.LibraryPageDto); }); endpoints.MapGet("/api/thumbnails/{key}", (string key, HttpContext context, FebeLibrary library) => @@ -233,6 +235,7 @@ public static class LibraryApi var local = LocalCalendar.ToLocal(entry.PublishedAt, zone); var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account))); var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false); + var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false); var media = new List(stored.Media.Count); foreach (var m in stored.Media) { @@ -259,7 +262,8 @@ public static class LibraryApi m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null, path is not null, ApiMapping.State(m.State), - damaged)); + damaged, + copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false))); } return new EntryDto( @@ -279,7 +283,150 @@ public static class LibraryApi entry.DownloadedAt is { } d ? ApiMapping.Local(d, now, zone) : null, highlights.Select(h => h.Title).ToList(), entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, entry, now, highlights.FirstOrDefault()?.InstagramId), - media); + media, + copies is { Effective: not null, Enabled: true }); + } + + /// + /// The tiles of a page with the mark of the copies to external folders (spec §4.6, tappa E2): an entry tile + /// «Copiato» or «Copiato in parte 1/3», a file tile of «Tutte le foto» «Copiato». Only due files count (decision + /// D3), and without a destination in use nothing more is asked to the database. + /// + public static async Task> TilesAsync(IFebeStorage storage, IReadOnlyList tiles, TimeZoneInfo zone, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(tiles); + var list = tiles.Select(t => Tile(t, zone)).ToList(); + if (list.Count == 0 || !await HasDestinationsAsync(storage, ct).ConfigureAwait(false)) + { + return list; + } + + var fileIds = tiles.Where(t => t.FilePosition is not null && t.CoverMediaId is not null).Select(t => t.CoverMediaId!.Value).Distinct().ToList(); + var entryIds = tiles.Where(t => t.FilePosition is null).Select(t => t.EntryId).Distinct().ToList(); + var fileMarks = fileIds.Count == 0 ? null : await storage.Exports.GetFileMarksAsync(fileIds, ct).ConfigureAwait(false); + var entryCopies = entryIds.Count == 0 ? null : await storage.Exports.GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false); + for (var i = 0; i < list.Count; i++) + { + var tile = tiles[i]; + if (tile.FilePosition is not null) + { + if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied) + { + list[i] = list[i] with { Copies = "copied" }; + } + } + else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies)) + { + list[i] = copies.Mark switch + { + ExportMark.Copied => list[i] with { Copies = "copied" }, + ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due }, + _ => list[i], + }; + } + } + + return list; + } + + /// Whether any destination of the copies is in use (the marks and the «Copie» filter make sense). + public static async Task HasDestinationsAsync(IFebeStorage storage, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(storage); + return (await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false)).Count > 0; + } + + /// + /// What the viewer needs to list the copies of the files of one entry (spec §4.6, §4.10): every destination, retired + /// ones too (an old copy keeps its name), the effective destination of the account and its switch, and «Lo stesso + /// post in due account». Null when no destination was ever added. + /// + private sealed record EntryCopiesContext( + Account Account, + IReadOnlyDictionary Destinations, + ExportDestination? Effective, + bool Enabled, + SamePostCopies SamePost, + IReadOnlyDictionary Usernames) + { + /// Copies shown for one file, newest first. + public const int MaxShown = 6; + + public static async Task LoadAsync(IFebeStorage storage, Account account, CancellationToken ct) + { + var exports = storage.Exports; + var destinations = await exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false); + if (destinations.Count == 0) + { + return null; + } + + var effective = await exports.GetAccountDestinationAsync(account.Id, ct).ConfigureAwait(false) + ?? await exports.GetGeneralDestinationAsync(ct).ConfigureAwait(false); + var enabled = ExportAccounts.IsEnabled(await exports.GetAccountExportEnabledAsync(account.Id, ct).ConfigureAwait(false)); + var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); + var usernames = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username); + return new EntryCopiesContext(account, destinations.ToDictionary(d => d.Id), effective, enabled, settings.SamePost, usernames); + } + + public async Task> CopiesAsync(IFebeStorage storage, Media media, DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct) + { + if (media.Sha256 is not { Length: > 0 } sha) + { + return []; + } + + var present = EntryStateRules.IsPresent(media.State); + var rows = await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false); + var shown = new List(); + foreach (var copy in rows.OrderByDescending(c => c.StateChangedAt ?? c.CopiedAt).ThenByDescending(c => c.Id)) + { + if (!Destinations.TryGetValue(copy.DestinationId, out var destination)) + { + continue; + } + + // The copies made for this account; with «Una copia sola», also the ones made for another account still + // in Febe in a folder still in use (that is why this file is «Già copiato»; a copy whose account was + // removed does not count, as in the plan). + var own = copy.AccountId == Account.Id; + if (!own && !(SamePost == SamePostCopies.OneOnly && copy.AccountId is not null && copy.State == ExportCopyState.Copied && !destination.IsRetired)) + { + continue; + } + + var canCopyAgain = own + && copy.State is ExportCopyState.Removed or ExportCopyState.Superseded + && present + && !destination.IsRetired + && Enabled + && Effective?.Id == destination.Id + && !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant); + shown.Add(new MediaCopyDto( + copy.Id, + ExportDestinations.Label(destination), + destination.IsRetired, + ExportApi.CopyState(copy.State), + copy.Variant switch + { + ExportVariant.Whole => "whole", + ExportVariant.Converted => "converted", + _ => "frame", + }, + copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(), + copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null, + ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone), + own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null, + canCopyAgain)); + if (shown.Count == MaxShown) + { + break; + } + } + + return shown; + } } /// diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs index baee7ae..14c621d 100644 --- a/src/Febe.Web/Api/SettingsApi.cs +++ b/src/Febe.Web/Api/SettingsApi.cs @@ -231,14 +231,16 @@ public static class SettingsApi throw new BadRequestException("Per confermare scrivi la parola «ricostruisci»."); } + // An import service built without the shared gate (a composition of tests) is still checked by itself. if ((await import.GetAsync(ct).ConfigureAwait(false)).ActiveRunId is not null) { - throw new BadRequestException("C'è un'importazione al lavoro: aspetta che finisca, poi ricostruisci."); + throw new BadRequestException(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Import)); } - if (!job.TryStart()) + // The gate covers import, copies to external folders and another rebuild (spec §4.10). + if (!job.TryStart(out var busy)) { - throw new BadRequestException("La ricostruzione è già in corso."); + throw new BadRequestException(busy ?? LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild)); } return ApiHttp.Message("Ricostruzione avviata: Febe rilegge le cartelle degli account e i loro file _febe.jsonl. Nessun file viene spostato o cancellato."); @@ -304,7 +306,7 @@ public static class SettingsApi } /// The account whose name the preview shows: the first one followed (or any), as in mockup 08. - private static async Task SampleAccountAsync(IFebeStorage storage, CancellationToken ct) + internal static async Task SampleAccountAsync(IFebeStorage storage, CancellationToken ct) { var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false); return accounts.Where(a => !a.IsMine && a.State is AccountState.UpToDate or AccountState.Backfilling).OrderBy(a => a.Id).Select(a => a.Username).FirstOrDefault() @@ -340,6 +342,19 @@ public static class SettingsApi throw new BadRequestException("La libreria non può stare dentro la cartella dei dati, né contenerla."); } + // Nor inside, or around, a folder of the copies (spec §4.10): only what the new root adds counts. + if (d.Services.GetService(typeof(Export.ExportHub)) is Export.ExportHub exports) + { + var destinations = (await exports.GetAsync(ct).ConfigureAwait(false)).Destinations; + var already = (await destinations.RecheckAsync(null, ct).ConfigureAwait(false)).Select(c => c.Destination.Id).ToHashSet(); + var conflicts = await destinations.RecheckAgainstAsync([new Core.Export.ProtectedFolder(root, Core.Export.ProtectedFolderKind.Library, null)], ct).ConfigureAwait(false); + if (conflicts.FirstOrDefault(c => !already.Contains(c.Destination.Id)) is { } conflict) + { + throw new BadRequestException( + $"La libreria non può stare dentro la cartella di esportazione «{Core.Export.ExportDestinations.Label(conflict.Destination)}», né contenerla: scegline un'altra."); + } + } + try { Directory.CreateDirectory(root); diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs index 2d9ed64..87555f5 100644 --- a/src/Febe.Web/Demo/DemoEngine.cs +++ b/src/Febe.Web/Demo/DemoEngine.cs @@ -374,7 +374,10 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat public bool IsSeparateWindow => Desktop; public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => - Task.FromResult(Desktop ? Path.Combine(root, "altre-cartelle", Path.GetFileName(Path.TrimEndingDirectorySeparator(initialFolder ?? "cartella"))) : null); + Task.FromResult(!Desktop ? null + // The folders of the copies are checked against the demo's /esporta: an empty one there. + : string.Equals(title, Api.ExportApi.PickTitle, StringComparison.Ordinal) ? Path.Combine(root, "esporta", DemoExport.PickedFolder) + : Path.Combine(root, "altre-cartelle", Path.GetFileName(Path.TrimEndingDirectorySeparator(initialFolder ?? "cartella")))); public Task ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(Desktop); diff --git a/src/Febe.Web/Demo/DemoExport.cs b/src/Febe.Web/Demo/DemoExport.cs new file mode 100644 index 0000000..215d677 --- /dev/null +++ b/src/Febe.Web/Demo/DemoExport.cs @@ -0,0 +1,280 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Data; + +namespace Febe.Web.Demo; + +/// +/// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder +/// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its +/// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore», +/// and a job left «interrotto» for the Dashboard. Everything lives in the demo's temporary folder, whose «esporta» is +/// the demo's /esporta: the counts, the marks and the «Copie» filter come from the same rows the engine wrote. +/// +public static class DemoExport +{ + /// The general folder of the demo. + public const string GeneralFolder = "Disco USB"; + + /// The own folder of @studio.lumen.demo. + public const string OwnFolder = "Studio Lumen"; + + /// The empty folder the demo's picker gives (desktop look). + public const string PickedFolder = "Chiavetta"; + + /// The account whose copies the demo shows in every state. + public const string CopiedAccount = "marta.demo"; + + /// The account with an own folder. + public const string OwnFolderAccount = "studio.lumen.demo"; + + /// The account with «Esporta questo account» off. + public const string NotExportedAccount = "il.porto.demo"; + + /// The demo's /esporta: a mounted, writable folder of the temporary root, shown as «/esporta». + public static ExportRootOptions Root(string root) + { + var folder = Path.Combine(root, "esporta"); + return ExportRootOptions.Docker(folder, declared: true, new DemoExportMounts(folder)) with { ShownAs = "/esporta" }; + } + + /// Creates the folders and the copies. A failure leaves the demo without copies, never without the demo. + public static async Task SeedAsync(string root, FebeDatabase database, DemoWorld world, LibraryLayout layout, DataFolderLayout data, IClock clock, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(world); + ArgumentNullException.ThrowIfNull(layout); + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(clock); + var options = Root(root); + foreach (var name in new[] { GeneralFolder, OwnFolder, PickedFolder }) + { + Directory.CreateDirectory(Path.Combine(options.Root!, name)); + } + + var files = new DemoFileResolver(world); + await using var service = new ExportService(new ExportEnvironment + { + Storage = database, + Layout = () => layout, + DataFolder = data.Root, + Clock = clock, + Root = options, + ResolveSource = files.Resolve, + Disk = new DemoExportDisk(), + Session = NoEngineSession.Instance, + Gate = new LongWorkGate(), + }); + + var accounts = await database.Accounts.ListAsync(ct).ConfigureAwait(false); + var marta = accounts.FirstOrDefault(a => a.Username == CopiedAccount); + var studio = accounts.FirstOrDefault(a => a.Username == OwnFolderAccount); + var porto = accounts.FirstOrDefault(a => a.Username == NotExportedAccount); + var general = (await service.Destinations.CreateAsync( + new DestinationSpec(ExportScope.General, null, GeneralFolder, GeneralFolder, ContentTypes.All, null, null, null), + ct).ConfigureAwait(false)).Destination; + if (studio is not null) + { + await service.Destinations.CreateAsync( + new DestinationSpec(ExportScope.Account, studio.Id, OwnFolder, OwnFolder, ContentTypes.PostPhotos | ContentTypes.PostVideos, null, null, null), + ct).ConfigureAwait(false); + } + + if (porto is not null) + { + await service.Destinations.SetAccountEnabledAsync(porto.Id, false, ct).ConfigureAwait(false); + } + + if (marta is null) + { + return; + } + + // The photos of @marta.demo, one file per picture (the demo shares its sample pictures between entries). + var pictures = await PhotosAsync(database, marta, world, ct).ConfigureAwait(false); + var photos = pictures.Select(p => p.Media).ToList(); + var copied = photos.Take(photos.Count * 2 / 3).ToList(); + + // «Tolto», «Superato» and «Errore» on the pictures the account uses least, so that few files show them. + var rest = pictures.Skip(copied.Count).OrderBy(p => p.Files).Select(p => p.Media).ToList(); + if (copied.Count > 0) + { + await service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. copied.Select(m => m.Id)])), ct).ConfigureAwait(false); + await service.WaitAsync(ct).ConfigureAwait(false); + } + + if (studio is not null) + { + var own = await PhotosAsync(database, studio, world, ct).ConfigureAwait(false); + if (own.Count > 0) + { + await service.StartAsync(new ExportJobRequest(new ExportSelection.Media([.. own.Take(Math.Max(1, own.Count / 2)).Select(p => p.Media.Id)])), ct).ConfigureAwait(false); + await service.WaitAsync(ct).ConfigureAwait(false); + } + } + + await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false); + } + + /// One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto». + private static async Task HistoryAsync( + FebeDatabase database, + DemoWorld world, + ExportDestination general, + Account marta, + IReadOnlyList photos, + IReadOnlyList rest, + IClock clock, + CancellationToken ct) + { + var now = clock.Now; + var exports = database.Exports; + var prefix = marta.Username + "/"; + if (rest.Count > 0 && rest[0].Sha256 is { } removedSha) + { + await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = general.Id, + AccountId = marta.Id, + MediaId = rest[0].Id, + SourceSha256 = removedSha, + Variant = ExportVariant.Whole, + State = ExportCopyState.Removed, + RelativePath = prefix + "spostate/foto-tolta.jpg", + Bytes = rest[0].Bytes ?? 0, + CopySha256 = removedSha, + CopiedAt = now.AddDays(-12), + StateChangedAt = now.AddDays(-3), + }, + ct).ConfigureAwait(false); + } + + // «Superato»: the folder keeps a picture that the library has replaced by another version (rest[1]). + var used = photos.Select(p => p.Sha256).ToHashSet(StringComparer.Ordinal); + var older = world.Pictures.FirstOrDefault(p => !used.Contains(p.Key) && File.Exists(p.Value)); + if (rest.Count > 1 && rest[1].Sha256 is { } newerSha && older.Key is { } olderSha) + { + var relative = prefix + "versioni-precedenti/foto-superata.jpg"; + var target = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative)); + Directory.CreateDirectory(Path.GetDirectoryName(target)!); + File.Copy(older.Value, target, overwrite: false); + await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = general.Id, + AccountId = marta.Id, + MediaId = rest[1].Id, + SourceSha256 = olderSha, + Variant = ExportVariant.Whole, + State = ExportCopyState.Superseded, + SupersededBySha256 = newerSha, + RelativePath = relative, + Bytes = new FileInfo(target).Length, + CopySha256 = olderSha, + CopiedAt = now.AddDays(-20), + StateChangedAt = now.AddDays(-2), + }, + ct).ConfigureAwait(false); + } + + if (rest.Count > 2 && rest[2].Sha256 is { } failedSha) + { + await exports.AddCopyAsync( + new ExportCopy + { + DestinationId = general.Id, + AccountId = marta.Id, + MediaId = rest[2].Id, + SourceSha256 = failedSha, + Variant = ExportVariant.Whole, + State = ExportCopyState.Failed, + CopiedAt = now.AddDays(-1), + LastError = "Errore di lettura o scrittura: il disco non ha risposto.", + }, + ct).ConfigureAwait(false); + } + + // A job stopped by the last stop: «Riprendi» on the Dashboard copies the rest. + var pending = rest.Skip(3).Take(12).ToList(); + if (pending.Count > 0) + { + var run = await exports.CreateRunAsync( + new ExportRun { DestinationId = general.Id, State = ExportRunState.Interrupted, StartedAt = now.AddHours(-5), CompletedAt = null }, + ct).ConfigureAwait(false); + await exports.AddItemsAsync( + [.. pending.Select(m => new ExportItem { RunId = run.Id, MediaId = m.Id, AccountId = marta.Id, SourceSha256 = m.Sha256 })], + ct).ConfigureAwait(false); + } + } + + /// The present photos of an account, one per picture (newest first), with how many files show that picture. + private static async Task> PhotosAsync(FebeDatabase database, Account account, DemoWorld world, CancellationToken ct) + { + var seen = new Dictionary(StringComparer.Ordinal); + var ids = new List(); + LibraryCursor? cursor = null; + do + { + var page = await database.Entries.QueryLibraryAsync( + new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 }, + ct).ConfigureAwait(false); + foreach (var tile in page.Tiles) + { + if (tile.CoverKind == MediaKind.Photo && tile.CoverMediaId is { } id && tile.CoverSha256 is { } sha && world.Pictures.ContainsKey(sha)) + { + if (seen.TryGetValue(sha, out var files)) + { + seen[sha] = files + 1; + } + else + { + seen[sha] = 1; + ids.Add(id); + } + } + } + + cursor = page.Older; + } + while (cursor is not null); + + var photos = new List<(Media Media, int Files)>(ids.Count); + foreach (var id in ids) + { + if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha } media && EntryStateRules.IsPresent(media.State)) + { + photos.Add((media, seen[sha])); + } + } + + return photos; + } +} + +/// The demo's mount table: its /esporta is a mounted, writable ext4 folder. +public sealed class DemoExportMounts(string root) : IExportMounts +{ + private readonly ExportMount _mount = new(Path.GetFullPath(root), "/esporta-demo", "ext4", false); + + public ExportMount? FindContaining(string fullPath) + { + ArgumentNullException.ThrowIfNull(fullPath); + return ExportPaths.IsSameOrInside(Path.GetFullPath(fullPath), _mount.MountPoint) ? _mount : null; + } + + public IReadOnlyList All() => [_mount]; +} + +/// The demo's disks: 1,8 TB free, no file size limit. +public sealed class DemoExportDisk : IExportDisk +{ + public const long Free = 1_800_000_000_000; + + public long? FreeBytes(string root) => Free; + + public long? MaxFileBytes(string root) => null; +} diff --git a/src/Febe.Web/Demo/DemoHost.cs b/src/Febe.Web/Demo/DemoHost.cs index 62f8741..0774c2c 100644 --- a/src/Febe.Web/Demo/DemoHost.cs +++ b/src/Febe.Web/Demo/DemoHost.cs @@ -1,5 +1,6 @@ using Febe.Core.Abstractions; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Library; using Febe.Core.Storage; @@ -71,6 +72,8 @@ public sealed class DemoHost : IAsyncDisposable await database.Settings.SetAsync(SettingKeys.LibraryRoot, layout.Root, ct).ConfigureAwait(false); var world = await DemoSeeder.SeedAsync(database, data, layout, clock, ct).ConfigureAwait(false); import = await DemoImport.PrepareAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false); + await DemoExport.SeedAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false); + var exportRoot = DemoExport.Root(root); var demoImport = import; var library = new FebeLibrary(database, data, layout, clock); var web = new FebeWebOptions @@ -103,6 +106,9 @@ public sealed class DemoHost : IAsyncDisposable services.AddSingleton(); services.AddSingleton(); services.AddSingleton(demoImport); + services.AddSingleton(exportRoot); + services.AddSingleton(); + services.AddSingleton(NoEngineSession.Instance); }); await app.StartAsync(ct).ConfigureAwait(false); return new DemoHost(root, database, import, app, world, FebeWebHost.BoundAddress(app)); diff --git a/src/Febe.Web/Export/ExportHub.cs b/src/Febe.Web/Export/ExportHub.cs new file mode 100644 index 0000000..df73e1e --- /dev/null +++ b/src/Febe.Web/Export/ExportHub.cs @@ -0,0 +1,129 @@ +using Febe.Core.Abstractions; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Web.Demo; +using Febe.Web.Import; +using Febe.Web.Library; +using Microsoft.AspNetCore.Http; + +namespace Febe.Web.Export; + +/// +/// The copies to external folders of the web host (spec §4.10, tappa E2): one over the +/// library of the web host, built at the first use and never rebuilt (the library layout is read at every use, so a +/// new library folder on Windows needs nothing here). At the first use the jobs left running by the last stop become +/// «interrotto» (). When a job ends, the open pages refresh tiles and filter through the +/// libreria event. +/// +public sealed class ExportHub : IAsyncDisposable +{ + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly IFebeStorage _storage; + private readonly FebeLibrary _library; + private readonly IClock _clock; + private readonly IMediaFileResolver _files; + private readonly FebeWebOptions _options; + private readonly LongWorkGate _longWork; + private readonly IEngineSessionState _session; + private readonly IExportDisk _disk; + private readonly LibraryChanges _changes; + private readonly ImportHub _import; + private ExportService? _service; + + public ExportHub( + IFebeStorage storage, + FebeLibrary library, + IClock clock, + IMediaFileResolver files, + ExportRootOptions root, + FebeWebOptions options, + LongWorkGate longWork, + IEngineSessionState session, + IExportDisk disk, + LibraryChanges changes, + ImportHub import) + { + _storage = storage ?? throw new ArgumentNullException(nameof(storage)); + _library = library ?? throw new ArgumentNullException(nameof(library)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _files = files ?? throw new ArgumentNullException(nameof(files)); + Root = root ?? throw new ArgumentNullException(nameof(root)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _longWork = longWork ?? throw new ArgumentNullException(nameof(longWork)); + _session = session ?? throw new ArgumentNullException(nameof(session)); + _disk = disk ?? throw new ArgumentNullException(nameof(disk)); + _changes = changes ?? throw new ArgumentNullException(nameof(changes)); + _import = import ?? throw new ArgumentNullException(nameof(import)); + } + + /// Where destinations may be chosen (Docker: /esporta), as the composition registered it. + public ExportRootOptions Root { get; } + + /// Jobs that the first use found running and made «interrotto» (the last stop interrupted them). + public int Recovered { get; private set; } + + /// + /// The root as a request sees it: in the demo the desktop look shows any folder (with the native picker of the + /// demo shell), the Docker look the subfolders of the demo's /esporta. Elsewhere, . + /// + public ExportRootOptions RootFor(HttpContext? context) => + _options.Demo && DemoRequest.Edition(context) != FebeEdition.Docker ? ExportRootOptions.AnyFolder : Root; + + /// The service, built at the first use (with the recovery of interrupted jobs). + public async Task GetAsync(CancellationToken ct = default) + { + if (_service is { } ready) + { + return ready; + } + + await _gate.WaitAsync(ct).ConfigureAwait(false); + try + { + if (_service is null) + { + var service = new ExportService(new ExportEnvironment + { + Storage = _storage, + Layout = () => _library.Layout, + DataFolder = _library.Data.Root, + Clock = _clock, + ImportRoot = _import.SourceRoot, + Root = Root, + ResolveSource = (account, media) => _files.Resolve(account, media), + Disk = _disk, + Session = _session, + Gate = _longWork, + }); + service.JobFinished += OnJobFinished; + Recovered = await service.RecoverAsync(ct).ConfigureAwait(false); + _service = service; + } + + return _service; + } + finally + { + _gate.Release(); + } + } + + public async ValueTask DisposeAsync() + { + if (_service is { } service) + { + service.JobFinished -= OnJobFinished; + await service.DisposeAsync().ConfigureAwait(false); + } + + _gate.Dispose(); + } + + private void OnJobFinished(object? sender, ExportJobFinished finished) + { + if (finished.CopiesChanged) + { + _changes.Publish(new LibraryChange(_clock.Now, null, "export")); + } + } +} diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs index d4c6254..013624c 100644 --- a/src/Febe.Web/FebeWeb.cs +++ b/src/Febe.Web/FebeWeb.cs @@ -2,12 +2,14 @@ using System.Net; using Febe.Core.Abstractions; using Febe.Core.Alerts; using Febe.Core.Engine; +using Febe.Core.Export; using Febe.Core.Import; using Febe.Core.Storage; using Febe.Web.Api; using Febe.Web.Connection; using Febe.Web.Demo; using Febe.Web.Engine; +using Febe.Web.Export; using Febe.Web.Hosting; using Febe.Web.Import; using Febe.Web.Library; @@ -73,10 +75,21 @@ public static class FebeWeb services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + // One gate for import, copies to external folders and rebuild (spec §4.10); the composition may register its own + // instance first, the one its import service already uses. + services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(sp => sp.GetService() is { } import ? new ImportHub(import, sp.GetRequiredService(), sp.GetRequiredService()) - : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService())); + : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService(), sp.GetRequiredService())); + // Copies to external folders (spec §4.10, tappa E2). Docker: only below /esporta, and only when declared and + // mounted (the composition registers the declared state); elsewhere any folder. + services.TryAddSingleton(NoEngineSession.Instance); + services.TryAddSingleton(_ => options.Edition == FebeEdition.Docker + ? ExportRootOptions.Docker(Path.GetFullPath("/esporta"), declared: false) + : ExportRootOptions.AnyFolder); + services.TryAddSingleton(sp => new SystemExportDisk(sp.GetRequiredService().Mounts)); + services.TryAddSingleton(); services.AddHttpContextAccessor(); if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password)) { @@ -138,6 +151,7 @@ public static class FebeWeb ActivityApi.Map(endpoints); SettingsApi.Map(endpoints); ImportApi.Map(endpoints); + ExportApi.Map(endpoints); DuplicatesApi.Map(endpoints); SearchApi.Map(endpoints); RemoteViewSocket.Map(endpoints); diff --git a/src/Febe.Web/Import/ImportHub.cs b/src/Febe.Web/Import/ImportHub.cs index ec1fab2..6d3fdfc 100644 --- a/src/Febe.Web/Import/ImportHub.cs +++ b/src/Febe.Web/Import/ImportHub.cs @@ -21,6 +21,7 @@ public sealed class ImportHub : IAsyncDisposable private readonly IClock _clock; private readonly FebeWebOptions? _options; private readonly LibraryChanges _changes; + private readonly LongWorkGate? _longWork; private readonly bool _owned; private ImportService? _service; private bool _stale; @@ -35,9 +36,13 @@ public sealed class ImportHub : IAsyncDisposable _service.ProgressChanged += OnProgress; } - /// Builds its own service over the library of the web host. - public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes) + /// + /// Builds its own service over the library of the web host. is the gate shared with the + /// copies to external folders and the rebuild (null: the import alone, as in some tests). + /// + public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes, LongWorkGate? longWork = null) { + _longWork = longWork; _storage = storage ?? throw new ArgumentNullException(nameof(storage)); _library = library ?? throw new ArgumentNullException(nameof(library)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); @@ -127,6 +132,7 @@ public sealed class ImportHub : IAsyncDisposable SetFileTimeToPublication = settings.SetFileTimeToPublication, Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder, DataFolder = library.Data.Root, + Gate = _longWork, }); } diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index b83f3b0..0e764a5 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -72,6 +72,11 @@ Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri | `IAlertTestSender` (Core) | `NoTelegramSender`: nessun messaggio parte (dimostrazione, prove), la risposta lo dice | La composizione (`Febe.App`, le due vesti): `TelegramAlertChannel` (Core, `Alerts/Telegram.cs`), lo stesso canale che usa `AlertService` | | `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop: `DesktopDataFolderChange` registra la scelta e `DataFolderMove` sposta la cartella al prossimo avvio, con copia verificata (SHA-256) | | `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 (decodificatore dei fotogrammi, cartella sorgente) | +| `LongWorkGate` | Uno nuovo: importazione, copie esterne e ricostruzione non girano mai insieme | `Febe.App`: lo stesso che usa la sua `ImportService` | +| `ExportRootOptions` (Core, copie esterne §4.10) | Docker: `/esporta` **non dichiarata** (nulla si scrive); desktop: qualsiasi cartella | Server: `--esporta`/`FEBE_ESPORTA` (attiva solo se c'è un montaggio su `/esporta` o sotto); dimostrazione: la sua `esporta`, mostrata come `/esporta` (`ShownAs`) | +| `IExportDisk` (Core) | `SystemExportDisk` (spazio libero delle lettere di unità, FAT32 dal tipo del file system) | Desktop: `WindowsExportDisk` (anche le condivisioni di rete come `\\nas\foto`); prove e dimostrazione: misure fisse | +| `IEngineSessionState` (Core) | `NoEngineSession`: le copie non aspettano mai | `Febe.App`: `RuntimeSessionState` sul motore (fra una sessione e l'altra, D10) | +| `ExportHub` (`Export/`) | Costruisce l'unico `ExportService` al primo uso (e segna «interrotto» ciò che l'arresto ha fermato, `Recovered`); a lavoro finito pubblica `LibraryChange` con motivo `export` | Nessuno | - `ImportHub.LibrarySettingsChanged()` va chiamato quando cambiano cartella o schema dei nomi (lo fa già `PUT /api/settings/general`); a copia finita pubblica `LibraryChange` con motivo `import`. @@ -108,7 +113,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser | | `GET /api/eventi` | SSE: `motore` (istantanea, al massimo ogni 300 ms, comunque ogni 60 s), `libreria` (al massimo ogni 1,5 s), commento ogni 25 s | | `GET /api/library/days?mode=grouped\|files` | Totali (sempre elementi: `entries`, `accounts`) e giorni con conteggio e cursore (per la finestra del mosaico); con `mode=files` («Tutte le foto») i giorni contano i file presenti in libreria e `files` è la loro somma (altrimenti `null`). Un altro valore di `mode` dà 400. Stessi filtri di `/api/library` | -| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | +| `GET /api/library?cursor=&direction=older\|newer&limit=&mode=grouped\|files` | Una finestra di tessere, con `older`/`newer` per continuare; filtri `kind`, `accounts`, `from`, `to`, `provenance`, `q`, `copies=notCopied\|copied\|removedOrSuperseded` (solo i file dovuti; un altro valore 400). Con una cartella delle copie in uso le tessere hanno `copies` (`copied`, `partly` con `copiesDone`/`copiesDue`) e `/days` ha `hasDestinations`; il visualizzatore dà le copie di ogni file (`copies`, al più 6) e `canCopy`. Con `mode=files` una tessera per file (con la sua posizione e `files`, i file dell'elemento) e il cursore è `ms.elemento.posizione` (raggruppato `ms.elemento`); un cursore malformato o `mode` sconosciuto danno 400 | | `GET /api/library/tiles?ids=` | Tessere per chiave | | `GET /api/thumbnails/{chiave}`, `GET /api/media/{id}/file[?download=1]` | Miniature (immutabili) e file (con range) | | `GET /api/entries/{id}`, `POST /api/entries/delete`, `/export`, `/{id}/open-on-instagram`, `POST /api/media/show-in-folder` | Visualizzatore, eliminazione (`remember` o `allowReturn`), CSV (`{ ids }` per la selezione, `{ query }` per il filtro della pagina: «Esporta l'elenco» nella riga degli strumenti) | @@ -134,6 +139,12 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `GET /api/import/{id}/progress`, `POST /{id}/interrupt`, `/resume` | Passi 2 e 4: avanzamento, interruzione e ripresa | | `GET /api/import/{id}/review`, `PUT /{id}/folders`, `PUT /{id}/mode`, `GET /{id}/duplicates?after=&all=`, `POST /{id}/duplicates/{pairId}`, `GET /api/import/files/{fileId}/preview` | Passo 3: contatori, cartelle → account, Copia/Sposta, doppioni con anteprime | | `POST /api/import/{id}/copy`, `GET /{id}/report`, `GET /{id}/report.csv`, `POST /{id}/discard` | Copia, resoconto, CSV (UTF-8 con BOM, `;`), abbandono di un'importazione non copiata | +| `GET /api/export`, `PUT /api/export/settings` (`{ samePost: "onePerAccount"\|"oneOnly" }`) | Copie esterne (§4.10, `Api/ExportApi.cs`): radice (`docker`, `active`, `root`, `problem`, `pickFolder`), cartella generale, cartelle proprie, lavori in corso e da riprendere (`unfinishedRuns`), schemi della libreria | +| `GET /api/export/folders?path=`, `POST /api/export/pick-folder` (`{ destinationId }`), `/check-folder` (`{ path }`), `/naming-preview` | Scelta della cartella: in Docker l'elenco sotto `/esporta` (solo se attiva; `..` è 400), sul desktop la finestra del sistema; controllo con spazio libero e FAT32; «Risultato» dei nomi | +| `POST /api/export/destinations`, `PUT/DELETE /api/export/destinations/{id}`, `GET /{id}/status`, `POST /{id}/resume`, `/{id}/check` | Cartelle: tipi `postFoto`, `postVideo`, `storie`, `evidenza`, `taggati`, `profilo`; un cambio di cartella dà un id nuovo; togliere non cancella nulla; «Riprova» (sonda, poi riprende i lavori in pausa); «Controlla le copie» | +| `POST /api/export/plan`, `/start` (`{ mediaIds \| entryIds \| query+mode \| accountId, copyAgain }`, uno solo), `POST /api/export/copy-again` (`{ copyId }`) | «Copia in…»: riepilogo, avvio (`runIds`, il piano, un messaggio), «Copia di nuovo» di un file tolto o superato | +| `GET /api/export/progress`, `GET /api/export/runs?limit=`, `POST /api/export/interrupt`, `/resume`, `/runs/{id}/resume`, `/runs/{id}/discard`, `GET /runs/{id}/report` | Scheda Esportazione della Dashboard: avanzamento, lavori, interruzione, ripresa, annullamento (i file copiati restano), resoconto (al più 200 problemi) | +| `POST /api/accounts/{id}/export-enabled` (`{ value }`) | «Esporta questo account»: spento, nessuna copia dell'account, neanche da «Copia in…». La scheda (`GET /api/accounts/{id}`) ha `export` con i conteggi dei file dovuti | | `GET /icone/tutte.svg` | Tutte le icone di `wwwroot/icone` (disegnate per Febe) in un solo sprite (``) | Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON. @@ -250,6 +261,10 @@ scrive mai nella libreria vera e non usa la rete. - Ricerca dei profili (`Demo/DemoProfileSearch.cs`): nessun browser; dopo 750 ms profili dimostrativi il cui nome contiene il testo e qualche nome inventato, con foto disegnate 300 ms dopo. Con `fermo`, `scollegato` e `alvolante` risponde `ferma`, `non-pronto` e `non-possibile`. +- Copie esterne (`Demo/DemoExport.cs`): `esporta/Disco USB` (cartella generale), `esporta/Studio Lumen` (cartella + propria di @studio.lumen.demo), `esporta/Chiavetta` (quella che dà la finestra di scelta); @il.porto.demo non si + esporta; di @marta.demo circa due terzi delle foto copiati dal motore vero (un lavoro concluso con resoconto), un file + tolto, uno superato, uno con errore e un lavoro interrotto da riprendere. In veste Docker la radice si chiama `/esporta`. - I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i conti tornino. diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs index c824448..c53ad7e 100644 --- a/src/Febe.Web/Library/DataFolderServices.cs +++ b/src/Febe.Web/Library/DataFolderServices.cs @@ -156,9 +156,10 @@ public sealed class FolderSizes(IClock clock) /// /// «Ricostruisci il database dalla libreria» (spec §8.5) as a background job with its progress and its last report, -/// one at a time. It never moves, renames or deletes a file (rule 12). +/// one at a time, never together with an import or a copy to external folders (the shared , +/// spec §4.10). It never moves, renames or deletes a file (rule 12). /// -public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes) +public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes, LongWorkGate gate, Export.ExportHub? exports = null) { private readonly Lock _gate = new(); private Task? _task; @@ -176,18 +177,32 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock } } - /// Starts the rebuild; false when one is already running. - public bool TryStart() + /// Starts the rebuild; false when one is already running or another long job holds the gate. + public bool TryStart() => TryStart(out _); + + /// + /// Starts the rebuild; false, with the Italian reason in , when a rebuild, an import or a copy + /// to external folders is running. + /// + public bool TryStart(out string? busy) { lock (_gate) { if (_task is { IsCompleted: false }) { + busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild); return false; } + if (!gate.TryEnter(LongWorkKind.Rebuild, out var lease, out var holder)) + { + busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, holder!.Value); + return false; + } + + busy = null; State = RebuildState.Idle with { Running = true, StartedAt = clock.Now }; - _task = Task.Run(RunAsync); + _task = Task.Run(() => RunAsync(lease)); return true; } } @@ -195,8 +210,9 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock /// Waits for the running rebuild (tests). public Task WaitAsync() => _task ?? Task.CompletedTask; - private async Task RunAsync() + private async Task RunAsync(IDisposable lease) { + using var held = lease; var progress = new SyncProgress(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked }); try { @@ -204,6 +220,7 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false); State = State with { Running = false, Report = report, FinishedAt = clock.Now }; changes.Publish(new LibraryChange(clock.Now, null, "rebuild")); + await RecheckExportsAsync().ConfigureAwait(false); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) { @@ -211,6 +228,27 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock } } + /// + /// After a rebuild the account folders may be others: a destination of the copies that now sits inside one of them, + /// or around it, is paused with the reason (spec §4.10). A failure here leaves the rebuild done. + /// + private async Task RecheckExportsAsync() + { + if (exports is null) + { + return; + } + + try + { + await (await exports.GetAsync().ConfigureAwait(false)).Destinations.RecheckAndPauseAsync(CancellationToken.None).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + { + // Nothing is lost: every copy checks its destination again before writing (and pauses it). + } + } + /// Progress reported on the calling thread (no synchronization context to post to). private sealed class SyncProgress(Action action) : IProgress { diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 51d9c86..757ce33 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -219,6 +219,7 @@ span.av.segnaposto{color:var(--testo-2);background:var(--bordo-forte)} .av.g{wid .avviso.ambra{background:var(--ambra-tinta)} .avviso.ambra svg{color:var(--ambra)} .avviso.rosso{background:var(--rosso-tinta)} .avviso.rosso svg{color:var(--rosso)} .avviso b{font-weight:650} +.avviso .btn svg{color:currentColor;margin-top:0} .velo{position:absolute;inset:0;background:var(--velo);z-index:20;display:flex;align-items:center;justify-content:center} .dialogo{background:var(--superficie);border-radius:var(--r-dialogo);box-shadow:var(--ombra-dialogo);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--bordo)} .dialogo header{display:flex;align-items:center;padding:18px 22px 6px} @@ -1160,6 +1161,58 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento .benvenuto{padding-top:40px} } +/* ---------- copie esterne (§4.10, tappa E2): impostazioni, finestre, scheda account, Dashboard ---------- */ +.breve-link{color:inherit;font-weight:650;white-space:nowrap;margin-left:4px} +p.aiuto.descrizione-copie{margin-top:8px} +.nota-copie:not(:empty) ~ .nota-copie:not(:empty){margin-top:10px} +.riga-conteggi{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-top:10px} +.riga-conteggi > span{flex:1;min-width:0} +.stato-copie.avviso{margin-top:10px} +.cartelle-copie .tab td{vertical-align:top} +.cartelle-copie .tab td .dati{display:block;overflow-wrap:anywhere} +.dialogo.destinazione{width:900px} +.dialogo.copia-in{width:600px} +.dialogo.resoconto-copia{width:700px} +.parte-dialogo{padding:12px 0 16px;border-bottom:1px solid var(--bordo)} +.parte-dialogo:first-child{padding-top:2px} +.parte-dialogo:last-child{border-bottom:0;padding-bottom:4px} +.parte-dialogo h3,.resoconto-copia h3{margin:0 0 4px;font-size:14px;font-weight:650} +.parte-dialogo .riga-cartella .campo input{flex:1;min-width:0;border:0;background:transparent;outline:none} +.controllo-cartella{margin-top:8px} +.controllo-cartella:empty{display:none} +.controllo-cartella .avviso{margin-top:2px} +.controllo-cartella p{margin:0} +.sfoglia-elenco li.scelta .sfoglia-voce{background:var(--accento-tinta);font-weight:600} +.sfoglia-elenco li.scelta .sfoglia-voce svg{color:var(--accento)} +.schemi-copie{margin-top:12px} +.destinazione .dialogo-tipi,.destinazione .tipi{margin-top:10px} +.riepilogo-copia{font-size:14px;margin:0 0 12px} +.riepilogo-copia b{font-weight:650} +.destinazioni-copia{list-style:none;margin:0 0 12px;padding:0} +.destinazioni-copia li{display:flex;align-items:flex-start;gap:10px;padding:11px 14px;border-bottom:1px solid var(--bordo)} +.destinazioni-copia li:last-child{border-bottom:0} +.destinazioni-copia li > svg{color:var(--testo-2);margin-top:2px} +.destinazioni-copia .chi-cosa{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px} +.destinazioni-copia .chi-cosa b{font-weight:600;overflow-wrap:anywhere} +.destinazioni-copia .chi-cosa > span{font-size:12.5px;color:var(--testo-2)} +.destinazioni-copia .avviso{margin-top:6px} +.di-nuovo{margin-top:4px} +.di-nuovo .aiuto{margin:4px 0 0 27px} +.copie-esterne .conteggio-copie{margin-top:12px} +.copie-esterne .etichetta-copie{margin:14px 0 6px} +.etichetta-copie + .cartella{margin-top:0} +.vis .scheda dd.riga-copia{display:flex;align-items:center;gap:4px 8px;flex-wrap:wrap} +.vis .scheda dd.riga-copia .btn{height:26px;padding:0 8px;margin-left:-8px} +.tess .segno .copia.parte{font-variant-numeric:tabular-nums} +.esportazione-dashboard{display:flex;flex-direction:column;gap:22px;max-width:980px;padding-top:18px} +.avanzamento-copia{padding:16px 18px} +.avanzamento-copia .misura{margin:12px 0 8px} +.avanzamento-copia .fase-copia{margin:8px 0} +.riga-riprendi + .riga-riprendi{margin-top:8px} +.resoconto-account .num{text-align:right;width:96px} +.problemi-copia li{min-height:0;padding:8px 14px} +.problemi-copia .chi-cosa b{white-space:normal} + /* ---------- animazioni: solo in risposta a un gesto, e mai con le animazioni ridotte ---------- */ @keyframes febe-compare{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}} .dialogo,.menu,.breve{animation:febe-compare .14s ease-out} diff --git a/src/Febe.Web/wwwroot/js/core/ui.js b/src/Febe.Web/wwwroot/js/core/ui.js index 40f649c..18d9a24 100644 --- a/src/Febe.Web/wwwroot/js/core/ui.js +++ b/src/Febe.Web/wwwroot/js/core/ui.js @@ -1,21 +1,26 @@ // Components of the style sheet (appendix B, mockup 13) as functions: dialogs, menus, short notices, switches, // check boxes, avatars. Keyboard first: every control is a real button or input, focus is always visible. +import { withCarried } from './api.js'; import { h, icon, uid } from './dom.js'; import { t } from './text.js'; // ------------------------------------------------------------------------------------------------- short notices let toasts; -/** A short notice at the bottom («Impostazioni salvate.»); errors stay longer. */ -export function toast(message, kind = '') { +/** + * A short notice at the bottom («Impostazioni salvate.»); errors stay longer. link: { label, href } of an internal page + * to go to («Apri l'esportazione»); a notice with a link stays longer too. + */ +export function toast(message, kind = '', link = null) { if (!toasts) { toasts = h('div.brevi', { role: 'status', 'aria-live': 'polite' }); document.body.append(toasts); } - const item = h(`div.breve${kind ? '.' + kind : ''}`, kind === 'errore' ? icon('octagon-alert', 's') : icon('circle-check', 's'), h('span', message)); + const item = h(`div.breve${kind ? '.' + kind : ''}`, kind === 'errore' ? icon('octagon-alert', 's') : icon('circle-check', 's'), h('span', message), + link ? h('a.breve-link', { href: withCarried(link.href) }, link.label) : null); toasts.append(item); - setTimeout(() => item.remove(), kind === 'errore' ? 8000 : 4000); + setTimeout(() => item.remove(), kind === 'errore' || link ? 8000 : 4000); } /** Shows the message of an error (ApiError or anything else). */ diff --git a/src/Febe.Web/wwwroot/js/pages/account.js b/src/Febe.Web/wwwroot/js/pages/account.js index 91bb51e..5c49dad 100644 --- a/src/Febe.Web/wwwroot/js/pages/account.js +++ b/src/Febe.Web/wwwroot/js/pages/account.js @@ -2,6 +2,9 @@ // the link to the profile; tabs Contenuti (Post, Storie as a regular 9:16 grid, In evidenza grouped by collection, // Taggati, Profilo when there is more than one picture), Impostazioni (with «Con queste impostazioni» recomputed at // every change and the fixed save bar) and Cronologia (the checks with their outcome). +// Copies to external folders (spec §4.10, tappa E2): in Contenuti the menu of the CSV icon, «Copia in…» in the +// selection bar and the «Copie» filter; in Impostazioni the block «Copie esterne» under «Cartella», with «Esporta +// questo account» (on unless switched off), the folder of the copies and «312 su 1.204 non ancora copiati». import { api, download, withCarried } from '../core/api.js'; import { caps, serverNow } from '../core/context.js'; @@ -15,6 +18,7 @@ import { confirmDelete, selectionBar } from './library.js'; import { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitch, storedMode } from './mosaic.js'; import { kindName, orderEditor, orderOrDefault } from './download-order.js'; import { openViewer } from './viewer.js'; +import { copiesApi, copiesLabel, copiesMenu, copyDialog, destinationDialog, exportButton, exportMenu, separator } from './export-dialogs.js'; const KINDS = [ { key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' }, @@ -108,6 +112,9 @@ async function contentsTab(page, route, detail) { const available = KINDS.filter((k) => k.key !== 'profilo' || s.profilePictures > 1); let kind = available.find((k) => k.key === route.query.get('tipo')) || available.find((k) => s[k.stat] > 0) || available[0]; let period = route.query.get('periodo') || ''; + let copies = copiesApi(route.query.get('copie')) ? route.query.get('copie') : ''; + // The «Copie» filter and «Copia in…» make sense once this account has a folder of the copies. + const hasDestination = Boolean(detail.export && detail.export.destination); let mosaic = null; // «Raggruppa i post» / «Tutte le foto» (spec §4.6): one choice for the views of every account, apart from the Libreria. let mode = storedMode('account'); @@ -121,8 +128,10 @@ async function contentsTab(page, route, detail) { let showToken = 0; const chips = h('div.filtri', { role: 'group', 'aria-label': t('scheda.linguette.contenuti') }); const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '150px' } }); + const copiesButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', hidden: !hasDestination && !copies, style: { minWidth: '96px' } }); const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona'))); - page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, h('div.destra', modes, selectButton))); + const csvButton = exportButton(); + page.tools(h('div', { style: { display: 'contents' } }, chips, periodButton, copiesButton, h('div.destra', csvButton, modes, selectButton))); const host = h('div'); fill(page.body, host); @@ -136,6 +145,8 @@ async function contentsTab(page, route, detail) { }, }, t(k.label), h('i', number(s[k.stat]))))); fill(periodButton, h('span.val', period ? t(`libreria.periodi.${period}`) : t('libreria.periodi.qualsiasi')), icon('chevron-down', 's')); + fill(copiesButton, h('span.val', copiesLabel(copies)), icon('chevron-down', 's')); + copiesButton.classList.toggle('attivo', Boolean(copies)); selectButton.hidden = kind.key === 'evidenza'; // «In evidenza» is drawn by collection, one tile per item (almost always a single story): no switch there. modes.hidden = kind.key === 'evidenza'; @@ -149,8 +160,28 @@ async function contentsTab(page, route, detail) { show(); })); + copiesButton.addEventListener('click', () => copiesMenu(copiesButton, copies, (value) => { + copies = value; + setQuery({ copie: value || null }); + show(); + })); + csvButton.addEventListener('click', () => exportMenu(csvButton, { + hasDestinations: hasDestination, + csv: async () => { + try { + await download('/api/entries/export', { query: query() }, 'febe-elementi.csv'); + toast(t('libreria.esportatoFiltro')); + } catch (error) { + showError(error); + } + }, + copy: () => copyDialog({ query: query(), mode: mode === 'files' ? 'files' : 'grouped' }), + })); + function query() { const q = new URLSearchParams({ accounts: String(detail.account.id), kind: kind.api }); + const copiesFilter = copiesApi(copies); + if (copiesFilter) q.set('copies', copiesFilter); const today = caps().today; const add = (n) => new Date(Date.parse(`${today}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10); const year = Number(today.slice(0, 4)); @@ -177,6 +208,9 @@ async function contentsTab(page, route, detail) { showError(error); } }, + copySelected: hasDestination + ? () => copyDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }) + : null, deleteSelected: async () => { const { ids, files } = mosaic.selectedEntries(); const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null); @@ -234,11 +268,16 @@ async function contentsTab(page, route, detail) { } const onChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 500); + const onMarks = later(() => mosaic && mosaic.refreshMarks().catch(() => {}), 600); page.onLibrary((change) => { - if (!change.accountId || change.accountId === detail.account.id) onChange(); + if (!change.accountId || change.accountId === detail.account.id) { + onChange(); + if (change.reason === 'export') onMarks(); + } }); page.onLeave(() => { onChange.cancel(); + onMarks.cancel(); if (mosaic) mosaic.destroy(); if (highlightCleanup) highlightCleanup(); }); @@ -467,7 +506,8 @@ function settingsTab(page, detail) { h('div.riga-campi', depthExtra), h('div', { style: { marginTop: '14px' } }, storyVideos)), h('div.sezione', h('h2.sez', t('impAccount.cartella')), h('p.aiuto', t(c.foldersReadOnly ? 'impAccount.cartellaDocker' : 'impAccount.cartellaAiuto')), - h('div.cartella', h('div.campo.sola', icon('folder', 's'), folderValue), folderActions))); + h('div.cartella', h('div.campo.sola', icon('folder', 's'), folderValue), folderActions)), + copiesBlock(page, detail)); function drawPlan() { const lines = plan.lines.map((l) => { @@ -540,6 +580,134 @@ function settingsTab(page, detail) { }); } +// --------------------------------------------------------------------------------------------- copie esterne + +/** + * «Copie esterne» (spec §4.10, mockup 05): «Esporta questo account», which acts at once and is not part of the form + * (decision D1: on unless switched off), where the copies go, how many files are still to copy and «Copia in…». + */ +function copiesBlock(page, detail) { + const account = detail.account; + const box = h('div.sezione.copie-esterne'); + let data = detail.export || { enabled: true, hasOwnFolder: false, destination: null, due: 0, notCopied: 0, removedOrSuperseded: 0, failed: 0 }; + const body = h('div.copie-corpo'); + const toggleBox = toggle({ + checked: data.enabled, + label: t('esportazione.account.interruttore'), + onchange: async (value, input) => { + input.disabled = true; + try { + const result = await api(`/api/accounts/${account.id}/export-enabled`, { method: 'POST', body: { value } }); + toast(result.message); + await reload(); + } catch (error) { + input.checked = !value; + showError(error); + } finally { + input.disabled = false; + } + }, + }); + + async function reload() { + try { + const fresh = await api(`/api/accounts/${account.id}`, { signal: page.signal }); + data = fresh.export || data; + toggleBox.input.checked = data.enabled; + draw(); + } catch (error) { + if (error.name !== 'AbortError') showError(error); + } + } + + async function chooseOwn() { + const saved = await destinationDialog({ scope: 'account', accountId: account.id, username: account.username, destination: data.hasOwnFolder ? data.destination : null }); + if (saved) await reload(); + } + + async function useGeneral() { + const general = data.hasOwnFolder && data.destination; + if (!general) return; + // Is there a general folder to fall back to? The overview says so. + let overview = null; + try { + overview = await api('/api/export'); + } catch (error) { + showError(error); + return; + } + const fallback = Boolean(overview.general); + const ok = await confirmDialog({ + title: t(fallback ? 'esportazione.account.usaGeneraleTitolo' : 'esportazione.account.togliTitolo', { nome: account.username }), + text: t(fallback ? 'esportazione.account.usaGeneraleTesto' : 'esportazione.account.togliTesto'), + buttons: [ + { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true }, + { label: t(fallback ? 'esportazione.account.usaGenerale' : 'esportazione.togliSi'), value: true, kind: fallback ? 'primo' : 'pericolo' }, + ], + }); + if (!ok) return; + try { + const result = await api(`/api/export/destinations/${data.destination.id}`, { method: 'DELETE' }); + toast(result.message); + await reload(); + } catch (error) { + showError(error); + } + } + + function draw() { + const d = data.destination; + const rows = []; + if (d) { + const where = data.hasOwnFolder ? d.display : `${d.display}${separator(d.display)}${account.username}`; + // The kind of folder goes above the field, like the labels of mockup 08: the path keeps the whole width. + rows.push(h('span.etichetta.etichetta-copie', t(data.hasOwnFolder ? 'esportazione.account.sua' : 'esportazione.account.generale'))); + rows.push(h('div.cartella', + h('div.campo.sola', { title: where }, icon('hard-drive', 's'), h('span.val.dati', where)), + data.hasOwnFolder + ? [h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.modifica')), + h('button.btn.nudo', { type: 'button', onclick: useGeneral }, t('esportazione.account.usaGenerale'))] + : h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.account.scegliSua')))); + if (d.pausedAt || d.problem) { + rows.push(h('div.avviso.ambra', { style: { marginTop: '10px' } }, icon('pause', 's'), h('span', t('esportazione.pausa', { problema: d.problem || '' })))); + } + } else { + rows.push(h('div.cartella', + h('div.campo.sola', icon('folder', 's'), h('span.val.tenue', t('esportazione.nessunaCartella'))), + h('button.btn', { type: 'button', onclick: chooseOwn }, t('esportazione.account.scegliSua'))), + h('p.aiuto', { style: { marginTop: '8px' } }, t('esportazione.account.nessuna'))); + } + if (!data.enabled) { + rows.push(h('p.aiuto.conteggio-copie', icon('info', 'xs'), ' ', t('esportazione.account.spento'))); + } else if (d) { + let count; + if (!data.due) count = t('esportazione.account.nessunFile'); + else if (!data.notCopied) count = t('esportazione.account.tuttiCopiati', { n: data.due }); + else count = t('esportazione.account.conteggio', { n: data.notCopied, totale: data.due }); + const extra = []; + if (data.removedOrSuperseded) extra.push(t('esportazione.account.tolti', { n: data.removedOrSuperseded })); + if (data.failed) extra.push(t('esportazione.account.falliti', { n: data.failed })); + rows.push(h('div.riga-conteggi.conteggio-copie', + h('span', h('b', count), extra.length ? ` · ${extra.join(' · ')}` : ''), + h('button.btn', { type: 'button', onclick: () => copyDialog({ accountId: account.id }, { title: t('esportazione.copia.titolo') }) }, icon('copy'), t('esportazione.account.copiaIn')))); + } + fill(body, rows); + } + + draw(); + fill(box, + h('h2.sez', t('esportazione.account.titolo')), + h('p.aiuto', t('esportazione.account.aiuto')), + h('div', { style: { margin: '12px 0 4px' } }, toggleBox), + body); + const onChange = later(() => reload(), 600); + page.onLibrary((change) => { + if (change.reason === 'export' && (!change.accountId || change.accountId === account.id)) onChange(); + }); + page.onLeave(() => onChange.cancel()); + return box; +} + // --------------------------------------------------------------------------------------------- history async function historyTab(page, detail) { diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js new file mode 100644 index 0000000..37d9730 --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js @@ -0,0 +1,294 @@ +// Dashboard, tab «Esportazione» (spec §7.9, §10.3, tappa E2; from mockup 06 and step 2 of mockup 09): the copy at +// work with its progress and «Interrompi»; the jobs to resume («Riprendi», «Annulla») and the folders in pause +// («Riprova»); the last jobs, each with its resoconto. The progress is asked every second while a copy works, every five +// seconds otherwise (decision D20), as the import does. A pause is an amber notice here, never the red strip. + +import { api } from '../core/api.js'; +import { h, icon, fill, later } from '../core/dom.js'; +import { t, at, bytes, capitalize, number } from '../core/text.js'; +import { confirmDialog, dialog, label, showError, toast } from '../core/ui.js'; + +const STATE_LOOK = { + running: ['accento', 'play'], + interrupted: ['ambra', 'pause'], + paused: ['ambra', 'pause'], + completed: ['verde', 'circle-check'], + cancelled: ['', 'x'], +}; + +const FILE_STATES = ['copied', 'adopted', 'alreadyCopied', 'skipped', 'missing', 'failed', 'pending']; + +export async function mountExport(page) { + page.title(t('attivita.titolo')); + document.title = t('app.titoloPagina', { pagina: `${t('esportazione.dashboard.esportazione')} · ${t('attivita.titolo')}` }); + const current = h('section.blocco.copia-in-corso'); + const pending = h('section.blocco', { hidden: true }); + const recent = h('section.blocco'); + fill(page.body, h('div.attivita.esportazione-dashboard', current, pending, recent)); + + let overview = null; + let runs = []; + let progress = null; + let wasRunning = null; + let timer = 0; + let ticks = 0; + let stopped = false; + // One reading at a time: a command or a change during a reading asks for one more right after it, never a second chain. + let inFlight = false; + let rerun = false; + page.onLeave(() => { + stopped = true; + clearTimeout(timer); + }); + + async function loadSide() { + try { + [overview, runs] = await Promise.all([ + api('/api/export', { signal: page.signal }), + api('/api/export/runs?limit=20', { signal: page.signal }), + ]); + drawPending(); + drawRecent(); + } catch (error) { + if (error.name !== 'AbortError') showError(error); + } + } + + async function poll() { + if (stopped) return; + if (inFlight) { + rerun = true; + return; + } + inFlight = true; + clearTimeout(timer); + try { + await read(); + } finally { + inFlight = false; + } + if (stopped) return; + clearTimeout(timer); + if (rerun) { + rerun = false; + wasRunning = null; + poll(); + return; + } + timer = setTimeout(poll, progress && progress.running ? 1000 : 5000); + } + + async function read() { + try { + progress = await api('/api/export/progress', { signal: page.signal }); + } catch (error) { + if (error.name === 'AbortError') return; + progress = null; + } + drawCurrent(); + const running = Boolean(progress && progress.running); + ticks += 1; + // The jobs and the folders follow the copy: when it starts or ends, and every few seconds while it works. + if (running !== wasRunning || !running || ticks % 5 === 0) await loadSide(); + wasRunning = running; + } + + /** Asks again now (after a command), keeping one timer. */ + function again() { + clearTimeout(timer); + wasRunning = null; + poll(); + } + + // ------------------------------------------------------------------------------------------- in corso + function drawCurrent() { + const p = progress; + const head = h('div.testa-blocco', h('h2', t('esportazione.dashboard.inCorso'))); + if (!p || !p.running) { + fill(current, head, h('p.vuoto-elenco.pannello', t('esportazione.dashboard.nessunaInCorso'))); + return; + } + const percent = Math.round((p.fraction || 0) * 100); + const bar = h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(percent), 'aria-label': t('esportazione.dashboard.copio', { cartella: p.destination || '' }) }, + h('i', { style: { width: `${percent}%` } })); + const phase = p.phase && p.phase !== 'copying' && p.phase !== 'finished' ? t(`esportazione.dashboard.fasi.${p.phase}`) : ''; + const count = [t('esportazione.dashboard.fatti', { fatti: number(p.filesDone), totale: number(p.filesTotal) })]; + if (p.bytesTotal) count.push(t('esportazione.dashboard.byte', { fatti: bytes(p.bytesDone), totale: bytes(p.bytesTotal) })); + fill(current, head, h('div.pannello.avanzamento-import.avanzamento-copia', + h('h2.sez', t('esportazione.dashboard.copio', { cartella: p.destination || '' })), + bar, + h('p.conteggio.dati', count.join(' · ')), + phase ? h('p.avviso.ambra.fase-copia', icon(p.phase === 'waitingForSession' ? 'hourglass' : 'info', 's'), h('span', phase)) : null, + h('p.aiuto.piccolo.file-corrente', p.currentFile ? t('esportazione.dashboard.ora', { file: p.currentFile }) : ''), + h('div.riga-azione', h('button.btn', { type: 'button', onclick: interrupt }, icon('pause', 's'), t('esportazione.dashboard.interrompi'))))); + } + + async function interrupt(e) { + e.currentTarget.disabled = true; + try { + const result = await api('/api/export/interrupt', { method: 'POST' }); + toast(result.message); + } catch (error) { + showError(error); + } + again(); + } + + // ------------------------------------------------------------------------------------------- da riprendere + function drawPending() { + const waiting = runs.filter((r) => !r.running && (r.state === 'interrupted' || r.state === 'paused')); + const folders = overview ? [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem)) : []; + pending.hidden = !waiting.length && !folders.length; + if (pending.hidden) { + pending.replaceChildren(); + return; + } + const busy = Boolean(progress && progress.running); + fill(pending, + h('div.testa-blocco', h('h2', t('esportazione.dashboard.daRiprendere')), + waiting.length > 1 ? h('div.destra', h('button.btn.piccolo', { type: 'button', disabled: busy, onclick: resumeAll }, icon('play', 's'), t('esportazione.dashboard.riprendiTutte'))) : null), + folders.map((d) => h('div.avviso.ambra.avviso-azione.riga-riprendi', icon('pause', 's'), + h('span', t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') })), + h('button.btn.piccolo', { type: 'button', onclick: (e) => retry(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.riprova')))), + waiting.map((r) => h('div.avviso.ambra.avviso-azione.riga-riprendi', icon('pause', 's'), + h('span', r.state === 'paused' + ? t('esportazione.dashboard.ferma', { cartella: r.destination, problema: r.error || t('esportazione.inPausa') }) + : t('esportazione.dashboard.interrotta', { cartella: r.destination, fatti: number(r.done), totale: number(r.total) })), + h('button.btn.primo.piccolo', { type: 'button', disabled: busy, onclick: (e) => resume(r, e.currentTarget) }, icon('play', 's'), t('esportazione.dashboard.riprendi')), + h('button.btn.nudo.piccolo', { type: 'button', onclick: () => discard(r) }, t('esportazione.dashboard.annulla'))))); + } + + async function resume(run, button) { + button.disabled = true; + try { + const result = await api(`/api/export/runs/${run.id}/resume`, { method: 'POST' }); + toast(result.message); + } catch (error) { + button.disabled = false; + showError(error); + } + again(); + } + + async function resumeAll(e) { + e.currentTarget.disabled = true; + try { + const result = await api('/api/export/resume', { method: 'POST' }); + toast(result.message); + } catch (error) { + showError(error); + } + again(); + } + + async function retry(d, button) { + button.disabled = true; + try { + const result = await api(`/api/export/destinations/${d.id}/resume`, { method: 'POST' }); + toast(result.message); + } catch (error) { + button.disabled = false; + showError(error); + } + again(); + } + + async function discard(run) { + const ok = await confirmDialog({ + title: t('esportazione.dashboard.annullaTitolo', { cartella: run.destination }), + text: t('esportazione.dashboard.annullaTesto'), + buttons: [ + { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true }, + { label: t('esportazione.dashboard.annullaSi'), value: true, kind: 'pericolo' }, + ], + }); + if (!ok) return; + try { + const result = await api(`/api/export/runs/${run.id}/discard`, { method: 'POST' }); + toast(result.message); + } catch (error) { + showError(error); + } + again(); + } + + // ------------------------------------------------------------------------------------------- ultimi lavori + function drawRecent() { + const head = h('div.testa-blocco', h('h2', t('esportazione.dashboard.ultimi'))); + if (!runs.length) { + fill(recent, head, h('p.vuoto-elenco.pannello', t('esportazione.dashboard.vuoto'))); + return; + } + fill(recent, head, h('div.pannello', h('ul.elenco-attivita.largo', runs.map((r) => { + const state = r.running ? 'running' : r.state; + const [kind, look] = STATE_LOOK[state] || STATE_LOOK.cancelled; + return h('li', + h('span.quando.dati', capitalize(at(r.startedAt))), + h('div.chi-cosa', + h('b', jobName(r)), + h('span', [t('esportazione.dashboard.fatti', { fatti: number(r.done), totale: number(r.total) }), r.error].filter(Boolean).join(' · '))), + label(t(`esportazione.dashboard.stati.${state}`), kind, look), + h('button.btn.piccolo', { type: 'button', onclick: () => openReport(r) }, t('esportazione.dashboard.resoconto'))); + })))); + } + + const onChange = later(() => again(), 400); + page.onLibrary((change) => { + if (change.reason === 'export') onChange(); + }); + page.onLeave(() => onChange.cancel()); + await poll(); +} + +function jobName(run) { + return t(run.kind === 'recognize' ? 'esportazione.dashboard.lavoroControllo' : 'esportazione.dashboard.lavoroCopia', { cartella: run.destination }); +} + +/** The resoconto of a job: files per state, per account, and the files that need a look (at most 200). */ +async function openReport(run) { + let report; + try { + report = await api(`/api/export/runs/${run.id}/report`); + } catch (error) { + showError(error); + return; + } + const r = report.run; + const when = [t('esportazione.dashboard.iniziata', { quando: at(r.startedAt) })]; + if (r.completedAt) when.push(t('esportazione.dashboard.finita', { quando: at(r.completedAt) })); + const states = FILE_STATES.filter((s) => report.byState[s]).map((s) => t(`esportazione.dashboard.statiFile.${s}`, { n: report.byState[s] })); + if (report.bytesCopied) states.push(t('esportazione.dashboard.copiatiByte', { spazio: bytes(report.bytesCopied) })); + const accounts = report.accounts.length + ? h('div.pannello', h('table.tab.resoconto-account', + h('thead', h('tr', + h('th', { scope: 'col' }, t('esportazione.dashboard.colonne.account')), + h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.copiati')), + h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.gia')), + h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.saltati')), + h('th.num', { scope: 'col' }, t('esportazione.dashboard.colonne.falliti')))), + h('tbody', report.accounts.map((a) => h('tr', + h('td', `@${a.username}`), + h('td.num.dati', number(a.copied)), + h('td.num.dati', number(a.alreadyCopied)), + h('td.num.dati', number(a.skipped)), + h('td.num.dati', number(a.failed))))))) + : null; + const problems = report.problems.length + ? h('div.pannello', h('ul.elenco-attivita.problemi-copia', report.problems.map((p) => h('li', + h('div.chi-cosa', h('b', `@${p.username}`, p.path ? h('span.codice.dati', p.path) : null), h('span', p.text)))))) + : h('p.aiuto', t('esportazione.dashboard.nessunProblema')); + await dialog({ + title: t('esportazione.dashboard.resocontoTitolo', { lavoro: jobName(r) }), + className: 'resoconto-copia', + build: (close) => ({ + body: h('div.contenuto', + h('p.aiuto', `${when.join(', ')} · ${t(`esportazione.dashboard.stati.${r.running ? 'running' : r.state}`)}`), + h('p.riepilogo-copia', states.join(' · ')), + accounts ? h('h3', t('esportazione.dashboard.perAccount')) : null, + accounts, + h('h3', t('esportazione.dashboard.problemi')), + problems), + footer: h('footer', h('div.destra', h('button.btn', { type: 'button', autofocus: true, onclick: () => close() }, t('comune.chiudi')))), + }), + }); +} diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard.js b/src/Febe.Web/wwwroot/js/pages/dashboard.js index 8602f18..5e333e7 100644 --- a/src/Febe.Web/wwwroot/js/pages/dashboard.js +++ b/src/Febe.Web/wwwroot/js/pages/dashboard.js @@ -23,9 +23,17 @@ const QUEUE_ROWS = 5; const THUMBS = 8; export default { - async mount(page) { + async mount(page, route) { page.title(t('attivita.titolo')); + const tab = route && route.params && route.params.scheda === 'esportazione' ? 'esportazione' : 'motore'; + page.tabs(dashboardTabs(tab)); + // The tab «Esportazione» (spec §7.9, §10.3, tappa E2): the copies to external folders, not the engine. + if (tab === 'esportazione') { + const module = await import('./dashboard-export.js'); + return module.mountExport(page); + } const notice = h('div'); + const exportNotice = h('div'); const now = h('div.ora-testo'); const preview = previewBox(page); const today = h('section.blocco.oggi-basso'); @@ -43,7 +51,7 @@ export default { h('section.cruscotto.pannello', preview.element, h('div.cruscotto-lato', now, budgets)), suspended, today, h('div.due-colonne.storia-coda', history.element, queue.element), - notice, incidents, alerts)); + exportNotice, notice, incidents, alerts)); let latest = null; page.onEngine((state) => { @@ -62,11 +70,17 @@ export default { async function loadSide() { first.check(); try { - const [counts, history, recent] = await Promise.all([ + const [counts, history, recent, exports] = await Promise.all([ api('/api/duplicates/count', { signal: page.signal }), api('/api/engine/incidents', { signal: page.signal }), api('/api/alerts', { signal: page.signal }), + // The copies are not the engine: without an answer the notice is simply not there. + api('/api/export', { signal: page.signal }).catch((error) => { + if (error.name === 'AbortError') throw error; + return null; + }), ]); + drawExportNotice(exportNotice, exports); drawNotice(notice, counts); drawIncidents(incidents, history); drawAlerts(alerts, recent); @@ -84,6 +98,15 @@ export default { }, }; +// ------------------------------------------------------------------------------------------------- tabs + +/** «Motore» and «Esportazione» under the title (spec §7.9: the export has its own tab, never the red strip). */ +function dashboardTabs(tab) { + const link = (key, href) => h(`a${tab === key ? '.qui' : ''}`, { href: withCarried(href), 'aria-current': tab === key ? 'page' : null }, t(`esportazione.dashboard.${key}`)); + return h('nav.linguette.linguette-dashboard', { 'aria-label': t('esportazione.dashboard.linguette') }, + link('motore', '/dashboard'), link('esportazione', '/dashboard/esportazione')); +} + // ------------------------------------------------------------------------------------------------- first start /** @@ -661,6 +684,23 @@ function drawNotice(box, counts) { h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi')))); } +/** + * A destination of the copies in pause, or copies left to resume (spec §4.10): an amber notice with the way to the tab + * «Esportazione». Never the red strip, which stays the engine's. + */ +function drawExportNotice(box, overview) { + if (!overview) { + box.replaceChildren(); + return; + } + const paused = [overview.general, ...(overview.own || [])].filter((d) => d && (d.pausedAt || d.problem)); + const items = paused.map((d) => t('esportazione.dashboard.cartellaInPausa', { cartella: d.label, problema: d.problem || t('esportazione.inPausa') })); + if (!paused.length && overview.unfinishedRuns) items.push(t('esportazione.dashboard.avvisoDaRiprendere', { n: overview.unfinishedRuns })); + fill(box, items.map((text) => h('div.avviso.ambra.avviso-azione', { style: { marginBottom: '10px' } }, icon('pause', 's'), + h('span', text), + h('a.btn.piccolo', { href: withCarried('/dashboard/esportazione') }, t('esportazione.apriEsportazione'))))); +} + /** 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 || []; diff --git a/src/Febe.Web/wwwroot/js/pages/export-dialogs.js b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js new file mode 100644 index 0000000..76b1112 --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/export-dialogs.js @@ -0,0 +1,519 @@ +// Copies to external folders (spec §4.10, §10.3, tappa E2): the pieces shared by the pages. The destination dialog +// (folder: native picker on the desktop, the subfolders of /esporta in Docker; content types; «Come la libreria» or a +// scheme of its own with the «Risultato» tree), «Copia in…» (the summary of what would be copied, one row per +// destination, «Copia di nuovo anche i N tolti o superati» unchecked), the menu of the CSV icon and the «Copie» filter. +// «Automatica» and the formats are not shown in this tappa: there is nothing behind them yet (decisions D7, D8). + +import { api } from '../core/api.js'; +import { h, icon, fill, later } from '../core/dom.js'; +import { t, bytes } from '../core/text.js'; +import { checkbox, dialog, menu, radio, showError, toast } from '../core/ui.js'; + +/** Content types of a destination, as the API names them, in the order of the dialog. */ +export const TYPES = [ + { key: 'postFoto', icon: 'image' }, + { key: 'postVideo', icon: 'clapperboard' }, + { key: 'storie', icon: 'circle-dashed' }, + { key: 'evidenza', icon: 'star' }, + { key: 'taggati', icon: 'square-user' }, + { key: 'profilo', icon: 'circle-user' }, +]; + +/** The «Copie» filter: the value in the page address (Italian) and in the API query. */ +export const COPIES = [ + { key: 'non-copiati', api: 'notCopied', label: 'esportazione.filtro.nonCopiati' }, + { key: 'copiati', api: 'copied', label: 'esportazione.filtro.copiati' }, + { key: 'tolti', api: 'removedOrSuperseded', label: 'esportazione.filtro.tolti' }, +]; + +/** The API value of the «Copie» filter of the address, or null. */ +export function copiesApi(value) { + const found = COPIES.find((c) => c.key === value); + return found ? found.api : null; +} + +/** The label of the «Copie» menu: its name until a value is chosen (spec §10.3). */ +export function copiesLabel(value) { + const found = COPIES.find((c) => c.key === value); + return found ? t(found.label) : t('esportazione.filtro.titolo'); +} + +/** The radio menu of the «Copie» filter; onPick('' | 'non-copiati' | 'copiati' | 'tolti'). */ +export function copiesMenu(anchor, value, onPick) { + return menu(anchor, [ + { label: t('esportazione.filtro.tutti'), value: '', checked: !value, radio: true }, + ...COPIES.map((c) => ({ label: t(c.label), value: c.key, checked: value === c.key, radio: true })), + ], onPick); +} + +/** + * The menu of the CSV icon (spec §10.3): «Esporta l'elenco (CSV)» and «Copia i file in…», the second only usable + * when a destination exists. + */ +export function exportMenu(anchor, { hasDestinations, csv, copy }) { + return menu(anchor, [ + { label: t('esportazione.libreria.menuCsv'), icon: 'file-down', value: 'csv' }, + { label: t('esportazione.libreria.menuCopia'), icon: 'copy', value: 'copy', disabled: !hasDestinations }, + ], (value) => { + if (value === 'csv') csv(); + if (value === 'copy') copy(); + }, { align: 'right' }); +} + +/** The CSV icon of the tools row, a menu anchor. */ +export function exportButton() { + return h('button.btn.nudo.piccolo.solo-icona', { + type: 'button', title: t('esportazione.libreria.menu'), 'aria-label': t('esportazione.libreria.menu'), 'aria-haspopup': 'menu', 'aria-expanded': 'false', + }, icon('file-down')); +} + +/** «54 copiati · 1 tolto · 1 superato · 1 non riuscito» of a destination (zeros left out, «copiati» always). */ +export function countsText(counts) { + const c = counts || {}; + const parts = [t('esportazione.conteggi.copiati', { n: c.copied || 0 })]; + if (c.removed) parts.push(t('esportazione.conteggi.tolti', { n: c.removed })); + if (c.superseded) parts.push(t('esportazione.conteggi.superati', { n: c.superseded })); + if (c.failed) parts.push(t('esportazione.conteggi.falliti', { n: c.failed })); + return parts.join(' · '); +} + +/** «Tipi: post foto, storie · nomi come la libreria». */ +export function describe(destination) { + const types = destination.types.length === TYPES.length + ? t('esportazione.tuttiITipi') + : destination.types.map((k) => t(`esportazione.tipi.${k}`).toLowerCase()).join(', '); + const own = destination.namingScheme || destination.highlightNamingScheme || destination.profileNamingScheme; + return `${t('esportazione.tipiScelti', { elenco: types })} · ${t(own ? 'esportazione.nomiSuoi' : 'esportazione.nomiLibreria')}`; +} + +/** The separator of the folders of a path as shown («/» in Docker, «\» on Windows). */ +export function separator(display) { + return String(display || '').startsWith('/') ? '/' : '\\'; +} + +// ------------------------------------------------------------------------------------------------- destination + +/** + * The dialog of a destination: the general folder, or the own folder of an account. overview: GET /api/export (asked + * when missing). destination: the one being changed, or null for a new one. Resolves with the saved destination, or + * undefined when closed. + */ +export async function destinationDialog({ scope, accountId = null, username = '', destination = null, overview = null }) { + let info = overview; + if (!info) { + try { + info = await api('/api/export'); + } catch (error) { + showError(error); + return undefined; + } + } + const root = info.root; + const docker = root.docker; + const general = scope === 'general'; + const original = destination ? (docker ? relativeOf(destination.display, root.root) : destination.rootPath) : ''; + const state = { + path: original, + check: null, + checking: false, + types: new Set(destination ? destination.types : TYPES.map((x) => x.key)), + own: Boolean(destination && (destination.namingScheme || destination.highlightNamingScheme || destination.profileNamingScheme)), + naming: (destination && destination.namingScheme) || info.library.general, + highlight: (destination && destination.highlightNamingScheme) || info.library.highlight, + profile: (destination && destination.profileNamingScheme) || info.library.profile, + errors: [], + saving: false, + }; + + return dialog({ + title: general ? t('esportazione.dialogo.titoloGenerale') : t('esportazione.dialogo.titoloAccount', { nome: username }), + className: 'destinazione', + build: (close) => { + const save = h('button.btn.primo', { type: 'button', disabled: true, onclick: () => submit(close) }, icon('check'), t('esportazione.dialogo.salva')); + + // ------------------------------------------------------------------------------- folder + const checkLine = h('div.controllo-cartella', { 'aria-live': 'polite' }); + const changedNote = h('p.avviso-testo', { hidden: true }, icon('triangle-alert', 'xs'), ' ', t('esportazione.dialogo.cambiata')); + let folderPart; + const pathInput = h('input.dati', { type: 'text', value: state.path, id: 'cartella-copie', spellcheck: 'false', autocomplete: 'off', 'aria-describedby': 'cartella-copie-aiuto' }); + if (!docker) { + const pick = root.pickFolder ? h('button.btn', { type: 'button', onclick: pickFolder }, icon('folder-open', 's'), t('esportazione.dialogo.sfoglia')) : null; + folderPart = h('div', + h('label.etichetta', { for: 'cartella-copie' }, t('esportazione.dialogo.percorso')), + h('div.riga-cartella', h('label.campo', icon('folder', 's'), pathInput), pick)); + const typed = later(() => checkFolder(pathInput.value.trim()), 500); + pathInput.addEventListener('input', () => { + state.path = pathInput.value.trim(); + state.check = null; + drawCheck(); + typed(); + }); + } else { + folderPart = h('div.sfoglia-copie'); + browse(parentOf(state.path)); + } + + async function pickFolder() { + try { + const result = await api('/api/export/pick-folder', { method: 'POST', body: { destinationId: destination ? destination.id : null } }); + if (!result.path) return; + pathInput.value = result.path; + state.path = result.path; + checkFolder(result.path); + } catch (error) { + showError(error); + } + } + + // focusPath: the folder whose button had the keyboard; after the list is drawn again the focus goes back there + // (or to the first folder), never lost on the page behind the dialog. + async function browse(path, focusPath = null) { + const hadFocus = folderPart.contains(document.activeElement); + try { + const list = await api(`/api/export/folders${path ? `?path=${encodeURIComponent(path)}` : ''}`); + fill(folderPart, h('div.pannello.sfoglia', + h('div.sfoglia-testa', icon('folder-open', 's'), h('span.dati', list.display), + list.parent != null ? h('button.btn.nudo.piccolo.destra', { type: 'button', onclick: () => browse(list.parent || null) }, icon('arrow-left', 's'), t('esportazione.dialogo.su')) : null), + list.folders.length + ? h('ul.sfoglia-elenco', list.folders.map((f) => h(`li${f.path === state.path ? '.scelta' : ''}`, + h('button.sfoglia-voce', { type: 'button', dataset: { path: f.path }, 'aria-pressed': String(f.path === state.path), onclick: () => { state.path = f.path; checkFolder(f.path); browse(list.relative || null, f.path); } }, + icon(f.path === state.path ? 'circle-check' : 'folder', 's'), h('span', f.name)), + f.hasSubfolders ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('esportazione.dialogo.apri', { nome: f.name }), onclick: () => browse(f.path) }, icon('chevron-right', 's')) : null))) + : h('p.vuoto-elenco', t('esportazione.dialogo.vuota')))); + if (hadFocus) { + const items = [...folderPart.querySelectorAll('.sfoglia-voce')]; + const target = items.find((b) => focusPath != null && b.dataset.path === focusPath) || items[0] + || folderPart.querySelector('button'); + if (target) target.focus(); + } + } catch (error) { + fill(folderPart, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', error.message))); + } + } + + let checkToken = 0; + async function checkFolder(path) { + const mine = ++checkToken; + if (!path) { + state.check = null; + drawCheck(); + return; + } + state.checking = true; + drawCheck(); + try { + const result = await api('/api/export/check-folder', { method: 'POST', body: { path } }); + if (mine !== checkToken) return; + state.check = result; + } catch (error) { + if (mine !== checkToken) return; + state.check = { accepted: false, problem: error.message }; + } + state.checking = false; + drawCheck(); + } + + function drawCheck() { + const c = state.check; + if (state.checking) fill(checkLine, h('p.aiuto', t('esportazione.dialogo.controllo'))); + else if (!c) fill(checkLine, docker && !state.path ? h('p.aiuto', t('esportazione.dialogo.scegliDocker')) : null); + else if (!c.accepted) fill(checkLine, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', c.problem || t('comune.errore')))); + else { + const name = c.display.split(/[\\/]/).filter(Boolean).pop() || c.display; + fill(checkLine, + h('p.aiuto', icon('circle-check', 'xs'), ' ', docker ? h('span.dati', c.display) : null, docker ? ' · ' : null, + c.freeBytes != null ? t('esportazione.dialogo.liberi', { nome: name, spazio: bytes(c.freeBytes) }) : name), + c.fat32 ? h('p.avviso-testo', icon('triangle-alert', 'xs'), ' ', t('esportazione.dialogo.fat32')) : null); + } + changedNote.hidden = !destination || !state.path || samePath(state.path, original); + drawSave(); + refresh(); + } + + // ------------------------------------------------------------------------------- types + const typesNote = h('p.errore-testo', { hidden: state.types.size > 0 }, t('esportazione.dialogo.nessunTipo')); + const types = h('div.tipi', TYPES.map((x) => { + const box = checkbox({ + checked: state.types.has(x.key), + labelNode: h('span.testo', t(`esportazione.tipi.${x.key}`)), + onchange: (v) => { + if (v) state.types.add(x.key); + else state.types.delete(x.key); + typesNote.hidden = state.types.size > 0; + drawSave(); + }, + }); + box.classList.add('tipo'); + box.append(icon(x.icon, 's')); + return box; + })); + + // ------------------------------------------------------------------------------- naming + const naming = h('input.dati', { type: 'text', value: state.naming, id: 'schema-copie', spellcheck: 'false', autocomplete: 'off' }); + const highlight = h('input.dati', { type: 'text', value: state.highlight, id: 'schema-copie-evidenza', spellcheck: 'false', autocomplete: 'off' }); + const profile = h('input.dati', { type: 'text', value: state.profile, id: 'schema-copie-profilo', spellcheck: 'false', autocomplete: 'off' }); + const namingField = h('label.campo', naming); + const highlightField = h('label.campo', highlight); + const profileField = h('label.campo', profile); + const fields = h('div.schemi-copie', + h('label.etichetta', { for: 'schema-copie' }, t('esportazione.dialogo.schema')), namingField, + h('label.etichetta', { for: 'schema-copie-evidenza' }, t('esportazione.dialogo.schemaEvidenza')), highlightField, + h('label.etichetta', { for: 'schema-copie-profilo' }, t('esportazione.dialogo.schemaProfilo')), profileField, + h('p.aiuto.segnaposto', t('esportazione.dialogo.segnaposto', { elenco: info.library.placeholders.join(', ') }))); + fields.hidden = !state.own; + const problems = h('div.problemi-schema', { 'aria-live': 'polite' }); + const tree = h('div.albero.pannello', { 'aria-label': t('esportazione.dialogo.risultato') }); + const choose = (value) => { + state.own = value === 'suo'; + fields.hidden = !state.own; + refresh(); + }; + const namingChoice = h('div.scelte', { role: 'radiogroup', 'aria-label': t('esportazione.dialogo.nomi') }, + radio({ name: 'nomi-copie', value: 'libreria', checked: !state.own, onchange: choose, labelNode: h('span', h('b', t('esportazione.dialogo.comeLibreria')), h('small', t('esportazione.dialogo.comeLibreriaAiuto'))) }), + radio({ name: 'nomi-copie', value: 'suo', checked: state.own, onchange: choose, labelNode: h('span', h('b', t('esportazione.dialogo.suo')), h('small', t('esportazione.dialogo.suoAiuto'))) })); + for (const [input, key] of [[naming, 'naming'], [highlight, 'highlight'], [profile, 'profile']]) { + input.addEventListener('input', () => { + state[key] = input.value; + refresh(); + }); + } + + function drawTree(preview) { + const errors = preview.errors || []; + state.errors = state.own ? errors : []; + namingField.classList.toggle('errore', state.own && errors.some((e) => e.startsWith('Schema:'))); + highlightField.classList.toggle('errore', state.own && errors.some((e) => e.startsWith('Schema per le raccolte in evidenza:'))); + profileField.classList.toggle('errore', state.own && errors.some((e) => e.startsWith('Schema per le foto del profilo:'))); + fill(problems, + errors.map((e) => h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', e)), + (preview.warnings || []).map((w) => h('p.aiuto', icon('info', 'xs'), ' ', w))); + const c = state.check; + const shown = c && c.accepted ? c.display : destination ? destination.display : (docker ? root.root : t('esportazione.dialogo.cartella')); + const sep = separator(shown); + const top = String(shown).split(/[\\/]/).filter(Boolean).pop() || shown; + fill(tree, + h('div.ramo.radice', icon('hard-drive', 's'), h('b', top)), + preview.folders.map((f) => [ + f.path.length ? h('div.ramo.livello-1', icon('folder', 's'), h('span', f.path.join(` ${sep} `))) : null, + f.files.map((file) => h(`div.ramo.${f.path.length ? 'livello-2' : 'livello-1'}`, icon(file.kind === 'video' ? 'clapperboard' : 'image', 's'), h('span.dati', file.name))), + ])); + drawSave(); + } + + let previewToken = 0; + const refresh = later(async () => { + const mine = ++previewToken; + try { + const preview = await api('/api/export/naming-preview', { + method: 'POST', + body: { scope, general: state.own ? state.naming : null, highlight: state.own ? state.highlight : null, profile: state.own ? state.profile : null }, + }); + if (mine === previewToken) drawTree(preview); + } catch (error) { + showError(error); + } + }, 150); + + // ------------------------------------------------------------------------------- save + function ready() { + if (state.saving || !state.path || state.types.size === 0 || state.errors.length) return false; + // The folder of a destination being changed is not checked again when it stays the same: an unplugged disk + // must not stop a change of types or names. + if (destination && samePath(state.path, original)) return true; + return Boolean(state.check && state.check.accepted && !state.checking); + } + + function drawSave() { + save.disabled = !ready(); + } + + async function submit(done) { + if (!ready()) return; + state.saving = true; + drawSave(); + const body = { + scope, + accountId: general ? null : accountId, + path: state.path, + label: null, + types: TYPES.map((x) => x.key).filter((k) => state.types.has(k)), + namingScheme: state.own ? state.naming : null, + highlightNamingScheme: state.own ? state.highlight : null, + profileNamingScheme: state.own ? state.profile : null, + // «Automatica» is kept as stored: tappa E5 acts on it (decision D8). + automatic: destination ? destination.automatic : false, + onlyNew: true, + }; + try { + const saved = await api(destination ? `/api/export/destinations/${destination.id}` : '/api/export/destinations', { method: destination ? 'PUT' : 'POST', body }); + toast(t('esportazione.salvata')); + for (const w of saved.warnings || []) toast(w); + done(saved.destination); + } catch (error) { + state.saving = false; + drawSave(); + showError(error); + } + } + + const body = h('div.contenuto', + h('section.parte-dialogo', + h('h3', t('esportazione.dialogo.cartella')), + h('p.aiuto', { id: 'cartella-copie-aiuto' }, docker ? t('esportazione.dialogo.cartellaAiutoDocker', { radice: root.root }) : t('esportazione.dialogo.cartellaAiuto')), + folderPart, checkLine, changedNote), + h('section.parte-dialogo', + h('h3', t('esportazione.dialogo.tipi')), + h('p.aiuto', t('esportazione.dialogo.tipiAiuto')), + types, typesNote), + h('section.parte-dialogo', + h('h3', t('esportazione.dialogo.nomi')), + general ? h('p.aiuto', t('esportazione.dialogo.notaAccount')) : null, + h('div.nomi-file', + h('div.colonna-nomi', namingChoice, fields, problems), + h('div.colonna-albero', h('span.etichetta', t('esportazione.dialogo.risultato')), tree)))); + const footer = h('footer', h('div.destra', + h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), + save)); + if (state.path) checkFolder(state.path); + else drawCheck(); + return { body, footer, onClose: () => refresh.cancel() }; + }, + }); +} + +function relativeOf(display, rootDisplay) { + const value = String(display || ''); + const base = String(rootDisplay || '').replace(/\/+$/, ''); + if (value === base) return ''; + return value.startsWith(`${base}/`) ? value.slice(base.length + 1) : value; +} + +function parentOf(relative) { + if (!relative) return null; + const i = relative.lastIndexOf('/'); + return i > 0 ? relative.slice(0, i) : null; +} + +function samePath(a, b) { + const norm = (p) => String(p || '').trim().replace(/[\\/]+$/, '').toLowerCase(); + return norm(a) === norm(b); +} + +// ------------------------------------------------------------------------------------------------- «Copia in…» + +/** + * «Copia in…» (spec §10.3, mockups 13 and 09). selection: exactly one of { mediaIds }, { entryIds }, + * { query, mode } (the filter of a page) or { accountId }. Each file goes to the folder of its account (decision D5): + * the dialog does not choose a destination, it says where the files go. Resolves with the started job, or undefined. + */ +export function copyDialog(selection, { title } = {}) { + let copyAgain = false; + return dialog({ + title: title || t('esportazione.copia.titolo'), + className: 'copia-in', + build: (close) => { + const content = h('div.contenuto', { 'aria-live': 'polite' }, h('p.aiuto', t('esportazione.copia.conto'))); + const start = h('button.btn.primo', { type: 'button', disabled: true, onclick: () => go() }, icon('copy'), t('esportazione.copia.pulsante', { n: 0 })); + const footer = h('footer', h('div.destra', h('button.btn.nudo', { type: 'button', onclick: () => close(undefined) }, t('comune.annulla')), start)); + let plan = null; + let token = 0; + let busy = false; + // The files «tolti o superati» as the plan without «Copia di nuovo» counts them: the choice keeps its label and + // stays on screen whatever the plan with it says (with it they are files to copy). + let againCount = 0; + let refocusAgain = false; + + async function load() { + const mine = ++token; + start.disabled = true; + try { + const result = await api('/api/export/plan', { method: 'POST', body: { ...selection, copyAgain } }); + if (mine !== token) return; + plan = result; + if (!copyAgain) againCount = result.removedOrSuperseded || 0; + draw(); + } catch (error) { + if (mine !== token) return; + fill(content, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', error.message))); + } + } + + function draw() { + const p = plan; + const parts = [h('b', t('esportazione.copia.file', { n: p.files }))]; + if (p.alreadyCopied) parts.push(t('esportazione.copia.giaCopiati', { n: p.alreadyCopied })); + if (p.removedOrSuperseded) parts.push(t(copyAgain ? 'esportazione.copia.toltiDiNuovo' : 'esportazione.copia.tolti', { n: p.removedOrSuperseded })); + if (p.notExported) parts.push(t('esportazione.copia.nonEsportati', { n: p.notExported })); + if (p.missing) parts.push(t('esportazione.copia.mancanti', { n: p.missing })); + if (p.files) parts.push(t('esportazione.copia.circa', { spazio: bytes(p.bytes) })); + const summary = h('p.riepilogo-copia', parts.flatMap((x, i) => (i ? [' · ', x] : [x]))); + const rows = p.destinations.filter((d) => d.files > 0 || d.problem).map((d) => h('li', + icon('hard-drive', 's'), + h('div.chi-cosa', + h('b', t('esportazione.copia.verso', { nome: d.label }), ' ', h('span.dati.muto', `(${d.display})`)), + h('span', [ + d.scope === 'account' && d.username ? t('esportazione.copia.versoAccount', { nome: d.username }) : t('esportazione.copia.versoGenerale'), + t('esportazione.copia.file', { n: d.files }), + bytes(d.bytes), + d.freeBytes != null ? t('esportazione.copia.liberi', { spazio: bytes(d.freeBytes) }) : null, + ].filter(Boolean).join(' · ')), + d.problem || d.paused ? h('div.avviso.ambra', icon('pause', 's'), h('span', t('esportazione.copia.inAttesa', { problema: d.problem || t('esportazione.inPausa') }))) : null))); + let empty = null; + if (!p.files) { + // «Nessuna cartella» only when there is really none; files of accounts not exported (or of kinds the folder + // does not copy) have their own words. + let key = 'esportazione.copia.niente'; + if (p.hasDestination === false) key = 'esportazione.copia.nessunaCartella'; + else if (p.notExported && !p.alreadyCopied && !p.removedOrSuperseded) key = 'esportazione.copia.nienteNonEsportati'; + empty = h('p.aiuto', t(key)); + } + const choice = againCount || copyAgain + ? checkbox({ + checked: copyAgain, + label: t('esportazione.copia.diNuovo', { n: againCount || p.removedOrSuperseded }), + onchange: (v) => { copyAgain = v; refocusAgain = true; load(); }, + }) + : null; + const again = choice + ? h('div.di-nuovo', choice, h('p.aiuto', t('esportazione.copia.diNuovoAiuto'))) + : null; + fill(content, summary, rows.length ? h('ul.destinazioni-copia.pannello', rows) : null, empty, again); + if (refocusAgain && choice) choice.input.focus(); + refocusAgain = false; + fill(start, icon('copy'), t('esportazione.copia.pulsante', { n: p.files })); + start.disabled = busy || !p.files; + } + + async function go() { + if (!plan || !plan.files || busy) return; + busy = true; + start.disabled = true; + try { + const job = await api('/api/export/start', { method: 'POST', body: { ...selection, copyAgain } }); + toast(job.message, '', job.runIds.length ? { label: t('esportazione.copia.vediAvanzamento'), href: '/dashboard/esportazione' } : null); + close(job); + } catch (error) { + busy = false; + if (plan) draw(); + showError(error); + } + } + + load(); + return { body: content, footer }; + }, + }); +} + +/** «Copia di nuovo» of a copy «Tolto» or «Superato» (the viewer). Resolves with the job, or null. */ +export async function copyAgain(copyId) { + try { + const job = await api('/api/export/copy-again', { method: 'POST', body: { copyId } }); + toast(job.message, '', job.runIds.length ? { label: t('esportazione.copia.vediAvanzamento'), href: '/dashboard/esportazione' } : null); + return job; + } catch (error) { + showError(error); + return null; + } +} + diff --git a/src/Febe.Web/wwwroot/js/pages/library.js b/src/Febe.Web/wwwroot/js/pages/library.js index 042c821..d2bda5b 100644 --- a/src/Febe.Web/wwwroot/js/pages/library.js +++ b/src/Febe.Web/wwwroot/js/pages/library.js @@ -3,6 +3,8 @@ // «Esporta l'elenco» in the tools row exports what the filter shows (spec §4.8: CSV with «;», UTF-8 with BOM). // «Raggruppa i post» / «Tutte le foto» (spec §4.6): one tile per entry or per file, remembered in this browser. With // «Tutte le foto» the selection is of files; the CSV list and «Elimina» work on the entries they belong to. +// Copies to external folders (spec §4.10, tappa E2): the CSV icon is a menu («Esporta l'elenco (CSV)», «Copia i file +// in…»), «Copia in…» in the selection bar and the «Copie» filter, these two only once a folder of the copies exists. import { api, download, withCarried } from '../core/api.js'; import { caps } from '../core/context.js'; @@ -14,6 +16,7 @@ import { engineState } from '../core/engine.js'; import { Mosaic, modeSwitch, storedMode } from './mosaic.js'; import { welcome } from './welcome.js'; import { openViewer } from './viewer.js'; +import { copiesApi, copiesLabel, copiesMenu, copyDialog, exportButton as exportMenuButton, exportMenu } from './export-dialogs.js'; const KINDS = [ { key: 'tutto', api: 'all', label: 'libreria.tipi.all' }, @@ -38,6 +41,8 @@ export function apiQuery(state, today) { if (state.provenienza === 'importati') q.set('provenance', 'imported'); if (state.provenienza === 'scaricati') q.set('provenance', 'downloaded'); if (state.q) q.set('q', state.q); + const copies = copiesApi(state.copie); + if (copies) q.set('copies', copies); return q.toString(); } @@ -66,6 +71,7 @@ function readState(query) { al: query.get('al') || '', provenienza: query.get('provenienza') || '', q: query.get('q') || '', + copie: copiesApi(query.get('copie')) ? query.get('copie') : '', }; } @@ -76,6 +82,8 @@ export default { let accounts = null; let mosaic = null; let mode = storedMode('libreria'); + // A folder of the copies exists (told by the days of the mosaic): the «Copie» filter, «Copia in…» and the marks. + let hasDestinations = false; page.title(t('libreria.titolo'), ''); const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q }); @@ -91,6 +99,7 @@ export default { const accountButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '118px' } }); const periodButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '111px' } }); const provenanceButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', style: { minWidth: '141px' } }); + const copiesButton = h('button.campo.scelta', { type: 'button', 'aria-haspopup': 'true', 'aria-expanded': 'false', hidden: true, style: { minWidth: '96px' } }); const filtersButton = h('button.btn.solo-stretto', { type: 'button', 'aria-haspopup': 'true' }, icon('list-filter'), t('libreria.filtri')); 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') }); @@ -100,7 +109,8 @@ export default { mode = value; apply(); }, { compact: true }); - const exportButton = h('button.btn.nudo.piccolo.solo-icona.solo-largo', { type: 'button', title: t('libreria.esportaAiuto'), 'aria-label': t('libreria.esporta') }, icon('file-down')); + const exportButton = exportMenuButton(); + exportButton.classList.add('solo-largo'); // 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) => { @@ -110,7 +120,7 @@ export default { }).catch(() => {}); page.tools(h('div', { style: { display: 'contents' } }, chips, - h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton), + h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton, copiesButton), filtersButton, h('div.destra', duplicates, @@ -123,7 +133,7 @@ export default { fill(page.body, host); function filtersActive() { - return state.tipo !== 'tutto' || state.account || state.periodo || state.dal || state.al || state.provenienza || state.q; + return state.tipo !== 'tutto' || state.account || state.periodo || state.dal || state.al || state.provenienza || state.q || state.copie; } function drawChips() { @@ -156,7 +166,9 @@ export default { else if (state.periodo) periodText = t(`libreria.periodi.${state.periodo}`); menuLabel(periodButton, periodText, state.periodo || state.dal || state.al); menuLabel(provenanceButton, state.provenienza ? t(`libreria.provenienze.${state.provenienza === 'importati' ? 'imported' : 'downloaded'}`) : t('libreria.menuProvenienza'), state.provenienza); - filtersButton.classList.toggle('primo', Boolean(state.account || state.periodo || state.dal || state.al || state.provenienza)); + menuLabel(copiesButton, copiesLabel(state.copie), state.copie); + copiesButton.hidden = !hasDestinations && !state.copie; + filtersButton.classList.toggle('primo', Boolean(state.account || state.periodo || state.dal || state.al || state.provenienza || state.copie)); } async function loadAccounts() { @@ -246,22 +258,32 @@ export default { }); } + function openCopies(anchor) { + copiesMenu(anchor, state.copie, (value) => { + state.copie = value; + apply(); + }); + } + function openFilters(anchor) { - // Narrow window: the three menus behind one button. + // Narrow window: the menus behind one button. menu(anchor, [ { label: accountButton.textContent, value: 'account', icon: 'users' }, { label: periodButton.textContent, value: 'periodo', icon: 'calendar' }, { label: provenanceButton.textContent, value: 'provenienza', icon: 'folder-input' }, - ], (value) => { + copiesButton.hidden ? null : { label: copiesButton.textContent, value: 'copie', icon: 'copy' }, + ].filter(Boolean), (value) => { if (value === 'account') openAccounts(anchor); if (value === 'periodo') openPeriod(anchor); if (value === 'provenienza') openProvenance(anchor); + if (value === 'copie') openCopies(anchor); }); } accountButton.addEventListener('click', () => openAccounts(accountButton)); periodButton.addEventListener('click', () => openPeriod(periodButton)); provenanceButton.addEventListener('click', () => openProvenance(provenanceButton)); + copiesButton.addEventListener('click', () => openCopies(copiesButton)); filtersButton.addEventListener('click', () => openFilters(filtersButton)); slider.addEventListener('input', () => { const value = Number(slider.value); @@ -281,7 +303,7 @@ export default { page.saveBar(null); return; } - page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected })); + page.saveBar(selectionBar(mosaic, selected, { cancel: () => setSelecting(false), exportSelected, deleteSelected, copySelected: hasDestinations ? copySelected : null })); } function setSelecting(on) { @@ -293,7 +315,16 @@ export default { } selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting)); - exportButton.addEventListener('click', () => exportFiltered()); + exportButton.addEventListener('click', () => exportMenu(exportButton, { + hasDestinations, + csv: exportFiltered, + copy: () => copyDialog({ query: apiQuery(state, today()), mode: mode === 'files' ? 'files' : 'grouped' }), + })); + + function copySelected() { + // «Tutte le foto»: the chosen files (spec §4.6); otherwise the chosen entries. + return copyDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids }); + } async function exportSelected() { try { @@ -361,6 +392,7 @@ export default { al: state.al || null, provenienza: state.provenienza || null, q: state.q || null, + copie: state.copie || null, }); drawChips(); drawMenus(); @@ -375,9 +407,16 @@ export default { signal: page.signal, onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }), onSelection: drawSelection, - onTotals: ({ entries, accounts: n, files }) => page.count(files == null - ? t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) }) - : t('libreria.quantiFile', { file: t('comune.file', { n: files }), elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })), + onTotals: ({ entries, accounts: n, files, hasDestinations: any }) => { + page.count(files == null + ? t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) }) + : t('libreria.quantiFile', { file: t('comune.file', { n: files }), elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })); + if (any !== hasDestinations) { + hasDestinations = any; + drawMenus(); + if (mosaic) drawSelection(mosaic.selected); + } + }, onEmpty: drawEmpty, }); try { @@ -389,9 +428,15 @@ export default { } const onLibraryChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 400); - page.onLibrary(onLibraryChange); + // Copies done or a folder changed: the counts may stay the same, the marks of the tiles do not. + const onExportChange = later(() => mosaic && mosaic.refreshMarks().catch(() => {}), 600); + page.onLibrary((change) => { + onLibraryChange(); + if (change && change.reason === 'export') onExportChange(); + }); page.onLeave(() => { onLibraryChange.cancel(); + onExportChange.cancel(); if (mosaic) mosaic.destroy(); }); loadAccounts().then(drawMenus).catch(() => {}); @@ -401,10 +446,11 @@ export default { }; /** - * The bar of the selection (Libreria and account view): how many are chosen, «Esporta l'elenco» and «Elimina». With - * «Tutte le foto» it counts the files and says how many entries they belong to: those are what the actions work on. + * The bar of the selection (Libreria and account view): how many are chosen, «Esporta l'elenco», «Copia in…» (only + * with copySelected, when a folder of the copies exists) and «Elimina». With «Tutte le foto» it counts the files and + * says how many entries they belong to: the CSV list and «Elimina» work on those, «Copia in…» on the chosen files. */ -export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected }) { +export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteSelected, copySelected = null }) { const n = selected.size; const entries = mosaic.selectedEntries().ids.length; let note = t('selezione.nessuno'); @@ -415,6 +461,7 @@ export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteS h('div.destra', h('button.btn.nudo', { type: 'button', onclick: cancel }, t('selezione.annulla')), h('button.btn', { type: 'button', disabled: !n, onclick: exportSelected }, icon('file-down'), t('selezione.esporta')), + copySelected ? h('button.btn', { type: 'button', disabled: !n, onclick: copySelected }, icon('copy'), t('esportazione.selezione.copia')) : null, h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: deleteSelected }, icon('trash-2'), t('selezione.elimina', { n: entries })))); } diff --git a/src/Febe.Web/wwwroot/js/pages/mosaic.js b/src/Febe.Web/wwwroot/js/pages/mosaic.js index a532a5c..be8677e 100644 --- a/src/Febe.Web/wwwroot/js/pages/mosaic.js +++ b/src/Febe.Web/wwwroot/js/pages/mosaic.js @@ -134,6 +134,16 @@ export function tileElement(tile, width, height, { selected = false, today = '', if (file && tile.files > 1) description.push(t('libreria.tesseraPosizione', { n: tile.position, totale: tile.files })); else if (!file && tile.files > 1) description.push(t('libreria.tesseraFile', { n: tile.files })); if (cover && cover.kind === 'video') description.push(t('libreria.tesseraDurata', { durata: duration(cover.duration || 0) })); + // The copies to external folders (spec §4.10): only when a destination exists does the server send a mark. Last, so + // that the place in the series stays the first mark; never colour only. + if (tile.copies === 'copied') { + marks.push(h('span.copia', { title: t('esportazione.segno.copiato') }, icon('copy'))); + description.push(t('esportazione.segno.copiato')); + } else if (tile.copies === 'partly') { + const parte = t('esportazione.segno.parte', { n: tile.copiesDone || 0, totale: tile.copiesDue || 0 }); + marks.push(h('span.copia.parte', { title: parte }, icon('copy'), `${tile.copiesDone || 0}/${tile.copiesDue || 0}`)); + description.push(parte); + } const el = h(`button.tess${selected ? '.scelta' : ''}`, { type: 'button', style: { width: `${width}px`, height: `${height}px` }, @@ -172,7 +182,8 @@ export class Mosaic { /** * scroller: the scrolling element (.corpo); host: where the groups go; query: filter as a query string; * mode: 'justified' or 'grid' (9:16 stories); files: «Tutte le foto» (one tile per file); rowHeight: target height; - * onOpen(tile), onSelection(set), onTotals({ entries, accounts, files, today }) (files only with «Tutte le foto»), + * onOpen(tile), onSelection(set), onTotals({ entries, accounts, files, today, hasDestinations }) (files only with + * «Tutte le foto»; hasDestinations: a folder of the copies exists, so the «Copie» filter and the marks make sense), * onEmpty(), dayLabel(day, count, today). */ constructor(options) { @@ -230,7 +241,7 @@ export class Mosaic { const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); if (this.destroyed) return; this.today = data.today; - this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today }); + this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today, hasDestinations: Boolean(data.hasDestinations) }); this.width = this.root.clientWidth || this.host.clientWidth || 800; for (const section of this.sections) this.unobserve(section); this.sections = []; @@ -559,7 +570,7 @@ export class Mosaic { async refresh() { const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); if (this.destroyed) return; - this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today }); + this.onTotals({ entries: data.entries, accounts: data.accounts, files: data.files, today: data.today, hasDestinations: Boolean(data.hasDestinations) }); // The empty state of the page took the place of the mosaic: the first new entries bring it back. if (data.days.length && !this.root.isConnected) { this.pendingNew = 0; @@ -602,6 +613,41 @@ export class Mosaic { if (!this.sections.length) this.onEmpty(); } + /** + * The copies changed (spec §4.10: a copy finished, a folder was added or taken away) and the counts did not: the + * marks of the tiles on screen are asked again and the tiles redrawn in place (the same sizes, so nothing moves); the + * days far from the view forget their tiles and load them again when they come near. + */ + async refreshMarks() { + for (const s of this.sections) { + if (!s.tiles.length || s.loading) continue; + if (!s.rendered) { + s.tiles = []; + s.complete = false; + continue; + } + try { + const page = await api(`/api/library?${this.query}${this.query ? '&' : ''}cursor=${encodeURIComponent(s.cursor)}&limit=${Math.min(600, s.tiles.length + 1)}`, { signal: this.signal }); + if (this.destroyed) return; + const fresh = new Map(page.tiles.map((x) => [this.files && x.cover ? x.cover.mediaId : x.id, x])); + let changed = false; + for (const tile of s.tiles) { + const now = fresh.get(keyOf(tile)); + if (!now) continue; + if (now.copies !== tile.copies || now.copiesDone !== tile.copiesDone || now.copiesDue !== tile.copiesDue) { + tile.copies = now.copies; + tile.copiesDone = now.copiesDone; + tile.copiesDue = now.copiesDue; + changed = true; + } + } + if (changed && s.rendered) this.render(s); + } catch (error) { + if (error.name === 'AbortError') return; + } + } + } + reset(s, day) { s.count = day.count; s.cursor = day.cursor; diff --git a/src/Febe.Web/wwwroot/js/pages/settings-export.js b/src/Febe.Web/wwwroot/js/pages/settings-export.js new file mode 100644 index 0000000..876bf92 --- /dev/null +++ b/src/Febe.Web/wwwroot/js/pages/settings-export.js @@ -0,0 +1,191 @@ +// Impostazioni → Esportazione (spec §4.10, §10.3, tappa E2; composed from mockups 08 and 07): the general folder of +// the copies with its state («In pausa» with «Riprova», or the counts with «Controlla le copie»), «Lo stesso post in +// due account», the folders of the accounts, and in Docker the note on /esporta. Everything acts at once: there is no +// save bar. The formats, the conversion of the library and «Automatica» come with later tappe (decisions D7, D8). + +import { api, withCarried } from '../core/api.js'; +import { h, icon, fill, later } from '../core/dom.js'; +import { t } from '../core/text.js'; +import { confirmDialog, label, segmented, showError, toast } from '../core/ui.js'; +import { heading } from './settings.js'; +import { countsText, describe, destinationDialog } from './export-dialogs.js'; + +export default async function exportSettings(page, box) { + let overview = await api('/api/export', { signal: page.signal }); + const generalBox = h('div'); + const ownBox = h('div'); + const noteBox = h('div.nota-copie'); + const pendingBox = h('div.nota-copie'); + + async function reload() { + try { + overview = await api('/api/export', { signal: page.signal }); + draw(); + } catch (error) { + if (error.name !== 'AbortError') showError(error); + } + } + + // ------------------------------------------------------------------------------------------- general folder + function drawGeneral() { + const g = overview.general; + const root = overview.root; + const canChange = root.active; + const buttons = []; + if (!g) { + buttons.push(h('button.btn.primo', { type: 'button', disabled: !canChange, onclick: () => edit(null) }, icon('folder-open', 's'), t('esportazione.scegli'))); + } else { + buttons.push(h('button.btn', { type: 'button', disabled: !canChange, onclick: () => edit(g) }, t('esportazione.modifica'))); + buttons.push(h('button.btn.nudo', { type: 'button', onclick: () => retire(g) }, t('esportazione.togli'))); + } + fill(generalBox, h('div.cartella-impostazioni', + h('div.riga-cartella', + h('div.campo.sola', { title: g ? g.display : null }, icon(g ? 'hard-drive' : 'folder', 's'), + g ? h('span.val.dati', g.display) : h('span.val.tenue', t('esportazione.nessunaCartella'))), + buttons), + g ? h('p.aiuto.descrizione-copie', describe(g)) : null, + g ? stateLine(g) : null)); + } + + /** «In pausa: …» with «Riprova», or the counts of the copies with «Controlla le copie». */ + function stateLine(d) { + if (d.pausedAt || d.problem) { + return h('div.avviso.ambra.avviso-azione.stato-copie', icon('pause', 's'), + h('span', t('esportazione.pausa', { problema: d.problem || '' })), + h('button.btn.piccolo', { type: 'button', onclick: (e) => retry(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.riprova'))); + } + return h('div.stato-copie.riga-conteggi', + h('span.muto', countsText(d.counts)), + h('button.btn.piccolo', { type: 'button', title: t('esportazione.controllaAiuto'), onclick: (e) => check(d, e.currentTarget) }, icon('rotate-cw', 's'), t('esportazione.controlla'))); + } + + async function edit(destination) { + const saved = await destinationDialog({ scope: 'general', destination, overview }); + if (saved) await reload(); + } + + async function retire(d) { + const ok = await confirmDialog({ + title: t('esportazione.togliTitolo', { nome: d.label }), + text: t('esportazione.togliConferma'), + buttons: [ + { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true }, + { label: t('esportazione.togliSi'), value: true, kind: 'pericolo' }, + ], + }); + if (!ok) return; + try { + const result = await api(`/api/export/destinations/${d.id}`, { method: 'DELETE' }); + toast(result.message); + await reload(); + } catch (error) { + showError(error); + } + } + + async function retry(d, button) { + button.disabled = true; + try { + const result = await api(`/api/export/destinations/${d.id}/resume`, { method: 'POST' }); + toast(result.message); + await reload(); + } catch (error) { + button.disabled = false; + showError(error); + } + } + + async function check(d, button) { + button.disabled = true; + try { + const result = await api(`/api/export/destinations/${d.id}/check`, { method: 'POST' }); + toast(result.message, '', { label: t('esportazione.apriEsportazione'), href: '/dashboard/esportazione' }); + } catch (error) { + showError(error); + } finally { + button.disabled = false; + } + } + + // ------------------------------------------------------------------------------------------- same post + const samePost = segmented({ + label: t('esportazione.stessoPost'), + value: overview.samePost, + options: [ + { value: 'onePerAccount', label: t('esportazione.unaPerAccount') }, + { value: 'oneOnly', label: t('esportazione.unaSola') }, + ], + onchange: async (v) => { + try { + const result = await api('/api/export/settings', { method: 'PUT', body: { samePost: v } }); + overview.samePost = v; + toast(result.message); + } catch (error) { + samePost.select(overview.samePost); + showError(error); + } + }, + }); + + // ------------------------------------------------------------------------------------------- own folders + function drawOwn() { + const own = overview.own || []; + if (!own.length) { + fill(ownBox, h('p.vuoto-elenco.pannello', t('esportazione.nessunaPropria'))); + return; + } + fill(ownBox, h('div.pannello.cartelle-copie', h('table.tab', + h('caption.vh', t('esportazione.cartelleAccount')), + h('thead', h('tr', + h('th', { scope: 'col' }, t('esportazione.colonne.account')), + h('th', { scope: 'col' }, t('esportazione.colonne.cartella')), + h('th', { scope: 'col' }, t('esportazione.colonne.stato')))), + h('tbody', own.map((d) => h('tr', + h('td', d.accountId && d.username + ? h('a', { href: withCarried(`/account/${d.accountId}/impostazioni`) }, `@${d.username}`) + : h('span.muto', t('esportazione.eraDi', { nome: d.formerUsername || '?' }))), + h('td', h('span.dati', { title: d.display }, d.display), h('div.piccolo.muto', describe(d))), + h('td', d.pausedAt || d.problem + ? label(t('esportazione.inPausa'), 'ambra', 'pause') + : h('span.muto.piccolo', countsText(d.counts))))))))); + } + + // ------------------------------------------------------------------------------------------- notes + function drawNotes() { + const root = overview.root; + if (root.docker && !root.active) { + fill(noteBox, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', root.problem || ''))); + } else if (root.docker) { + fill(noteBox, h('div.avviso', icon('info', 's'), h('span', t('esportazione.dockerNota', { radice: root.root })))); + } else if (!root.active && root.problem) { + fill(noteBox, h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', root.problem))); + } else { + noteBox.replaceChildren(); + } + const unfinished = overview.unfinishedRuns || 0; + fill(pendingBox, unfinished + ? h('div.avviso.ambra.avviso-azione', icon('pause', 's'), h('span', t('esportazione.daRiprendere', { n: unfinished })), + h('a.btn.piccolo', { href: withCarried('/dashboard/esportazione') }, t('esportazione.apriEsportazione'))) + : null); + } + + function draw() { + drawGeneral(); + drawOwn(); + drawNotes(); + } + + draw(); + fill(box, + h('div.sezione', heading(t('esportazione.titolo'), t('esportazione.aiuto')), noteBox, pendingBox), + h('div.sezione', heading(t('esportazione.generale'), t('esportazione.generaleAiuto')), generalBox), + h('div.sezione', heading(t('esportazione.stessoPost'), t('esportazione.stessoPostAiuto')), samePost), + h('div.sezione', heading(t('esportazione.cartelleAccount'), t('esportazione.cartelleAccountAiuto')), ownBox)); + + // Copies finished, a folder paused or changed elsewhere (another tab, an account card): the page follows. + const onChange = later(() => reload(), 500); + page.onLibrary((change) => { + if (change.reason === 'export') onChange(); + }); + page.onLeave(() => onChange.cancel()); +} diff --git a/src/Febe.Web/wwwroot/js/pages/settings.js b/src/Febe.Web/wwwroot/js/pages/settings.js index 3384535..a827941 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings.js +++ b/src/Febe.Web/wwwroot/js/pages/settings.js @@ -1,5 +1,5 @@ // Impostazioni (spec §10.3; mockups 07, 08, 10): the left sub-menu (Generali, Limiti e comportamento, Collegamento a -// Instagram, Notifiche, Dati e copie di sicurezza, Informazioni) and the section on the right. «Collegamento a +// Instagram, Notifiche, Dati e copie di sicurezza, Esportazione, Informazioni) and the section on the right. «Collegamento a // Instagram» is a page of its own (mockup 10: back link, no sub-menu). import { withCarried } from '../core/api.js'; @@ -13,6 +13,7 @@ export const SECTIONS = [ { key: 'collegamento', icon: 'key-round', load: null }, { key: 'notifiche', icon: 'bell', load: () => import('./settings-notifications.js') }, { key: 'dati', icon: 'database', load: () => import('./settings-data.js') }, + { key: 'esportazione', icon: 'hard-drive', load: () => import('./settings-export.js') }, { key: 'informazioni', icon: 'info', load: () => import('./settings-about.js') }, ]; diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js index 4a98446..bccffe5 100644 --- a/src/Febe.Web/wwwroot/js/pages/viewer.js +++ b/src/Febe.Web/wwwroot/js/pages/viewer.js @@ -5,10 +5,12 @@ import { api, withCarried } from '../core/api.js'; import { caps, serverNow } from '../core/context.js'; -import { h, icon, fill } from '../core/dom.js'; +import { h, icon, fill, later } from '../core/dom.js'; +import { onLibrary } from '../core/engine.js'; import { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js'; import { avatar, label, showError, toast } from '../core/ui.js'; import { confirmDelete } from './library.js'; +import { copyAgain, copyDialog } from './export-dialogs.js'; const KIND_ICON = { post: 'image', story: 'circle-dashed', highlight: 'star', tagged: 'square-user', profile: 'circle-user' }; @@ -25,6 +27,8 @@ export function openViewer({ tile, source, origin, onDeleted }) { let fileIndex = 0; let zoomed = false; let token = 0; + // The copies whose «Copia di nuovo» started a job: their button stays «In copia…» until the job ends (spec §4.10). + const copying = new Set(); const where = h('span.dove'); const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x')); @@ -76,6 +80,8 @@ export function openViewer({ tile, source, origin, onDeleted }) { function close() { document.removeEventListener('keydown', onKey, true); + stopWatching(); + onCopiesChanged.cancel(); for (const v of box.querySelectorAll('video')) v.pause(); if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); box.remove(); @@ -248,7 +254,8 @@ export function openViewer({ tile, source, origin, onDeleted }) { row(t('vis.codice'), entry.code || entry.instagramId), entry.author ? row(t('vis.autore'), `@${entry.author}`) : null, entry.media.length > 1 ? row(t('vis.posizione'), t('vis.posizioneDi', { n: fileIndex + 1, totale: entry.media.length })) : null, - entry.highlights.length ? row(t('vis.raccolte'), entry.highlights.join(', ')) : null)), + entry.highlights.length ? row(t('vis.raccolte'), entry.highlights.join(', ')) : null, + media && media.copies ? media.copies.map((c) => copyRow(c, media)) : null)), h('section', h('h3', t('vis.provenienza')), h('dl', row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')), row(t('vis.quando'), downloaded)))); @@ -265,12 +272,47 @@ export function openViewer({ tile, source, origin, onDeleted }) { ? h('button.btn', { type: 'button', onclick: () => openNative(entry.id) }, icon('external-link'), t('vis.apri')) : h('a.btn', { href: entry.instagramUrl, target: '_blank', rel: 'noopener noreferrer' }, icon('external-link'), t('vis.apri'))); } + // «Copia in…» (spec §4.6, §4.10): the file on screen goes to the folder of the copies of its account. + if (entry.canCopy && media && media.available) { + actions.push(h('button.btn', { type: 'button', onclick: () => copyDialog({ mediaIds: [media.id] }) }, icon('copy'), t('esportazione.vis.copiaIn'))); + } if (entry.state !== 'deleted') { actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina'))); } fill(panelBottom, actions); } + /** + * A copy of the file in an external folder (spec §4.10): «Copiato in Disco USB il 3 novembre · intero», «Tolto da + * Disco USB il 4 novembre» with «Copia di nuovo», «Superato in…», «Non riuscito in…». + */ + function copyRow(copy, media) { + const today = caps().today; + const vars = { cartella: copy.destination, giorno: shortDay(copy.at.day, today), nome: copy.forAccount || '' }; + const key = { copied: copy.forAccount ? 'copiatoPer' : 'copiato', removed: 'tolto', superseded: 'superato' }[copy.state] || 'fallito'; + const text = t(`esportazione.vis.${key}`, vars) + (copy.destinationRetired ? ` (${t('esportazione.vis.tolta')})` : ''); + const busy = copying.has(copy.copyId); + const again = copy.canCopyAgain + ? h('button.btn.nudo.piccolo.copia-di-nuovo', { + type: 'button', + disabled: busy, + onclick: async (e) => { + const button = e.currentTarget; + button.disabled = true; + const job = await copyAgain(copy.copyId); + if (!job) { + button.disabled = false; + return; + } + // The job runs on: the row says so, and the viewer reads the copies again when it ends (onLibrary «export»). + copying.add(copy.copyId); + await load(entry.id, fileIndex, media.id); + }, + }, icon('rotate-cw', 's'), t(busy ? 'esportazione.vis.inCopia' : 'esportazione.vis.diNuovo')) + : null; + return [h('dt', t('esportazione.vis.copia')), h('dd.riga-copia', h('span', text), again)]; + } + async function showInFolder(mediaId) { try { const result = await api('/api/media/show-in-folder', { method: 'POST', body: { mediaId } }); @@ -301,6 +343,17 @@ export function openViewer({ tile, source, origin, onDeleted }) { else close(); } + // A job of the copies ended (or a folder changed): the rows of «Copia» are read again, on the same file. + const onCopiesChanged = later(() => { + if (!entry) return; + copying.clear(); + const current = entry.media[fileIndex]; + load(entry.id, fileIndex, current ? current.id : null); + }, 400); + const stopWatching = onLibrary((change) => { + if (change.reason === 'export') onCopiesChanged(); + }); + document.addEventListener('keydown', onKey, true); document.body.append(box); closeButton.focus(); diff --git a/src/Febe.Web/wwwroot/js/routes.js b/src/Febe.Web/wwwroot/js/routes.js index 4628b28..a15740b 100644 --- a/src/Febe.Web/wwwroot/js/routes.js +++ b/src/Febe.Web/wwwroot/js/routes.js @@ -5,7 +5,7 @@ export const routes = [ // The Dashboard is the start page (spec §7.9, §10.2, tappa D1); the old address of Attività leads there too. { pattern: /^\/$/, redirect: '/dashboard' }, - { pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') }, + { pattern: /^\/dashboard(?:\/(?esportazione))?\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') }, { pattern: /^\/attivita\/?$/, redirect: '/dashboard' }, { pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') }, { pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') }, @@ -14,7 +14,7 @@ export const routes = [ { pattern: /^\/doppioni\/?$/, nav: 'dashboard', page: () => import('./pages/duplicates.js') }, { pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' }, { - pattern: /^\/impostazioni\/(?
generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/, + pattern: /^\/impostazioni\/(?
generali|limiti|collegamento|notifiche|dati|esportazione|informazioni)\/?$/, nav: 'impostazioni', page: () => import('./pages/settings.js'), }, diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index 1267699..e72d376 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -527,6 +527,7 @@ "collegamento": "Collegamento a Instagram", "notifiche": "Notifiche", "dati": "Dati e copie di sicurezza", + "esportazione": "Esportazione", "informazioni": "Informazioni" }, "prossimamente": "Questa pagina arriva con la seconda parte dell'interfaccia.", @@ -1078,5 +1079,228 @@ "rimedio": "Che cosa fare", "ricarica": "Ricarica la pagina", "guida": "Altri problemi comuni sono spiegati nella guida." + }, + "esportazione": { + "titolo": "Esportazione", + "aiuto": "Copie dei file della libreria in cartelle fuori da Febe: un disco esterno, una chiavetta, una cartella di rete. La libreria non cambia, e nelle cartelle delle copie Febe non cancella e non sovrascrive mai nulla.", + "generale": "Cartella generale", + "generaleAiuto": "Qui vanno le copie degli account che non hanno una cartella loro, ognuno nella sottocartella con il suo nome.", + "nessunaCartella": "Nessuna cartella scelta", + "scegli": "Scegli una cartella…", + "modifica": "Modifica…", + "togli": "Togli la cartella", + "togliTitolo": "Togliere la cartella {nome}?", + "togliConferma": "I file già copiati restano dove sono.", + "togliSi": "Togli la cartella", + "pausa": "In pausa: {problema}", + "inPausa": "In pausa", + "riprova": "Riprova", + "controlla": "Controlla le copie", + "controllaAiuto": "Guarda se i file copiati sono ancora nella cartella. Nessun file viene toccato.", + "conteggi": { + "copiati": "1 copiato|{n} copiati", + "tolti": "1 tolto|{n} tolti", + "superati": "1 superato|{n} superati", + "falliti": "1 non riuscito|{n} non riusciti" + }, + "tipiScelti": "Tipi: {elenco}", + "tuttiITipi": "tutti", + "nomiLibreria": "nomi come la libreria", + "nomiSuoi": "nomi con uno schema suo", + "salvata": "Cartella delle copie salvata.", + "stessoPost": "Lo stesso post in due account", + "stessoPostAiuto": "Quando lo stesso file è il post di un account e il taggato di un altro: una copia per ciascun account, ognuna nella sua cartella, oppure una copia sola, nel primo account che la copia; l'altro la mostra «Copiato» con la cartella dove sta.", + "unaPerAccount": "Una copia per account", + "unaSola": "Una copia sola", + "cartelleAccount": "Cartelle degli account", + "cartelleAccountAiuto": "Un account può avere una cartella sua al posto di quella generale: si sceglie nella scheda dell'account, Impostazioni, blocco «Copie esterne».", + "nessunaPropria": "Nessun account ha una cartella sua.", + "colonne": { + "account": "Account", + "cartella": "Cartella", + "stato": "Copie" + }, + "eraDi": "era di @{nome}", + "daRiprendere": "1 copia da riprendere.|{n} copie da riprendere.", + "apriEsportazione": "Apri l'esportazione", + "dockerNota": "Le cartelle delle copie sono sottocartelle di {radice}, il disco o la condivisione montata nel contenitore. Febe non crea mai la cartella scelta: deve esistere già.", + "dialogo": { + "titoloGenerale": "Cartella generale delle copie", + "titoloAccount": "Cartella delle copie di @{nome}", + "cartella": "Cartella", + "cartellaAiuto": "Una cartella che esiste già, fuori da Dati, Libreria e dalle cartelle degli account; non la radice di un disco. Va bene anche una cartella di rete.", + "cartellaAiutoDocker": "Una sottocartella di {radice} che esiste già: scegli il suo nome, la freccia apre le cartelle che contiene.", + "scegliDocker": "Nessuna cartella scelta.", + "percorso": "Percorso della cartella", + "sfoglia": "Scegli…", + "su": "Su", + "apri": "Apri {nome}", + "vuota": "Nessuna sottocartella qui.", + "controllo": "Controllo la cartella…", + "liberi": "{nome} · liberi {spazio}", + "fat32": "Disco FAT32: i file oltre 4 GB non si copiano.", + "cambiata": "Le copie già fatte restano nella cartella di prima; qui si ricomincia, e i file già presenti si riconoscono.", + "tipi": "Che cosa copiare", + "tipiAiuto": "Una storia entrata in una raccolta in evidenza conta anche come evidenza.", + "nessunTipo": "Scegli almeno un tipo.", + "nomi": "Nomi dei file", + "comeLibreria": "Come la libreria", + "comeLibreriaAiuto": "Gli schemi di Impostazioni → Generali, anche quando cambiano.", + "suo": "Uno schema suo", + "suoAiuto": "Schemi solo per questa cartella, con le regole di quelli della libreria.", + "notaAccount": "Febe mette sempre per primo il nome dell'account, perché gli account non si scontrino.", + "schema": "Schema", + "schemaEvidenza": "Schema per le raccolte in evidenza", + "schemaProfilo": "Schema per le foto del profilo", + "segnaposto": "Segnaposto: {elenco}.", + "risultato": "Risultato", + "salva": "Salva la cartella" + }, + "tipi": { + "postFoto": "Post foto", + "postVideo": "Post video", + "storie": "Storie", + "evidenza": "In evidenza", + "taggati": "Taggati", + "profilo": "Foto del profilo" + }, + "copia": { + "titolo": "Copia in…", + "conto": "Conto i file…", + "file": "1 file|{n} file", + "giaCopiati": "1 già copiato, saltato|{n} già copiati, saltati", + "tolti": "1 tolto o superato, saltato|{n} tolti o superati, saltati", + "toltiDiNuovo": "1 tolto o superato, copiato di nuovo|{n} tolti o superati, copiati di nuovo", + "nonEsportati": "1 di un account che non si esporta|{n} di account che non si esportano", + "mancanti": "1 non presente in libreria|{n} non presenti in libreria", + "circa": "circa {spazio}", + "verso": "In {nome}", + "versoGenerale": "cartella generale", + "versoAccount": "cartella di @{nome}", + "liberi": "liberi {spazio}", + "inAttesa": "{problema} I file restano in attesa: la copia riparte con «Riprendi» nella Dashboard, scheda Esportazione.", + "diNuovo": "Copia di nuovo anche 1 tolto o superato|Copia di nuovo anche i {n} tolti o superati", + "diNuovoAiuto": "Scrive un file nuovo; la copia di prima resta dov'è.", + "niente": "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria.", + "nessunaCartella": "Nessuna cartella delle copie: scegline una in Impostazioni → Esportazione.", + "nienteNonEsportati": "Niente da copiare: questi file sono di account che non si esportano o di tipi che la cartella non copia.", + "pulsante": "Copia 1 file|Copia {n} file", + "vediAvanzamento": "Apri l'esportazione" + }, + "filtro": { + "titolo": "Copie", + "tutti": "Tutti", + "nonCopiati": "Non ancora copiati", + "copiati": "Copiati", + "tolti": "Tolti o superati" + }, + "segno": { + "copiato": "copiato", + "parte": "copiato in parte, {n} file di {totale}" + }, + "vis": { + "copia": "Copia", + "copiato": "Copiato in {cartella} il {giorno} · intero", + "copiatoPer": "Copiato per @{nome} in {cartella} il {giorno} · intero", + "tolto": "Tolto da {cartella} il {giorno}", + "superato": "Superato in {cartella} il {giorno}", + "fallito": "Non riuscito in {cartella} il {giorno}", + "tolta": "cartella tolta", + "diNuovo": "Copia di nuovo", + "inCopia": "In copia…", + "copiaIn": "Copia in…" + }, + "account": { + "titolo": "Copie esterne", + "aiuto": "Copie dei file di questo account in una cartella fuori da Febe, con «Copia in…». I file già copiati si saltano.", + "interruttore": "Esporta questo account", + "spento": "Questo account non si esporta: «Copia in…» lo salta. Le copie già fatte restano dove sono.", + "generale": "Nella cartella generale", + "sua": "Nella sua cartella", + "nessuna": "Nessuna cartella delle copie: scegline una qui o in Impostazioni → Esportazione.", + "scegliSua": "Scegli una cartella sua…", + "usaGenerale": "Usa la cartella generale", + "usaGeneraleTitolo": "Usare la cartella generale per @{nome}?", + "usaGeneraleTesto": "La cartella sua si toglie: i file già copiati restano dove sono, le copie nuove vanno nella cartella generale.", + "togliTitolo": "Togliere la cartella di @{nome}?", + "togliTesto": "I file già copiati restano dove sono. Senza una cartella generale l'account non ha più dove copiare.", + "conteggio": "{n} su {totale} non ancora copiati", + "tuttiCopiati": "1 file, già copiato|Tutti i {n} file sono copiati", + "nessunFile": "Nessun file da copiare con i tipi di questa cartella", + "tolti": "1 tolto o superato|{n} tolti o superati", + "falliti": "1 non riuscito|{n} non riusciti", + "copiaIn": "Copia in…" + }, + "selezione": { + "copia": "Copia in…" + }, + "libreria": { + "menu": "Esporta", + "menuCsv": "Esporta l'elenco (CSV)", + "menuCopia": "Copia i file in…" + }, + "dashboard": { + "linguette": "Sezioni della Dashboard", + "motore": "Motore", + "esportazione": "Esportazione", + "inCorso": "In corso", + "nessunaInCorso": "Nessuna copia al lavoro.", + "copio": "Copio in {cartella}", + "fatti": "{fatti} di {totale} file", + "byte": "{fatti} di {totale}", + "ora": "Ora: {file}", + "fasi": { + "preparing": "Preparo la copia…", + "checking": "Controllo la cartella…", + "waitingForSession": "Aspetto la fine della sessione del motore: durante una sessione non si copia." + }, + "interrompi": "Interrompi", + "daRiprendere": "Da riprendere", + "interrotta": "Copia in {cartella} interrotta: {fatti} di {totale} file fatti.", + "ferma": "Copia in {cartella} in pausa: {problema}", + "cartellaInPausa": "{cartella} è in pausa: {problema}", + "riprendi": "Riprendi", + "riprendiTutte": "Riprendi tutte", + "annulla": "Annulla", + "annullaTitolo": "Annullare la copia in {cartella}?", + "annullaTesto": "I file già copiati restano dove sono; quelli che mancano non si copiano.", + "annullaSi": "Annulla la copia", + "ultimi": "Ultimi lavori", + "vuoto": "Nessuna copia ancora. Le copie partono da «Copia in…» nella Libreria, nel visualizzatore o nella scheda di un account.", + "lavoroCopia": "Copia in {cartella}", + "lavoroControllo": "Controllo delle copie in {cartella}", + "stati": { + "running": "In corso", + "interrupted": "Interrotta", + "paused": "In pausa", + "completed": "Completata", + "cancelled": "Annullata" + }, + "resoconto": "Resoconto", + "resocontoTitolo": "Resoconto: {lavoro}", + "iniziata": "Iniziata {quando}", + "finita": "finita {quando}", + "copiatiByte": "{spazio} scritti", + "statiFile": { + "pending": "1 in attesa|{n} in attesa", + "copied": "1 copiato|{n} copiati", + "adopted": "1 già presente, riconosciuto|{n} già presenti, riconosciuti", + "alreadyCopied": "1 già copiato|{n} già copiati", + "skipped": "1 saltato|{n} saltati", + "missing": "1 non presente in libreria|{n} non presenti in libreria", + "failed": "1 non riuscito|{n} non riusciti" + }, + "perAccount": "Per account", + "colonne": { + "account": "Account", + "copiati": "Copiati", + "gia": "Già copiati", + "saltati": "Saltati", + "falliti": "Non riusciti" + }, + "problemi": "File da guardare", + "nessunProblema": "Nessun file da guardare.", + "avvisoDaRiprendere": "1 copia da riprendere.|{n} copie da riprendere." + } } } diff --git a/tests/Febe.Tests/Data/ExportConstraintTests.cs b/tests/Febe.Tests/Data/ExportConstraintTests.cs index ae2f6a8..8109321 100644 --- a/tests/Febe.Tests/Data/ExportConstraintTests.cs +++ b/tests/Febe.Tests/Data/ExportConstraintTests.cs @@ -564,6 +564,9 @@ public sealed class ExportConstraintTests await using var db = await TestDatabase.OpenAsync(temp); var w = await CreateAsync(db); await FillAsync(db, w); + // Two copies of the files of the world, so that the «Copie» filter has copies and history to look at. + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg")); + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/b.jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Removed }); // Without statistics the planner's choice is the point for the «Copie» set shape and the latest row of an identity. var setShape = await PlanAsync( @@ -627,6 +630,51 @@ public sealed class ExportConstraintTests } } + // The lookups of tappa E2 (WP1.11). The handful of destinations in use may be read whole; never the copies. + var shas = string.Join(", ", Enumerable.Range(0, 3).Select(i => $"@x{i}")); + (string, object?)[] Shas(params (string, object?)[] more) => [.. Enumerable.Range(0, 3).Select(i => ($"@x{i}", (object?)Make.Sha(i * 7))), .. more]; + // «Una copia sola» may sort the few rows of one SHA-256 (its key is in the index the planner picks either way). + var lookupsE2 = new (string Name, string Sql, (string, object?)[] Parameters, bool SortAllowed)[] + { + ("FindReplacedCopyAsync", ExportStore.ReplacedCopySql, [("@h", Make.Sha(5008)), ("@d", w.General), ("@a", w.Marta)], false), + ("FindCopiedElsewhereAsync", ExportStore.CopiedElsewhereSql, [("@h", Make.Sha(17)), ("@v", "Whole"), ("@f", "Original"), ("@a", w.Marta)], true), + ("GetCopyStatesAsync", ExportStore.CopyStatesSql(shas), Shas(("@d", w.General)), false), + ("GetCopyStatesAsync (sostituiti)", ExportStore.ReplacedStatesSql(shas), Shas(("@d", w.General)), false), + }; + foreach (var (name, sql, parameters, sortAllowed) in lookupsE2) + { + var plan = await PlanAsync(db, sql, parameters); + var copies = plan.Replace("SCAN export_destination", string.Empty, StringComparison.Ordinal); + var withoutAllowedSort = sortAllowed ? plan.Replace("USE TEMP B-TREE FOR ORDER BY", string.Empty, StringComparison.Ordinal) : plan; + if (!plan.Contains("SEARCH export_copy USING", StringComparison.Ordinal) || !plan.Contains("sha256=?", StringComparison.Ordinal) + || copies.Contains("SCAN", StringComparison.Ordinal) || withoutAllowedSort.Contains("TEMP B-TREE", StringComparison.Ordinal)) + { + problems.Add($"{name}: {plan}"); + } + } + + // The «Copie» filter: the two prefilter lists of the grouped mosaic read the copies of the destinations in use + // through ix_export_copy_destination, and the files through their SHA-256. + var x = await db.ReadAsync(ExportFilterSql.Load, default); + foreach (var filter in new[] { Core.Storage.LibraryCopiesFilter.Copied, Core.Storage.LibraryCopiesFilter.RemovedOrSuperseded }) + { + var term = ExportFilterSql.EntryTerm(x, filter); + var start = term.IndexOf("+e.id IN (", StringComparison.Ordinal) + "+e.id IN (".Length; + var end = term.IndexOf(") AND EXISTS", start, StringComparison.Ordinal); + Assert.IsGreaterThan(start, end, term); + var plan = await PlanAsync(db, term[start..end]); + // With statistics that say the files are fewer than the copies (this small world), the planner may walk the + // SHA-256 index of the files first; the copies are always searched by destination and state. + var searchesCopies = plan.Contains("SEARCH c USING INDEX ix_export_copy_destination (destination_id=? AND state=?", StringComparison.Ordinal) + || plan.Contains("SEARCH c USING COVERING INDEX ix_export_copy_destination (destination_id=? AND state=?", StringComparison.Ordinal); + var otherScans = plan.Replace("SCAN m2 USING INDEX ix_media_sha256", string.Empty, StringComparison.Ordinal) + .Replace("SCAN m2 USING COVERING INDEX ix_media_sha256", string.Empty, StringComparison.Ordinal).Contains("SCAN", StringComparison.Ordinal); + if (!searchesCopies || !plan.Contains("m2 USING", StringComparison.Ordinal) || otherScans || plan.Contains("TEMP B-TREE", StringComparison.Ordinal)) + { + problems.Add($"prefiltro {filter}: {plan}"); + } + } + Assert.IsEmpty(problems, $"{when}: {string.Join(" || ", problems)}"); } diff --git a/tests/Febe.Tests/Data/ExportStoreTests.cs b/tests/Febe.Tests/Data/ExportStoreTests.cs index 74f5b51..fbb28fb 100644 --- a/tests/Febe.Tests/Data/ExportStoreTests.cs +++ b/tests/Febe.Tests/Data/ExportStoreTests.cs @@ -1,4 +1,5 @@ using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; using Febe.Data; using Febe.Tests.Support; @@ -482,6 +483,191 @@ public sealed class ExportStoreTests Assert.AreEqual(0, await db.Exports.RelinkOrphanCopiesAsync(again.Id)); } + [TestMethod] + public async Task AccountSwitchesAreListedInBulk() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await CreateAsync(db); + var third = await db.Accounts.AddAsync(Make.Account("anna.demo", "300")); + Assert.IsEmpty(await db.Exports.ListAccountExportSwitchesAsync()); + + await db.Exports.SetAccountExportEnabledAsync(w.Marta, false); + await db.Exports.SetAccountExportEnabledAsync(third.Id, true); + var switches = await db.Exports.ListAccountExportSwitchesAsync(); + Assert.HasCount(2, switches); + Assert.IsFalse(switches[w.Marta]); + Assert.IsTrue(switches[third.Id]); + Assert.IsFalse(switches.ContainsKey(w.Luca), "no row: «Esporta questo account» is on by default"); + + // Removing an account takes its switch with it. + await db.Accounts.DeleteAsync(third.Id); + CollectionAssert.AreEquivalent(new[] { w.Marta }, (await db.Exports.ListAccountExportSwitchesAsync()).Keys.ToArray()); + } + + [TestMethod] + public async Task ReplacedCopiesAreFoundBySupersedingSha() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await CreateAsync(db); + var older = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) }); + var newer = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg") with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2), State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) }); + await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(6) }); + + Assert.AreEqual(newer.Id, (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5)))!.Id, "the newest row first"); + Assert.AreEqual(newer.Id, (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5).ToUpperInvariant()))!.Id); + Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(5)), "another account"); + Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Marta, Make.Sha(5)), "another destination"); + Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(1)), "by the file now in the library, not by the old one"); + + // «Controlla le copie» turned it into Removed: it keeps the SHA-256 that replaced it and is still found. + Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([newer.Id], Make.T0.AddDays(1))); + var removed = (await db.Exports.FindReplacedCopyAsync(w.General, w.Marta, Make.Sha(5)))!; + Assert.AreEqual((newer.Id, ExportCopyState.Removed, Make.Sha(5)), (removed.Id, removed.State, removed.SupersededBySha256)); + Assert.AreEqual(ExportCopyState.Superseded, (await db.Exports.GetCopyAsync(older.Id))!.State); + } + + [TestMethod] + public async Task CopiesElsewhereIgnoreRetiredDestinations() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await CreateAsync(db); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original)); + var own = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own)); + var general = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia)); + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Removed }); + + Assert.AreEqual(general.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id, "the newest Copied row"); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Jpg), "another format"); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(2), ExportVariant.Whole, ExportFormat.Original)); + + await db.Exports.RetireDestinationAsync(w.General, Make.T0.AddDays(1)); + Assert.AreEqual(own.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original))!.Id); + await db.Exports.RetireDestinationAsync(w.Own, Make.T0.AddDays(1)); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original), "a retired folder is not in use"); + + // A copy whose account was removed has no account to be «per un altro account». + var third = await db.Exports.AddDestinationAsync(Destination(ExportScope.General, null, @"G:\Nuova")); + var orphan = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg", destination: third.Id)); + await db.Accounts.DeleteAsync(w.Marta); + Assert.IsNull((await db.Exports.GetCopyAsync(orphan.Id))!.AccountId); + Assert.IsNull(await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original)); + } + + [TestMethod] + public async Task CopyStatesAreReadInBatch() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await CreateAsync(db); + // 1,000 originals of marta.demo in the general folder (more than one chunk of 900 parameters): every tenth is + // Removed, every tenth plus one Superseded, every tenth plus two Failed, the rest Copied; none for luca.demo. + await InsertCopiesAsync(db, w, i => (i % 10) switch { 0 => "Removed", 1 => "Superseded", 2 => "Failed", _ => "Copied" }); + + var keys = Enumerable.Range(0, 1000).Select(i => (w.Marta, Make.Sha(100 + i))) + .Append((w.Luca, Make.Sha(100))) + .Append((w.Marta, Make.Sha(5001))) // the file that superseded the copy of number 1 + .Append((w.Marta, Make.Sha(4000))) + .ToList(); + var states = await db.Exports.GetCopyStatesAsync(w.General, keys); + Assert.HasCount(1001, states); + for (var i = 0; i < 1000; i++) + { + var expected = (i % 10) switch { 0 => ExportCopyState.Removed, 1 => ExportCopyState.Superseded, 2 => ExportCopyState.Failed, _ => ExportCopyState.Copied }; + Assert.AreEqual(expected, states[(w.Marta, Make.Sha(100 + i))], i.ToString(System.Globalization.CultureInfo.InvariantCulture)); + } + + Assert.AreEqual(ExportCopyState.Superseded, states[(w.Marta, Make.Sha(5001))]); + Assert.IsFalse(states.ContainsKey((w.Luca, Make.Sha(100)))); + Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(4000)))); + Assert.IsEmpty(await db.Exports.GetCopyStatesAsync(w.Own, keys)); + + // A new Copied row of a removed copy is the current state; the history stays behind it. + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/0 (2).jpg") with { SourceSha256 = Make.Sha(100), CopySha256 = Make.Sha(100) }); + Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.General, [(w.Marta, Make.Sha(100))]))[(w.Marta, Make.Sha(100))]); + } + + [TestMethod] + public async Task MissingCopiesAreMarkedRemovedInOneTransaction() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await CreateAsync(db); + await InsertCopiesAsync(db, w, i => (i % 4) switch { 0 => "Superseded", 1 => "Failed", 2 => "Removed", _ => "Copied" }); + var all = await db.Exports.ListCopiesAsync(w.General, limit: 2000); + Assert.HasCount(1000, all); + Assert.AreEqual(0, await db.Exports.MarkCopiesRemovedAsync([], Make.T0)); + + // Every id, twice, over two chunks: only the Copied and Superseded rows change, each once. + var ids = all.Select(c => c.Id).Concat(all.Select(c => c.Id)).ToList(); + Assert.AreEqual(500, await db.Exports.MarkCopiesRemovedAsync(ids, Make.T0.AddDays(3))); + var after = (await db.Exports.ListCopiesAsync(w.General, limit: 2000)).ToDictionary(c => c.Id); + foreach (var before in all) + { + var now = after[before.Id]; + if (before.State is ExportCopyState.Copied or ExportCopyState.Superseded) + { + Assert.AreEqual((ExportCopyState.Removed, Make.T0.AddDays(3)), (now.State, now.StateChangedAt)); + Assert.AreEqual(before.SupersededBySha256, now.SupersededBySha256, "a superseded copy keeps the file that replaced it"); + } + else + { + Assert.AreEqual(before, now); + } + } + + Assert.AreEqual(0, await db.Exports.MarkCopiesRemovedAsync(ids, Make.T0.AddDays(4)), "idempotent"); + } + + [TestMethod] + public async Task CandidatesFollowTheLibraryFilter() + { + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await CreateAsync(db); + var story = await db.Entries.AddAsync(Make.Entry(w.Luca, "556", Make.T0.AddDays(1), EntryKind.Story), [Make.Stored(Make.Photo(1), Make.Sha(3), "storie/s.jpg"), Make.Stored(Make.Photo(2), Make.Sha(4), "storie/s2.jpg")]); + var highlight = await db.Highlights.UpsertAsync(new Highlight { AccountId = w.Luca, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 }); + await db.Highlights.AddItemAsync(highlight.Id, story.Stored.Entry.Id); + var waiting = await db.Entries.AddAsync(Make.Entry(w.Luca, "557", Make.T0.AddDays(2)), [Make.Photo(1)]); + + var lucaFilter = new ExportSelection.Filter(new LibraryFilter { AccountIds = [w.Luca] }, MosaicMode.Grouped); + var luca = await db.Exports.ListCandidatesAsync(lucaFilter, 0, 100); + CollectionAssert.AreEqual(new[] { w.LucaMedia, story.Stored.Media[0].Id, story.Stored.Media[1].Id }, luca.Select(c => c.MediaId).ToArray(), "an entry still to download is not in the library"); + var first = luca.Single(c => c.MediaId == story.Stored.Media[0].Id); + Assert.AreEqual((story.Stored.Entry.Id, w.Luca, EntryKind.Story, MediaKind.Photo, Make.Sha(3), "storie/s.jpg", 1, true), + (first.EntryId, first.AccountId, first.EntryKind, first.MediaKind, first.Sha256, first.RelativePath, first.Position, first.InHighlight)); + Assert.IsFalse(luca[0].InHighlight); + + // Pages by media id. + var page = await db.Exports.ListCandidatesAsync(lucaFilter, w.LucaMedia, 1); + Assert.AreEqual(story.Stored.Media[0].Id, page.Single().MediaId); + + // An explicit choice of an entry that is not downloaded yet: listed, to be counted «non presente in libreria». + var chosen = await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([waiting.Stored.Entry.Id]), 0, 100); + Assert.AreEqual((waiting.Stored.Media[0].Id, MediaState.ToDownload, (string?)null), (chosen.Single().MediaId, chosen[0].State, chosen[0].Sha256)); + } + + /// 1,000 whole copies of marta.demo in the general folder, SHA-256 100.. with the state chosen per number (a Superseded one by 5000 + n). + private static Task InsertCopiesAsync(FebeDatabase db, ExportWorld w, Func stateOf) => + db.WriteAsync( + x => + { + var insert = x.Command(""" + INSERT INTO export_copy (destination_id, account_id, source_sha256, variant, format, state, superseded_by_sha256, relative_path, bytes, copy_sha256, copied_at) + VALUES (@d, @a, @h, 'Whole', 'Original', @s, @by, @p, CASE WHEN @p IS NULL THEN NULL ELSE 10 END, CASE WHEN @p IS NULL THEN NULL ELSE @h END, 0) + """); + for (var i = 0; i < 1000; i++) + { + var state = stateOf(i); + insert.With("@d", w.General).With("@a", w.Marta).With("@h", Make.Sha(100 + i)).With("@s", state) + .With("@by", state == "Superseded" ? Make.Sha(5000 + i) : null) + .With("@p", state == "Failed" ? null : $"marta.demo/{i}.jpg").ExecuteNonQuery(); + } + }, + default); + private static Task<(string? InstagramId, string? Username)> RemovedAccountAsync(FebeDatabase db, long copyId) => db.ReadAsync( c => diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index 3fbe074..688b495 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; using Febe.Data; using Febe.Tests.Support; @@ -8,7 +9,10 @@ namespace Febe.Tests.Data; /// /// Spec §4.6: the library must stay fluid with 200,000 entries. The class runs alone, after the parallel tests, so the -/// timings do not compete with the other workers and the long fill does not load them (#46). +/// timings do not compete with the other workers and the long fill does not load them (#46). Tappa E2 adds the «Copie» +/// filter (§15: «filtro Copie con 200.000 elementi entro 250 ms»): a general folder, an own folder that takes only the +/// photos of its account, an account with «Esporta questo account» off, a third of the due files copied, 2 % removed +/// and 1 % superseded. /// [TestClass] [DoNotParallelize] @@ -17,6 +21,10 @@ public sealed class LibraryScaleTests private const int Entries = 200_000; private const int Accounts = 40; + // Tappa E2: the account with its own folder (posts, photos only) and the account with «Esporta questo account» off. + private const int OwnAccount = 4; + private const int OffAccount = 7; + // Bounds per class of query, about 5-8× the values measured on an unloaded machine (docs/decisioni.md, #46). // Index seeks and windows measure 2-30 ms; aggregates over the whole library or an account 60-220 ms. private const double IndexBoundMs = 250; @@ -25,6 +33,11 @@ public sealed class LibraryScaleTests // «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail. private const double FilteredAggregateBoundMs = 600; + // «Copie» over the whole library (tappa E2, WP5b): every due file is classified against the copies, 240,000 files + // at about 4 µs each; measured 0.23-1.1 s (docs/decisioni.md), «Non ancora copiati» the slowest. The design asked for + // the 600 ms of the filtered aggregates: not reachable without a column of state per file, which E2 does not add. + private const double CopiesAggregateBoundMs = 3000; + public TestContext TestContext { get; set; } = null!; [TestMethod] @@ -67,17 +80,66 @@ public sealed class LibraryScaleTests await db.Entries.AddManyAsync(items, ct); } + var copies = await FillCopiesAsync(db, temp, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); // Plans differ with and without ANALYZE statistics: both must be fast. // The fill stays outside the timings. - await MeasureAll(db, accountIds, "senza statistiche", ct); + await MeasureAll(db, accountIds, copies, "senza statistiche", ct); await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct); - await MeasureAll(db, accountIds, "con ANALYZE", ct); + await MeasureAll(db, accountIds, copies, "con ANALYZE", ct); } - private async Task MeasureAll(FebeDatabase db, List accountIds, string label, CancellationToken ct) + /// + /// The export side of the library: the general folder for every account, an own folder for account 4 (post photos + /// only, so its videos are not due), account 7 switched off. The copies are written in bulk on the due files only, + /// chosen by a hash of the media id: a third Copied, then 2 % Removed and 1 % Superseded by the file now in the + /// library. Not by the media id itself: the fill repeats every 40 entries (48 files), so «m.id % 3» (or any linear + /// hash of it) would copy all the files of some accounts and none of others; a square mixes the ids. + /// + private static async Task FillCopiesAsync(FebeDatabase db, TempFolder temp, List accountIds, CancellationToken ct) + { + const string Hash = "((m.id * 2654435761) % 1000003)"; + const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)"; + var general = await db.Exports.AddDestinationAsync( + new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct); + var own = await db.Exports.AddDestinationAsync( + new ExportDestination { Scope = ExportScope.Account, AccountId = accountIds[OwnAccount], RootPath = temp.Combine("sua"), ContentTypes = ContentTypes.PostPhotos, CreatedAt = Make.T0 }, + ct); + await db.Exports.SetAccountExportEnabledAsync(accountIds[OffAccount], false, ct); + + var destination = $"(CASE e.account_id WHEN {accountIds[OwnAccount]} THEN {own.Id} ELSE {general.Id} END)"; + var due = $"m.sha256 IS NOT NULL AND e.account_id <> {accountIds[OffAccount]} AND (e.account_id <> {accountIds[OwnAccount]} OR m.kind = 'Photo')"; + int Insert(WriteContext w, string state, string source, string supersededBy, string which) => w.Command( + $""" + INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, state, superseded_by_sha256, + origin, relative_path, bytes, copy_sha256, copied_at) + SELECT {destination}, e.account_id, m.id, {source}, 'Whole', 'Original', '{state}', {supersededBy}, + 'Written', 'p/' || m.id || '.jpg', 1000, {source}, 1767225600000 + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE {due} AND {which} + """).ExecuteNonQuery(); + return await db.WriteAsync( + w => new CopiesWorld( + Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0"), + Insert(w, "Removed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 50 = 1"), + // The old original of a file replaced in the library («Tieni il più grande», a rebuild). + Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"), + DueFiles(), + accountIds[OwnAccount]), + ct); + } + + /// The due files of the fill, from its rules: every file, but none of account 7 and only the photos of account 4. + private static int DueFiles() => Enumerable.Range(0, Entries).Sum(n => (n % Accounts) switch + { + OffAccount => 0, + OwnAccount => (n % 7 != 0 ? 1 : 0) + (n % 5 == 0 ? 1 : 0), + _ => 1 + (n % 5 == 0 ? 1 : 0), + }); + + private async Task MeasureAll(FebeDatabase db, List accountIds, CopiesWorld copies, string label, CancellationToken ct) { var times = new List<(string Name, double Bound, Timing Timing)>(); async Task Measure(string name, double bound, Func> query) @@ -155,15 +217,74 @@ public sealed class LibraryScaleTests await Measure("coda degli scaricamenti", IndexBoundMs, () => db.Media.ListPendingDownloadsAsync(50)); var hashes = await Measure("caricamento impronte", AggregateBoundMs, () => db.Media.LoadPerceptualHashesAsync()); Assert.IsGreaterThan(150_000, hashes.Count); + // The times are printed even when a result of the «Copie» filter is wrong (the measures are the point of #46). + AssertFailedException? copiesProblem = null; + try + { + await MeasureCopiesAsync(Measure, db, accountIds, copies); + } + catch (AssertFailedException e) + { + copiesProblem = e; + } foreach (var (name, bound, timing) in times) { TestContext.WriteLine($"[{label}] {name,-40} {timing.BestMs,8:F1} ms (limite {bound:F0}, {timing.Runs} prove)"); } + if (copiesProblem is not null) + { + throw copiesProblem; + } + foreach (var (name, bound, timing) in times) { Assert.IsLessThan(bound, timing.BestMs, $"[{label}] {name}"); } } + + /// + /// The «Copie» filter (tappa E2): the window of each of its three values at the bound of the windows, in the + /// grouped mosaic, in «Tutte le foto» and on one account (§15: 250 ms); totals and days at their own bound. + /// In «Tutte le foto» the three values split the due files (D3), so their days add up to the copies written. + /// + private static async Task MeasureCopiesAsync( + Func>, Task> measure, FebeDatabase db, List accountIds, CopiesWorld copies) + { + var values = new (LibraryCopiesFilter Value, string Name)[] + { + (LibraryCopiesFilter.Copied, "copiati"), + (LibraryCopiesFilter.NotCopied, "non ancora copiati"), + (LibraryCopiesFilter.RemovedOrSuperseded, "tolti o superati"), + }; + var files = new Dictionary(); + foreach (var (value, name) in values) + { + var filter = new LibraryFilter { Copies = value }; + var window = (LibraryPage)await measure($"Copie {name}", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = filter })); + Assert.HasCount(200, window.Tiles, name); + Assert.IsFalse(window.Tiles.Any(t => t.AccountId == accountIds[OffAccount]), name); + var fileWindow = (LibraryPage)await measure($"Copie {name}: tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = filter })); + Assert.HasCount(200, fileWindow.Tiles, name); + var own = new LibraryFilter { Copies = value, AccountIds = [copies.OwnAccountId] }; + var ownWindow = (LibraryPage)await measure($"Copie {name}: un account", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = own })); + Assert.IsNotEmpty(ownWindow.Tiles, name); + Assert.IsTrue(ownWindow.Tiles.All(t => t.AccountId == copies.OwnAccountId), name); + await measure($"Copie {name}: un account, tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = own })); + var totals = (LibraryTotals)await measure($"Copie {name}: totali", CopiesAggregateBoundMs, async () => await db.Entries.GetLibraryTotalsAsync(filter)); + var days = (IReadOnlyList)await measure($"Copie {name}: giorni", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome)); + Assert.AreEqual(totals.Entries, days.Sum(d => d.Count), name); + Assert.AreEqual(Accounts - 1, totals.Accounts, name); + var fileDays = (IReadOnlyList)await measure($"Copie {name}: giorni, tutte le foto", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files)); + files[value] = fileDays.Sum(d => d.Count); + } + + Assert.AreEqual(copies.Copied, files[LibraryCopiesFilter.Copied]); + Assert.AreEqual(copies.Removed + copies.Superseded, files[LibraryCopiesFilter.RemovedOrSuperseded]); + Assert.AreEqual(copies.Due - copies.Copied - copies.Removed - copies.Superseded, files[LibraryCopiesFilter.NotCopied]); + } + + /// What the export fill wrote: copies by state, the due files, and the account with its own folder. + private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId); } diff --git a/tests/Febe.Tests/Data/MigrationTests.cs b/tests/Febe.Tests/Data/MigrationTests.cs index 7e3d287..d21125f 100644 --- a/tests/Febe.Tests/Data/MigrationTests.cs +++ b/tests/Febe.Tests/Data/MigrationTests.cs @@ -164,6 +164,9 @@ public sealed class MigrationTests [TestMethod] public async Task DatabaseAtVersion2IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(2); + [TestMethod] + public async Task DatabaseAtVersion3IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(3); + [TestMethod] public void MigrationThreeChangesNoExistingTable() { @@ -174,12 +177,42 @@ public sealed class MigrationTests var before = SchemaOf(path, Version1Tables); var shapesBefore = TableShapes(path, Version1Tables); - Close(FebeDatabase.Open(path, all)); + // Migration 4 adds an index on media (the «Copie» filter): migration 3 alone is compared here. + Close(FebeDatabase.Open(path, all.Take(3).ToList())); CollectionAssert.AreEqual(before, SchemaOf(path, Version1Tables), "la migrazione 3 non tocca tabelle né indici esistenti"); CollectionAssert.AreEqual(shapesBefore, TableShapes(path, Version1Tables), "colonne e indici delle tabelle esistenti restano gli stessi"); } + /// + /// Migration 4 (tappa E2) adds only the index of the «Copie» filter on media (sha256, entry_id): every other table, + /// column and index stays the same, and the plan of the list of the entries with a copy reads it. + /// + [TestMethod] + public void MigrationFourOnlyAddsTheIndexOfTheCopiesFilter() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + var all = MigrationRunner.LoadEmbedded(); + Assert.IsGreaterThanOrEqualTo(4, all.Count); + Close(FebeDatabase.Open(path, all.Take(3).ToList())); + var tables = TablesOf(path); + var before = SchemaOf(path, tables); + + Close(FebeDatabase.Open(path, all.Take(4).ToList())); + + CollectionAssert.AreEqual(tables, TablesOf(path), "nessuna tabella nuova"); + var added = SchemaOf(path, tables).Except(before).ToList(); + Assert.HasCount(1, added, string.Join(" | ", added)); + StringAssert.Contains(added[0], "ix_media_sha256_entry"); + StringAssert.Contains(added[0], "(sha256, entry_id) WHERE sha256 IS NOT NULL"); + CollectionAssert.IsSubsetOf(before, SchemaOf(path, tables), "nulla di prima cambia"); + using var connection = Connect(path); + var plan = string.Join(" | ", ReadColumn(connection, + "EXPLAIN QUERY PLAN SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN (1, 2) AND c.state = 'Copied'", 3)); + StringAssert.Contains(plan, "COVERING INDEX ix_media_sha256_entry", plan); + } + [TestMethod] public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched() { @@ -218,7 +251,7 @@ public sealed class MigrationTests await using (var db = FebeDatabase.Open(path, all)) { Assert.AreEqual(all.Count, db.SchemaVersion); - Assert.AreEqual(3, db.SchemaVersion); + Assert.AreEqual(4, db.SchemaVersion); } using var connection = Connect(path); @@ -340,6 +373,26 @@ public sealed class MigrationTests return rows; } + /// Every table of the database, by name. + private static List TablesOf(string path) + { + using var connection = Connect(path); + return ReadColumn(connection, "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", 0); + } + + /// One column of every row of a query, as text. + private static List ReadColumn(SqliteConnection connection, string sql, int column) + { + using var r = connection.Command(sql).ExecuteReader(); + var values = new List(); + while (r.Read()) + { + values.Add(Convert.ToString(r.GetValue(column), System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty); + } + + return values; + } + /// The SQL of the tables and of their indexes and triggers. private static List SchemaOf(string path, IEnumerable tables) { diff --git a/tests/Febe.Tests/Docs/GuideTests.cs b/tests/Febe.Tests/Docs/GuideTests.cs index f5d7aef..624749d 100644 --- a/tests/Febe.Tests/Docs/GuideTests.cs +++ b/tests/Febe.Tests/Docs/GuideTests.cs @@ -20,6 +20,7 @@ public sealed partial class GuideTests "Account-e-impostazioni", "Libreria", "Importazione", + "Esportazione", "Limiti-e-comportamento", "Dashboard-e-arresti", "Avvisi-e-Telegram", @@ -48,6 +49,9 @@ public sealed partial class GuideTests ["che cosa fare dopo una verifica o un rallentamento", new[] { "Dashboard-e-arresti" }, new[] { "che cosa fare dopo una verifica", "che cosa fare dopo un rallentamento", "completa la verifica a mano", "riprendi", "tre rallentamenti in sette giorni" }], ["dove sono le copie del database e come si ricostruisce", new[] { "Copie-e-ricostruzione" }, new[] { "/dati/copie", "%localappdata%\\febe\\copie", "febe-aaaa-mm-gg.sqlite", "ricostruisci il database dalla libreria", "_febe.jsonl" }], ["esportazione CSV dell'elenco (§4.8)", new[] { "Libreria" }, new[] { "esporta l'elenco", "`;`", "utf-8 con bom" }], + ["copie esterne fuori dal controllo di Febe (§13.2)", new[] { "Esportazione", "Sicurezza-e-riservatezza" }, new[] { "escono dal controllo di febe", "non le cifra", "non le cancella" }], + ["le copie esterne: interruttore acceso, radice mai creata, /esporta montata (§4.10)", new[] { "Esportazione" }, new[] { "«esporta questo account»", "è acceso", "febe non la crea mai", "febe_esporta=1", "/esporta", "«copia di nuovo»", "non si ricopiano mai da soli", "dashboard" }], + ["/esporta in Docker: variabile e volume facoltativo (§11)", new[] { "Installazione-Docker-e-Unraid", "Problemi-comuni" }, new[] { "/esporta", "febe_esporta" }], ["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" }], diff --git a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs index af3afe0..4ec8a32 100644 --- a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs +++ b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs @@ -193,7 +193,12 @@ public sealed partial class SpecificationConsistencyTests ["«Tutte le foto» mostra solo i file in libreria e manca in «In evidenza»", "- **«Raggruppa i post» o «Tutte le foto»**", new[] { "scheda account, tranne «in evidenza», disegnata per raccolta", "ha una tessera solo un file presente in libreria", "un file ancora da scaricare, fallito o saltato no", "con i filtri «foto» e «video» si vedono solo i file di quel tipo" }], ["la scheda account ha l'interruttore tranne in «In evidenza»", "- Scheda dell'account con gli elementi divisi", new[] { "«raggruppa i post» / «tutte le foto» in ogni linguetta tranne «in evidenza»" }], ["il mockup 12 dà l'interruttore tranne in «In evidenza»", "- **«Raggruppa i post» / «Tutte le foto»** (§4.6), dal mockup 01", new[] { "scheda account (mockup 12), tranne «in evidenza»" }], - ["la riga del mockup 06 rimanda alle schermate di D1", "| `06-attivita.png` |", new[] { "superato dalla dashboard (qui sotto, «schermate della tappa d1»)" }], + ["«Esporta questo account» è acceso per impostazione predefinita", "- Una **cartella di esportazione generale**", new[] { "«esporta questo account» è acceso per impostazione predefinita", "decisione di alberto del 27 novembre 2026", "un account senza scelta registrata si esporta", "anche quando la si chiede a mano", "§16 domanda 22" }], + ["/esporta è attiva su un montaggio in /esporta o sotto, letto da mountinfo", "**Docker e Windows.** In Docker", new[] { "`/proc/self/mountinfo`", "su un montaggio in `/esporta` o sotto", "un'opzione senza valore", "§16 domanda 23", "né un `mkdir`", "solo quando le copie esterne sono dichiarate" }], + ["i file dovuti sono la base di segno, filtro, conteggio e «Copia in…»", "- **File dovuti** (tappa E2)", new[] { "«esporta questo account» acceso", "tipo di contenuto è fra quelli della destinazione", "§16 domanda 26", "«non riuscito» compreso", "un account spento non ha file dovuti" }], + ["le tabelle dell'esportazione sono usate da E2", "| `export_destination`", new[] { "usate dalla tappa e2", "nessuna riga vuol dire acceso" }], + ["§16 propone le risposte delle domande di E2", "| 22 |", new[] { "copia in…", "anche a mano", "così fa la tappa e2" }], + ["la riga del mockup 06 rimanda alle schermate di D1","| `06-attivita.png` |", new[] { "superato dalla dashboard (qui sotto, «schermate della tappa d1»)" }], ]; /// diff --git a/tests/Febe.Tests/Export/ExportCopierTests.cs b/tests/Febe.Tests/Export/ExportCopierTests.cs new file mode 100644 index 0000000..f4ed1e4 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportCopierTests.cs @@ -0,0 +1,391 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The copy job on real folders (spec §4.10 «Come si copia», §4.10 l.272-274; the E2 row: «nessuna sovrascrittura», +/// «adozione», «radice mai creata»). The cases already in (account segment, «Tolto», +/// adoption next to a taken name, missing root, sessions and space, FAT32, leftovers after a restart) are not repeated. +/// +[TestClass] +public sealed class ExportCopierTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task CopiesOriginalsByteForByteAndRecordsThem() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "950", Make.T0.AddDays(-3)), [ExportTestBed.Photo(1, 21), TestFile.Video(2, 70_000)]); + var usb = await bed.GeneralAsync(ct: ct); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var items = await bed.ItemsAsync(start.Runs.Single().Id, ct); + Assert.HasCount(2, items); + foreach (var media in post.Media) + { + var item = items.Single(i => i.MediaId == media.Id); + Assert.AreEqual((ExportItemState.Copied, ExportVariant.Whole, ExportFormat.Original), (item.State, item.Variant, item.Format)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportCopyState.Copied, ExportCopyOrigin.Written), (copy.State, copy.Origin)); + Assert.AreEqual((usb.Id, bed.Marta.Id, media.Id), (copy.DestinationId, copy.AccountId, copy.MediaId)); + Assert.AreEqual((media.Sha256, media.Sha256, media.Bytes), (copy.SourceSha256, copy.CopySha256, copy.Bytes)); + Assert.AreEqual(item.RelativePath, copy.RelativePath); + Assert.AreEqual("marta.demo/" + media.RelativePath, copy.RelativePath); + Assert.AreEqual(bed.Clock.Now, copy.CopiedAt); + + var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)); + Assert.AreEqual(media.Sha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(file, ct)))); + Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(file)); // «libreria.data-file-pubblicazione» is on + } + + Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb)); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual((ExportRunState.Completed, ExportRunKind.Copy, ExportRunOrigin.Manual), (run.State, run.Kind, run.Origin)); + var completed = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Single(e => e.Code == "esportazione-completata"); + Assert.AreEqual(EventSeverity.Success, completed.Severity); + } + + [TestMethod] + public async Task TheFileTimeIsLeftAloneWhenTheLibrarySaysSo() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "951", 22); + await bed.Db.Settings.SetAsync(Core.Storage.SettingKeys.SetFileTimeToPublication, "false", ct); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreNotEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0]))); + } + + [TestMethod] + public async Task TheRootIsNeverCreatedWhenTheDiskGoesDuringAJob() + { + var ct = TestContext.CancellationToken; + var unplug = new Unplug(); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = unplug }); + var post = await bed.PostAsync(bed.Marta, "952", 23, 24); + var usb = await bed.GeneralAsync(ct: ct); + unplug.Root = bed.Usb; + unplug.When = path => path.EndsWith("_2.jpg", StringComparison.Ordinal); // the disk goes while the second file starts + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State); + Assert.IsFalse(Directory.Exists(bed.Usb), "the root is never created again"); + Assert.IsTrue(post.Media.All(m => File.Exists(bed.LibraryFile(bed.Marta, m))), "the library is untouched"); + var items = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State); + Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State); + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(items[post.Media[0].Id].CopyId!.Value, ct))!.State, "never «Tolto» because the disk went"); + Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + + // Plugged in again (empty): «Riprendi» writes the second file only. + unplug.When = _ => false; + Directory.CreateDirectory(bed.Usb); + await bed.Service.ResumeAsync([run.Id], ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[1]))); + } + + [TestMethod] + public async Task AnIdenticalFileAtThePathIsAdoptedAndASameSizeDifferentFileIsNot() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var same = await bed.PostAsync(bed.Marta, "953", 25); + var other = await bed.PostAsync(bed.Marta, "954", 26); + await bed.GeneralAsync(ct: ct); + + // An earlier copy by hand, with its own date, and a file of the same size but other bytes. + var adopted = bed.GeneralCopy(bed.Marta, same.Media[0]); + var foreign = bed.GeneralCopy(bed.Marta, other.Media[0]); + Directory.CreateDirectory(Path.GetDirectoryName(adopted)!); + File.Copy(bed.LibraryFile(bed.Marta, same.Media[0]), adopted); + var handDate = new DateTime(2020, 5, 1, 12, 0, 0, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(adopted, handDate); + var bytes = await File.ReadAllBytesAsync(bed.LibraryFile(bed.Marta, other.Media[0]), ct); + bytes[^3] ^= 0x01; + await File.WriteAllBytesAsync(foreign, bytes, ct); + var before = Fingerprint.Of(bed.Usb); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value); + var adoption = items[same.Media[0].Id]; + Assert.AreEqual(ExportItemState.Adopted, adoption.State); + var copy = (await bed.Db.Exports.GetCopyAsync(adoption.CopyId!.Value, ct))!; + Assert.AreEqual((ExportCopyState.Copied, ExportCopyOrigin.Adopted), (copy.State, copy.Origin)); + Assert.AreEqual(handDate, File.GetLastWriteTimeUtc(adopted), "adopted, not written again"); + + var written = items[other.Media[0].Id]; + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (written.State, written.Note)); + StringAssert.EndsWith(written.RelativePath, " (2).jpg"); + + // Both files that were there are exactly as they were; one new file beside them. + var after = Fingerprint.Of(bed.Usb); + foreach (var (path, print) in before) + { + Assert.AreEqual(print, after[path], path); + } + + Assert.AreEqual(before.Count + 1, after.Count); + Assert.IsTrue(after.ContainsKey(written.RelativePath!)); + } + + [TestMethod] + public async Task AnOrphanRowOnThePathIsRelinkedOnAdoption() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await bed.PostAsync(bed.Marta, "955", 27); + await bed.GeneralAsync(ct: ct); + var first = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value; + + // marta.demo is removed from Febe (her copy stays, without an account) and another account with that name comes: + // another Instagram id, so the copy does not come back by itself. + await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct); + Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true); + Assert.IsNull((await bed.Db.Exports.GetCopyAsync(copyId, ct))!.AccountId); + var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct); + Assert.IsNull((await bed.Db.Exports.GetCopyAsync(copyId, ct))!.AccountId); + await bed.PostAsync(again, "955", 27); // the same post, the same bytes + + var files = Fingerprint.Of(bed.Usb); + var start = await bed.CopyAccountAsync(again, ct: ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Adopted, copyId), (item.State, item.CopyId)); + var relinked = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!; + Assert.AreEqual((again.Id, ExportCopyState.Copied), (relinked.AccountId, relinked.State)); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written"); + Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(again.Id)), ct)).Files); + } + + [TestMethod] + public async Task AResumedItemAdoptsItsOwnFileAfterACrash() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "956", 28); + var usb = await bed.GeneralAsync(ct: ct); + var planned = "marta.demo/" + post.Media[0].RelativePath; + + // Before the crash: the planned name was taken by another file, ours was renamed «(2)», the record never came. + var taken = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(planned)); + Directory.CreateDirectory(Path.GetDirectoryName(taken)!); + await File.WriteAllBytesAsync(taken, [7, 7, 7], ct); + var ours = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(ExportPaths.NumberedName(bed.Usb, planned, 2))); + File.Copy(bed.LibraryFile(bed.Marta, post.Media[0]), ours); + var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = bed.Clock.Now }, ct); + await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = bed.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct); + var pending = (await bed.ItemsAsync(run.Id, ct)).Single(); + await bed.Db.Exports.UpdateItemsAsync([pending with { RelativePath = planned }], ct); + var files = Fingerprint.Of(bed.Usb); + + Assert.AreEqual(1, await bed.Service.RecoverAsync(ct)); + await bed.Service.ResumeAsync(null, ct); + await bed.Service.WaitAsync(ct); + + var item = (await bed.ItemsAsync(run.Id, ct)).Single(); + Assert.AreEqual(ExportItemState.Adopted, item.State); + Assert.AreEqual(ExportPaths.NumberedName(bed.Usb, planned, 2), item.RelativePath); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "no second file, nothing overwritten"); + Assert.AreEqual(ExportCopyOrigin.Adopted, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.Origin); + } + + [TestMethod] + public async Task ACorruptedReadIsNotRenamedAndAFailedCopyIsRetried() + { + var ct = TestContext.CancellationToken; + var corrupt = true; + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = new CorruptingExportFileSystem(_ => Volatile.Read(ref corrupt)) }); + var post = await bed.PostAsync(bed.Marta, "957", 29); + var usb = await bed.GeneralAsync(ct: ct); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Failed, ExportText.Notes.SourceChanged), (item.State, item.Note)); + Assert.AreEqual("Il file della libreria non corrisponde a quello registrato.", item.LastError); + Assert.IsEmpty(Fingerprint.Of(bed.Usb), "no final file, no .part left"); + var failed = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual(ExportCopyState.Failed, failed.State); + Assert.IsNull(failed.RelativePath); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs.Single().Id, ct)).State, "the job goes on"); + Assert.AreEqual(EventSeverity.Warning, (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Single(e => e.Code == "esportazione-completata").Severity); + Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 1, 0, 1), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)); + + // The cable is fixed: the next «Copia in…» tries again, on the same copy row. + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual(1, plan.Files); + Volatile.Write(ref corrupt, false); + var again = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var retried = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, failed.Id), (retried.State, retried.CopyId)); + var copy = (await bed.Db.Exports.GetCopyAsync(failed.Id, ct))!; + Assert.AreEqual((ExportCopyState.Copied, (string?)null), (copy.State, copy.LastError)); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + } + + [TestMethod] + public async Task AFileMissingInTheLibraryIsReportedNotDownloaded() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var present = await bed.PostAsync(bed.Marta, "958", 30, 31); + var waiting = await bed.Db.Entries.AddAsync(Make.Entry(bed.Marta.Id, "959", Make.T0.AddDays(-2)), [Make.Photo(1)], ct); // still to download + await bed.GeneralAsync(ct: ct); + File.Delete(bed.LibraryFile(bed.Marta, present.Media[1])); // gone from the disk behind Febe's back + + var request = new ExportJobRequest(new ExportSelection.Entries([present.Entry.Id, waiting.Stored.Entry.Id])); + var plan = await bed.Service.PlanAsync(request, ct); + Assert.AreEqual((2, 1), (plan.Files, plan.Missing)); // the plan reads the database only + + var start = await bed.CopyAsync(request, ct); + var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.HasCount(2, items); // the file to download has no item: it is only counted + Assert.AreEqual(ExportItemState.Copied, items[present.Media[0].Id].State); + var missing = items[present.Media[1].Id]; + Assert.AreEqual((ExportItemState.Missing, ExportText.Notes.SourceMissing), (missing.State, missing.Note)); + Assert.AreEqual("File non presente in libreria", ExportText.Note(missing.Note!)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + Assert.IsFalse(File.Exists(bed.LibraryFile(bed.Marta, present.Media[1])), "nothing is downloaded or restored"); + var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(1, report.ByState[ExportItemState.Missing]); + } + + [TestMethod] + public async Task NotEnoughSpacePausesTheDestinationAtTheMargin() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "960", 32); + var usb = await bed.GeneralAsync(ct: ct); + var bytes = post.Media[0].Bytes!.Value; + + bed.Disk.Free = bytes + ExportSpace.Margin - 1; + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State); + var paused = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!; + Assert.IsNotNull(paused.PausedAt); + Assert.AreEqual(run.LastError, paused.LastError); + StringAssert.Contains(paused.LastError, "margine di 64 MB"); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + Assert.IsTrue((await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).Destinations.Single().Paused); + + bed.Disk.Free = bytes + ExportSpace.Margin; // exactly the margin is enough + await bed.Service.ResumeAsync([run.Id], ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + } + + [TestMethod] + public async Task AProbeFailurePausesAndResumeCarriesOn() + { + var ct = TestContext.CancellationToken; + var probes = 0; + var failAt = -1; + await using var bed = await ExportTestBed.CreateAsync(env => env with + { + GroupFiles = 1, // a probe before every file + WriteProbe = path => + { + if (Interlocked.Increment(ref probes) == Volatile.Read(ref failAt)) + { + throw new IOException("Il supporto è protetto da scrittura."); + } + + File.WriteAllText(path, "Febe"); + }, + }); + var post = await bed.PostAsync(bed.Marta, "961", 33, 34); + var usb = await bed.GeneralAsync(ct: ct); + Volatile.Write(ref failAt, Volatile.Read(ref probes) + 2); // the probe before the second file fails + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State); + StringAssert.StartsWith(run.LastError, $"Febe non riesce a scrivere in {Path.GetFullPath(bed.Usb)}"); + var items = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State); + Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State); + Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + var alert = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Where(e => e.Code == ExportPause.PausedEventCode).ToList(); + Assert.HasCount(1, alert); + Assert.AreNotEqual(EventSeverity.Error, alert[0].Severity, "a pause, never the red strip"); + + await bed.Service.ResumeAsync(null, ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(run.Id, ct)).Single(i => i.MediaId == post.Media[1].Id).State); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + Assert.HasCount(2, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task ThePartFilesOfADiscardedRunAreCleanedOnlyInItsFolders() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "962", 35); + var usb = await bed.GeneralAsync(ct: ct); + var relative = "marta.demo/" + post.Media[0].RelativePath; + var folder = Path.GetDirectoryName(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(relative)))!; + var elsewhere = bed.Temp.Combine("usb", "altro"); + Directory.CreateDirectory(folder); + Directory.CreateDirectory(elsewhere); + var ours = Path.Combine(folder, ".febe-0123456789ab.part"); + var notInAFolderOfItems = Path.Combine(elsewhere, ".febe-ba9876543210.part"); + var alberto = Path.Combine(folder, "appunti.part"); // not one of our names + foreach (var file in new[] { ours, notInAFolderOfItems, alberto }) + { + await File.WriteAllBytesAsync(file, [9], ct); + } + + var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct); + await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = bed.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct); + var item = (await bed.ItemsAsync(run.Id, ct)).Single(); + await bed.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct); + + await bed.Service.DiscardAsync(run.Id, ct); + Assert.AreEqual(ExportRunState.Cancelled, (await bed.RunAsync(run.Id, ct)).State); + Assert.IsFalse(File.Exists(ours)); + Assert.IsTrue(File.Exists(notInAFolderOfItems)); + Assert.IsTrue(File.Exists(alberto)); + await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync([run.Id], ct)); + } + + /// The real file system; opening a chosen library file first takes the destination disk away. + private sealed class Unplug : IExportFileSystem + { + public string? Root { get; set; } + + public Func When { get; set; } = _ => false; + + public Stream OpenRead(string path) + { + if (Root is { } root && When(path) && Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + + return ExportFileSystem.Instance.OpenRead(path); + } + + public Task ComputeSha256Async(string path, CancellationToken ct) => ExportFileSystem.Instance.ComputeSha256Async(path, ct); + + public bool FileExists(string path) => ExportFileSystem.Instance.FileExists(path); + + public long? FileLength(string path) => ExportFileSystem.Instance.FileLength(path); + } +} diff --git a/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs new file mode 100644 index 0000000..1902b26 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportCopiesFilterTests.cs @@ -0,0 +1,124 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The «Copie» filter, the tile marks, the account counts and the store lookups of tappa E2 on a small real database +/// (decision D3: only due files count). WP5 of tappa E2 adds the full set and the timings over 200,000 entries. +/// +[TestClass] +public sealed class ExportCopiesFilterTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheCopiesFilterSplitsDueFilesIntoCopiedNotCopiedAndRemoved() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + // A post of marta.demo with two photos: only the first is copied («Copiato in parte»). + var pair = await db.Entries.AddAsync( + Make.Entry(w.Marta, "777", Make.T0.AddDays(1)), + [Make.Stored(Make.Photo(1), Make.Sha(2), "post/b1.jpg"), Make.Stored(Make.Photo(2), Make.Sha(3), "post/b2.jpg")], + ct); + var pairEntry = pair.Stored.Entry.Id; + + // Marta's own folder has her shared post and the first photo of the pair; luca.demo's tagged post was copied + // in the general folder and then removed from it. + await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct); + await db.Exports.AddCopyAsync(w.WholeCopy("b1.jpg", destination: w.Own, media: pair.Stored.Media[0].Id) with { SourceSha256 = Make.Sha(2), CopySha256 = Make.Sha(2) }, ct); + var removed = await db.Exports.AddCopyAsync( + w.WholeCopy("luca.demo/a.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed }, + ct); + + Assert.IsTrue(AreSame([w.MartaEntry], await EntriesAsync(db, LibraryCopiesFilter.Copied, ct))); + Assert.IsTrue(AreSame([pairEntry], await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct))); + Assert.IsTrue(AreSame([w.LucaEntry], await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct))); + Assert.AreEqual(new LibraryTotals(1, 1), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, ct)); + Assert.AreEqual(1, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied }, TestZones.Rome, ct: ct)).Sum(d => d.Count)); + + // «Tutte le foto» judges each file: the copied photo of the pair is «Copiato», the other «Non ancora copiato». + var copiedFiles = await FilesAsync(db, LibraryCopiesFilter.Copied, ct); + Assert.IsTrue(AreSame([w.MartaMedia, pair.Stored.Media[0].Id], copiedFiles)); + Assert.IsTrue(AreSame([pair.Stored.Media[1].Id], await FilesAsync(db, LibraryCopiesFilter.NotCopied, ct))); + Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + Assert.AreEqual(2, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Marta] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + Assert.AreEqual(0, (await db.Entries.CountLibraryByDayAsync(new LibraryFilter { Copies = LibraryCopiesFilter.Copied, AccountIds = [w.Luca] }, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + + var marks = await db.Exports.GetEntryMarksAsync([w.MartaEntry, w.LucaEntry, pairEntry], ct); + Assert.AreEqual(ExportMark.Copied, marks[w.MartaEntry]); + Assert.AreEqual(ExportMark.None, marks[w.LucaEntry]); + Assert.AreEqual(ExportMark.Partly, marks[pairEntry]); + var fileMarks = await db.Exports.GetFileMarksAsync([.. pair.Stored.Media.Select(m => m.Id)], ct); + Assert.AreEqual(ExportMark.Copied, fileMarks[pair.Stored.Media[0].Id]); + Assert.AreEqual(ExportMark.None, fileMarks[pair.Stored.Media[1].Id]); + Assert.AreEqual(new ExportAccountCounts(3, 1, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct)); + + // «Esporta questo account» off: marta.demo has no due files any more. + await db.Exports.SetAccountExportEnabledAsync(w.Marta, false, ct); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + Assert.AreEqual(new ExportAccountCounts(0, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + Assert.IsFalse((await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct)).ContainsKey(w.MartaEntry)); + var switches = await db.Exports.ListAccountExportSwitchesAsync(ct); + Assert.IsFalse(switches[w.Marta]); + Assert.IsFalse(switches.ContainsKey(w.Luca)); + + // «Controlla le copie» turns a Copied row into Removed. + Assert.AreEqual(1, await db.Exports.MarkCopiesRemovedAsync([removed.Id, (await db.Exports.FindCurrentCopyAsync(new ExportCopyIdentity(w.Own, w.Marta, Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, null), ct))!.Id], Make.T0.AddDays(2), ct)); + } + + [TestMethod] + public async Task TheStoreAnswersThePlannerLookups() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + var copy = await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct); + await db.Exports.AddCopyAsync( + w.WholeCopy("luca.demo/old.jpg", destination: w.General, account: w.Luca, media: w.LucaMedia) with + { + SourceSha256 = Make.Sha(9), + CopySha256 = Make.Sha(9), + State = ExportCopyState.Superseded, + SupersededBySha256 = Make.Sha(1), + }, + ct); + + var states = await db.Exports.GetCopyStatesAsync(w.General, [(w.Luca, Make.Sha(1)), (w.Marta, Make.Sha(1))], ct); + Assert.AreEqual(ExportCopyState.Superseded, states[(w.Luca, Make.Sha(1))]); + Assert.IsFalse(states.ContainsKey((w.Marta, Make.Sha(1)))); + Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyStatesAsync(w.Own, [(w.Marta, Make.Sha(1))], ct))[(w.Marta, Make.Sha(1))]); + Assert.IsNotNull(await db.Exports.FindReplacedCopyAsync(w.General, w.Luca, Make.Sha(1), ct)); + Assert.IsNull(await db.Exports.FindReplacedCopyAsync(w.Own, w.Luca, Make.Sha(1), ct)); + Assert.AreEqual(copy.Id, (await db.Exports.FindCopiedElsewhereAsync(Make.Sha(1), ExportVariant.Whole, ExportFormat.Original, ct: ct))!.Id); + + var byAccount = await db.Exports.ListCandidatesAsync(new ExportSelection.Account(w.Marta), 0, 10, ct); + Assert.AreEqual(w.MartaMedia, byAccount.Single().MediaId); + Assert.AreEqual(EntryKind.Post, byAccount[0].EntryKind); + var byFilter = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(new LibraryFilter(), MosaicMode.Files), 0, 10, ct); + Assert.HasCount(2, byFilter); + Assert.AreEqual(w.LucaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Entries([w.LucaEntry, w.MartaEntry]), w.MartaMedia, 10, ct)).Single().MediaId); + Assert.AreEqual(w.MartaMedia, (await db.Exports.ListCandidatesAsync(new ExportSelection.Media([w.MartaMedia, w.LucaMedia]), 0, 1, ct)).Single().MediaId); + + var run = await db.Exports.CreateRunAsync(new ExportRun { DestinationId = w.General, StartedAt = Make.T0 }, ct); + Assert.AreEqual(run.Id, (await db.Exports.ListRecentRunsAsync(5, ct)).Single().Id); + } + + private static async Task> EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)]; + + private static async Task> FilesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter }, Mode = MosaicMode.Files }, ct)).Tiles.Select(t => t.CoverMediaId!.Value)]; + + private static bool AreSame(IEnumerable expected, IEnumerable actual) => expected.Order().SequenceEqual(actual.Order()); +} diff --git a/tests/Febe.Tests/Export/ExportCopyJobTests.cs b/tests/Febe.Tests/Export/ExportCopyJobTests.cs new file mode 100644 index 0000000..a02db4d --- /dev/null +++ b/tests/Febe.Tests/Export/ExportCopyJobTests.cs @@ -0,0 +1,358 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The copy job of tappa E2 (WP1b) on a real library and real folders: paths, never overwriting, adoption by path, +/// «Tolto» and «Copia di nuovo», pause of a missing destination, engine sessions, leftovers and «Superato». WP5 adds +/// the full set. +/// +[TestClass] +public sealed class ExportCopyJobTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task ACopyGoesUnderTheAccountSegmentAndIsNotWrittenTwice() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "777", Make.T0.AddDays(-1)), [TestFile.Photo(1, 1), TestFile.Photo(2, 2)]); + var usb = await w.GeneralAsync(ct); + + var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + Assert.AreEqual(2, plan.Files); + Assert.AreEqual(usb.Id, plan.Destinations.Single().DestinationId); + Assert.IsNull(plan.Destinations.Single().Problem); + + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!; + Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError); + foreach (var media in post.Media) + { + var copied = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(media.RelativePath!)); + Assert.IsTrue(File.Exists(copied), copied); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(w.Library.Layout.FullPath(w.Marta, media.RelativePath!), ct), await File.ReadAllBytesAsync(copied, ct)); + } + + Assert.IsEmpty(Directory.GetFiles(w.Usb, "*.part", SearchOption.AllDirectories)); + var report = await w.Service.Reports.BuildAsync(run.Id, ct); + Assert.AreEqual(2, report.ByState[ExportItemState.Copied]); + Assert.AreEqual(2, report.Accounts.Single().Copied); + + // Nothing is written twice: the plan says «già copiati», a second job finds them. + var again = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + Assert.AreEqual(0, again.Files); + Assert.AreEqual(2, again.AlreadyCopied); + var second = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(2, (await w.Library.Db.Exports.GetRunSummaryAsync(second.Runs.Single().Id, ct)).ByState[ExportItemState.AlreadyCopied]); + Assert.HasCount(2, Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task ARemovedCopyIsNotCopiedAgainUnlessAsked() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "778", Make.T0.AddDays(-1)), [TestFile.Photo(1, 3)]); + await w.GeneralAsync(ct); + var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)); + await w.Service.StartAsync(request, ct); + await w.Service.WaitAsync(ct); + var copy = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(post.Media[0].RelativePath!)); + File.Delete(copy); // Alberto removed it from the disk + + var skipped = await w.Service.StartAsync(request, ct); + await w.Service.WaitAsync(ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = skipped.Runs.Single().Id }, ct)).Single(); + Assert.AreEqual(ExportItemState.Skipped, item.State); + Assert.AreEqual(ExportText.Notes.Removed, item.Note); + Assert.IsFalse(File.Exists(copy)); + var plan = await w.Service.PlanAsync(request, ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); + + var again = await w.Service.StartAsync(request with { CopyAgain = true }, ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(1, again.Plan.Files); + Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = again.Runs.Single().Id }, ct)).Single().State); + Assert.IsTrue(File.Exists(copy)); + } + + [TestMethod] + public async Task AFileAlreadyThereIsAdoptedAndAnotherFileIsNeverOverwritten() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var first = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "779", Make.T0.AddDays(-1)), [TestFile.Photo(1, 4)]); + var second = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "780", Make.T0.AddDays(-2)), [TestFile.Photo(1, 5)]); + await w.GeneralAsync(ct); + var same = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(first.Media[0].RelativePath!)); + var other = Path.Combine(w.Usb, "marta.demo", LibraryLayout.ToPlatform(second.Media[0].RelativePath!)); + Directory.CreateDirectory(Path.GetDirectoryName(same)!); + Directory.CreateDirectory(Path.GetDirectoryName(other)!); + File.Copy(w.Library.Layout.FullPath(w.Marta, first.Media[0].RelativePath!), same); + await File.WriteAllBytesAsync(other, [1, 2, 3], ct); // something else with that name + + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var items = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = start.Runs.Single().Id }, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.AreEqual(ExportItemState.Adopted, items[first.Media[0].Id].State); + Assert.AreEqual(ExportItemState.Copied, items[second.Media[0].Id].State); + Assert.AreEqual(ExportText.Notes.NameTaken, items[second.Media[0].Id].Note); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(other, ct)); + var renamed = Path.Combine(w.Usb, LibraryLayout.ToPlatform(items[second.Media[0].Id].RelativePath!)); + StringAssert.EndsWith(renamed, " (2).jpg"); + Assert.IsTrue(File.Exists(renamed)); + Assert.AreEqual(ExportCopyOrigin.Adopted, (await w.Library.Db.Exports.GetCopyAsync(items[first.Media[0].Id].CopyId!.Value, ct))!.Origin); + } + + [TestMethod] + public async Task AMissingDestinationPausesAndIsNeverCreated() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "781", Make.T0.AddDays(-1)), [TestFile.Photo(1, 6)]); + var usb = await w.GeneralAsync(ct); + Directory.Delete(w.Usb); // the disk was unplugged + + var plan = await w.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + Assert.IsNotNull(plan.Destinations.Single().Problem); + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!; + Assert.AreEqual(ExportRunState.Paused, run.State); + Assert.IsFalse(Directory.Exists(w.Usb)); + var paused = (await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!; + Assert.IsNotNull(paused.PausedAt); + Assert.Contains("non è raggiungibile", paused.LastError!); + Assert.AreEqual(ExportItemState.Pending, (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single().State); + + // The disk is back: «Riprendi» clears the pause and copies. + Directory.CreateDirectory(w.Usb); + await w.Service.ResumeAsync(null, ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State); + Assert.IsNull((await w.Library.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + } + + [TestMethod] + public async Task CopiesWaitForTheEngineSessionAndForSpace() + { + var ct = TestContext.CancellationToken; + var session = new CountedSession(3); + var disk = new FakeDisk(); + await using var w = await World.CreateAsync(session, disk); + await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "782", Make.T0.AddDays(-1)), [TestFile.Photo(1, 7)]); + await w.GeneralAsync(ct); + var before = w.Library.Clock.Now; + + disk.Free = 1000; // less than the file plus 64 MB + var start = await w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct); + await w.Service.WaitAsync(ct); + var run = (await w.Library.Db.Exports.GetRunAsync(start.Runs.Single().Id, ct))!; + Assert.AreEqual(ExportRunState.Paused, run.State); + Assert.Contains("margine di 64 MB", run.LastError!); + Assert.AreEqual(w.Library.Clock.Now, before + TimeSpan.FromSeconds(15)); // three polls of 5 s while the session ran + + disk.Free = null; + disk.Max = 10; // a FAT32 disk, with a tiny limit for the test + await w.Service.ResumeAsync([run.Id], ct); + await w.Service.WaitAsync(ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single(); + Assert.AreEqual(ExportItemState.Failed, item.State); + Assert.AreEqual(ExportText.Notes.TooLargeForFileSystem, item.Note); + Assert.AreEqual(ExportRunState.Completed, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State); + Assert.AreEqual(ExportCopyState.Failed, (await w.Library.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.State); + } + + [TestMethod] + public async Task LeftoversGoOnlyInTheFoldersOfAnUnfinishedJob() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "783", Make.T0.AddDays(-1)), [TestFile.Photo(1, 8)]); + var usb = await w.GeneralAsync(ct); + var relative = "marta.demo/" + post.Media[0].RelativePath; + var folder = Path.GetDirectoryName(Path.Combine(w.Usb, LibraryLayout.ToPlatform(relative)))!; + Directory.CreateDirectory(folder); + var leftover = Path.Combine(folder, ".febe-0123456789ab.part"); + var elsewhere = Path.Combine(w.Usb, ".febe-ba9876543210.part"); + await File.WriteAllBytesAsync(leftover, [9], ct); + await File.WriteAllBytesAsync(elsewhere, [9], ct); + + // A job interrupted after it recorded the target path. + var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = w.Library.Clock.Now }, ct); + await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single(); + await w.Library.Db.Exports.UpdateItemsAsync([item with { RelativePath = relative }], ct); + + Assert.AreEqual(1, await w.Service.RecoverAsync(ct)); + await w.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Interrupted, (await w.Library.Db.Exports.GetRunAsync(run.Id, ct))!.State); + Assert.IsFalse(File.Exists(leftover)); + Assert.IsTrue(File.Exists(elsewhere)); // the root holds no item: never cleaned + + await w.Service.ResumeAsync(null, ct); + await w.Service.WaitAsync(ct); + Assert.AreEqual(ExportItemState.Copied, (await w.Library.Db.Exports.GetItemAsync(item.Id, ct))!.State); + } + + [TestMethod] + public async Task ASwitchedOffAccountIsSkippedWhenAJobResumes() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "786", Make.T0.AddDays(-1)), [TestFile.Photo(1, 11)]); + var usb = await w.GeneralAsync(ct); + var run = await w.Library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = w.Library.Clock.Now }, ct); + await w.Library.Db.Exports.AddItemsAsync([new ExportItem { RunId = run.Id, MediaId = post.Media[0].Id, AccountId = w.Marta.Id, SourceSha256 = post.Media[0].Sha256 }], ct); + await w.Service.Destinations.SetAccountEnabledAsync(w.Marta.Id, false, ct); + + await w.Service.ResumeAsync([run.Id], ct); + await w.Service.WaitAsync(ct); + var item = (await w.Library.Db.Exports.ListItemsAsync(new() { RunId = run.Id }, ct)).Single(); + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotExported), (item.State, item.Note)); + Assert.IsEmpty(Directory.GetFiles(w.Usb, "*", SearchOption.AllDirectories)); + } + + [TestMethod] + public async Task AChangedLibraryFileSupersedesItsCopies() + { + var ct = TestContext.CancellationToken; + await using var w = await World.CreateAsync(); + var post = await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "784", Make.T0.AddDays(-1)), [TestFile.Photo(1, 9)]); + await w.GeneralAsync(ct); + var request = new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)); + await w.Service.StartAsync(request, ct); + await w.Service.WaitAsync(ct); + + // «Tieni il più grande» put another file in the slot. + var oldSha = post.Media[0].Sha256!; + var newSha = Make.Sha(4242); + await w.Library.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, 10, newSha, null, 1, 1, null, false), MediaState.Downloaded, w.Library.Clock.Now, ct); + Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, newSha, newSha, w.Library.Clock.Now, ct)); + Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(w.Library.Db, w.Marta.Id, oldSha, newSha, w.Library.Clock.Now, ct)); + var copies = await w.Library.Db.Exports.ListCopiesBySha256Async(newSha, ct); + Assert.AreEqual(ExportCopyState.Superseded, copies.Single().State); + Assert.AreEqual(1, (await w.Service.PlanAsync(request, ct)).RemovedOrSuperseded); + } + + [TestMethod] + public async Task AnExportDoesNotStartWhileAnImportHoldsTheGate() + { + var ct = TestContext.CancellationToken; + var gate = new LongWorkGate(); + await using var w = await World.CreateAsync(gate: gate); + await w.Library.SaveAsync(w.Marta, Make.Entry(w.Marta.Id, "785", Make.T0.AddDays(-1)), [TestFile.Photo(1, 10)]); + await w.GeneralAsync(ct); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _)); + var refused = await Assert.ThrowsExactlyAsync(() => w.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(w.Marta.Id)), ct)); + Assert.StartsWith("C'è un'importazione al lavoro", refused.Message); + Assert.IsEmpty(await w.Library.Db.Exports.ListRunsAsync(ct)); + lease.Dispose(); + } + + [TestMethod] + public void PathsFollowTheLibraryTheAccountSegmentAndTheHighlightRule() + { + var naming = LibraryNaming.Default; + var account = Make.Account("marta.demo") with { Id = 1 }; + var general = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = Path.GetTempPath(), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }; + var story = Make.Entry(1, "9001", Make.T0, EntryKind.Story); + var media = Make.Stored(Make.Photo(), Make.Sha(1), "storie/2026/x.jpg"); + + var asStory = ExportPaths.Segments(general, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome); + Assert.AreEqual("marta.demo", asStory[0]); + Assert.AreEqual("storie", asStory[1]); + + var onlyHighlights = general with { Scope = ExportScope.Account, AccountId = 1, ContentTypes = ContentTypes.Highlights }; + var asHighlight = ExportPaths.Segments(onlyHighlights, naming, account, story, media, "Estate", inHighlight: true, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "evidenza", "Estate" }, asHighlight.Take(2).ToArray()); + + var imported = media with { RelativePath = "importati/IMG_0001.JPG" }; + CollectionAssert.AreEqual(new[] { "marta.demo", "importati", "IMG_0001.JPG" }, ExportPaths.Segments(general, naming, account, story, imported, null, false, TestZones.Rome).ToArray()); + var renamed = ExportPaths.Segments(general with { NamingScheme = @"{anno}\{codice}_{n}" }, naming, account, story, imported, null, false, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "marta.demo", "2026", "9001_1.jpg" }, renamed.ToArray()); + + var deep = general with { RootPath = Path.Combine(Path.GetTempPath(), new string('d', 150)) }; + var fitted = ExportPaths.RelativePathFor(deep, ["marta.demo", new string('x', 120) + ".jpg"]); + Assert.IsLessThanOrEqualTo(240, Path.TrimEndingDirectorySeparator(deep.RootPath).Length + 1 + fitted.Length); + StringAssert.EndsWith(fitted, ".jpg"); + } + + private sealed class CountedSession(int polls) : IEngineSessionState + { + private int _left = polls; + + public bool InSession => Interlocked.Decrement(ref _left) >= 0; + } + + private sealed class FakeDisk : IExportDisk + { + public long? Free { get; set; } + + public long? Max { get; set; } + + public long? FreeBytes(string root) => Free; + + public long? MaxFileBytes(string root) => Max; + } + + private sealed class World : IAsyncDisposable + { + private readonly TempFolder _temp; + + private World(TempFolder temp, TestLibrary library, ExportService service, Account marta) + { + _temp = temp; + Library = library; + Service = service; + Marta = marta; + Usb = temp.Combine("usb"); + Directory.CreateDirectory(Usb); + } + + public TestLibrary Library { get; } + + public ExportService Service { get; } + + public Account Marta { get; } + + public string Usb { get; } + + public static async Task CreateAsync(IEngineSessionState? session = null, IExportDisk? disk = null, LongWorkGate? gate = null) + { + var temp = new TempFolder(); + var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var env = new ExportEnvironment + { + Storage = library.Db, + Layout = () => library.Layout, + DataFolder = library.Data.Root, + Clock = library.Clock, + Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) }, + Disk = disk ?? new FakeDisk(), + Session = session ?? NoEngineSession.Instance, + Gate = gate, + }; + return new World(temp, library, new ExportService(env), marta); + } + + public async Task GeneralAsync(CancellationToken ct) => + (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, Usb, "Disco USB", ContentTypes.All, null, null, null), ct)).Destination; + + public async ValueTask DisposeAsync() + { + await Service.DisposeAsync(); + await Library.DisposeAsync(); + _temp.Dispose(); + } + } +} diff --git a/tests/Febe.Tests/Export/ExportDestinationsTests.cs b/tests/Febe.Tests/Export/ExportDestinationsTests.cs new file mode 100644 index 0000000..8e6583a --- /dev/null +++ b/tests/Febe.Tests/Export/ExportDestinationsTests.cs @@ -0,0 +1,281 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// Destinations and «Esporta questo account» (spec §4.10 «Destinazioni»; decisions D1, D2, D8 and WP1.10 of tappa E2). +/// +[TestClass] +public sealed class ExportDestinationsTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheAccountSwitchIsOnWhenNothingIsRecorded() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + Assert.IsTrue(ExportAccounts.IsEnabled(null)); + Assert.IsNull(await bed.Db.Exports.GetAccountExportEnabledAsync(bed.Marta.Id, ct)); + Assert.IsEmpty(await bed.Db.Exports.ListAccountExportSwitchesAsync(ct)); + + var before = await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct); + Assert.IsTrue(before.Enabled); + Assert.IsFalse(before.Exports); // no folder yet + await bed.GeneralAsync(ct: ct); + var all = await bed.Service.Destinations.ResolveAllAsync(ct); + Assert.IsTrue(all[bed.Marta.Id].Exports && all[bed.Luca.Id].Exports); + Assert.IsTrue(all[bed.Marta.Id].Wants(ContentTypes.Stories)); + Assert.IsEmpty(await bed.Db.Exports.ListAccountExportSwitchesAsync(ct)); // reading never writes a row + } + + [TestMethod] + public async Task TheSwitchOffIsRemembered() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await bed.GeneralAsync(ct: ct); + await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct); + + var again = new ExportDestinations(bed.Environment); // another service reads the database, not a cache + var marta = await again.ResolveAsync(bed.Marta.Id, ct); + Assert.IsFalse(marta.Enabled); + Assert.IsTrue(marta.HasDestination); + Assert.IsFalse(marta.Exports); + Assert.IsFalse(marta.Wants(ContentTypes.PostPhotos)); + Assert.IsTrue((await again.ResolveAllAsync(ct))[bed.Luca.Id].Exports); + Assert.IsFalse((await bed.Db.Exports.ListAccountExportSwitchesAsync(ct))[bed.Marta.Id]); + + await again.SetAccountEnabledAsync(bed.Marta.Id, true, ct); + Assert.IsTrue(await bed.Db.Exports.GetAccountExportEnabledAsync(bed.Marta.Id, ct)); // a row with «on» now + Assert.IsTrue((await again.ResolveAsync(bed.Marta.Id, ct)).Exports); + await Assert.ThrowsExactlyAsync(() => again.SetAccountEnabledAsync(9999, false, ct)); + } + + [TestMethod] + public async Task TheOwnFolderReplacesTheGeneralOne() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var general = await bed.GeneralAsync(ct: ct); + var own = await bed.OwnAsync(bed.Marta, "marta", ContentTypes.PostPhotos, ct); + + var all = await bed.Service.Destinations.ResolveAllAsync(ct); + Assert.AreEqual(own.Id, all[bed.Marta.Id].Destination!.Id); + Assert.IsTrue(all[bed.Marta.Id].IsOwn); + Assert.IsFalse(all[bed.Marta.Id].Wants(ContentTypes.Stories)); // the own folder's types, not the general ones + Assert.AreEqual(general.Id, all[bed.Luca.Id].Destination!.Id); + Assert.IsFalse(all[bed.Luca.Id].IsOwn); + Assert.AreEqual(own.Id, (await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).Destination!.Id); + Assert.AreEqual("marta", ExportDestinations.Label(own)); + + var second = await Assert.ThrowsExactlyAsync(() => bed.GeneralAsync(folder: bed.Temp.Combine("marta"), ct: ct)); + StringAssert.StartsWith(second.Message, "C'è già una cartella generale"); + Directory.CreateDirectory(bed.Temp.Combine("marta2")); + var twice = await Assert.ThrowsExactlyAsync(() => bed.OwnAsync(bed.Marta, "marta2", ct: ct)); + StringAssert.StartsWith(twice.Message, "@marta.demo ha già una cartella sua"); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync( + new DestinationSpec(ExportScope.Account, null, bed.Temp.Combine("marta2"), null, ContentTypes.All, null, null, null), ct)); + + // «Usa la cartella generale»: the own folder goes, the general one is back. + await bed.Service.Destinations.RetireAsync(own.Id, ct); + Assert.AreEqual(general.Id, (await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).Destination!.Id); + } + + [TestMethod] + public async Task RetiringKeepsTheCopiesAndTheFiles() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "910", 1, 2); + var usb = await bed.GeneralAsync(ct: ct); + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); + Assert.HasCount(2, copies); + var files = Fingerprint.Of(bed.Usb); + Assert.HasCount(2, files); + + await bed.Service.Destinations.RetireAsync(usb.Id, ct); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the files stay"); + var retired = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!; + Assert.IsTrue(retired.IsRetired); + foreach (var copy in copies) + { + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!.State); + } + + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs.Single().Id, ct)).State); + Assert.IsFalse((await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).HasDestination); + var status = await bed.Service.Destinations.StatusAsync(usb.Id, ct); + Assert.AreEqual((false, "Questa cartella è stata tolta."), (status.Reachable, status.Problem)); + Assert.AreEqual(2, status.Counts[ExportCopyState.Copied]); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync( + usb.Id, new DestinationSpec(ExportScope.General, null, bed.Usb, "Altro", ContentTypes.All, null, null, null), ct)); + await bed.Service.Destinations.RetireAsync(usb.Id, ct); // twice: nothing happens + + // Nothing is due any more: the plan says the files are not exported. + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([post.Entry.Id])), ct); + Assert.AreEqual((0, 2), (plan.Files, plan.NotExported)); + + // A new general folder on the same disk starts from nothing: the files there are adopted, never written twice. + var back = await bed.GeneralAsync(ct: ct); + var again = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.IsTrue((await bed.ItemsAsync(again.Runs.Single().Id, ct)).All(i => i.State == ExportItemState.Adopted)); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "adopted, not written"); + Assert.AreNotEqual(usb.Id, back.Id); + } + + [TestMethod] + public async Task ChangingTheFolderRetiresAndAddsAndIsRefusedWithAnUnfinishedRun() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var usb = await bed.GeneralAsync(ct: ct); + var nas = bed.Temp.Combine("nas"); + Directory.CreateDirectory(nas); + DestinationSpec Spec(string path, string? label = null) => new(ExportScope.General, null, path, label, ContentTypes.PostPhotos | ContentTypes.Stories, null, null, null); + + // The same folder: the row changes in place. + var renamed = await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed.Usb + Path.DirectorySeparatorChar, " Disco nero "), ct); + Assert.AreEqual(usb.Id, renamed.Destination.Id); + Assert.AreEqual("Disco nero", (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.Label); + Assert.AreEqual(ContentTypes.PostPhotos | ContentTypes.Stories, (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.ContentTypes); + + // Another folder, while a job writes to the old one: refused, nothing changes. + var run = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct); + var refused = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(usb.Id, Spec(nas), ct)); + Assert.AreEqual(ExportDestinations.UnfinishedRunText, refused.Message); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.RetireAsync(usb.Id, ct)); + Assert.IsFalse((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.IsRetired); + Assert.AreEqual(usb.Id, (await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(bed.Usb, "Solo il nome"), ct)).Destination.Id); // the label still changes + + // The job is gone: the old row is retired, a new one is added. + await bed.Service.DiscardAsync(run.Id, ct); + var moved = await bed.Service.Destinations.UpdateAsync(usb.Id, Spec(nas), ct); + Assert.AreNotEqual(usb.Id, moved.Destination.Id); + Assert.AreEqual(Path.GetFullPath(nas), moved.Destination.RootPath); + Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.IsRetired); + Assert.AreEqual(moved.Destination.Id, (await bed.Service.Destinations.ResolveAsync(bed.Marta.Id, ct)).Destination!.Id); + Assert.HasCount(1, await bed.Db.Exports.ListDestinationsAsync(includeRetired: false, ct)); + + // A folder that cannot be a destination leaves the destination as it was. + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(moved.Destination.Id, Spec(bed.Temp.Combine("assente")), ct)); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync( + moved.Destination.Id, new DestinationSpec(ExportScope.Account, bed.Marta.Id, nas, null, ContentTypes.All, null, null, null), ct)); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync(9999, Spec(nas), ct)); + Assert.IsFalse((await bed.Db.Exports.GetDestinationAsync(moved.Destination.Id, ct))!.IsRetired); + } + + [TestMethod] + public async Task SchemesAreValidatedLikeTheLibraryOnes() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + DestinationSpec Spec(string? general, string? highlight = null, string? profile = null) => + new(ExportScope.General, null, bed.Usb, null, ContentTypes.All, general, highlight, profile); + + var unknown = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(@"{anno}\{inventato}"), ct)); + StringAssert.StartsWith(unknown.Message, "Schema: Segnaposto sconosciuto: {inventato}."); + var collection = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(@"{anno}\{raccolta}\{codice}_{n}"), ct)); + StringAssert.StartsWith(collection.Message, "Schema: {raccolta} si usa solo nello schema per le raccolte in evidenza."); + var profile = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(null, null, @"{raccolta}\{codice}"), ct)); + StringAssert.StartsWith(profile.Message, "Schema per le foto del profilo: {raccolta} si usa solo"); + var brace = await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.CreateAsync(Spec(null, @"{raccolta\{codice}"), ct)); + StringAssert.StartsWith(brace.Message, "Schema per le raccolte in evidenza: "); + Assert.IsEmpty(await bed.Db.Exports.ListDestinationsAsync(includeRetired: true, ct)); + + // Warnings do not block, and come back with their prefix; blank schemes are «Come la libreria». + var saved = await bed.Service.Destinations.CreateAsync(Spec(@"{anno}\{codice}", @"{account}\{data}_{codice}_{n}", " "), ct); + CollectionAssert.Contains(saved.Warnings.ToList(), "Schema: Senza {n} i file di un post con più foto o video hanno lo stesso nome: Febe aggiunge un numero per distinguerli."); + CollectionAssert.Contains(saved.Warnings.ToList(), "Schema per le raccolte in evidenza: Senza {raccolta} i contenuti delle diverse raccolte finiscono nella stessa cartella."); + var stored = (await bed.Db.Exports.GetDestinationAsync(saved.Destination.Id, ct))!; + Assert.AreEqual(@"{anno}\{codice}", stored.NamingScheme); + Assert.IsNull(stored.ProfileNamingScheme); + } + + [TestMethod] + public async Task NoTypeIsRefused() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + foreach (var types in new[] { ContentTypes.None, (ContentTypes)64, ContentTypes.Stories | (ContentTypes)128 }) + { + var refused = await Assert.ThrowsExactlyAsync(() => bed.GeneralAsync(types, ct: ct), types.ToString()); + StringAssert.StartsWith(refused.Message, "Scegli almeno un tipo di contenuto."); + } + + var usb = await bed.GeneralAsync(ContentTypes.Tagged, ct: ct); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.UpdateAsync( + usb.Id, new DestinationSpec(ExportScope.General, null, bed.Usb, null, ContentTypes.None, null, null, null), ct)); + Assert.AreEqual(ContentTypes.Tagged, (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.ContentTypes); + } + + [TestMethod] + public async Task AutomaticIsStoredButNothingIsQueued() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await bed.PostAsync(bed.Marta, "920", 1); + var spec = new DestinationSpec(ExportScope.General, null, bed.Usb, null, ContentTypes.All, null, null, null, Automatic: true, OnlyNew: true); + var saved = (await bed.Service.Destinations.CreateAsync(spec, ct)).Destination; + var stored = (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!; + Assert.IsTrue(stored.Automatic); + Assert.AreEqual(Make.T0, stored.AutomaticSince); + + // Tappa E2 does not act on it: no job, nothing written, nothing running. + Assert.IsFalse(bed.Service.IsBusy); + Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); + Assert.IsEmpty(Directory.GetFileSystemEntries(bed.Usb)); + + // Still on: «da quando» is kept; off: it goes; on with «tutti»: no date. + bed.Clock.Now = Make.T0.AddDays(3); + await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Label = "Disco" }, ct); + Assert.AreEqual(Make.T0, (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!.AutomaticSince); + await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Automatic = false }, ct); + Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(saved.Id, ct)) is { Automatic: false, AutomaticSince: null }); + await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { OnlyNew = false }, ct); + Assert.IsTrue((await bed.Db.Exports.GetDestinationAsync(saved.Id, ct)) is { Automatic: true, AutomaticSince: null }); + await bed.Service.Destinations.UpdateAsync(saved.Id, spec with { Automatic = false }, ct); + await bed.Service.Destinations.UpdateAsync(saved.Id, spec, ct); + Assert.AreEqual(Make.T0.AddDays(3), (await bed.Db.Exports.GetDestinationAsync(saved.Id, ct))!.AutomaticSince); + Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct)); + } + + [TestMethod] + public async Task AnAccountFolderInsideADestinationIsRefusedOnRecheck() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var usb = await bed.GeneralAsync(ct: ct); + var own = await bed.OwnAsync(bed.Marta, "marta", ct: ct); + Assert.IsEmpty(await bed.Service.Destinations.RecheckAsync(null, ct)); + + // The folder Alberto is about to give luca.demo sits inside the general folder. + var planned = Path.Combine(bed.Usb, "luca"); + var conflicts = await bed.Service.Destinations.RecheckAsync([planned], ct); + var conflict = conflicts.Single(); + Assert.AreEqual(usb.Id, conflict.Destination.Id); + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, conflict.Problem.Kind); + Assert.AreEqual($"{Path.GetFullPath(bed.Usb)} contiene la cartella di un account: scegli una cartella che non la contenga.", conflict.Problem.Message); + Assert.IsFalse(Directory.Exists(planned)); // checked as text: the folder is not created + + // A new library root that would hold marta's own folder. + var root = await bed.Service.Destinations.RecheckAgainstAsync([new(bed.Temp.Path, ProtectedFolderKind.Library, null)], ct); + CollectionAssert.AreEquivalent(new[] { usb.Id, own.Id }, root.Select(c => c.Destination.Id).ToArray()); + Assert.IsTrue(root.All(c => c.Problem.Kind == ExportFolderProblemKind.InsideProtected)); + + // After a rebuild the account folder really is there: the destination pauses, nothing is interactive. + Directory.CreateDirectory(planned); + await bed.Db.Accounts.UpdateAsync(bed.Luca with { Folder = planned }, ct); + var paused = await bed.Service.Destinations.RecheckAndPauseAsync(ct); + Assert.AreEqual(usb.Id, paused.Single().Destination.Id); + var row = (await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!; + Assert.IsNotNull(row.PausedAt); + StringAssert.Contains(row.LastError, "contiene la cartella dell'account @luca.demo"); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(own.Id, ct))!.PausedAt); + Assert.IsFalse(row.IsRetired); + } +} diff --git a/tests/Febe.Tests/Export/ExportFilterTests.cs b/tests/Febe.Tests/Export/ExportFilterTests.cs new file mode 100644 index 0000000..5df6c91 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFilterTests.cs @@ -0,0 +1,165 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The rules of the «Copie» filter that does not reach (decision D3 of tappa E2): +/// a file is judged in the effective destination of its account only, «Tolti o superati» takes both states, a content +/// type the destination does not take is not due, retired destinations do not count, and «Una copia sola» counts the +/// copies of the other accounts. Marks, account counts, totals and days follow the same rules. +/// +[TestClass] +public sealed class ExportFilterTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task RemovedOrSupersededFindsBothStates() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + await db.Exports.RetireDestinationAsync(w.Own, Make.T0, ct); // marta.demo goes to the general folder too + // Her file was replaced in the library (Sha(1) → Sha(5)) after its copy. + await db.Media.MarkStoredAsync(w.MartaMedia, new StoredFile("post/a.jpg", 2000, Make.Sha(5), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct); + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg") with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(5) }, ct); + await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia) with { State = ExportCopyState.Removed }, ct); + + CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct)); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct), "a «tolto» or «superato» file is not «non ancora copiato»"); + Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct)); + + // A newer Copied row for the same file wins over the old state. + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a (2).jpg") with { SourceSha256 = Make.Sha(5), CopySha256 = Make.Sha(5) }, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + CollectionAssert.AreEquivalent(new[] { w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.RemovedOrSuperseded, ct)); + Assert.AreEqual(ExportMark.Copied, (await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct))[w.MartaEntry]); + } + + [TestMethod] + public async Task TheFilterFollowsTheEffectiveDestinationOfEachAccount() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + + // marta.demo has her own folder: a copy in the general folder does not make her file «copiato». + await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"), ct); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + Assert.AreEqual(ExportMark.None, (await db.Exports.GetEntryMarksAsync([w.MartaEntry], ct))[w.MartaEntry]); + + // Her own folder is retired: the general folder is hers again, with the copy already there. + await db.Exports.RetireDestinationAsync(w.Own, Make.T0, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + + // The general folder is retired as well: nothing is due, so nothing is in any of the three. + await db.Exports.RetireDestinationAsync(w.General, Make.T0, ct); + foreach (var filter in Enum.GetValues()) + { + Assert.IsEmpty(await EntriesAsync(db, filter, ct), filter.ToString()); + } + + Assert.AreEqual(new ExportAccountCounts(0, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + Assert.IsEmpty(await db.Exports.GetEntryMarksAsync([w.MartaEntry, w.LucaEntry], ct)); + Assert.AreEqual(new LibraryTotals(0, 0), await db.Entries.GetLibraryTotalsAsync(new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied }, ct)); + } + + [TestMethod] + public async Task ExcludedTypesAndSwitchedOffAccountsAreNotDue() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + var general = (await db.Exports.GetDestinationAsync(w.General, ct))!; + await db.Exports.UpdateDestinationAsync(general with { ContentTypes = ContentTypes.All & ~ContentTypes.Tagged }, ct); + // A story of luca.demo in a highlight: due for «Evidenza» even without «Storie». + var story = await db.Entries.AddAsync(Make.Entry(w.Luca, "556", Make.T0, EntryKind.Story), [Make.Stored(Make.Photo(), Make.Sha(4), "storie/s.jpg")], ct); + var highlight = await db.Highlights.UpsertAsync(new Highlight { AccountId = w.Luca, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 }, ct); + await db.Highlights.AddItemAsync(highlight.Id, story.Stored.Entry.Id, ct); + + // luca.demo's tagged post is not due in a folder without «Taggati». + CollectionAssert.AreEquivalent(new[] { w.MartaEntry, story.Stored.Entry.Id }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + Assert.AreEqual(new ExportAccountCounts(1, 1, 0, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct)); + Assert.IsFalse((await db.Exports.GetEntryMarksAsync([w.LucaEntry], ct)).ContainsKey(w.LucaEntry)); + + await db.Exports.UpdateDestinationAsync(general with { ContentTypes = ContentTypes.Highlights }, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry, story.Stored.Entry.Id }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + await db.Exports.UpdateDestinationAsync(general with { ContentTypes = ContentTypes.PostPhotos }, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + + // Switched off, an account has no due file even in its own folder. + await db.Exports.SetAccountExportEnabledAsync(w.Marta, false, ct); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + await db.Exports.SetAccountExportEnabledAsync(w.Marta, true, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + } + + [TestMethod] + public async Task OneCopyOnlyCountsCopiesOfOtherAccounts() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + await db.Exports.AddCopyAsync(w.WholeCopy("a.jpg", destination: w.Own), ct); // marta.demo's, in her own folder + + CollectionAssert.AreEquivalent(new[] { w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + await (ExportSettings.Default with { SamePost = SamePostCopies.OneOnly }).SaveAsync(db.Settings, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.Copied, ct)); + Assert.IsEmpty(await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await db.Exports.CountAccountFilesAsync(w.Luca, ct)); + Assert.AreEqual(ExportMark.Copied, (await db.Exports.GetFileMarksAsync([w.LucaMedia], ct))[w.LucaMedia]); + + // Only a copy in a destination in use counts. + await db.Exports.RetireDestinationAsync(w.Own, Make.T0, ct); + CollectionAssert.AreEquivalent(new[] { w.MartaEntry, w.LucaEntry }, await EntriesAsync(db, LibraryCopiesFilter.NotCopied, ct)); + } + + [TestMethod] + public async Task FilesModeTotalsAndDaysObeyTheFilter() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await ExportWorld.CreateAsync(db); + var other = await db.Entries.AddAsync( + Make.Entry(w.Marta, "557", Make.T0.AddDays(3)), + [Make.Stored(Make.Photo(1), Make.Sha(6), "post/c1.jpg"), Make.Stored(Make.Photo(2), Make.Sha(7), "post/c2.jpg"), Make.Stored(Make.Photo(3), Make.Sha(8), "post/c3.jpg")], + ct); + await db.Exports.AddCopyAsync(w.WholeCopy("c2.jpg", destination: w.Own, media: other.Stored.Media[1].Id) with { SourceSha256 = Make.Sha(7), CopySha256 = Make.Sha(7) }, ct); + + var notCopied = new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied, AccountIds = [w.Marta] }; + var copied = notCopied with { Copies = LibraryCopiesFilter.Copied }; + Assert.AreEqual(new LibraryTotals(2, 1), await db.Entries.GetLibraryTotalsAsync(notCopied, ct)); // a partly copied entry is «non ancora copiato» + Assert.AreEqual(new LibraryTotals(0, 0), await db.Entries.GetLibraryTotalsAsync(copied, ct)); + Assert.AreEqual(3, (await db.Entries.CountLibraryByDayAsync(notCopied, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + Assert.AreEqual(1, (await db.Entries.CountLibraryByDayAsync(copied, TestZones.Rome, MosaicMode.Files, ct)).Sum(d => d.Count)); + var days = await db.Entries.CountLibraryByDayAsync(notCopied, TestZones.Rome, ct: ct); + Assert.HasCount(2, days); + Assert.AreEqual(ExportMark.Partly, (await db.Exports.GetEntryMarksAsync([other.Stored.Entry.Id], ct))[other.Stored.Entry.Id]); + Assert.AreEqual(new ExportAccountCounts(4, 3, 0, 0), await db.Exports.CountAccountFilesAsync(w.Marta, ct)); + + // The «Copia i file in…» selection of the filter takes exactly the files the mosaic shows. + var selection = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(notCopied, MosaicMode.Files), 0, 100, ct); + CollectionAssert.AreEquivalent( + new[] { w.MartaMedia, other.Stored.Media[0].Id, other.Stored.Media[2].Id }, + selection.Select(c => c.MediaId).ToArray()); + var byEntries = await db.Exports.ListCandidatesAsync(new ExportSelection.Filter(notCopied, MosaicMode.Grouped), 0, 100, ct); + Assert.HasCount(4, byEntries); + } + + private static async Task EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)]; +} diff --git a/tests/Febe.Tests/Export/ExportFolderCheckTests.cs b/tests/Febe.Tests/Export/ExportFolderCheckTests.cs new file mode 100644 index 0000000..73ea840 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFolderCheckTests.cs @@ -0,0 +1,349 @@ +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// «Cartelle rifiutate» of spec §4.10 (decision D13 of tappa E2): textual checks, then the identity test with a probe +/// written only in the candidate. Failures of the disk are injected through the probe seam, never provoked with +/// permissions (the CI runs as root, which writes anywhere). +/// +[TestClass] +public sealed class ExportFolderCheckTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task AMissingFolderIsRefusedAndNeverCreated() + { + using var temp = new TempFolder(); + var missing = temp.Combine("disco", "Febe"); + var verdict = await Check().CheckAsync(missing, Context(temp), TestContext.CancellationToken); + Assert.AreEqual(ExportFolderProblemKind.Missing, verdict.Problem!.Kind); + Assert.StartsWith($"La cartella {Path.GetFullPath(missing)} non esiste. Febe non crea mai la cartella di una destinazione", verdict.Problem.Message); + Assert.IsFalse(Directory.Exists(temp.Combine("disco"))); + Assert.IsFalse(verdict.Accepted); + } + + [TestMethod] + public async Task AFileIsNotAFolder() + { + using var temp = new TempFolder(); + var file = temp.Combine("copie.txt"); + await File.WriteAllTextAsync(file, "testo", TestContext.CancellationToken); + var verdict = await Check().CheckAsync(file, Context(temp), TestContext.CancellationToken); + Assert.AreEqual(ExportFolderProblemKind.NotAFolder, verdict.Problem!.Kind); + Assert.AreEqual($"{Path.GetFullPath(file)} è un file: scegli una cartella.", verdict.Problem.Message); + Assert.AreEqual("testo", await File.ReadAllTextAsync(file, TestContext.CancellationToken)); + } + + [TestMethod] + public async Task TheRootOfADiskIsRefused() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var context = Context(temp); + + // Windows: «C:\», textually; Linux: «/». + var root = Path.GetPathRoot(temp.Path)!; + var verdict = await Check().CheckAsync(root, context, ct); + Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, verdict.Problem!.Kind, verdict.Problem.Message); + StringAssert.Contains(verdict.Problem.Message, "è la radice di un disco o di una condivisione"); + + // Linux: a mount point that shows the root of its file system (a USB disk mounted there) is a root too; one that + // shows a folder of its file system is not (Windows decides from the path alone). + var usb = temp.Combine("usb"); + var nas = temp.Combine("nas"); + Directory.CreateDirectory(usb); + Directory.CreateDirectory(nas); + var mounts = new FixedMounts(ExportRootTests.Mount(usb, "/"), ExportRootTests.Mount(nas, "/condivisa/foto")); + var onMount = await new ExportFolderCheck(mounts).CheckAsync(usb, context, ct); + if (OperatingSystem.IsWindows()) + { + Assert.IsTrue(onMount.Accepted, onMount.Problem?.Message); + } + else + { + Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, onMount.Problem!.Kind); + } + + Assert.IsTrue((await new ExportFolderCheck(mounts).CheckAsync(nas, context, ct)).Accepted); + Directory.CreateDirectory(Path.Combine(usb, "Febe")); + Assert.IsTrue((await new ExportFolderCheck(mounts).CheckAsync(Path.Combine(usb, "Febe"), context, ct)).Accepted); + } + + [TestMethod] + [DataRow(ProtectedFolderKind.Data, "la cartella dei dati di Febe")] + [DataRow(ProtectedFolderKind.Library, "la cartella della libreria")] + [DataRow(ProtectedFolderKind.Account, "la cartella dell'account @marta.demo")] + [DataRow(ProtectedFolderKind.Import, "la cartella delle importazioni")] + public async Task FoldersInsideOrContainingDataLibraryAccountsOrImportAreRefused(ProtectedFolderKind kind, string description) + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var guarded = temp.Combine("dentro", "protetta"); + var inside = Path.Combine(guarded, "sotto"); + var outside = temp.Combine("fuori"); + Directory.CreateDirectory(inside); + Directory.CreateDirectory(outside); + var context = new ExportFolderContext([new(Path.GetFullPath(guarded), kind, kind == ProtectedFolderKind.Account ? "marta.demo" : null)], ExportRootOptions.AnyFolder); + var check = Check(); + + var same = (await check.CheckAsync(guarded, context, ct)).Problem!; + Assert.AreEqual((ExportFolderProblemKind.SameAsProtected, $"{Path.GetFullPath(guarded)} è {description}: scegli un'altra cartella."), (same.Kind, same.Message)); + var within = (await check.CheckAsync(inside, context, ct)).Problem!; + Assert.AreEqual((ExportFolderProblemKind.InsideProtected, $"{Path.GetFullPath(inside)} è dentro {description}: scegli una cartella fuori."), (within.Kind, within.Message)); + var containing = (await check.CheckAsync(temp.Combine("dentro"), context, ct)).Problem!; + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, containing.Kind); + Assert.AreEqual($"{Path.GetFullPath(temp.Combine("dentro"))} contiene {description}: scegli una cartella che non la contenga.", containing.Message); + Assert.IsTrue(same.IsOverlap && within.IsOverlap && containing.IsOverlap); + + Assert.IsTrue((await check.CheckAsync(outside, context, ct)).Accepted); + Assert.IsEmpty(Fingerprint.Temporaries(temp.Path)); + } + + [TestMethod] + public async Task AnAccountFolderOutsideTheLibraryCountsToo() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var elsewhere = bed.Temp.Combine("archivio", "luca"); + Directory.CreateDirectory(Path.Combine(elsewhere, "post")); + await bed.Db.Accounts.UpdateAsync(bed.Luca with { Folder = elsewhere }, ct); + var import = bed.Temp.Combine("importa"); + Directory.CreateDirectory(import); + + var context = await ExportFolderCheck.ContextAsync(bed.Db, bed.Library.Layout, bed.Library.Data.Root, import, ExportRootOptions.AnyFolder, null, ct); + var kinds = context.Protected.Select(p => (p.Kind, p.Username)).ToList(); + CollectionAssert.Contains(kinds, (ProtectedFolderKind.Data, (string?)null)); + CollectionAssert.Contains(kinds, (ProtectedFolderKind.Library, (string?)null)); + CollectionAssert.Contains(kinds, (ProtectedFolderKind.Import, (string?)null)); + Assert.AreEqual(Path.GetFullPath(elsewhere), context.Protected.Single(p => p.Username == "luca.demo").Path); + + var check = Check(); + var verdict = await check.CheckAsync(Path.Combine(elsewhere, "post"), context, ct); + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, verdict.Problem!.Kind); + StringAssert.Contains(verdict.Problem.Message, "la cartella dell'account @luca.demo"); + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(bed.Temp.Combine("archivio"), context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(import, context, ct)).Problem!.Kind); + + // A folder about to be saved for an account (WP1.10) is protected before it is stored. + var future = bed.Temp.Combine("nuova"); + Directory.CreateDirectory(future); + var extra = await ExportFolderCheck.ContextAsync(bed.Db, bed.Library.Layout, bed.Library.Data.Root, null, ExportRootOptions.AnyFolder, [new(future, ProtectedFolderKind.Account, null)], ct); + Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(future, extra, ct)).Problem!.Kind); + Assert.IsTrue((await check.CheckAsync(future, context, ct)).Accepted); + } + + [TestMethod] + public async Task AnAliasIsRecognisedByTheProbeFile() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var library = temp.Combine("libreria"); + Directory.CreateDirectory(Path.Combine(library, "marta.demo")); + + // A second path to the same folder that no text comparison sees: a symbolic link on Linux; on Windows the + // «\\?\» form of the path (a link needs rights a test does not have there). + string Alias(string target, string name) + { + if (OperatingSystem.IsWindows()) + { + return @"\\?\" + Path.GetFullPath(target); + } + + var link = temp.Combine(name); + Directory.CreateSymbolicLink(link, target); + return link; + } + + var check = Check(); + var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder); + + // The candidate is the library under another name, or a folder of it. + var same = Alias(library, "alias-libreria"); + Assert.IsFalse(ExportPaths.IsSameOrInside(same, library) || ExportPaths.IsSameOrInside(library, same), "the text must not tell"); + Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(same, guarded, ct)).Problem!.Kind); + var inside = Alias(Path.Combine(library, "marta.demo"), "alias-account"); + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(inside, guarded, ct)).Problem!.Kind); + + // The other direction: the protected folder is known by its other name, the candidate by the real one. + var aliased = new ExportFolderContext([new(Alias(library, "alias-protetta"), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder); + Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(library, aliased, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), aliased, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, aliased, ct)).Problem!.Kind); + + Assert.IsEmpty(Fingerprint.Temporaries(temp.Path)); + } + + [TestMethod] + public async Task ALinkToAFolderInsideTheLibraryIsRecognised() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var library = temp.Combine("libreria"); + var inner = Path.Combine(library, "copie", "usb"); + Directory.CreateDirectory(inner); + + // Not an account folder: a plain folder deep in the library, reached by a link (a junction or a symbolic link + // where the test may make one, else the «\\?\» form of its path on Windows). + var alias = temp.Combine("alias-copie"); + try + { + Directory.CreateSymbolicLink(alias, inner); + } + catch (Exception ex) when (OperatingSystem.IsWindows() && ex is IOException or UnauthorizedAccessException) + { + alias = @"\\?\" + Path.GetFullPath(inner); + } + + Assert.IsFalse(ExportPaths.IsSameOrInside(alias, library), "the text must not tell"); + var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder); + var verdict = await Check().CheckAsync(alias, guarded, ct); + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, verdict.Problem!.Kind); + StringAssert.Contains(verdict.Problem.Message, "è dentro la cartella della libreria"); + Assert.IsEmpty(Fingerprint.Temporaries(temp.Path)); + } + + [TestMethod] + public async Task ABindMountOfAFolderOfTheLibraryIsRecognised() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + + // Docker on Unraid: -v /mnt/user/Febe:/libreria and -v /mnt/user/Febe/copie:/esporta/usb. Two folders that no + // path and no probe relate, on the same device, the second showing a folder inside the first. + var library = temp.Combine("libreria"); + var usb = temp.Combine("esporta", "usb"); + var nas = temp.Combine("esporta", "nas"); + var other = temp.Combine("esporta", "altro"); + foreach (var folder in new[] { library, usb, nas, Path.Combine(nas, "Febe", "lib"), other }) + { + Directory.CreateDirectory(folder); + } + + string Real(string path) => FolderIdentity.RealPath(path)!; + var mounts = new FixedMounts( + new ExportMount(Real(library), "/Febe", "fuse.shfs", false, "0:51"), + new ExportMount(Real(usb), "/Febe/copie", "fuse.shfs", false, "0:51"), + new ExportMount(Real(nas), "/condivisa", "cifs", false, "0:60"), + new ExportMount(Real(Path.Combine(nas, "Febe", "lib")), "/Febe", "fuse.shfs", false, "0:51"), // the library again, below the NAS + new ExportMount(Real(other), "/Altro", "fuse.shfs", false, "0:51")); + var check = new ExportFolderCheck(mounts); + var guarded = new ExportFolderContext([new(Path.GetFullPath(library), ProtectedFolderKind.Library, null)], ExportRootOptions.AnyFolder with { Mounts = mounts }); + + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(usb, guarded, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(nas, guarded, ct)).Problem!.Kind, "a mount below the candidate shows the library"); + Assert.IsTrue((await check.CheckAsync(other, guarded, ct)).Accepted, "another folder of the same device is not the library"); + Assert.IsEmpty(Fingerprint.Temporaries(temp.Path)); + } + + [TestMethod] + public async Task TheProbeIsWrittenOnlyInTheCandidate() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + await bed.PostAsync(bed.Marta, "901", 1); + var import = bed.Temp.Combine("importa"); + Directory.CreateDirectory(import); + await File.WriteAllTextAsync(Path.Combine(import, "IMG_0001.JPG"), "foto", ct); + var before = (Data: Fingerprint.Of(bed.Library.Data.Root, DatabaseName(bed)), Library: Fingerprint.Of(bed.Library.Layout.Root), Import: Fingerprint.Of(import)); + Assert.IsNotEmpty(before.Library); + + var probes = new List(); + var check = new ExportFolderCheck(new FixedMounts(), writeProbe: path => + { + probes.Add(path); + File.WriteAllText(path, "Febe"); + }); + var context = await ExportFolderCheck.ContextAsync(bed.Db, bed.Library.Layout, bed.Library.Data.Root, import, ExportRootOptions.AnyFolder, null, ct); + Assert.IsTrue((await check.CheckAsync(bed.Usb, context, ct)).Accepted); + + var probe = probes.Single(); + Assert.AreEqual(Path.GetFullPath(bed.Usb), Path.GetDirectoryName(probe)); + StringAssert.Matches(Path.GetFileName(probe), new System.Text.RegularExpressions.Regex(@"^\.febe-prova-[0-9a-f]{12}\.part$")); + Assert.IsFalse(File.Exists(probe)); + Assert.IsEmpty(Directory.GetFileSystemEntries(bed.Usb)); + Fingerprint.AreEqual(before.Data, Fingerprint.Of(bed.Library.Data.Root, DatabaseName(bed)), "Dati"); + Fingerprint.AreEqual(before.Library, Fingerprint.Of(bed.Library.Layout.Root), "Libreria"); + Fingerprint.AreEqual(before.Import, Fingerprint.Of(import), "importa"); + Assert.IsEmpty(Directory.GetFiles(bed.Temp.Path, ExportFolderCheck.ProbePrefix + "*", SearchOption.AllDirectories)); + + // A refused folder is refused by its text: no probe at all. + Assert.IsFalse((await check.CheckAsync(bed.Library.Layout.Root, context, ct)).Accepted); + Assert.HasCount(1, probes); + } + + [TestMethod] + public async Task AFolderWhereTheProbeCannotBeWrittenIsRefused() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var usb = temp.Combine("usb"); + Directory.CreateDirectory(usb); + + var readOnly = await new ExportFolderCheck(new FixedMounts(), writeProbe: _ => throw new IOException("Il supporto è protetto da scrittura.")) + .CheckAsync(usb, Context(temp), ct); + Assert.AreEqual(ExportFolderProblemKind.ProbeFailed, readOnly.Problem!.Kind); + Assert.AreEqual( + $"Febe non riesce a scrivere in {Path.GetFullPath(usb)} (Il supporto è protetto da scrittura.): controlla i permessi o che il disco non sia in sola lettura.", + readOnly.Problem.Message); + + var denied = await new ExportFolderCheck(new FixedMounts(), writeProbe: _ => throw new UnauthorizedAccessException("no")) + .CheckAsync(usb, Context(temp), ct); + Assert.AreEqual(ExportFolderProblemKind.ProbeFailed, denied.Problem!.Kind); + StringAssert.Contains(denied.Problem.Message, "(accesso negato)"); + Assert.IsFalse(denied.Problem.IsOverlap); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task ASlowFolderTimesOutWithoutBlocking() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var usb = temp.Combine("usb"); + Directory.CreateDirectory(usb); + using var release = new ManualResetEventSlim(); + var check = new ExportFolderCheck(new FixedMounts(), TimeSpan.FromMilliseconds(200), _ => release.Wait(TimeSpan.FromSeconds(20))); + + var started = System.Diagnostics.Stopwatch.StartNew(); + var verdict = await check.CheckAsync(usb, Context(temp), ct); + started.Stop(); + release.Set(); + Assert.AreEqual(ExportFolderProblemKind.NotResponding, verdict.Problem!.Kind); + Assert.AreEqual( + "La cartella non risponde entro 0 secondi: controlla che il disco o la condivisione siano collegati, poi riprova.", + verdict.Problem.Message); + Assert.IsLessThan(TimeSpan.FromSeconds(10), started.Elapsed, "the caller did not wait for the disk"); + } + + [TestMethod] + public async Task APathTooLongIsRefused() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var deep = temp.Path; + while (deep.Length < WindowsFileNames.MaxPathLength + 2) + { + deep = Path.Combine(deep, new string('c', 40)); + } + + Directory.CreateDirectory(deep); + var verdict = await Check().CheckAsync(deep, Context(temp), ct); + Assert.AreEqual(ExportFolderProblemKind.PathTooLong, verdict.Problem!.Kind); + StringAssert.Contains(verdict.Problem.Message, "è troppo lungo: i nomi dei file non ci starebbero nei 240 caratteri"); + Assert.IsEmpty(Directory.GetFileSystemEntries(deep)); + } + + private static ExportFolderCheck Check() => new(new FixedMounts()); + + private static string DatabaseName(ExportTestBed bed) => Path.GetFileName(bed.Library.Data.Database); + + /// A Data folder and a library inside the temporary folder, away from the candidates. + private static ExportFolderContext Context(TempFolder temp) => new( + [new(Path.GetFullPath(temp.Combine("dati")), ProtectedFolderKind.Data, null), new(Path.GetFullPath(temp.Combine("libreria")), ProtectedFolderKind.Library, null)], + ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() }); +} diff --git a/tests/Febe.Tests/Export/ExportFoundationTests.cs b/tests/Febe.Tests/Export/ExportFoundationTests.cs new file mode 100644 index 0000000..7c0bd10 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFoundationTests.cs @@ -0,0 +1,172 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The shared pieces of tappa E2 (WP1a): the gate of long work, the mount table, the export root in Docker, the folder +/// check with its probe, the destinations with «Esporta questo account» on by default. WP5 adds the full set. +/// +[TestClass] +public sealed class ExportFoundationTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheGateLetsOneLongJobRunAtATime() + { + var gate = new LongWorkGate(); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Import, out var lease, out _)); + Assert.AreEqual(LongWorkKind.Import, gate.Busy); + Assert.IsFalse(gate.TryEnter(LongWorkKind.Export, out _, out var busy)); + Assert.AreEqual(LongWorkKind.Import, busy); + Assert.AreEqual( + "C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi copia.", + LongWorkGate.BusyMessage(LongWorkKind.Export, busy!.Value)); + + lease.Dispose(); + Assert.IsNull(gate.Busy); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Rebuild, out var rebuild, out _)); + lease.Dispose(); // a second dispose of the old lease releases nothing + Assert.AreEqual(LongWorkKind.Rebuild, gate.Busy); + rebuild.Dispose(); + } + + [TestMethod] + public async Task AnImportDoesNotStartWhileTheGateIsHeld() + { + using var temp = new TempFolder(); + await using var bed = await ImportTestBed.CreateAsync(temp); + var gate = new LongWorkGate(); + await using var service = new ImportService(bed.Environment with { Gate = gate }); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _)); + + var refused = await Assert.ThrowsExactlyAsync(() => service.StartAsync(bed.Source, ct: TestContext.CancellationToken)); + Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message); + Assert.IsEmpty(await bed.Library.Db.Imports.ListRunsAsync(TestContext.CancellationToken)); + + lease.Dispose(); + var run = await service.StartAsync(bed.Source, ct: TestContext.CancellationToken); + await service.WaitAsync(run.Id, TestContext.CancellationToken); + Assert.IsNull(gate.Busy); // the job's lease went with it + } + + [TestMethod] + public void MountInfoGivesRootMountPointAndType() + { + const string content = """ + 22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw + 40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 - vfat /dev/sdb1 rw + 41 22 0:50 / /esporta/nas\040rete ro,relatime - cifs //nas/copie rw + bad line + """; + var mounts = MountInfoTable.Parse(content); + Assert.HasCount(3, mounts); + Assert.AreEqual("/esporta/nas rete", mounts[2].MountPoint); + Assert.IsTrue(mounts[2].ReadOnly); + Assert.AreEqual("/backup/foto", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe")!.Root); + Assert.AreEqual("vfat", MountInfoTable.FindContaining(mounts, "/esporta/usb")!.FileSystemType); + Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint); + + var o = ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => content)); + Assert.IsFalse(ExportRoots.Evaluate(o with { Declared = false }).Active); + Assert.IsFalse(ExportRoots.Evaluate(ExportRootOptions.Docker("/esporta", declared: true, new ProcMountInfo(() => "22 1 8:1 / / rw - ext4 /dev/sda1 rw"))).Active); + if (!OperatingSystem.IsWindows()) + { + // Docker paths are Linux paths: on Windows "/esporta" becomes a drive path the table cannot hold. + Assert.IsTrue(ExportRoots.Evaluate(o).Active); + Assert.IsNull(ExportRoots.MountProblem(o, "/esporta/usb/Febe")); + Assert.Contains("sola lettura", ExportRoots.MountProblem(o, "/esporta/nas rete/x")!); + Assert.IsNotNull(ExportRoots.MountProblem(o, "/esporta/altro")); + } + + Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, "usb/../../etc")).Kind); + Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, Assert.ThrowsExactly(() => ExportRoots.Resolve(o, ".")).Kind); + } + + [TestMethod] + public async Task TheFolderCheckRefusesOverlapsAndLeavesNoProbe() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var library = temp.Combine("libreria"); + var data = temp.Combine("dati"); + var outside = temp.Combine("copie"); + Directory.CreateDirectory(Path.Combine(library, "marta.demo")); + Directory.CreateDirectory(data); + Directory.CreateDirectory(outside); + var context = new ExportFolderContext( + [new(data, ProtectedFolderKind.Data, null), new(library, ProtectedFolderKind.Library, null), new(Path.Combine(library, "marta.demo"), ProtectedFolderKind.Account, "marta.demo")], + ExportRootOptions.AnyFolder); + var check = new ExportFolderCheck(new ProcMountInfo(() => null)); + + var accepted = await check.CheckAsync(outside, context, ct); + Assert.IsTrue(accepted.Accepted, accepted.Problem?.Message); + Assert.IsEmpty(Directory.GetFileSystemEntries(outside)); + Assert.AreEqual(ExportFolderProblemKind.InsideProtected, (await check.CheckAsync(Path.Combine(library, "marta.demo"), context with { Protected = context.Protected.Take(2).ToList() }, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.SameAsProtected, (await check.CheckAsync(data, context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.ContainsProtected, (await check.CheckAsync(temp.Path, context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.Missing, (await check.CheckAsync(temp.Combine("non-esiste"), context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, (await check.CheckAsync("relativa", context, ct)).Problem!.Kind); + Assert.AreEqual(ExportFolderProblemKind.RootOfDisk, (await check.CheckAsync(Path.GetPathRoot(temp.Path)!, context, ct)).Problem!.Kind); + Assert.IsFalse(Directory.Exists(temp.Combine("non-esiste"))); + } + + [TestMethod] + public async Task TheSafeWriterNeverCreatesAMissingRoot() + { + using var temp = new TempFolder(); + var root = temp.Combine("disco-assente"); + using var source = new MemoryStream([1, 2, 3]); + await Assert.ThrowsExactlyAsync(() => new SafeFileWriter().SaveAsync( + source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken)); + Assert.IsFalse(Directory.Exists(root)); + + Directory.CreateDirectory(root); + source.Position = 0; + var saved = await new SafeFileWriter().SaveAsync(source, root, "a/b.jpg", new SafeWriteOptions { RequireExistingRoot = true, VerifyFromDisk = true }, TestContext.CancellationToken); + Assert.AreEqual("a/b.jpg", saved.RelativePath); + } + + [TestMethod] + public async Task DestinationsAreCheckedAndTheSwitchIsOnByDefault() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"), ct); + var env = new ExportEnvironment { Storage = library.Db, Layout = () => library.Layout, DataFolder = library.Data.Root, Clock = library.Clock, Root = ExportRootOptions.AnyFolder with { Mounts = new ProcMountInfo(() => null) } }; + var destinations = new ExportDestinations(env); + var usb = temp.Combine("usb"); + Directory.CreateDirectory(usb); + + Assert.IsTrue((await destinations.ResolveAsync(account.Id, ct)) is { Enabled: true, HasDestination: false }); + await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(library.Layout.Root), ct)); + await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(usb) with { ContentTypes = ContentTypes.None }, ct)); + await Assert.ThrowsExactlyAsync(() => destinations.CreateAsync(Spec(usb) with { NamingScheme = "{inesistente}" }, ct)); + + var saved = await destinations.CreateAsync(Spec(usb) with { Label = " Disco USB " }, ct); + Assert.AreEqual("Disco USB", saved.Destination.Label); + var all = await destinations.ResolveAllAsync(ct); + Assert.AreEqual(saved.Destination.Id, all[account.Id].Destination!.Id); + Assert.IsTrue(all[account.Id].Exports); + + await destinations.SetAccountEnabledAsync(account.Id, false, ct); + Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).Exports); + + var run = await library.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = saved.Destination.Id, StartedAt = library.Clock.Now }, ct); + await Assert.ThrowsExactlyAsync(() => destinations.RetireAsync(saved.Destination.Id, ct)); + await library.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Cancelled }, ct); + await destinations.RetireAsync(saved.Destination.Id, ct); + Assert.IsTrue(Directory.Exists(usb)); + Assert.IsFalse((await destinations.ResolveAsync(account.Id, ct)).HasDestination); + Assert.IsEmpty(await destinations.RecheckAsync(null, ct)); + + static DestinationSpec Spec(string path) => new(ExportScope.General, null, path, null, ContentTypes.All, null, null, null); + } +} diff --git a/tests/Febe.Tests/Export/ExportPathsTests.cs b/tests/Febe.Tests/Export/ExportPathsTests.cs new file mode 100644 index 0000000..af336df --- /dev/null +++ b/tests/Febe.Tests/Export/ExportPathsTests.cs @@ -0,0 +1,183 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// Where a copy goes below its destination (spec §4.10 «Nomi dei file», §4.7; decision D18 of tappa E2). The default +/// library scheme names a post of 13 October 2026 08:00 UTC «post/2026/2026-10-13_10-00-00_C<id>_<n>» in Rome. +/// +[TestClass] +public sealed class ExportPathsTests +{ + private static readonly Account Marta = Make.Account("marta.demo") with { Id = 1 }; + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void TheGeneralFolderStartsWithTheAccountSegment() + { + var segments = ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), Photo(2), null, false, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "marta.demo", "post", "2026", "2026-10-13_10-00-00_C500_2.jpg" }, segments.ToArray()); + + // The account segment is sanitized as a folder name (a reserved name on Windows gets changed). + var aux = Marta with { Username = "aux" }; + var first = ExportPaths.Segments(General(), LibraryNaming.Default, aux, Post(), Photo(1), null, false, TestZones.Rome)[0]; + Assert.AreEqual(WindowsFileNames.SanitizeSegment("aux"), first); + Assert.AreNotEqual("aux", first); + } + + [TestMethod] + public void TheOwnFolderHasNoAccountSegment() + { + var own = General() with { Scope = ExportScope.Account, AccountId = 1 }; + var segments = ExportPaths.Segments(own, LibraryNaming.Default, Marta, Post(), Photo(1), null, false, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "post", "2026", "2026-10-13_10-00-00_C500_1.jpg" }, segments.ToArray()); + Assert.AreEqual("post/2026/2026-10-13_10-00-00_C500_1.jpg", ExportPaths.RelativePathFor(own, segments)); + } + + [TestMethod] + public void ComeLaLibreriaFollowsTheCurrentLibrarySchemes() + { + // The library file was named with an older scheme: the copy follows the scheme of now, not the stored path. + var naming = LibraryNaming.Default with { General = NamingScheme.Parse(@"{account}\{anno}-{mese}\{codice}_{n}", NamingSchemeUse.General) }; + var old = Photo(1) with { RelativePath = "post/2019/vecchio-nome.JPG" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "2026-10", "C500_1.jpg" }, + ExportPaths.Segments(General(), naming, Marta, Post(), old, null, false, TestZones.Rome).ToArray()); + + // A scheme of the destination wins over the library's; the highlight and profile schemes stay «Come la libreria». + var own = General() with { NamingScheme = @"{tipo}\{data}_{n}" }; + CollectionAssert.AreEqual(new[] { "marta.demo", "post", "2026-10-13_1.jpg" }, ExportPaths.Segments(own, naming, Marta, Post(), old, null, false, TestZones.Rome).ToArray()); + var highlight = Make.Entry(1, "700", Make.T0, EntryKind.Highlight); + CollectionAssert.AreEqual( + new[] { "marta.demo", "evidenza", "Mare", "2026-10-13_10-00-00_700_1.jpg" }, + ExportPaths.Segments(own, naming, Marta, highlight, old, "Mare", true, TestZones.Rome).ToArray()); + } + + [TestMethod] + public async Task ComeLaLibreriaFollowsTheSchemeSavedInTheSettings() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "930", 1); + await bed.Db.Settings.SetAsync(SettingKeys.NamingScheme, @"{account}\{anno}\{codice}_{n}", ct); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.IsTrue(File.Exists(Path.Combine(bed.Usb, "marta.demo", "2026", "C930_1.jpg"))); + Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + } + + [TestMethod] + public void ImportedFilesWithoutDateKeepTheirName() + { + var imported = Photo(1) with { RelativePath = "importati/vacanze/IMG 0001.JPG" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "importati", "vacanze", "IMG 0001.JPG" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome).ToArray()); + var own = General() with { Scope = ExportScope.Account, AccountId = 1 }; + CollectionAssert.AreEqual( + new[] { "importati", "vacanze", "IMG 0001.JPG" }, + ExportPaths.Segments(own, LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome).ToArray()); + + // Only a file the import left in «importati/» keeps its path; a scheme of the destination renames it. + var renamed = ExportPaths.Segments(own with { NamingScheme = @"{anno}\{codice}_{n}" }, LibraryNaming.Default, Marta, Post(), imported, null, false, TestZones.Rome); + CollectionAssert.AreEqual(new[] { "2026", "C500_1.jpg" }, renamed.ToArray()); + Assert.ThrowsExactly(() => ExportPaths.Segments(General(), LibraryNaming.Default, Marta, Post(), Photo(1) with { RelativePath = null }, null, false, TestZones.Rome)); + } + + [TestMethod] + public void AStoryInAHighlightRendersAsHighlightOnlyWithoutStories() + { + var story = Make.Entry(1, "800", Make.T0, EntryKind.Story); + var media = Photo(1) with { RelativePath = "storie/2026/x.jpg" }; + string[] Render(ContentTypes types, bool inHighlight) => + [.. ExportPaths.Segments(General() with { ContentTypes = types }, LibraryNaming.Default, Marta, story, media, "Estate", inHighlight, TestZones.Rome)]; + + CollectionAssert.AreEqual(new[] { "marta.demo", "evidenza", "Estate", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Highlights, inHighlight: true)); + CollectionAssert.AreEqual(new[] { "marta.demo", "storie", "2026", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Highlights | ContentTypes.Stories, inHighlight: true)); + CollectionAssert.AreEqual(new[] { "marta.demo", "storie", "2026", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Stories, inHighlight: true)); + CollectionAssert.AreEqual(new[] { "marta.demo", "storie", "2026", "2026-10-13_10-00-00_800_1.jpg" }, Render(ContentTypes.Highlights, inHighlight: false)); + + // The content types of D4. + Assert.AreEqual(ContentTypes.Stories | ContentTypes.Highlights, ExportPaths.TypeOf(EntryKind.Story, MediaKind.Video, inHighlight: true)); + Assert.AreEqual(ContentTypes.Stories, ExportPaths.TypeOf(EntryKind.Story, MediaKind.Photo, inHighlight: false)); + Assert.AreEqual(ContentTypes.PostVideos, ExportPaths.TypeOf(EntryKind.Post, MediaKind.Video, false)); + Assert.AreEqual(ContentTypes.Tagged, ExportPaths.TypeOf(EntryKind.Tagged, MediaKind.Video, false)); + Assert.AreEqual(ContentTypes.ProfilePicture, ExportPaths.TypeOf(EntryKind.ProfilePicture, MediaKind.Photo, false)); + } + + [TestMethod] + public void ProfilePicturesUseTheFirstEightDigitsOfTheSha() + { + var profile = Make.Entry(1, "900", Make.T0, EntryKind.ProfilePicture); + var sha = "abcdef0123456789" + new string('0', 48); + var media = Photo(1) with { Sha256 = sha, RelativePath = "profilo/vecchio.jpg" }; + CollectionAssert.AreEqual( + new[] { "marta.demo", "profilo", "2026-10-13_10-00-00_abcdef01_1.jpg" }, + ExportPaths.Segments(General(), LibraryNaming.Default, Marta, profile, media, null, false, TestZones.Rome).ToArray()); + var own = General() with { Scope = ExportScope.Account, AccountId = 1, ProfileNamingScheme = @"foto\{codice}" }; + CollectionAssert.AreEqual(new[] { "foto", "abcdef01.jpg" }, ExportPaths.Segments(own, LibraryNaming.Default, Marta, profile, media, null, false, TestZones.Rome).ToArray()); + } + + [TestMethod] + public void LongPathsAreShortenedTo240WithTheRoot() + { + var root = Path.Combine(Path.GetTempPath(), new string('r', 120)); + var deep = General() with { RootPath = root }; + var segments = new[] { "marta.demo", new string('a', 60), new string('b', 60) + ".jpg" }; + var fitted = ExportPaths.RelativePathFor(deep, segments); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + fitted.Length); + StringAssert.EndsWith(fitted, ".jpg"); + StringAssert.StartsWith(fitted, "marta.demo/"); + Assert.AreEqual("marta.demo/x.jpg", ExportPaths.RelativePathFor(deep, ["marta.demo", "x.jpg"])); // short paths are not touched + + // A root that leaves no room for a name at all. + var hopeless = General() with { RootPath = Path.Combine(Path.GetTempPath(), new string('r', 235)) }; + Assert.ThrowsExactly(() => ExportPaths.RelativePathFor(hopeless, segments)); + + // The numbered names of the safe writer fit too, keeping the extension (at the limit the number goes into + // the shortened name, as the safe writer does). + Assert.AreEqual("a/b/foto.jpg", ExportPaths.NumberedName(root, "a/b/foto.jpg", 1)); + Assert.AreEqual("a/b/foto (2).jpg", ExportPaths.NumberedName(root, "a/b/foto.jpg", 2)); + var numbered = ExportPaths.NumberedName(root, fitted, 3); + StringAssert.EndsWith(numbered, ".jpg"); + CollectionAssert.AllItemsAreUnique(new[] { fitted, ExportPaths.NumberedName(root, fitted, 2), numbered }); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, Path.TrimEndingDirectorySeparator(root).Length + 1 + numbered.Length); + } + + [TestMethod] + public void TheNamingPreviewOfADestinationTakesTheLibrarySchemesWhenNull() + { + var naming = LibraryNaming.Default with { General = NamingScheme.Parse(@"{account}\{anno}\{codice}_{n}", NamingSchemeUse.General) }; + var library = NamingPreview.Build(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, TestZones.Rome, "marta.demo"); + var own = ExportNamingPreview.Build(ExportScope.Account, null, null, null, naming, TestZones.Rome, "marta.demo"); + Assert.AreEqual(Describe(library), Describe(own)); + + var general = ExportNamingPreview.Build(ExportScope.General, @"{tipo}\{codice}_{n}", null, null, naming, TestZones.Rome, "marta.demo"); + Assert.IsNotEmpty(general.Folders); + Assert.IsTrue(general.Folders.All(f => f.Path[0] == "marta.demo"), Describe(general)); + Assert.IsTrue(general.Folders.Any(f => f.Path.Count > 1 && f.Path[1] == "post"), Describe(general)); + Assert.IsTrue(general.Folders.Any(f => f.Path.Contains("evidenza")), Describe(general)); // the highlight scheme of the library + } + + private static string Describe(NamingPreview preview) => + string.Join(" | ", preview.Folders.Select(f => string.Join('/', f.Path) + ": " + string.Join(", ", f.Files))); + + private static ExportDestination General() => new() + { + Id = 1, + Scope = ExportScope.General, + RootPath = Path.Combine(Path.GetTempPath(), "copie"), + ContentTypes = ContentTypes.All, + CreatedAt = Make.T0, + }; + + private static Entry Post() => Make.Entry(1, "500", Make.T0); + + private static Media Photo(int position) => Make.Stored(Make.Photo(position), Make.Sha(position), $"post/2026/vecchio_{position}.jpg"); +} diff --git a/tests/Febe.Tests/Export/ExportReviewTests.cs b/tests/Febe.Tests/Export/ExportReviewTests.cs new file mode 100644 index 0000000..30931f7 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportReviewTests.cs @@ -0,0 +1,381 @@ +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The cases found by the review of tappa E2 (27 November 2026): a stale row on the free name the writer takes, a +/// path that differs only in letter case, a superseded copy whose file is back in the library, «Una copia sola» with +/// copies of the account itself or of a removed account, a disk unplugged during «Controlla le copie», the later runs of +/// an interrupted «Copia in…», and the long-work gate held while a «Copia in…» is planned. +/// +[TestClass] +public sealed class ExportReviewTests +{ + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30); + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task AStaleRowOnTheFreeNameIsReleasedAndTheCopyRecorded() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "970", 40); + var usb = await bed.GeneralAsync(ct: ct); + var planned = "marta.demo/" + post.Media[0].RelativePath; + var numbered = ExportPaths.NumberedName(bed.Usb, planned, 2); + + // The planned name holds another file (other bytes); the next name is still recorded for a copy of luca.demo + // whose file Alberto deleted. + var foreign = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(planned)); + Directory.CreateDirectory(Path.GetDirectoryName(foreign)!); + await File.WriteAllBytesAsync(foreign, [1, 2, 3], ct); + var stale = await bed.Db.Exports.AddCopyAsync(StaleCopy(usb.Id, bed.Luca.Id, numbered, 91), ct); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken, numbered), (item.State, item.Note, item.RelativePath)); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportCopyState.Copied, numbered), (copy.State, copy.RelativePath)); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(stale.Id, ct))!.State, "the stale row is «Tolto»"); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(foreign, ct), "the other file is untouched"); + + // A second «Copia in…» writes nothing more. + var files = Fingerprint.Of(bed.Usb); + var again = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreEqual((0, 1), (again.Plan.Files, again.Plan.AlreadyCopied)); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "no duplicate"); + } + + [TestMethod] + public async Task APathThatDiffersOnlyInCaseIsNotTakenFromItsCopy() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "971", 41); + var usb = await bed.GeneralAsync(ct: ct); + var planned = "marta.demo/" + post.Media[0].RelativePath; + var slash = planned.LastIndexOf('/'); + var shouted = planned[..(slash + 1)] + planned[(slash + 1)..].ToUpperInvariant(); + Assert.AreNotEqual(planned, shouted); + + // Another copy is recorded and present under the same name in other letters (a case-sensitive disk keeps both). + var other = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(shouted)); + Directory.CreateDirectory(Path.GetDirectoryName(other)!); + await File.WriteAllBytesAsync(other, [4, 5, 6], ct); + var held = await bed.Db.Exports.AddCopyAsync(StaleCopy(usb.Id, bed.Luca.Id, shouted, 92) with { Bytes = 3 }, ct); + + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (item.State, item.Note)); + Assert.AreEqual(ExportPaths.NumberedName(bed.Usb, planned, 2), item.RelativePath); + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(held.Id, ct))!.State, "its file is there: not «Tolto»"); + CollectionAssert.AreEqual(new byte[] { 4, 5, 6 }, await File.ReadAllBytesAsync(other, ct)); + } + + [TestMethod] + public async Task ASupersededCopyOfAFileBackInTheLibraryAgreesAndCanBeCopiedAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "972", 42); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var media = post.Media[0]; + + // The copy was superseded by another file; that file went, and this one came back (another entry, with no + // change of file that would have revived the row). + Assert.AreEqual(1, await bed.Db.Exports.SupersedeCopiesAsync(bed.Marta.Id, media.Sha256!, Make.Sha(77), bed.Clock.Now, ct)); + var request = new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)); + var plan = await bed.Service.PlanAsync(request, ct); + Assert.AreEqual((0, 0, 1), (plan.Files, plan.AlreadyCopied, plan.RemovedOrSuperseded)); + Assert.AreEqual(new ExportAccountCounts(1, 0, 1, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct), "the filter says what the plan does"); + CollectionAssert.AreEqual(new[] { post.Entry.Id }, await EntriesAsync(bed.Db, LibraryCopiesFilter.RemovedOrSuperseded, ct)); + Assert.IsEmpty(await EntriesAsync(bed.Db, LibraryCopiesFilter.NotCopied, ct)); + + // «Copia di nuovo» finds its own bytes at the path: the row is «Copiato» again, nothing is written. + var files = Fingerprint.Of(bed.Usb); + var start = await bed.CopyAsync(request with { CopyAgain = true }, ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual(ExportItemState.AlreadyCopied, item.State); + var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!; + Assert.AreEqual((ExportCopyState.Copied, (string?)null), (copy.State, copy.SupersededBySha256)); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written"); + Assert.AreEqual(new ExportAccountCounts(1, 0, 0, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)); + Assert.AreEqual(1, (await bed.Service.PlanAsync(request, ct)).AlreadyCopied); + } + + [TestMethod] + public async Task OneCopyOnlyIgnoresTheAccountsOwnCopyInAnotherFolder() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "973", 43); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + + // Her own folder now, the general one still in use for the others. + await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 1, ct); + Assert.AreEqual(ExportMark.None, (await bed.Db.Exports.GetFileMarksAsync([post.Media[0].Id], ct))[post.Media[0].Id]); + } + + [TestMethod] + public async Task OneCopyOnlyIgnoresTheCopyOfARemovedAccount() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var lucas = await bed.PostAsync(bed.Luca, "974", 44); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Luca, ct: ct); + var martas = await bed.PostAsync(bed.Marta, "975", 44); // the same bytes + Assert.AreEqual(lucas.Media[0].Sha256, martas.Media[0].Sha256); + + // luca.demo leaves Febe: his copy stays, without an account. + await bed.Db.Accounts.DeleteAsync(bed.Luca.Id, ct); + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 1, ct); + Assert.AreEqual(ExportMark.None, (await bed.Db.Exports.GetFileMarksAsync([martas.Media[0].Id], ct))[martas.Media[0].Id]); + } + + [TestMethod] + public async Task OneCopyOnlyFindsTheOtherAccountsCopyBehindTheAccountsOwnNewerOne() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var lucas = await bed.PostAsync(bed.Luca, "976", 45); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Luca, ct: ct); // the older copy, of luca.demo + var martas = await bed.PostAsync(bed.Marta, "977", 45); + await bed.CopyAccountAsync(bed.Marta, ct: ct); // the newer one, hers («Una copia per account») + Assert.AreEqual(lucas.Media[0].Sha256, martas.Media[0].Sha256); + + await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + await AssertAgreeAsync(bed, bed.Marta, expectedToWrite: 0, ct); + var start = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (item.State, item.Note)); + } + + [TestMethod] + public async Task ADiskUnpluggedDuringTheCheckMarksNothingRemoved() + { + var ct = TestContext.CancellationToken; + var unplug = new UnplugOnCheck(); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = unplug }); + await bed.PostAsync(bed.Marta, "978", 46, 47, 48); + var usb = await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct)); + + // The disk goes away after the root was found and before the files of the page are looked for. + unplug.Root = bed.Usb; + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + Assert.IsTrue(unplug.Unplugged); + Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct), "nothing is «Tolto»"); + Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt, "the destination is paused"); + + // Plugged in again, the check finds every file. + Directory.Move(bed.Usb + "-staccato", bed.Usb); + unplug.Root = null; + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, ct: ct)); + } + + [TestMethod] + public async Task InterruptingAJobOfTwoDestinationsLeavesBothResumable() + { + var ct = TestContext.CancellationToken; + string? blocked = null; + var gated = new GatedExportFileSystem(p => string.Equals(p, Volatile.Read(ref blocked), StringComparison.Ordinal)); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated }); + var martas = await bed.PostAsync(bed.Marta, "979", 49); + var lucas = await bed.PostAsync(bed.Luca, "980", 50); + await bed.GeneralAsync(ct: ct); + await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct); + Volatile.Write(ref blocked, bed.LibraryFile(bed.Marta, martas.Media[0])); + + var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([martas.Entry.Id, lucas.Entry.Id])), ct); + Assert.HasCount(2, start.Runs); + await gated.Reached.Task.WaitAsync(Patience, ct); + await bed.Service.InterruptAsync(ct); + Assert.IsFalse(bed.Service.IsBusy); + foreach (var run in start.Runs) + { + Assert.AreEqual((ExportRunState.Interrupted, (string?)null), ((await bed.RunAsync(run.Id, ct)).State, (await bed.RunAsync(run.Id, ct)).LastError), $"run {run.Id}"); + } + + // «Riprendi tutte» takes both. + Volatile.Write(ref blocked, null); + var resumed = await bed.Service.ResumeAsync(ct: ct); + Assert.HasCount(2, resumed); + await bed.Service.WaitAsync(ct); + foreach (var run in start.Runs) + { + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + } + } + + [TestMethod] + public async Task TheLongWorkGateIsHeldWhileACopyIsPlanned() + { + var ct = TestContext.CancellationToken; + GateWatchingClock? clock = null; + await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new GateWatchingClock(env.Clock, env.Gate!) }); + await bed.PostAsync(bed.Marta, "981", 51, 52); + await bed.GeneralAsync(ct: ct); + + clock!.Watching = true; + await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + clock.Watching = false; + await bed.Service.WaitAsync(ct); + Assert.IsGreaterThan(0, clock.Looks, "the start read the clock while it planned"); + Assert.AreEqual(0, clock.Overlaps, "a rebuild could have started while the runs were recorded"); + Assert.IsNull(bed.Gate.Busy); + + // Nothing to copy: the gate is free again at once. + var nothing = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct); + Assert.IsEmpty(nothing.Runs); + Assert.IsNull(bed.Gate.Busy); + } + + [TestMethod] + public void TheRenameNeverReplacesAnExistingName() + { + using var temp = new TempFolder("rename"); + var taken = temp.Combine("taken.jpg"); + var source = temp.Combine(".febe-0123456789ab.part"); + File.WriteAllBytes(taken, [1]); + File.WriteAllBytes(source, [2]); + if (OperatingSystem.IsWindows()) + { + // On Windows the move itself refuses an existing name: nothing to do here. + Assert.AreEqual(NoReplaceOutcome.Unsupported, NoReplaceRename.TryMove(source, taken)); + } + else + { + Assert.AreEqual(NoReplaceOutcome.Taken, NoReplaceRename.TryMove(source, taken)); + CollectionAssert.AreEqual(new byte[] { 1 }, File.ReadAllBytes(taken)); + Assert.IsTrue(File.Exists(source)); + + var free = temp.Combine("free.jpg"); + Assert.AreEqual(NoReplaceOutcome.Moved, NoReplaceRename.TryMove(source, free)); + CollectionAssert.AreEqual(new byte[] { 2 }, File.ReadAllBytes(free)); + Assert.IsFalse(File.Exists(source)); + } + + Assert.AreEqual(1, File.ReadAllBytes(taken)[0]); + } + + /// A Copied row of a whole original (any SHA-256 given by its seed) at a path, with no file behind it. + private static ExportCopy StaleCopy(long destinationId, long accountId, string path, int seed) => new() + { + DestinationId = destinationId, + AccountId = accountId, + SourceSha256 = Make.Sha(seed), + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportCopyState.Copied, + RelativePath = path, + Bytes = 1, + CopySha256 = Make.Sha(seed), + CopiedAt = Make.T0, + }; + + /// The plan of the account, its counts, its marks and the «Copie» filter tell the same. + private static async Task AssertAgreeAsync(ExportTestBed bed, Account account, int expectedToWrite, CancellationToken ct) + { + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(account.Id)), ct); + var counts = await bed.Db.Exports.CountAccountFilesAsync(account.Id, ct); + Assert.AreEqual(expectedToWrite, plan.Files, "plan"); + Assert.AreEqual(plan.Files, counts.NotCopied, "«non ancora copiati» is what «Copia in…» writes"); + Assert.AreEqual(plan.AlreadyCopied, counts.Copied, "«copiati» is what «Copia in…» skips as copied"); + var filter = new LibraryFilter { Copies = LibraryCopiesFilter.NotCopied, AccountIds = [account.Id] }; + Assert.AreEqual(expectedToWrite, (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = filter, Mode = MosaicMode.Files }, ct)).Tiles.Count); + var copied = filter with { Copies = LibraryCopiesFilter.Copied }; + Assert.AreEqual(plan.AlreadyCopied, (await bed.Db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = copied, Mode = MosaicMode.Files }, ct)).Tiles.Count); + } + + private static async Task EntriesAsync(FebeDatabase db, LibraryCopiesFilter filter, CancellationToken ct) => + [.. (await db.Entries.QueryLibraryAsync(new LibraryQuery { Filter = new LibraryFilter { Copies = filter } }, ct)).Tiles.Select(t => t.EntryId)]; + + /// The real file system; once is set, the first look for a file in it takes the disk away. + private sealed class UnplugOnCheck : IExportFileSystem + { + private int _unplugged; + + public string? Root { get; set; } + + public bool Unplugged => Volatile.Read(ref _unplugged) != 0; + + public Stream OpenRead(string path) => ExportFileSystem.Instance.OpenRead(path); + + public Task ComputeSha256Async(string path, CancellationToken ct) => ExportFileSystem.Instance.ComputeSha256Async(path, ct); + + public bool FileExists(string path) + { + if (Root is { } root && path.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.Ordinal) && Interlocked.Exchange(ref _unplugged, 1) == 0) + { + Directory.Move(root, root + "-staccato"); + } + + return ExportFileSystem.Instance.FileExists(path); + } + + public long? FileLength(string path) => ExportFileSystem.Instance.FileLength(path); + } + + /// + /// The clock of the export; while , each look at the time tries to start a rebuild through the + /// long-work gate (and lets it go at once), counting the times it could. + /// + private sealed class GateWatchingClock(IClock inner, LongWorkGate gate) : IClock + { + private int _looks; + private int _overlaps; + private volatile bool _watching; + + public bool Watching + { + get => _watching; + set => _watching = value; + } + + public int Looks => Volatile.Read(ref _looks); + + public int Overlaps => Volatile.Read(ref _overlaps); + + public DateTimeOffset Now + { + get + { + if (Watching) + { + Interlocked.Increment(ref _looks); + if (gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _)) + { + Interlocked.Increment(ref _overlaps); + lease.Dispose(); + } + } + + return inner.Now; + } + } + + public TimeZoneInfo LocalZone => inner.LocalZone; + + public Task Delay(TimeSpan time, CancellationToken ct) => inner.Delay(time, ct); + } +} diff --git a/tests/Febe.Tests/Export/ExportRootTests.cs b/tests/Febe.Tests/Export/ExportRootTests.cs new file mode 100644 index 0000000..809bace --- /dev/null +++ b/tests/Febe.Tests/Export/ExportRootTests.cs @@ -0,0 +1,218 @@ +using Febe.Core.Export; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// Where destinations may be chosen (spec §4.10, §11; decision D14 and question Q2 of tappa E2): any folder on Windows; +/// in Docker only below /esporta, only when it is declared and the folder sits on a mount at /esporta or +/// below it. The Docker root is a temporary folder and the mount table is given by the test, so this runs on every +/// platform. +/// +[TestClass] +public sealed class ExportRootTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public void DesktopHasNoRootAndIsActive() + { + var o = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() }; + Assert.AreEqual(new ExportRootState(true, null, null), ExportRoots.Evaluate(o)); + using var temp = new TempFolder(); + Assert.IsNull(ExportRoots.MountProblem(o, temp.Path)); + Assert.AreEqual(Path.GetFullPath(temp.Combine("usb")), ExportRoots.Resolve(o, temp.Combine("usb") + Path.DirectorySeparatorChar)); + Assert.AreEqual(temp.Path, ExportRoots.DisplayPath(o, temp.Path)); + Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, Kind(() => ExportRoots.Resolve(o, "usb"))); + Assert.AreEqual(ExportFolderProblemKind.Empty, Kind(() => ExportRoots.Resolve(o, " "))); + } + + [TestMethod] + public void DockerNotDeclaredIsOffAndSaysWhy() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(Path.Combine(root, "usb")); + var o = ExportRootOptions.Docker(root, declared: false, new FixedMounts(Mount(root))); + + var state = ExportRoots.Evaluate(o); + Assert.IsFalse(state.Active); + Assert.AreEqual(Path.GetFullPath(root), state.Root); + Assert.AreEqual(ExportRoots.NotDeclaredText, state.Problem); + StringAssert.Contains(state.Problem, "FEBE_ESPORTA=1"); + Assert.AreEqual(ExportRoots.NotDeclaredText, ExportRoots.MountProblem(o, Path.Combine(root, "usb"))); + } + + [TestMethod] + public void DockerDeclaredButNotMountedIsOff() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(Path.Combine(root, "usb")); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(Path.GetPathRoot(temp.Path)!), Mount(temp.Combine("altro")))); + o = o with { ShownAs = "/esporta" }; + + var state = ExportRoots.Evaluate(o); + Assert.IsFalse(state.Active); + Assert.AreEqual("/esporta è dichiarata ma non è montata: Febe non scrive nulla finché non monti una cartella del server su /esporta.", state.Problem); + Assert.AreEqual(state.Problem, ExportRoots.MountProblem(o, Path.Combine(root, "usb"))); + } + + [TestMethod] + public void DockerMountedAtTheRootIsActive() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(Path.Combine(root, "usb", "Febe")); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(Path.GetPathRoot(temp.Path)!), Mount(root))) with { ShownAs = "/esporta" }; + + Assert.IsTrue(ExportRoots.Evaluate(o).Active); + Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(root, "usb"))); + Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(root, "usb", "Febe"))); + Assert.AreEqual(Path.GetFullPath(Path.Combine(root, "usb", "Febe")), ExportRoots.Resolve(o, "usb/Febe")); + Assert.AreEqual(Path.GetFullPath(Path.Combine(root, "usb")), ExportRoots.Resolve(o, "usb/")); + Assert.AreEqual(Path.GetFullPath(Path.Combine(root, "usb")), ExportRoots.Resolve(o, Path.Combine(root, "usb"))); + Assert.AreEqual("/esporta/usb/Febe", ExportRoots.DisplayPath(o, Path.Combine(root, "usb", "Febe"))); + Assert.AreEqual(ExportFolderProblemKind.OutsideExportRoot, Kind(() => ExportRoots.Resolve(o, temp.Combine("altro")))); + } + + [TestMethod] + public void DockerSubMountOnlyAcceptsFoldersOnTheMount() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + var usb = Path.Combine(root, "usb"); + Directory.CreateDirectory(Path.Combine(usb, "Febe")); + Directory.CreateDirectory(Path.Combine(root, "immagine")); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(Path.GetPathRoot(temp.Path)!), Mount(usb))) with { ShownAs = "/esporta" }; + + Assert.IsTrue(ExportRoots.Evaluate(o).Active); // a mount below /esporta is enough (Q2) + Assert.IsNull(ExportRoots.MountProblem(o, usb)); + Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(usb, "Febe"))); + + // A folder of /esporta that is not on the mount is the disk of the image: never written. + var problem = ExportRoots.MountProblem(o, Path.Combine(root, "immagine")); + Assert.AreEqual("/esporta/immagine non è su una cartella montata in /esporta: Febe non ci scrive nulla. Scegli una cartella dentro un montaggio di /esporta.", problem); + Assert.IsNotNull(ExportRoots.MountProblem(o, Path.Combine(root, "usbx"))); + } + + [TestMethod] + public void ReadOnlyMountIsRefused() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + var nas = Path.Combine(root, "nas"); + Directory.CreateDirectory(nas); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root), Mount(nas, readOnly: true))) with { ShownAs = "/esporta" }; + + Assert.IsTrue(ExportRoots.Evaluate(o).Active); + Assert.AreEqual("/esporta/nas/Febe è montata in sola lettura: Febe non può copiarci nulla.", ExportRoots.MountProblem(o, Path.Combine(nas, "Febe"))); + Assert.IsNull(ExportRoots.MountProblem(o, Path.Combine(root, "usb"))); + } + + [TestMethod] + public void ParentSegmentsAreRefusedEvenWhenTheyStayInside() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(Path.Combine(root, "usb")); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" }; + + foreach (var chosen in new[] { "usb/../usb", "usb/..", "../esporta/usb", @"usb\..\usb", "usb/../../etc" }) + { + var refused = Assert.ThrowsExactly(() => ExportRoots.Resolve(o, chosen), chosen); + Assert.AreEqual(ExportFolderProblemKind.ParentSegment, refused.Kind, chosen); + Assert.AreEqual("«..» non è ammesso: scegli una sottocartella di /esporta dall'elenco.", refused.Message); + } + + Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Kind(() => ExportRoots.Resolve(ExportRootOptions.AnyFolder, Path.Combine(temp.Path, "..", "x")))); + Assert.AreEqual(ExportFolderProblemKind.ParentSegment, Kind(() => ExportRoots.Browse(o, "usb/.."))); + Assert.AreEqual("..x", Path.GetFileName(ExportRoots.Resolve(o, "usb/..x"))); // a name that only starts with dots is a name + } + + [TestMethod] + public void TheRootItselfIsRefused() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(root); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" }; + + // («/» alone is a full path on Linux, so it is refused there as outside the root: refused all the same.) + foreach (var chosen in new[] { ".", "./", "./.", root, root + Path.DirectorySeparatorChar }) + { + var refused = Assert.ThrowsExactly(() => ExportRoots.Resolve(o, chosen), chosen); + Assert.AreEqual(ExportFolderProblemKind.ExportRootItself, refused.Kind, chosen); + Assert.AreEqual("Scegli una sottocartella di /esporta: /esporta stessa non è una destinazione.", refused.Message); + } + + Assert.AreEqual(ExportFolderProblemKind.Empty, Kind(() => ExportRoots.Resolve(o, string.Empty))); + Assert.IsEmpty(ExportRoots.Browse(o, null)); // the picker may open it, just not choose it + } + + [TestMethod] + public void BrowseListsSubfoldersWithoutLinksOrHiddenOnes() + { + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(Path.Combine(root, "usb", "Febe")); + Directory.CreateDirectory(Path.Combine(root, "nas")); + var hidden = Directory.CreateDirectory(Path.Combine(root, ".nascosta")); + hidden.Attributes |= FileAttributes.Hidden; // on Linux the dot is enough + File.WriteAllText(Path.Combine(root, "file.txt"), "non è una cartella"); + if (!OperatingSystem.IsWindows()) + { + // A link out of the root (creating one on Windows needs rights a test does not have). + Directory.CreateSymbolicLink(Path.Combine(root, "collegamento"), temp.Path); + } + + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" }; + var top = ExportRoots.Browse(o, null); + CollectionAssert.AreEqual(new[] { "nas", "usb" }, top.Select(c => c.Name).ToArray()); + Assert.AreEqual("usb", top[1].Path); // relative to the root + Assert.IsTrue(top[1].HasSubfolders); + Assert.IsFalse(top[0].HasSubfolders); + Assert.AreEqual("usb/Febe", ExportRoots.Browse(o, "usb").Single().Path); + + var missing = Assert.ThrowsExactly(() => ExportRoots.Browse(o, "assente")); + Assert.AreEqual(ExportFolderProblemKind.Missing, missing.Kind); + Assert.AreEqual("La cartella /esporta/assente non esiste.", missing.Message); + + // Windows: a full path, and the whole tree is offered (links and hidden folders still skipped). + var desktop = ExportRoots.Browse(ExportRootOptions.AnyFolder, root); + CollectionAssert.AreEqual(new[] { Path.Combine(Path.GetFullPath(root), "nas"), Path.Combine(Path.GetFullPath(root), "usb") }, desktop.Select(c => c.Path).ToArray()); + Assert.AreEqual(ExportFolderProblemKind.NotFullyQualified, Kind(() => ExportRoots.Browse(ExportRootOptions.AnyFolder, "usb"))); + } + + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task ADeadShareBelowTheRootDoesNotBlockThePicker() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + var root = temp.Combine("esporta"); + Directory.CreateDirectory(Path.Combine(root, "nas", "Febe")); + Directory.CreateDirectory(Path.Combine(root, "usb", "Febe")); + var o = ExportRootOptions.Docker(root, declared: true, new FixedMounts(Mount(root))) with { ShownAs = "/esporta" }; + + // The NAS behind /esporta/nas is off: a look into it never answers. + using var dead = new ManualResetEventSlim(); + bool Look(string folder) => Path.GetFileName(folder) == "nas" ? dead.Wait(Timeout.Infinite, ct) : Directory.EnumerateDirectories(folder).Any(); + var started = System.Diagnostics.Stopwatch.StartNew(); + var top = await ExportRoots.BrowseAsync(o, null, TimeSpan.FromMilliseconds(300), Look, ct); + Assert.IsLessThan(TimeSpan.FromSeconds(10), started.Elapsed); + CollectionAssert.AreEqual(new[] { "nas", "usb" }, top.Select(c => c.Name).ToArray()); + Assert.IsFalse(top[0].HasSubfolders, "the dead share is shown, without the arrow"); + Assert.IsTrue(top[1].HasSubfolders, "the healthy one is listed as usual"); + dead.Set(); + + var missing = await Assert.ThrowsExactlyAsync(() => ExportRoots.BrowseAsync(o, "assente", TimeSpan.FromSeconds(5), ct)); + Assert.AreEqual(ExportFolderProblemKind.Missing, missing.Kind); + } + + internal static ExportMount Mount(string point, string root = "/", string type = "ext4", bool readOnly = false) => + new(Path.GetFullPath(point), root, type, readOnly); + + private static ExportFolderProblemKind? Kind(Action action) => Assert.ThrowsExactly(action).Kind; +} diff --git a/tests/Febe.Tests/Export/ExportSamePostTests.cs b/tests/Febe.Tests/Export/ExportSamePostTests.cs new file mode 100644 index 0000000..cc31f38 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportSamePostTests.cs @@ -0,0 +1,127 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The same file in two places (spec §4.10 l.311-312): «Una copia per account» or «Una copia sola» for a post seen by two +/// accounts, and a story that is also in a highlight, which is one file and one copy. +/// +[TestClass] +public sealed class ExportSamePostTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task OneCopyPerAccountWritesTwoFilesUnderTwoSegments() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var marta = await bed.PostAsync(bed.Marta, "980", 60); + var luca = await bed.PostAsync(bed.Luca, "980", 60); + Assert.AreEqual(marta.Media[0].Sha256, luca.Media[0].Sha256); + var usb = await bed.GeneralAsync(ct: ct); + + var started = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct); + Assert.AreEqual((2, 0), (started.Plan.Files, started.Plan.AlreadyCopied)); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, marta.Media[0]))); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, luca.Media[0]))); + Assert.HasCount(2, Fingerprint.Of(bed.Usb)); + var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); + CollectionAssert.AreEquivalent(new long?[] { bed.Marta.Id, bed.Luca.Id }, copies.Select(c => c.AccountId).ToArray()); + Assert.IsTrue(copies.All(c => c.State == ExportCopyState.Copied)); + } + + [TestMethod] + public async Task OneCopyOnlyWritesOnceAndTheOtherShowsCopied() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var marta = await bed.PostAsync(bed.Marta, "981", 61); + var luca = await bed.PostAsync(bed.Luca, "981", 61); + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + var usb = await bed.GeneralAsync(ct: ct); + + // In one job: the plan counts it once and one file is written. + var both = new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])); + var plan = await bed.Service.PlanAsync(both, ct); + Assert.AreEqual((1, 1), (plan.Files, plan.AlreadyCopied)); + var started = await bed.CopyAsync(both, ct); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + var items = await bed.ItemsAsync(started.Runs.Single().Id, ct); + Assert.AreEqual(1, items.Count(i => i.State == ExportItemState.Copied)); + var other = items.Single(i => i.State != ExportItemState.Copied); + Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (other.State, other.Note)); + var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + Assert.AreEqual(copy.Id, other.CopyId); + + // Later, the other account alone: still «Già copiato», nothing written. + var otherAccount = copy.AccountId == bed.Marta.Id ? bed.Luca : bed.Marta; + var again = await bed.CopyAccountAsync(otherAccount, ct: ct); + Assert.AreEqual((0, 1), (again.Plan.Files, again.Plan.AlreadyCopied)); + Assert.AreEqual(ExportItemState.AlreadyCopied, (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().State); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + + // Back to «Una copia per account»: the other account would get its own. + await bed.SetSamePostAsync(SamePostCopies.OnePerAccount, ct); + Assert.AreEqual(1, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(otherAccount.Id)), ct)).Files); + await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct); + + // The one copy goes from the disk: the copier checks the file and writes the other account's copy after all. + var copiedAccount = otherAccount == bed.Marta ? bed.Luca : bed.Marta; + File.Delete(bed.GeneralCopy(copiedAccount, (copiedAccount == bed.Marta ? marta : luca).Media[0])); + var written = await bed.CopyAccountAsync(otherAccount, ct: ct); + Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(written.Runs.Single().Id, ct)).Single().State); + Assert.IsTrue(File.Exists(bed.GeneralCopy(otherAccount, (otherAccount == bed.Marta ? marta : luca).Media[0]))); + } + + [TestMethod] + public async Task AStoryAndItsHighlightAreOneCopy() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var story = await StoryInHighlightAsync(bed, "982", 62, ct); + var usb = await bed.GeneralAsync(ContentTypes.Stories | ContentTypes.Highlights, ct: ct); + + var started = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreEqual(1, started.Plan.Files); + var item = (await bed.ItemsAsync(started.Runs.Single().Id, ct)).Single(); + Assert.AreEqual(ExportItemState.Copied, item.State); + Assert.StartsWith("marta.demo/storie/", item.RelativePath!, "with «Storie» chosen it stays a story"); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + + // Asked again through the entry: already copied. + Assert.AreEqual(1, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([story.Entry.Id])), ct)).AlreadyCopied); + } + + [TestMethod] + public async Task AHighlightOnlyDestinationCopiesStoriesInHighlights() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var inHighlight = await StoryInHighlightAsync(bed, "983", 63, ct); + await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "984", Make.T0.AddHours(-2), EntryKind.Story), [ExportTestBed.Photo(1, 64)]); + await bed.GeneralAsync(ContentTypes.Highlights, ct: ct); + + var started = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreEqual((1, 1), (started.Plan.Files, started.Plan.NotExported)); + var item = (await bed.ItemsAsync(started.Runs.Single().Id, ct)).Single(i => i.State == ExportItemState.Copied); + Assert.AreEqual(inHighlight.Media[0].Id, item.MediaId); + Assert.StartsWith("marta.demo/evidenza/Estate/", item.RelativePath!); + var files = Fingerprint.Of(bed.Usb); + Assert.HasCount(1, files); + Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "marta.demo", "storie")), "a story outside highlights is not due"); + } + + private static async Task StoryInHighlightAsync(ExportTestBed bed, string code, int scene, CancellationToken ct) + { + var highlight = await bed.Db.Highlights.UpsertAsync(new Highlight { AccountId = bed.Marta.Id, InstagramId = "h" + code, Title = "Estate", DiscoveredAt = Make.T0 }, ct); + var story = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, code, Make.T0.AddHours(-1), EntryKind.Story), [ExportTestBed.Photo(1, scene)]); + await bed.Db.Highlights.AddItemAsync(highlight.Id, story.Entry.Id, ct); + return story; + } +} diff --git a/tests/Febe.Tests/Export/ExportServiceTests.cs b/tests/Febe.Tests/Export/ExportServiceTests.cs new file mode 100644 index 0000000..9c32149 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportServiceTests.cs @@ -0,0 +1,412 @@ +using System.Collections.Concurrent; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// The export job as the page drives it (spec §4.10, decisions D6, D10, D11 of tappa E2): one run per destination in +/// the background, «Interrompi», «Riprendi», «Annulla», the restart, the gate shared with the import and the rebuild, +/// the engine session, «Esporta questo account» and Docker without its mount. +/// +[TestClass] +public sealed class ExportServiceTests +{ + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30); + + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheJobRunsInTheBackgroundOneRunPerDestination() + { + var ct = TestContext.CancellationToken; + var held = new HeldExportFileSystem(SecondFile); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held }); + var marta = await bed.PostAsync(bed.Marta, "990", 70, 71); + var luca = await bed.PostAsync(bed.Luca, "991", 72); + var usb = await bed.GeneralAsync(ct: ct); + var own = await bed.OwnAsync(bed.Luca, "luca-nas", ct: ct); + var finished = new ConcurrentQueue(); + var progress = new ConcurrentQueue(); + bed.Service.JobFinished += (_, f) => finished.Enqueue(f); + bed.Service.ProgressChanged += (_, p) => progress.Enqueue(p); + + var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct); + CollectionAssert.AreEqual(new[] { usb.Id, own.Id }, start.Runs.Select(r => r.DestinationId).ToArray()); + Assert.AreEqual(3, start.Plan.Files); + Assert.HasCount(2, start.Plan.Destinations); + + // While it runs: busy, its runs, and a second «Copia in…» or «Controlla le copie» is refused. + await held.Reached.Task.WaitAsync(Patience, ct); + Assert.IsTrue(bed.Service.IsBusy); + CollectionAssert.AreEqual(start.Runs.Select(r => r.Id).ToArray(), bed.Service.ActiveRunIds.ToArray()); + var busy = await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Luca.Id)), ct)); + Assert.StartsWith("C'è già una copia al lavoro", busy.Message); + await Assert.ThrowsExactlyAsync(() => bed.Service.CheckCopiesAsync(usb.Id, ct)); + var now = await bed.Service.GetProgressAsync(ct); + Assert.AreEqual((start.Runs[0].Id, ExportPhase.Copying, "Disco USB"), (now.RunId, now.Phase, now.DestinationLabel)); + Assert.HasCount(2, await bed.Db.Exports.ListRunsAsync(ct)); + + held.Release(); + await bed.Service.WaitAsync(ct); + Assert.IsFalse(bed.Service.IsBusy); + Assert.IsEmpty(bed.Service.ActiveRunIds); + foreach (var run in start.Runs) + { + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + } + + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, marta.Media[1]))); + Assert.IsTrue(File.Exists(Path.Combine(own.RootPath, Core.Library.LibraryLayout.ToPlatform(luca.Media[0].RelativePath!)))); + Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "luca.demo")), "Luca's own folder replaces the general one"); + var job = finished.Single(); + CollectionAssert.AreEqual(start.Runs.Select(r => r.Id).ToArray(), job.RunIds.ToArray()); + Assert.IsTrue(progress.Any(p => p.Phase == ExportPhase.Finished)); + Assert.AreEqual(2, (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Count(e => e.Code == "esportazione-completata")); + var last = await bed.Service.GetProgressAsync(ct); + Assert.AreEqual((start.Runs[1].Id, ExportPhase.Finished), (last.RunId, last.Phase)); + } + + [TestMethod] + public async Task InterruptStopsAndKeepsWhatIsDoneAndResumeSkipsFinishedItems() + { + var ct = TestContext.CancellationToken; + var block = true; + var gated = new GatedExportFileSystem(p => Volatile.Read(ref block) && SecondFile(p)); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated }); + var post = await bed.PostAsync(bed.Marta, "992", 73, 74, 75); + await bed.GeneralAsync(ct: ct); + + var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + var runId = start.Runs.Single().Id; + await gated.Reached.Task.WaitAsync(Patience, ct); + await bed.Service.InterruptAsync(ct); + Assert.IsFalse(bed.Service.IsBusy); + + var run = await bed.RunAsync(runId, ct); + Assert.AreEqual((ExportRunState.Interrupted, null), (run.State, run.LastError)); + var items = (await bed.ItemsAsync(runId, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.AreEqual(ExportItemState.Copied, items[post.Media[0].Id].State); + Assert.AreEqual(ExportItemState.Pending, items[post.Media[1].Id].State); + Assert.AreEqual(ExportItemState.Pending, items[post.Media[2].Id].State); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[1]))); + Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(start.Runs[0].DestinationId, ct: ct)); + var first = File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0])); + Assert.HasCount(1, await bed.Db.Exports.ListUnfinishedRunsAsync(ct)); + + // «Riprendi»: only the pending items are worked on; the copied one is neither written again nor recorded twice. + Volatile.Write(ref block, false); + var resumed = await bed.Service.ResumeAsync(ct: ct); + Assert.AreEqual(runId, resumed.Single().Id); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(runId, ct)).State); + var after = (await bed.ItemsAsync(runId, ct)).ToDictionary(i => i.MediaId!.Value); + Assert.IsTrue(after.Values.All(i => i.State == ExportItemState.Copied)); + Assert.AreEqual(items[post.Media[0].Id].CopyId, after[post.Media[0].Id].CopyId); + Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(start.Runs[0].DestinationId, ct: ct)); + Assert.AreEqual(first, File.GetLastWriteTimeUtc(bed.GeneralCopy(bed.Marta, post.Media[0]))); + Assert.HasCount(3, Fingerprint.Of(bed.Usb)); + Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb)); + Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct)); + var done = await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync([runId], ct)); + Assert.Contains("già finito", done.Message); + } + + [TestMethod] + public async Task AJobLeftRunningByAStopIsRecoveredAsInterrupted() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "993", 76); + var usb = await bed.GeneralAsync(ct: ct); + + // Febe stopped while a job was running: the record still says «in corso». + var running = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Running, StartedAt = Make.T0 }, ct); + await bed.Db.Exports.AddItemsAsync([Pending(running.Id, post.Media[0], bed.Marta.Id)], ct); + var paused = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, State = ExportRunState.Paused, StartedAt = Make.T0, LastError = "Disco USB non è raggiungibile." }, ct); + + Assert.AreEqual(1, await bed.Service.RecoverAsync(ct)); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(running.Id, ct)).State); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(paused.Id, ct)).State); + Assert.IsFalse(bed.Service.IsBusy, "never resumes by itself"); + Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(running.Id, ct)).Single().State); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + Assert.AreEqual(0, await bed.Service.RecoverAsync(ct)); + await bed.Service.WaitAsync(ct); + + await bed.Service.ResumeAsync([running.Id], ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(running.Id, ct)).State); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(paused.Id, ct)).State); + } + + [TestMethod] + public async Task DiscardLeavesFilesAlone() + { + var ct = TestContext.CancellationToken; + var gated = new GatedExportFileSystem(SecondFile); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated }); + var post = await bed.PostAsync(bed.Marta, "994", 77, 78); + var usb = await bed.GeneralAsync(ct: ct); + await File.WriteAllTextAsync(Path.Combine(bed.Usb, "di Alberto.txt"), "non toccare", ct); + + var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + var runId = start.Runs.Single().Id; + await gated.Reached.Task.WaitAsync(Patience, ct); + + // «Annulla» of the running job interrupts it first. + await bed.Service.DiscardAsync(runId, ct); + await bed.Service.WaitAsync(ct); + Assert.IsFalse(bed.Service.IsBusy); + var run = await bed.RunAsync(runId, ct); + Assert.AreEqual(ExportRunState.Cancelled, run.State); + Assert.IsNotNull(run.CompletedAt); + var files = Fingerprint.Of(bed.Usb); + Assert.HasCount(2, files); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])), "the copies made stay"); + Assert.AreEqual("non toccare", await File.ReadAllTextAsync(Path.Combine(bed.Usb, "di Alberto.txt"), ct)); + Assert.IsEmpty(Fingerprint.Temporaries(bed.Usb)); + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().State); + Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct)); + + // Nothing to resume, and a second «Annulla» changes nothing. + await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync([runId], ct)); + await bed.Service.DiscardAsync(runId, ct); + Assert.AreEqual(run, await bed.RunAsync(runId, ct)); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "«Annulla» never removes a copy"); + await Assert.ThrowsExactlyAsync(() => bed.Service.DiscardAsync(runId + 100, ct)); + } + + [TestMethod] + public async Task ExportImportAndRebuildNeverRunTogether() + { + var ct = TestContext.CancellationToken; + var gated = new GatedExportFileSystem(SecondFile); + await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = gated }); + await bed.PostAsync(bed.Marta, "995", 79, 80); + var usb = await bed.GeneralAsync(ct: ct); + + // A copy holds the gate: the import and the rebuild wait. + await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + await gated.Reached.Task.WaitAsync(Patience, ct); + Assert.AreEqual(LongWorkKind.Export, bed.Gate.Busy); + Assert.IsFalse(bed.Gate.TryEnter(LongWorkKind.Import, out _, out var holder)); + Assert.AreEqual(LongWorkKind.Export, holder); + Assert.IsFalse(bed.Gate.TryEnter(LongWorkKind.Rebuild, out _, out _)); + Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export)); + await bed.Service.InterruptAsync(ct); + Assert.IsNull(bed.Gate.Busy, "the gate is given back however the job ends"); + + // A rebuild holds it: no copy starts, resumes or checks, and nothing is recorded. + var runs = await bed.Db.Exports.ListRunsAsync(ct); + Assert.IsTrue(bed.Gate.TryEnter(LongWorkKind.Rebuild, out var lease, out _)); + using (lease) + { + var expected = LongWorkGate.BusyMessage(LongWorkKind.Export, LongWorkKind.Rebuild); + Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct))).Message); + Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync(() => bed.Service.ResumeAsync(ct: ct))).Message); + Assert.AreEqual(expected, (await Assert.ThrowsExactlyAsync(() => bed.Service.CheckCopiesAsync(usb.Id, ct))).Message); + Assert.IsFalse(bed.Service.IsBusy); + CollectionAssert.AreEqual(runs.ToArray(), (await bed.Db.Exports.ListRunsAsync(ct)).ToArray()); + var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct); + Assert.IsNull(retry.Problem); + Assert.IsEmpty(retry.Resumed, "with other long work running the paused jobs wait for «Riprendi»"); + } + + Assert.IsNull(bed.Gate.Busy); + } + + [TestMethod] + public async Task NoCopyDuringAnEngineSession() + { + var ct = TestContext.CancellationToken; + WaitingClock? clock = null; + await using var bed = await ExportTestBed.CreateAsync(env => env with { Clock = clock = new WaitingClock(env.Clock) }); + var post = await bed.PostAsync(bed.Marta, "996", 81); + await bed.GeneralAsync(ct: ct); + bed.Session.InSession = true; + var before = bed.Clock.Now; + + var start = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + var waiting = await PollAsync(bed, p => p.Phase == ExportPhase.WaitingForSession, ct); + Assert.AreEqual(start.Runs.Single().Id, waiting.RunId); + await PollUntilAsync(() => clock!.Delays >= 3, ct); + Assert.IsTrue(bed.Service.IsBusy); + Assert.IsEmpty(Fingerprint.Of(bed.Usb), "nothing is written while the engine works"); + Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(start.Runs[0].Id, ct)).Single().State); + + bed.Session.InSession = false; + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(start.Runs[0].Id, ct)).State); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + var waited = bed.Clock.Now - before; + Assert.AreEqual(0, waited.Ticks % TimeSpan.FromSeconds(5).Ticks, "the wait goes by polls of 5 s on the clock"); + Assert.IsGreaterThanOrEqualTo(TimeSpan.FromSeconds(15), waited); + } + + [TestMethod] + public async Task TheSwitchOffSkipsTheAccount() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var marta = await bed.PostAsync(bed.Marta, "997", 82, 83); + var luca = await bed.PostAsync(bed.Luca, "998", 84); + await bed.GeneralAsync(ct: ct); + var own = await bed.OwnAsync(bed.Marta, "marta-nas", ct: ct); + await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct); + + // Even a manual «Copia in…» of her entry skips her files (decision Q1), in her own folder too. + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id])), ct); + Assert.AreEqual((0, 2), (plan.Files, plan.NotExported)); + var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Entries([marta.Entry.Id, luca.Entry.Id])), ct); + Assert.AreEqual((1, 2), (start.Plan.Files, start.Plan.NotExported)); + Assert.IsTrue(start.Runs.All(r => r.DestinationId != own.Id)); + Assert.IsEmpty(Fingerprint.Of(own.RootPath)); + Assert.IsFalse(Directory.Exists(Path.Combine(bed.Usb, "marta.demo"))); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Luca, luca.Media[0]))); + Assert.IsEmpty((await bed.CopyAccountAsync(bed.Marta, ct: ct)).Runs); + + // Switched on again, her files are due. + await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct); + Assert.AreEqual(2, (await bed.CopyAccountAsync(bed.Marta, ct: ct)).Plan.Files); + Assert.HasCount(2, Fingerprint.Of(own.RootPath)); + await Assert.ThrowsExactlyAsync(() => bed.Service.Destinations.SetAccountEnabledAsync(9999, false, ct)); + } + + [TestMethod] + public async Task PlanCountsFilesAlreadyCopiedRemovedAndBytes() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "999", 85, 86, 87); + await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "1000", Make.T0.AddDays(-2), EntryKind.Tagged), [ExportTestBed.Photo(1, 88)]); + var waiting = await bed.Db.Entries.AddAsync(Make.Entry(bed.Marta.Id, "1001", Make.T0.AddDays(-3)), [Make.Photo(1)], ct); // never downloaded + var usb = await bed.GeneralAsync(ContentTypes.All & ~ContentTypes.Tagged, ct: ct); + await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id, post.Media[1].Id])), ct); + File.Delete(bed.GeneralCopy(bed.Marta, post.Media[1])); + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + bed.Disk.Free = 123_456_789; + + var request = new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)); + var plan = await bed.Service.PlanAsync(request, ct); + var third = new FileInfo(bed.LibraryFile(bed.Marta, post.Media[2])).Length; + // The account card counts the files of the library: an entry still to download is not one of them. + Assert.AreEqual((1, third, 1, 1, 1, 0), (plan.Files, plan.Bytes, plan.AlreadyCopied, plan.RemovedOrSuperseded, plan.NotExported, plan.Missing)); + var asked = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Entries([waiting.Stored.Entry.Id])), ct); + Assert.AreEqual((0, 1), (asked.Files, asked.Missing)); // asked for by itself, it is «non presente in libreria» + var destination = plan.Destinations.Single(); + Assert.AreEqual((usb.Id, "Disco USB", ExportScope.General, (string?)null, 1, third, false, (string?)null, (long?)123_456_789), + (destination.DestinationId, destination.Label, destination.Scope, destination.Username, destination.Files, destination.Bytes, destination.Paused, destination.Problem, destination.FreeBytes)); + + // With «Copia di nuovo» the removed one is counted among the files to write too. + var again = await bed.Service.PlanAsync(request with { CopyAgain = true }, ct); + var second = new FileInfo(bed.LibraryFile(bed.Marta, post.Media[1])).Length; + Assert.AreEqual((2, third + second, 1, 1), (again.Files, again.Bytes, again.AlreadyCopied, again.RemovedOrSuperseded)); + + // The plan is database only: it records and writes nothing. + Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + + // Only files not exported or not in the library: no job is recorded and nothing starts. + var tagged = (await bed.Db.Exports.ListCandidatesAsync(request.Selection, 0, 100, ct)).Single(c => c.EntryKind == EntryKind.Tagged); + var nothing = await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Media([tagged.MediaId, waiting.Stored.Media[0].Id])), ct); + Assert.IsEmpty(nothing.Runs); + Assert.AreEqual((1, 1), (nothing.Plan.NotExported, nothing.Plan.Missing)); + Assert.IsFalse(bed.Service.IsBusy); + Assert.HasCount(1, await bed.Db.Exports.ListRunsAsync(ct)); + + // An already copied file still makes a job, for its report: «Già copiato», and nothing written. + var copied = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id])), ct); + Assert.AreEqual(ExportItemState.AlreadyCopied, (await bed.ItemsAsync(copied.Runs.Single().Id, ct)).Single().State); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + [DataRow(true, DisplayName = "dichiarato, senza montaggio")] + [DataRow(false, DisplayName = "non dichiarato")] + public async Task DockerNotMountedWritesNothing(bool declared) + { + var ct = TestContext.CancellationToken; + string? root = null; + await using var bed = await ExportTestBed.CreateAsync(env => + { + root = Path.Combine(Path.GetDirectoryName(env.DataFolder)!, "esporta"); + return env with { Root = ExportRootOptions.Docker(root, declared, new FixedMounts()) with { ShownAs = "/esporta" } }; + }); + var usb = Path.Combine(root!, "usb"); + Directory.CreateDirectory(usb); + await File.WriteAllTextAsync(Path.Combine(usb, "già qui.txt"), "di Alberto", ct); + var files = Fingerprint.Of(root!); + await bed.PostAsync(bed.Marta, "1002", 89); + + // A destination recorded when the folder was mounted; now the container runs without it. + var destination = await bed.Db.Exports.AddDestinationAsync(Data.ExportWorld.Destination(ExportScope.General, null, usb), ct); + var state = ExportRoots.Evaluate(bed.Environment.Root); + Assert.IsFalse(state.Active); + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.IsNotNull(plan.Destinations.Single().Problem); + + var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State); + Assert.AreEqual(state.Problem, run.LastError); + Assert.AreEqual(declared, run.LastError != ExportRoots.NotDeclaredText); + Assert.AreEqual(ExportItemState.Pending, (await bed.ItemsAsync(run.Id, ct)).Single().State); + Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(destination.Id, ct))!.PausedAt); + Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(destination.Id, ct: ct)); + Fingerprint.AreEqual(files, Fingerprint.Of(root!), "not a byte in /esporta, not even the probe file"); + + // «Controlla le copie» and «Riprova» write nothing either. + Assert.IsNotNull((await bed.Service.RetryDestinationAsync(destination.Id, ct)).Problem); + await bed.Service.CheckCopiesAsync(destination.Id, ct); + await bed.Service.WaitAsync(ct); + Fingerprint.AreEqual(files, Fingerprint.Of(root!), "the checks write nothing"); + Assert.AreEqual(ExportRunState.Paused, (await bed.RunAsync(run.Id, ct)).State); + } + + private static bool SecondFile(string path) => path.EndsWith("_2.jpg", StringComparison.Ordinal); + + private static ExportItem Pending(long runId, Media media, long accountId) => new() + { + RunId = runId, + MediaId = media.Id, + AccountId = accountId, + SourceSha256 = media.Sha256, + Variant = ExportVariant.Whole, + Format = ExportFormat.Original, + State = ExportItemState.Pending, + }; + + private async Task PollAsync(ExportTestBed bed, Func until, CancellationToken ct) + { + var deadline = DateTime.UtcNow + Patience; + while (true) + { + var progress = await bed.Service.GetProgressAsync(ct); + if (until(progress)) + { + return progress; + } + + Assert.IsLessThan(deadline, DateTime.UtcNow, $"never reached; last phase {progress.Phase}"); + await Task.Delay(10, ct); + } + } + + private static async Task PollUntilAsync(Func until, CancellationToken ct) + { + var deadline = DateTime.UtcNow + Patience; + while (!until()) + { + Assert.IsLessThan(deadline, DateTime.UtcNow, "never reached"); + await Task.Delay(10, ct); + } + } +} diff --git a/tests/Febe.Tests/Export/ExportStatesTests.cs b/tests/Febe.Tests/Export/ExportStatesTests.cs new file mode 100644 index 0000000..ace9b47 --- /dev/null +++ b/tests/Febe.Tests/Export/ExportStatesTests.cs @@ -0,0 +1,288 @@ +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Import; +using Febe.Core.Library; +using Febe.Tests.Export.Support; +using Febe.Tests.Import.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Export; + +/// +/// «Tolto» and «Superato» (spec §4.10 l.304, §14.1; decision D9 of tappa E2): a copy whose file went from the +/// destination, or whose library file changed, is never copied again by itself, only with «Copia di nuovo», and the old +/// files always stay where they are. +/// +[TestClass] +public sealed class ExportStatesTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task RemovedIsRecopiedOnlyWithCopyAgain() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "970", 41); + var usb = await bed.GeneralAsync(ct: ct); + var first = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var oldCopy = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value; + File.Delete(bed.GeneralCopy(bed.Marta, post.Media[0])); + + // The next «Copia in…» finds it gone: «Tolto», skipped, not written. + var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.AreEqual(ExportItemState.Skipped, (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single().State); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(oldCopy, ct))!.State); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 0, 1, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)); + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + Assert.IsEmpty(Fingerprint.Of(bed.Usb), "a second «Copia in…» still writes nothing"); + + // «Copia di nuovo»: a new row, the old one stays «Tolto» in the history. + var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct); + Assert.AreEqual((1, 1), (again.Plan.Files, again.Plan.RemovedOrSuperseded)); + var newCopy = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().CopyId!.Value; + Assert.AreNotEqual(oldCopy, newCopy); + Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(oldCopy, ct))!.State); + Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(newCopy, ct))!.State); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0]))); + Assert.HasCount(2, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + Assert.AreEqual(new Core.Storage.ExportAccountCounts(1, 0, 0, 0), await bed.Db.Exports.CountAccountFilesAsync(bed.Marta.Id, ct)); + } + + [TestMethod] + public async Task ReplacingTheLibraryFileSupersedesTheCopy() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var (marta, library) = await bed.AccountWithPhotoAsync("marta.demo", "60", ImportTestFiles.Resized(60, 800, 600, 400, 300, 70)); + var usb = temp.Combine("usb"); + Directory.CreateDirectory(usb); + await using var export = new ExportService(Environment(bed.Library)); + await export.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, usb, null, ContentTypes.All, null, null, null), ct); + await export.StartAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id)), ct); + await export.WaitAsync(ct); + var copy = (await bed.Library.Db.Exports.ListCopiesBySha256Async(library.Media[0].Sha256!, ct)).Single(); + var files = Fingerprint.Of(usb); + + // An import brings the original, larger: «Tieni il più grande» replaces the library file. + var largest = ImportTestFiles.Photo(60, 800, 600, 92); + bed.Write("marta.demo/originale.jpg", largest); + var run = await bed.AnalyzeAsync(); + var pair = (await bed.Review.ListDuplicatesAsync(run.Id, ct: ct)).Single(); + await bed.Review.DecideAsync(run.Id, pair.Pair.Id, DuplicateDecision.KeepLarger, ct: ct); + await bed.Copier.CopyAsync(run.Id, ct: ct); + + var media = (await bed.Library.Db.Media.GetAsync(library.Media[0].Id, ct))!; + Assert.AreNotEqual(copy.SourceSha256, media.Sha256); + var superseded = (await bed.Library.Db.Exports.GetCopyAsync(copy.Id, ct))!; + Assert.AreEqual((ExportCopyState.Superseded, media.Sha256), (superseded.State, superseded.SupersededBySha256)); + Fingerprint.AreEqual(files, Fingerprint.Of(usb), "the old copy stays, untouched"); + + // Never copied again by itself; «Copia di nuovo» writes the new file beside the old one. + var plan = await export.PlanAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id)), ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); + await export.StartAsync(new ExportJobRequest(new ExportSelection.Account(marta.Id), CopyAgain: true), ct); + await export.WaitAsync(ct); + var after = Fingerprint.Of(usb); + Assert.HasCount(2, after); + foreach (var (path, print) in files) + { + Assert.AreEqual(print, after[path], path); + } + + Assert.AreEqual(ExportCopyState.Superseded, (await bed.Library.Db.Exports.GetCopyAsync(copy.Id, ct))!.State); + } + + [TestMethod] + public async Task KeepLargerAfterADownloadSupersedes() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var small = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "971", Make.T0.AddDays(-3)), [TestFile.Photo(1, 42, 360, 450)]); + var usb = await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + var files = Fingerprint.Of(bed.Usb); + + // The same picture comes again, larger, in another post: «Tieni il più grande». + var large = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "972", Make.T0), [TestFile.Photo(1, 42, 720, 900)]); + var lib = bed.Library; + var review = new DownloadDuplicateReview(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index); + var pair = (await review.ListAsync(ct: ct)).Single(c => c.Candidate.MediaId == large.Media[0].Id); + Assert.AreEqual(small.Media[0].Id, pair.Existing.MediaId); + Assert.AreEqual(1, (await review.DecideAsync(pair.Pair.Id, DuplicateDecision.KeepLarger, ct: ct)).FilesRemoved); + + var superseded = (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!; + Assert.AreEqual((ExportCopyState.Superseded, large.Media[0].Sha256), (superseded.State, superseded.SupersededBySha256)); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the copy of the smaller file stays"); + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded)); // the larger file is «tolto o superato», never copied by itself + } + + [TestMethod] + public async Task ARefilledSlotAfterRebuildSupersedes() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "973", 43); + await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var oldSha = post.Media[0].Sha256!; + + // After a rebuild the file is to download again, the journal's SHA-256 kept; the download brings other bytes. + File.Delete(bed.LibraryFile(bed.Marta, post.Media[0])); + await bed.Db.Media.UpdateAsync(post.Media[0] with { State = MediaState.ToDownload, RelativePath = null }, ct); + var media = (await bed.Db.Media.GetAsync(post.Media[0].Id, ct))!; + Assert.AreEqual(oldSha, media.Sha256); + var other = ExportTestBed.Photo(1, 44); + var saved = await bed.Library.Ingest.SaveMediaAsync(bed.Marta, post.Entry, media, new MediaContent { Content = new MemoryStream(other.Bytes), Extension = ".jpg" }, ct: ct); + Assert.AreEqual(MediaSaveOutcome.Stored, saved.Outcome); + + var copy = (await bed.Db.Exports.ListCopiesBySha256Async(oldSha, ct)).Single(); + Assert.AreEqual((ExportCopyState.Superseded, saved.File!.Sha256), (copy.State, copy.SupersededBySha256)); + Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])), "the old copy stays"); + } + + [TestMethod] + public async Task SupersededIsNotRecopiedByItselfButCopyAgainWritesANewFile() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "974", 45); + var usb = await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + var oldFile = bed.GeneralCopy(bed.Marta, post.Media[0]); + var oldBytes = await File.ReadAllBytesAsync(oldFile, ct); + + // The library file changes in place (same path, other bytes), as a replacement does. + var newBytes = ExportTestBed.Photo(1, 46).Bytes; + var library = bed.LibraryFile(bed.Marta, post.Media[0]); + await File.WriteAllBytesAsync(library, newBytes, ct); + var newSha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(newBytes)); + await bed.Db.Media.MarkStoredAsync(post.Media[0].Id, new StoredFile(post.Media[0].RelativePath!, newBytes.Length, newSha, null, 96, 120, null, false), MediaState.Downloaded, bed.Clock.Now, ct); + Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(bed.Db, bed.Marta.Id, post.Media[0].Sha256, newSha, bed.Clock.Now, ct)); + + // By itself: skipped as «Superato», nothing written. + var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct); + var item = (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Superseded, copy.Id), (item.State, item.Note, item.CopyId)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + + // «Copia di nuovo»: the new file goes beside the old one, which is never overwritten. + var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct); + var written = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.NameTaken), (written.State, written.Note)); + CollectionAssert.AreEqual(oldBytes, await File.ReadAllBytesAsync(oldFile, ct)); + CollectionAssert.AreEqual(newBytes, await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(written.RelativePath!)), ct)); + Assert.AreEqual(ExportCopyState.Superseded, (await bed.Db.Exports.GetCopyAsync(copy.Id, ct))!.State); + Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).RemovedOrSuperseded); + } + + [TestMethod] + public async Task SupersessionWaitsWhileAnotherPresentFileHasTheOldSha() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var db = await TestDatabase.OpenAsync(temp); + var w = await Data.ExportWorld.CreateAsync(db); + // A second post of marta.demo with the same bytes as her first (for instance a story and its highlight). + var twin = await db.Entries.AddAsync(Make.Entry(w.Marta, "556", Make.T0), [Make.Stored(Make.Photo(), Make.Sha(1), "post/twin.jpg")], ct); + var copy = await db.Exports.AddCopyAsync(w.WholeCopy("marta.demo/a.jpg"), ct); + var luca = await db.Exports.AddCopyAsync(w.WholeCopy("luca.demo/a.jpg", account: w.Luca, media: w.LucaMedia), ct); + + // The first file changes: the twin still has the old bytes, so the copy is still of a file of the library. + await db.Media.MarkStoredAsync(w.MartaMedia, new StoredFile("post/a.jpg", 2000, Make.Sha(7), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct); + Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(1), Make.Sha(7), Make.T0, ct)); + Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(copy.Id, ct))!.State); + + // The twin changes too: now the copy is superseded, and only marta's (luca.demo still has the old file). + await db.Media.MarkStoredAsync(twin.Stored.Media[0].Id, new StoredFile("post/twin.jpg", 2000, Make.Sha(8), null, 1, 1, null, false), MediaState.Downloaded, Make.T0, ct); + Assert.AreEqual(1, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(1), Make.Sha(8), Make.T0, ct)); + Assert.AreEqual((ExportCopyState.Superseded, Make.Sha(8)), ((await db.Exports.GetCopyAsync(copy.Id, ct))!.State, (await db.Exports.GetCopyAsync(copy.Id, ct))!.SupersededBySha256)); + Assert.AreEqual(ExportCopyState.Copied, (await db.Exports.GetCopyAsync(luca.Id, ct))!.State); + + // Nothing to do without an old file, or when nothing changed. + Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, null, Make.Sha(8), Make.T0, ct)); + Assert.AreEqual(0, await ExportSupersession.FileChangedAsync(db, w.Marta, Make.Sha(8), Make.Sha(8).ToUpperInvariant(), Make.T0, ct)); + } + + [TestMethod] + public async Task CheckCopiesMarksMissingFilesRemoved() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "975", 47, 48, 49); + var usb = await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copies = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).ToDictionary(c => c.MediaId!.Value); + await bed.Db.Exports.UpdateCopyAsync(copies[post.Media[2].Id] with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(99) }, ct); + File.Delete(bed.GeneralCopy(bed.Marta, post.Media[0])); + File.Delete(bed.GeneralCopy(bed.Marta, post.Media[2])); + var files = Fingerprint.Of(bed.Usb); + + // The disk is unplugged first: nothing becomes «Tolto», the folder pauses. + Directory.Move(bed.Usb, bed.Temp.Combine("staccato")); + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + Assert.IsTrue((await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).All(c => c.State != ExportCopyState.Removed)); + Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + Assert.IsFalse(Directory.Exists(bed.Usb)); + + Directory.Move(bed.Temp.Combine("staccato"), bed.Usb); + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + var after = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).ToDictionary(c => c.MediaId!.Value); + Assert.AreEqual(ExportCopyState.Removed, after[post.Media[0].Id].State); + Assert.AreEqual(ExportCopyState.Copied, after[post.Media[1].Id].State); + Assert.AreEqual(ExportCopyState.Removed, after[post.Media[2].Id].State); + Assert.AreEqual(Make.Sha(99), after[post.Media[2].Id].SupersededBySha256); + Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt); + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the check never touches a file"); + var check = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).First(e => e.Code == "esportazione-controllo"); + Assert.AreEqual(EventSeverity.Warning, check.Severity); + Assert.IsEmpty(await bed.Db.Exports.ListUnfinishedRunsAsync(ct)); + + // Idempotent. + await bed.Service.CheckCopiesAsync(usb.Id, ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, ct: ct)).Count); + } + + [TestMethod] + public async Task DeletingAnEntryLeavesItsCopies() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var post = await bed.PostAsync(bed.Marta, "976", 50); + var usb = await bed.GeneralAsync(ct: ct); + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var files = Fingerprint.Of(bed.Usb); + var lib = bed.Library; + + var deleted = await new LibraryDeletion(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index).DeleteAsync(post.Entry.Id, ct: ct); + Assert.IsTrue(deleted.Complete); + Assert.IsFalse(File.Exists(bed.LibraryFile(bed.Marta, post.Media[0]))); + + Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the copy outside is Alberto's"); + var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + Assert.AreEqual(ExportCopyState.Copied, copy.State); + Assert.AreEqual(post.Media[0].Sha256, copy.SourceSha256); + var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct); + Assert.AreEqual((0, 0, 0), (plan.Files, plan.AlreadyCopied, plan.Missing)); // a deleted entry is not a candidate + } + + private static ExportEnvironment Environment(TestLibrary library) => new() + { + Storage = library.Db, + Layout = () => library.Layout, + DataFolder = library.Data.Root, + Clock = library.Clock, + Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() }, + Disk = new FakeExportDisk(), + }; +} diff --git a/tests/Febe.Tests/Export/MountInfoTests.cs b/tests/Febe.Tests/Export/MountInfoTests.cs new file mode 100644 index 0000000..9ceab48 --- /dev/null +++ b/tests/Febe.Tests/Export/MountInfoTests.cs @@ -0,0 +1,92 @@ +using Febe.Core.Export; +using Febe.Core.Library; + +namespace Febe.Tests.Export; + +/// +/// /proc/self/mountinfo as the export reads it (spec §4.10 «Docker e Windows», decision D14 of tappa E2). The +/// content is always given by the test: nothing reads the mounts of the machine that runs the tests. +/// +[TestClass] +public sealed class MountInfoTests +{ + [TestMethod] + public void ParsesMountPointRootTypeAndOptionsWithOptionalFields() + { + const string content = """ + 22 1 8:1 / / rw,relatime shared:1 - ext4 /dev/sda1 rw,errors=remount-ro + 40 22 8:17 /backup/foto /esporta/usb rw,noatime master:3 propagate_from:2 - vfat /dev/sdb1 rw,fmask=0022 + 41 22 0:50 / /esporta/nas ro,relatime - cifs //nas/copie rw,vers=3.0 + """; + var mounts = MountInfoTable.Parse(content); + Assert.HasCount(3, mounts); + + var usb = mounts[1]; + Assert.AreEqual((40, 22), (usb.Id, usb.ParentId)); + Assert.AreEqual("/backup/foto", usb.Root); + Assert.AreEqual("/esporta/usb", usb.MountPoint); + CollectionAssert.AreEqual(new[] { "rw", "noatime" }, usb.Options.ToArray()); + Assert.AreEqual("vfat", usb.FileSystemType); // after the optional fields and their separator «-» + Assert.AreEqual("/dev/sdb1", usb.Source); + Assert.IsFalse(usb.ReadOnly); + + Assert.AreEqual("ext4", mounts[0].FileSystemType); + Assert.AreEqual("//nas/copie", mounts[2].Source); + Assert.IsTrue(mounts[2].ReadOnly); // the per-mount options say ro, the super options say rw + } + + [TestMethod] + public void UnescapesSpacesAndTabsInPaths() + { + var mounts = MountInfoTable.Parse(@"50 22 8:33 /foto\040di\011Marta /esporta/disco\040usb rw - ext4 /dev/sdc\0401 rw"); + Assert.AreEqual("/foto di\tMarta", mounts.Single().Root); + Assert.AreEqual("/esporta/disco usb", mounts[0].MountPoint); + Assert.AreEqual("/dev/sdc 1", mounts[0].Source); + Assert.AreEqual("/esporta/disco usb", MountInfoTable.FindContaining(mounts, "/esporta/disco usb/Febe")!.MountPoint); + } + + [TestMethod] + public void SkipsMalformedLines() + { + const string content = """ + + riga senza senso + 22 1 8:1 / / rw - ext4 /dev/sda1 rw + x 1 8:1 / /a rw - ext4 /dev/sda2 rw + 23 y 8:1 / /b rw - ext4 /dev/sda3 rw + 24 1 8:1 / /c rw shared:1 ext4 /dev/sda4 rw extra + 25 1 8:1 / /d rw - + 26 1 8:1 relativa /e rw - ext4 /dev/sda6 rw + 27 1 8:1 / relativo rw - ext4 /dev/sda7 rw + 28 1 8:1 / /f rw + """; + var mounts = MountInfoTable.Parse(content.Replace("\n", "\r\n", StringComparison.Ordinal)); + Assert.AreEqual("/", mounts.Single().MountPoint); + Assert.IsEmpty(MountInfoTable.Parse(string.Empty)); + Assert.IsEmpty(new ProcMountInfo(() => null).All()); + Assert.IsNull(new ProcMountInfo(() => throw new IOException("letto male")).FindContaining("/esporta/usb")); + } + + [TestMethod] + public void FindsTheLongestMountContainingAPath() + { + const string content = """ + 22 1 8:1 / / rw - ext4 /dev/sda1 rw + 40 22 8:17 / /esporta rw - ext4 /dev/sdb1 rw + 41 40 8:33 / /esporta/usb rw - vfat /dev/sdc1 rw + 42 40 8:49 / /esporta/usb rw - exfat /dev/sdd1 rw + """; + var mounts = MountInfoTable.Parse(content); + Assert.AreEqual("exfat", MountInfoTable.FindContaining(mounts, "/esporta/usb/Febe/marta.demo")!.FileSystemType); // the last mount over a point wins + Assert.AreEqual("exfat", MountInfoTable.FindContaining(mounts, "/esporta/usb/")!.FileSystemType); + Assert.AreEqual("/esporta", MountInfoTable.FindContaining(mounts, "/esporta/usbx")!.MountPoint); // not a prefix of a segment + Assert.AreEqual("/esporta", MountInfoTable.FindContaining(mounts, "/esporta")!.MountPoint); + Assert.AreEqual("/", MountInfoTable.FindContaining(mounts, "/dati")!.MountPoint); + Assert.IsNull(MountInfoTable.FindContaining([], "/esporta")); + + var proc = new ProcMountInfo(() => content); + Assert.AreEqual(new ExportMount("/esporta/usb", "/", "exfat", false, "8:49"), proc.FindContaining("/esporta/usb/a")); + Assert.AreEqual("8:17", MountInfoTable.FindContaining(mounts, "/esporta")!.Device); // the device, for the identity test + Assert.HasCount(4, proc.All()); + } +} diff --git a/tests/Febe.Tests/Export/Support/ExportTestBed.cs b/tests/Febe.Tests/Export/Support/ExportTestBed.cs new file mode 100644 index 0000000..853bcfb --- /dev/null +++ b/tests/Febe.Tests/Export/Support/ExportTestBed.cs @@ -0,0 +1,405 @@ +using System.Security.Cryptography; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Data; +using Febe.Tests.Support; + +namespace Febe.Tests.Export.Support; + +/// +/// A real library (database, account folders, files saved as the collection pipeline saves them) in a temporary +/// folder, two accounts, a real destination folder «usb» next to it and the export service with fakes for the disk, +/// the engine session and the mount table (tappa E2, WP5). Nothing outside the temporary folder is ever touched. +/// +internal sealed class ExportTestBed : IAsyncDisposable +{ + private ExportTestBed(TempFolder temp, TestLibrary library, ExportEnvironment env, Account marta, Account luca, FakeExportDisk disk, FakeSessionState session, LongWorkGate gate) + { + Temp = temp; + Library = library; + Environment = env; + Service = new ExportService(env); + Marta = marta; + Luca = luca; + Disk = disk; + Session = session; + Gate = gate; + } + + public TempFolder Temp { get; } + + public TestLibrary Library { get; } + + public FebeDatabase Db => Library.Db; + + public ManualClock Clock => Library.Clock; + + public ExportEnvironment Environment { get; } + + public ExportService Service { get; } + + public Account Marta { get; } + + public Account Luca { get; } + + public FakeExportDisk Disk { get; } + + public FakeSessionState Session { get; } + + public LongWorkGate Gate { get; } + + /// The folder of the general destination (created, empty). + public string Usb => Temp.Combine("usb"); + + /// + /// A new bed. changes the environment (a file system seam, a Docker root…) before the + /// service is built. + /// + public static async Task CreateAsync(Func? configure = null) + { + var temp = new TempFolder("export"); + var library = await TestLibrary.CreateAsync(temp); + var marta = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + var luca = await library.Db.Accounts.AddAsync(Make.Account("luca.demo", "200")); + Directory.CreateDirectory(temp.Combine("usb")); + var disk = new FakeExportDisk(); + var session = new FakeSessionState(); + var gate = new LongWorkGate(); + var env = new ExportEnvironment + { + Storage = library.Db, + Layout = () => library.Layout, + DataFolder = library.Data.Root, + Clock = library.Clock, + Root = ExportRootOptions.AnyFolder with { Mounts = new FixedMounts() }, + Disk = disk, + Session = session, + Gate = gate, + }; + return new ExportTestBed(temp, library, configure is null ? env : configure(env), marta, luca, disk, session, gate); + } + + /// The general folder at (or another folder), every type unless told. + public async Task GeneralAsync(ContentTypes types = ContentTypes.All, string? folder = null, string? scheme = null, CancellationToken ct = default) => + (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, folder ?? Usb, "Disco USB", types, scheme, null, null), ct)).Destination; + + /// The own folder of an account, created under the temporary folder. + public async Task OwnAsync(Account account, string name, ContentTypes types = ContentTypes.All, CancellationToken ct = default) + { + var folder = Temp.Combine(name); + Directory.CreateDirectory(folder); + return (await Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.Account, account.Id, folder, null, types, null, null, null), ct)).Destination; + } + + /// A post of the account with small photos (distinct scenes give distinct bytes; the same scene the same bytes). + public Task PostAsync(Account account, string code, params int[] scenes) => + Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [.. scenes.Select((s, i) => Photo(i + 1, s))]); + + /// A small photo (fast to encode). + public static TestFile Photo(int position, int scene) => TestFile.Photo(position, scene, 96, 120); + + /// «Copia in…» and waits for the job to end. + public async Task CopyAsync(ExportJobRequest request, CancellationToken ct = default) + { + var start = await Service.StartAsync(request, ct); + await Service.WaitAsync(ct); + return start; + } + + /// «Copia in…» of every file of an account. + public Task CopyAccountAsync(Account account, bool copyAgain = false, CancellationToken ct = default) => + CopyAsync(new ExportJobRequest(new ExportSelection.Account(account.Id), copyAgain), ct); + + public async Task> ItemsAsync(long runId, CancellationToken ct = default) => + await Db.Exports.ListItemsAsync(new ExportItemQuery { RunId = runId, Limit = 10_000 }, ct); + + public async Task RunAsync(long runId, CancellationToken ct = default) => (await Db.Exports.GetRunAsync(runId, ct))!; + + /// Where a file of the account goes in the general folder «Come la libreria». + public string GeneralCopy(Account account, Media media) => Path.Combine(Usb, account.Username, LibraryLayout.ToPlatform(media.RelativePath!)); + + /// The library file. + public string LibraryFile(Account account, Media media) => Library.Layout.FullPath(account, media.RelativePath!); + + public Task SetSamePostAsync(SamePostCopies value, CancellationToken ct = default) => (ExportSettings.Default with { SamePost = value }).SaveAsync(Db.Settings, ct); + + public async ValueTask DisposeAsync() + { + await Service.DisposeAsync(); + await Library.DisposeAsync(); + Temp.Dispose(); + } +} + +/// A disk with settable free space and largest file (null: not measurable, no limit). +internal sealed class FakeExportDisk(long? free = null, long? max = null) : IExportDisk +{ + public long? Free { get; set; } = free; + + public long? Max { get; set; } = max; + + public long? FreeBytes(string root) => Free; + + public long? MaxFileBytes(string root) => Max; +} + +/// An engine session that the test starts and ends. +internal sealed class FakeSessionState : IEngineSessionState +{ + private volatile bool _inSession; + + public bool InSession + { + get => _inSession; + set => _inSession = value; + } +} + +/// A clock whose delays really pass a little (so a waiting loop does not spin) and move the time on. +internal sealed class WaitingClock(IClock inner) : IClock +{ + private long _delays; + + public DateTimeOffset Now => inner.Now; + + public TimeZoneInfo LocalZone => inner.LocalZone; + + /// How many delays were asked. + public long Delays => Interlocked.Read(ref _delays); + + public async Task Delay(TimeSpan time, CancellationToken ct) + { + Interlocked.Increment(ref _delays); + await inner.Delay(time, ct); + await Task.Delay(5, ct); + } +} + +/// A mount table given by the test, on any platform (the longest mount point that holds the path wins). +internal sealed class FixedMounts(params ExportMount[] mounts) : IExportMounts +{ + public ExportMount? FindContaining(string fullPath) => + mounts.Where(m => ExportPaths.IsSameOrInside(fullPath, m.MountPoint)).OrderByDescending(m => ExportPaths.Trim(m.MountPoint).Length).FirstOrDefault(); + + public IReadOnlyList All() => mounts; +} + +/// The real file system, but the first read of a blocked file never ends until the job is cancelled. +internal sealed class GatedExportFileSystem(Func blocks) : IExportFileSystem +{ + private readonly IExportFileSystem _inner = ExportFileSystem.Instance; + + /// Set when a blocked file is opened. + public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public Stream OpenRead(string path) + { + var stream = _inner.OpenRead(path); + if (!blocks(path)) + { + return stream; + } + + Reached.TrySetResult(); + return new BlockedStream(stream); + } + + public Task ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct); + + public bool FileExists(string path) => _inner.FileExists(path); + + public long? FileLength(string path) => _inner.FileLength(path); + + private sealed class BlockedStream(Stream inner) : ReadOnlyStream(inner) + { + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + return 0; + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } +} + +/// +/// The real file system, but reading a held file waits until (or until the job is cancelled), so +/// a test can look at a job while it runs. +/// +internal sealed class HeldExportFileSystem(Func holds) : IExportFileSystem +{ + private readonly IExportFileSystem _inner = ExportFileSystem.Instance; + private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// Set when a held file is opened. + public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// Lets every held read go on. + public void Release() => _release.TrySetResult(); + + public Stream OpenRead(string path) + { + var stream = _inner.OpenRead(path); + if (!holds(path)) + { + return stream; + } + + Reached.TrySetResult(); + return new HeldStream(stream, _release.Task); + } + + public Task ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct); + + public bool FileExists(string path) => _inner.FileExists(path); + + public long? FileLength(string path) => _inner.FileLength(path); + + private sealed class HeldStream(Stream inner, Task release) : Stream + { + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => inner.Length; + + public override long Position { get => inner.Position; set => throw new NotSupportedException(); } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await release.WaitAsync(cancellationToken); + return await inner.ReadAsync(buffer, cancellationToken); + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } + } +} + +/// The real file system, but reading a chosen library file gives one byte changed (a failing disk or cable). +internal sealed class CorruptingExportFileSystem(Func corrupts) : IExportFileSystem +{ + private readonly IExportFileSystem _inner = ExportFileSystem.Instance; + + public Stream OpenRead(string path) + { + var stream = _inner.OpenRead(path); + if (!corrupts(path)) + { + return stream; + } + + using (stream) + { + using var copy = new MemoryStream(); + stream.CopyTo(copy); + var bytes = copy.ToArray(); + bytes[bytes.Length / 2] ^= 0x5A; + return new MemoryStream(bytes, writable: false); + } + } + + public Task ComputeSha256Async(string path, CancellationToken ct) => _inner.ComputeSha256Async(path, ct); + + public bool FileExists(string path) => _inner.FileExists(path); + + public long? FileLength(string path) => _inner.FileLength(path); +} + +/// A read-only wrapper stream. +internal abstract class ReadOnlyStream(Stream inner) : Stream +{ + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => inner.Length; + + public override long Position { get => inner.Position; set => throw new NotSupportedException(); } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + inner.Dispose(); + } + + base.Dispose(disposing); + } +} + +/// Every file of a folder tree (relative path → length and SHA-256): equal before and after means nothing was touched. +internal static class Fingerprint +{ + /// The fingerprint; files whose name starts with (the open database) are left out. + public static IReadOnlyDictionary Of(string folder, string? skipPrefix = null) + { + var files = new SortedDictionary(StringComparer.Ordinal); + if (!Directory.Exists(folder)) + { + return files; + } + + foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)) + { + if (skipPrefix is not null && Path.GetFileName(file).StartsWith(skipPrefix, StringComparison.Ordinal)) + { + continue; + } + + var bytes = File.ReadAllBytes(file); + files[Path.GetRelativePath(folder, file).Replace('\\', '/')] = $"{bytes.Length}:{Convert.ToHexStringLower(SHA256.HashData(bytes))}"; + } + + return files; + } + + public static void AreEqual(IReadOnlyDictionary expected, IReadOnlyDictionary actual, string because) + { + CollectionAssert.AreEqual(expected.Keys.ToList(), actual.Keys.ToList(), $"{because}: {string.Join(", ", actual.Keys)}"); + foreach (var (path, print) in expected) + { + Assert.AreEqual(print, actual[path], $"{because}: {path}"); + } + } + + /// Temporary files of Febe (.febe-*.part: the probe and the writes) anywhere below the folder. + public static IReadOnlyList Temporaries(string folder) => + Directory.Exists(folder) ? Directory.GetFiles(folder, SafeFileWriter.TempPrefix + "*", SearchOption.AllDirectories) : []; +} diff --git a/tests/Febe.Tests/Import/ImportServiceTests.cs b/tests/Febe.Tests/Import/ImportServiceTests.cs index 9c88d8a..3a31675 100644 --- a/tests/Febe.Tests/Import/ImportServiceTests.cs +++ b/tests/Febe.Tests/Import/ImportServiceTests.cs @@ -1,6 +1,9 @@ using System.Collections.Concurrent; +using Febe.Core.Abstractions; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Import; +using Febe.Tests.Export.Support; using Febe.Tests.Import.Support; using Febe.Tests.Support; @@ -120,4 +123,32 @@ public sealed class ImportServiceTests Assert.IsNull(await bed.Library.Db.Settings.GetAsync($"importazione.{run.Id}.ipotesi-stogram")); CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList()); } + + [TestMethod] + public async Task AnImportDoesNotStartWhileAnExportRuns() + { + // A real copy to an external folder holds the gate shared by the import, the export and the rebuild (tappa E2). + var held = new HeldExportFileSystem(path => path.EndsWith("_1.jpg", StringComparison.Ordinal)); + await using var export = await ExportTestBed.CreateAsync(env => env with { FileSystem = held }); + await export.PostAsync(export.Marta, "700", 1); + await export.GeneralAsync(); + await export.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(export.Marta.Id))); + await held.Reached.Task.WaitAsync(TimeSpan.FromSeconds(30)); + + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(330, 200, 150)); + await using var service = new ImportService(bed.Environment with { Gate = export.Gate }); + var refused = await Assert.ThrowsExactlyAsync(() => service.StartAsync(bed.Source)); + Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Import, LongWorkKind.Export), refused.Message); + Assert.StartsWith("C'è una copia nelle cartelle esterne al lavoro", refused.Message); + Assert.IsEmpty(await service.ListRunsAsync(), "a refused import records nothing"); + + // The copy ends: the import starts. + held.Release(); + await export.Service.WaitAsync(); + Assert.IsNull(export.Gate.Busy); + var run = await service.StartAsync(bed.Source); + Assert.AreEqual(ImportRunState.Reviewing, (await service.WaitAsync(run.Id))!.State); + } } diff --git a/tests/Febe.Tests/Packaging/ImageContentsTests.cs b/tests/Febe.Tests/Packaging/ImageContentsTests.cs index 7a8b934..0667b2e 100644 --- a/tests/Febe.Tests/Packaging/ImageContentsTests.cs +++ b/tests/Febe.Tests/Packaging/ImageContentsTests.cs @@ -154,6 +154,45 @@ public sealed partial class ImageContentsTests handovers); } + /// + /// Copie esterne (spec §4.10, §11): /esporta is never made by the image. A VOLUME or a mkdir would give an anonymous + /// volume or a folder of the image disk that looks like a mounted folder; Compose and Unraid offer it commented out + /// or empty, with FEBE_ESPORTA. + /// + [TestMethod] + public void TheImageNeverMakesTheExportFolderAndTheTemplatesOfferItOff() + { + var code = Code(Dockerfile()); + var volume = code.Split('\n').Single(line => line.StartsWith("VOLUME ", StringComparison.Ordinal)); + Assert.DoesNotContain("esporta", volume); + foreach (var line in code.Split('\n').Where(line => line.Contains("mkdir", StringComparison.Ordinal))) + { + Assert.DoesNotContain("esporta", line); + } + + Assert.DoesNotContain("FEBE_ESPORTA", code, "export is off unless the container declares it"); + StringAssert.Contains(Dockerfile(), "Niente /esporta qui", "the reason stays next to VOLUME"); + + var lines = File.ReadAllText(Repository.PathOf("docker", "compose.yml")).Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); + var mount = lines.Single(line => line.Contains(":/esporta", StringComparison.Ordinal) && line.Contains("FEBE_CARTELLA_ESPORTA", StringComparison.Ordinal)); + StringAssert.StartsWith(mount.TrimStart(), "# - ", "the mount of /esporta is commented out in compose.yml"); + var variable = lines.Single(line => line.TrimStart().TrimStart('#').TrimStart().StartsWith("FEBE_ESPORTA:", StringComparison.Ordinal)); + StringAssert.StartsWith(variable.TrimStart(), "# ", "FEBE_ESPORTA is commented out in compose.yml"); + var active = lines.Where(line => !line.TrimStart().StartsWith('#') && line.Contains("esporta", StringComparison.OrdinalIgnoreCase)).ToList(); + Assert.IsEmpty(active, string.Join('\n', active)); + + var template = System.Xml.Linq.XDocument.Load(Repository.PathOf("docker", "unraid", "febe.xml")).Root!; + var folder = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "/esporta"); + Assert.AreEqual("Path", (string?)folder.Attribute("Type")); + Assert.AreEqual("false", (string?)folder.Attribute("Required")); + Assert.AreEqual(string.Empty, (string?)folder.Attribute("Default")); + Assert.AreEqual(string.Empty, folder.Value.Trim(), "no folder of the server by default"); + var flag = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "FEBE_ESPORTA"); + Assert.AreEqual("Variable", (string?)flag.Attribute("Type")); + Assert.AreEqual(string.Empty, (string?)flag.Attribute("Default")); + Assert.AreEqual(string.Empty, flag.Value.Trim()); + } + [TestMethod] public void TheToolsTheStartUsesComeWithTheBaseImageAndTheBuildChecksThem() { diff --git a/tests/Febe.Tests/Packaging/PackagingTests.cs b/tests/Febe.Tests/Packaging/PackagingTests.cs index 6ecc46b..3baebeb 100644 --- a/tests/Febe.Tests/Packaging/PackagingTests.cs +++ b/tests/Febe.Tests/Packaging/PackagingTests.cs @@ -63,9 +63,11 @@ public sealed partial class PackagingTests Assert.Inconclusive(reason); } - // A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library. + // A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library, and + // an /esporta mounted with a folder of copies, while the copies are not declared. using var temp = new TempFolder("avvio-contenitore"); Directory.CreateDirectory(temp.Combine("libreria", "foto")); + Directory.CreateDirectory(temp.Combine("esporta", "usb")); var whoAmI = temp.Combine("dati", "home", "chi"); var (code, _, errors) = await RunEntrypointAsync(temp, "/bin/sh", "-c", $"id -u > '{whoAmI}'"); Assert.AreEqual(0, code, errors); @@ -75,12 +77,40 @@ public sealed partial class PackagingTests Assert.IsFalse(File.Exists(temp.Combine("dati", "seccomp.json")), "the profile Docker reads stays out of /dati"); Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("libreria"))).Split(' ')[0]); Assert.AreEqual("0:0", (await StatAsync(temp.Combine("libreria", "foto"))).Split(' ')[0], "the library is never changed recursively"); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "/esporta is left alone while the copies are not declared"); // A /dati/home left by a start as root (a real folder): given back to the user. await RunAsync("chown", "0:0", temp.Combine("dati", "home")); (code, _, errors) = await RunEntrypointAsync(temp, "true"); Assert.AreEqual(0, code, errors); Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home"))); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]); + (code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "no")); + Assert.AreEqual(0, code, errors); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "only the values of a switch declare the copies"); + + // Copie esterne declared (FEBE_ESPORTA=1): the root of /esporta, owned by root, goes to the user; what is inside + // (files of Alberto, other copies) never changes owner. + (code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "1")); + Assert.AreEqual(0, code, errors); + Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta", "usb"))).Split(' ')[0], "/esporta is never changed recursively"); + + // Declared with --esporta among the arguments of the server: the same. A root of another user stays his. + await RunAsync("chown", "0:0", temp.Combine("esporta")); + (code, _, errors) = await RunEntrypointAsync(temp, "true", "--esporta"); + Assert.AreEqual(0, code, errors); + Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]); + await RunAsync("chown", "1234:1234", temp.Combine("esporta")); + (code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "1")); + Assert.AreEqual(0, code, errors); + Assert.AreEqual("1234:1234", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "only a root owned by root is given to the user"); + + // A missing /esporta is never created, declared or not. + Directory.Delete(temp.Combine("esporta"), recursive: true); + (code, _, errors) = await RunEntrypointAsync(temp, ["true", "--esporta"], ("FEBE_ESPORTA", "1")); + Assert.AreEqual(0, code, errors); + Assert.IsFalse(Directory.Exists(temp.Combine("esporta")), "the start never creates /esporta"); } [TestMethod] @@ -205,8 +235,13 @@ public sealed partial class PackagingTests : $"L'utente o il gruppo {Nobody} non esistono qui: la prova si salta per non crearli."; } - /// The real entrypoint, with /dati, /libreria and the profile of the image moved into . - private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command) + /// The real entrypoint, with /dati, /libreria, /esporta and the profile of the image moved into . + private Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command) => + RunEntrypointAsync(temp, command, []); + + /// The same, with variables of the container (FEBE_ESPORTA is never taken from the machine of the tests). + private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync( + TempFolder temp, string[] command, params (string Name, string Value)[] variables) { var text = await File.ReadAllTextAsync(Repository.PathOf("docker", "entrypoint.sh"), TestContext.CancellationToken); var image = temp.Combine("immagine-seccomp.json"); @@ -215,6 +250,7 @@ public sealed partial class PackagingTests .Replace("/usr/share/febe/seccomp.json", image, StringComparison.Ordinal) .Replace("/dati", temp.Combine("dati"), StringComparison.Ordinal) .Replace("/libreria", temp.Combine("libreria"), StringComparison.Ordinal) + .Replace("/esporta", temp.Combine("esporta"), StringComparison.Ordinal) .Replace("groupadd ", ": groupadd ", StringComparison.Ordinal) .Replace("useradd ", ": useradd ", StringComparison.Ordinal); var script = temp.Combine("avvio.sh"); @@ -228,6 +264,12 @@ public sealed partial class PackagingTests start.Environment["PUID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture); start.Environment["PGID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture); + start.Environment.Remove("FEBE_ESPORTA"); + foreach (var (name, value) in variables) + { + start.Environment[name] = value; + } + using var process = Process.Start(start)!; var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); diff --git a/tests/Febe.Tests/Server/ServerOptionsTests.cs b/tests/Febe.Tests/Server/ServerOptionsTests.cs index 4ee4fbd..de41d3a 100644 --- a/tests/Febe.Tests/Server/ServerOptionsTests.cs +++ b/tests/Febe.Tests/Server/ServerOptionsTests.cs @@ -1,5 +1,6 @@ using System.Net; using Febe.Core.Abstractions; +using Febe.Core.Export; using Febe.Server; using Febe.Tests.Support; using Febe.Web; @@ -28,6 +29,14 @@ public sealed class ServerOptionsTests Assert.AreEqual("instagram", o.Site.Name); Assert.AreEqual("https://www.instagram.com/accounts/login/", o.LoginUrl); Assert.IsEmpty(o.AllowedHostList(), "any host name by default"); + // Copie esterne (§4.10, §11): /esporta is the only root, and it is off until declared. + Assert.IsFalse(o.ExportDeclared); + Assert.AreEqual("/esporta", o.ExportFolder); + var export = o.AppOptions().ExportRoot; + Assert.IsFalse(export.Declared); + Assert.AreEqual(ExportPaths.Trim(Path.GetFullPath("/esporta")), export.Root); + Assert.IsFalse(ExportRoots.Evaluate(export).Active); + Assert.Contains("Copie esterne = spente", o.ToString()); var web = o.WebOptions(); Assert.AreEqual(FebeEdition.Docker, web.Edition); @@ -46,13 +55,17 @@ public sealed class ServerOptionsTests ("FEBE_HOST", "tower.local, 192.168.1.10"), ("FEBE_PROXY_FIDATO", "1"), ("FEBE_SENZA_SANDBOX", "1"), - ("FEBE_PORTA_DEBUG", "9333")); + ("FEBE_PORTA_DEBUG", "9333"), + ("FEBE_ESPORTA", "1")); Assert.IsTrue(ServerOptions.TryParse(["--dati", "/tmp/d", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5"], env, out var o, out var problem), problem); Assert.AreEqual(9000, o.Port); Assert.AreEqual("Europe/London", o.ZoneId); Assert.IsTrue(o.TrustForwardedHost); Assert.IsTrue(o.NoSandbox); Assert.AreEqual(9333, o.DebugPort); + Assert.IsTrue(o.ExportDeclared); + Assert.IsTrue(o.AppOptions().ExportRoot.Declared); + Assert.Contains("Copie esterne = dichiarate", o.ToString()); Assert.AreEqual("/tmp/d", o.DataFolder); Assert.AreEqual(TimeSpan.FromSeconds(5), o.FirstSessionDelay); Assert.AreEqual("prova", o.Site.Name); @@ -62,6 +75,22 @@ public sealed class ServerOptionsTests Assert.AreEqual("http://127.0.0.1:8481/benvenuto", o.LoginUrl); CollectionAssert.IsSubsetOf(new[] { "tower.local", "tower.local:*", "192.168.1.10:*", "127.0.0.1:*", "localhost:*" }, o.AllowedHostList().ToList()); + // --esporta is a bare flag (no value), and FEBE_ESPORTA takes the values of the other switches. + Assert.IsTrue(ServerOptions.TryParse(["--esporta", "--porta", "9001"], Env(("FEBE_PASSWORD", "x")), out var flagged, out problem), problem); + Assert.IsTrue(flagged.ExportDeclared); + Assert.AreEqual(9001, flagged.Port); + foreach (var value in new[] { "true", "sì", "yes" }) + { + Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "x"), ("FEBE_ESPORTA", value)), out var on, out problem), problem); + Assert.IsTrue(on.ExportDeclared, value); + } + + foreach (var value in new[] { "0", "no", "/esporta" }) + { + Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "x"), ("FEBE_ESPORTA", value)), out var off, out problem), problem); + Assert.IsFalse(off.ExportDeclared, value); + } + var browser = o.BrowserEnvironment("/dati/home"); Assert.AreEqual("Europe/London", browser["TZ"]); Assert.AreEqual("/dati/home", browser["HOME"]); diff --git a/tests/Febe.Tests/Web/DemoExportTests.cs b/tests/Febe.Tests/Web/DemoExportTests.cs new file mode 100644 index 0000000..7c60263 --- /dev/null +++ b/tests/Febe.Tests/Web/DemoExportTests.cs @@ -0,0 +1,153 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text.Json; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account +/// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real +/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. +/// +[TestClass] +public sealed class DemoExportTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task TheDemoExportDataIsCoherent() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("demo-export-coerente"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct); + using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + + async Task GetAsync(string path) + { + using var response = await client.GetAsync(path, ct); + var text = await response.Content.ReadAsStringAsync(ct); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + // Every tile of a query, following the cursors. + async Task> AllTilesAsync(string query) + { + var tiles = new List(); + string? cursor = null; + for (var page = 0; page < 100; page++) + { + var answer = await GetAsync($"/api/library?{query}&limit=1000" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor))); + tiles.AddRange(answer.Items("tiles")); + if (answer.GetProperty("older").ValueKind == JsonValueKind.Null) + { + return tiles; + } + + cursor = answer.Str("older"); + } + + Assert.Fail($"too many pages for {query}"); + return tiles; + } + + // The copies and their files. + var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct); + Assert.IsGreaterThanOrEqualTo(2, destinations.Count); + var states = new HashSet(); + foreach (var destination in destinations) + { + Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath); + foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct)) + { + states.Add(copy.State); + var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null; + switch (copy.State) + { + case ExportCopyState.Copied: + Assert.IsTrue(File.Exists(path), $"«Copiato» without its file: {path}"); + Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path); + Assert.AreEqual(copy.Bytes, new FileInfo(path!).Length, path); + break; + case ExportCopyState.Removed: + Assert.IsFalse(path is not null && File.Exists(path), $"«Tolto» with a file: {path}"); + break; + case ExportCopyState.Superseded: + Assert.IsTrue(File.Exists(path), $"the old file of «Superato» stays: {path}"); + Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path); + break; + case ExportCopyState.Failed: + Assert.IsFalse(string.IsNullOrEmpty(copy.LastError), "a failure says why"); + break; + } + } + } + + CollectionAssert.AreEquivalent( + new[] { ExportCopyState.Copied, ExportCopyState.Removed, ExportCopyState.Superseded, ExportCopyState.Failed }, + states.ToArray(), + "the demo shows every state of a copy"); + Assert.IsFalse(Directory.EnumerateFiles(temp.Path, "*.part", SearchOption.AllDirectories).Any(f => f.Contains("esporta", StringComparison.Ordinal)), "no .part left"); + + // Every job has its files, and a finished one has none pending. + var runs = await demo.Storage.Exports.ListRecentRunsAsync(100, ct); + Assert.IsNotEmpty(runs); + foreach (var run in runs) + { + var summary = await demo.Storage.Exports.GetRunSummaryAsync(run.Id, ct); + Assert.IsGreaterThan(0, summary.Total, $"job {run.Id}"); + if (run.State == ExportRunState.Completed) + { + Assert.AreEqual(0, summary.ByState.GetValueOrDefault(ExportItemState.Pending), $"job {run.Id}"); + } + } + + // Each account: the card, the filter and the marks count the same files. + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + var checkedAccounts = 0; + foreach (var account in accounts) + { + var id = account.Long("id"); + var card = (await GetAsync($"/api/accounts/{id}")).GetProperty("export"); + // The card counts every due file of the account, its profile pictures too, which «Tutto» leaves out. + async Task FilesAsync(string copies) => + (await GetAsync($"/api/library/days?accounts={id}&mode=files&copies={copies}")).Int("files") + + (await GetAsync($"/api/library/days?accounts={id}&mode=files&kind=profile&copies={copies}")).Int("files"); + var copied = card.Int("due") - card.Int("notCopied") - card.Int("removedOrSuperseded"); + Assert.AreEqual(card.Int("notCopied"), await FilesAsync("notCopied"), account.Str("username")); + Assert.AreEqual(card.Int("removedOrSuperseded"), await FilesAsync("removedOrSuperseded"), account.Str("username")); + Assert.AreEqual(copied, await FilesAsync("copied"), account.Str("username")); + Assert.IsLessThanOrEqualTo(card.Int("notCopied"), card.Int("failed"), "a failed file is one still to copy"); + + var grouped = await AllTilesAsync($"accounts={id}"); + if (!card.Bool("enabled")) + { + Assert.AreEqual(0, card.Int("due"), account.Str("username")); + Assert.IsTrue(grouped.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "an account that is not exported has no marks"); + continue; + } + + var marked = grouped.Where(t => t.Str("copies") == "copied").Select(t => t.Long("id")).ToHashSet(); + var filtered = (await AllTilesAsync($"accounts={id}&copies=copied")).Select(t => t.Long("id")).ToHashSet(); + Assert.IsTrue(marked.SetEquals(filtered), $"{account.Str("username")}: the mark «copiato» is the filter «Copiati»"); + foreach (var partly in grouped.Where(t => t.Str("copies") == "partly")) + { + Assert.IsGreaterThan(0, partly.Int("copiesDone")); + Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone")); + } + + var fileMarks = (await AllTilesAsync($"accounts={id}&mode=files")).Count(t => t.Str("copies") == "copied") + + (await AllTilesAsync($"accounts={id}&mode=files&kind=profile")).Count(t => t.Str("copies") == "copied"); + Assert.AreEqual(copied, fileMarks, $"{account.Str("username")}: one mark per copied file"); + checkedAccounts += card.Int("due") > 0 ? 1 : 0; + } + + Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy"); + } +} diff --git a/tests/Febe.Tests/Web/ExportApiDemoCommandTests.cs b/tests/Febe.Tests/Web/ExportApiDemoCommandTests.cs new file mode 100644 index 0000000..dd7453b --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiDemoCommandTests.cs @@ -0,0 +1,134 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The commands of the copies to external folders over the demo (tappa E2): an own folder added with the picker and +/// taken away, the switch of an account, «Lo stesso post in due account», «Copia di nuovo» of a file «Tolto» and the +/// resume of the interrupted job. One demo for the whole sequence, which changes it. +/// +[TestClass] +public sealed class ExportApiDemoCommandTests +{ + [TestMethod] + public async Task TheCommandsChangeWhatTheCardTheFilterAndTheJobsShow() + { + using var temp = new TempFolder("demo-export-commands"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + var origin = $"{demo.Address.Scheme}://{demo.Address.Authority}"; + + async Task<(HttpStatusCode Status, JsonElement Body)> SendAsync(HttpMethod method, string path, object? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); + } + + request.Headers.Add("Origin", origin); + using var response = await client.SendAsync(request); + var text = await response.Content.ReadAsStringAsync(); + return (response.StatusCode, text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone()); + } + + async Task OkAsync(HttpMethod method, string path, object? body = null) + { + var (status, answer) = await SendAsync(method, path, body); + Assert.AreEqual(HttpStatusCode.OK, status, $"{method} {path}: {answer}"); + return answer; + } + + async Task WaitIdleAsync() + { + for (var i = 0; i < 300; i++) + { + if (!(await OkAsync(HttpMethod.Get, "/api/export/progress")).Bool("running")) + { + return; + } + + await Task.Delay(100); + } + + Assert.Fail("the copy did not end"); + } + + var accounts = (await OkAsync(HttpMethod.Get, "/api/accounts")).Items("accounts").ToList(); + long Id(string username) => accounts.First(a => a.Str("username") == username).Long("id"); + var marta = Id(DemoExport.CopiedAccount); + var giulia = Id("giulia.corre.demo"); + + // An own folder for @giulia.corre.demo with the demo's picker, then taken away (the copies would stay). + var picked = (await OkAsync(HttpMethod.Post, "/api/export/pick-folder", new { })).Str("path"); + var saved = await OkAsync(HttpMethod.Post, "/api/export/destinations", new + { + scope = "account", + accountId = giulia, + path = picked, + label = (string?)null, + types = new[] { "postFoto", "storie" }, + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + }); + var destination = saved.GetProperty("destination"); + Assert.AreEqual(DemoExport.PickedFolder, destination.Str("label")); + Assert.AreEqual("giulia.corre.demo", destination.Str("username")); + Assert.IsTrue((await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Bool("hasOwnFolder")); + var status = await OkAsync(HttpMethod.Get, $"/api/export/destinations/{destination.Long("id")}/status"); + Assert.IsTrue(status.Bool("reachable"), status.ToString()); + var (twice, _) = await SendAsync(HttpMethod.Post, "/api/export/destinations", new { scope = "account", accountId = giulia, path = picked, types = new[] { "postFoto" } }); + Assert.AreEqual(HttpStatusCode.BadRequest, twice, "one own folder per account"); + Assert.Contains("restano", (await OkAsync(HttpMethod.Delete, $"/api/export/destinations/{destination.Long("id")}")).Str("message")); + Assert.IsFalse((await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Bool("hasOwnFolder")); + + // The switch of an account acts at once on its card. + await OkAsync(HttpMethod.Post, $"/api/accounts/{giulia}/export-enabled", new { value = false }); + Assert.AreEqual(0, (await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Int("due")); + await OkAsync(HttpMethod.Post, $"/api/accounts/{giulia}/export-enabled", new { value = true }); + Assert.IsGreaterThan(0, (await OkAsync(HttpMethod.Get, $"/api/accounts/{giulia}")).GetProperty("export").Int("due")); + + // «Lo stesso post in due account». + await OkAsync(HttpMethod.Put, "/api/export/settings", new { samePost = "oneOnly" }); + Assert.AreEqual("oneOnly", (await OkAsync(HttpMethod.Get, "/api/export")).Str("samePost")); + await OkAsync(HttpMethod.Put, "/api/export/settings", new { samePost = "onePerAccount" }); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Put, "/api/export/settings", new { samePost = "tutti" })).Status); + + // «Copia di nuovo» of the file «Tolto» from the viewer: the copy is written again. + var before = (await OkAsync(HttpMethod.Get, $"/api/accounts/{marta}")).GetProperty("export"); + var tiles = (await OkAsync(HttpMethod.Get, $"/api/library?accounts={marta}&mode=files&copies=removedOrSuperseded&limit=600")).Items("tiles").ToList(); + long? removedCopy = null; + foreach (var tile in tiles) + { + var file = (await OkAsync(HttpMethod.Get, $"/api/entries/{tile.Long("id")}")).Items("media").First(m => m.Long("id") == tile.GetProperty("cover").Long("mediaId")); + if (file.Items("copies").FirstOrDefault(c => c.Str("state") == "removed" && c.Bool("canCopyAgain")) is { ValueKind: JsonValueKind.Object } copy) + { + removedCopy = copy.Long("copyId"); + break; + } + } + + Assert.IsNotNull(removedCopy, "the demo has a file «Tolto»"); + var job = await OkAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removedCopy }); + Assert.HasCount(1, job.Items("runIds").ToList()); + await WaitIdleAsync(); + var after = (await OkAsync(HttpMethod.Get, $"/api/accounts/{marta}")).GetProperty("export"); + Assert.IsLessThan(before.Int("removedOrSuperseded"), after.Int("removedOrSuperseded")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removedCopy })).Status, "a copied file is not copied again"); + + // «Riprendi» of the job left interrupted: it ends, and nothing is left to resume. + Assert.AreEqual(1, (await OkAsync(HttpMethod.Get, "/api/export")).Int("unfinishedRuns")); + await OkAsync(HttpMethod.Post, "/api/export/resume"); + await WaitIdleAsync(); + Assert.AreEqual(0, (await OkAsync(HttpMethod.Get, "/api/export")).Int("unfinishedRuns")); + var runs = (await OkAsync(HttpMethod.Get, "/api/export/runs")).EnumerateArray().ToList(); + Assert.IsFalse(runs.Any(r => r.Str("state") is "interrupted" or "running" or "paused")); + Assert.IsLessThan(after.Int("notCopied"), (await OkAsync(HttpMethod.Get, $"/api/accounts/{marta}")).GetProperty("export").Int("notCopied")); + } +} diff --git a/tests/Febe.Tests/Web/ExportApiDemoTests.cs b/tests/Febe.Tests/Web/ExportApiDemoTests.cs new file mode 100644 index 0000000..6248097 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiDemoTests.cs @@ -0,0 +1,253 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The copies to external folders over the API of the demo (spec §4.10, §10.6, tappa E2): destinations, the account +/// card, marks and the «Copie» filter, the viewer's copies, jobs and their report, and the folders of each look. The +/// demo's copies were written by the real engine into its temporary «esporta», so every number here comes from rows +/// and files that agree. Only reads and plans: nothing here changes the demo. +/// +[TestClass] +public sealed class ExportApiDemoTests +{ + private static TempFolder? s_temp; + private static DemoHost? s_demo; + private static HttpClient? s_client; + + private static DemoHost Demo => s_demo ?? throw new InvalidOperationException("demo not started"); + + private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started"); + + [ClassInitialize] + public static async Task StartDemoAsync(TestContext context) + { + s_temp = new TempFolder("demo-export"); + s_demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, s_temp.Path)); + s_client = new HttpClient { BaseAddress = s_demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + } + + [ClassCleanup] + public static async Task StopDemoAsync() + { + s_client?.Dispose(); + if (s_demo is not null) + { + await s_demo.DisposeAsync(); + } + + s_temp?.Dispose(); + } + + [TestMethod] + public async Task TheOverviewListsTheDemoFoldersInBothLooks() + { + var desktop = await GetAsync("/api/export"); + Assert.IsFalse(desktop.GetProperty("root").Bool("docker")); + Assert.IsTrue(desktop.GetProperty("root").Bool("active")); + Assert.IsTrue(desktop.GetProperty("root").Bool("pickFolder")); + var general = desktop.GetProperty("general"); + Assert.AreEqual("Disco USB", general.Str("label")); + Assert.AreEqual("general", general.Str("scope")); + Assert.HasCount(6, general.Items("types").ToList()); + Assert.IsGreaterThan(0, general.GetProperty("counts").Int("copied")); + Assert.AreEqual(1, general.GetProperty("counts").Int("removed")); + Assert.AreEqual(1, general.GetProperty("counts").Int("superseded")); + Assert.AreEqual(1, general.GetProperty("counts").Int("failed")); + var own = desktop.Items("own").Single(); + Assert.AreEqual("studio.lumen.demo", own.Str("username")); + Assert.AreEqual("Studio Lumen", own.Str("label")); + CollectionAssert.AreEquivalent(new[] { "postFoto", "postVideo" }, own.Items("types").Select(t => t.GetString()).ToArray()); + Assert.AreEqual(1, desktop.Int("unfinishedRuns"), "the job left interrupted by the demo"); + Assert.AreEqual("onePerAccount", desktop.Str("samePost")); + + var docker = await GetAsync("/api/export?veste=docker"); + Assert.IsTrue(docker.GetProperty("root").Bool("docker")); + Assert.IsTrue(docker.GetProperty("root").Bool("active")); + Assert.IsFalse(docker.GetProperty("root").Bool("pickFolder")); + Assert.AreEqual("/esporta", docker.GetProperty("root").Str("root")); + Assert.AreEqual("/esporta/Disco USB", docker.GetProperty("general").Str("display")); + } + + [TestMethod] + public async Task TheFoldersAreListedInDockerAndPickedOnTheDesktop() + { + var list = await GetAsync("/api/export/folders?veste=docker"); + CollectionAssert.IsSubsetOf(new[] { "Chiavetta", "Disco USB", "Studio Lumen" }, list.Items("folders").Select(f => f.Str("name")).ToArray()); + Assert.AreEqual("/esporta", list.Str("display")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/export/folders?veste=docker&path=..")).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/export/folders")).Status, "the desktop uses the picker"); + + var check = await PostAsync("/api/export/check-folder?veste=docker", new { path = "Chiavetta" }); + Assert.IsTrue(check.Bool("accepted"), check.ToString()); + Assert.AreEqual("/esporta/Chiavetta", check.Str("display")); + Assert.AreEqual(DemoExportDisk.Free, check.Long("freeBytes")); + Assert.IsFalse(check.Bool("fat32")); + var outside = await SendAsync(HttpMethod.Post, "/api/export/check-folder?veste=docker", new { path = "../fuori" }); + Assert.IsTrue(outside.Status == HttpStatusCode.BadRequest || !JsonDocument.Parse(outside.Body).RootElement.Bool("accepted"), outside.Body); + + var picked = await PostAsync("/api/export/pick-folder", new { destinationId = (long?)null }); + Assert.EndsWith("Chiavetta", picked.Str("path")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/pick-folder?veste=docker", new { })).Status); + } + + [TestMethod] + public async Task TheAccountCardCountsOnlyDueFilesAndTheSwitchOffCountsNothing() + { + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + long Id(string username) => accounts.First(a => a.Str("username") == username).Long("id"); + + var marta = (await GetAsync($"/api/accounts/{Id(DemoExport.CopiedAccount)}")).GetProperty("export"); + Assert.IsTrue(marta.Bool("enabled")); + Assert.IsFalse(marta.Bool("hasOwnFolder")); + Assert.AreEqual("Disco USB", marta.GetProperty("destination").Str("label")); + Assert.IsGreaterThan(0, marta.Int("due")); + Assert.IsGreaterThan(0, marta.Int("notCopied")); + Assert.IsLessThan(marta.Int("due"), marta.Int("notCopied"), "about two thirds are copied"); + Assert.IsGreaterThan(0, marta.Int("removedOrSuperseded")); + Assert.IsGreaterThan(0, marta.Int("failed")); + Assert.IsGreaterThan(marta.Int("notCopied") + marta.Int("removedOrSuperseded") + marta.Int("failed"), marta.Int("due"), "the rest is copied"); + + var studio = (await GetAsync($"/api/accounts/{Id(DemoExport.OwnFolderAccount)}")).GetProperty("export"); + Assert.IsTrue(studio.Bool("hasOwnFolder")); + Assert.AreEqual("Studio Lumen", studio.GetProperty("destination").Str("label")); + + var porto = (await GetAsync($"/api/accounts/{Id(DemoExport.NotExportedAccount)}")).GetProperty("export"); + Assert.IsFalse(porto.Bool("enabled")); + Assert.AreEqual(0, porto.Int("due")); + Assert.AreEqual(0, porto.Int("notCopied")); + } + + [TestMethod] + public async Task TheFilterTheMarksAndTheViewerAgree() + { + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + var marta = accounts.First(a => a.Str("username") == DemoExport.CopiedAccount).Long("id"); + + var card = (await GetAsync($"/api/accounts/{marta}")).GetProperty("export"); + var days = await GetAsync($"/api/library/days?accounts={marta}&mode=files&copies=removedOrSuperseded"); + Assert.IsTrue(days.Bool("hasDestinations")); + Assert.AreEqual(card.Int("removedOrSuperseded"), days.Int("files"), "the card and the filter count the same files"); + Assert.AreEqual(card.Int("notCopied"), (await GetAsync($"/api/library/days?accounts={marta}&mode=files&copies=notCopied")).Int("files")); + var copied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=copied&limit=600")).Items("tiles").ToList(); + Assert.IsNotEmpty(copied); + Assert.IsTrue(copied.All(t => t.Str("copies") == "copied"), "every file the filter finds copied carries the mark"); + var notCopied = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=notCopied&limit=600")).Items("tiles").ToList(); + Assert.IsNotEmpty(notCopied); + Assert.IsTrue(notCopied.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "a file not copied has no mark"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Get, "/api/library?copies=tutti")).Status); + + var grouped = (await GetAsync($"/api/library?accounts={marta}&limit=600")).Items("tiles").ToList(); + foreach (var partly in grouped.Where(t => t.Str("copies") == "partly")) + { + Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone")); + Assert.IsGreaterThan(0, partly.Int("copiesDone")); + } + + // The viewer of a file «Tolto o superato»: its copy, with «Copia di nuovo». + var replaced = (await GetAsync($"/api/library?accounts={marta}&mode=files&copies=removedOrSuperseded&limit=600")).Items("tiles").ToList(); + Assert.HasCount(card.Int("removedOrSuperseded"), replaced); + var states = new HashSet(); + foreach (var tile in replaced) + { + var entry = await GetAsync($"/api/entries/{tile.Long("id")}"); + Assert.IsTrue(entry.Bool("canCopy")); + var file = entry.Items("media").First(m => m.Long("id") == tile.GetProperty("cover").Long("mediaId")); + var copy = file.Items("copies").First(c => c.Str("state") is "removed" or "superseded"); + Assert.IsTrue(copy.Bool("canCopyAgain"), copy.ToString()); + Assert.AreEqual("Disco USB", copy.Str("destination")); + Assert.AreEqual("whole", copy.Str("variant")); + states.Add(copy.Str("state")); + } + + CollectionAssert.AreEquivalent(new[] { "removed", "superseded" }, states.ToArray()); + } + + [TestMethod] + public async Task TheJobsHaveTheirReportAndThePlanSaysWhatWouldBeCopied() + { + var runs = await GetAsync("/api/export/runs"); + var list = runs.EnumerateArray().ToList(); + var completed = list.First(r => r.Str("state") == "completed" && r.Str("destination") == "Disco USB"); + Assert.IsTrue(list.Any(r => r.Str("state") == "interrupted" && r.Int("done") == 0 && r.Int("total") > 0)); + Assert.AreEqual(completed.Int("total"), completed.Int("done")); + + var report = await GetAsync($"/api/export/runs/{completed.Long("id")}/report"); + Assert.IsGreaterThan(0, report.GetProperty("byState").Int("copied")); + Assert.AreEqual(0, report.GetProperty("byState").Int("failed")); + Assert.IsGreaterThan(0L, report.Long("bytesCopied")); + Assert.AreEqual(DemoExport.CopiedAccount, report.Items("accounts").Single().Str("username")); + + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + var marta = accounts.First(a => a.Str("username") == DemoExport.CopiedAccount).Long("id"); + var card = (await GetAsync($"/api/accounts/{marta}")).GetProperty("export"); + var plan = await PostAsync("/api/export/plan", new { accountId = marta }); + // One write per picture of the account: the other files with the same picture are «Già copiato». + Assert.IsGreaterThan(0, plan.Int("files")); + Assert.IsLessThanOrEqualTo(card.Int("notCopied") + card.Int("failed"), plan.Int("files")); + Assert.IsGreaterThan(0, plan.Int("alreadyCopied")); + Assert.IsGreaterThan(0, plan.Int("removedOrSuperseded"), "skipped unless «Copia di nuovo»"); + Assert.IsLessThanOrEqualTo(card.Int("removedOrSuperseded"), plan.Int("removedOrSuperseded")); + Assert.AreEqual("Disco USB", plan.Items("destinations").Single().Str("label")); + var again = await PostAsync("/api/export/plan", new { accountId = marta, copyAgain = true }); + Assert.IsGreaterThan(plan.Int("files"), again.Int("files")); + + var porto = accounts.First(a => a.Str("username") == DemoExport.NotExportedAccount).Long("id"); + var off = await PostAsync("/api/export/plan", new { accountId = porto }); + Assert.AreEqual(0, off.Int("files")); + Assert.IsGreaterThan(0, off.Int("notExported")); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta, mediaIds = new[] { 1L } })).Status, "exactly one selection"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await SendAsync(HttpMethod.Post, "/api/export/plan", new { })).Status); + + var progress = await GetAsync("/api/export/progress"); + Assert.IsFalse(progress.Bool("running")); + } + + [TestMethod] + public async Task CommandsWithoutTheOriginOfThePageAreRefused() + { + using var request = new HttpRequestMessage(HttpMethod.Post, "/api/export/interrupt") { Content = new StringContent("{}", Encoding.UTF8, "application/json") }; + request.Headers.Add("Origin", "http://altro.example"); + using var response = await Client.SendAsync(request); + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode); + } + + private static string Origin => $"{Demo.Address.Scheme}://{Demo.Address.Authority}"; + + private static async Task GetAsync(string path) + { + var (status, body) = await SendAsync(HttpMethod.Get, path); + Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {body}"); + return JsonDocument.Parse(body).RootElement.Clone(); + } + + private static async Task PostAsync(string path, object body) + { + var (status, text) = await SendAsync(HttpMethod.Post, path, body); + Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + private static async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpMethod method, string path, object? body = null) + { + using var request = new HttpRequestMessage(method, path); + if (body is not null) + { + request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); + } + + if (method != HttpMethod.Get) + { + request.Headers.Add("Origin", Origin); + } + + using var response = await Client.SendAsync(request); + return (response.StatusCode, await response.Content.ReadAsStringAsync()); + } +} diff --git a/tests/Febe.Tests/Web/ExportApiTests.cs b/tests/Febe.Tests/Web/ExportApiTests.cs new file mode 100644 index 0000000..5061063 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiTests.cs @@ -0,0 +1,555 @@ +using System.Net; +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// The copies to external folders over the API of a real web host (spec §4.10, §10.3, tappa E2), outside the demo: +/// whether export is available (Docker not declared, not mounted, mounted), the folders of /esporta, the check of a +/// candidate folder, destinations, «Copia in…» from plan to the files on disk, «Controlla le copie» and «Copia di +/// nuovo», the «Copie» filter, the marks, the viewer and the account card, and the exclusive long work. Files are +/// real (saved through ), destinations are folders of the temporary folder of the test. +/// +[TestClass] +public sealed class ExportApiTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheOverviewSaysWhetherExportIsAvailable() + { + // Docker, not declared (the default of the web host): off, and nothing can be chosen or saved. + await using (var server = await WebTestServer.StartAsync()) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsTrue(root.Bool("docker")); + Assert.IsFalse(root.Bool("active")); + Assert.IsFalse(root.Bool("pickFolder")); + Assert.AreEqual(ExportRoots.NotDeclaredText, root.Str("problem")); + var (folders, folderError) = await server.SendJsonAsync(HttpMethod.Get, "/api/export/folders"); + Assert.AreEqual(HttpStatusCode.BadRequest, folders); + Assert.AreEqual(ExportRoots.NotDeclaredText, folderError.Str("message")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status); + Assert.IsEmpty(await server.Db.Exports.ListDestinationsAsync(includeRetired: true)); + } + + // Declared, but nothing is mounted at or below /esporta: still off, with its own reason. + using var esporta = new TempFolder("esporta"); + Directory.CreateDirectory(esporta.Combine("usb")); + await using (var server = await StartAsync(ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts()), desktop: false)) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsTrue(root.Bool("docker")); + Assert.IsFalse(root.Bool("active")); + Assert.AreNotEqual(ExportRoots.NotDeclaredText, root.Str("problem")); + Assert.IsNotEmpty(root.Str("problem")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status); + } + + // Declared and mounted: on. + await using (var server = await StartAsync(Mounted(esporta), desktop: false)) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsTrue(root.Bool("active"), root.ToString()); + Assert.AreEqual(JsonValueKind.Null, root.GetProperty("problem").ValueKind); + } + + // Windows: any folder, through the picker of the system. + await using (var server = await StartAsync()) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsFalse(root.Bool("docker")); + Assert.IsTrue(root.Bool("active")); + Assert.AreEqual(JsonValueKind.Null, root.GetProperty("root").ValueKind); + } + } + + [TestMethod] + public async Task FoldersAreListedUnderTheExportRootAndDotDotIsRefused() + { + using var esporta = new TempFolder("esporta"); + Directory.CreateDirectory(esporta.Combine("usb", "foto")); + Directory.CreateDirectory(esporta.Combine("nas")); + // Hidden as the import picker hides it: a dot folder on Linux, the attribute on Windows. + var hidden = Directory.CreateDirectory(esporta.Combine(".nascosta")); + hidden.Attributes |= FileAttributes.Hidden; + await using var server = await StartAsync(Mounted(esporta), desktop: false); + + var list = await server.GetJsonAsync("/api/export/folders"); + CollectionAssert.AreEquivalent(new[] { "nas", "usb" }, list.Items("folders").Select(f => f.Str("name")).ToArray(), "no hidden folders"); + Assert.AreEqual(string.Empty, list.Str("relative")); + Assert.AreEqual(JsonValueKind.Null, list.GetProperty("parent").ValueKind); + var usb = await server.GetJsonAsync("/api/export/folders?path=usb"); + Assert.AreEqual("foto", usb.Items("folders").Single().Str("name")); + Assert.AreEqual(string.Empty, usb.Str("parent")); + foreach (var path in new[] { "..", "usb/../..", "../fuori" }) + { + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/export/folders?path={Uri.EscapeDataString(path)}")).Status, path); + } + + var check = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Body; + Assert.IsTrue(check.Bool("accepted"), check.ToString()); + Assert.AreEqual(Free, check.Long("freeBytes")); + Assert.IsFalse(check.Bool("fat32")); + foreach (var path in new[] { string.Empty, "..", "../fuori", "usb/../.." }) + { + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path }); + Assert.IsTrue(status == HttpStatusCode.BadRequest || !answer.Bool("accepted"), $"«{path}»: {answer}"); + } + + // In Docker there is no picker of the system: the page lists the folders of /esporta. + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/pick-folder", new { })).Status); + Assert.IsFalse(Directory.Exists(esporta.Combine("fuori")), "nothing is ever created"); + } + + [TestMethod] + public async Task CheckFolderRefusesTheLibraryAndTheDataFolder() + { + await using var server = await StartAsync(); + var account = await AddPhotosAsync(server, "marta.demo", 1); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + Directory.CreateDirectory(server.Library.Layout.AccountFolder(account.Account)); + + var accepted = await CheckAsync(server, usb); + Assert.IsTrue(accepted.Bool("accepted"), accepted.ToString()); + Assert.AreEqual(Free, accepted.Long("freeBytes")); + foreach (var refused in new[] + { + server.Library.Layout.Root, + Path.Combine(server.Library.Layout.Root, "dentro"), + server.Library.Data.Root, + server.Library.Layout.AccountFolder(account.Account), + server.Temp.Path, + server.Temp.Combine("non-esiste"), + }) + { + if (refused.EndsWith("dentro", StringComparison.Ordinal)) + { + Directory.CreateDirectory(refused); + } + + var answer = await CheckAsync(server, refused); + Assert.IsFalse(answer.Bool("accepted"), refused); + Assert.IsNotEmpty(answer.Str("problem"), refused); + } + + Assert.IsFalse(Directory.Exists(server.Temp.Combine("non-esiste")), "a missing folder is never created"); + Assert.IsEmpty(Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "the probe leaves nothing behind"); + } + + [TestMethod] + public async Task DestinationsAreCreatedUpdatedAndRetired() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 1); + var usb = server.Temp.Combine("usb"); + var nas = server.Temp.Combine("nas"); + Directory.CreateDirectory(usb); + Directory.CreateDirectory(nas); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, types: []))).Status, "at least one type"); + var (status, created) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, label: "Disco USB")); + Assert.AreEqual(HttpStatusCode.OK, status, created.ToString()); + var general = created.GetProperty("destination"); + Assert.AreEqual("general", general.Str("scope")); + Assert.AreEqual("Disco USB", general.Str("label")); + Assert.HasCount(6, general.Items("types").ToList()); + Assert.IsFalse(general.Bool("automatic")); + Assert.AreEqual(general.Long("id"), (await server.GetJsonAsync("/api/export")).GetProperty("general").Long("id")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas))).Status, "one general folder"); + + // The same folder: the same destination, changed in place. + var (sameStatus, same) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(usb, label: "Chiavetta", types: ["postFoto"])); + Assert.AreEqual(HttpStatusCode.OK, sameStatus, same.ToString()); + Assert.AreEqual(general.Long("id"), same.GetProperty("destination").Long("id")); + Assert.AreEqual("Chiavetta", same.GetProperty("destination").Str("label")); + CollectionAssert.AreEqual(new[] { "postFoto" }, same.GetProperty("destination").Items("types").Select(t => t.GetString()).ToArray()); + + // Another folder: the old destination is retired (it keeps its copies), a new one takes its place. + var (movedStatus, moved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(nas)); + Assert.AreEqual(HttpStatusCode.OK, movedStatus, moved.ToString()); + var next = moved.GetProperty("destination").Long("id"); + Assert.AreNotEqual(general.Long("id"), next); + Assert.IsNotNull((await server.Db.Exports.GetDestinationAsync(general.Long("id")))!.RemovedAt); + + // An own folder of the account, then retired: the account goes back to the general folder. + var sua = server.Temp.Combine("sua"); + Directory.CreateDirectory(sua); + var (ownStatus, own) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(sua, scope: "account", accountId: marta.Account.Id, types: ["postFoto", "postVideo"])); + Assert.AreEqual(HttpStatusCode.OK, ownStatus, own.ToString()); + Assert.AreEqual("marta.demo", own.GetProperty("destination").Str("username")); + var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsTrue(card.Bool("hasOwnFolder")); + Assert.AreEqual(own.GetProperty("destination").Long("id"), card.GetProperty("destination").Long("id")); + var overview = await server.GetJsonAsync("/api/export"); + Assert.AreEqual("marta.demo", overview.Items("own").Single().Str("username")); + + var (retiredStatus, retired) = await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{own.GetProperty("destination").Long("id")}"); + Assert.AreEqual(HttpStatusCode.OK, retiredStatus); + Assert.AreEqual(ExportDestinations.RetiredText, retired.Str("message")); + card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsFalse(card.Bool("hasOwnFolder")); + Assert.AreEqual(next, card.GetProperty("destination").Long("id")); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{next}")).Status); + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("general").ValueKind); + Assert.IsTrue(Directory.Exists(usb) && Directory.Exists(nas) && Directory.Exists(sua), "retiring a destination never touches its folder"); + } + + [TestMethod] + public async Task PlanAndStartCopyTheFilesAndTheProgressFinishes() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var usb = await GeneralAsync(server); + + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(3, plan.Int("files"), plan.ToString()); + Assert.IsGreaterThan(0L, plan.Long("bytes")); + Assert.AreEqual(0, plan.Int("alreadyCopied")); + Assert.AreEqual(usb.Id, plan.Items("destinations").Single().Long("id")); + Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "a plan writes nothing"); + + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + var run = job.Items("runIds").Single().GetInt64(); + await WaitIdleAsync(server); + + var progress = await server.GetJsonAsync("/api/export/progress"); + Assert.IsFalse(progress.Bool("running")); + Assert.AreEqual(JsonValueKind.Null, progress.GetProperty("error").ValueKind, progress.ToString()); + var written = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories); + Assert.HasCount(3, written); + Assert.IsTrue(written.All(f => Path.GetRelativePath(usb.Root, f).StartsWith("marta.demo", StringComparison.Ordinal)), "the account segment comes first in the general folder"); + CollectionAssert.AreEquivalent( + marta.Files.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(), + written.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(), + "copies byte for byte"); + Assert.IsFalse(written.Any(f => f.EndsWith(".part", StringComparison.Ordinal))); + + var runs = (await server.GetJsonAsync("/api/export/runs")).EnumerateArray().ToList(); + var done = runs.Single(r => r.Long("id") == run); + Assert.AreEqual("completed", done.Str("state")); + Assert.AreEqual(3, done.Int("done")); + var report = await server.GetJsonAsync($"/api/export/runs/{run}/report"); + Assert.AreEqual(3, report.GetProperty("byState").Int("copied")); + Assert.AreEqual("marta.demo", report.Items("accounts").Single().Str("username")); + Assert.IsEmpty(report.Items("problems").ToList()); + + var again = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(0, again.Int("files")); + Assert.AreEqual(3, again.Int("alreadyCopied")); + var overview = await server.GetJsonAsync("/api/export"); + Assert.AreEqual(3, overview.GetProperty("general").GetProperty("counts").Int("copied")); + Assert.AreEqual(0, overview.Int("unfinishedRuns")); + } + + [TestMethod] + public async Task CheckCopiesThenCopyAgainWritesTheRemovedFileOnce() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 2); + var usb = await GeneralAsync(server); + await StartAndWaitAsync(server, new { accountId = marta.Account.Id }); + + // Alberto deletes one copy by hand; «Controlla le copie» finds it «Tolto» and touches no file. + var gone = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).First(); + File.Delete(gone); + var kept = Fingerprint.Of(usb.Root); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{usb.Id}/check")).Status); + var removed = await WaitForAsync(async () => + { + var copies = await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, 0, 10); + return copies.Count == 1 ? copies[0] : null; + }); + await WaitIdleAsync(server); + Fingerprint.AreEqual(kept, Fingerprint.Of(usb.Root), "«Controlla le copie» touches no file"); + + // The plan skips it by itself; the viewer offers «Copia di nuovo». + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(0, plan.Int("files")); + Assert.AreEqual(1, plan.Int("removedOrSuperseded")); + var entry = marta.Entries.Single(e => e.Media.Any(m => m.Id == removed.MediaId)); + var file = (await server.GetJsonAsync($"/api/entries/{entry.Entry.Id}")).Items("media").Single(m => m.Long("id") == removed.MediaId); + var copy = file.Items("copies").Single(); + Assert.AreEqual("removed", copy.Str("state")); + Assert.IsTrue(copy.Bool("canCopyAgain")); + Assert.AreEqual(removed.Id, copy.Long("copyId")); + + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + Assert.HasCount(1, job.Items("runIds").ToList()); + await WaitIdleAsync(server); + Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories)); + Assert.IsTrue(File.Exists(gone), "written again at its place"); + Assert.AreEqual(ExportCopyState.Removed, (await server.Db.Exports.GetCopyAsync(removed.Id))!.State, "the old row stays as history"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id })).Status, "already copied again"); + var notRemoved = (await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, 0, 10)).First(); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = notRemoved.Id })).Status, "only a removed or superseded copy"); + } + + [TestMethod] + public async Task TheLibraryFilterTheMarksTheViewerAndTheCardAgree() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var pair = await AddPostAsync(server, marta.Account, "coppia", 40, 41); + + // No destination: no mark, no «Copie» filter offered, and every count is zero. + var days = await server.GetJsonAsync("/api/library/days"); + Assert.IsFalse(days.Bool("hasDestinations")); + Assert.IsTrue((await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null)); + var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsTrue(card.Bool("enabled"), "«Esporta questo account» is on when nothing is recorded"); + Assert.AreEqual(0, card.Int("due")); + Assert.AreEqual(JsonValueKind.Null, card.GetProperty("destination").ValueKind); + Assert.IsFalse((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Bool("canCopy")); + + // A destination and the copy of the first photos: one post copied, one in part. + var usb = await GeneralAsync(server); + await StartAndWaitAsync(server, new { mediaIds = new[] { marta.Entries[0].Media[0].Id, pair.Media[0].Id } }); + Assert.IsTrue((await server.GetJsonAsync("/api/library/days")).Bool("hasDestinations")); + var tiles = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").ToDictionary(t => t.Long("id")); + Assert.AreEqual("copied", tiles[marta.Entries[0].Entry.Id].Str("copies")); + Assert.AreEqual("partly", tiles[pair.Entry.Id].Str("copies")); + Assert.AreEqual(1, tiles[pair.Entry.Id].Int("copiesDone")); + Assert.AreEqual(2, tiles[pair.Entry.Id].Int("copiesDue")); + Assert.AreEqual(JsonValueKind.Null, tiles[marta.Entries[1].Entry.Id].GetProperty("copies").ValueKind); + + // The filter: grouped («Copiati» only when every due file is copied) and per file. + long[] Ids(JsonElement page) => [.. page.Items("tiles").Select(t => t.Long("id"))]; + CollectionAssert.AreEquivalent(new[] { marta.Entries[0].Entry.Id }, Ids(await server.GetJsonAsync("/api/library?copies=copied"))); + CollectionAssert.AreEquivalent( + new[] { marta.Entries[1].Entry.Id, marta.Entries[2].Entry.Id, pair.Entry.Id }, + Ids(await server.GetJsonAsync("/api/library?copies=notCopied"))); + Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=removedOrSuperseded"))); + Assert.HasCount(2, (await server.GetJsonAsync("/api/library?copies=copied&mode=files")).Items("tiles").ToList()); + Assert.AreEqual(3, (await server.GetJsonAsync("/api/library/days?copies=notCopied&mode=files")).Int("files")); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?copies=copied")).Int("entries")); + foreach (var bad in new[] { "tutti", "copied,notCopied", "1" }) + { + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/library?copies={bad}")).Status, bad); + } + + // The viewer: the copy of the file, and «Copia in…». + var entry = await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}"); + Assert.IsTrue(entry.Bool("canCopy")); + var media = entry.Items("media").ToDictionary(m => m.Long("id")); + var copy = media[pair.Media[0].Id].Items("copies").Single(); + Assert.AreEqual("copied", copy.Str("state")); + Assert.AreEqual("usb", copy.Str("destination")); + Assert.AreEqual("whole", copy.Str("variant")); + Assert.IsFalse(copy.Bool("canCopyAgain")); + Assert.IsFalse(copy.Bool("destinationRetired")); + Assert.IsEmpty(media[pair.Media[1].Id].Items("copies").ToList()); + + // The card counts what the filter finds; the switch off counts nothing and acts at once. + card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.AreEqual(5, card.Int("due")); + Assert.AreEqual(3, card.Int("notCopied")); + Assert.AreEqual(0, card.Int("removedOrSuperseded")); + Assert.AreEqual(usb.Id, card.GetProperty("destination").Long("id")); + var (offStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = false }); + Assert.AreEqual(HttpStatusCode.OK, offStatus); + card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsFalse(card.Bool("enabled")); + Assert.AreEqual(0, card.Int("due")); + Assert.AreEqual(0, card.Int("notCopied")); + Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=notCopied"))); + var off = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(0, off.Int("files")); + Assert.IsGreaterThan(0, off.Int("notExported"), "Q1: the switch off skips manual copies too"); + Assert.IsTrue((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Items("media").Any(m => m.Items("copies").Any()), "the copies made stay visible"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = true })).Status); + Assert.AreEqual(3, (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").Int("notCopied")); + } + + [TestMethod] + public async Task RebuildIsRefusedDuringAnExportAndTheCopyWaitsForTheEngineSession() + { + var session = new FakeSessionState { InSession = true }; + await using var server = await StartAsync(session: session, clock: new WaitingClock(new ManualClock(Make.T0))); + var marta = await AddPhotosAsync(server, "marta.demo", 2); + var usb = await GeneralAsync(server); + + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + var waiting = await WaitForAsync(async () => + { + var progress = await server.GetJsonAsync("/api/export/progress"); + return progress.Str("phase") == "waitingForSession" ? (JsonElement?)progress : null; + }); + Assert.IsTrue(waiting.GetValueOrDefault().Bool("running")); + Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "no copy during an engine session"); + + var (rebuild, refusal) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "ricostruisci" }); + Assert.AreEqual(HttpStatusCode.BadRequest, rebuild); + Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Export), refusal.Str("message")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id })).Status, "one copy at a time"); + + session.InSession = false; + await WaitIdleAsync(server); + Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories)); + Assert.IsNull(server.App.Services.GetRequiredService().Busy, "the long work is free again once the copy ended"); + } + + [TestMethod] + public async Task AnAccountFolderInsideADestinationIsRefused() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 1); + var usb = await GeneralAsync(server); + var detail = await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}"); + var form = JsonSerializer.Deserialize>(detail.GetProperty("settings").GetRawText())! + .ToDictionary(k => k.Key, k => (object?)k.Value); + + form["folder"] = Path.Combine(usb.Root, "marta"); + var (status, error) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form); + Assert.AreEqual(HttpStatusCode.BadRequest, status); + StringAssert.Contains(error.Str("message"), "cartella di esportazione"); + Assert.IsNull((await server.Db.Accounts.GetAsync(marta.Account.Id))!.Folder, "nothing saved"); + + form["folder"] = server.Temp.Combine("altrove", "marta"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form)).Status); + Assert.IsNull((await server.Db.Exports.GetDestinationAsync(usb.Id))!.PausedAt); + } + + // ------------------------------------------------------------------------------------------------- support + + private const long Free = 500_000_000_000; + + private static ExportRootOptions Mounted(TempFolder esporta) => + ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts(new ExportMount(esporta.Path, "/", "ext4", ReadOnly: false))); + + /// A web host of the Windows edition (any folder) or, with a root, the Docker one, with a disk of 500 GB. + private static Task StartAsync(ExportRootOptions? root = null, bool desktop = true, IEngineSessionState? session = null, IClock? clock = null) => + WebTestServer.StartAsync( + desktop ? new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None } : null, + s => + { + if (root is not null) + { + s.AddSingleton(root); + } + + s.AddSingleton(new FakeExportDisk(Free)); + if (session is not null) + { + s.AddSingleton(session); + } + + if (clock is not null) + { + s.AddSingleton(clock); + } + }); + + private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null) => new + { + scope, + accountId, + path, + label, + types = types ?? ["postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo"], + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + }; + + /// The general folder «usb» in the temporary folder of the host. + private static async Task<(long Id, string Root)> GeneralAsync(WebTestServer server) + { + var root = server.Temp.Combine("usb"); + Directory.CreateDirectory(root); + var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root)); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + return (saved.GetProperty("destination").Long("id"), root); + } + + private static async Task CheckAsync(WebTestServer server, string path) + { + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path }); + Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {answer}"); + return answer; + } + + /// An account with posts of one real photo each, saved as the collection does. + private static async Task<(Account Account, List Entries, List Files)> AddPhotosAsync(WebTestServer server, string username, int count) + { + var account = await server.Db.Accounts.AddAsync(Make.Account(username)); + var entries = new List(); + for (var i = 0; i < count; i++) + { + entries.Add(await AddPostAsync(server, account, $"{username}-{i}", 10 + i)); + } + + var files = entries.SelectMany(e => e.Media).Select(m => Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(m.RelativePath!))).ToList(); + Assert.IsTrue(files.All(File.Exists)); + return (account, entries, files); + } + + private static async Task AddPostAsync(WebTestServer server, Account account, string code, params int[] scenes) + { + var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex()); + var added = await server.Db.Entries.AddAsync( + Make.Entry(account.Id, code, Make.T0.AddDays(-scenes[0])), + [.. scenes.Select((_, i) => Make.Photo(i + 1))]); + foreach (var (media, scene) in added.Stored.Media.Zip(scenes)) + { + await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(scene, 96, 120)), Extension = ".jpg" }); + } + + await ingest.AppendJournalAsync(added.Stored.Entry.Id); + return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + } + + private static async Task StartAndWaitAsync(WebTestServer server, object request) + { + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", request); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + Assert.IsNotEmpty(job.Items("runIds").ToList(), job.ToString()); + await WaitIdleAsync(server); + } + + private static async Task WaitIdleAsync(WebTestServer server) + { + for (var i = 0; i < 600; i++) + { + if (!(await server.GetJsonAsync("/api/export/progress")).Bool("running")) + { + return; + } + + await Task.Delay(50); + } + + Assert.Fail("the copy did not end"); + } + + private static async Task WaitForAsync(Func> probe) + { + for (var i = 0; i < 600; i++) + { + if (await probe() is { } found) + { + return found; + } + + await Task.Delay(50); + } + + Assert.Fail("the expected state did not come"); + return default!; + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.cs new file mode 100644 index 0000000..c85cfb1 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.cs @@ -0,0 +1,298 @@ +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The copies to external folders in a real browser, on the demo (spec §4.10, §10.3, tappa E2): Impostazioni → +/// Esportazione with the note of Docker, the dialog of a destination (folders of /esporta, the check of the folder, the +/// types, the preview of the names), the block «Copie esterne» of an account whose switch acts at once, «Copia in…» from +/// the selection with its summary and the toast that leads to the Dashboard, the «Copie» filter in the address with the +/// marks of the tiles and the menu of the CSV icon, the rows «Copia» of the viewer with «Copia di nuovo», and the +/// Dashboard tab «Esportazione». Chromium only (CI); the selectors follow the pages of WP3, checked on the demo. +/// +[TestClass] +public sealed class ExportInterfaceTests +{ + /// The demo copies its general folder to «Disco USB», under /esporta in the Docker look. + private const string General = "document.querySelector('.cartella-impostazioni .val')?.textContent || ''"; + + /// The «Copie» button of the tools row (the one whose label is a value of the filter). + private const string CopiesButton = "[...document.querySelectorAll('.strumenti .campo.scelta')].find((b) => /^(Copie|Copiati|Non ancora copiati|Tolti o superati)$/.test(b.textContent.trim()))"; + + /// Clicks the button (or menu item) of a scope whose text contains a given text. + private static string ClickText(string scope, string selector, string text) => + $"(() => {{ const b = [...document.querySelectorAll({Js(scope + " " + selector)})].find((x) => x.textContent.includes({Js(text)})); if (!b) return false; b.click(); return true; }})()"; + + /// The last open menu. + private const string LastMenu = "[...document.querySelectorAll('.menu[role=menu]')].pop()"; + + private static string Js(string text) => System.Text.Json.JsonSerializer.Serialize(text); + + [TestMethod] + public async Task TheExportSettingsPageShowsTheGeneralFolderAndTheDockerNote() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-impostazioni-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // Docker: the folders are under /esporta, and the page says so. + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker")); + await ui.WaitAsync($"({General}) !== ''", "la cartella generale " + ui.Report()); + Assert.AreEqual("/esporta/Disco USB", (await ui.EvalAsync(General)).GetString()); + var notes = (await ui.EvalAsync("[...document.querySelectorAll('.avviso')].map((a) => a.textContent).join(' | ')")).GetString()!; + StringAssert.Contains(notes, "sottocartelle di /esporta", "la nota di Docker"); + StringAssert.Contains(notes, "da riprendere", "il lavoro interrotto della demo"); + CollectionAssert.AreEqual( + new[] { "Esportazione", "Cartella generale", "Lo stesso post in due account", "Cartelle degli account" }, + (await ui.EvalAsync("[...document.querySelectorAll('.sezione h2')].map((x) => x.textContent)"))); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.stato-copie')?.textContent || ''")).GetString(), "copiati", "i conteggi della cartella"); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.stato-copie button')].some((b) => b.textContent.includes('Controlla le copie'))")).GetBoolean(), "«Controlla le copie»"); + StringAssert.Contains((await ui.EvalAsync("[...document.querySelectorAll('table tbody tr')].map((r) => r.textContent).join(' | ')")).GetString(), "@studio.lumen.demo", "la cartella sua di un account"); + + // Windows: the path of the folder, no note of Docker. + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + await ui.WaitAsync($"({General}).endsWith('Disco USB') && !({General}).startsWith('/esporta')", "la cartella generale in Windows"); + Assert.IsFalse((await ui.EvalAsync("[...document.querySelectorAll('.avviso')].some((a) => a.textContent.includes('sottocartelle di'))")).GetBoolean(), "nessuna nota di Docker"); + } + + [TestMethod] + public async Task TheDestinationDialogChecksTheFolderAndPreviewsNames() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-dialogo-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker")); + await ui.WaitAsync($"({General}) !== ''", "la cartella generale"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".cartella-impostazioni", "button", "Modifica"))).GetBoolean()); + const string Dialog = "document.querySelector('.dialogo.destinazione')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.sfoglia-voce') && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "il dialogo con le cartelle di /esporta e il controllo"); + CollectionAssert.IsSubsetOf( + new[] { "Chiavetta", "Disco USB", "Studio Lumen" }, + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.sfoglia-voce')].map((b) => b.textContent.trim())")); + Assert.AreEqual("Disco USB", (await ui.EvalAsync($"{Dialog}.querySelector('.sfoglia-voce[aria-pressed=true]').textContent.trim()")).GetString(), "la cartella di adesso è scelta"); + + // Another folder: the check follows it. + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.sfoglia-voce')].find((b) => b.textContent.trim() === 'Chiavetta').click()"); + await ui.WaitAsync($"{Dialog}.querySelector('.controllo-cartella').textContent.includes('/esporta/Chiavetta')", "il controllo della cartella scelta"); + + // «Uno schema suo»: the three schemes of the library to start from, and the tree follows what is typed. + await ui.EvalAsync($"{Dialog}.querySelector('input[value=suo]').click()"); + await ui.WaitAsync($"!{Dialog}.querySelector('.schemi-copie').hidden", "gli schemi"); + Assert.IsTrue((await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.schemi-copie input')].every((i) => i.value.includes('{{account}}'))")).GetBoolean(), "gli schemi partono da quelli della libreria"); + var before = (await ui.EvalAsync($"{Dialog}.querySelector('.albero').textContent")).GetString(); + await ui.EvalAsync($"(() => {{ const i = {Dialog}.querySelector('#schema-copie'); i.value = '{{account}}/{{anno}}/{{codice}}_{{n}}'; i.dispatchEvent(new Event('input', {{ bubbles: true }})); }})()"); + await ui.WaitAsync($"{Dialog}.querySelector('.albero').textContent !== {Js(before!)} && {Dialog}.querySelector('.albero').textContent.startsWith('Chiavetta')", "l'anteprima dei nomi nella cartella scelta"); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.albero').textContent")).GetString(), "marta.demo / 2026"); + + // No type: nothing to save. + await ui.EvalAsync($"{Dialog}.querySelectorAll('.tipi input:checked').forEach((i) => i.click())"); + await ui.WaitAsync($"!{Dialog}.querySelector('.errore-testo').hidden", "«Scegli almeno un tipo.»"); + Assert.IsTrue((await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent.includes('Salva')).disabled")).GetBoolean()); + + // «Annulla» keeps the folder of before. + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + Assert.AreEqual("/esporta/Disco USB", (await ui.EvalAsync(General)).GetString()); + } + + [TestMethod] + public async Task TheAccountBlockSwitchActsAtOnce() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-account-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/account")); + await ui.WaitAsync("document.querySelector('a[href^=\"/account/\"]') !== null", "elenco degli account"); + var id = (await ui.EvalAsync("fetch('/api/accounts').then((r) => r.json()).then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/account/{id}/impostazioni")); + const string Block = "document.querySelector('.copie-esterne')"; + await ui.WaitAsync($"{Block}?.querySelector('.conteggio-copie') != null", "il blocco «Copie esterne»"); + Assert.IsTrue((await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').checked")).GetBoolean(), "«Esporta questo account» acceso"); + StringAssert.Contains((await ui.EvalAsync($"{Block}.textContent")).GetString(), "Nella cartella generale"); + StringAssert.Contains((await ui.EvalAsync($"{Block}.querySelector('.conteggio-copie').textContent")).GetString(), "non ancora copiati"); + + // Off: at once, without «Salva», the server knows it and the block says what it means. + await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').click()"); + await ui.WaitAsync($"{Block}.textContent.includes('Questo account non si esporta')", "il blocco spento"); + await ui.WaitAsync($"fetch('/api/accounts/{id}').then((r) => r.json()).then((j) => j.export.enabled === false)", "spento sul server"); + await ui.WaitAsync("[...document.querySelectorAll('.brevi .breve')].some((b) => b.textContent.includes('non si copia più'))", "l'avviso breve"); + Assert.IsFalse((await ui.EvalAsync($"[...{Block}.querySelectorAll('button')].some((b) => b.textContent.includes('Copia in'))")).GetBoolean(), "niente «Copia in…» da spento"); + + // On again. + await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').click()"); + await ui.WaitAsync($"{Block}.querySelector('.conteggio-copie')?.textContent.includes('non ancora copiati') && {Block}.querySelector('input[role=switch]').checked", "di nuovo acceso"); + await ui.WaitAsync($"fetch('/api/accounts/{id}').then((r) => r.json()).then((j) => j.export.enabled === true)", "acceso sul server"); + } + + [TestMethod] + public async Task CopyInFromTheSelectionShowsTheSummaryAndStarts() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-selezione-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // The newest entries of marta.demo (general folder) with a file still to copy. The demo places its entries by the + // hour it is built (decision of 26 November 2026), so how many files they have is asked of the plan, not assumed. + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico"); + var marta = (await ui.EvalAsync("fetch('/api/accounts').then((r) => r.json()).then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?copie=non-copiati&account={marta}")); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 1 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico dei non ancora copiati"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); + await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].slice(0, 3).forEach((t) => t.click())"); + var files = (await ui.EvalAsync( + "fetch('/api/export/plan', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, " + + "body: JSON.stringify({ entryIds: [...document.querySelectorAll('.mosaico .tess')].slice(0, 3).map((t) => Number(t.dataset.id)), copyAgain: false }) })" + + ".then((r) => r.json()).then((j) => j.files)")).GetInt32(); + Assert.IsGreaterThan(0, files, "«Non ancora copiati» has files to copy"); + const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))"; + await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…» nella barra della scelta"); + await ui.EvalAsync($"({CopyIn}).click()"); + + const string Dialog = "document.querySelector('.dialogo.copia-in')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo"); + var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!; + StringAssert.StartsWith(summary, $"{files} file", summary); + StringAssert.Contains(summary, "circa", "lo spazio"); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.destinazioni-copia').textContent")).GetString(), "In Disco USB"); + Assert.AreEqual($"Copia {files} file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString()); + + await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + await ui.WaitAsync("document.querySelector('.brevi .breve a.breve-link') !== null", "l'avviso breve con il collegamento"); + Assert.AreEqual("/dashboard/esportazione", (await ui.EvalAsync("new URL(document.querySelector('.brevi .breve a.breve-link').href).pathname")).GetString()); + + // The job is in the Dashboard tab, finished: the demo copies at once. + await ui.EvalAsync("document.querySelector('.brevi .breve a.breve-link').click()"); + await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .elenco-attivita li') !== null", "la linguetta «Esportazione»"); + await ui.WaitAsync($"document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('{files} di {files} file')", $"il lavoro di {files} file " + ui.Report()); + } + + [TestMethod] + public async Task TheCopiesFilterIsRememberedInTheAddressAndTheTilesShowTheCopiedMark() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-filtro-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // «Copiati» from the address: the button says it, every tile has the mark. + await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=copiati")); + await ui.WaitAsync($"({CopiesButton}) && document.querySelectorAll('.mosaico .tess').length > 0", "la Libreria con «Copiati»"); + Assert.AreEqual("Copiati", (await ui.EvalAsync($"({CopiesButton}).textContent.trim()")).GetString()); + Assert.IsTrue((await ui.EvalAsync($"({CopiesButton}).classList.contains('attivo')")).GetBoolean()); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].every((t) => t.querySelector('.segno span.copia:not(.parte)') !== null)")).GetBoolean(), "il segno «copiato» su ogni tessera " + ui.Report()); + Assert.AreEqual("copia", (await ui.EvalAsync("document.querySelector('.mosaico .tess .segno').lastElementChild.className")).GetString(), "il segno sta per ultimo"); + + // The menu of the filter: «Tolti o superati» goes to the address and stays after a reload. + await ui.EvalAsync($"({CopiesButton}).click()"); + await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitemradio]').length === 4", "il menu delle copie"); + CollectionAssert.AreEqual( + new[] { "Tutti", "Non ancora copiati", "Copiati", "Tolti o superati" }, + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].map((b) => b.textContent.trim())")); + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].find((b) => b.textContent.trim() === 'Tolti o superati').click()"); + await ui.WaitAsync("new URLSearchParams(location.search).get('copie') === 'tolti'", "«copie=tolti» nell'indirizzo"); + await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=tolti")); + await ui.WaitAsync($"({CopiesButton})?.textContent.trim() === 'Tolti o superati'", "il filtro dopo il ricaricamento"); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length > 0", "le tessere dei tolti o superati"); + + // The CSV icon is a menu: the list, and «Copia i file in…» of what the filter shows. + await ui.EvalAsync("document.querySelector('.strumenti button[aria-label=Esporta]').click()"); + await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitem]').length === 2", "il menu dell'icona CSV"); + CollectionAssert.AreEqual( + new[] { "Esporta l'elenco (CSV)", "Copia i file in…" }, + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitem]')].map((b) => b.textContent.trim())")); + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitem]')].find((b) => b.textContent.includes('Copia i file')).click()"); + await ui.WaitAsync("document.querySelector('.dialogo.copia-in .di-nuovo input') != null", "«Copia in…» del filtro, con «Copia di nuovo anche…»"); + Assert.IsFalse((await ui.EvalAsync("document.querySelector('.dialogo.copia-in .di-nuovo input').checked")).GetBoolean(), "«Copia di nuovo» spento"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.dialogo.copia-in .di-nuovo').textContent")).GetString(), "Copia di nuovo anche i"); + await ui.EvalAsync("[...document.querySelectorAll('.dialogo.copia-in footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.copia-in') === null", "il dialogo si chiude"); + + // «Tutti» takes the filter out of the address. + await ui.EvalAsync($"({CopiesButton}).click()"); + await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitemradio]').length === 4", "il menu delle copie"); + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].find((b) => b.textContent.trim() === 'Tutti').click()"); + await ui.WaitAsync("!new URLSearchParams(location.search).has('copie')", "nessun filtro nell'indirizzo"); + Assert.AreEqual("Copie", (await ui.EvalAsync($"({CopiesButton}).textContent.trim()")).GetString()); + } + + [TestMethod] + public async Task TheViewerShowsCopyRowsWithCopyAgain() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-visualizzatore-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // «Tutte le foto» with «Tolti o superati»: every tile is a file whose copy was removed or superseded. + await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=tolti")); + await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria con «Tolti o superati»"); + await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()"); + await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && document.querySelector('.mosaico .tess') !== null", "«Tutte le foto»"); + + // The first of those files that is on disk (the demo shares the bytes of a picture with a video that has no file, + // and which comes first depends on the hour the demo is built): «Copia in…» is offered only for a file on disk. + var target = (await ui.EvalAsync( + "(async () => { const j = await (await fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000')).json(); " + + "for (const tile of j.tiles) { if (!tile.cover) continue; const e = await (await fetch('/api/entries/' + tile.id)).json(); " + + "const m = e.media.find((x) => x.id === tile.cover.mediaId); if (m && m.available) return tile.cover.mediaId; } return 0; })()")).GetInt64(); + Assert.IsGreaterThan(0L, target, "a «tolto o superato» file on disk"); + var tile = $"document.querySelector('.mosaico .tess[data-id=\"{target}\"]')"; + await ui.WaitAsync($"{tile} !== null", "la tessera del file"); + await ui.EvalAsync($"{tile}.click()"); + + await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "le righe «Copia» del visualizzatore " + ui.Report()); + var row = (await ui.EvalAsync("document.querySelector('.vis .riga-copia').textContent")).GetString()!; + Assert.IsTrue(row.StartsWith("Tolto da Disco USB", StringComparison.Ordinal) || row.StartsWith("Superato in Disco USB", StringComparison.Ordinal), row); + Assert.AreEqual("Copia", (await ui.EvalAsync("document.querySelector('.vis .riga-copia').previousElementSibling.textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.vis button')].some((b) => b.textContent.trim() === 'Copia in…')")).GetBoolean(), "«Copia in…» in fondo al pannello"); + + // «Copia di nuovo»: the job starts, with its toast, and the file is copied again (no longer «tolto o superato»). + const string Replaced = "fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000').then((r) => r.json()).then((j) => j.tiles.length)"; + var before = (await ui.EvalAsync(Replaced)).GetInt32(); + Assert.IsGreaterThan(0, before); + await ui.EvalAsync("document.querySelector('.vis .riga-copia .copia-di-nuovo').click()"); + await ui.WaitAsync("document.querySelector('.brevi .breve a.breve-link') !== null", "l'avviso breve del lavoro"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.brevi .breve').textContent")).GetString(), "Copia avviata"); + await ui.WaitAsync($"({Replaced}).then((n) => n < {before})", "il file copiato di nuovo"); + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))"); + await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude"); + } + + [TestMethod] + public async Task TheDashboardExportTabShowsProgressAndResume() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-dashboard-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // The engine tab says there is a copy to resume and leads to the export tab. + await ui.OpenAsync(new Uri(demo.Address, "/dashboard")); + const string Notice = "[...document.querySelectorAll('.avviso')].find((a) => a.textContent.includes('da riprendere'))"; + await ui.WaitAsync($"({Notice}) !== undefined", "l'avviso della copia da riprendere"); + CollectionAssert.AreEqual(new[] { "Motore", "Esportazione" }, await ui.EvalAsync("[...document.querySelectorAll('.linguette-dashboard a')].map((a) => a.textContent)")); + await ui.EvalAsync($"({Notice}).querySelector('a').click()"); + + await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .riga-riprendi') !== null", "la linguetta «Esportazione»"); + Assert.AreEqual("Esportazione", (await ui.EvalAsync("document.querySelector('.linguette-dashboard a.qui').textContent")).GetString()); + CollectionAssert.AreEqual(new[] { "In corso", "Da riprendere", "Ultimi lavori" }, await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard h2')].map((x) => x.textContent)")); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.copia-in-corso').textContent")).GetString(), "Nessuna copia al lavoro"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.riga-riprendi').textContent")).GetString(), "interrotta"); + + // «Resoconto» of the last job. + await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard .elenco-attivita li')][0].querySelector('button').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.resoconto-copia') !== null", "il resoconto"); + StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia h2').textContent")).GetString(), "Resoconto"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia').textContent")).GetString(), "Per account"); + await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia header button').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.resoconto-copia') === null", "il resoconto si chiude"); + + // «Riprendi»: the job goes on (the demo copies at once) and leaves «Da riprendere». + Assert.IsTrue((await ui.EvalAsync(ClickText(".riga-riprendi", "button", "Riprendi"))).GetBoolean()); + await ui.WaitAsync("[...document.querySelectorAll('.brevi .breve')].some((b) => b.textContent.includes('ripresa'))", "«Copia ripresa»"); + await ui.WaitAsync("document.querySelector('.esportazione-dashboard .riga-riprendi') === null", "niente più da riprendere " + ui.Report()); + } +} diff --git a/tests/Febe.Tests/Web/HostingAndSecurityTests.cs b/tests/Febe.Tests/Web/HostingAndSecurityTests.cs index fa11106..d6da58c 100644 --- a/tests/Febe.Tests/Web/HostingAndSecurityTests.cs +++ b/tests/Febe.Tests/Web/HostingAndSecurityTests.cs @@ -17,7 +17,7 @@ public sealed class HostingAndSecurityTests [ "/", "/libreria", "/account", "/account/12", "/account/12/impostazioni", "/attivita", "/importa", "/impostazioni/generali", "/impostazioni/limiti", "/impostazioni/collegamento", "/impostazioni/notifiche", - "/impostazioni/dati", "/impostazioni/informazioni", "/browser", + "/impostazioni/dati", "/impostazioni/esportazione", "/impostazioni/informazioni", "/browser", "/dashboard/esportazione", ]; [TestMethod] diff --git a/tools/Febe.Schermate/Shots.cs b/tools/Febe.Schermate/Shots.cs index 9648a6e..9d71242 100644 --- a/tools/Febe.Schermate/Shots.cs +++ b/tools/Febe.Schermate/Shots.cs @@ -50,6 +50,17 @@ internal static class Shots new("/doppioni?tema=chiaro", "doppioni-download.png"), new("/libreria?scena=scollegato&tema=chiaro", "primo-avvio.png", Step: "benvenuto.js"), new("/libreria?scena=errore&tema=chiaro", "errore-configurazione.png"), + + // Part 3: copie esterne (tappa E2, spec §4.10 and §10.3, composed from mockups 08, 07, 05, 13, 09, 01, 02, 06). + // No step starts a copy: the demo's copies stay as they were seeded. + new("/impostazioni/esportazione?tema=chiaro", "15-impostazioni-esportazione.png"), + new("/impostazioni/esportazione?tema=chiaro&veste=docker", "15-impostazioni-esportazione-docker.png"), + new("/impostazioni/esportazione?tema=chiaro", "16-destinazione.png", 1440, 1000, Step: "destinazione.js"), + new("/account/3/impostazioni?tema=chiaro", "17-account-copie-esterne.png", 1440, 1000, Step: "account-copie.js"), + new("/libreria?tema=chiaro", "18-copia-in.png", Step: "copia-in.js"), + new("/libreria?copie=copiati&tema=chiaro", "19-libreria-copie.png", Step: "menu-csv.js"), + new("/libreria?copie=tolti&tema=chiaro", "20-visualizzatore-copie.png", Step: "visualizzatore-copie.js"), + new("/dashboard/esportazione?tema=chiaro", "21-dashboard-esportazione.png"), ]; /// diff --git a/tools/Febe.Schermate/passi/account-copie.js b/tools/Febe.Schermate/passi/account-copie.js new file mode 100644 index 0000000..90761e7 --- /dev/null +++ b/tools/Febe.Schermate/passi/account-copie.js @@ -0,0 +1,13 @@ +// Scrolls the account's Impostazioni down to «Cartella» and the block «Copie esterne» under it (spec §4.10, tappa E2; +// composed from mockup 05): the switch, the account's own folder, the files still to copy and «Copia in…». +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let block = null; +for (let i = 0; i < 50 && !block; i++) { + block = document.querySelector('.copie-esterne'); + if (!block) await sleep(100); +} +const body = document.querySelector('.corpo'); +const folder = block.previousElementSibling || block; +body.scrollTop = folder.getBoundingClientRect().top - body.getBoundingClientRect().top + body.scrollTop - 24; +await sleep(400); +return block.querySelector('.conteggio-copie')?.textContent; diff --git a/tools/Febe.Schermate/passi/copia-in.js b/tools/Febe.Schermate/passi/copia-in.js new file mode 100644 index 0000000..7fa7771 --- /dev/null +++ b/tools/Febe.Schermate/passi/copia-in.js @@ -0,0 +1,13 @@ +// «Copia in…» on the whole Libreria, from the menu of the CSV icon (spec §4.10, §10.3, tappa E2; composed from the +// dialogs of mockup 13 and mockup 09): the summary line, one row per folder the files go to, «Copia di nuovo anche i N +// tolti o superati» unchecked. Nothing is started. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const button = () => [...document.querySelectorAll('.strumenti button')].find((b) => (b.getAttribute('aria-label') || '').startsWith('Esporta')); +for (let i = 0; i < 50 && !(button() && document.querySelector('.tess[data-id]')); i++) await sleep(100); +button().click(); +await sleep(400); +[...document.querySelectorAll('.menu button, .menu [role=menuitem]')].find((x) => x.textContent.includes('Copia'))?.click(); +for (let i = 0; i < 100 && !document.querySelector('.dialogo.copia-in .riepilogo-copia'); i++) await sleep(100); +await sleep(300); +document.activeElement?.blur(); +return document.querySelector('.dialogo.copia-in .riepilogo-copia')?.textContent; diff --git a/tools/Febe.Schermate/passi/destinazione.js b/tools/Febe.Schermate/passi/destinazione.js new file mode 100644 index 0000000..d638f24 --- /dev/null +++ b/tools/Febe.Schermate/passi/destinazione.js @@ -0,0 +1,22 @@ +// Opens «Modifica…» on the general folder of Impostazioni → Esportazione (spec §4.10, tappa E2; composed from mockup 08 +// and the dialogs of mockup 13), chooses «Uno schema suo» and changes the first scheme, so «Risultato» shows the tree. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +let edit = null; +for (let i = 0; i < 50 && !edit; i++) { + edit = [...document.querySelectorAll('.cartella-impostazioni .btn')].find((b) => b.textContent.includes('Modifica')); + if (!edit) await sleep(100); +} +edit.click(); +let own = null; +for (let i = 0; i < 50 && !own; i++) { + own = document.querySelector('.dialogo.destinazione input[type=radio][value=suo]'); + if (!own) await sleep(100); +} +own.click(); +await sleep(400); +const scheme = document.getElementById('schema-copie'); +scheme.value = ['{account}', '{anno}', '{tipo}', '{data}_{ora}_{codice}_{n}'].join(String.fromCharCode(92)); +scheme.dispatchEvent(new Event('input', { bubbles: true })); +await sleep(1500); +document.activeElement?.blur(); +return document.querySelector('.dialogo.destinazione .albero')?.textContent.slice(0, 120); diff --git a/tools/Febe.Schermate/passi/menu-csv.js b/tools/Febe.Schermate/passi/menu-csv.js new file mode 100644 index 0000000..b675c16 --- /dev/null +++ b/tools/Febe.Schermate/passi/menu-csv.js @@ -0,0 +1,8 @@ +// Opens the menu of the CSV icon in the Libreria (spec §4.10, tappa E2; composed from mockup 01): «Esporta l'elenco +// (CSV)» and «Copia i file in…». The address chooses «Copie: Copiati», so every tile has the copy mark. +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const button = () => [...document.querySelectorAll('.strumenti button')].find((b) => (b.getAttribute('aria-label') || '').startsWith('Esporta')); +for (let i = 0; i < 50 && !(button() && document.querySelector('.tess[data-id]')); i++) await sleep(100); +button().click(); +await sleep(600); +return [document.querySelector('.quanti')?.textContent, document.querySelector('.menu')?.textContent]; diff --git a/tools/Febe.Schermate/passi/visualizzatore-copie.js b/tools/Febe.Schermate/passi/visualizzatore-copie.js new file mode 100644 index 0000000..166014a --- /dev/null +++ b/tools/Febe.Schermate/passi/visualizzatore-copie.js @@ -0,0 +1,16 @@ +// Opens in the viewer a photo whose copy was taken away from the folder, with the copy row and «Copia di nuovo» in the +// File panel (spec §4.10, tappa E2; composed from mockup 02). The address chooses «Copie: Tolti o superati». +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +for (let i = 0; i < 50 && !document.querySelector('.tess[data-id]'); i++) await sleep(100); +document.querySelector('.tess[data-id]').click(); +const wanted = () => { + const text = document.querySelector('.vis')?.innerText || ''; + return text.includes('Copia di nuovo') && !text.includes('non è sul disco') && /\n(Post|Storia), foto/.test(text); +}; +await sleep(1500); +for (let i = 0; i < 40 && !wanted(); i++) { + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true })); + await sleep(900); +} +await sleep(600); +return document.querySelector('.vis .dove')?.textContent;