E2: copie esterne #71

Merged
Alby96 merged 9 commits from funzione/esportazione-copie into main 2026-11-27 17:59:43 +01:00
138 changed files with 15651 additions and 120 deletions

No files matched your search

+2
View File
@@ -147,6 +147,8 @@ ENV LANG=it_IT.UTF-8 \
DOTNET_gcServer=0 DOTNET_gcServer=0
WORKDIR /app 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"] 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 # Solo la porta dell'interfaccia. La porta di debug del browser ascolta su 127.0.0.1 dentro il contenitore e non si
+4
View File
@@ -43,6 +43,9 @@ services:
- ${FEBE_LIBRERIA:-/srv/febe/libreria}:/libreria - ${FEBE_LIBRERIA:-/srv/febe/libreria}:/libreria
# Cartelle da importare, sempre in sola lettura. # Cartelle da importare, sempre in sola lettura.
- ${FEBE_IMPORTA:-/srv/febe/importa}:/importa:ro - ${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: environment:
FEBE_PASSWORD: ${FEBE_PASSWORD:?Imposta FEBE_PASSWORD, la password dell interfaccia} FEBE_PASSWORD: ${FEBE_PASSWORD:?Imposta FEBE_PASSWORD, la password dell interfaccia}
TZ: Europe/Rome TZ: Europe/Rome
@@ -55,4 +58,5 @@ services:
# FEBE_SENZA_SANDBOX: "1" # solo se Chromium non parte: vedi docs/docker.md, «Sandbox» # 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_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_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. # Chromium usa /tmp invece della memoria condivisa (--disable-dev-shm-usage): shm_size non serve.
+11 -1
View File
@@ -8,7 +8,9 @@
# Sempre exec, mai un processo figlio: il server prende il posto di questo script come processo 1 del contenitore # 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. # (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). # 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 # 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é. # pagina, invece di un contenitore che si riavvia senza dire perché.
set -eu set -eu
@@ -63,6 +65,14 @@ if [ -d /libreria ] && [ "$(stat -c '%u' /libreria)" = "0" ]; then
chown "${PUID}:${PGID}" /libreria 2>/dev/null || true chown "${PUID}:${PGID}" /libreria 2>/dev/null || true
fi 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 export HOME=/dati/home
echo "Febe: avvio come utente ${PUID}, gruppo ${PGID}, fuso ${TZ:-Europe/Rome}, lingua ${LANG:-it_IT.UTF-8}." 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 "$@" exec setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups "$@"
+3 -1
View File
@@ -9,7 +9,7 @@
<Privileged>false</Privileged> <Privileged>false</Privileged>
<Support>http://192.168.30.23:3000/Alby96/Febe/issues</Support> <Support>http://192.168.30.23:3000/Alby96/Febe/issues</Support>
<Project>http://192.168.30.23:3000/Alby96/Febe</Project> <Project>http://192.168.30.23:3000/Alby96/Febe</Project>
<Overview>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.</Overview> <Overview>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.</Overview>
<Category>Backup: MediaApp:Photos</Category> <Category>Backup: MediaApp:Photos</Category>
<WebUI>http://[IP]:[PORT:8480]/</WebUI> <WebUI>http://[IP]:[PORT:8480]/</WebUI>
<TemplateURL>http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml</TemplateURL> <TemplateURL>http://192.168.30.23:3000/Alby96/Febe/raw/branch/main/docker/unraid/febe.xml</TemplateURL>
@@ -26,6 +26,7 @@
<Config Name="Dati (/dati)" Target="/dati" Default="/mnt/user/appdata/febe" Mode="rw" Description="Database, profilo del browser con la sessione di Instagram, miniature, copie giornaliere del database, registro. Deve stare su un disco locale: la cartella delle applicazioni sul disco di cache. Mai una condivisione di rete." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/febe</Config> <Config Name="Dati (/dati)" Target="/dati" Default="/mnt/user/appdata/febe" Mode="rw" Description="Database, profilo del browser con la sessione di Instagram, miniature, copie giornaliere del database, registro. Deve stare su un disco locale: la cartella delle applicazioni sul disco di cache. Mai una condivisione di rete." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/febe</Config>
<Config Name="Libreria (/libreria)" Target="/libreria" Default="/mnt/user/Febe" Mode="rw" Description="Dove finiscono foto e video, una cartella per account. Puo' stare anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/Febe</Config> <Config Name="Libreria (/libreria)" Target="/libreria" Default="/mnt/user/Febe" Mode="rw" Description="Dove finiscono foto e video, una cartella per account. Puo' stare anche su una condivisione. Febe non cancella e non sostituisce mai un file da solo." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/Febe</Config>
<Config Name="Da importare (/importa)" Target="/importa" Default="/mnt/user/Febe-importa" Mode="ro" Description="Cartelle con foto e video che hai gia', da importare dalla pagina Importa. Sempre in sola lettura: Febe copia, non tocca gli originali." Type="Path" Display="always" Required="false" Mask="false">/mnt/user/Febe-importa</Config> <Config Name="Da importare (/importa)" Target="/importa" Default="/mnt/user/Febe-importa" Mode="ro" Description="Cartelle con foto e video che hai gia', da importare dalla pagina Importa. Sempre in sola lettura: Febe copia, non tocca gli originali." Type="Path" Display="always" Required="false" Mask="false">/mnt/user/Febe-importa</Config>
<Config Name="Copie esterne (/esporta)" Target="/esporta" Default="" Mode="rw" Description="Facoltativo: cartella dove Febe copia i file per le copie esterne (SPECIFICA §4.10), per esempio un disco USB montato con Unassigned Devices. Serve anche FEBE_ESPORTA=1. Lascia vuoto per non usarlo: senza una cartella montata qui Febe non scrive nulla fuori dalla libreria." Type="Path" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="Password dell'interfaccia" Target="FEBE_PASSWORD" Default="" Mode="" Description="Obbligatoria. Senza password Febe mostra solo una pagina che spiega il problema: il motore e il browser non partono. Usa una frase lunga che non usi altrove (non quella di Instagram)." Type="Variable" Display="always" Required="true" Mask="true"></Config> <Config Name="Password dell'interfaccia" Target="FEBE_PASSWORD" Default="" Mode="" Description="Obbligatoria. Senza password Febe mostra solo una pagina che spiega il problema: il motore e il browser non partono. Usa una frase lunga che non usi altrove (non quella di Instagram)." Type="Variable" Display="always" Required="true" Mask="true"></Config>
<Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario: orari dei nomi dei file, fascia oraria del motore e fuso dichiarato dal browser." Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config> <Config Name="TZ" Target="TZ" Default="Europe/Rome" Mode="" Description="Fuso orario: orari dei nomi dei file, fascia oraria del motore e fuso dichiarato dal browser." Type="Variable" Display="advanced" Required="false" Mask="false">Europe/Rome</Config>
<Config Name="PUID" Target="PUID" Default="99" Mode="" Description="Utente dei file (su Unraid 99, nobody). Il browser non gira mai come root." Type="Variable" Display="advanced" Required="false" Mask="false">99</Config> <Config Name="PUID" Target="PUID" Default="99" Mode="" Description="Utente dei file (su Unraid 99, nobody). Il browser non gira mai come root." Type="Variable" Display="advanced" Required="false" Mask="false">99</Config>
@@ -34,4 +35,5 @@
<Config Name="FEBE_SENZA_SANDBOX" Target="FEBE_SENZA_SANDBOX" Default="" Mode="" Description="Lasciala vuota. Mettila a 1 solo se il registro dice che Chromium non parte per la sandbox: e' un compromesso, spiegato in docs/docker.md." Type="Variable" Display="advanced" Required="false" Mask="false"></Config> <Config Name="FEBE_SENZA_SANDBOX" Target="FEBE_SENZA_SANDBOX" Default="" Mode="" Description="Lasciala vuota. Mettila a 1 solo se il registro dice che Chromium non parte per la sandbox: e' un compromesso, spiegato in docs/docker.md." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="FEBE_RACCOLTA" Target="FEBE_RACCOLTA" Default="" Mode="" Description="Lasciala vuota (pagine: Febe legge il sito con il browser, come sempre). richieste: le ricette che il catalogo del sito configura vanno con richieste dirette e la sessione copiata a Ho finito; con Instagram, per ora, non cambia nulla." Type="Variable" Display="advanced" Required="false" Mask="false"></Config> <Config Name="FEBE_RACCOLTA" Target="FEBE_RACCOLTA" Default="" Mode="" Description="Lasciala vuota (pagine: Febe legge il sito con il browser, come sempre). richieste: le ricette che il catalogo del sito configura vanno con richieste dirette e la sessione copiata a Ho finito; con Instagram, per ora, non cambia nulla." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
<Config Name="FEBE_CHIAVE_SESSIONE" Target="FEBE_CHIAVE_SESSIONE" Default="" Mode="" Description="Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (openssl rand -base64 32). Vuota: Febe crea una volta /dati/sessione/chiave.bin, leggibile solo dal proprietario. Se la cambi, rifai l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega." Type="Variable" Display="advanced" Required="false" Mask="true"></Config> <Config Name="FEBE_CHIAVE_SESSIONE" Target="FEBE_CHIAVE_SESSIONE" Default="" Mode="" Description="Facoltativa: la chiave che cifra la sessione salvata, 32 byte in base64 (openssl rand -base64 32). Vuota: Febe crea una volta /dati/sessione/chiave.bin, leggibile solo dal proprietario. Se la cambi, rifai l'accesso. Un valore sbagliato ferma l'avvio con una pagina che lo spiega." Type="Variable" Display="advanced" Required="false" Mask="true"></Config>
<Config Name="FEBE_ESPORTA" Target="FEBE_ESPORTA" Default="" Mode="" Description="Facoltativa: 1 accende le copie esterne, che Febe scrive solo nella cartella montata su /esporta (o in una cartella montata sotto /esporta). Vuota: copie esterne spente." Type="Variable" Display="advanced" Required="false" Mask="false"></Config>
</Container> </Container>
+19 -10
View File
@@ -259,18 +259,18 @@ Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più
### 4.10 Esportazione ### 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». **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.** **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. - 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». - 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. - 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. - **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. - **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: **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 e automatica.**
- **Manuale sempre**: «Copia in…» dalla selezione, dal filtro corrente, dal visualizzatore e dalla scheda dell'account. - **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».** **«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. - 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. - **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»). - 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». - 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.** **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. - **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. - **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. **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 | | `event` | Cronologia leggibile per l'interfaccia |
| `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura | | `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura |
| `import_run`, `import_file` | Importazioni e loro file, con esito e decisione | | `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: 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). - 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). - 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 `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. - 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 ### 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 | | `/dati` | Database, profilo del browser, miniature, copie. Su un disco locale del server |
| `/libreria` | Foto e video | | `/libreria` | Foto e video |
| `/importa` | Sorgenti da importare, in sola lettura | | `/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 | | 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 | | `LANG` | Lingua del contenitore e del browser | it_IT.UTF-8 |
| `PUID`, `PGID` | Utente e gruppo dei file | 99, 100 | | `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_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` | | `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. - 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. - 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). - 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. - 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. - **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. - 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`. - 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 | | 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 | | 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 | | 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) | | 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 | | 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) | | 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 | | Fotogramma | `Frame` | Un'immagine presa da un video |
| Video fermo | `StillVideo` | Video che mostra sempre la stessa immagine: basta un fotogramma | | 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 | | Rimuxaggio | `Remux` | Passaggio di un video in un altro contenitore senza ricodifica |
+41
View File
@@ -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 | `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 | 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-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 |
+49 -3
View File
@@ -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 | | `/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 | | `/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 | | `/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 ## 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_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_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_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` | | `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 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 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 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 ricorsivamente: se Febe non riesce a scriverci, il registro lo dice. Di `/esporta`, solo quando le copie esterne sono
contenitore si ferma con un messaggio. 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) ## 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; - porta 8480;
- `/dati` su `/mnt/user/appdata/febe` (disco di cache); - `/dati` su `/mnt/user/appdata/febe` (disco di cache);
- `/libreria` dove vuoi le foto; `/importa` in sola lettura; - `/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); - **password dell'interfaccia** (obbligatoria, nascosta);
- `TZ`, `PUID` 99, `PGID` 100 tra le impostazioni avanzate; - `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`. - 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
`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 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 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. 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 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 ## Salute
`GET /salute` risponde senza password `{"stato":"ok"}` (200) oppure `{"stato":"problema"}` (503) quando un problema di `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 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 | | 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`) | | 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`). 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 Contiene azioni ed esiti, nomi utente sì; mai password, cookie, tasti, didascalie, corpi delle risposte né indirizzi
+3
View File
@@ -146,6 +146,9 @@ I numeri dell'intestazione e delle linguette restano elementi.
Valgono insieme ai limiti generali: vince sempre il più stretto. 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 - **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. 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: 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 ogni quanto verrà controllato davvero, quanti giorni richiede lo storico (quando il numero dei post è noto), quanto
+4
View File
@@ -35,6 +35,10 @@ solo appena aggiungi un account.
Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprendi»), **«Riprendi»**, **«Apri il Comandi: **«Metti in pausa»** (Febe non apre nulla finché non premi «Riprendi»), **«Riprendi»**, **«Apri il
browser»**, **«Diagnostica»** (vedi sotto). 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 ## 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, Se una prova va storta (Febe si ferma, non trova nulla, scarica meno del previsto) e vuoi farla guardare a qualcuno,
+183
View File
@@ -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».
+3
View File
@@ -47,6 +47,8 @@ fare solo con Instagram o su Windows:
[Installazione su Windows](Installazione-Windows). [Installazione su Windows](Installazione-Windows).
- **Docker, interfaccia, importazione, avvisi (anche Telegram), copie e ricostruzione:** pronti, da provare sul tuo - **Docker, interfaccia, importazione, avvisi (anche Telegram), copie e ricostruzione:** pronti, da provare sul tuo
Unraid. 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 ## 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 | | [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 | | [Libreria](Libreria) | Mosaico, filtri, visualizzatore, eliminazione, esportazione CSV, nomi dei file |
| [Importazione](Importazione) | Portare in libreria foto e video che hai già, senza doppioni | | [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 | | [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 | | [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 | | [Avvisi e Telegram](Avvisi-e-Telegram) | Striscia, notifiche di Windows, messaggi Telegram con un bot tuo |
+22 -1
View File
@@ -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 | | `/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 | | `/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 | | `/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 ## 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_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_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_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 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 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. `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 ## Porte
Si pubblica **solo** la porta dell'interfaccia (8480). La porta di debug del browser (9222) ascolta solo su 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; - porta 8480;
- `/dati` su `/mnt/user/appdata/febe` (disco di cache); - `/dati` su `/mnt/user/appdata/febe` (disco di cache);
- `/libreria` dove vuoi le foto; `/importa` in sola lettura; - `/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); - **password dell'interfaccia** (obbligatoria, nascosta);
- `TZ`, `PUID` 99, `PGID` 100 tra le impostazioni avanzate; - `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`. - 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 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 ## La sandbox di Chromium
+2 -1
View File
@@ -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 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 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: 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, `;` come separatore, codifica UTF-8 con BOM, date e ore locali. Colonne: Account, Tipo, Data, Ora, Codice,
+27 -1
View File
@@ -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 | | 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 | | «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 | | 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 ## Database
| Che cosa vedi | Che cosa fare | | 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) | | 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 |
+5
View File
@@ -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: Febe è un archivio privato: non ripubblica e non condivide nulla. Le esportazioni CSV contengono le didascalie:
trattale come i dati che descrivono. 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.
+5
View File
@@ -124,6 +124,11 @@ vera e non invia messaggi Telegram.
- Scene: `?scena=normale`, `sessione`, `fermo`, `scollegato`, `errore`; tema `?tema=chiaro` o `scuro`; veste - Scene: `?scena=normale`, `sessione`, `fermo`, `scollegato`, `errore`; tema `?tema=chiaro` o `scuro`; veste
`?veste=desktop` o `docker`. `?veste=desktop` o `docker`.
- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/importa?passo=3`, `/doppioni`. - 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: - Per modificare l'interfaccia senza ricompilare:
`FEBE_INTERFACCIA=$PWD/src/Febe.Web/wwwroot dotnet run --project src/Febe.Server -- --demo`, poi basta ricaricare. `FEBE_INTERFACCIA=$PWD/src/Febe.Web/wwwroot dotnet run --project src/Febe.Server -- --demo`, poi basta ricaricare.
+1
View File
@@ -9,6 +9,7 @@
- [Account e impostazioni](Account-e-impostazioni) - [Account e impostazioni](Account-e-impostazioni)
- [Libreria](Libreria) - [Libreria](Libreria)
- [Importazione](Importazione) - [Importazione](Importazione)
- [Copie esterne](Esportazione)
- [Limiti e comportamento](Limiti-e-comportamento) - [Limiti e comportamento](Limiti-e-comportamento)
- [Dashboard e arresti](Dashboard-e-arresti) - [Dashboard e arresti](Dashboard-e-arresti)
- [Avvisi e Telegram](Avvisi-e-Telegram) - [Avvisi e Telegram](Avvisi-e-Telegram)
+80
View File
@@ -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 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. 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/<account>/…`, 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'è.
Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 515 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 447 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

+79
View File
@@ -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) | | `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) | | `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) |
| `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) | | `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 ## 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». 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». - **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) ### 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 Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre
+56 -3
View File
@@ -1,14 +1,67 @@
# Stato # Stato
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché. 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`, Aggiornato il 27 novembre 2026 (tappa E2 Copie esterne; prima, E1 Schema unita in `main` con #69 e la catena della
#60 … #66), versione 0.1.2 in 0.3.0, #60 … #66), versione 0.1.2 in
`main` (il tag `v0.1.2` non è stato creato). **Le attività stanno `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 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. fra le sessioni; ciò che è da fare si legge nelle issue aperte.
## In breve ## 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 **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. 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, 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. account rimosso solo sulle orfane, «Automatica» booleana) cadono le prove che li riguardano.
- **Lasciato a E2 ed E3**: - **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` - 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 (`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); falliscono, ed è voluto (nessun convertito resta sul disco senza traccia);
+13
View File
@@ -130,6 +130,7 @@ disinstallato.
| Programma | `%LOCALAPPDATA%\Programs\Febe\Febe.exe` | Dove l'hai copiato, per la versione portabile | | 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) | | **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` | | **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 - **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 è 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 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 è 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. 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 ## 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 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 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 | | 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 |
+46 -1
View File
@@ -11,6 +11,7 @@ using Febe.Core.Collection.Requests;
using Febe.Core.Collection.Search; using Febe.Core.Collection.Search;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Engine; using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import; using Febe.Core.Import;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Security; 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 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. // the configuration gate answers 503 before any of them runs.
var longWork = new LongWorkGate();
Import = new ImportService(new ImportEnvironment Import = new ImportService(new ImportEnvironment
{ {
Storage = Database, Storage = Database,
@@ -190,9 +192,12 @@ public sealed class FebeApp : IAsyncDisposable
Clock = Clock, Clock = Clock,
Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")), Sources = ImportSourceOptions.Docker(Path.Combine(_temporaryFolder, "importa")),
DataFolder = data.Root, DataFolder = data.Root,
Gate = longWork,
}); });
await StartWebAsync(hooks, services => await StartWebAsync(hooks, services =>
{ {
services.AddSingleton(longWork);
services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false));
services.AddSingleton<IFebeStorage>(Database); services.AddSingleton<IFebeStorage>(Database);
services.AddSingleton(library); services.AddSingleton(library);
services.AddSingleton<IClock>(Clock); services.AddSingleton<IClock>(Clock);
@@ -217,7 +222,15 @@ public sealed class FebeApp : IAsyncDisposable
var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false); var settings = await LibrarySettings.LoadAsync(Database.Settings, o.LibraryFolder, ct).ConfigureAwait(false);
var libraryRoot = o.LibraryFolderFromSettings ? settings.LibraryRoot : o.LibraryFolder; var libraryRoot = o.LibraryFolderFromSettings ? settings.LibraryRoot : o.LibraryFolder;
var importRoot = o.ImportFolder is { } import ? Path.GetFullPath(import) : null; 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) 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."); 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 library = new FebeLibrary(Database, data, layout, Clock, hashes);
var staging = Path.Combine(data.Root, "temporanei"); 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 // 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 // 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). // 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, SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot), Sources = importRoot is null ? ImportSourceOptions.AnyFolder : ImportSourceOptions.Docker(importRoot),
DataFolder = data.Root, DataFolder = data.Root,
Gate = longWork,
}); });
LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false)); LogRecovered(await Import.RecoverAsync(ct).ConfigureAwait(false));
} }
@@ -321,6 +338,10 @@ public sealed class FebeApp : IAsyncDisposable
await StartWebAsync(hooks, s => await StartWebAsync(hooks, s =>
{ {
s.AddSingleton(longWork);
s.AddSingleton(exportRoot);
s.AddSingleton<IExportDisk>(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
s.AddSingleton<IEngineSessionState>(new RuntimeSessionState(services.Runtime));
s.AddSingleton<IFebeStorage>(Database); s.AddSingleton<IFebeStorage>(Database);
s.AddSingleton(library); s.AddSingleton(library);
s.AddSingleton<IClock>(Clock); s.AddSingleton<IClock>(Clock);
@@ -350,6 +371,11 @@ public sealed class FebeApp : IAsyncDisposable
await Web.Services.GetRequiredService<Febe.Web.Import.ImportHub>().GetAsync(ct).ConfigureAwait(false); await Web.Services.GetRequiredService<Febe.Web.Import.ImportHub>().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<Febe.Web.Export.ExportHub>();
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 // 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. // 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 // 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.");
}
}
/// <summary>The part of the start-up line about the copies to external folders (Docker only).</summary>
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) private void LogRecovered(int recovered)
{ {
if (recovered > 0) if (recovered > 0)
+13
View File
@@ -1,6 +1,7 @@
using Febe.Browser.Recipes; using Febe.Browser.Recipes;
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Alerts; using Febe.Core.Alerts;
using Febe.Core.Export;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Security; using Febe.Core.Security;
using Febe.Core.Storage; using Febe.Core.Storage;
@@ -108,6 +109,12 @@ public sealed record FebeAppOptions
/// <summary>Docker: the read-only root of the import sources (/importa). Null: any folder, chosen with the picker.</summary> /// <summary>Docker: the read-only root of the import sources (/importa). Null: any folder, chosen with the picker.</summary>
public string? ImportFolder { get; init; } public string? ImportFolder { get; init; }
/// <summary>
/// Where the copies to external folders may go (spec §4.10, tappa E2). Docker: the subfolders of /esporta, and only
/// when declared (<c>--esporta</c>) and mounted. Windows: any folder, chosen with the picker.
/// </summary>
public ExportRootOptions ExportRoot { get; init; } = ExportRootOptions.AnyFolder;
/// <summary>Time zone of the engine, of file names and (Docker) of the browser.</summary> /// <summary>Time zone of the engine, of file names and (Docker) of the browser.</summary>
public string ZoneId { get; init; } = "Europe/Rome"; public string ZoneId { get; init; } = "Europe/Rome";
@@ -163,4 +170,10 @@ public sealed record FebeAppHooks
/// <summary>Fake free-space probe for the «Disco quasi pieno» alert.</summary> /// <summary>Fake free-space probe for the «Disco quasi pieno» alert.</summary>
public IFreeSpaceProbe? FreeSpace { get; init; } public IFreeSpaceProbe? FreeSpace { get; init; }
/// <summary>Fake mount table for /esporta (it replaces the one of <see cref="FebeAppOptions.ExportRoot"/>).</summary>
public IExportMounts? ExportMounts { get; init; }
/// <summary>Fake free space and file size limit of the export folders.</summary>
public IExportDisk? ExportDisk { get; init; }
} }
+106
View File
@@ -0,0 +1,106 @@
using System.Diagnostics.CodeAnalysis;
namespace Febe.Core.Abstractions;
/// <summary>The long pieces of work that never run together (spec §4.10: «esportazione, importazione e ricostruzione non girano insieme»).</summary>
public enum LongWorkKind
{
/// <summary>An import job: analysis or copy (spec §9).</summary>
Import,
/// <summary>A job of copies to external folders (spec §4.10).</summary>
Export,
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
Rebuild,
}
/// <summary>
/// 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.
/// </summary>
public sealed class LongWorkGate
{
private readonly Lock _lock = new();
private Lease? _holder;
/// <summary>Who holds the gate, or null when it is free.</summary>
public LongWorkKind? Busy
{
get
{
lock (_lock)
{
return _holder?.Kind;
}
}
}
/// <summary>
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
/// kind, the same one included) holds it.
/// </summary>
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;
}
}
/// <summary>The Italian answer when <paramref name="wanted"/> cannot start because <paramref name="busy"/> is running.</summary>
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);
}
}
}
}
@@ -0,0 +1,29 @@
using Febe.Core.Engine;
namespace Febe.Core.Export;
/// <summary>Whether the engine is in a session now: copies never run during one (spec §4.10, decision D11 of tappa E2).</summary>
public interface IEngineSessionState
{
bool InSession { get; }
}
/// <summary>No engine (tests, a start with problems): never in a session.</summary>
public sealed class NoEngineSession : IEngineSessionState
{
public static readonly NoEngineSession Instance = new();
private NoEngineSession()
{
}
public bool InSession => false;
}
/// <summary>The session of the running engine.</summary>
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;
}
+31
View File
@@ -0,0 +1,31 @@
using Febe.Core.Domain;
namespace Febe.Core.Export;
/// <summary>«Esporta questo account» (spec §4.10).</summary>
public static class ExportAccounts
{
/// <summary>On when Alberto never chose: decision of Alberto, 27 November 2026 (D1 of tappa E2).</summary>
public const bool DefaultEnabled = true;
/// <summary>The switch of an account from its stored choice (null: none recorded).</summary>
public static bool IsEnabled(bool? stored) => stored ?? DefaultEnabled;
}
/// <summary>
/// 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».
/// </summary>
public sealed record EffectiveDestination(long AccountId, ExportDestination? Destination, bool Enabled)
{
/// <summary>The account's own folder.</summary>
public bool IsOwn => Destination?.Scope == ExportScope.Account;
public bool HasDestination => Destination is not null;
/// <summary>The switch is on and there is a destination: files of the account may be copied (D3).</summary>
public bool Exports => Enabled && Destination is not null;
/// <summary>The account's files of this content type are copied (D3, D4).</summary>
public bool Wants(ContentTypes type) => Exports && (Destination!.ContentTypes & type) != ContentTypes.None;
}
+755
View File
@@ -0,0 +1,755 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// One export job towards one destination (spec §4.10 «Come si copia»; decisions D11, D12, D16, D17 of tappa E2):
/// <list type="bullet">
/// <item>before each group of files (at most <see cref="ExportEnvironment.GroupFiles"/> files, or until
/// <see cref="ExportEnvironment.GroupBytes"/> bytes are reached) the destination is checked with a probe file; a failed
/// check pauses the destination and the job, never the red strip;</item>
/// <item>each file is written to a <c>.part</c> 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;</item>
/// <item>a file already at the planned path with the same SHA-256 is adopted, not written again;</item>
/// <item>«Tolto» and «Superato» are never copied again by themselves, only with «Copia di nuovo»;</item>
/// <item>nothing is copied during an engine session: the job waits;</item>
/// <item>resumable: every file has its state, and the target path is recorded before its <c>.part</c> exists.</item>
/// </list>
/// </summary>
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));
/// <summary>
/// Runs (or resumes) a job. A destination that does not answer pauses it (returns, does not throw). On cancellation
/// the job becomes «interrotto» and <see cref="OperationCanceledException"/> is thrown.
/// </summary>
/// <exception cref="KeyNotFoundException">No such job.</exception>
/// <exception cref="InvalidOperationException">The job already ended.</exception>
public async Task<ExportRun> CopyAsync(long runId, IProgress<ExportProgress>? 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<ExportItemState, int>(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<ExportItemState, int>(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;
}
}
/// <summary>
/// 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.
/// </summary>
internal async Task<string?> 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<string?> 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<ExportRun> 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<long> 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<ItemResult> 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);
}
/// <summary>d. and e.: the path, the limits of the disk, adoption, the safe write and its record.</summary>
private async Task<ItemResult> 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<string?>(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);
}
/// <summary>
/// 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).
/// </summary>
private async Task<string> 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;
}
/// <summary>
/// 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 <paramref name="justWritten"/> this job has just written the file at exactly
/// <paramref name="path"/>, 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.
/// </summary>
private async Task<bool> 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;
}
/// <summary>
/// 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.
/// </summary>
private async Task<ItemResult> 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);
}
/// <summary>Files to look at for adoption: the planned path, then the one recorded before a crash and its numbered names.</summary>
private IEnumerable<string> AdoptionCandidates(string root, string planned, string? previous)
{
var seen = new HashSet<string>(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<ItemResult> 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);
}
/// <summary>f.: the item fails, and its copy is «Non riuscito» (the viewer shows it), the job goes on.</summary>
private async Task<ItemResult> 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<ItemResult> 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;
}
}
/// <summary>«Disco pieno»: ERROR_DISK_FULL or ERROR_HANDLE_DISK_FULL on Windows, ENOSPC elsewhere.</summary>
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);
/// <summary>What happened to an item; <see cref="Pause"/> stops the job with the destination paused.</summary>
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<ExportProgress>? progress)
{
private readonly Dictionary<long, ExportDestination?> _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<long, EffectiveDestination> Effective { get; set; } = new Dictionary<long, EffectiveDestination>();
public int FilesDone { get; set; }
public int FilesTotal { get; set; }
public long BytesDone { get; set; }
public long BytesTotal { get; set; }
public Dictionary<ExportItemState, int> ByState { get; set; } = [];
public async Task<ExportDestination?> 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<ExportItemState, int>(ByState),
env.Clock.Now));
}
}
+402
View File
@@ -0,0 +1,402 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>What Alberto sets for a destination (Impostazioni → Esportazione, scheda account → «Copie esterne»).</summary>
/// <param name="Scope">General folder or own folder of an account.</param>
/// <param name="AccountId">The account of an own folder; null for the general folder.</param>
/// <param name="Path">The folder as chosen (Docker: relative to <c>/esporta</c>, or a full path inside it).</param>
/// <param name="Label">Name shown; null: the last segment of the folder.</param>
/// <param name="ContentTypes">At least one type.</param>
/// <param name="NamingScheme">General scheme; null: «Come la libreria».</param>
/// <param name="HighlightNamingScheme">Scheme of highlight collections; null: «Come la libreria».</param>
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
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);
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> Warnings);
/// <summary>A destination in use that now overlaps a protected folder (WP1.10 of tappa E2).</summary>
public sealed record ExportFolderConflict(ExportDestination Destination, ExportFolderProblem Problem);
/// <summary>What Impostazioni and the Dashboard show of a destination.</summary>
/// <param name="Destination">The stored row (paused or not).</param>
/// <param name="Reachable">The folder answered now (and, in Docker, sits on a usable mount).</param>
/// <param name="Problem">Why it is not reachable, or the error of its pause; null when fine.</param>
/// <param name="Counts">Copies per state, every state present.</param>
/// <param name="FreeBytes">Free space when reachable and measurable.</param>
public sealed record ExportDestinationStatus(
ExportDestination Destination,
bool Reachable,
string? Problem,
IReadOnlyDictionary<ExportCopyState, int> Counts,
long? FreeBytes);
/// <summary>
/// Destinations and the switch «Esporta questo account» (spec §4.10 «Destinazioni»), for the API. No file is touched
/// here except through <see cref="ExportFolderCheck"/> (its probe, only in the candidate folder).
/// </summary>
public sealed class ExportDestinations(ExportEnvironment env)
{
/// <summary>The answer to «Togli la cartella».</summary>
public const string RetiredText = "Cartella tolta. I file già copiati restano dove sono.";
/// <summary>A destination with an unfinished job cannot be retired nor moved.</summary>
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));
/// <summary>The name shown for a destination: its label, or the last segment of its folder.</summary>
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;
}
/// <summary>The effective destination of an account (D2) with its switch (D1).</summary>
public async Task<EffectiveDestination> 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);
}
/// <summary>The effective destination of every account, with one read of each table.</summary>
public async Task<IReadOnlyDictionary<long, EffectiveDestination>> 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)));
}
/// <summary>
/// Adds a destination after checking folder (WP1.3), content types and naming schemes.
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be a destination.</exception>
/// <exception cref="ArgumentException">Types, schemes, scope or account are not valid (Italian message).</exception>
public async Task<DestinationSaveResult> 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));
}
}
/// <summary>
/// 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.
/// </summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
/// <exception cref="ExportFolderException">The new folder cannot be a destination.</exception>
/// <exception cref="ArgumentException">Types, schemes, scope or account are not valid.</exception>
/// <exception cref="InvalidOperationException">An unfinished job uses the old folder.</exception>
public async Task<DestinationSaveResult> 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);
}
/// <summary>«Togli la cartella»: only the configuration goes; copies and files stay (<see cref="RetiredText"/>).</summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
/// <exception cref="InvalidOperationException">An unfinished job uses it.</exception>
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);
}
/// <summary>«Esporta questo account».</summary>
/// <exception cref="KeyNotFoundException">No such account.</exception>
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);
}
/// <summary>Checks a folder for the dialog, before saving (WP1.3).</summary>
public async Task<ExportFolderVerdict> CheckFolderAsync(string candidate, CancellationToken ct)
{
var context = await _env.FolderContextAsync(null, ct).ConfigureAwait(false);
return await _env.CreateFolderCheck().CheckAsync(candidate, context, ct).ConfigureAwait(false);
}
/// <summary>
/// Checks again every destination in use against the protected folders, with <paramref name="extraAccountFolders"/>
/// (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.
/// </summary>
public Task<IReadOnlyList<ExportFolderConflict>> RecheckAsync(IReadOnlyList<string>? extraAccountFolders, CancellationToken ct) =>
RecheckAgainstAsync(extraAccountFolders?.Select(f => new ProtectedFolder(f, ProtectedFolderKind.Account, null)).ToList(), ct);
/// <summary>As <see cref="RecheckAsync"/>, with folders of any kind (a new library root is <see cref="ProtectedFolderKind.Library"/>).</summary>
public async Task<IReadOnlyList<ExportFolderConflict>> RecheckAgainstAsync(IReadOnlyList<ProtectedFolder>? 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();
}
/// <summary>
/// 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.
/// </summary>
public async Task<IReadOnlyList<ExportFolderConflict>> 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;
}
/// <summary>Whether a destination answers now, its pause, its copies and its free space.</summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
public async Task<ExportDestinationStatus> 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<Account?> 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));
}
/// <summary>Content types and naming schemes; returns the warnings of the schemes.</summary>
private static List<string> 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<string>();
var warnings = new List<string>();
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<string> 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.";
}
+82
View File
@@ -0,0 +1,82 @@
using Febe.Core.Alerts;
namespace Febe.Core.Export;
/// <summary>Free space and the largest file a destination's disk accepts (a seam: tests give their own).</summary>
public interface IExportDisk
{
/// <summary>Bytes free for Febe on the disk of <paramref name="root"/>; null when it cannot be measured.</summary>
long? FreeBytes(string root);
/// <summary>The largest file the file system accepts (FAT32: 4 GB − 1); null when there is no known limit.</summary>
long? MaxFileBytes(string root);
}
/// <summary>Limits of the space check before each copy (spec §4.10 «Spazio»).</summary>
public static class ExportSpace
{
/// <summary>The margin left free after the next file (decision of Alberto, question Q6 of tappa E2): 64 MiB.</summary>
public const long Margin = 64L * 1024 * 1024;
/// <summary>The largest file on FAT32: 4 GiB − 1 byte.</summary>
public const long Fat32Limit = (4L * 1024 * 1024 * 1024) - 1;
private static readonly HashSet<string> FatTypes = new(StringComparer.OrdinalIgnoreCase) { "FAT32", "FAT", "vfat", "msdos", "fat" };
/// <summary>True for the names Windows (<c>DriveFormat</c>) and Linux (mount type) give to FAT file systems.</summary>
public static bool IsFat(string? fileSystem) => fileSystem is not null && FatTypes.Contains(fileSystem);
}
/// <summary>
/// The real disks: free space through <see cref="DriveFreeSpaceProbe"/> (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.
/// </summary>
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;
}
}
}
+147
View File
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed record ExportEnvironment
{
public required IFebeStorage Storage { get; init; }
/// <summary>The library folder and account folders now.</summary>
public required Func<LibraryLayout> Layout { get; init; }
/// <summary>The Data folder: a destination may not overlap it.</summary>
public required string DataFolder { get; init; }
public required IClock Clock { get; init; }
/// <summary>Docker <c>/importa</c>: a destination may not overlap it. Null on Windows.</summary>
public string? ImportRoot { get; init; }
/// <summary>Where destinations may be chosen (Docker: <c>/esporta</c>).</summary>
public ExportRootOptions Root { get; init; } = ExportRootOptions.AnyFolder;
/// <summary>
/// The full path of a library file present on disk, or null. Null: the library layout (as the web layer's
/// <c>LibraryFileResolver</c>). Use <see cref="ResolveSourcePath"/>.
/// </summary>
public Func<Account, Media, string?>? ResolveSource { get; init; }
/// <summary>Reading and hashing files (library files and files found in a destination).</summary>
public IExportFileSystem FileSystem { get; init; } = ExportFileSystem.Instance;
/// <summary>Free space and the FAT32 limit of a destination.</summary>
public IExportDisk Disk { get; init; } = new SystemExportDisk(new ProcMountInfo());
/// <summary>Copies never run during an engine session.</summary>
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
/// <summary>Shared with import and rebuild: never together (spec §4.10). Null: nothing else to keep out (tests).</summary>
public LongWorkGate? Gate { get; init; }
/// <summary>Time allowed to a check of a destination folder (a disconnected share must not block).</summary>
public TimeSpan FolderCheckTimeout { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>Writes the probe file of a folder check (a seam: tests make it fail or hang); null: the real file.</summary>
public Action<string>? WriteProbe { get; init; }
/// <summary>How often a waiting job looks whether the engine session ended.</summary>
public TimeSpan SessionPoll { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>A group of copies, checked with a probe before it starts: at most this many files…</summary>
public int GroupFiles { get; init; } = 100;
/// <summary>…or this many planned bytes, whichever comes first.</summary>
public long GroupBytes { get; init; } = 1L << 30;
/// <summary>The checker of destination folders of this environment.</summary>
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
/// <summary>The protected folders now (Data, library, account folders, <c>/importa</c>) and the extra ones.</summary>
public Task<ExportFolderContext> FolderContextAsync(IReadOnlyList<ProtectedFolder>? extra, CancellationToken ct) =>
ExportFolderCheck.ContextAsync(Storage, Layout(), DataFolder, ImportRoot, Root, extra, ct);
/// <summary>The full path of a library file present on disk, or null (<see cref="ResolveSource"/> or the layout).</summary>
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;
}
}
}
/// <summary>File operations of the export (a seam, like <c>IImportFileSystem</c>).</summary>
public interface IExportFileSystem
{
/// <summary>Opens a file for reading only.</summary>
Stream OpenRead(string path);
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
Task<string> ComputeSha256Async(string path, CancellationToken ct);
bool FileExists(string path);
/// <summary>Size of a file, or null when it is not there.</summary>
long? FileLength(string path);
}
/// <summary>The real file system.</summary>
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<string> 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;
}
}
}
+450
View File
@@ -0,0 +1,450 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>Why a folder cannot be a destination (spec §4.10 «Cartelle rifiutate»).</summary>
public enum ExportFolderProblemKind
{
Empty,
NotFullyQualified,
OutsideExportRoot,
ExportRootItself,
ParentSegment,
NotMounted,
ReadOnlyMount,
Missing,
NotAFolder,
Link,
RootOfDisk,
PathTooLong,
InsideProtected,
ContainsProtected,
SameAsProtected,
ProbeFailed,
NotResponding,
}
/// <summary>A refused folder: the kind and the Italian message that says why and what to do.</summary>
public sealed record ExportFolderProblem(ExportFolderProblemKind Kind, string Message)
{
/// <summary>The folder overlaps Data, Libreria, an account folder or <c>/importa</c> (the conflicts of a re-check).</summary>
public bool IsOverlap => Kind is ExportFolderProblemKind.InsideProtected or ExportFolderProblemKind.ContainsProtected or ExportFolderProblemKind.SameAsProtected;
}
/// <summary>The outcome of a folder check.</summary>
/// <param name="FullPath">The full path of the candidate (as typed when it could not be resolved).</param>
/// <param name="Problem">Null when the folder is accepted.</param>
public sealed record ExportFolderVerdict(string FullPath, ExportFolderProblem? Problem)
{
public bool Accepted => Problem is null;
}
/// <summary>What a protected folder is.</summary>
public enum ProtectedFolderKind
{
/// <summary>The Data folder.</summary>
Data,
/// <summary>The library folder.</summary>
Library,
/// <summary>The folder of an account (inside the library or outside it).</summary>
Account,
/// <summary>The root of the import sources (Docker <c>/importa</c>).</summary>
Import,
}
/// <summary>A folder a destination may neither be, sit inside nor contain.</summary>
/// <param name="Path">Full path.</param>
/// <param name="Kind">What it is (for the message).</param>
/// <param name="Username">The account of an account folder, when known.</param>
public sealed record ProtectedFolder(string Path, ProtectedFolderKind Kind, string? Username)
{
/// <summary>«la cartella dei dati di Febe», «la cartella dell'account @x»…</summary>
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",
};
}
/// <summary>The folders a candidate is checked against, and where destinations may be chosen.</summary>
public sealed record ExportFolderContext(IReadOnlyList<ProtectedFolder> Protected, ExportRootOptions Root);
/// <summary>A folder or path that cannot be used as a destination; the message (Italian) says why. The API answers 400.</summary>
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;
/// <summary>The kind of refusal, when known.</summary>
public ExportFolderProblemKind? Kind { get; }
}
/// <summary>
/// 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 <b>only in the candidate</b>, so that a drive letter and a UNC
/// path to the same place are recognised. In Data, Libreria, the account folders and <c>/importa</c> 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.
/// </summary>
/// <param name="mounts">The mount table (the root of a file system is refused).</param>
/// <param name="timeout">Time allowed to the checks on disk; 10 s when null.</param>
/// <param name="writeProbe">
/// Writes the probe file at the full path given (a seam: tests make it fail or hang); null writes «Febe» in a new file.
/// </param>
public sealed class ExportFolderCheck(IExportMounts mounts, TimeSpan? timeout = null, Action<string>? writeProbe = null)
{
/// <summary>Prefix of the probe file (a temporary file of <see cref="SafeFileWriter"/>: <c>.febe-prova-*.part</c>).</summary>
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<string> _writeProbe = writeProbe ?? WriteProbeFile;
/// <summary>A new probe file name: <c>.febe-prova-&lt;12 hex&gt;.part</c>.</summary>
public static string NewProbeName() => ProbePrefix + Guid.NewGuid().ToString("N")[..12] + SafeFileWriter.TempSuffix;
/// <summary>
/// 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.
/// </summary>
public static async Task<ExportFolderContext> ContextAsync(
IFebeStorage storage,
LibraryLayout layout,
string dataFolder,
string? importRoot,
ExportRootOptions root,
IReadOnlyList<ProtectedFolder>? extra = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(layout);
ArgumentException.ThrowIfNullOrWhiteSpace(dataFolder);
ArgumentNullException.ThrowIfNull(root);
var folders = new List<ProtectedFolder>
{
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);
}
/// <summary>
/// Checks <paramref name="candidate"/>. Never throws for a refused folder (the verdict says why); only
/// <paramref name="ct"/> cancels it.
/// </summary>
public async Task<ExportFolderVerdict> 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);
}
/// <summary>
/// The identity comparison (decision of 2026-11-27): the candidate is a protected folder, or inside one, when its
/// <see cref="FolderLocation"/> 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.
/// </summary>
private ExportFolderProblem? IdentityOverlap(string full, string shown, IReadOnlyList<ProtectedFolder> 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<FolderLocation>()
.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.");
/// <summary>
/// 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).
/// </summary>
private ExportFolderVerdict ProbeIdentity(string full, string shown, IReadOnlyList<ProtectedFolder> 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/<candidate relative to M> 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;
}
}
/// <summary>
/// Decision D15: on Windows the path is its own root (<c>C:\</c>, <c>\\srv\share</c>); on Linux it is <c>/</c> or
/// exactly a mount point that shows the root of its file system.
/// </summary>
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));
}
+89
View File
@@ -0,0 +1,89 @@
using Febe.Core.Domain;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// The <c>.part</c> 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 (<c>.febe-*.part</c>, the probes included) are touched.
/// </summary>
public static class ExportLeftovers
{
private const int PageSize = 1000;
/// <summary>Removes our temporary files in the folders of the items of <paramref name="run"/>. Returns how many.</summary>
public static async Task<int> 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<string>(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<bool> 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;
}
}
}
+122
View File
@@ -0,0 +1,122 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>What a «Copia in…» is asked for (spec §4.10 «Manuale sempre»).</summary>
public abstract record ExportSelection
{
private ExportSelection()
{
}
/// <summary>Files by id: a selection of «Tutte le foto», a file of the viewer.</summary>
public sealed record Media(IReadOnlyList<long> MediaIds) : ExportSelection;
/// <summary>Entries by id: a grouped selection, an entry of the viewer.</summary>
public sealed record Entries(IReadOnlyList<long> EntryIds) : ExportSelection;
/// <summary>The current filter («Copia i file in…» of the CSV menu).</summary>
public sealed record Filter(LibraryFilter LibraryFilter, MosaicMode Mode) : ExportSelection;
/// <summary>Every file of an account (the account card).</summary>
public sealed record Account(long AccountId) : ExportSelection;
}
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
/// <summary>
/// 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).
/// </summary>
/// <param name="Files">Files to write.</param>
/// <param name="Bytes">Their bytes.</param>
/// <param name="AlreadyCopied">Already in their destination (or, with «Una copia sola», copied for another account).</param>
/// <param name="RemovedOrSuperseded">
/// «Tolti o superati»: never copied again by themselves. With <see cref="ExportJobRequest.CopyAgain"/> they are also
/// counted in <paramref name="Files"/> and <paramref name="Bytes"/>, since they will be written.
/// </param>
/// <param name="NotExported">«Esporta questo account» off, no destination, or a content type the destination does not take.</param>
/// <param name="Missing">«File non presente in libreria».</param>
/// <param name="Destinations">Each destination that gets files, with whether it answers now.</param>
/// <param name="HasDestination">
/// 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.
/// </param>
public sealed record ExportPlan(
int Files,
long Bytes,
int AlreadyCopied,
int RemovedOrSuperseded,
int NotExported,
int Missing,
IReadOnlyList<ExportPlanDestination> Destinations,
bool HasDestination = true)
{
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
}
/// <summary>A destination of a plan.</summary>
/// <param name="Username">The account of an own folder; null for the general folder.</param>
/// <param name="Files">Files to write there.</param>
/// <param name="Paused">The destination is paused (its last check failed).</param>
/// <param name="Problem">Why it cannot be written now (not reachable, not mounted, paused), in Italian; null when fine.</param>
/// <param name="FreeBytes">Free space, when it can be measured.</param>
public sealed record ExportPlanDestination(
long DestinationId,
string Label,
string RootPath,
ExportScope Scope,
string? Username,
int Files,
long Bytes,
bool Paused,
string? Problem,
long? FreeBytes);
/// <summary>What the export job is doing.</summary>
public enum ExportPhase
{
Preparing,
/// <summary>«Controlla le copie».</summary>
Checking,
/// <summary>An engine session is running: copies wait for it to end (decision D11).</summary>
WaitingForSession,
Copying,
Finished,
}
/// <summary>Progress of the export job, for the progress card (polled, D20).</summary>
/// <param name="RunId">The job's run being worked on; null for «Controlla le copie» and when nothing ever ran.</param>
/// <param name="BytesTotal">Bytes of the files still pending when the run (re)started, plus those done since; 0 when unknown.</param>
public sealed record ExportProgress(
long? RunId,
ExportPhase Phase,
int FilesDone,
int FilesTotal,
long BytesDone,
long BytesTotal,
string? CurrentFile,
string? DestinationLabel,
IReadOnlyDictionary<ExportItemState, int> ByState,
DateTimeOffset UpdatedAt)
{
/// <summary>0..1: by bytes when known, otherwise by files.</summary>
public double Fraction => BytesTotal > 0
? Math.Clamp((double)BytesDone / BytesTotal, 0, 1)
: FilesTotal > 0 ? Math.Clamp((double)FilesDone / FilesTotal, 0, 1) : 0;
}
/// <summary>What <c>ExportService.StartAsync</c> did: one run per destination (D6), and the plan it followed.</summary>
public sealed record ExportStart(IReadOnlyList<ExportRun> Runs, ExportPlan Plan);
/// <summary>What «Riprova» of a paused destination did: the reason it is still paused (null: it answers), and the jobs resumed.</summary>
public sealed record ExportRetry(string? Problem, IReadOnlyList<ExportRun> Resumed);
/// <summary>The export job ended (however it ended): the runs it worked on, and whether copies may have changed.</summary>
public sealed record ExportJobFinished(IReadOnlyList<long> RunIds, bool CopiesChanged);
@@ -0,0 +1,35 @@
using Febe.Core.Domain;
using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>
/// 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.
/// </summary>
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(),
};
}
}
+145
View File
@@ -0,0 +1,145 @@
using System.Globalization;
using Febe.Core.Domain;
using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>Paths and content types of the export (spec §4.10).</summary>
public static class ExportPaths
{
/// <summary>Folders compare without case on Windows (and its shares), exactly elsewhere, as the import does.</summary>
public static StringComparison PathComparison { get; } = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
/// <summary>True when <paramref name="path"/> is <paramref name="folder"/> or inside it, as text (full paths).</summary>
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);
}
/// <summary>The same folder, as text.</summary>
public static bool Same(string a, string b) => string.Equals(Trim(a), Trim(b), PathComparison);
/// <summary>A full path without its trailing separator (a root such as <c>C:\</c> or <c>/</c> keeps it).</summary>
public static string Trim(string path)
{
ArgumentNullException.ThrowIfNull(path);
return path.Length > 1 ? Path.TrimEndingDirectorySeparator(path) : path;
}
/// <summary>
/// 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.
/// </summary>
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,
};
/// <summary>Folder of imported files without a known date or code (as the import names it).</summary>
public const string ImportedFolder = "importati";
/// <summary>
/// The path of a copy below the destination root, as sanitized segments, before <see cref="RelativePathFor"/>
/// (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 <c>importati/</c>, 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.
/// </summary>
public static IReadOnlyList<string> 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<string> 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;
}
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength)
{
ArgumentNullException.ThrowIfNull(d);
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath));
}
/// <summary>
/// The name the safe writer gives a file at its <paramref name="attempt"/>-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.
/// </summary>
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));
}
/// <summary>The scheme that names an entry kind.</summary>
public static NamingSchemeUse UseOf(EntryKind kind) => kind switch
{
EntryKind.Highlight => NamingSchemeUse.Highlight,
EntryKind.ProfilePicture => NamingSchemeUse.ProfilePicture,
_ => NamingSchemeUse.General,
};
}
+70
View File
@@ -0,0 +1,70 @@
using Febe.Core.Domain;
namespace Febe.Core.Export;
/// <summary>
/// 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
/// <c>esportazione-in-pausa</c> is not an alert of the engine.
/// </summary>
public static class ExportPause
{
/// <summary>Code of the event written once when a destination goes into pause.</summary>
public const string PausedEventCode = "esportazione-in-pausa";
/// <summary>
/// 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.
/// </summary>
public static async Task<ExportDestination> 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;
}
/// <summary>Clears the pause of a destination after a check succeeded. Returns the stored row.</summary>
public static async Task<ExportDestination> 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;
}
}
+238
View File
@@ -0,0 +1,238 @@
using System.Runtime.CompilerServices;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// 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.
/// </summary>
public sealed class ExportPlanner(ExportEnvironment env)
{
private const int PageSize = 2000;
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
public async Task<ExportPlan> 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);
}
/// <summary>
/// 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.
/// </summary>
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
ExportJobRequest request,
IReadOnlyDictionary<long, EffectiveDestination> 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<long, HashSet<(long AccountId, string Sha256)>>();
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<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
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;
}
}
}
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
/// <summary>The destination a present file goes to (D3), or null when it is not exported.</summary>
private static long? Due(ExportCandidate c, IReadOnlyDictionary<long, EffectiveDestination> effective) =>
IsPresent(c) && effective.TryGetValue(c.AccountId, out var e) && e.Wants(ExportPaths.TypeOf(c.EntryKind, c.MediaKind, c.InHighlight))
? e.Destination!.Id
: null;
}
/// <summary>A candidate with what the plan does with it.</summary>
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false);
internal enum PlannedCopy
{
Write,
AlreadyCopied,
RemovedOrSuperseded,
NotExported,
Missing,
}
/// <summary>Counts of a plan while its files go by.</summary>
internal sealed class PlanTally
{
private readonly Dictionary<long, (int Files, long Bytes)> _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));
}
/// <summary>The plan. With <paramref name="checkDestinations"/> each destination is asked whether it answers now.</summary>
public async Task<ExportPlan> BuildAsync(
ExportEnvironment env,
ExportDestinations destinations,
IReadOnlyDictionary<long, EffectiveDestination> 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<ExportPlanDestination>();
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);
}
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
public IReadOnlyCollection<long> Destinations => _byDestination.Keys;
}
+106
View File
@@ -0,0 +1,106 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>The report of an export job (spec §4.10): counts, per account, and the files that need a look.</summary>
/// <param name="Problems">At most <see cref="ExportReports.MaxProblems"/> lines: failed, missing, and skipped files with a note.</param>
public sealed record ExportReport(
ExportRun Run,
ExportDestination Destination,
int Total,
IReadOnlyDictionary<ExportItemState, int> ByState,
long BytesCopied,
IReadOnlyList<ExportReportAccount> Accounts,
IReadOnlyList<ExportReportLine> Problems);
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
/// <summary>A file of the report, with its reason in Italian.</summary>
public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text);
/// <summary>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).</summary>
public sealed class ExportReports(ExportEnvironment env)
{
public const int MaxProblems = 200;
private const int PageSize = 1000;
/// <summary>A name for files whose account was removed.</summary>
public const string RemovedAccount = "account rimosso";
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
/// <exception cref="KeyNotFoundException">No such job.</exception>
public async Task<ExportReport> 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<long, int[]>();
var problems = new List<ExportReportLine>();
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);
}
}
+344
View File
@@ -0,0 +1,344 @@
using Febe.Core.Import;
using Febe.Core.Library;
namespace Febe.Core.Export;
/// <summary>A mounted file system, as the export needs it (spec §4.10 «Docker e Windows»).</summary>
/// <param name="MountPoint">Where it is mounted.</param>
/// <param name="Root">Folder of its file system shown there (<c>/</c>: the root of that file system).</param>
/// <param name="FileSystemType">File system type (<c>vfat</c> for FAT32).</param>
/// <param name="ReadOnly">Mounted read-only.</param>
/// <param name="Device">
/// The device of its file system (<c>major:minor</c> in <c>mountinfo</c>), 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).
/// </param>
public sealed record ExportMount(string MountPoint, string Root, string FileSystemType, bool ReadOnly, string? Device = null);
/// <summary>The mount table (a seam: tests give their own; Linux reads <c>/proc/self/mountinfo</c>).</summary>
public interface IExportMounts
{
/// <summary>The mount that holds a full path, or null (always null on Windows).</summary>
ExportMount? FindContaining(string fullPath);
/// <summary>Every mount (empty on Windows).</summary>
IReadOnlyList<ExportMount> All();
}
/// <summary>The mounts of this process from <c>/proc/self/mountinfo</c>, read at each call (it is small).</summary>
public sealed class ProcMountInfo(Func<string?>? read = null) : IExportMounts
{
private readonly Func<string?> _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<ExportMount> All() => Read().Select(m => Map(m)!).ToList();
private IReadOnlyList<MountInfoEntry> 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);
}
/// <summary>
/// Where destinations may be chosen. Docker: subfolders of <c>/esporta</c>, only when it is declared
/// (<c>--esporta</c>, <c>FEBE_ESPORTA</c>) and the destination sits on a mount at <c>/esporta</c> or below it (decision of
/// Alberto, question Q2 of tappa E2). Windows: any folder, through the native picker.
/// </summary>
public sealed record ExportRootOptions
{
/// <summary>Docker: the full path of <c>/esporta</c>. Null: any folder.</summary>
public string? Root { get; init; }
/// <summary><c>--esporta</c> or <c>FEBE_ESPORTA</c> (always true without a root).</summary>
public bool Declared { get; init; }
/// <summary>The mount table.</summary>
public IExportMounts Mounts { get; init; } = new ProcMountInfo();
/// <summary>How the page names <see cref="Root"/> (the demo shows «/esporta» for its temporary folder); null: as it is.</summary>
public string? ShownAs { get; init; }
/// <summary>Windows (and development): any folder.</summary>
public static ExportRootOptions AnyFolder { get; } = new() { Declared = true };
/// <summary>Docker: destinations under <paramref name="root"/>.</summary>
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() };
}
}
/// <summary>Whether copies to external folders can be written at all, and why not.</summary>
/// <param name="Active">True: destinations may be created and written.</param>
/// <param name="Root">Docker: the root (<c>/esporta</c>); null on Windows.</param>
/// <param name="Problem">Italian text of the reason when not active.</param>
public sealed record ExportRootState(bool Active, string? Root, string? Problem);
/// <summary>The rules of the export root (spec §4.10, §11): <c>/esporta</c> in Docker, any folder on Windows.</summary>
public static class ExportRoots
{
/// <summary>Copies to external folders are switched off in Docker (not declared).</summary>
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.";
/// <summary>Whether the root is usable: always without a root; in Docker declared and with a mount at or below it.</summary>
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));
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// Subfolders offered by the picker in Docker: <paramref name="relative"/> 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.
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be browsed.</exception>
public static IReadOnlyList<SourceFolderChoice> Browse(ExportRootOptions o, string? relative)
{
var folder = BrowsedFolder(o, relative);
return [.. Subfolders(o, folder).Select(s => s.Choice with { HasSubfolders = HasSubfolders(s.FullPath) })];
}
/// <summary>
/// <see cref="Browse"/> 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 <paramref name="timeout"/>, 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.
/// </summary>
/// <exception cref="ExportFolderException">The folder cannot be browsed, or does not answer in time.</exception>
public static Task<IReadOnlyList<SourceFolderChoice>> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, CancellationToken ct) =>
BrowseAsync(o, relative, timeout, HasSubfolders, ct);
/// <summary><see cref="BrowseAsync(ExportRootOptions, string?, TimeSpan, CancellationToken)"/> with the look into a subfolder given (a seam for tests).</summary>
internal static async Task<IReadOnlyList<SourceFolderChoice>> BrowseAsync(ExportRootOptions o, string? relative, TimeSpan timeout, Func<string, bool> hasSubfolders, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(hasSubfolders);
var folder = BrowsedFolder(o, relative);
IReadOnlyList<Subfolder> 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<SourceFolderChoice> 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;
}
/// <summary>The subfolders of a folder, sorted, without looking into them.</summary>
private static List<Subfolder> 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);
}
}
/// <summary>The folder has a subfolder to open (false when it cannot be read).</summary>
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;
}
}
/// <summary>A subfolder found by the picker, with its full path.</summary>
private sealed record Subfolder(string FullPath, SourceFolderChoice Choice);
/// <summary>
/// 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.
/// </summary>
/// <exception cref="ExportFolderException">The path cannot be a destination; the message says why.</exception>
public static string Resolve(ExportRootOptions o, string chosen) => Resolve(o, chosen, allowRoot: false);
/// <summary>The path shown to Alberto: in Docker «/esporta/usb»; elsewhere the full path.</summary>
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!)}.";
}
+26
View File
@@ -0,0 +1,26 @@
using System.Globalization;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// Settings of one export job (like <c>ImportRunSettings</c>): a row of the <c>setting</c> table each, so the schema
/// stays as E1 left it. Cleared when the job completes, is cancelled or deleted.
/// </summary>
internal static class ExportRunSettings
{
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
public static async Task<bool> 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);
}
+765
View File
@@ -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;
/// <summary>
/// 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 (<see cref="LongWorkGate"/>), 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 <see cref="RecoverAsync"/> once; «Riprendi» is always Alberto's.
/// </summary>
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);
}
/// <summary>Progress of the running job, at most four times a second and at every change of phase (pool thread).</summary>
public event EventHandler<ExportProgress>? ProgressChanged;
/// <summary>The job ended, however it ended (pool thread): the interface refreshes tiles and filter.</summary>
public event EventHandler<ExportJobFinished>? JobFinished;
public ExportDestinations Destinations { get; }
public ExportPlanner Planner { get; }
public ExportCopier Copier { get; }
public ExportReports Reports { get; }
/// <summary>The runs of the running job; empty when idle (and for «Controlla le copie», which has none).</summary>
public IReadOnlyList<long> ActiveRunIds
{
get
{
lock (_gate)
{
return _job is { Task.IsCompleted: false } job ? job.RunIds : [];
}
}
}
/// <summary>A job is running.</summary>
public bool IsBusy
{
get
{
lock (_gate)
{
return _starting || _job is { Task.IsCompleted: false };
}
}
}
/// <summary>The last error of a background job that could not be stored with its run (normally null).</summary>
public string? LastJobError { get; private set; }
/// <summary>
/// After a restart: a job that was running becomes «interrotto» (paused and interrupted ones stay), and the
/// <c>.part</c> files of unfinished jobs are removed in the background, only in their items' folders. Never resumes
/// by itself. Returns how many jobs became interrupted.
/// </summary>
public async Task<int> 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;
}
/// <summary>The plan of a «Copia in…», for its dialog (database only, plus whether each destination answers).</summary>
public Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct = default) => Planner.PlanAsync(request, ct);
/// <summary>
/// «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.
/// </summary>
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
public async Task<ExportStart> 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<ExportStart> 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<long, ExportRun>();
var pending = new List<ExportItem>();
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);
}
/// <summary>
/// «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).
/// </summary>
public async Task<IReadOnlyList<ExportRun>> ResumeAsync(IReadOnlyList<long>? runIds = null, CancellationToken ct = default)
{
EnsureIdle();
var unfinished = await _env.Storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false);
List<ExportRun> 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;
}
/// <summary>«Interrompi»: stops the running job and waits until its states are saved.</summary>
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);
}
/// <summary>
/// «Annulla»: an unfinished job becomes «annullato» (the running job is interrupted first when it holds it). Our
/// <c>.part</c> files in its folders go; no other file is touched, and the copies made stay.
/// </summary>
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);
}
}
/// <summary>
/// «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.
/// </summary>
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));
}
/// <summary>
/// «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».
/// </summary>
/// <exception cref="KeyNotFoundException">No such destination.</exception>
/// <exception cref="InvalidOperationException">The destination was retired.</exception>
public async Task<ExportRetry> 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));
}
/// <summary>The progress of the running job, or a snapshot of the newest job.</summary>
public async Task<ExportProgress> 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<ExportItemState, int>(), _env.Clock.Now)
: await SnapshotAsync(newest, ct).ConfigureAwait(false);
}
/// <summary>Waits for the running job (if any) to end, however it ends.</summary>
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<ExportProgress> 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<ExportProgress> 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<ExportItemState, int>(), _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<ExportCopy>();
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);
}
/// <summary>The root of the destination is there, asked within the folder-check time (a dead share must not block).</summary>
private async Task<bool> 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;
}
}
/// <summary>The disk went away during «Controlla le copie»: nothing is «Tolto» because of that, the destination pauses.</summary>
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<ExportRun> 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<ExportRun> 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<long> 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);
/// <summary>Runs of a stopped job that were never reached and are still recorded as running become «interrotto».</summary>
private async Task InterruptQueuedAsync(IEnumerable<long> 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.
}
}
}
/// <summary>Starts a job; <paramref name="held"/> is a lease of the gate already taken (the job owns it once started).</summary>
private void StartJob(IReadOnlyList<long> runIds, Func<IProgress<ExportProgress>, 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<ExportItemState, int>(), _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<long> RunIds, CancellationTokenSource Cancellation, Task Task);
/// <summary>A lease of the long-work gate on its way from <see cref="StartAsync"/> to the job.</summary>
private sealed class LeaseHolder
{
public IDisposable? Lease { get; set; }
}
private sealed class Reporter(ExportService owner) : IProgress<ExportProgress>
{
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);
}
}
}
@@ -0,0 +1,36 @@
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// «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.
/// </summary>
public static class ExportSupersession
{
/// <summary>
/// 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.
/// </summary>
public static async Task<int> 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);
}
}
+138
View File
@@ -0,0 +1,138 @@
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
namespace Febe.Core.Export;
/// <summary>
/// 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 <c>export_item.note</c> as English codes (<see cref="Notes"/>) and shown with
/// <see cref="Note"/>.
/// </summary>
public static class ExportText
{
/// <summary>The codes of <c>export_item.note</c>.</summary>
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";
}
/// <summary>Name of the state of a file of a job.</summary>
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(),
};
/// <summary>Name of the state of a copy.</summary>
public static string CopyState(ExportCopyState state) => state switch
{
ExportCopyState.Copied => "Copiato",
ExportCopyState.Removed => "Tolto",
ExportCopyState.Superseded => "Superato",
ExportCopyState.Failed => "Non riuscito",
_ => state.ToString(),
};
/// <summary>The Italian text of a note code; null for none; an unknown code is shown as it is.</summary>
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,
};
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
public static string Count(int count, string one, string many) => count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many;
/// <summary>The event written when a job ends: «Copia in Disco USB finita: 120 file copiati, 30 già copiati.»</summary>
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<string> { 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)}.";
}
/// <summary>The event of «Controlla le copie».</summary>
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)")}.");
}
/// <summary>The space is not enough for the next file (decision D16).</summary>
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.";
/// <summary>The disk said it is full.</summary>
public static string DiskFull(ExportDestination destination) =>
$"Su {ExportDestinations.Label(destination)} non c'è più spazio: libera spazio, poi riprendi.";
/// <summary>A file over the FAT32 limit.</summary>
public static string TooLarge(long bytes) =>
$"Il file pesa {ItalianText.Bytes(bytes)}: su un disco FAT32 un file non può superare 4 GB.";
/// <summary>The destination was retired while a job used it.</summary>
public const string RetiredDestination = "La cartella è stata tolta.";
/// <summary>An error for Alberto, without paths of secrets: the message of a file error, or a generic sentence.</summary>
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.",
};
}
}
+162
View File
@@ -0,0 +1,162 @@
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Febe.Core.Export;
/// <summary>
/// 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»).
/// <list type="bullet">
/// <item>Windows: the final path of the folder (<c>GetFinalPathNameByHandle</c> on a handle opened without any access
/// right), which resolves junctions, symbolic links, <c>subst</c> drives and mapped drives (to their UNC path);</item>
/// <item>Linux: the real path (<c>realpath</c>, 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).</item>
/// </list>
/// </summary>
/// <param name="Device">The device of the file system (<c>major:minor</c>), or null: then <paramref name="Path"/> is a full path.</param>
/// <param name="Path">With a device, the folder within its file system ('/' separated); else the real full path.</param>
internal sealed record FolderLocation(string? Device, string Path)
{
/// <summary>This folder is <paramref name="other"/>.</summary>
public bool IsSame(FolderLocation other) => Comparable(other) && (Device is null ? ExportPaths.Same(Path, other.Path) : string.Equals(Path, other.Path, ExportPaths.PathComparison));
/// <summary>This folder is <paramref name="other"/> or inside it.</summary>
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);
}
}
/// <summary>Finds the <see cref="FolderLocation"/> of a folder (see there).</summary>
internal static class FolderIdentity
{
private const uint FileShareAll = 0x1 | 0x2 | 0x4;
private const uint OpenExisting = 3;
private const uint FileFlagBackupSemantics = 0x02000000;
/// <summary>The location of an existing folder, or null when it cannot be told (missing, unreadable).</summary>
public static FolderLocation? Locate(string fullPath, IExportMounts mounts) => Locate(fullPath, mounts, out _);
/// <summary>The location of an existing folder and its real path, or null when it cannot be told.</summary>
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);
}
/// <summary>The location of what a mount shows, when its device is known.</summary>
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;
/// <summary>The path of the folder with every link (and on Windows every drive alias) resolved, or null.</summary>
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);
}
+4
View File
@@ -1,5 +1,6 @@
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Engine; using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Storage; using Febe.Core.Storage;
@@ -545,6 +546,9 @@ public sealed class ImportCopier(ImportEnvironment env)
media.State, media.State,
env.Clock.Now, env.Clock.Now,
none).ConfigureAwait(false); 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); 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)) if (entry.InstagramId is null && string.IsNullOrWhiteSpace(entry.Code) && !string.Equals(oldRelative, saved.RelativePath, StringComparison.Ordinal))
{ {
@@ -58,6 +58,12 @@ public sealed record ImportEnvironment
/// <summary>Reading, hashing and deleting source files.</summary> /// <summary>Reading, hashing and deleting source files.</summary>
public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance; public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance;
/// <summary>
/// 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).
/// </summary>
public LongWorkGate? Gate { get; init; }
/// <summary>Files analysed at the same time (hashing and decoding).</summary> /// <summary>Files analysed at the same time (hashing and decoding).</summary>
public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4); public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
+17
View File
@@ -1,4 +1,5 @@
using System.Diagnostics; using System.Diagnostics;
using Febe.Core.Abstractions;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Storage; 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."); 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<IProgress<ImportProgress>, CancellationToken, Task> work) private void StartJob(long runId, ImportPhase phase, Func<IProgress<ImportProgress>, 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."); 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(); _job?.Cancellation.Dispose();
var cancellation = new CancellationTokenSource(); var cancellation = new CancellationTokenSource();
var reporter = new Reporter(this); var reporter = new Reporter(this);
@@ -322,6 +335,10 @@ public sealed class ImportService : IAsyncDisposable
{ {
// The database is closing: nothing to publish. // The database is closing: nothing to publish.
} }
finally
{
lease?.Dispose();
}
} }
}); });
_job = new Job(runId, phase, cancellation, task); _job = new Job(runId, phase, cancellation, task);
@@ -1,5 +1,6 @@
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage; using Febe.Core.Storage;
namespace Febe.Core.Library; namespace Febe.Core.Library;
@@ -174,6 +175,11 @@ public sealed class DownloadDuplicateReview(
if (ok) if (ok)
{ {
removed++; 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) else if (problem is not null)
{ {
+5
View File
@@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using System.Globalization; using System.Globalization;
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage; using Febe.Core.Storage;
namespace Febe.Core.Library; namespace Febe.Core.Library;
@@ -319,6 +320,10 @@ public sealed class LibraryIngest(
throw new EntryDeletedException(); 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<DuplicatePair>(); var pairs = new List<DuplicatePair>();
if (hash is { } h && hashIndex is not null) if (hash is { } h && hashIndex is not null)
{ {
+13
View File
@@ -1,6 +1,7 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage; using Febe.Core.Storage;
namespace Febe.Core.Library; namespace Febe.Core.Library;
@@ -202,6 +203,14 @@ public sealed class LibraryRebuilder(
} }
await FlushAsync(account, batch, report, ct).ConfigureAwait(false); 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); CountUntracked(folder, allItems, report);
} }
@@ -554,6 +563,7 @@ public sealed class LibraryRebuilder(
report.FilesVerified++; report.FilesVerified++;
if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal)) if (media.Sha256 is not null && !string.Equals(media.Sha256, check.Sha256, StringComparison.Ordinal))
{ {
report.Changed.Add((media.Sha256, check.Sha256));
report.HashMismatches++; report.HashMismatches++;
report.Note($"Contenuto diverso da quello registrato: {file.Path}"); report.Note($"Contenuto diverso da quello registrato: {file.Path}");
} }
@@ -738,6 +748,9 @@ public sealed class LibraryRebuilder(
public int InvalidLines { get; set; } public int InvalidLines { get; set; }
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
public List<(string Old, string New)> Changed { get; } = [];
public void Note(string note) public void Note(string note)
{ {
if (_notes.Count < MaxNotes) if (_notes.Count < MaxNotes)
+117
View File
@@ -0,0 +1,117 @@
namespace Febe.Core.Library;
/// <summary>
/// One line of <c>/proc/self/mountinfo</c> (proc(5)): unlike <c>/proc/self/mounts</c> it says which folder of its file
/// system a mount shows (<see cref="Root"/>: <c>/</c> when the mount is the root of that file system) and gives the exact
/// mount point, which the export needs for <c>/esporta</c> (spec §4.10, §11).
/// </summary>
/// <param name="Id">Mount id.</param>
/// <param name="ParentId">Id of the parent mount.</param>
/// <param name="Root">Folder of the file system shown at the mount point (<c>/</c>: its root).</param>
/// <param name="MountPoint">Where it is mounted, unescaped.</param>
/// <param name="Options">Per-mount options (<c>rw</c>, <c>ro</c>, <c>noatime</c>…).</param>
/// <param name="FileSystemType">File system type (<c>ext4</c>, <c>vfat</c>, <c>cifs</c>…).</param>
/// <param name="Source">Mount source (<c>/dev/sdb1</c>, <c>//server/share</c>…), unescaped.</param>
/// <param name="Device">The device of the file system, <c>major:minor</c> (field 3): two mounts with the same device show
/// folders of one file system, so <see cref="Root"/> tells whether one is inside the other.</param>
public sealed record MountInfoEntry(int Id, int ParentId, string Root, string MountPoint, IReadOnlyList<string> Options, string FileSystemType, string Source, string? Device = null)
{
/// <summary>The mount is read-only (<c>ro</c>, as for a Docker volume mounted with <c>:ro</c>).</summary>
public bool ReadOnly => Options.Contains("ro", StringComparer.Ordinal);
}
/// <summary>Reads <c>/proc/self/mountinfo</c>.</summary>
public static class MountInfoTable
{
private const string MountInfoPath = "/proc/self/mountinfo";
/// <summary>
/// Parses the content of <c>/proc/self/mountinfo</c>: fields 0-5, then optional fields up to the separator «-», then
/// file system type and source. Malformed lines are skipped; nothing throws.
/// </summary>
public static IReadOnlyList<MountInfoEntry> Parse(string content)
{
ArgumentNullException.ThrowIfNull(content);
var entries = new List<MountInfoEntry>();
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;
}
/// <summary>
/// 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.
/// </summary>
public static MountInfoEntry? FindContaining(IReadOnlyList<MountInfoEntry> 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;
}
/// <summary>The content of <c>/proc/self/mountinfo</c> on Linux; null elsewhere or when it cannot be read.</summary>
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;
}
}
}
+108
View File
@@ -0,0 +1,108 @@
using System.Runtime.InteropServices;
namespace Febe.Core.Library;
/// <summary>What <see cref="NoReplaceRename.TryMove"/> did.</summary>
internal enum NoReplaceOutcome
{
/// <summary>The file has its new name.</summary>
Moved,
/// <summary>The new name exists: nothing changed.</summary>
Taken,
/// <summary>The file system cannot do it atomically: nothing changed, the caller checks and moves.</summary>
Unsupported,
}
/// <summary>
/// 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 <c>File.Move(overwrite: false)</c> 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).
/// <list type="number">
/// <item>Linux: <c>renameat2(…, RENAME_NOREPLACE)</c>; EEXIST means the name is taken;</item>
/// <item>without it (an older kernel, a file system that refuses the flag, another Unix): <c>link</c> then
/// <c>unlink</c> of the temporary name, where link refuses an existing name with EEXIST;</item>
/// <item>without hard links either (vfat, some CIFS mounts): <see cref="NoReplaceOutcome.Unsupported"/>.</item>
/// </list>
/// Not for Windows, where <c>MoveFileEx</c> without <c>MOVEFILE_REPLACE_EXISTING</c> already refuses an existing name.
/// </summary>
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;
/// <summary>Renames <paramref name="source"/> to <paramref name="destination"/> unless that name exists.</summary>
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);
}
+83 -3
View File
@@ -27,6 +27,21 @@ public sealed record SafeWriteOptions
/// <summary>Bytes written so far.</summary> /// <summary>Bytes written so far.</summary>
public IProgress<long>? Progress { get; init; } public IProgress<long>? Progress { get; init; }
/// <summary>
/// The root folder must already exist: <see cref="ExportRootMissingException"/> 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.
/// </summary>
public bool RequireExistingRoot { get; init; }
/// <summary>
/// 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 <see cref="IOException"/> says so.
/// </summary>
public bool VerifyFromDisk { get; init; }
} }
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary> /// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
@@ -47,6 +62,24 @@ public sealed class FileTooLargeException : IOException
} }
} }
/// <summary>The root folder of a write with <see cref="SafeWriteOptions.RequireExistingRoot"/> does not exist; nothing was created.</summary>
public sealed class ExportRootMissingException : DirectoryNotFoundException
{
public ExportRootMissingException()
{
}
public ExportRootMissingException(string message)
: base(message)
{
}
public ExportRootMissingException(string message, Exception innerException)
: base(message, innerException)
{
}
}
/// <summary> /// <summary>
/// Writes library files safely (spec §6.5 point 4, rule 12): /// Writes library files safely (spec §6.5 point 4, rule 12):
/// <list type="number"> /// <list type="number">
@@ -136,6 +169,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
options ??= new SafeWriteOptions(); options ??= new SafeWriteOptions();
var root = Path.GetFullPath(rootFolder); var root = Path.GetFullPath(rootFolder);
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory); 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); Directory.CreateDirectory(tempFolder);
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix); var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
using var reservation = ReserveTemporaryFile(tempPath); 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); var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
if (options.VerifyFromDisk)
{
await VerifyFromDiskAsync(tempPath, digest, ct).ConfigureAwait(false);
}
var desired = await decide(digest, ct).ConfigureAwait(false); var desired = await decide(digest, ct).ConfigureAwait(false);
if (desired is null) if (desired is null)
@@ -247,6 +289,22 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset())); return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
} }
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
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.");
}
}
/// <summary>Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.</summary> /// <summary>Sanitized segments of a relative path ('/' or '\' separated). «..» becomes «_»: nothing escapes the root.</summary>
private static List<string> Segments(string relativePath) private static List<string> Segments(string relativePath)
{ {
@@ -272,11 +330,33 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
// On Unix File.Move(overwrite: false) checks for the destination and then renames, and a rename replaces: // 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 // another writer (of this process, another Febe on the same export folder, another program) could take the
// one lock (Febe is the only writer of its library). On Windows the move itself refuses an existing name. // 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) 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; continue;
} }
+103
View File
@@ -1,4 +1,5 @@
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export;
namespace Febe.Core.Storage; namespace Febe.Core.Storage;
@@ -169,6 +170,108 @@ public interface IExportStore
/// <summary>Removes a job with its items. Only records: copies stay.</summary> /// <summary>Removes a job with its items. Only records: copies stay.</summary>
Task DeleteRunAsync(long runId, CancellationToken ct = default); Task DeleteRunAsync(long runId, CancellationToken ct = default);
// Tappa E2: the copies to external folders ----------------------------------------------------------------------
/// <summary>Every recorded «Esporta questo account», in one read: only accounts with a row (absent = the default).</summary>
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
/// <summary>
/// The newest Superseded or Removed row of (destination, account) whose <see cref="ExportCopy.SupersededBySha256"/> is
/// this SHA-256: the library file that took the place of a copied one, never copied again by itself.
/// </summary>
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
/// <summary>
/// «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
/// <paramref name="exceptAccountId"/>, 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»).
/// </summary>
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default);
/// <summary>
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) 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
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
/// </summary>
Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
long destinationId,
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
CancellationToken ct = default);
/// <summary>«Controlla le copie»: Copied or Superseded rows become Removed («Tolto», state time <paramref name="at"/>) in one transaction. Returns the rows changed.</summary>
Task<int> MarkCopiesRemovedAsync(IReadOnlyList<long> copyIds, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// The library files of a «Copia in…», by media id, a page at a time (after <paramref name="afterMediaId"/>), 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).
/// </summary>
Task<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default);
/// <summary>Jobs for the Dashboard: newest first, at most <paramref name="limit"/>.</summary>
Task<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default);
/// <summary>
/// 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.
/// </summary>
Task<IReadOnlyDictionary<long, ExportMark>> GetEntryMarksAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
/// <summary>
/// As <see cref="GetEntryMarksAsync"/>, 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.
/// </summary>
Task<IReadOnlyDictionary<long, ExportEntryCopies>> GetEntryCopyCountsAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
/// <summary>The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent.</summary>
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
Task<ExportAccountCounts> CountAccountFilesAsync(long accountId, CancellationToken ct = default);
}
/// <summary>A library file a «Copia in…» may copy (one row per media, with what the plan needs of its entry).</summary>
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);
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
public enum ExportMark
{
None,
Partly,
Copied,
}
/// <summary>The due files of an entry and how many are copied (decision D3 of tappa E2).</summary>
public sealed record ExportEntryCopies(int Due, int Copied)
{
/// <summary>«Non ancora copiato» (none), «Copiato in parte», «Copiato».</summary>
public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
}
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
/// <param name="Due">Files that go to the account's effective destination.</param>
/// <param name="NotCopied">Due files «Copia in…» would copy: neither copied nor «Tolti o superati» (failed ones included).</param>
/// <param name="RemovedOrSuperseded">Due files whose copy was removed from the destination or superseded: never copied again by themselves.</param>
/// <param name="Failed">Due files whose last copy failed (also counted in <paramref name="NotCopied"/>).</param>
public sealed record ExportAccountCounts(int Due, int NotCopied, int RemovedOrSuperseded, int Failed)
{
/// <summary>Due files copied.</summary>
public int Copied => Due - NotCopied - RemovedOrSuperseded;
} }
/// <summary>A page of the items of an export job.</summary> /// <summary>A page of the items of an export job.</summary>
+19
View File
@@ -30,6 +30,22 @@ public enum LibraryKindFilter
Posts, Posts,
} }
/// <summary>
/// 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».
/// </summary>
public enum LibraryCopiesFilter
{
/// <summary>«Non ancora copiati»: an entry with a due file that «Copia in…» would copy (a failed copy included).</summary>
NotCopied,
/// <summary>«Copiati»: an entry whose due files are all copied in their effective destination.</summary>
Copied,
/// <summary>«Tolti o superati»: an entry with a due file whose copy was removed or superseded (never copied again by itself).</summary>
RemovedOrSuperseded,
}
/// <summary>Filters of the library mosaic and of the account tabs (spec §4.6).</summary> /// <summary>Filters of the library mosaic and of the account tabs (spec §4.6).</summary>
public sealed record LibraryFilter public sealed record LibraryFilter
{ {
@@ -54,6 +70,9 @@ public sealed record LibraryFilter
/// <summary>Entry states shown. Null means <see cref="EntryStateRules.Visible"/> (entries with files).</summary> /// <summary>Entry states shown. Null means <see cref="EntryStateRules.Visible"/> (entries with files).</summary>
public IReadOnlyList<EntryState>? States { get; init; } public IReadOnlyList<EntryState>? States { get; init; }
/// <summary>«Copie» (null: «Tutti»). With «Tutte le foto» it applies to each file.</summary>
public LibraryCopiesFilter? Copies { get; init; }
} }
/// <summary> /// <summary>
@@ -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;
+48 -15
View File
@@ -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. // 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 command = c.Command(string.Empty);
var files = mode == MosaicMode.Files; var files = mode == MosaicMode.Files;
var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true);
var counts = files ? FileCounts(c, filter) : null; 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; var perEntry = files && counts is null;
command.CommandText = !files command.CommandText = !files
? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at" ? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at"
: perEntry : 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"; : $"SELECT e.published_at, e.id FROM entry e WHERE {where} ORDER BY e.published_at";
var days = new List<DayCount>(); var days = new List<DayCount>();
long dayStart = long.MaxValue, dayEnd = long.MinValue; long dayStart = long.MaxValue, dayEnd = long.MinValue;
@@ -417,15 +420,25 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
// --------------------------------------------------------------------------------------------- «Tutte le foto» // --------------------------------------------------------------------------------------------- «Tutte le foto»
/// <summary>The files of «Tutte le foto» on <c>media m</c>: those in the library, of the kind of «Foto» or «Video».</summary> /// <summary>
private static string FileTerms(LibraryFilter filter) => /// The files of «Tutte le foto» on <c>media m</c>: 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 <c>e</c> of the file too (account and kind), so
/// the caller must have it in scope (<see cref="NeedsEntry"/>).
/// </summary>
/// <param name="c">The connection (for the export tables of «Copie»).</param>
/// <param name="filter">The filter.</param>
/// <param name="bulk">The terms are read on every file of the library (the counts per entry): see ExportFilterSql.FileTerm.</param>
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. // 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 "+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch
{ {
LibraryKindFilter.Photos => " AND m.kind = 'Photo'", LibraryKindFilter.Photos => " AND m.kind = 'Photo'",
LibraryKindFilter.Videos => " AND m.kind = 'Video'", LibraryKindFilter.Videos => " AND m.kind = 'Video'",
_ => string.Empty, _ => string.Empty,
}; } + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty);
/// <summary>The file terms of this filter read the entry of the file (the «Copie» filter).</summary>
private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null;
/// <summary> /// <summary>
/// The files of «Tutte le foto» of every entry, in one pass over ix_media_entry_files: over the whole library a /// 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; 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<long, int>(); var counts = new Dictionary<long, int>();
using var r = command.ExecuteReader(); using var r = command.ExecuteReader();
while (r.Read()) 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; filter.Kind is LibraryKindFilter.Photos or LibraryKindFilter.Videos ? filter with { Kind = LibraryKindFilter.Posts } : filter;
/// <summary>A correlated count of the files of «Tutte le foto» of the entry <c>e</c>.</summary> /// <summary>A correlated count of the files of «Tutte le foto» of the entry <c>e</c>.</summary>
private static string FilesOfEntry(LibraryFilter filter) => private static string FilesOfEntry(SqliteConnection c, LibraryFilter filter) =>
$"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(filter)})"; $"(SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {FileTerms(c, filter)})";
/// <summary> /// <summary>
/// A window of «Tutte le foto»: the keys of the entries come from the same keyset scan of the publication index as /// 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) 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); 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}"); var sql = new StringBuilder($"SELECT e.id, e.published_at FROM entry e WHERE {where}");
if (cursor is { } at) if (cursor is { } at)
{ {
@@ -607,8 +621,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
{ {
using var command = c.Command(string.Empty); using var command = c.Command(string.Empty);
var list = command.AddList("f", chunk); 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 " 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(); using var r = command.ExecuteReader();
while (r.Read()) 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) private static bool FileExists(SqliteConnection c, LibraryFilter filter, LibraryCursor cursor, bool older)
{ {
using var command = c.Command(string.Empty); using var command = c.Command(string.Empty);
var where = BuildWhere(c, command, filter); var where = BuildWhere(c, command, filter, files: true);
var terms = FileTerms(filter); 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 = command.CommandText =
$"SELECT EXISTS (SELECT 1 FROM media m WHERE m.entry_id = @xi AND m.position {(older ? ">" : "<")} @xn AND {terms} " first
+ $"AND EXISTS (SELECT 1 FROM entry e WHERE e.id = m.entry_id AND {where})) "
+ $"OR EXISTS (SELECT 1 FROM entry e WHERE {where} AND (e.published_at, e.id) {(older ? "<" : ">")} (@xp, @xi) " + $"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}))"; + $"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); 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
} }
/// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary> /// <summary>The WHERE clause of a library filter on <c>entry e</c>; parameters are added to <paramref name="command"/>.</summary>
/// <param name="c">The connection (for the accounts of a search and the export tables of «Copie»).</param>
/// <param name="command">The command that gets the parameters.</param>
/// <param name="filter">The filter.</param>
/// <param name="files">
/// «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»).
/// </param>
/// <param name="aggregate"> /// <param name="aggregate">
/// The clause is for a count over every entry of the filter (totals, day counts) rather than for a window. «Foto» and /// 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 /// «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. /// hundred posts in index order.
/// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two. /// With a filter on accounts the posts are few and the EXISTS is the cheaper of the two.
/// </param> /// </param>
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 }; 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): // 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)); 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); var term = TextSearch.Normalize(filter.Search);
if (term.Length > 0) if (term.Length > 0)
{ {
+310
View File
@@ -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;
/// <summary>
/// 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).
/// </summary>
internal sealed record ExportFilterContext(
long? GeneralId,
ContentTypes GeneralTypes,
IReadOnlyList<(long AccountId, long DestinationId, ContentTypes Types)> Own,
IReadOnlySet<long> Off,
SamePostCopies SamePost,
bool HasCopies,
bool HasFailed,
bool HasHistory)
{
public bool HasDestination => GeneralId is not null || Own.Count > 0;
public IEnumerable<long> InUse => (GeneralId is { } g ? [g] : Array.Empty<long>()).Concat(Own.Select(o => o.DestinationId));
}
/// <summary>
/// The SQL of decision D3 of tappa E2 on <c>media m</c> joined to its <c>entry e</c>: a file is <b>due</b> 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.
/// </summary>
internal static class ExportFilterSql
{
private const string Present = "m.sha256 IS NOT NULL AND +m.state IN ('Downloaded', 'Imported')";
/// <summary>The content type of a file as a bit of <see cref="ContentTypes"/>, as <see cref="ExportPaths.TypeOf"/>.</summary>
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)";
/// <summary>Reads the context of one query.</summary>
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<long>();
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<long>()).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'"));
}
/// <summary>The file <c>m</c> of entry <c>e</c> is due (D3).</summary>
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})";
}
/// <summary>
/// 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.
/// </summary>
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')";
}
/// <summary>«Una copia sola»: a copy <c>c</c> counts for the file of <c>e</c> (in a destination in use, tested apart).</summary>
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))";
/// <summary>The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again.</summary>
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')";
/// <summary>
/// «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.
/// </summary>
/// <param name="x">The context of the query.</param>
/// <param name="bulk">The term is evaluated on every file of the library (see <see cref="FileTerm"/>).</param>
public static string Replaced(ExportFilterContext x, bool bulk = false) => !x.HasHistory
? "0"
: $"({History(x, bulk)} AND NOT {CopiedTerm(x, bulk)} AND NOT {Failed(x)})";
/// <summary>
/// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). The same partition
/// as <c>NOT Copied AND NOT Replaced</c>, without testing the copy twice.
/// </summary>
/// <param name="x">The context of the query.</param>
/// <param name="bulk">The term is evaluated on every file of the library (see <see cref="FileTerm"/>).</param>
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)})";
}
/// <summary>The term of «Tutte le foto» on <c>m</c> (with <c>e</c> its entry): a due file of the chosen class.</summary>
/// <param name="x">The context of the query.</param>
/// <param name="filter">The class.</param>
/// <param name="bulk">
/// 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).
/// </param>
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),
};
/// <summary>
/// The term of the grouped mosaic on <c>entry e</c>. «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.
/// </summary>
/// <param name="x">The context of the query.</param>
/// <param name="filter">The class.</param>
/// <param name="aggregate">
/// 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
/// <see cref="FileTerm"/> 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.
/// </param>
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),
};
}
/// <summary>With «Tutte le foto» an entry qualifies when one of its files does.</summary>
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";
/// <summary>The effective destination of the account of <c>e</c>: its own folder, else the general one (NULL: none).</summary>
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();
}
/// <summary>
/// «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 <see cref="Copied"/> per file; a third of the time of a pass over every
/// file of 200,000 entries.
/// </summary>
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)}))";
}
/// <summary>
/// Copied (<see cref="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.
/// </summary>
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);
/// <summary>
/// The removed or superseded part of <see cref="Replaced"/>: 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
/// (<c>GetCopyStatesAsync</c>), so filter, marks, counts and plan agree (D3). In bulk each EXISTS sits behind its list
/// of SHA-256.
/// </summary>
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);
}
+344
View File
@@ -1,4 +1,6 @@
using System.Globalization;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Storage; using Febe.Core.Storage;
using Microsoft.Data.Sqlite; 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(); w.Command("DELETE FROM export_run WHERE id = @r").With("@r", runId).ExecuteNonQuery();
}, },
ct); ct);
// Tappa E2 -------------------------------------------------------------------------------------------------------
/// <summary>SQLite allows 999 parameters per statement: id lists go in chunks below that.</summary>
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";
/// <summary>The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256.</summary>
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'
""";
/// <summary>
/// The rows of a destination superseded or removed in favour of some files (ix_export_copy_superseded_by). <c>+state</c>
/// 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.
/// </summary>
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<EntryKind>(3),
r.GetEnum<MediaKind>(4),
r.GetEnum<MediaState>(5),
r.GetTextOrNull(6),
r.GetInt64OrNull(7),
r.GetTextOrNull(8),
r.GetInt32(9),
r.GetBool(10));
public Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyDictionary<long, bool>>(
c =>
{
var switches = new Dictionary<long, bool>();
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<ExportCopy?> 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<ExportCopy?> 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<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> 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<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>(
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<string, string> 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<ExportCopyState>(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<int> MarkCopiesRemovedAsync(IReadOnlyList<long> 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<IReadOnlyList<ExportCandidate>> ListCandidatesAsync(ExportSelection selection, long afterMediaId, int limit, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(selection);
var n = Math.Clamp(limit, 1, 10_000);
return db.ReadAsync<IReadOnlyList<ExportCandidate>>(
c =>
{
List<ExportCandidate> Page(Func<SqliteCommand, string> 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<ExportCandidate> ByIds(IReadOnlyList<long> 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<IReadOnlyList<ExportRun>> ListRecentRunsAsync(int limit, CancellationToken ct = default) =>
db.ReadAsync<IReadOnlyList<ExportRun>>(
c => ReadAll(c.Command(RecentRunsSql).With("@limit", (long)Math.Clamp(limit, 1, 1000)), ReadRun),
ct);
public async Task<IReadOnlyDictionary<long, ExportMark>> GetEntryMarksAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default) =>
(await GetEntryCopyCountsAsync(entryIds, ct).ConfigureAwait(false)).ToDictionary(p => p.Key, p => p.Value.Mark);
public Task<IReadOnlyDictionary<long, ExportEntryCopies>> GetEntryCopyCountsAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(entryIds);
return db.ReadAsync<IReadOnlyDictionary<long, ExportEntryCopies>>(
c =>
{
var marks = new Dictionary<long, ExportEntryCopies>();
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<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(mediaIds);
return db.ReadAsync<IReadOnlyDictionary<long, ExportMark>>(
c =>
{
var marks = new Dictionary<long, ExportMark>();
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<ExportAccountCounts> 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);
} }
+10
View File
@@ -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. /// desktop framework of .NET (no package). Tests on Linux pass AES-256-GCM with a key made at run time.
/// </summary> /// </summary>
ISessionProtector SessionProtector { get; } ISessionProtector SessionProtector { get; }
/// <summary>
/// Free space and file system of the folders of the copies (spec §4.10), network shares included; null: the
/// shared measure (drive letters only).
/// </summary>
Febe.Core.Export.IExportDisk? ExportDisk => null;
} }
/// <summary> /// <summary>
@@ -176,6 +182,10 @@ public sealed class DesktopPlatform : IFebePlatform
services.AddSingleton(_shell.Native); services.AddSingleton(_shell.Native);
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow()); services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow());
services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed)); services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
if (_shell.ExportDisk is { } disk)
{
services.AddSingleton(disk);
}
} }
public void RegisterProblemServices(IServiceCollection services, FebeApp app) public void RegisterProblemServices(IServiceCollection services, FebeApp app)
+2
View File
@@ -21,6 +21,8 @@ internal sealed class DesktopShell(Dispatcher ui, ImageSource? icon, INativeShel
public ISessionProtector SessionProtector { get; } = new DpapiSessionProtector(); public ISessionProtector SessionProtector { get; } = new DpapiSessionProtector();
public Febe.Core.Export.IExportDisk? ExportDisk { get; } = new Native.WindowsExportDisk();
public string? WebView2Version() public string? WebView2Version()
{ {
try try
@@ -0,0 +1,79 @@
using System.Runtime.InteropServices;
using System.Text;
using Febe.Core.Export;
namespace Febe.Desktop.Native;
/// <summary>
/// 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 (<c>\\nas\foto</c>), which <see cref="DriveInfo"/> 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).
/// </summary>
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);
}
+2 -2
View File
@@ -10,12 +10,12 @@ namespace Febe.Server;
internal static class ServerCommand internal static class ServerCommand
{ {
public const string Usage = 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" + " [--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" + " [--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" + " [--raccolta pagine|richieste]\n"
+ "Variabili: FEBE_PASSWORD (obbligatoria), FEBE_PORTA, TZ, LANG, FEBE_HOST, FEBE_PROXY_FIDATO, FEBE_SENZA_SANDBOX, FEBE_CHROMIUM,\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."; + "Altri comandi: --demo, --simula 30g --profilo prudente, --controllo-salute.";
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error) public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error)
+15 -1
View File
@@ -66,6 +66,15 @@ internal sealed record ServerOptions
/// <summary>Import sources, read-only (/importa).</summary> /// <summary>Import sources, read-only (/importa).</summary>
public string ImportFolder { get; init; } = "/importa"; public string ImportFolder { get; init; } = "/importa";
/// <summary>
/// <c>--esporta</c> or <c>FEBE_ESPORTA=1</c>: the copies to external folders are switched on (spec §4.10). They are
/// written only below <see cref="ExportFolder"/>, and only when a folder of the server is mounted there.
/// </summary>
public bool ExportDeclared { get; init; }
/// <summary>Root of the copies to external folders (/esporta); not on the command line, tests change it.</summary>
public string ExportFolder { get; init; } = "/esporta";
/// <summary>FEBE_HOST: names the interface is reached with (comma separated). Empty: any name.</summary> /// <summary>FEBE_HOST: names the interface is reached with (comma separated). Empty: any name.</summary>
public IReadOnlyList<string> Hosts { get; init; } = []; public IReadOnlyList<string> Hosts { get; init; } = [];
@@ -125,6 +134,7 @@ internal sealed record ServerOptions
LibraryFolder = LibraryFolder, LibraryFolder = LibraryFolder,
LibraryFolderFromSettings = false, LibraryFolderFromSettings = false,
ImportFolder = ImportFolder, ImportFolder = ImportFolder,
ExportRoot = Core.Export.ExportRootOptions.Docker(Path.GetFullPath(ExportFolder), ExportDeclared),
ZoneId = ZoneId, ZoneId = ZoneId,
Zone = Zone, Zone = Zone,
Language = Language, Language = Language,
@@ -236,6 +246,7 @@ internal sealed record ServerOptions
Hosts = SplitHosts(Env("FEBE_HOST")), Hosts = SplitHosts(Env("FEBE_HOST")),
TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"), TrustForwardedHost = Flag("FEBE_PROXY_FIDATO"),
NoSandbox = Flag("FEBE_SENZA_SANDBOX"), NoSandbox = Flag("FEBE_SENZA_SANDBOX"),
ExportDeclared = Flag("FEBE_ESPORTA"),
ChromiumPath = Env("FEBE_CHROMIUM"), ChromiumPath = Env("FEBE_CHROMIUM"),
DebugPort = debugPort, DebugPort = debugPort,
Display = Env("FEBE_DISPLAY") ?? DefaultDisplay, Display = Env("FEBE_DISPLAY") ?? DefaultDisplay,
@@ -305,6 +316,9 @@ internal sealed record ServerOptions
case "--senza-sandbox": case "--senza-sandbox":
options = options with { NoSandbox = true }; options = options with { NoSandbox = true };
break; break;
case "--esporta":
options = options with { ExportDeclared = true };
break;
case "--sito-di-prova": case "--sito-di-prova":
case "--cdn-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"; var key = SessionKey is not null ? "impostata" : SessionKeyProblem is not null ? "non valida" : "assente";
return string.Create( return string.Create(
CultureInfo.InvariantCulture, 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} }}");
} }
/// <summary>The time zone named by TZ, or null when unknown.</summary> /// <summary>The time zone named by TZ, or null when unknown.</summary>
+48 -6
View File
@@ -4,9 +4,11 @@ using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search; using Febe.Core.Collection.Search;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Engine; using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Storage; using Febe.Core.Storage;
using Febe.Web.Engine; using Febe.Web.Engine;
using Febe.Web.Export;
using Febe.Web.Library; using Febe.Web.Library;
using Febe.Web.Native; using Febe.Web.Native;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@@ -23,8 +25,8 @@ public static class AccountsApi
endpoints.MapGet("/api/accounts", async (IFebeStorage storage, IClock clock, CancellationToken ct) => endpoints.MapGet("/api/accounts", async (IFebeStorage storage, IClock clock, CancellationToken ct) =>
ApiHttp.Json(await ListAsync(storage, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountListDto)); 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) => 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, ct).ConfigureAwait(false), FebeJsonContext.Default.AccountDetailDto)); 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) => 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, 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 body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AccountSettingsDto).ConfigureAwait(false);
var account = await GetAsync(storage, id, ct).ConfigureAwait(false); var account = await GetAsync(storage, id, ct).ConfigureAwait(false);
var readOnly = SystemApi.Capabilities(context, options, shell, browser, clock).FoldersReadOnly; var readOnly = SystemApi.Capabilities(context, options, shell, browser, clock).FoldersReadOnly;
var folder = ResolveFolder(account, body.Folder, library, readOnly); var folder = ResolveFolder(account, body.Folder, library, readOnly);
var edited = AccountSettingsMapper.Apply(account, body, clock.LocalZone, clock.Now, folder); 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 storage.Accounts.UpdateAsync(edited, ct).ConfigureAwait(false);
await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false); await engine.NotifyAccountsChangedAsync(ct).ConfigureAwait(false);
changes.Publish(new LibraryChange(clock.Now, id, "account")); 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. // «Tieni aggiornato» of the table: acts at once.
@@ -273,7 +290,7 @@ public static class AccountsApi
account.PreviousUsername); account.PreviousUsername);
} }
public static async Task<AccountDetailDto> DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, CancellationToken ct) public static async Task<AccountDetailDto> DetailAsync(long id, IFebeStorage storage, FebeLibrary library, IClock clock, ExportRootOptions exportRoot, CancellationToken ct)
{ {
ArgumentNullException.ThrowIfNull(storage); ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(library); 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), account.State == AccountState.ArchiveOnly && account.InstagramId is null && account.IsMine is false ? null : InstagramLinks.Profile(account.Username),
highlights, highlights,
AccountSettingsMapper.MaxBackfillPerDay, 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));
}
/// <summary>
/// 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.
/// </summary>
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.");
}
} }
/// <summary>«Con queste impostazioni», recomputed at every change of the form (spec §4.4).</summary> /// <summary>«Con queste impostazioni», recomputed at every change of the form (spec §4.4).</summary>
+10
View File
@@ -218,9 +218,19 @@ public static class ApiMapping
_ => throw new BadRequestException("Provenienza sconosciuta."), _ => 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(); var search = query["q"].ToString().Trim();
return new LibraryFilter return new LibraryFilter
{ {
Copies = copies,
Kind = kind, Kind = kind,
AccountIds = accounts, AccountIds = accounts,
From = from, From = from,
+14 -6
View File
@@ -43,7 +43,9 @@ public sealed record CoverDto(long MediaId, string Kind, int? Width, int? Height
/// <summary> /// <summary>
/// A tile of the mosaic: one entry, or with «Tutte le foto» one file of it (the cover is that file and /// A tile of the mosaic: one entry, or with «Tutte le foto» one file of it (the cover is that file and
/// <see cref="Position"/> its place in the series; null for an entry tile). /// <see cref="Position"/> its place in the series; null for an entry tile). <see cref="Copies"/>: the mark of the copies
/// to external folders, <c>copied</c> or <c>partly</c> (with <see cref="CopiesDone"/> of <see cref="CopiesDue"/>, the
/// «1/3»), null when nothing is copied or no destination is in use.
/// </summary> /// </summary>
public sealed record TileDto( public sealed record TileDto(
long Id, long Id,
@@ -57,7 +59,10 @@ public sealed record TileDto(
string State, string State,
int Files, int Files,
CoverDto? Cover, CoverDto? Cover,
int? Position = null); int? Position = null,
string? Copies = null,
int? CopiesDone = null,
int? CopiesDue = null);
/// <summary>A window of tiles; cursors continue it (null: nothing more that way).</summary> /// <summary>A window of tiles; cursors continue it (null: nothing more that way).</summary>
public sealed record LibraryPageDto(IReadOnlyList<TileDto> Tiles, string? Older, string? Newer); public sealed record LibraryPageDto(IReadOnlyList<TileDto> Tiles, string? Older, string? Newer);
@@ -69,7 +74,7 @@ public sealed record ArrivedDto(IReadOnlyList<TileDto> Tiles, int Total);
public sealed record DayDto(string Day, int Count, string Cursor); public sealed record DayDto(string Day, int Count, string Cursor);
/// <summary>Days of the mosaic with the totals; <see cref="Files"/> only with «Tutte le foto» (the files of the entries).</summary> /// <summary>Days of the mosaic with the totals; <see cref="Files"/> only with «Tutte le foto» (the files of the entries).</summary>
public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList<DayDto> Days, int? Files = null); public sealed record LibraryDaysDto(long Now, string Today, int Entries, int Accounts, IReadOnlyList<DayDto> 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); 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, string? Thumb,
bool Available, bool Available,
string State, string State,
bool Damaged = false); bool Damaged = false,
IReadOnlyList<MediaCopyDto>? Copies = null);
/// <summary>Everything the viewer shows of an entry.</summary> /// <summary>Everything the viewer shows of an entry.</summary>
public sealed record EntryDto( public sealed record EntryDto(
@@ -106,7 +112,8 @@ public sealed record EntryDto(
LocalTimeDto? Downloaded, LocalTimeDto? Downloaded,
IReadOnlyList<string> Highlights, IReadOnlyList<string> Highlights,
string? InstagramUrl, string? InstagramUrl,
IReadOnlyList<MediaDto> Media); IReadOnlyList<MediaDto> Media,
bool CanCopy = false);
public sealed record EntryIdsRequest(IReadOnlyList<long> Ids, string? Mode); public sealed record EntryIdsRequest(IReadOnlyList<long> Ids, string? Mode);
@@ -200,7 +207,8 @@ public sealed record AccountDetailDto(
string? InstagramUrl, string? InstagramUrl,
IReadOnlyList<HighlightDto> Highlights, IReadOnlyList<HighlightDto> Highlights,
int MaxBackfillPerDay, int MaxBackfillPerDay,
IReadOnlyList<string>? GeneralDownloadOrder = null); IReadOnlyList<string>? GeneralDownloadOrder = null,
ExportAccountDto? Export = null);
public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message); public sealed record HistoryItemDto(long Id, LocalTimeDto At, string Severity, string Code, string Message);
+755
View File
@@ -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;
/// <summary>
/// The copies to external folders (spec §4.10, §10.3, tappa E2) over <see cref="ExportService"/>: 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.
/// </summary>
public static class ExportApi
{
/// <summary>Title of the native folder picker for a destination.</summary>
public const string PickTitle = "Scegli la cartella delle copie";
/// <summary>The most files a «Copia in…» can name one by one (a larger choice goes through the filter).</summary>
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<ExportDestinationDto>(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<MediaLocation> present = [];
foreach (var candidate in new[] { copy.SupersededBySha256, copy.SourceSha256 }.OfType<string>().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<ExportRunDto>(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<IReadOnlyList<ExportRunDto>>(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";
/// <summary>The wire names of the content types of a destination, in the order of the dialog.</summary>
public static IReadOnlyList<string> TypeNames(ContentTypes types)
{
var names = new List<string>(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",
};
/// <summary>Copies per state with every state present.</summary>
public static IReadOnlyDictionary<string, int> CopyCounts(IReadOnlyDictionary<ExportCopyState, int> counts)
{
ArgumentNullException.ThrowIfNull(counts);
return Enum.GetValues<ExportCopyState>().ToDictionary(CopyState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal);
}
/// <summary>Files of a job per state with every state present.</summary>
public static IReadOnlyDictionary<string, int> ItemCounts(IReadOnlyDictionary<ExportItemState, int> counts)
{
ArgumentNullException.ThrowIfNull(counts);
return Enum.GetValues<ExportItemState>().ToDictionary(ItemState, s => counts.GetValueOrDefault(s), StringComparer.Ordinal);
}
/// <summary>The path of a folder as shown to Alberto (relative to <c>/esporta</c> in Docker).</summary>
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<long, string> usernames,
IReadOnlyDictionary<ExportCopyState, int> 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);
}
/// <summary>A destination with its counts, read from the database.</summary>
public static async Task<ExportDestinationDto> 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<long, string>();
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);
}
/// <summary>«Copie esterne» of the account card (decisions D1-D3 of tappa E2).</summary>
public static async Task<ExportAccountDto> 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);
}
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
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<string>? 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<long> Ids(IReadOnlyList<long> 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<long, string> 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<ExportDestinationSavedDto> 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<IReadOnlyDictionary<long, string>> UsernamesAsync(IFebeStorage storage, CancellationToken ct) =>
(await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id, a => a.Username);
/// <summary>Names of every destination, retired ones included (old jobs keep their name).</summary>
private static async Task<IReadOnlyDictionary<long, string>> LabelsAsync(IFebeStorage storage, CancellationToken ct) =>
(await storage.Exports.ListDestinationsAsync(includeRetired: true, ct).ConfigureAwait(false)).ToDictionary(d => d.Id, ExportDestinations.Label);
/// <summary>Docker with <c>/esporta</c> not declared or not mounted: nothing can be written (decision D14 of tappa E2).</summary>
private static void EnsureActive(ExportHub hub)
{
if (ExportRoots.Evaluate(hub.Root) is { Active: false, Problem: { } problem })
{
throw new BadRequestException(problem);
}
}
/// <summary>A measure of a disk that may not answer (a disconnected share): null after the timeout.</summary>
private static async Task<T?> MeasureAsync<T>(Func<T?> 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<bool> ExistsAsync(string folder, CancellationToken ct)
{
try
{
return await Task.Run(() => Directory.Exists(folder), ct).WaitAsync(DiskTimeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
{
return false;
}
}
// ---------------------------------------------------------------------------------------------- errors
/// <summary>The export's own exceptions become Italian answers: 400 for a refused request, 404 for something missing.</summary>
internal static T Guard<T>(Func<T> action)
{
try
{
return action();
}
catch (Exception ex) when (Translate(ex) is { } translated)
{
throw translated;
}
}
internal static async Task<T> GuardAsync<T>(Func<Task<T>> 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,
};
}
+220
View File
@@ -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».
/// <summary>
/// Where copies can go. <paramref name="Docker"/>: destinations are subfolders of <paramref name="Root"/> (the page
/// lists them); otherwise any folder, with the native picker when <paramref name="PickFolder"/>.
/// <paramref name="Active"/> false: nothing can be written, <paramref name="Problem"/> says why.
/// </summary>
public sealed record ExportRootDto(bool Docker, bool Active, string? Root, string? Problem, bool PickFolder);
/// <summary>The library's naming schemes, to prefill «Uno schema suo», and the placeholders.</summary>
public sealed record ExportSchemesDto(string General, string Highlight, string Profile, IReadOnlyList<string> Placeholders);
/// <summary>
/// A destination. <paramref name="Display"/> is the folder as shown («/esporta/usb» in Docker). <paramref name="Types"/>
/// are the wire names of the content types; null schemes are «Come la libreria». <paramref name="Problem"/>: the reason
/// of its pause (or, with <c>/status</c>, why it does not answer now). <paramref name="Counts"/>: copies per state
/// (<c>copied</c>, <c>removed</c>, <c>superseded</c>, <c>failed</c>). <paramref name="Reachable"/> and
/// <paramref name="FreeBytes"/> only from <c>/status</c>. <paramref name="Orphan"/>: an own folder whose account was
/// removed («era di @<paramref name="FormerUsername"/>»).
/// </summary>
public sealed record ExportDestinationDto(
long Id,
string Scope,
long? AccountId,
string? Username,
string Label,
string RootPath,
string Display,
IReadOnlyList<string> Types,
string? NamingScheme,
string? HighlightNamingScheme,
string? ProfileNamingScheme,
bool Automatic,
LocalTimeDto? PausedAt,
string? Problem,
IReadOnlyDictionary<string, int> Counts,
bool? Reachable = null,
long? FreeBytes = null,
bool Orphan = false,
string? FormerUsername = null);
/// <summary>
/// <c>GET /api/export</c>: Impostazioni → Esportazione and the notice of the Dashboard. <paramref name="SamePost"/>:
/// <c>onePerAccount</c> or <c>oneOnly</c>. <paramref name="UnfinishedRuns"/>: interrupted or paused jobs («Riprendi»).
/// </summary>
public sealed record ExportOverviewDto(
ExportRootDto Root,
string SamePost,
ExportDestinationDto? General,
IReadOnlyList<ExportDestinationDto> Own,
IReadOnlyList<long> ActiveRunIds,
int UnfinishedRuns,
ExportSchemesDto Library);
/// <summary><c>PUT /api/export/settings</c>: «Lo stesso post in due account», <c>onePerAccount</c> or <c>oneOnly</c>.</summary>
public sealed record ExportSettingsRequest(string SamePost);
/// <summary>Docker: the subfolders of a folder of <c>/esporta</c>. <paramref name="Relative"/> is "" for the root.</summary>
public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList<SourceFolderDto> Folders);
/// <summary><c>POST /api/export/pick-folder</c>: the destination being changed, to open the picker on its folder.</summary>
public sealed record ExportPickRequest(long? DestinationId);
/// <summary>The check of a candidate folder (before saving). <paramref name="Fat32"/>: files over 4 GB cannot go there.</summary>
public sealed record ExportFolderCheckDto(bool Accepted, string FullPath, string Display, string? Problem, long? FreeBytes, bool Fat32);
/// <summary>The «Risultato» of a destination's naming. <paramref name="Scope"/>: general or account; null schemes are the library's.</summary>
public sealed record ExportNamingPreviewRequest(string Scope, string? General, string? Highlight, string? Profile);
/// <summary>
/// A destination to add or change. <paramref name="Path"/>: in Docker the folder relative to <c>/esporta</c> (as listed),
/// elsewhere the full path. <paramref name="Types"/>: wire names, at least one. Null or empty schemes: «Come la
/// libreria». «Automatica» is stored only (tappa E5 acts on it).
/// </summary>
public sealed record ExportDestinationRequest(
string Scope,
long? AccountId,
string Path,
string? Label,
IReadOnlyList<string> Types,
string? NamingScheme,
string? HighlightNamingScheme,
string? ProfileNamingScheme,
bool Automatic = false,
bool OnlyNew = true);
/// <summary>A saved destination (a change of folder gives a new id) and the warnings of its schemes.</summary>
public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList<string> Warnings);
/// <summary>
/// What a «Copia in…» copies: exactly one of <paramref name="MediaIds"/> (files of «Tutte le foto» or the viewer),
/// <paramref name="EntryIds"/> (a grouped selection), <paramref name="Query"/> (the filter of the Libreria, as its query
/// string, with <paramref name="Mode"/> <c>grouped</c> or <c>files</c>) or <paramref name="AccountId"/> (every file of
/// the account). <paramref name="CopyAgain"/>: «Copia di nuovo anche i tolti o superati».
/// </summary>
public sealed record CopyJobRequestDto(
IReadOnlyList<long>? MediaIds,
IReadOnlyList<long>? EntryIds,
string? Query,
string? Mode,
long? AccountId,
bool CopyAgain = false);
/// <summary>A destination of a plan. <paramref name="Problem"/>: why it cannot be written now (paused, not reachable).</summary>
public sealed record ExportPlanDestinationDto(
long Id,
string Label,
string Display,
string Scope,
string? Username,
int Files,
long Bytes,
bool Paused,
string? Problem,
long? FreeBytes);
/// <summary>
/// The summary of «Copia in…» (spec §10.3). <paramref name="Files"/>/<paramref name="Bytes"/>: what will be written
/// (with «Copia di nuovo» the tolti/superati too). <paramref name="NotExported"/>: of accounts that are not exported
/// (switch off, no destination, type not taken). <paramref name="Missing"/>: not in the library.
/// </summary>
public sealed record ExportPlanDto(
int Files,
long Bytes,
int AlreadyCopied,
int RemovedOrSuperseded,
int NotExported,
int Missing,
IReadOnlyList<ExportPlanDestinationDto> Destinations,
bool HasDestination = true);
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
/// <summary>«Copia di nuovo» of a copy «Tolto» or «Superato» (the viewer).</summary>
public sealed record CopyAgainRequest(long CopyId);
/// <summary>
/// <c>GET /api/export/progress</c>, polled by the Dashboard tab. <paramref name="Phase"/>: preparing, checking,
/// waitingForSession, copying, finished. <paramref name="ByState"/>: files of the job per state.
/// </summary>
public sealed record ExportProgressDto(
long? RunId,
string Phase,
double Fraction,
int FilesDone,
int FilesTotal,
long BytesDone,
long BytesTotal,
string? CurrentFile,
string? Destination,
IReadOnlyDictionary<string, int> ByState,
bool Running,
string? Error);
/// <summary>An export job. <paramref name="Kind"/>: copy or recognize; <paramref name="Origin"/>: manual or automatic.</summary>
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);
/// <summary>The files of one account in a job (<paramref name="Copied"/> counts written and adopted files).</summary>
public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
/// <summary>A file of the report that needs a look, with its reason in Italian.</summary>
public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text);
/// <summary>The report of a job (at most 200 problems).</summary>
public sealed record ExportReportDto(
ExportRunDto Run,
IReadOnlyDictionary<string, int> ByState,
long BytesCopied,
IReadOnlyList<ExportReportAccountDto> Accounts,
IReadOnlyList<ExportReportLineDto> Problems);
/// <summary>
/// A copy of a file of the viewer (spec §4.6, §4.10). <paramref name="State"/>: copied, removed, superseded, failed;
/// <paramref name="Variant"/>: whole (tappa E2 copies originals only). <paramref name="ForAccount"/>: with «Una copia
/// sola», the account it was copied for when it is another one. <paramref name="CanCopyAgain"/>: «Copia di nuovo».
/// </summary>
public sealed record MediaCopyDto(
long CopyId,
string Destination,
bool DestinationRetired,
string State,
string Variant,
string? Format,
long? FrameAtMs,
LocalTimeDto At,
string? ForAccount,
bool CanCopyAgain);
/// <summary>
/// «Copie esterne» of the account card. <paramref name="Destination"/>: 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.
/// </summary>
public sealed record ExportAccountDto(
bool Enabled,
bool HasOwnFolder,
ExportDestinationDto? Destination,
int Due,
int NotCopied,
int RemovedOrSuperseded,
int Failed);
+17
View File
@@ -88,4 +88,21 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(ImportModeRequest))] [JsonSerializable(typeof(ImportModeRequest))]
[JsonSerializable(typeof(ImportPlanDto))] [JsonSerializable(typeof(ImportPlanDto))]
[JsonSerializable(typeof(ImportReportDto))] [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<ExportRunDto>))]
[JsonSerializable(typeof(ExportReportDto))]
[JsonSerializable(typeof(ExportAccountDto))]
public sealed partial class FebeJsonContext : JsonSerializerContext; public sealed partial class FebeJsonContext : JsonSerializerContext;
+152 -5
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Storage; using Febe.Core.Storage;
using Febe.Web.Library; using Febe.Web.Library;
@@ -41,8 +42,9 @@ public static class LibraryApi
var end = LocalCalendar.StartOfDay(d.Day.AddDays(1), zone); 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)); return new DayDto(ApiMapping.Day(d.Day), d.Count, ApiMapping.Cursor(new LibraryCursor(end, 0), mode));
}).ToList(); }).ToList();
var hasDestinations = await HasDestinationsAsync(storage, ct).ConfigureAwait(false);
return ApiHttp.Json( 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); FebeJsonContext.Default.LibraryDaysDto);
}); });
@@ -65,7 +67,7 @@ public static class LibraryApi
ct).ConfigureAwait(false); ct).ConfigureAwait(false);
return ApiHttp.Json( return ApiHttp.Json(
new LibraryPageDto( 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.Older is { } older ? ApiMapping.Cursor(older, mode) : null,
page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null), page.Newer is { } newer ? ApiMapping.Cursor(newer, mode) : null),
FebeJsonContext.Default.LibraryPageDto); FebeJsonContext.Default.LibraryPageDto);
@@ -76,7 +78,7 @@ public static class LibraryApi
{ {
var ids = ParseIds(context.Request.Query["ids"].ToString()); var ids = ParseIds(context.Request.Query["ids"].ToString());
var tiles = await storage.Entries.GetTilesAsync(ids, ct).ConfigureAwait(false); 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) => 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 local = LocalCalendar.ToLocal(entry.PublishedAt, zone);
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account))); var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false); 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<MediaDto>(stored.Media.Count); var media = new List<MediaDto>(stored.Media.Count);
foreach (var m in stored.Media) 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, m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
path is not null, path is not null,
ApiMapping.State(m.State), ApiMapping.State(m.State),
damaged)); damaged,
copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false)));
} }
return new EntryDto( return new EntryDto(
@@ -279,7 +283,150 @@ public static class LibraryApi
entry.DownloadedAt is { } d ? ApiMapping.Local(d, now, zone) : null, entry.DownloadedAt is { } d ? ApiMapping.Local(d, now, zone) : null,
highlights.Select(h => h.Title).ToList(), highlights.Select(h => h.Title).ToList(),
entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, entry, now, highlights.FirstOrDefault()?.InstagramId), entry.State == EntryState.Deleted ? null : InstagramLinks.For(account, entry, now, highlights.FirstOrDefault()?.InstagramId),
media); media,
copies is { Effective: not null, Enabled: true });
}
/// <summary>
/// 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.
/// </summary>
public static async Task<IReadOnlyList<TileDto>> TilesAsync(IFebeStorage storage, IReadOnlyList<LibraryTile> 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;
}
/// <summary>Whether any destination of the copies is in use (the marks and the «Copie» filter make sense).</summary>
public static async Task<bool> HasDestinationsAsync(IFebeStorage storage, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(storage);
return (await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false)).Count > 0;
}
/// <summary>
/// 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.
/// </summary>
private sealed record EntryCopiesContext(
Account Account,
IReadOnlyDictionary<long, ExportDestination> Destinations,
ExportDestination? Effective,
bool Enabled,
SamePostCopies SamePost,
IReadOnlyDictionary<long, string> Usernames)
{
/// <summary>Copies shown for one file, newest first.</summary>
public const int MaxShown = 6;
public static async Task<EntryCopiesContext?> 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<IReadOnlyList<MediaCopyDto>> 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<MediaCopyDto>();
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;
}
} }
/// <summary> /// <summary>
+19 -4
View File
@@ -231,14 +231,16 @@ public static class SettingsApi
throw new BadRequestException("Per confermare scrivi la parola «ricostruisci»."); 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) 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."); 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
} }
/// <summary>The account whose name the preview shows: the first one followed (or any), as in mockup 08.</summary> /// <summary>The account whose name the preview shows: the first one followed (or any), as in mockup 08.</summary>
private static async Task<string> SampleAccountAsync(IFebeStorage storage, CancellationToken ct) internal static async Task<string> SampleAccountAsync(IFebeStorage storage, CancellationToken ct)
{ {
var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false); 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() 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."); 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 try
{ {
Directory.CreateDirectory(root); Directory.CreateDirectory(root);
+4 -1
View File
@@ -374,7 +374,10 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
public bool IsSeparateWindow => Desktop; public bool IsSeparateWindow => Desktop;
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) =>
Task.FromResult<string?>(Desktop ? Path.Combine(root, "altre-cartelle", Path.GetFileName(Path.TrimEndingDirectorySeparator(initialFolder ?? "cartella"))) : null); Task.FromResult<string?>(!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<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(Desktop); public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(Desktop);
+280
View File
@@ -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;
/// <summary>
/// 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 <c>/esporta</c>: the counts, the marks and the «Copie» filter come from the same rows the engine wrote.
/// </summary>
public static class DemoExport
{
/// <summary>The general folder of the demo.</summary>
public const string GeneralFolder = "Disco USB";
/// <summary>The own folder of @studio.lumen.demo.</summary>
public const string OwnFolder = "Studio Lumen";
/// <summary>The empty folder the demo's picker gives (desktop look).</summary>
public const string PickedFolder = "Chiavetta";
/// <summary>The account whose copies the demo shows in every state.</summary>
public const string CopiedAccount = "marta.demo";
/// <summary>The account with an own folder.</summary>
public const string OwnFolderAccount = "studio.lumen.demo";
/// <summary>The account with «Esporta questo account» off.</summary>
public const string NotExportedAccount = "il.porto.demo";
/// <summary>The demo's <c>/esporta</c>: a mounted, writable folder of the temporary root, shown as «/esporta».</summary>
public static ExportRootOptions Root(string root)
{
var folder = Path.Combine(root, "esporta");
return ExportRootOptions.Docker(folder, declared: true, new DemoExportMounts(folder)) with { ShownAs = "/esporta" };
}
/// <summary>Creates the folders and the copies. A failure leaves the demo without copies, never without the demo.</summary>
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);
}
/// <summary>One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».</summary>
private static async Task HistoryAsync(
FebeDatabase database,
DemoWorld world,
ExportDestination general,
Account marta,
IReadOnlyList<Media> photos,
IReadOnlyList<Media> 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);
}
}
/// <summary>The present photos of an account, one per picture (newest first), with how many files show that picture.</summary>
private static async Task<List<(Media Media, int Files)>> PhotosAsync(FebeDatabase database, Account account, DemoWorld world, CancellationToken ct)
{
var seen = new Dictionary<string, int>(StringComparer.Ordinal);
var ids = new List<long>();
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;
}
}
/// <summary>The demo's mount table: its <c>/esporta</c> is a mounted, writable ext4 folder.</summary>
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<ExportMount> All() => [_mount];
}
/// <summary>The demo's disks: 1,8 TB free, no file size limit.</summary>
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;
}
+6
View File
@@ -1,5 +1,6 @@
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Engine; using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import; using Febe.Core.Import;
using Febe.Core.Library; using Febe.Core.Library;
using Febe.Core.Storage; using Febe.Core.Storage;
@@ -71,6 +72,8 @@ public sealed class DemoHost : IAsyncDisposable
await database.Settings.SetAsync(SettingKeys.LibraryRoot, layout.Root, ct).ConfigureAwait(false); await database.Settings.SetAsync(SettingKeys.LibraryRoot, layout.Root, ct).ConfigureAwait(false);
var world = await DemoSeeder.SeedAsync(database, data, layout, clock, 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); 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 demoImport = import;
var library = new FebeLibrary(database, data, layout, clock); var library = new FebeLibrary(database, data, layout, clock);
var web = new FebeWebOptions var web = new FebeWebOptions
@@ -103,6 +106,9 @@ public sealed class DemoHost : IAsyncDisposable
services.AddSingleton<IDiagnosticSource, DemoDiagnosticSource>(); services.AddSingleton<IDiagnosticSource, DemoDiagnosticSource>();
services.AddSingleton<IDataFolderChange, DemoDataFolderChange>(); services.AddSingleton<IDataFolderChange, DemoDataFolderChange>();
services.AddSingleton(demoImport); services.AddSingleton(demoImport);
services.AddSingleton(exportRoot);
services.AddSingleton<IExportDisk, DemoExportDisk>();
services.AddSingleton<IEngineSessionState>(NoEngineSession.Instance);
}); });
await app.StartAsync(ct).ConfigureAwait(false); await app.StartAsync(ct).ConfigureAwait(false);
return new DemoHost(root, database, import, app, world, FebeWebHost.BoundAddress(app)); return new DemoHost(root, database, import, app, world, FebeWebHost.BoundAddress(app));
+129
View File
@@ -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;
/// <summary>
/// The copies to external folders of the web host (spec §4.10, tappa E2): one <see cref="ExportService"/> 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» (<see cref="Recovered"/>). When a job ends, the open pages refresh tiles and filter through the
/// <c>libreria</c> event.
/// </summary>
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));
}
/// <summary>Where destinations may be chosen (Docker: <c>/esporta</c>), as the composition registered it.</summary>
public ExportRootOptions Root { get; }
/// <summary>Jobs that the first use found running and made «interrotto» (the last stop interrupted them).</summary>
public int Recovered { get; private set; }
/// <summary>
/// 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 <c>/esporta</c>. Elsewhere, <see cref="Root"/>.
/// </summary>
public ExportRootOptions RootFor(HttpContext? context) =>
_options.Demo && DemoRequest.Edition(context) != FebeEdition.Docker ? ExportRootOptions.AnyFolder : Root;
/// <summary>The service, built at the first use (with the recovery of interrupted jobs).</summary>
public async Task<ExportService> 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"));
}
}
}
+15 -1
View File
@@ -2,12 +2,14 @@ using System.Net;
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Alerts; using Febe.Core.Alerts;
using Febe.Core.Engine; using Febe.Core.Engine;
using Febe.Core.Export;
using Febe.Core.Import; using Febe.Core.Import;
using Febe.Core.Storage; using Febe.Core.Storage;
using Febe.Web.Api; using Febe.Web.Api;
using Febe.Web.Connection; using Febe.Web.Connection;
using Febe.Web.Demo; using Febe.Web.Demo;
using Febe.Web.Engine; using Febe.Web.Engine;
using Febe.Web.Export;
using Febe.Web.Hosting; using Febe.Web.Hosting;
using Febe.Web.Import; using Febe.Web.Import;
using Febe.Web.Library; using Febe.Web.Library;
@@ -73,10 +75,21 @@ public static class FebeWeb
services.TryAddSingleton<IAlertTestSender, NoTelegramSender>(); services.TryAddSingleton<IAlertTestSender, NoTelegramSender>();
services.TryAddSingleton<IDataFolderChange, FixedDataFolder>(); services.TryAddSingleton<IDataFolderChange, FixedDataFolder>();
services.TryAddSingleton<FolderSizes>(); services.TryAddSingleton<FolderSizes>();
// 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<LongWorkGate>();
services.TryAddSingleton<RebuildJob>(); services.TryAddSingleton<RebuildJob>();
services.TryAddSingleton(sp => sp.GetService<ImportService>() is { } import services.TryAddSingleton(sp => sp.GetService<ImportService>() is { } import
? new ImportHub(import, sp.GetRequiredService<IClock>(), sp.GetRequiredService<LibraryChanges>()) ? new ImportHub(import, sp.GetRequiredService<IClock>(), sp.GetRequiredService<LibraryChanges>())
: new ImportHub(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<FebeLibrary>(), sp.GetRequiredService<IClock>(), options, sp.GetRequiredService<LibraryChanges>())); : new ImportHub(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<FebeLibrary>(), sp.GetRequiredService<IClock>(), options, sp.GetRequiredService<LibraryChanges>(), sp.GetRequiredService<LongWorkGate>()));
// 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<IEngineSessionState>(NoEngineSession.Instance);
services.TryAddSingleton(_ => options.Edition == FebeEdition.Docker
? ExportRootOptions.Docker(Path.GetFullPath("/esporta"), declared: false)
: ExportRootOptions.AnyFolder);
services.TryAddSingleton<IExportDisk>(sp => new SystemExportDisk(sp.GetRequiredService<ExportRootOptions>().Mounts));
services.TryAddSingleton<ExportHub>();
services.AddHttpContextAccessor(); services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password)) if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{ {
@@ -138,6 +151,7 @@ public static class FebeWeb
ActivityApi.Map(endpoints); ActivityApi.Map(endpoints);
SettingsApi.Map(endpoints); SettingsApi.Map(endpoints);
ImportApi.Map(endpoints); ImportApi.Map(endpoints);
ExportApi.Map(endpoints);
DuplicatesApi.Map(endpoints); DuplicatesApi.Map(endpoints);
SearchApi.Map(endpoints); SearchApi.Map(endpoints);
RemoteViewSocket.Map(endpoints); RemoteViewSocket.Map(endpoints);
+8 -2
View File
@@ -21,6 +21,7 @@ public sealed class ImportHub : IAsyncDisposable
private readonly IClock _clock; private readonly IClock _clock;
private readonly FebeWebOptions? _options; private readonly FebeWebOptions? _options;
private readonly LibraryChanges _changes; private readonly LibraryChanges _changes;
private readonly LongWorkGate? _longWork;
private readonly bool _owned; private readonly bool _owned;
private ImportService? _service; private ImportService? _service;
private bool _stale; private bool _stale;
@@ -35,9 +36,13 @@ public sealed class ImportHub : IAsyncDisposable
_service.ProgressChanged += OnProgress; _service.ProgressChanged += OnProgress;
} }
/// <summary>Builds its own service over the library of the web host.</summary> /// <summary>
public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes) /// Builds its own service over the library of the web host. <paramref name="longWork"/> is the gate shared with the
/// copies to external folders and the rebuild (null: the import alone, as in some tests).
/// </summary>
public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes, LongWorkGate? longWork = null)
{ {
_longWork = longWork;
_storage = storage ?? throw new ArgumentNullException(nameof(storage)); _storage = storage ?? throw new ArgumentNullException(nameof(storage));
_library = library ?? throw new ArgumentNullException(nameof(library)); _library = library ?? throw new ArgumentNullException(nameof(library));
_clock = clock ?? throw new ArgumentNullException(nameof(clock)); _clock = clock ?? throw new ArgumentNullException(nameof(clock));
@@ -127,6 +132,7 @@ public sealed class ImportHub : IAsyncDisposable
SetFileTimeToPublication = settings.SetFileTimeToPublication, SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder, Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder,
DataFolder = library.Data.Root, DataFolder = library.Data.Root,
Gate = _longWork,
}); });
} }
+16 -1
View File
@@ -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` | | `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) | | `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) | | `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à - `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`. `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 | | `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/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/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/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/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) | | `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}/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 | | `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 | | `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 (`<symbol id="i-nome">`) | | `GET /icone/tutte.svg` | Tutte le icone di `wwwroot/icone` (disegnate per Febe) in un solo sprite (`<symbol id="i-nome">`) |
Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON. 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 - 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` 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`. 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 - I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
conti tornino. conti tornino.
+44 -6
View File
@@ -156,9 +156,10 @@ public sealed class FolderSizes(IClock clock)
/// <summary> /// <summary>
/// «Ricostruisci il database dalla libreria» (spec §8.5) as a background job with its progress and its last report, /// «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 <see cref="LongWorkGate"/>,
/// spec §4.10). It never moves, renames or deletes a file (rule 12).
/// </summary> /// </summary>
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 readonly Lock _gate = new();
private Task? _task; private Task? _task;
@@ -176,18 +177,32 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
} }
} }
/// <summary>Starts the rebuild; false when one is already running.</summary> /// <summary>Starts the rebuild; false when one is already running or another long job holds the gate.</summary>
public bool TryStart() public bool TryStart() => TryStart(out _);
/// <summary>
/// Starts the rebuild; false, with the Italian reason in <paramref name="busy"/>, when a rebuild, an import or a copy
/// to external folders is running.
/// </summary>
public bool TryStart(out string? busy)
{ {
lock (_gate) lock (_gate)
{ {
if (_task is { IsCompleted: false }) if (_task is { IsCompleted: false })
{ {
busy = LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Rebuild);
return false; 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 }; State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
_task = Task.Run(RunAsync); _task = Task.Run(() => RunAsync(lease));
return true; return true;
} }
} }
@@ -195,8 +210,9 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
/// <summary>Waits for the running rebuild (tests).</summary> /// <summary>Waits for the running rebuild (tests).</summary>
public Task WaitAsync() => _task ?? Task.CompletedTask; public Task WaitAsync() => _task ?? Task.CompletedTask;
private async Task RunAsync() private async Task RunAsync(IDisposable lease)
{ {
using var held = lease;
var progress = new SyncProgress<RebuildProgress>(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked }); var progress = new SyncProgress<RebuildProgress>(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked });
try try
{ {
@@ -204,6 +220,7 @@ public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock
var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false); var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false);
State = State with { Running = false, Report = report, FinishedAt = clock.Now }; State = State with { Running = false, Report = report, FinishedAt = clock.Now };
changes.Publish(new LibraryChange(clock.Now, null, "rebuild")); 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) 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
} }
} }
/// <summary>
/// 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.
/// </summary>
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).
}
}
/// <summary>Progress reported on the calling thread (no synchronization context to post to).</summary> /// <summary>Progress reported on the calling thread (no synchronization context to post to).</summary>
private sealed class SyncProgress<T>(Action<T> action) : IProgress<T> private sealed class SyncProgress<T>(Action<T> action) : IProgress<T>
{ {
+53
View File
@@ -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.ambra{background:var(--ambra-tinta)} .avviso.ambra svg{color:var(--ambra)}
.avviso.rosso{background:var(--rosso-tinta)} .avviso.rosso svg{color:var(--rosso)} .avviso.rosso{background:var(--rosso-tinta)} .avviso.rosso svg{color:var(--rosso)}
.avviso b{font-weight:650} .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} .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{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} .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} .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 ---------- */ /* ---------- 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}} @keyframes febe-compare{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.dialogo,.menu,.breve{animation:febe-compare .14s ease-out} .dialogo,.menu,.breve{animation:febe-compare .14s ease-out}
+9 -4
View File
@@ -1,21 +1,26 @@
// Components of the style sheet (appendix B, mockup 13) as functions: dialogs, menus, short notices, switches, // 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. // 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 { h, icon, uid } from './dom.js';
import { t } from './text.js'; import { t } from './text.js';
// ------------------------------------------------------------------------------------------------- short notices // ------------------------------------------------------------------------------------------------- short notices
let toasts; 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) { if (!toasts) {
toasts = h('div.brevi', { role: 'status', 'aria-live': 'polite' }); toasts = h('div.brevi', { role: 'status', 'aria-live': 'polite' });
document.body.append(toasts); 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); 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). */ /** Shows the message of an error (ApiError or anything else). */
+171 -3
View File
@@ -2,6 +2,9 @@
// the link to the profile; tabs Contenuti (Post, Storie as a regular 9:16 grid, In evidenza grouped by collection, // 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 // 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). // 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 { api, download, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.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 { Mosaic, justify, tileElement, defaultDayLabel, filesDayLabel, modeSwitch, storedMode } from './mosaic.js';
import { kindName, orderEditor, orderOrDefault } from './download-order.js'; import { kindName, orderEditor, orderOrDefault } from './download-order.js';
import { openViewer } from './viewer.js'; import { openViewer } from './viewer.js';
import { copiesApi, copiesLabel, copiesMenu, copyDialog, destinationDialog, exportButton, exportMenu, separator } from './export-dialogs.js';
const KINDS = [ const KINDS = [
{ key: 'post', api: 'posts', stat: 'posts', label: 'scheda.tipi.posts' }, { 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); 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 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 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; let mosaic = null;
// «Raggruppa i post» / «Tutte le foto» (spec §4.6): one choice for the views of every account, apart from the Libreria. // «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'); let mode = storedMode('account');
@@ -121,8 +128,10 @@ async function contentsTab(page, route, detail) {
let showToken = 0; let showToken = 0;
const chips = h('div.filtri', { role: 'group', 'aria-label': t('scheda.linguette.contenuti') }); 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 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'))); 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'); const host = h('div');
fill(page.body, host); fill(page.body, host);
@@ -136,6 +145,8 @@ async function contentsTab(page, route, detail) {
}, },
}, t(k.label), h('i', number(s[k.stat]))))); }, 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(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'; selectButton.hidden = kind.key === 'evidenza';
// «In evidenza» is drawn by collection, one tile per item (almost always a single story): no switch there. // «In evidenza» is drawn by collection, one tile per item (almost always a single story): no switch there.
modes.hidden = kind.key === 'evidenza'; modes.hidden = kind.key === 'evidenza';
@@ -149,8 +160,28 @@ async function contentsTab(page, route, detail) {
show(); 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() { function query() {
const q = new URLSearchParams({ accounts: String(detail.account.id), kind: kind.api }); 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 today = caps().today;
const add = (n) => new Date(Date.parse(`${today}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10); const add = (n) => new Date(Date.parse(`${today}T12:00:00Z`) + n * 86400000).toISOString().slice(0, 10);
const year = Number(today.slice(0, 4)); const year = Number(today.slice(0, 4));
@@ -177,6 +208,9 @@ async function contentsTab(page, route, detail) {
showError(error); showError(error);
} }
}, },
copySelected: hasDestination
? () => copyDialog(mosaic.files ? { mediaIds: [...mosaic.selected] } : { entryIds: mosaic.selectedEntries().ids })
: null,
deleteSelected: async () => { deleteSelected: async () => {
const { ids, files } = mosaic.selectedEntries(); const { ids, files } = mosaic.selectedEntries();
const removed = await confirmDelete(ids, mosaic.files ? { files: mosaic.selected.size, total: files } : null); 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 onChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 500);
const onMarks = later(() => mosaic && mosaic.refreshMarks().catch(() => {}), 600);
page.onLibrary((change) => { 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(() => { page.onLeave(() => {
onChange.cancel(); onChange.cancel();
onMarks.cancel();
if (mosaic) mosaic.destroy(); if (mosaic) mosaic.destroy();
if (highlightCleanup) highlightCleanup(); if (highlightCleanup) highlightCleanup();
}); });
@@ -467,7 +506,8 @@ function settingsTab(page, detail) {
h('div.riga-campi', depthExtra), h('div.riga-campi', depthExtra),
h('div', { style: { marginTop: '14px' } }, storyVideos)), 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.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() { function drawPlan() {
const lines = plan.lines.map((l) => { 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 // --------------------------------------------------------------------------------------------- history
async function historyTab(page, detail) { async function historyTab(page, detail) {
@@ -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')))),
}),
});
}
+43 -3
View File
@@ -23,9 +23,17 @@ const QUEUE_ROWS = 5;
const THUMBS = 8; const THUMBS = 8;
export default { export default {
async mount(page) { async mount(page, route) {
page.title(t('attivita.titolo')); 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 notice = h('div');
const exportNotice = h('div');
const now = h('div.ora-testo'); const now = h('div.ora-testo');
const preview = previewBox(page); const preview = previewBox(page);
const today = h('section.blocco.oggi-basso'); 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)), h('section.cruscotto.pannello', preview.element, h('div.cruscotto-lato', now, budgets)),
suspended, today, suspended, today,
h('div.due-colonne.storia-coda', history.element, queue.element), h('div.due-colonne.storia-coda', history.element, queue.element),
notice, incidents, alerts)); exportNotice, notice, incidents, alerts));
let latest = null; let latest = null;
page.onEngine((state) => { page.onEngine((state) => {
@@ -62,11 +70,17 @@ export default {
async function loadSide() { async function loadSide() {
first.check(); first.check();
try { 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/duplicates/count', { signal: page.signal }),
api('/api/engine/incidents', { signal: page.signal }), api('/api/engine/incidents', { signal: page.signal }),
api('/api/alerts', { 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); drawNotice(notice, counts);
drawIncidents(incidents, history); drawIncidents(incidents, history);
drawAlerts(alerts, recent); 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 // ------------------------------------------------------------------------------------------------- first start
/** /**
@@ -661,6 +684,23 @@ function drawNotice(box, counts) {
h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi')))); 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». */ /** Recipes suspended after three problems in a row (unknown formats, targets not found): what to do, «Riattiva». */
function drawSuspended(box, state) { function drawSuspended(box, state) {
const items = state.snapshot.suspendedRecipes || []; const items = state.snapshot.suspendedRecipes || [];
@@ -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;
}
}
+62 -15
View File
@@ -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). // «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 // «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. // «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 { api, download, withCarried } from '../core/api.js';
import { caps } from '../core/context.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 { Mosaic, modeSwitch, storedMode } from './mosaic.js';
import { welcome } from './welcome.js'; import { welcome } from './welcome.js';
import { openViewer } from './viewer.js'; import { openViewer } from './viewer.js';
import { copiesApi, copiesLabel, copiesMenu, copyDialog, exportButton as exportMenuButton, exportMenu } from './export-dialogs.js';
const KINDS = [ const KINDS = [
{ key: 'tutto', api: 'all', label: 'libreria.tipi.all' }, { 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 === 'importati') q.set('provenance', 'imported');
if (state.provenienza === 'scaricati') q.set('provenance', 'downloaded'); if (state.provenienza === 'scaricati') q.set('provenance', 'downloaded');
if (state.q) q.set('q', state.q); if (state.q) q.set('q', state.q);
const copies = copiesApi(state.copie);
if (copies) q.set('copies', copies);
return q.toString(); return q.toString();
} }
@@ -66,6 +71,7 @@ function readState(query) {
al: query.get('al') || '', al: query.get('al') || '',
provenienza: query.get('provenienza') || '', provenienza: query.get('provenienza') || '',
q: query.get('q') || '', q: query.get('q') || '',
copie: copiesApi(query.get('copie')) ? query.get('copie') : '',
}; };
} }
@@ -76,6 +82,8 @@ export default {
let accounts = null; let accounts = null;
let mosaic = null; let mosaic = null;
let mode = storedMode('libreria'); 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'), ''); page.title(t('libreria.titolo'), '');
const search = h('input', { type: 'search', placeholder: t('libreria.cerca'), 'aria-label': t('libreria.cerca'), value: state.q }); 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 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 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 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 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 size = local.get('libreria.tessere', 160);
const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') }); const 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; mode = value;
apply(); apply();
}, { compact: true }); }, { 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. // 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 }); const duplicates = h('a.btn.nudo.piccolo.doppioni-link', { href: withCarried('/doppioni'), hidden: true });
api('/api/duplicates/count', { signal: page.signal }).then((counts) => { api('/api/duplicates/count', { signal: page.signal }).then((counts) => {
@@ -110,7 +120,7 @@ export default {
}).catch(() => {}); }).catch(() => {});
page.tools(h('div', { style: { display: 'contents' } }, page.tools(h('div', { style: { display: 'contents' } },
chips, chips,
h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton), h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton, copiesButton),
filtersButton, filtersButton,
h('div.destra', h('div.destra',
duplicates, duplicates,
@@ -123,7 +133,7 @@ export default {
fill(page.body, host); fill(page.body, host);
function filtersActive() { 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() { function drawChips() {
@@ -156,7 +166,9 @@ export default {
else if (state.periodo) periodText = t(`libreria.periodi.${state.periodo}`); else if (state.periodo) periodText = t(`libreria.periodi.${state.periodo}`);
menuLabel(periodButton, periodText, state.periodo || state.dal || state.al); 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); 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() { async function loadAccounts() {
@@ -246,22 +258,32 @@ export default {
}); });
} }
function openCopies(anchor) {
copiesMenu(anchor, state.copie, (value) => {
state.copie = value;
apply();
});
}
function openFilters(anchor) { function openFilters(anchor) {
// Narrow window: the three menus behind one button. // Narrow window: the menus behind one button.
menu(anchor, [ menu(anchor, [
{ label: accountButton.textContent, value: 'account', icon: 'users' }, { label: accountButton.textContent, value: 'account', icon: 'users' },
{ label: periodButton.textContent, value: 'periodo', icon: 'calendar' }, { label: periodButton.textContent, value: 'periodo', icon: 'calendar' },
{ label: provenanceButton.textContent, value: 'provenienza', icon: 'folder-input' }, { 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 === 'account') openAccounts(anchor);
if (value === 'periodo') openPeriod(anchor); if (value === 'periodo') openPeriod(anchor);
if (value === 'provenienza') openProvenance(anchor); if (value === 'provenienza') openProvenance(anchor);
if (value === 'copie') openCopies(anchor);
}); });
} }
accountButton.addEventListener('click', () => openAccounts(accountButton)); accountButton.addEventListener('click', () => openAccounts(accountButton));
periodButton.addEventListener('click', () => openPeriod(periodButton)); periodButton.addEventListener('click', () => openPeriod(periodButton));
provenanceButton.addEventListener('click', () => openProvenance(provenanceButton)); provenanceButton.addEventListener('click', () => openProvenance(provenanceButton));
copiesButton.addEventListener('click', () => openCopies(copiesButton));
filtersButton.addEventListener('click', () => openFilters(filtersButton)); filtersButton.addEventListener('click', () => openFilters(filtersButton));
slider.addEventListener('input', () => { slider.addEventListener('input', () => {
const value = Number(slider.value); const value = Number(slider.value);
@@ -281,7 +303,7 @@ export default {
page.saveBar(null); page.saveBar(null);
return; 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) { function setSelecting(on) {
@@ -293,7 +315,16 @@ export default {
} }
selectButton.addEventListener('click', () => setSelecting(!mosaic.selecting)); 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() { async function exportSelected() {
try { try {
@@ -361,6 +392,7 @@ export default {
al: state.al || null, al: state.al || null,
provenienza: state.provenienza || null, provenienza: state.provenienza || null,
q: state.q || null, q: state.q || null,
copie: state.copie || null,
}); });
drawChips(); drawChips();
drawMenus(); drawMenus();
@@ -375,9 +407,16 @@ export default {
signal: page.signal, signal: page.signal,
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }), onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }),
onSelection: drawSelection, onSelection: drawSelection,
onTotals: ({ entries, accounts: n, files }) => page.count(files == null onTotals: ({ entries, accounts: n, files, hasDestinations: any }) => {
? t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) }) page.count(files == null
: t('libreria.quantiFile', { file: t('comune.file', { n: files }), elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })), ? 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, onEmpty: drawEmpty,
}); });
try { try {
@@ -389,9 +428,15 @@ export default {
} }
const onLibraryChange = later(() => mosaic && mosaic.refresh().catch(() => {}), 400); 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(() => { page.onLeave(() => {
onLibraryChange.cancel(); onLibraryChange.cancel();
onExportChange.cancel();
if (mosaic) mosaic.destroy(); if (mosaic) mosaic.destroy();
}); });
loadAccounts().then(drawMenus).catch(() => {}); 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 * The bar of the selection (Libreria and account view): how many are chosen, «Esporta l'elenco», «Copia in…» (only
* «Tutte le foto» it counts the files and says how many entries they belong to: those are what the actions work on. * 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 n = selected.size;
const entries = mosaic.selectedEntries().ids.length; const entries = mosaic.selectedEntries().ids.length;
let note = t('selezione.nessuno'); let note = t('selezione.nessuno');
@@ -415,6 +461,7 @@ export function selectionBar(mosaic, selected, { cancel, exportSelected, deleteS
h('div.destra', h('div.destra',
h('button.btn.nudo', { type: 'button', onclick: cancel }, t('selezione.annulla')), h('button.btn.nudo', { type: 'button', onclick: cancel }, t('selezione.annulla')),
h('button.btn', { type: 'button', disabled: !n, onclick: exportSelected }, icon('file-down'), t('selezione.esporta')), h('button.btn', { 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 })))); h('button.btn.pericolo', { type: 'button', disabled: !n, onclick: deleteSelected }, icon('trash-2'), t('selezione.elimina', { n: entries }))));
} }
+49 -3
View File
@@ -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 })); 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 })); 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) })); 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' : ''}`, { const el = h(`button.tess${selected ? '.scelta' : ''}`, {
type: 'button', type: 'button',
style: { width: `${width}px`, height: `${height}px` }, 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; * 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; * 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). * onEmpty(), dayLabel(day, count, today).
*/ */
constructor(options) { constructor(options) {
@@ -230,7 +241,7 @@ export class Mosaic {
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
if (this.destroyed) return; if (this.destroyed) return;
this.today = data.today; 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; this.width = this.root.clientWidth || this.host.clientWidth || 800;
for (const section of this.sections) this.unobserve(section); for (const section of this.sections) this.unobserve(section);
this.sections = []; this.sections = [];
@@ -559,7 +570,7 @@ export class Mosaic {
async refresh() { async refresh() {
const data = await api(`/api/library/days?${this.query}`, { signal: this.signal }); const data = await api(`/api/library/days?${this.query}`, { signal: this.signal });
if (this.destroyed) return; 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. // 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) { if (data.days.length && !this.root.isConnected) {
this.pendingNew = 0; this.pendingNew = 0;
@@ -602,6 +613,41 @@ export class Mosaic {
if (!this.sections.length) this.onEmpty(); 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) { reset(s, day) {
s.count = day.count; s.count = day.count;
s.cursor = day.cursor; s.cursor = day.cursor;
@@ -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());
}
+2 -1
View File
@@ -1,5 +1,5 @@
// Impostazioni (spec §10.3; mockups 07, 08, 10): the left sub-menu (Generali, Limiti e comportamento, Collegamento a // 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). // Instagram» is a page of its own (mockup 10: back link, no sub-menu).
import { withCarried } from '../core/api.js'; import { withCarried } from '../core/api.js';
@@ -13,6 +13,7 @@ export const SECTIONS = [
{ key: 'collegamento', icon: 'key-round', load: null }, { key: 'collegamento', icon: 'key-round', load: null },
{ key: 'notifiche', icon: 'bell', load: () => import('./settings-notifications.js') }, { key: 'notifiche', icon: 'bell', load: () => import('./settings-notifications.js') },
{ key: 'dati', icon: 'database', load: () => import('./settings-data.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') }, { key: 'informazioni', icon: 'info', load: () => import('./settings-about.js') },
]; ];
+55 -2
View File
@@ -5,10 +5,12 @@
import { api, withCarried } from '../core/api.js'; import { api, withCarried } from '../core/api.js';
import { caps, serverNow } from '../core/context.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 { t, dayName, capitalize, bytes, duration, number, ago, shortDay } from '../core/text.js';
import { avatar, label, showError, toast } from '../core/ui.js'; import { avatar, label, showError, toast } from '../core/ui.js';
import { confirmDelete } from './library.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' }; 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 fileIndex = 0;
let zoomed = false; let zoomed = false;
let token = 0; 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 where = h('span.dove');
const closeButton = h('button.tondino', { type: 'button', 'aria-label': t('vis.chiudi'), title: t('vis.chiudi'), onclick: close }, icon('x')); 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() { function close() {
document.removeEventListener('keydown', onKey, true); document.removeEventListener('keydown', onKey, true);
stopWatching();
onCopiesChanged.cancel();
for (const v of box.querySelectorAll('video')) v.pause(); for (const v of box.querySelectorAll('video')) v.pause();
if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
box.remove(); box.remove();
@@ -248,7 +254,8 @@ export function openViewer({ tile, source, origin, onDeleted }) {
row(t('vis.codice'), entry.code || entry.instagramId), row(t('vis.codice'), entry.code || entry.instagramId),
entry.author ? row(t('vis.autore'), `@${entry.author}`) : null, 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.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', h('section', h('h3', t('vis.provenienza')), h('dl',
row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')), row(t('vis.origine'), t(entry.provenance === 'imported' ? 'vis.importato' : 'vis.scaricato')),
row(t('vis.quando'), downloaded)))); 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('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'))); : 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') { if (entry.state !== 'deleted') {
actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina'))); actions.push(h('button.btn.nudo.pericolo', { type: 'button', onclick: remove }, icon('trash-2'), t('vis.elimina')));
} }
fill(panelBottom, actions); 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) { async function showInFolder(mediaId) {
try { try {
const result = await api('/api/media/show-in-folder', { method: 'POST', body: { mediaId } }); 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(); 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.addEventListener('keydown', onKey, true);
document.body.append(box); document.body.append(box);
closeButton.focus(); closeButton.focus();
+2 -2
View File
@@ -5,7 +5,7 @@
export const routes = [ export const routes = [
// The Dashboard is the start page (spec §7.9, §10.2, tappa D1); the old address of Attività leads there too. // 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: /^\/$/, redirect: '/dashboard' },
{ pattern: /^\/dashboard\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') }, { pattern: /^\/dashboard(?:\/(?<scheda>esportazione))?\/?$/, nav: 'dashboard', page: () => import('./pages/dashboard.js') },
{ pattern: /^\/attivita\/?$/, redirect: '/dashboard' }, { pattern: /^\/attivita\/?$/, redirect: '/dashboard' },
{ pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') }, { pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') },
{ pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.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: /^\/doppioni\/?$/, nav: 'dashboard', page: () => import('./pages/duplicates.js') },
{ pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' }, { pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
{ {
pattern: /^\/impostazioni\/(?<section>generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/, pattern: /^\/impostazioni\/(?<section>generali|limiti|collegamento|notifiche|dati|esportazione|informazioni)\/?$/,
nav: 'impostazioni', nav: 'impostazioni',
page: () => import('./pages/settings.js'), page: () => import('./pages/settings.js'),
}, },
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff. Show more