diff --git a/docs/schermate/06-attivita-tutti-i-tetti.png b/docs/schermate/06-attivita-tutti-i-tetti.png
new file mode 100644
index 0000000..8ccaa11
Binary files /dev/null and b/docs/schermate/06-attivita-tutti-i-tetti.png differ
diff --git a/docs/schermate/06-attivita.png b/docs/schermate/06-attivita.png
new file mode 100644
index 0000000..e393eed
Binary files /dev/null and b/docs/schermate/06-attivita.png differ
diff --git a/docs/schermate/07-limiti-e-comportamento.png b/docs/schermate/07-limiti-e-comportamento.png
new file mode 100644
index 0000000..461d351
Binary files /dev/null and b/docs/schermate/07-limiti-e-comportamento.png differ
diff --git a/docs/schermate/07-limiti-su-misura.png b/docs/schermate/07-limiti-su-misura.png
new file mode 100644
index 0000000..bbf3bb8
Binary files /dev/null and b/docs/schermate/07-limiti-su-misura.png differ
diff --git a/docs/schermate/08-impostazioni-generali.png b/docs/schermate/08-impostazioni-generali.png
new file mode 100644
index 0000000..4e9698c
Binary files /dev/null and b/docs/schermate/08-impostazioni-generali.png differ
diff --git a/docs/schermate/09-importa-revisione.png b/docs/schermate/09-importa-revisione.png
new file mode 100644
index 0000000..4f40c9d
Binary files /dev/null and b/docs/schermate/09-importa-revisione.png differ
diff --git a/docs/schermate/09-importa-sorgente.png b/docs/schermate/09-importa-sorgente.png
new file mode 100644
index 0000000..d3fe77c
Binary files /dev/null and b/docs/schermate/09-importa-sorgente.png differ
diff --git a/docs/schermate/09-importa-telefono.png b/docs/schermate/09-importa-telefono.png
new file mode 100644
index 0000000..35cbc21
Binary files /dev/null and b/docs/schermate/09-importa-telefono.png differ
diff --git a/docs/schermate/10-browser.png b/docs/schermate/10-browser.png
new file mode 100644
index 0000000..ef67f6b
Binary files /dev/null and b/docs/schermate/10-browser.png differ
diff --git a/docs/schermate/10-collegamento-collegato.png b/docs/schermate/10-collegamento-collegato.png
new file mode 100644
index 0000000..cc4421a
Binary files /dev/null and b/docs/schermate/10-collegamento-collegato.png differ
diff --git a/docs/schermate/10-collegamento-instagram.png b/docs/schermate/10-collegamento-instagram.png
new file mode 100644
index 0000000..25333b1
Binary files /dev/null and b/docs/schermate/10-collegamento-instagram.png differ
diff --git a/docs/schermate/10-collegamento-windows.png b/docs/schermate/10-collegamento-windows.png
new file mode 100644
index 0000000..50db922
Binary files /dev/null and b/docs/schermate/10-collegamento-windows.png differ
diff --git a/docs/schermate/11-attivita-fermo-tema-scuro.png b/docs/schermate/11-attivita-fermo-tema-scuro.png
new file mode 100644
index 0000000..32800f3
Binary files /dev/null and b/docs/schermate/11-attivita-fermo-tema-scuro.png differ
diff --git a/docs/schermate/14-attivita-finestra-stretta-normale.png b/docs/schermate/14-attivita-finestra-stretta-normale.png
new file mode 100644
index 0000000..c22b674
Binary files /dev/null and b/docs/schermate/14-attivita-finestra-stretta-normale.png differ
diff --git a/docs/schermate/14-attivita-finestra-stretta.png b/docs/schermate/14-attivita-finestra-stretta.png
new file mode 100644
index 0000000..4503138
Binary files /dev/null and b/docs/schermate/14-attivita-finestra-stretta.png differ
diff --git a/docs/schermate/14-attivita-telefono-normale.png b/docs/schermate/14-attivita-telefono-normale.png
new file mode 100644
index 0000000..bfe8a98
Binary files /dev/null and b/docs/schermate/14-attivita-telefono-normale.png differ
diff --git a/docs/schermate/14-attivita-telefono.png b/docs/schermate/14-attivita-telefono.png
new file mode 100644
index 0000000..90a11fd
Binary files /dev/null and b/docs/schermate/14-attivita-telefono.png differ
diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md
index e237fcc..14cd15e 100644
--- a/docs/schermate/differenze.md
+++ b/docs/schermate/differenze.md
@@ -17,6 +17,29 @@ solo per l'interfaccia di Febe (§10.7).
| `14-finestra-stretta.png` | `/libreria`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
| `14-telefono.png` | `/libreria`, 390 × 844 | (il mockup mostra Attività al telefono) |
| `account-cronologia.png` | `/account/2/cronologia` | (nessuno) |
+| `06-attivita.png` | `/attivita?scena=sessione&tema=chiaro` | `miniature/06-attivita.png` |
+| `06-attivita-tutti-i-tetti.png` | come sopra, «Tutti i tetti» aperto | (nessuno: §7.4) |
+| `07-limiti-e-comportamento.png` | `/impostazioni/limiti`, 1440 × 1470 | `miniature/07-limiti-e-comportamento.png` |
+| `07-limiti-su-misura.png` | come sopra, un tetto cambiato: «Su misura» e barra di salvataggio attiva | (nessuno: §7.5) |
+| `08-impostazioni-generali.png` | `/impostazioni/generali` | `docs/mockup/08-impostazioni-generali.png` |
+| `09-importa-sorgente.png` | `/importa?passo=1&veste=docker` | (nessuno: passo 1 di §9.1) |
+| `09-importa-revisione.png` | `/importa?passo=3`, primo doppione deciso («Tieni il più grande») | `miniature/09-importa-revisione.png` |
+| `09-importa-telefono.png` | `/importa?passo=3`, 390 × 844 | (nessuno) |
+| `10-collegamento-instagram.png` | `/impostazioni/collegamento?scena=scollegato&veste=docker` | `docs/mockup/10-collegamento-instagram.png` |
+| `10-collegamento-windows.png` | come sopra con `veste=windows` | (nessuno: variante di §6.4) |
+| `10-collegamento-collegato.png` | `/impostazioni/collegamento?veste=docker`, account collegato | (nessuno) |
+| `10-browser.png` | `/browser?scena=fermo&veste=docker` | mockup 10 senza colonna dei passi |
+| `11-attivita-fermo-tema-scuro.png` | `/attivita?scena=fermo&tema=scuro` | `miniature/11-attivita-fermo-tema-scuro.png` |
+| `14-attivita-finestra-stretta.png` | `/attivita?scena=sessione`, 860 × 900 | parte sinistra di `miniature/14-finestra-stretta-e-telefono.png` |
+| `14-attivita-telefono.png` | `/attivita?scena=sessione`, 390 × 844 | parte destra di `miniature/14-finestra-stretta-e-telefono.png` |
+| `14-attivita-finestra-stretta-normale.png` | `/attivita?scena=normale`, 860 × 900 | (come sopra, motore in ascolto) |
+| `14-attivita-telefono-normale.png` | `/attivita?scena=normale`, 390 × 844 | (come sopra, motore in ascolto) |
+| `impostazioni-notifiche.png` | `/impostazioni/notifiche` | (nessuno: §13.3) |
+| `impostazioni-dati.png` | `/impostazioni/dati` | (nessuno: §8.2, §8.5) |
+| `impostazioni-informazioni.png` | `/impostazioni/informazioni` | (nessuno) |
+| `doppioni-download.png` | `/doppioni` | confronto di `miniature/09-importa-revisione.png` (§9.5) |
+| `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) |
+| `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) |
## Differenze che restano
@@ -42,6 +65,41 @@ dovute ai dati dimostrativi:
Il riquadro «Con queste impostazioni» usa i testi del calcolatore del motore, più lunghi di quelli del mockup.
- **Storie in tema scuro.** Le tessere delle storie non hanno l'anello attorno all'elemento scelto: nel mockup c'è
una tessera selezionata, qui la schermata è senza selezione.
-- **Telefono.** Il mockup del telefono mostra la pagina Attività, che fa parte della seconda metà dell'interfaccia;
- qui c'è la libreria. I filtri a pastiglia vanno a capo su due righe.
-- **Pagine non ancora fatte.** Attività, Importa, Impostazioni e Browser mostrano un segnaposto: sono della parte 2.
+- **Telefono, libreria.** `14-telefono.png` mostra la libreria; la pagina Attività del mockup al telefono è in
+ `14-attivita-telefono.png`. I filtri a pastiglia vanno a capo su due righe.
+
+### Seconda parte (Attività, Impostazioni, Collegamento, Importa)
+
+Rifatte con `bash tools/schermate/tutte.sh 8490` (le righe dopo «Part 2»), su una dimostrazione appena avviata: la
+schermata del motore fermo si prende per prima, perché «Riprendi» resta spento finché il browser non è stato usato.
+
+- **Attività, anteprima del browser.** Nella dimostrazione l'anteprima compone tre immagini della libreria finta
+ (sessione) o un riquadro neutro con l'indirizzo (in ascolto, fermo): la vera schermata del browser arriva dalla
+ composizione (`IBrowserPreview`). Il motore in ascolto mostra «about:blank» con la luna, come prevede §7.6.
+- **Attività, numeri e righe.** Sessioni, conteggi, orari «verso le» e righe di «In coda» e «Appena fatto» vengono
+ dal motore finto e dall'ora reale. Nella scena fermo l'elenco «In coda» dice «Sospeso» invece degli orari. In
+ «Appena fatto» la riga della verifica ha il segno rosso «Tutto fermo».
+- **Attività, doppioni.** Quando ci sono doppioni da decidere dopo uno scaricamento compare un avviso con il
+ collegamento a «Doppioni da decidere», sotto gli elenchi: il mockup non lo prevede (§9.5).
+- **Attività, fermo.** La striscia rossa ha «Riprendi» solo nell'intestazione della pagina (non doppio). Nel giorno
+ la parte dopo l'arresto è tratteggiata in rosso, come nel mockup; lo storico degli incidenti sta in fondo.
+- **Limiti e comportamento.** Gli orari sono campi di testo a 24 ore («07:30») invece del selettore d'ora del
+ browser, che in alcune lingue mostra AM/PM. I giorni sono cerchi con l'iniziale. La barra di salvataggio resta
+ sempre visibile: spenta con «Nessuna modifica», si accende alla prima modifica.
+- **Impostazioni generali.** In più rispetto al mockup: lo spazio libero accanto alle cartelle, la nota «Per ora
+ c'è solo l'italiano» sotto la lingua e la riga «Solo versione Windows» accanto ad «Avvio». In Docker le cartelle
+ non si cambiano dall'interfaccia (si cambiano i volumi del contenitore) e la sezione Avvio non c'è.
+- **Importa, revisione.** Percorso della cartella temporanea della dimostrazione; le immagini dei doppioni sono
+ disegni generati. Il riquadro dei doppioni passa al caso seguente dopo ogni scelta: la schermata torna al primo
+ caso per mostrarne la decisione. La riga «restano fuori» va a capo su due righe quando spiega più motivi.
+- **Collegamento.** Nella dimostrazione la vista remota non riceve immagini (non c'è un browser vero): al posto della
+ pagina di Instagram c'è un riquadro neutro con lo schema di un modulo e la frase «Qui compare la vera pagina di
+ accesso di Instagram, caricata dal sito. Febe non la ridisegna e non la imita.» La variante Windows sostituisce la
+ vista con «Il browser di Febe è aperto in un'altra finestra» e «Portalo in primo piano».
+- **Dati e copie.** La dimostrazione parte senza copie del database («Nessuna copia ancora.»): la prima si fa con
+ «Fai una copia adesso» o la notte successiva.
+- **Primo avvio.** La dimostrazione ha sempre una libreria; la schermata è disegnata dal passo `benvenuto.js`,
+ che mette nel corpo della pagina quello che la libreria mostra quando è vuota e Febe non è collegato.
+- **Finestra stretta e telefono.** A 860 px il menu delle impostazioni diventa una fila di schede sopra il contenuto
+ e le colonne laterali (passi del collegamento, doppioni dell'importazione) vanno sotto. Al telefono la tabella
+ delle cartelle dell'importazione diventa un elenco di schede e «Esporta l'elenco in CSV» resta solo come icona.
diff --git a/docs/schermate/doppioni-download.png b/docs/schermate/doppioni-download.png
new file mode 100644
index 0000000..1ac06d0
Binary files /dev/null and b/docs/schermate/doppioni-download.png differ
diff --git a/docs/schermate/errore-configurazione.png b/docs/schermate/errore-configurazione.png
new file mode 100644
index 0000000..c628cf1
Binary files /dev/null and b/docs/schermate/errore-configurazione.png differ
diff --git a/docs/schermate/impostazioni-dati.png b/docs/schermate/impostazioni-dati.png
new file mode 100644
index 0000000..a6ba39e
Binary files /dev/null and b/docs/schermate/impostazioni-dati.png differ
diff --git a/docs/schermate/impostazioni-informazioni.png b/docs/schermate/impostazioni-informazioni.png
new file mode 100644
index 0000000..7679568
Binary files /dev/null and b/docs/schermate/impostazioni-informazioni.png differ
diff --git a/docs/schermate/impostazioni-notifiche.png b/docs/schermate/impostazioni-notifiche.png
new file mode 100644
index 0000000..b871b47
Binary files /dev/null and b/docs/schermate/impostazioni-notifiche.png differ
diff --git a/docs/schermate/primo-avvio.png b/docs/schermate/primo-avvio.png
new file mode 100644
index 0000000..7756b71
Binary files /dev/null and b/docs/schermate/primo-avvio.png differ
diff --git a/src/Febe.Core/Alerts/AlertSettings.cs b/src/Febe.Core/Alerts/AlertSettings.cs
new file mode 100644
index 0000000..8f41a12
--- /dev/null
+++ b/src/Febe.Core/Alerts/AlertSettings.cs
@@ -0,0 +1,117 @@
+using Febe.Core.Storage;
+
+namespace Febe.Core.Alerts;
+
+/// The events that deserve an alert (spec §13.3). The red strip in the interface is always on.
+/// «Verifica richiesta».
+/// «Disconnessione».
+/// «Fermo per rallentamento e ripresa».
+/// «Storico di un account completato».
+/// «Disco quasi pieno».
+/// «Formato non riconosciuto».
+public sealed record AlertEvents(bool Verification, bool Disconnection, bool Throttle, bool BackfillDone, bool DiskLow, bool UnknownFormat)
+{
+ public static AlertEvents All { get; } = new(true, true, true, true, true, true);
+}
+
+///
+/// Where and when Febe sends alerts (Impostazioni, Notifiche; spec §13.3): the events, Windows notifications (desktop),
+/// Telegram with the bot token and the chat identifier. The token is a secret: it is stored in the settings table of
+/// the Data folder, never logged, never sent back to the interface.
+///
+public sealed record AlertSettings(AlertEvents Events, bool WindowsNotifications, string? TelegramChatId, string? TelegramToken)
+{
+ public static AlertSettings Default { get; } = new(AlertEvents.All, true, null, null);
+
+ /// Both the bot token and the chat identifier are set.
+ public bool TelegramConfigured => !string.IsNullOrWhiteSpace(TelegramToken) && !string.IsNullOrWhiteSpace(TelegramChatId);
+
+ /// Never prints the token.
+ public override string ToString() =>
+ $"AlertSettings {{ Events = {Events}, WindowsNotifications = {WindowsNotifications}, TelegramChatId = {(TelegramChatId is null ? "-" : "impostato")}, TelegramToken = {(TelegramToken is null ? "-" : "***")} }}";
+}
+
+/// Setting keys of the alerts (spec §8.3 setting).
+public static class AlertSettingKeys
+{
+ public const string Verification = "avvisi.verifica";
+ public const string Disconnection = "avvisi.disconnessione";
+ public const string Throttle = "avvisi.rallentamento";
+ public const string BackfillDone = "avvisi.storico-completato";
+ public const string DiskLow = "avvisi.disco-quasi-pieno";
+ public const string UnknownFormat = "avvisi.formato-non-riconosciuto";
+ public const string Windows = "avvisi.windows";
+ public const string TelegramChat = "avvisi.telegram.chat";
+
+ /// The bot token: a secret (rule 10), never logged nor shown.
+ public const string TelegramToken = "avvisi.telegram.gettone";
+}
+
+/// Reads and writes .
+public static class AlertSettingsStore
+{
+ public static async Task LoadAsync(ISettingsStore store, CancellationToken ct = default)
+ {
+ ArgumentNullException.ThrowIfNull(store);
+ var all = await store.GetAllAsync(ct).ConfigureAwait(false);
+ bool Flag(string key) => !all.TryGetValue(key, out var text) || !bool.TryParse(text, out var value) || value;
+ string? Text(string key) => all.TryGetValue(key, out var text) && !string.IsNullOrWhiteSpace(text) ? text : null;
+ return new AlertSettings(
+ new AlertEvents(
+ Flag(AlertSettingKeys.Verification),
+ Flag(AlertSettingKeys.Disconnection),
+ Flag(AlertSettingKeys.Throttle),
+ Flag(AlertSettingKeys.BackfillDone),
+ Flag(AlertSettingKeys.DiskLow),
+ Flag(AlertSettingKeys.UnknownFormat)),
+ Flag(AlertSettingKeys.Windows),
+ Text(AlertSettingKeys.TelegramChat),
+ Text(AlertSettingKeys.TelegramToken));
+ }
+
+ /// Stores the settings in one transaction (a null token or chat removes it).
+ public static Task SaveAsync(ISettingsStore store, AlertSettings settings, CancellationToken ct = default)
+ {
+ ArgumentNullException.ThrowIfNull(store);
+ ArgumentNullException.ThrowIfNull(settings);
+ static string B(bool value) => value ? "true" : "false";
+ return store.SetManyAsync(
+ new Dictionary
+ {
+ [AlertSettingKeys.Verification] = B(settings.Events.Verification),
+ [AlertSettingKeys.Disconnection] = B(settings.Events.Disconnection),
+ [AlertSettingKeys.Throttle] = B(settings.Events.Throttle),
+ [AlertSettingKeys.BackfillDone] = B(settings.Events.BackfillDone),
+ [AlertSettingKeys.DiskLow] = B(settings.Events.DiskLow),
+ [AlertSettingKeys.UnknownFormat] = B(settings.Events.UnknownFormat),
+ [AlertSettingKeys.Windows] = B(settings.WindowsNotifications),
+ [AlertSettingKeys.TelegramChat] = string.IsNullOrWhiteSpace(settings.TelegramChatId) ? null : settings.TelegramChatId.Trim(),
+ [AlertSettingKeys.TelegramToken] = string.IsNullOrWhiteSpace(settings.TelegramToken) ? null : settings.TelegramToken.Trim(),
+ },
+ ct);
+ }
+}
+
+/// Outcome of «Invia una prova».
+/// The message left.
+/// Italian text for the page: what happened and what to do.
+public sealed record AlertTestResult(bool Sent, string Message);
+
+///
+/// «Invia una prova» of the Telegram alerts (spec §13.3). The real sender (one HTTPS call with HttpClient, no
+/// library, the address never logged because it contains the token) arrives with milestone M8 and replaces
+/// .
+///
+public interface IAlertTestSender
+{
+ Task SendTelegramTestAsync(AlertSettings settings, CancellationToken ct);
+}
+
+/// Until M8: no message leaves, and the page says so plainly.
+public sealed class TelegramNotAvailableYet : IAlertTestSender
+{
+ public const string Text =
+ "Le impostazioni sono salvate, ma l'invio dei messaggi Telegram non c'è ancora in questa versione di Febe (arriva con la tappa M8): nessun messaggio è partito, nemmeno di prova.";
+
+ public Task SendTelegramTestAsync(AlertSettings settings, CancellationToken ct) => Task.FromResult(new AlertTestResult(false, Text));
+}
diff --git a/src/Febe.Core/Library/DailyBackup.cs b/src/Febe.Core/Library/DailyBackup.cs
index 09ae4b9..f14200c 100644
--- a/src/Febe.Core/Library/DailyBackup.cs
+++ b/src/Febe.Core/Library/DailyBackup.cs
@@ -64,6 +64,35 @@ public sealed partial class DailyBackup(IDatabaseMaintenance database, IClock cl
return new BackupResult(created, ApplyRetention(today));
}
+ ///
+ /// «Fai una copia adesso» (Impostazioni, Dati): a fresh copy of the database now. It becomes today's copy, replacing
+ /// the one made earlier today only after the new one is complete (one copy per day, as the retention expects).
+ /// Then the retention is applied.
+ ///
+ public async Task RunNowAsync(CancellationToken ct = default)
+ {
+ Directory.CreateDirectory(Folder);
+ var today = LocalCalendar.Today(clock.Now, clock.LocalZone);
+ var target = Path.Combine(Folder, FileNameFor(today));
+ var part = target + "." + Guid.NewGuid().ToString("N")[..8] + PartSuffix;
+ BackupFile created;
+ try
+ {
+ await database.BackupToAsync(part, ct).ConfigureAwait(false);
+ File.Move(part, target, overwrite: true);
+ created = new BackupFile(today, target, new FileInfo(target).Length);
+ }
+ finally
+ {
+ if (File.Exists(part))
+ {
+ File.Delete(part);
+ }
+ }
+
+ return new BackupResult(created, ApplyRetention(today));
+ }
+
/// The copies present, newest first.
public IReadOnlyList List()
{
diff --git a/src/Febe.Core/Library/DownloadDuplicateReview.cs b/src/Febe.Core/Library/DownloadDuplicateReview.cs
new file mode 100644
index 0000000..81ce928
--- /dev/null
+++ b/src/Febe.Core/Library/DownloadDuplicateReview.cs
@@ -0,0 +1,327 @@
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Storage;
+
+namespace Febe.Core.Library;
+
+/// One side of a probable duplicate found after a download (spec §9.5): a file of the library.
+/// The file.
+/// Its entry.
+/// The account.
+/// The account's user name.
+/// Post, story, highlight…
+/// Photo or video.
+/// Width in pixels.
+/// Height in pixels.
+/// Size on disk.
+/// Publication of the entry.
+/// Downloaded or imported.
+/// SHA-256: the thumbnail key.
+/// A thumbnail exists.
+/// Path relative to the account folder.
+/// Files of the entry still present.
+/// The file is still in the library (not deleted meanwhile).
+public sealed record DownloadDuplicateSide(
+ long MediaId,
+ long EntryId,
+ long AccountId,
+ string Username,
+ EntryKind EntryKind,
+ MediaKind Kind,
+ int? Width,
+ int? Height,
+ long? Bytes,
+ DateTimeOffset PublishedAt,
+ Provenance Provenance,
+ string? Sha256,
+ bool HasThumbnail,
+ string? RelativePath,
+ int FilesInEntry,
+ bool Present);
+
+/// A probable duplicate after a download: the file already there and the one just downloaded.
+/// The stored pair (Pending until Alberto chooses: nothing is decided in advance).
+/// The file that was already in the library.
+/// The file just downloaded.
+/// The «Più grande» badge goes on the downloaded file (more pixels, then more bytes).
+public sealed record DownloadDuplicateCase(DuplicatePair Pair, DownloadDuplicateSide Existing, DownloadDuplicateSide Candidate, bool CandidateIsLarger);
+
+/// What a decision did.
+/// Pairs decided (more than one with «applica a tutti i casi simili»).
+/// Files removed from the library by the decision.
+/// Italian notes on files that could not be removed (they stay, nothing is lost).
+public sealed record DownloadDecisionResult(int Decided, int FilesRemoved, IReadOnlyList Problems);
+
+///
+/// The review of the probable duplicates found after a download (spec §9.5, §10.3): the same comparison as mockup 09
+/// for duplicate_pair rows with origin «download». Both files stay in the library until Alberto decides; only his
+/// explicit choice removes one (rule 12):
+///
+/// - «Tienili entrambi»: nothing is removed.
+/// - «Tieni quello in libreria»: the file just downloaded goes.
+/// - «Tieni il più grande»: the smaller goes (more pixels, then more bytes; on a tie the one already there stays).
+///
+/// A removed file whose entry has no other file is deleted as «Elimina dalla libreria» with the choice remembered, so it
+/// is not downloaded again; a file of a series leaves only its position (marked «eliminato»), and the journal of the
+/// account receives the entry again with the files that remain.
+///
+public sealed class DownloadDuplicateReview(
+ IFebeStorage storage,
+ LibraryLayout layout,
+ AccountJournal journal,
+ IClock clock,
+ ThumbnailStore? thumbnails = null,
+ PerceptualHashIndex? hashIndex = null)
+{
+ public Task CountPendingAsync(CancellationToken ct = default) => storage.Duplicates.CountPendingAsync(DuplicateOrigin.Download, ct);
+
+ /// Pending cases in creation order, after . Pairs whose files are gone are skipped.
+ public async Task> ListAsync(long afterPairId = 0, int limit = 50, CancellationToken ct = default)
+ {
+ var list = new List();
+ var after = afterPairId;
+ while (list.Count < limit)
+ {
+ var pairs = await storage.Duplicates.ListPendingAsync(DuplicateOrigin.Download, after, Math.Max(limit, 50), ct).ConfigureAwait(false);
+ if (pairs.Count == 0)
+ {
+ break;
+ }
+
+ foreach (var pair in pairs)
+ {
+ after = pair.Id;
+ if (await BuildAsync(pair, ct).ConfigureAwait(false) is { } found)
+ {
+ list.Add(found);
+ if (list.Count >= limit)
+ {
+ break;
+ }
+ }
+ }
+ }
+
+ return list;
+ }
+
+ public async Task GetAsync(long pairId, CancellationToken ct = default)
+ {
+ var pair = await storage.Duplicates.GetAsync(pairId, ct).ConfigureAwait(false);
+ return pair is { Origin: DuplicateOrigin.Download } ? await BuildAsync(pair, ct).ConfigureAwait(false) : null;
+ }
+
+ ///
+ /// Alberto's decision on a pair; with the same choice goes to every pending pair
+ /// of downloads («Applica a tutti i casi simili»). Throws for an unknown pair and
+ /// for .
+ ///
+ public async Task DecideAsync(long pairId, DuplicateDecision decision, bool applyToAllPending = false, CancellationToken ct = default)
+ {
+ if (decision == DuplicateDecision.Pending)
+ {
+ throw new ArgumentException("Scegli che cosa tenere: il più grande, quello già in libreria oppure entrambi.", nameof(decision));
+ }
+
+ var first = await GetAsync(pairId, ct).ConfigureAwait(false) ?? throw new KeyNotFoundException("Questo doppione non c'è più: forse è già stato deciso.");
+ var cases = new List { first };
+ if (applyToAllPending)
+ {
+ var after = 0L;
+ while (true)
+ {
+ var page = await ListAsync(after, 200, ct).ConfigureAwait(false);
+ if (page.Count == 0)
+ {
+ break;
+ }
+
+ cases.AddRange(page.Where(c => c.Pair.Id != pairId));
+ after = page[^1].Pair.Id;
+ }
+ }
+
+ var removed = 0;
+ var problems = new List();
+ var gone = new HashSet();
+ foreach (var item in cases)
+ {
+ ct.ThrowIfCancellationRequested();
+ if (gone.Contains(item.Existing.MediaId) || gone.Contains(item.Candidate.MediaId))
+ {
+ // One of its files went with an earlier decision of the same batch: this pair is decided without
+ // removing anything else (nothing is removed twice, nothing is lost).
+ await storage.Duplicates.DecideAsync(item.Pair.Id, DuplicateDecision.KeepBoth, clock.Now, ct).ConfigureAwait(false);
+ continue;
+ }
+
+ var loser = decision switch
+ {
+ DuplicateDecision.KeepExisting => item.Candidate,
+ DuplicateDecision.KeepLarger => item.CandidateIsLarger ? item.Existing : item.Candidate,
+ _ => null,
+ };
+
+ // From here the decision goes to the end: it is recorded first, then applied.
+ await storage.Duplicates.DecideAsync(item.Pair.Id, decision, clock.Now, CancellationToken.None).ConfigureAwait(false);
+ if (loser is not { Present: true })
+ {
+ continue;
+ }
+
+ var (ok, problem) = await RemoveAsync(loser, CancellationToken.None).ConfigureAwait(false);
+ gone.Add(loser.MediaId);
+ if (ok)
+ {
+ removed++;
+ }
+ else if (problem is not null)
+ {
+ problems.Add(problem);
+ }
+ }
+
+ return new DownloadDecisionResult(cases.Count, removed, problems);
+ }
+
+ /// True when the candidate is larger: more pixels, then more bytes; a tie keeps the file already there.
+ public static bool IsLarger(DownloadDuplicateSide candidate, DownloadDuplicateSide existing)
+ {
+ ArgumentNullException.ThrowIfNull(candidate);
+ ArgumentNullException.ThrowIfNull(existing);
+ var a = (long)(candidate.Width ?? 0) * (candidate.Height ?? 0);
+ var b = (long)(existing.Width ?? 0) * (existing.Height ?? 0);
+ if (a != b)
+ {
+ return a > b;
+ }
+
+ return (candidate.Bytes ?? 0) > (existing.Bytes ?? 0);
+ }
+
+ private async Task BuildAsync(DuplicatePair pair, CancellationToken ct)
+ {
+ if (pair.ExistingMediaId is not { } existingId || pair.CandidateMediaId is not { } candidateId)
+ {
+ return null;
+ }
+
+ var existing = await SideAsync(existingId, ct).ConfigureAwait(false);
+ var candidate = await SideAsync(candidateId, ct).ConfigureAwait(false);
+ if (existing is null || candidate is null)
+ {
+ return null;
+ }
+
+ return new DownloadDuplicateCase(pair, existing, candidate, IsLarger(candidate, existing));
+ }
+
+ private async Task SideAsync(long mediaId, CancellationToken ct)
+ {
+ var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
+ if (media is null)
+ {
+ return null;
+ }
+
+ var stored = await storage.Entries.GetWithMediaAsync(media.EntryId, ct).ConfigureAwait(false);
+ if (stored is null)
+ {
+ return null;
+ }
+
+ var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false);
+ if (account is null)
+ {
+ return null;
+ }
+
+ return new DownloadDuplicateSide(
+ media.Id,
+ stored.Entry.Id,
+ account.Id,
+ account.Username,
+ stored.Entry.Kind,
+ media.Kind,
+ media.Width,
+ media.Height,
+ media.Bytes,
+ stored.Entry.PublishedAt,
+ stored.Entry.Provenance,
+ media.Sha256,
+ media.HasThumbnail,
+ media.RelativePath,
+ stored.Media.Count(m => EntryStateRules.IsPresent(m.State)),
+ EntryStateRules.IsPresent(media.State));
+ }
+
+ private async Task<(bool Removed, string? Problem)> RemoveAsync(DownloadDuplicateSide side, CancellationToken ct)
+ {
+ if (side.FilesInEntry <= 1)
+ {
+ var deletion = new LibraryDeletion(storage, layout, journal, clock, thumbnails, hashIndex);
+ var result = await deletion.DeleteAsync(side.EntryId, DeletionMode.Remember, ct).ConfigureAwait(false);
+ return result.FailedFiles.Count == 0
+ ? (true, null)
+ : (false, $"@{side.Username}: {string.Join("; ", result.FailedFiles)}. Il file resta sul disco; l'elemento è segnato come eliminato.");
+ }
+
+ // A file of a series: only this position goes; the entry and its other files stay.
+ var stored = await storage.Entries.GetWithMediaAsync(side.EntryId, ct).ConfigureAwait(false);
+ var account = await storage.Accounts.GetAsync(side.AccountId, ct).ConfigureAwait(false);
+ var media = stored?.Media.FirstOrDefault(m => m.Id == side.MediaId);
+ if (stored is null || account is null || media is null)
+ {
+ return (false, null);
+ }
+
+ var folder = layout.AccountFolder(account);
+ await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
+ await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
+ hashIndex?.Remove(media.Id);
+ var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
+ var highlights = await storage.Highlights.ListForEntryAsync(stored.Entry.Id, ct).ConfigureAwait(false);
+ await journal.AppendSavedAsync(
+ folder,
+ account,
+ stored.Entry,
+ remaining,
+ highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
+ ct).ConfigureAwait(false);
+
+ string? problem = null;
+ if (media.RelativePath is { } relative)
+ {
+ try
+ {
+ var path = LibraryLayout.FullPath(folder, relative);
+ if (File.Exists(path))
+ {
+ File.Delete(path);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ problem = $"@{side.Username}, {relative}: {ex.Message}. Il file resta sul disco.";
+ }
+ }
+
+ if (thumbnails is not null && media.Sha256 is { } sha)
+ {
+ var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
+ if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State)))
+ {
+ try
+ {
+ thumbnails.Delete(sha);
+ }
+ catch (IOException)
+ {
+ // A thumbnail left behind costs a few kilobytes.
+ }
+ }
+ }
+
+ return (problem is null, problem);
+ }
+}
diff --git a/src/Febe.Web/Api/ActivityApi.cs b/src/Febe.Web/Api/ActivityApi.cs
new file mode 100644
index 0000000..a1b06ce
--- /dev/null
+++ b/src/Febe.Web/Api/ActivityApi.cs
@@ -0,0 +1,106 @@
+using System.Globalization;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Engine;
+using Febe.Core.Storage;
+using Febe.Web.Engine;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+
+namespace Febe.Web.Api;
+
+///
+/// What the Attività page needs beside the engine snapshot (spec §7.6, §7.9, mockups 06 and 11): the history of the
+/// stops, the still frame of the browser, the probable duplicates waiting for Alberto.
+///
+public static class ActivityApi
+{
+ /// Days of stops shown by the page.
+ public const int HistoryDays = 14;
+
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ endpoints.MapGet("/api/engine/incidents", async (IIncidentHistory history, IClock clock, CancellationToken ct) =>
+ ApiHttp.Json(await IncidentsAsync(history, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.IncidentListDto));
+
+ endpoints.MapGet("/api/browser/preview", async (IBrowserPreview preview, CancellationToken ct) =>
+ {
+ var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
+ var dto = frame is null
+ ? new BrowserPreviewDto(false, null, null, null)
+ : new BrowserPreviewDto(true, WithoutQuery(frame.Url), frame.At.ToUnixTimeMilliseconds(), "/api/browser/preview/frame?v=" + frame.At.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture));
+ return ApiHttp.Json(dto, FebeJsonContext.Default.BrowserPreviewDto);
+ });
+
+ endpoints.MapGet("/api/browser/preview/frame", async (HttpContext context, IBrowserPreview preview, CancellationToken ct) =>
+ {
+ var frame = await preview.GetLatestAsync(ct).ConfigureAwait(false);
+ if (frame is null)
+ {
+ throw new NotFoundException("Nessuna immagine del browser in questo momento.");
+ }
+
+ context.Response.Headers.CacheControl = "no-store";
+ return Results.Bytes(frame.Jpeg, "image/jpeg");
+ });
+
+ endpoints.MapGet("/api/duplicates/count", async (IFebeStorage storage, CancellationToken ct) =>
+ {
+ var download = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Download, ct).ConfigureAwait(false);
+ var import = await storage.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct).ConfigureAwait(false);
+ return ApiHttp.Json(new DuplicateCountsDto(download, import), FebeJsonContext.Default.DuplicateCountsDto);
+ });
+ }
+
+ public static async Task IncidentsAsync(IIncidentHistory history, IClock clock, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(history);
+ ArgumentNullException.ThrowIfNull(clock);
+ var now = clock.Now;
+ var zone = clock.LocalZone;
+ var items = await history.ListAsync(now - TimeSpan.FromDays(HistoryDays), now + TimeSpan.FromMinutes(1), ct).ConfigureAwait(false);
+ var dtos = items.Select(i => new IncidentDto(
+ i.Id,
+ ApiMapping.Local(i.At, now, zone),
+ Level(i.Level),
+ Title(i.Level),
+ i.Signal,
+ WithoutQuery(i.Url),
+ i.StoppedUntil is { } until ? ApiMapping.Local(until, now, zone) : null,
+ i.ResolvedAt is { } resolved ? ApiMapping.Local(resolved, now, zone) : null,
+ i.IsOpen,
+ i.Note)).ToList();
+ var throttles = items.Count(i => i.Level == SignalLevel.Throttle && i.At >= now - TimeSpan.FromDays(7));
+ var advice = throttles >= 3
+ ? $"{ItalianText.Count(throttles, "rallentamento", "rallentamenti")} negli ultimi sette giorni: conviene passare a un profilo più prudente o seguire meno account (Impostazioni, Limiti e comportamento)."
+ : null;
+ return new IncidentListDto(dtos, throttles, advice);
+ }
+
+ public static string Level(SignalLevel level) => level switch
+ {
+ SignalLevel.Throttle => "throttle",
+ SignalLevel.Challenge => "challenge",
+ _ => "disconnect",
+ };
+
+ public static string Title(SignalLevel level) => level switch
+ {
+ SignalLevel.Throttle => "Rallentamento",
+ SignalLevel.Challenge => "Verifica richiesta",
+ _ => "Disconnessione",
+ };
+
+ /// An address without its query string and fragment (signed addresses never reach the page).
+ public static string? WithoutQuery(string? url)
+ {
+ if (string.IsNullOrWhiteSpace(url))
+ {
+ return null;
+ }
+
+ var cut = url.IndexOfAny(['?', '#']);
+ return cut < 0 ? url : url[..cut];
+ }
+}
diff --git a/src/Febe.Web/Api/ApiErrorMiddleware.cs b/src/Febe.Web/Api/ApiErrorMiddleware.cs
index 1c2b324..d31db34 100644
--- a/src/Febe.Web/Api/ApiErrorMiddleware.cs
+++ b/src/Febe.Web/Api/ApiErrorMiddleware.cs
@@ -34,7 +34,7 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger (StatusCodes.Status400BadRequest, ex.Message),
- ArgumentException => (StatusCodes.Status400BadRequest, ex.Message),
+ ArgumentException a => (StatusCodes.Status400BadRequest, CleanMessage(a)),
JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
@@ -53,6 +53,13 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILoggerThe Italian message of an argument error, without the « (Parameter 'x')» that .NET appends.
+ public static string CleanMessage(ArgumentException exception)
+ {
+ ArgumentNullException.ThrowIfNull(exception);
+ return exception.ParamName is { } name ? exception.Message.Replace($" (Parameter '{name}')", string.Empty, StringComparison.Ordinal) : exception.Message;
+ }
}
/// Small helpers of the endpoints.
diff --git a/src/Febe.Web/Api/ConnectionApi.cs b/src/Febe.Web/Api/ConnectionApi.cs
new file mode 100644
index 0000000..8756136
--- /dev/null
+++ b/src/Febe.Web/Api/ConnectionApi.cs
@@ -0,0 +1,65 @@
+using Febe.Core.Abstractions;
+using Febe.Web.Connection;
+using Febe.Web.Engine;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+
+namespace Febe.Web.Api;
+
+///
+/// The link to Instagram (spec §4.1, §10.3; contract in Connection/PROTOCOLLO.md) over .
+/// Commands pass the Origin check of the security middleware like every other command (§13.1). Opening the login page
+/// is not an engine action: Alberto uses the browser and the engine is still.
+///
+public static class ConnectionApi
+{
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ endpoints.MapGet("/api/connection", async (IConnectionService connection, CancellationToken ct) =>
+ ApiHttp.Json(ToDto(await connection.GetStatusAsync(ct).ConfigureAwait(false)), FebeJsonContext.Default.ConnectionStatusDto));
+
+ endpoints.MapPost("/api/connection/begin", async (HttpContext context, IConnectionService connection, CancellationToken ct) =>
+ {
+ var body = context.Request.ContentLength is null or > 0
+ ? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
+ : new BeginDrivingRequest(false);
+ await connection.BeginUserDrivingAsync(body.OpenLogin, ct).ConfigureAwait(false);
+ return Results.NoContent();
+ });
+
+ // «Ho finito» counts as having used the browser: «Riprendi» after a verification becomes active (mockup 11).
+ endpoints.MapPost("/api/connection/finish", async (IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
+ {
+ var result = await connection.FinishAsync(ct).ConfigureAwait(false);
+ tracker.MarkUsed(clock.Now);
+ return ApiHttp.Json(new FinishDto(result.Connected, result.Message), FebeJsonContext.Default.FinishDto);
+ });
+
+ endpoints.MapPost("/api/connection/cancel", async (IConnectionService connection, CancellationToken ct) =>
+ {
+ await connection.CancelAsync(ct).ConfigureAwait(false);
+ return Results.NoContent();
+ });
+
+ endpoints.MapPost("/api/connection/disconnect", async (IConnectionService connection, CancellationToken ct) =>
+ {
+ await connection.DisconnectAsync(ct).ConfigureAwait(false);
+ return Results.NoContent();
+ });
+ }
+
+ public static ConnectionStatusDto ToDto(ConnectionStatus status)
+ {
+ ArgumentNullException.ThrowIfNull(status);
+ return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl);
+ }
+
+ public static string State(ConnectionState state) => state switch
+ {
+ ConnectionState.NotConnected => "notConnected",
+ ConnectionState.Connected => "connected",
+ ConnectionState.VerificationRequired => "verificationRequired",
+ _ => "browserUnavailable",
+ };
+}
diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs
index a363382..6c9d14c 100644
--- a/src/Febe.Web/Api/Dtos.cs
+++ b/src/Febe.Web/Api/Dtos.cs
@@ -31,7 +31,8 @@ public sealed record CapabilitiesDto(
string? Scene,
IReadOnlyList Scenes,
long Now,
- string Today);
+ string Today,
+ IReadOnlyList Problems);
public sealed record PreferencesDto(string Theme);
diff --git a/src/Febe.Web/Api/DuplicatesApi.cs b/src/Febe.Web/Api/DuplicatesApi.cs
new file mode 100644
index 0000000..9000146
--- /dev/null
+++ b/src/Febe.Web/Api/DuplicatesApi.cs
@@ -0,0 +1,106 @@
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Engine;
+using Febe.Core.Library;
+using Febe.Web.Library;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+
+namespace Febe.Web.Api;
+
+///
+/// The review of the probable duplicates found after a download (spec §9.5, §10.3): the same comparison as mockup 09
+/// for pairs with origin «download». Nothing is decided in advance; a file leaves the library only on Alberto's choice
+/// (rule 12).
+///
+public static class DuplicatesApi
+{
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ endpoints.MapGet("/api/duplicates", async (long? after, FebeLibrary library, IClock clock, CancellationToken ct) =>
+ {
+ var review = library.DownloadDuplicates;
+ var cases = await review.ListAsync(after ?? 0, 50, ct).ConfigureAwait(false);
+ var pending = await review.CountPendingAsync(ct).ConfigureAwait(false);
+ return ApiHttp.Json(new DuplicatePageDto([.. cases.Select(c => Case(c, clock))], pending), FebeJsonContext.Default.DuplicatePageDto);
+ });
+
+ endpoints.MapPost("/api/duplicates/{pairId:long}", async (long pairId, HttpContext context, FebeLibrary library, LibraryChanges changes, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.DecideRequest).ConfigureAwait(false);
+ var decision = ParseDecision(body.Decision);
+ if (decision == DuplicateDecision.Pending)
+ {
+ throw new BadRequestException("Scegli che cosa tenere: il più grande, quello già in libreria oppure entrambi.");
+ }
+
+ var review = library.DownloadDuplicates;
+ DownloadDecisionResult result;
+ try
+ {
+ result = await review.DecideAsync(pairId, decision, body.ApplyToAll, ct).ConfigureAwait(false);
+ }
+ catch (KeyNotFoundException ex)
+ {
+ throw new NotFoundException(ex.Message, ex);
+ }
+
+ if (result.FilesRemoved > 0)
+ {
+ changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
+ }
+
+ var pending = await review.CountPendingAsync(ct).ConfigureAwait(false);
+ var message = result.FilesRemoved switch
+ {
+ 0 => result.Decided == 1 ? "Fatto: restano entrambi i file." : $"Fatto per {ItalianText.Count(result.Decided, "doppione", "doppioni")}.",
+ _ => $"Fatto: {ItalianText.Count(result.FilesRemoved, "file tolto", "file tolti")} dalla libreria (Febe ricorda la scelta e non li riscarica).",
+ };
+ if (result.Problems.Count > 0)
+ {
+ message += " Alcuni file non si sono potuti cancellare e restano sul disco.";
+ }
+
+ return ApiHttp.Json(new DecideDto(result.Decided, result.FilesRemoved, result.Problems, message, pending), FebeJsonContext.Default.DecideDto);
+ });
+ }
+
+ public static DuplicateCaseDto Case(DownloadDuplicateCase item, IClock clock)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ ArgumentNullException.ThrowIfNull(clock);
+ DuplicateSideDto Side(DownloadDuplicateSide s) => new(
+ true,
+ s.MediaId,
+ null,
+ s.Username,
+ s.RelativePath,
+ ApiMapping.Media(s.Kind),
+ s.Width,
+ s.Height,
+ s.Bytes,
+ ApiMapping.Local(s.PublishedAt, clock.Now, clock.LocalZone),
+ s.HasThumbnail && s.Sha256 is { } sha ? "/api/thumbnails/" + sha : null);
+ return new DuplicateCaseDto(item.Pair.Id, Reason(item.Pair.Reason), Decision(item.Pair.Decision), Side(item.Existing), Side(item.Candidate), item.CandidateIsLarger, false);
+ }
+
+ public static string Reason(DuplicateReason reason) => reason == DuplicateReason.SameInstagramId ? "sameInstagramId" : "visuallySimilar";
+
+ public static string Decision(DuplicateDecision decision) => decision switch
+ {
+ DuplicateDecision.KeepLarger => "keepLarger",
+ DuplicateDecision.KeepExisting => "keepExisting",
+ DuplicateDecision.KeepBoth => "keepBoth",
+ _ => "pending",
+ };
+
+ public static DuplicateDecision ParseDecision(string? text) => text?.ToLowerInvariant() switch
+ {
+ "keeplarger" => DuplicateDecision.KeepLarger,
+ "keepexisting" => DuplicateDecision.KeepExisting,
+ "keepboth" => DuplicateDecision.KeepBoth,
+ "pending" => DuplicateDecision.Pending,
+ _ => throw new BadRequestException("Scelta sconosciuta: tieni il più grande, quello in libreria oppure entrambi."),
+ };
+}
diff --git a/src/Febe.Web/Api/FebeJsonContext.cs b/src/Febe.Web/Api/FebeJsonContext.cs
index 2181589..0f798ca 100644
--- a/src/Febe.Web/Api/FebeJsonContext.cs
+++ b/src/Febe.Web/Api/FebeJsonContext.cs
@@ -44,4 +44,41 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(LoginRequest))]
[JsonSerializable(typeof(LoginDto))]
[JsonSerializable(typeof(Library.LibraryChange))]
+[JsonSerializable(typeof(ConnectionStatusDto))]
+[JsonSerializable(typeof(BeginDrivingRequest))]
+[JsonSerializable(typeof(FinishDto))]
+[JsonSerializable(typeof(IncidentListDto))]
+[JsonSerializable(typeof(BrowserPreviewDto))]
+[JsonSerializable(typeof(DuplicateCountsDto))]
+[JsonSerializable(typeof(GeneralSettingsDto))]
+[JsonSerializable(typeof(GeneralSettingsRequest))]
+[JsonSerializable(typeof(NamingRequest))]
+[JsonSerializable(typeof(NamingPreviewDto))]
+[JsonSerializable(typeof(PickFolderRequest))]
+[JsonSerializable(typeof(PathDto))]
+[JsonSerializable(typeof(PathRequest))]
+[JsonSerializable(typeof(LimitsDto))]
+[JsonSerializable(typeof(LimitsRequest))]
+[JsonSerializable(typeof(NotificationSettingsDto))]
+[JsonSerializable(typeof(NotificationSettingsRequest))]
+[JsonSerializable(typeof(AlertTestRequest))]
+[JsonSerializable(typeof(AlertTestDto))]
+[JsonSerializable(typeof(DataSettingsDto))]
+[JsonSerializable(typeof(RebuildRequest))]
+[JsonSerializable(typeof(RebuildStatusDto))]
+[JsonSerializable(typeof(AboutDto))]
+[JsonSerializable(typeof(DuplicatePageDto))]
+[JsonSerializable(typeof(DecideRequest))]
+[JsonSerializable(typeof(DecideDto))]
+[JsonSerializable(typeof(ImportRunDto))]
+[JsonSerializable(typeof(ImportOverviewDto))]
+[JsonSerializable(typeof(SourceListDto))]
+[JsonSerializable(typeof(SourceInfoDto))]
+[JsonSerializable(typeof(ImportStartRequest))]
+[JsonSerializable(typeof(ImportProgressDto))]
+[JsonSerializable(typeof(ImportReviewDto))]
+[JsonSerializable(typeof(FolderTargetRequest))]
+[JsonSerializable(typeof(ImportModeRequest))]
+[JsonSerializable(typeof(ImportPlanDto))]
+[JsonSerializable(typeof(ImportReportDto))]
public sealed partial class FebeJsonContext : JsonSerializerContext;
diff --git a/src/Febe.Web/Api/ImportApi.cs b/src/Febe.Web/Api/ImportApi.cs
new file mode 100644
index 0000000..7427833
--- /dev/null
+++ b/src/Febe.Web/Api/ImportApi.cs
@@ -0,0 +1,426 @@
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Import;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Web.Import;
+using Febe.Web.Native;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+
+namespace Febe.Web.Api;
+
+///
+/// Importa (spec §9, mockup 09) over : the four steps Sorgente, Analisi, Revisione, Copia.
+/// The analysis and the copy run in the background; the page follows them with /progress. No file of the source
+/// is touched before the copy, and «Sposta» deletes an original only after its copy was verified (spec §9.4).
+///
+public static class ImportApi
+{
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ endpoints.MapGet("/api/import", async (HttpContext context, ImportHub hub, IClock clock, IServiceProvider services, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var runs = await service.ListRunsAsync(ct).ConfigureAwait(false);
+ var d = SettingsApi.Deps.From(services);
+ var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock);
+ var active = service.ActiveRunId;
+ return ApiHttp.Json(
+ new ImportOverviewDto([.. runs.Take(20).Select(r => Run(service, r, clock, active))], active, service.Sources.Root, hub.SourceRoot is null && caps.PickFolder),
+ FebeJsonContext.Default.ImportOverviewDto);
+ });
+
+ endpoints.MapGet("/api/import/sources", async (string? path, ImportHub hub, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var root = service.Sources.Root ?? throw new BadRequestException("Qui la cartella si sceglie con la finestra del sistema.");
+ var folders = Guard(() => service.BrowseSources(path));
+ var relative = string.IsNullOrWhiteSpace(path) ? null : path.Trim('/', '\\');
+ var parent = relative is null ? null : relative.Contains('/', StringComparison.Ordinal) ? relative[..relative.LastIndexOf('/')] : string.Empty;
+ return ApiHttp.Json(
+ new SourceListDto(relative, parent, relative is null ? root : LibraryLayout.ToStored(Path.Combine(root, relative)), [.. folders.Select(f => new SourceFolderDto(f.Name, f.Path, f.HasSubfolders))]),
+ FebeJsonContext.Default.SourceListDto);
+ });
+
+ endpoints.MapPost("/api/import/pick-folder", async (ImportHub hub, INativeShell shell, CancellationToken ct) =>
+ {
+ if (hub.SourceRoot is not null || !shell.CanPickFolder)
+ {
+ throw new BadRequestException("Qui la cartella da importare si sceglie dall'elenco delle cartelle di /importa.");
+ }
+
+ var picked = await shell.PickFolderAsync("Cartella da importare", null, ct).ConfigureAwait(false);
+ return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto);
+ });
+
+ endpoints.MapPost("/api/import/inspect", async (HttpContext context, ImportHub hub, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false);
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var info = Guard(() => service.InspectSource(body.Path));
+ return ApiHttp.Json(
+ new SourceInfoDto(body.Path, info.DisplayPath, info.Name, info.ReadOnly, info.CanMove, info.LooksLikeFebeLibrary, info.LooksLikeStogram, info.Folders),
+ FebeJsonContext.Default.SourceInfoDto);
+ });
+
+ endpoints.MapPost("/api/import/start", async (HttpContext context, ImportHub hub, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ImportStartRequest).ConfigureAwait(false);
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var run = await GuardAsync(() => service.StartAsync(body.Path, new ImportAnalysisOptions { StogramHypothesis = body.Stogram }, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(Run(service, run, clock, service.ActiveRunId), FebeJsonContext.Default.ImportRunDto);
+ });
+
+ endpoints.MapGet("/api/import/{id:long}/progress", async (long id, ImportHub hub, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var run = await GetRunAsync(service, id, ct).ConfigureAwait(false);
+ var progress = await GuardAsync(() => service.GetProgressAsync(id)).ConfigureAwait(false);
+ return ApiHttp.Json(Progress(progress, run, service.ActiveRunId == id), FebeJsonContext.Default.ImportProgressDto);
+ });
+
+ endpoints.MapPost("/api/import/{id:long}/interrupt", async (long id, ImportHub hub, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ await GetRunAsync(service, id, ct).ConfigureAwait(false);
+ await service.InterruptAsync(id).ConfigureAwait(false);
+ return ApiHttp.Message("Interrotta: quello che è stato fatto resta, e riprendi da qui quando vuoi.");
+ });
+
+ endpoints.MapPost("/api/import/{id:long}/resume", async (long id, ImportHub hub, IClock clock, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var run = await GuardAsync(() => service.ResumeAsync(id, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(Run(service, run, clock, service.ActiveRunId), FebeJsonContext.Default.ImportRunDto);
+ });
+
+ endpoints.MapGet("/api/import/{id:long}/review", async (long id, ImportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ return ApiHttp.Json(await ReviewAsync(service, storage, id, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ImportReviewDto);
+ });
+
+ endpoints.MapPut("/api/import/{id:long}/folders", async (long id, HttpContext context, ImportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FolderTargetRequest).ConfigureAwait(false);
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var target = body.Kind?.ToLowerInvariant() switch
+ {
+ "none" => FolderTarget.None,
+ "existing" => FolderTarget.Existing(body.AccountId ?? throw new BadRequestException("Scegli l'account.")),
+ "newarchiveaccount" => FolderTarget.NewArchiveAccount(body.Username ?? throw new BadRequestException("Scrivi il nome del nuovo account.")),
+ _ => throw new BadRequestException("Destinazione sconosciuta."),
+ };
+ await GuardAsync(async () =>
+ {
+ await service.SetFolderTargetAsync(id, body.Folder ?? string.Empty, target, ct).ConfigureAwait(false);
+ return true;
+ }).ConfigureAwait(false);
+ return ApiHttp.Json(await ReviewAsync(service, storage, id, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.ImportReviewDto);
+ });
+
+ endpoints.MapPut("/api/import/{id:long}/mode", async (long id, HttpContext context, ImportHub hub, IFebeStorage storage, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ImportModeRequest).ConfigureAwait(false);
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ await GuardAsync(() => service.SetModeAsync(id, ParseMode(body.Mode), ct)).ConfigureAwait(false);
+ return ApiHttp.Json(Plan(await GuardAsync(() => service.GetPlanAsync(id, ct)).ConfigureAwait(false)), FebeJsonContext.Default.ImportPlanDto);
+ });
+
+ endpoints.MapGet("/api/import/{id:long}/duplicates", async (long id, long? after, bool? all, ImportHub hub, IClock clock, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ await GetRunAsync(service, id, ct).ConfigureAwait(false);
+ var cases = await GuardAsync(() => service.ListDuplicatesAsync(id, pendingOnly: all != true, after ?? 0, 50, ct)).ConfigureAwait(false);
+ var review = await GuardAsync(() => service.GetReviewAsync(id, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(new DuplicatePageDto([.. cases.Select(c => Case(c, clock))], review.PendingDuplicates), FebeJsonContext.Default.DuplicatePageDto);
+ });
+
+ endpoints.MapPost("/api/import/{id:long}/duplicates/{pairId:long}", async (long id, long pairId, HttpContext context, ImportHub hub, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.DecideRequest).ConfigureAwait(false);
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var decision = DuplicatesApi.ParseDecision(body.Decision);
+ int decided;
+ if (decision == DuplicateDecision.Pending)
+ {
+ await GuardAsync(async () =>
+ {
+ await service.Review.UndecideAsync(id, pairId, ct).ConfigureAwait(false);
+ return true;
+ }).ConfigureAwait(false);
+ decided = 1;
+ }
+ else
+ {
+ decided = await GuardAsync(() => service.DecideAsync(id, pairId, decision, body.ApplyToAll ? DecisionScope.AllPending : DecisionScope.ThisPair, ct)).ConfigureAwait(false);
+ }
+
+ var review = await GuardAsync(() => service.GetReviewAsync(id, ct)).ConfigureAwait(false);
+ var message = decided == 1 ? "Scelta registrata: vale quando importi." : $"Scelta registrata per {ItalianTextCount(decided)}: vale quando importi.";
+ return ApiHttp.Json(new DecideDto(decided, 0, [], message, review.PendingDuplicates), FebeJsonContext.Default.DecideDto);
+ });
+
+ endpoints.MapGet("/api/import/files/{fileId:long}/preview", async (long fileId, HttpContext context, ImportHub hub, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var jpeg = await GuardAsync(() => service.Review.RenderPreviewAsync(fileId, 640, ct)).ConfigureAwait(false)
+ ?? throw new NotFoundException("Anteprima non disponibile per questo file.");
+ context.Response.Headers.CacheControl = "private, max-age=600";
+ return Results.Bytes(jpeg, "image/jpeg");
+ });
+
+ endpoints.MapPost("/api/import/{id:long}/copy", async (long id, HttpContext context, ImportHub hub, IClock clock, CancellationToken ct) =>
+ {
+ var body = context.Request.ContentLength is null or > 0
+ ? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ImportModeRequest).ConfigureAwait(false)
+ : null;
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ ImportMode? mode = body?.Mode is { Length: > 0 } m ? ParseMode(m) : null;
+ var run = await GuardAsync(() => service.StartCopyAsync(id, mode, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(Run(service, run, clock, service.ActiveRunId), FebeJsonContext.Default.ImportRunDto);
+ });
+
+ endpoints.MapGet("/api/import/{id:long}/report", async (long id, ImportHub hub, IClock clock, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var report = await GuardAsync(() => service.GetReportAsync(id, ct)).ConfigureAwait(false);
+ return ApiHttp.Json(Report(service, report, clock), FebeJsonContext.Default.ImportReportDto);
+ });
+
+ endpoints.MapGet("/api/import/{id:long}/report.csv", async (long id, HttpContext context, ImportHub hub, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ var run = await GetRunAsync(service, id, ct).ConfigureAwait(false);
+ var name = service.Reports.CsvFileName(run);
+ context.Response.ContentType = "text/csv; charset=utf-8";
+ context.Response.Headers.ContentDisposition = $"attachment; filename=\"{name}\"";
+ context.Response.Headers.CacheControl = "no-store";
+ await service.WriteCsvAsync(id, context.Response.Body, ct).ConfigureAwait(false);
+ });
+
+ endpoints.MapPost("/api/import/{id:long}/discard", async (long id, ImportHub hub, CancellationToken ct) =>
+ {
+ var service = await hub.GetAsync(ct).ConfigureAwait(false);
+ await GetRunAsync(service, id, ct).ConfigureAwait(false);
+ await service.DiscardAsync(id, ct).ConfigureAwait(false);
+ return ApiHttp.Message("Importazione annullata: nessun file della sorgente è stato toccato.");
+ });
+ }
+
+ // ---------------------------------------------------------------------------------------------- mapping
+
+ public static ImportRunDto Run(ImportService service, ImportRun run, IClock clock, long? active)
+ {
+ ArgumentNullException.ThrowIfNull(service);
+ ArgumentNullException.ThrowIfNull(run);
+ ArgumentNullException.ThrowIfNull(clock);
+ return new ImportRunDto(
+ run.Id,
+ run.SourcePath,
+ service.Sources.DisplayPath(run.SourcePath),
+ State(run.State),
+ run.Mode == ImportMode.Move ? "move" : "copy",
+ run.SourceReadOnly,
+ ApiMapping.Local(run.StartedAt, clock.Now, clock.LocalZone),
+ run.CompletedAt is { } done ? ApiMapping.Local(done, clock.Now, clock.LocalZone) : null,
+ run.LastError,
+ active == run.Id);
+ }
+
+ public static string State(ImportRunState state) => state switch
+ {
+ ImportRunState.Analyzing => "analyzing",
+ ImportRunState.AnalysisInterrupted => "analysisInterrupted",
+ ImportRunState.Reviewing => "reviewing",
+ ImportRunState.Copying => "copying",
+ ImportRunState.CopyInterrupted => "copyInterrupted",
+ ImportRunState.Completed => "completed",
+ _ => "cancelled",
+ };
+
+ public static OutcomeCountsDto Outcomes(IReadOnlyDictionary counts)
+ {
+ ArgumentNullException.ThrowIfNull(counts);
+ int Of(ImportOutcome o) => counts.TryGetValue(o, out var n) ? n : 0;
+ return new OutcomeCountsDto(Of(ImportOutcome.New), Of(ImportOutcome.AlreadyInLibrary), Of(ImportOutcome.ProbableDuplicate), Of(ImportOutcome.Unrecognized), Of(ImportOutcome.IdenticalInSource));
+ }
+
+ public static ImportProgressDto Progress(ImportProgress progress, ImportRun run, bool running)
+ {
+ ArgumentNullException.ThrowIfNull(progress);
+ ArgumentNullException.ThrowIfNull(run);
+ var phase = progress.Phase switch
+ {
+ ImportPhase.Listing => "listing",
+ ImportPhase.Analyzing => "analyzing",
+ ImportPhase.Copying => "copying",
+ _ => "finished",
+ };
+ return new ImportProgressDto(
+ progress.RunId,
+ phase,
+ State(run.State),
+ running,
+ progress.FilesDone,
+ progress.FilesTotal,
+ progress.BytesDone,
+ progress.BytesTotal,
+ progress.Fraction,
+ progress.CurrentFile,
+ Outcomes(progress.Outcomes),
+ progress.Copied,
+ run.LastError);
+ }
+
+ public static ImportPlanDto Plan(ImportPlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ return new ImportPlanDto(
+ plan.ToImport,
+ plan.ToReplace,
+ plan.Skipped,
+ plan.LeftOutNoAccount,
+ plan.FoldersWithoutAccount,
+ plan.LeftOutUndecided,
+ plan.AlreadyDone,
+ plan.Bytes,
+ plan.Mode == ImportMode.Move ? "move" : "copy",
+ plan.ButtonLabel,
+ plan.LeftOutLabel);
+ }
+
+ public static FolderTargetDto Target(FolderTarget target)
+ {
+ ArgumentNullException.ThrowIfNull(target);
+ return new FolderTargetDto(
+ target.Kind switch { FolderTargetKind.Existing => "existing", FolderTargetKind.NewArchiveAccount => "newArchiveAccount", _ => "none" },
+ target.AccountId,
+ target.Username);
+ }
+
+ public static async Task ReviewAsync(ImportService service, IFebeStorage storage, long runId, IClock clock, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(service);
+ ArgumentNullException.ThrowIfNull(storage);
+ var review = await GuardAsync(() => service.GetReviewAsync(runId, ct)).ConfigureAwait(false);
+ var plan = await GuardAsync(() => service.GetPlanAsync(runId, ct)).ConfigureAwait(false);
+ var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
+ return new ImportReviewDto(
+ Run(service, review.Run, clock, service.ActiveRunId),
+ review.DisplayPath,
+ review.Headline,
+ review.Files,
+ review.Bytes,
+ Outcomes(review.ByOutcome),
+ review.Recognized,
+ review.PendingDuplicates,
+ [.. review.Folders.Select(f => new ImportFolderDto(f.Folder, f.DisplayName, f.ProbableAccount, f.Files, f.Bytes, f.New, f.AlreadyInLibrary, f.ProbableDuplicates, f.Unrecognized, f.Recognized, Target(f.Target), f.IsBlocked))],
+ Plan(plan),
+ review.CanMove,
+ review.StogramHypothesis,
+ review.Copied,
+ [.. accounts.OrderBy(a => a.Username, StringComparer.Ordinal).Select(a => new AccountChoiceDto(a.Id, a.Username, ApiMapping.State(a.State)))]);
+ }
+
+ public static DuplicateCaseDto Case(DuplicateCase item, IClock clock)
+ {
+ ArgumentNullException.ThrowIfNull(item);
+ ArgumentNullException.ThrowIfNull(clock);
+ DuplicateSideDto Side(DuplicateSide s) => new(
+ s.InLibrary,
+ s.MediaId,
+ s.ImportFileId,
+ s.Username,
+ s.Path,
+ s.Kind is { } k ? ApiMapping.Media(k) : null,
+ s.Width,
+ s.Height,
+ s.Bytes,
+ s.Date is { } date ? ApiMapping.Local(date, clock.Now, clock.LocalZone) : null,
+ s.InLibrary
+ ? (s.HasThumbnail && s.Sha256 is { } sha ? "/api/thumbnails/" + sha : null)
+ : s.ImportFileId is { } f && s.Kind == MediaKind.Photo ? "/api/import/files/" + f.ToString(System.Globalization.CultureInfo.InvariantCulture) + "/preview" : null);
+ return new DuplicateCaseDto(
+ item.Pair.Id,
+ DuplicatesApi.Reason(item.Pair.Reason),
+ DuplicatesApi.Decision(item.Pair.Decision),
+ Side(item.Existing),
+ Side(item.Candidate),
+ item.CandidateIsLarger,
+ item.InsideSource);
+ }
+
+ public static ImportReportDto Report(ImportService service, ImportReport report, IClock clock)
+ {
+ ArgumentNullException.ThrowIfNull(service);
+ ArgumentNullException.ThrowIfNull(report);
+ return new ImportReportDto(
+ Run(service, report.Run, clock, service.ActiveRunId),
+ report.DisplayPath,
+ report.Files,
+ report.Bytes,
+ Outcomes(report.ByOutcome),
+ report.Copied,
+ report.Moved,
+ report.Replaced,
+ report.Skipped,
+ report.LeftOut,
+ report.Failed,
+ report.BytesCopied,
+ [.. report.ImportedByAccount.Select(a => new ImportCountDto(a.Username, a.Files))],
+ [.. report.AlreadyInLibraryByAccount.Select(a => new ImportCountDto(a.Username, a.Files))],
+ report.Unrecognized,
+ [.. report.Problems.Select(p => new ImportNoteDto(p.Path, p.Note))]);
+ }
+
+ private static ImportMode ParseMode(string? text) => text?.ToLowerInvariant() switch
+ {
+ "copy" => ImportMode.Copy,
+ "move" => ImportMode.Move,
+ _ => throw new BadRequestException("Modo sconosciuto: copia o sposta."),
+ };
+
+ private static string ItalianTextCount(int n) => Core.Engine.ItalianText.Count(n, "doppione", "doppioni");
+
+ private static async Task GetRunAsync(ImportService service, long id, CancellationToken ct) =>
+ await service.GetRunAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa importazione non esiste più.");
+
+ // ---------------------------------------------------------------------------------------------- errors
+
+ /// The import's own exceptions become Italian answers: 400 for a refused request, 404 for a missing import.
+ internal static T Guard(Func action)
+ {
+ try
+ {
+ return action();
+ }
+ catch (Exception ex) when (Translate(ex) is { } translated)
+ {
+ throw translated;
+ }
+ }
+
+ internal static async Task GuardAsync(Func> action)
+ {
+ try
+ {
+ return await action().ConfigureAwait(false);
+ }
+ catch (Exception ex) when (Translate(ex) is { } translated)
+ {
+ throw translated;
+ }
+ }
+
+ private static Exception? Translate(Exception ex) => ex switch
+ {
+ ImportSourceException => new BadRequestException(ex.Message, ex),
+ KeyNotFoundException => new NotFoundException(ex.Message, ex),
+ ArgumentException a => new BadRequestException(ApiErrorMiddleware.CleanMessage(a), ex),
+ InvalidOperationException => new BadRequestException(ex.Message, ex),
+ _ => null,
+ };
+}
diff --git a/src/Febe.Web/Api/Part2Dtos.cs b/src/Febe.Web/Api/Part2Dtos.cs
new file mode 100644
index 0000000..14ccbfe
--- /dev/null
+++ b/src/Febe.Web/Api/Part2Dtos.cs
@@ -0,0 +1,296 @@
+namespace Febe.Web.Api;
+
+// JSON shapes of the second part of the interface (Attività, Impostazioni, Importa, Collegamento, Browser, doppioni).
+// Same conventions as Dtos.cs: English camelCase names, Italian texts, times as Unix milliseconds or LocalTimeDto.
+
+// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
+
+/// GET /api/connection. : notConnected, connected, verificationRequired, browserUnavailable.
+public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl);
+
+/// POST /api/connection/begin.
+public sealed record BeginDrivingRequest(bool OpenLogin);
+
+/// POST /api/connection/finish.
+public sealed record FinishDto(bool Connected, string Message);
+
+// ---------------------------------------------------------------- activity
+
+/// A stop of the circuit breaker. : throttle, challenge, disconnect.
+public sealed record IncidentDto(
+ long Id,
+ LocalTimeDto At,
+ string Level,
+ string Title,
+ string Signal,
+ string? Url,
+ LocalTimeDto? StoppedUntil,
+ LocalTimeDto? ResolvedAt,
+ bool Open,
+ string? Note);
+
+/// «Tre rallentamenti in sette giorni»: the proposal of spec §7.6, or null.
+public sealed record IncidentListDto(IReadOnlyList Items, int ThrottlesLastWeek, string? Advice);
+
+/// The preview of Febe's browser: is the address of the JPEG (with a version), or null.
+public sealed record BrowserPreviewDto(bool HasFrame, string? Url, long? At, string? Frame);
+
+/// Probable duplicates waiting for a decision, by origin.
+public sealed record DuplicateCountsDto(int Download, int Import);
+
+// ---------------------------------------------------------------- settings: general
+
+/// A folder with the free space of its disk and the space it uses (measured in the background).
+public sealed record FolderInfoDto(string Path, long? FreeBytes, long? UsedBytes, bool Measuring);
+
+public sealed record NamingPreviewFileDto(string Name, string Kind);
+
+public sealed record NamingPreviewFolderDto(IReadOnlyList Path, IReadOnlyList Files);
+
+/// The «Risultato» tree of mockup 08 and the problems of the two schemes.
+public sealed record NamingPreviewDto(string AccountFolder, IReadOnlyList Folders, IReadOnlyList Errors, IReadOnlyList Warnings);
+
+/// Impostazioni, Generali (mockup 08).
+/// Windows: «Avvia Febe all'accensione del computer»; null where it does not exist.
+/// Windows: «Chiudendo la finestra, Febe resta attivo nell'area di notifica».
+public sealed record GeneralSettingsDto(
+ FolderInfoDto Library,
+ FolderInfoDto Data,
+ bool FoldersReadOnly,
+ bool CanPickFolder,
+ bool CanChangeDataFolder,
+ string NamingScheme,
+ string HighlightScheme,
+ string DefaultNamingScheme,
+ string DefaultHighlightScheme,
+ IReadOnlyList Placeholders,
+ bool SetFileTime,
+ NamingPreviewDto Preview,
+ bool? Autostart,
+ bool KeepInTray,
+ string Language);
+
+/// Saves Impostazioni, Generali. A null keeps the library folder.
+public sealed record GeneralSettingsRequest(string? LibraryFolder, string NamingScheme, string HighlightScheme, bool SetFileTime, bool? Autostart, bool? KeepInTray);
+
+public sealed record NamingRequest(string? NamingScheme, string? HighlightScheme);
+
+/// : library or data.
+public sealed record PickFolderRequest(string Which);
+
+/// A path; null or empty when Alberto cancelled the picker.
+public sealed record PathDto(string? Path);
+
+public sealed record PathRequest(string Path);
+
+// ---------------------------------------------------------------- settings: limits (mockup 07)
+
+/// A budget of a category (ActionKind names, as in the engine snapshot) with the most the interface accepts.
+public sealed record BudgetValueDto(string Kind, string Label, int PerHour, int PerDay, int MaxPerHour, int MaxPerDay);
+
+/// The values of a caution profile. : prudent, balanced, fast, custom. Times «07:30».
+public sealed record ProfileValuesDto(
+ string Kind,
+ string Name,
+ string WindowStart,
+ string WindowEnd,
+ int JitterMinutes,
+ int SessionMinMinutes,
+ int SessionMaxMinutes,
+ int PauseMinMinutes,
+ int PauseMaxMinutes,
+ IReadOnlyList Budgets,
+ double DataPerDayGb,
+ int BackfillPerAccount,
+ int RampUpDays);
+
+/// The limits of spec §7.5 that the interface enforces.
+public sealed record LimitRulesDto(int MinPauseMinutes, int MaxSessionMinutes, int MaxWindowHours, int MaxJitterMinutes, double MaxDataPerDayGb, int MaxBackfillPerAccount, int MaxRampUpDays);
+
+/// Impostazioni, Limiti e comportamento. : slow, natural, brisk. Days: 0 Sunday … 6 Saturday.
+/// The fixed stops after throttles, informative only: «1 ora», «6 ore», «24 ore».
+public sealed record LimitsDto(
+ string Profile,
+ IReadOnlyList Presets,
+ ProfileValuesDto Current,
+ string Pace,
+ bool GradualStart,
+ IReadOnlyList ActiveDays,
+ LimitRulesDto Rules,
+ IReadOnlyList Stops);
+
+/// Saves the limits; is read when is custom.
+public sealed record LimitsRequest(string Profile, ProfileValuesDto? Values, string Pace, bool GradualStart, IReadOnlyList ActiveDays);
+
+// ---------------------------------------------------------------- settings: notifications (spec §13.3)
+
+public sealed record AlertEventsDto(bool Verification, bool Disconnection, bool Throttle, bool BackfillDone, bool DiskLow, bool UnknownFormat);
+
+/// The token is never sent back: only whether it is set.
+public sealed record NotificationSettingsDto(AlertEventsDto Events, bool Windows, bool WindowsAvailable, string? TelegramChatId, bool TelegramTokenSet, bool TelegramAvailable);
+
+///
+/// Saves the notifications. : null or empty keeps the stored token, a value replaces it;
+/// removes it.
+///
+public sealed record NotificationSettingsRequest(AlertEventsDto Events, bool Windows, string? TelegramChatId, string? TelegramToken, bool RemoveTelegramToken);
+
+/// : telegram or windows.
+public sealed record AlertTestRequest(string Channel);
+
+public sealed record AlertTestDto(bool Sent, string Message);
+
+// ---------------------------------------------------------------- settings: data and backups (spec §8.2, §8.5)
+
+public sealed record BackupDto(string Day, string Name, long Bytes, LocalTimeDto Modified);
+
+/// The rebuild of the database: progress while running, then the report as Italian lines.
+public sealed record RebuildStatusDto(bool Running, string? Folder, int FoldersDone, int FoldersTotal, int FilesChecked, IReadOnlyList Lines, string? Error, LocalTimeDto? FinishedAt);
+
+public sealed record DataSettingsDto(FolderInfoDto Data, string Database, long? DatabaseBytes, string BackupsFolder, IReadOnlyList Backups, int KeepDays, RebuildStatusDto Rebuild);
+
+/// «Ricostruisci»: must be the word «ricostruisci» typed by Alberto.
+public sealed record RebuildRequest(string Confirm);
+
+/// Impostazioni, Informazioni.
+public sealed record AboutDto(string Version, string Edition, string DataFolder, string LibraryFolder, string Guide, string Repository);
+
+// ---------------------------------------------------------------- probable duplicates (mockup 09, spec §9.5)
+
+/// One side of a probable duplicate. is the address of its picture (thumbnail or preview).
+public sealed record DuplicateSideDto(
+ bool InLibrary,
+ long? MediaId,
+ long? ImportFileId,
+ string? Username,
+ string? Path,
+ string? Kind,
+ int? Width,
+ int? Height,
+ long? Bytes,
+ LocalTimeDto? Date,
+ string? Image);
+
+/// A probable duplicate. : sameInstagramId, visuallySimilar. : pending, keepLarger, keepExisting, keepBoth.
+public sealed record DuplicateCaseDto(long PairId, string Reason, string Decision, DuplicateSideDto Existing, DuplicateSideDto Candidate, bool CandidateIsLarger, bool InsideSource);
+
+public sealed record DuplicatePageDto(IReadOnlyList Cases, int Pending);
+
+/// A decision. : «Applica a tutti i casi simili» (every pending pair).
+public sealed record DecideRequest(string Decision, bool ApplyToAll);
+
+public sealed record DecideDto(int Decided, int FilesRemoved, IReadOnlyList Problems, string Message, int Pending);
+
+// ---------------------------------------------------------------- import (spec §9, mockup 09)
+
+/// An import. : analyzing, analysisInterrupted, reviewing, copying, copyInterrupted, completed, cancelled.
+public sealed record ImportRunDto(long Id, string Source, string DisplayPath, string State, string Mode, bool ReadOnly, LocalTimeDto Started, LocalTimeDto? Completed, string? Error, bool Running);
+
+/// Docker: the root of the sources (the page lists its subfolders); null: the native picker.
+public sealed record ImportOverviewDto(IReadOnlyList Runs, long? ActiveRunId, string? SourceRoot, bool PickFolder);
+
+public sealed record SourceFolderDto(string Name, string Path, bool HasSubfolders);
+
+/// The folder listed (relative to the root), null for the root itself.
+/// The folder above, or null at the root.
+public sealed record SourceListDto(string? Path, string? Parent, string DisplayPath, IReadOnlyList Folders);
+
+public sealed record SourceInfoDto(string Path, string DisplayPath, string Name, bool ReadOnly, bool CanMove, bool LooksLikeFebeLibrary, bool LooksLikeStogram, IReadOnlyList Folders);
+
+public sealed record ImportStartRequest(string Path, bool Stogram);
+
+public sealed record OutcomeCountsDto(int New, int AlreadyInLibrary, int ProbableDuplicates, int Unrecognized, int IdenticalInSource);
+
+/// Step 2 and 4. : listing, analyzing, copying, finished.
+public sealed record ImportProgressDto(
+ long RunId,
+ string Phase,
+ string State,
+ bool Running,
+ int FilesDone,
+ int FilesTotal,
+ long BytesDone,
+ long BytesTotal,
+ double Fraction,
+ string? CurrentFile,
+ OutcomeCountsDto Outcomes,
+ int Copied,
+ string? Error);
+
+/// Where a folder goes. : none, existing, newArchiveAccount.
+public sealed record FolderTargetDto(string Kind, long? AccountId, string? Username);
+
+public sealed record ImportFolderDto(
+ string Folder,
+ string DisplayName,
+ string? ProbableAccount,
+ int Files,
+ long Bytes,
+ int New,
+ int AlreadyInLibrary,
+ int ProbableDuplicates,
+ int Unrecognized,
+ int Recognized,
+ FolderTargetDto Target,
+ bool Blocked);
+
+public sealed record ImportPlanDto(
+ int ToImport,
+ int ToReplace,
+ int Skipped,
+ int LeftOutNoAccount,
+ int FoldersWithoutAccount,
+ int LeftOutUndecided,
+ int AlreadyDone,
+ long Bytes,
+ string Mode,
+ string ButtonLabel,
+ string? LeftOutLabel);
+
+public sealed record AccountChoiceDto(long Id, string Username, string State);
+
+/// Step 3 (mockup 09).
+public sealed record ImportReviewDto(
+ ImportRunDto Run,
+ string DisplayPath,
+ string Headline,
+ int Files,
+ long Bytes,
+ OutcomeCountsDto Outcomes,
+ int Recognized,
+ int PendingDuplicates,
+ IReadOnlyList Folders,
+ ImportPlanDto Plan,
+ bool CanMove,
+ bool StogramHypothesis,
+ int Copied,
+ IReadOnlyList Accounts);
+
+/// Sets where a folder goes. : none, existing (with ), newArchiveAccount (with ).
+public sealed record FolderTargetRequest(string Folder, string Kind, long? AccountId, string? Username);
+
+/// : copy or move.
+public sealed record ImportModeRequest(string Mode);
+
+public sealed record ImportCountDto(string Username, int Files);
+
+public sealed record ImportNoteDto(string Path, string Note);
+
+/// Step 4: the final report.
+public sealed record ImportReportDto(
+ ImportRunDto Run,
+ string DisplayPath,
+ int Files,
+ long Bytes,
+ OutcomeCountsDto Outcomes,
+ int Copied,
+ int Moved,
+ int Replaced,
+ int Skipped,
+ int LeftOut,
+ int Failed,
+ long BytesCopied,
+ IReadOnlyList ImportedByAccount,
+ IReadOnlyList AlreadyInLibraryByAccount,
+ IReadOnlyList Unrecognized,
+ IReadOnlyList Problems);
diff --git a/src/Febe.Web/Api/SettingsApi.cs b/src/Febe.Web/Api/SettingsApi.cs
new file mode 100644
index 0000000..4180da8
--- /dev/null
+++ b/src/Febe.Web/Api/SettingsApi.cs
@@ -0,0 +1,634 @@
+using System.Globalization;
+using Febe.Core.Abstractions;
+using Febe.Core.Alerts;
+using Febe.Core.Domain;
+using Febe.Core.Engine;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Web.Engine;
+using Febe.Web.Import;
+using Febe.Web.Library;
+using Febe.Web.Native;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Routing;
+
+namespace Febe.Web.Api;
+
+///
+/// Impostazioni (spec §4.7, §7.5, §8.2, §8.5, §13.3; mockups 07 and 08): Generali, Limiti e comportamento, Notifiche,
+/// Dati e copie di sicurezza, Informazioni. Collegamento a Instagram is .
+///
+public static class SettingsApi
+{
+ /// Where the guide lives (wiki of the repository).
+ public const string GuideUrl = "https://gitea.encke-hake.ts.net/Alby96/Febe/wiki";
+
+ public const string RepositoryUrl = "https://gitea.encke-hake.ts.net/Alby96/Febe";
+
+ private const double GiB = 1024d * 1024 * 1024;
+
+ public static void Map(IEndpointRouteBuilder endpoints)
+ {
+ // ------------------------------------------------------------------------------------------ Generali
+ endpoints.MapGet("/api/settings/general", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
+ ApiHttp.Json(await GeneralAsync(context, Deps.From(services), ct).ConfigureAwait(false), FebeJsonContext.Default.GeneralSettingsDto));
+
+ endpoints.MapPut("/api/settings/general", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
+ {
+ var d = Deps.From(services);
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.GeneralSettingsRequest).ConfigureAwait(false);
+ var general = Validate(NamingScheme.Validate(body.NamingScheme, forHighlights: false), "Schema");
+ var highlight = Validate(NamingScheme.Validate(body.HighlightScheme, forHighlights: true), "Schema per le raccolte in evidenza");
+ var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
+ var root = d.Library.Layout.Root;
+ if (!string.IsNullOrWhiteSpace(body.LibraryFolder) && !SamePath(body.LibraryFolder, root))
+ {
+ if (caps.FoldersReadOnly)
+ {
+ throw new BadRequestException("In Docker la cartella della libreria si cambia dal contenitore (volume /libreria), non dall'interfaccia.");
+ }
+
+ root = await ChangeLibraryRootAsync(d, body.LibraryFolder, ct).ConfigureAwait(false);
+ }
+
+ await new LibrarySettings(root, new LibraryNaming(general, highlight), body.SetFileTime).SaveAsync(d.Storage.Settings, ct).ConfigureAwait(false);
+ if (caps.Autostart && body.Autostart is { } autostart)
+ {
+ await d.Shell.SetAutostartAsync(autostart, ct).ConfigureAwait(false);
+ }
+
+ if (body.KeepInTray is { } tray)
+ {
+ await d.Storage.Settings.SetBoolAsync(DesktopSettingKeys.KeepInTray, tray, ct).ConfigureAwait(false);
+ }
+
+ d.Import.LibrarySettingsChanged();
+ d.Changes.Publish(new LibraryChange(d.Clock.Now, null, "settings"));
+ return ApiHttp.Json(await GeneralAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.GeneralSettingsDto);
+ });
+
+ endpoints.MapPost("/api/settings/naming-preview", async (HttpContext context, IFebeStorage storage, IClock clock, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.NamingRequest).ConfigureAwait(false);
+ var sample = await SampleAccountAsync(storage, ct).ConfigureAwait(false);
+ return ApiHttp.Json(Preview(NamingPreview.Build(body.NamingScheme, body.HighlightScheme, clock.LocalZone, sample)), FebeJsonContext.Default.NamingPreviewDto);
+ });
+
+ endpoints.MapPost("/api/settings/pick-folder", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
+ {
+ var d = Deps.From(services);
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PickFolderRequest).ConfigureAwait(false);
+ if (!d.Shell.CanPickFolder)
+ {
+ throw new BadRequestException("Qui le cartelle si cambiano dal contenitore, non dall'interfaccia.");
+ }
+
+ var data = string.Equals(body.Which, "data", StringComparison.OrdinalIgnoreCase);
+ var picked = await d.Shell.PickFolderAsync(
+ data ? "Cartella dei dati di Febe" : "Cartella della libreria",
+ data ? d.Library.Data.Root : d.Library.Layout.Root,
+ ct).ConfigureAwait(false);
+ return ApiHttp.Json(new PathDto(picked), FebeJsonContext.Default.PathDto);
+ });
+
+ endpoints.MapPost("/api/settings/data-folder", async (HttpContext context, IDataFolderChange change, FebeLibrary library, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.PathRequest).ConfigureAwait(false);
+ if (!change.CanChange)
+ {
+ throw new BadRequestException("La cartella dei dati qui non si cambia dall'interfaccia: si sceglie quando si avvia Febe (in Docker, con il volume /dati).");
+ }
+
+ if (string.IsNullOrWhiteSpace(body.Path) || !Path.IsPathFullyQualified(body.Path))
+ {
+ throw new BadRequestException("Serve il percorso completo di una cartella.");
+ }
+
+ if (IsSameOrInside(body.Path, library.Layout.Root) || IsSameOrInside(library.Layout.Root, body.Path))
+ {
+ throw new BadRequestException("La cartella dei dati non può stare dentro la libreria, né contenerla.");
+ }
+
+ return ApiHttp.Message(await change.RequestChangeAsync(body.Path, ct).ConfigureAwait(false));
+ });
+
+ // ------------------------------------------------------------------------------------------ Limiti e comportamento
+ endpoints.MapGet("/api/settings/limits", async (IFebeStorage storage, CancellationToken ct) =>
+ ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto));
+
+ endpoints.MapPut("/api/settings/limits", async (HttpContext context, IFebeStorage storage, IEngineSettingsControl engine, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.LimitsRequest).ConfigureAwait(false);
+ var stored = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
+ var settings = ToSettings(body, stored);
+ var errors = CautionProfileRules.Validate(settings.EffectiveProfile);
+ if (errors.Count > 0)
+ {
+ throw new BadRequestException(string.Join(" ", errors));
+ }
+
+ await engine.ApplyAsync(settings, ct).ConfigureAwait(false);
+ return ApiHttp.Json(Limits(await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false)), FebeJsonContext.Default.LimitsDto);
+ });
+
+ // ------------------------------------------------------------------------------------------ Notifiche
+ endpoints.MapGet("/api/settings/notifications", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
+ {
+ var d = Deps.From(services);
+ return ApiHttp.Json(await NotificationsAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.NotificationSettingsDto);
+ });
+
+ endpoints.MapPut("/api/settings/notifications", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
+ {
+ var d = Deps.From(services);
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.NotificationSettingsRequest).ConfigureAwait(false);
+ var stored = await AlertSettingsStore.LoadAsync(d.Storage.Settings, ct).ConfigureAwait(false);
+ var chat = string.IsNullOrWhiteSpace(body.TelegramChatId) ? null : body.TelegramChatId.Trim();
+ if (chat is not null && (chat.Length > 64 || !chat.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '@')))
+ {
+ throw new BadRequestException("L'identificativo della chat è un numero (anche negativo, per i gruppi) o un nome come @canale.");
+ }
+
+ var token = body.RemoveTelegramToken ? null : string.IsNullOrWhiteSpace(body.TelegramToken) ? stored.TelegramToken : body.TelegramToken.Trim();
+ if (token is not null && (token.Length > 200 || token.Any(char.IsWhiteSpace)))
+ {
+ throw new BadRequestException("Il gettone del bot non è valido: copialo per intero dal messaggio di BotFather, senza spazi.");
+ }
+
+ var e = body.Events;
+ await AlertSettingsStore.SaveAsync(
+ d.Storage.Settings,
+ new AlertSettings(new AlertEvents(e.Verification, e.Disconnection, e.Throttle, e.BackfillDone, e.DiskLow, e.UnknownFormat), body.Windows, chat, token),
+ ct).ConfigureAwait(false);
+ return ApiHttp.Json(await NotificationsAsync(context, d, ct).ConfigureAwait(false), FebeJsonContext.Default.NotificationSettingsDto);
+ });
+
+ endpoints.MapPost("/api/settings/notifications/test", async (HttpContext context, IServiceProvider services, CancellationToken ct) =>
+ {
+ var d = Deps.From(services);
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.AlertTestRequest).ConfigureAwait(false);
+ var settings = await AlertSettingsStore.LoadAsync(d.Storage.Settings, ct).ConfigureAwait(false);
+ if (string.Equals(body.Channel, "windows", StringComparison.OrdinalIgnoreCase))
+ {
+ if (!SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock).Notifications)
+ {
+ throw new BadRequestException("Le notifiche di Windows esistono solo nella versione per Windows.");
+ }
+
+ await d.Shell.NotifyAsync("Febe", "Prova di notifica: gli avvisi di Febe arriveranno così.", ct).ConfigureAwait(false);
+ return ApiHttp.Json(new AlertTestDto(true, "Notifica di prova inviata: dovresti vederla nell'angolo dello schermo."), FebeJsonContext.Default.AlertTestDto);
+ }
+
+ if (!settings.TelegramConfigured)
+ {
+ throw new BadRequestException("Scrivi il gettone del bot e l'identificativo della chat, salva, poi invia la prova.");
+ }
+
+ var sender = d.Services.GetService(typeof(IAlertTestSender)) as IAlertTestSender ?? new TelegramNotAvailableYet();
+ var result = await sender.SendTelegramTestAsync(settings, ct).ConfigureAwait(false);
+ return ApiHttp.Json(new AlertTestDto(result.Sent, result.Message), FebeJsonContext.Default.AlertTestDto);
+ });
+
+ // ------------------------------------------------------------------------------------------ Dati e copie
+ endpoints.MapGet("/api/settings/data", (IServiceProvider services) =>
+ ApiHttp.Json(Data(Deps.From(services)), FebeJsonContext.Default.DataSettingsDto));
+
+ endpoints.MapPost("/api/settings/backups", async (IServiceProvider services, CancellationToken ct) =>
+ {
+ var d = Deps.From(services);
+ var backup = new DailyBackup(d.Storage.Maintenance, d.Clock, d.Library.Data.Backups);
+ var result = await backup.RunNowAsync(ct).ConfigureAwait(false);
+ d.Sizes.Invalidate(d.Library.Data.Root);
+ var created = result.Created!;
+ return ApiHttp.Message($"Copia fatta: {Path.GetFileName(created.Path)}, {ItalianText.Bytes(created.Bytes)}. Se ce n'era già una di oggi, questa la sostituisce.");
+ });
+
+ endpoints.MapPost("/api/settings/rebuild", async (HttpContext context, RebuildJob job, ImportHub import, CancellationToken ct) =>
+ {
+ var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.RebuildRequest).ConfigureAwait(false);
+ if (!string.Equals(body.Confirm?.Trim(), "ricostruisci", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new BadRequestException("Per confermare scrivi la parola «ricostruisci».");
+ }
+
+ if ((await import.GetAsync(ct).ConfigureAwait(false)).ActiveRunId is not null)
+ {
+ throw new BadRequestException("C'è un'importazione al lavoro: aspetta che finisca, poi ricostruisci.");
+ }
+
+ if (!job.TryStart())
+ {
+ throw new BadRequestException("La ricostruzione è già in corso.");
+ }
+
+ return ApiHttp.Message("Ricostruzione avviata: Febe rilegge le cartelle degli account e i loro file _febe.jsonl. Nessun file viene spostato o cancellato.");
+ });
+
+ endpoints.MapGet("/api/settings/rebuild", (RebuildJob job, IClock clock) =>
+ ApiHttp.Json(Rebuild(job.State, clock), FebeJsonContext.Default.RebuildStatusDto));
+
+ // ------------------------------------------------------------------------------------------ Informazioni
+ endpoints.MapGet("/api/about", (HttpContext context, IServiceProvider services) =>
+ {
+ var d = Deps.From(services);
+ var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
+ return ApiHttp.Json(
+ new AboutDto(d.Options.Version, caps.Edition == "desktop" ? "Windows" : "Docker", d.Library.Data.Root, d.Library.Layout.Root, GuideUrl, RepositoryUrl),
+ FebeJsonContext.Default.AboutDto);
+ });
+ }
+
+ // ---------------------------------------------------------------------------------------------- Generali
+
+ public static async Task GeneralAsync(HttpContext context, Deps d, CancellationToken ct)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ ArgumentNullException.ThrowIfNull(d);
+ var settings = await LibrarySettings.LoadAsync(d.Storage.Settings, d.Library.Layout.Root, ct).ConfigureAwait(false);
+ var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock);
+ var sample = await SampleAccountAsync(d.Storage, ct).ConfigureAwait(false);
+ var library = d.Library.Layout.Root;
+ var data = d.Library.Data.Root;
+ var (used, measuring) = d.Sizes.Get(data);
+ bool? autostart = caps.Autostart ? await d.Shell.GetAutostartAsync(ct).ConfigureAwait(false) : null;
+ var tray = await d.Storage.Settings.GetBoolAsync(DesktopSettingKeys.KeepInTray, true, ct).ConfigureAwait(false);
+ var dataChange = d.Services.GetService(typeof(IDataFolderChange)) as IDataFolderChange;
+ return new GeneralSettingsDto(
+ new FolderInfoDto(library, FolderSizes.FreeBytes(library), null, false),
+ new FolderInfoDto(data, FolderSizes.FreeBytes(data), used, measuring),
+ caps.FoldersReadOnly,
+ caps.PickFolder,
+ !caps.FoldersReadOnly && (dataChange?.CanChange ?? false),
+ settings.Naming.General.Text,
+ settings.Naming.Highlight.Text,
+ NamingScheme.DefaultGeneral,
+ NamingScheme.DefaultHighlight,
+ NamingScheme.Placeholders,
+ settings.SetFileTimeToPublication,
+ Preview(NamingPreview.Build(settings.Naming.General.Text, settings.Naming.Highlight.Text, d.Clock.LocalZone, sample)),
+ autostart,
+ tray,
+ "it");
+ }
+
+ public static NamingPreviewDto Preview(NamingPreview preview)
+ {
+ ArgumentNullException.ThrowIfNull(preview);
+ return new NamingPreviewDto(
+ preview.AccountFolder,
+ [.. preview.Folders.Select(f => new NamingPreviewFolderDto(f.Path, [.. f.Files.Select(x => new NamingPreviewFileDto(x.Name, ApiMapping.Media(x.Kind)))]))],
+ preview.Errors,
+ preview.Warnings);
+ }
+
+ /// The account whose name the preview shows: the first one followed (or any), as in mockup 08.
+ private static async Task SampleAccountAsync(IFebeStorage storage, CancellationToken ct)
+ {
+ 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()
+ ?? accounts.OrderBy(a => a.Id).Select(a => a.Username).FirstOrDefault()
+ ?? "nome.utente";
+ }
+
+ private static NamingScheme Validate(NamingSchemeValidation validation, string name)
+ {
+ if (validation.IsValid)
+ {
+ return validation.Scheme!;
+ }
+
+ throw new BadRequestException(string.Join(" ", validation.Errors.Select(e => $"{name}: {e}")));
+ }
+
+ ///
+ /// A new library folder (desktop). Accounts whose files are in their default folder of the old library keep it
+ /// (their folder becomes an absolute path), so nothing has to move; new accounts go in the new folder.
+ ///
+ private static async Task ChangeLibraryRootAsync(Deps d, string requested, CancellationToken ct)
+ {
+ if (!Path.IsPathFullyQualified(requested))
+ {
+ throw new BadRequestException("Serve il percorso completo di una cartella.");
+ }
+
+ var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(requested));
+ var data = d.Library.Data.Root;
+ if (IsSameOrInside(root, data) || IsSameOrInside(data, root))
+ {
+ throw new BadRequestException("La libreria non può stare dentro la cartella dei dati, né contenerla.");
+ }
+
+ try
+ {
+ Directory.CreateDirectory(root);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
+ {
+ throw new BadRequestException($"Febe non riesce a usare questa cartella ({ex.Message}). Scegline un'altra, su un disco collegato e scrivibile.");
+ }
+
+ var old = d.Library.Layout;
+ foreach (var account in await d.Storage.Accounts.ListAsync(ct).ConfigureAwait(false))
+ {
+ if (account.Folder is { } folder && Path.IsPathFullyQualified(folder))
+ {
+ continue;
+ }
+
+ var current = old.AccountFolder(account);
+ if (Directory.Exists(current))
+ {
+ await d.Storage.Accounts.UpdateAsync(account with { Folder = current }, ct).ConfigureAwait(false);
+ }
+ }
+
+ d.Library.UseLibraryRoot(root);
+ return root;
+ }
+
+ // ---------------------------------------------------------------------------------------------- Limiti
+
+ public static LimitsDto Limits(EngineSettings settings)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ var rules = new LimitRulesDto(
+ (int)CautionProfile.Limits.MinPause.TotalMinutes,
+ (int)CautionProfile.Limits.MaxSession.TotalMinutes,
+ (int)CautionProfile.Limits.MaxWindow.TotalHours,
+ (int)CautionProfileRules.MaxJitter.TotalMinutes,
+ CautionProfile.Limits.MaxDataPerDayBytes / GiB,
+ CautionProfile.Fast.BackfillPostsPerAccountPerDay * 2,
+ CautionProfileRules.MaxRampUpDays);
+ return new LimitsDto(
+ ProfileName(settings.ProfileKind),
+ [Values(CautionProfile.Prudent), Values(CautionProfile.Balanced), Values(CautionProfile.Fast)],
+ Values(settings.EffectiveProfile),
+ Pace(settings.Pace),
+ settings.GradualStart,
+ [.. settings.ActiveDays.Select(d => (int)d).Order()],
+ rules,
+ ["1 ora", "6 ore", "24 ore"]);
+ }
+
+ public static ProfileValuesDto Values(CautionProfile profile)
+ {
+ ArgumentNullException.ThrowIfNull(profile);
+ var budgets = SnapshotParts.All.Where(k => k != ActionKind.DataDownload).Select(k =>
+ {
+ var budget = profile.Budgets.TryGetValue(k, out var b) ? b : CautionProfile.Prudent.Budgets[k];
+ var max = CautionProfile.Limits.MaxBudget(k);
+ return new BudgetValueDto(k.ToString(), ItalianText.CategoryLabel(k), budget.PerHour, budget.PerDay, max.PerHour, max.PerDay);
+ }).ToList();
+ return new ProfileValuesDto(
+ ProfileName(profile.Kind),
+ ItalianText.Profile(profile.Kind),
+ profile.WindowStart.ToString("HH:mm", CultureInfo.InvariantCulture),
+ profile.WindowEnd.ToString("HH:mm", CultureInfo.InvariantCulture),
+ (int)Math.Round(profile.WindowJitter.TotalMinutes),
+ (int)Math.Round(profile.SessionMin.TotalMinutes),
+ (int)Math.Round(profile.SessionMax.TotalMinutes),
+ (int)Math.Round(profile.PauseMin.TotalMinutes),
+ (int)Math.Round(profile.PauseMax.TotalMinutes),
+ budgets,
+ Math.Round(profile.DataPerDayBytes / GiB, 2),
+ profile.BackfillPostsPerAccountPerDay,
+ profile.RampUpDays);
+ }
+
+ private static EngineSettings ToSettings(LimitsRequest body, EngineSettings stored)
+ {
+ var kind = ParseProfile(body.Profile) ?? throw new BadRequestException("Profilo di prudenza sconosciuto.");
+ var pace = body.Pace?.ToLowerInvariant() switch
+ {
+ "slow" => GesturePace.Slow,
+ "natural" => GesturePace.Natural,
+ "brisk" => GesturePace.Brisk,
+ _ => throw new BadRequestException("Ritmo dei gesti sconosciuto: lento, naturale o svelto."),
+ };
+ var days = new HashSet();
+ foreach (var day in body.ActiveDays ?? [])
+ {
+ if (day is < 0 or > 6)
+ {
+ throw new BadRequestException("Giorno della settimana non valido.");
+ }
+
+ days.Add((DayOfWeek)day);
+ }
+
+ if (days.Count == 0)
+ {
+ throw new BadRequestException("Serve almeno un giorno attivo.");
+ }
+
+ var custom = stored.Custom;
+ if (kind == CautionProfileKind.Custom)
+ {
+ custom = FromValues(body.Values ?? throw new BadRequestException("Mancano i valori del profilo «Su misura»."));
+ }
+
+ return new EngineSettings { ProfileKind = kind, Custom = custom, Pace = pace, GradualStart = body.GradualStart, ActiveDays = days };
+ }
+
+ private static CautionProfile FromValues(ProfileValuesDto v)
+ {
+ var budgets = new Dictionary();
+ foreach (var budget in v.Budgets ?? [])
+ {
+ if (!Enum.TryParse(budget.Kind, ignoreCase: false, out var kind) || kind == ActionKind.DataDownload)
+ {
+ throw new BadRequestException("Tetto di una categoria sconosciuta.");
+ }
+
+ budgets[kind] = new Budget(budget.PerHour, budget.PerDay);
+ }
+
+ foreach (var kind in SnapshotParts.All.Where(k => k != ActionKind.DataDownload && !budgets.ContainsKey(k)))
+ {
+ throw new BadRequestException($"Manca il tetto delle {ItalianText.Category(kind)}.");
+ }
+
+ if (double.IsNaN(v.DataPerDayGb) || v.DataPerDayGb < 0 || v.DataPerDayGb > 1_000)
+ {
+ throw new BadRequestException("I dati scaricati al giorno sono un numero di GB.");
+ }
+
+ return new CautionProfile
+ {
+ Kind = CautionProfileKind.Custom,
+ WindowStart = ParseTime(v.WindowStart, "L'inizio della fascia"),
+ WindowEnd = ParseTime(v.WindowEnd, "La fine della fascia"),
+ WindowJitter = TimeSpan.FromMinutes(v.JitterMinutes),
+ SessionMin = TimeSpan.FromMinutes(v.SessionMinMinutes),
+ SessionMax = TimeSpan.FromMinutes(v.SessionMaxMinutes),
+ PauseMin = TimeSpan.FromMinutes(v.PauseMinMinutes),
+ PauseMax = TimeSpan.FromMinutes(v.PauseMaxMinutes),
+ Budgets = budgets,
+ DataPerDayBytes = (long)Math.Round(v.DataPerDayGb * GiB),
+ BackfillPostsPerAccountPerDay = v.BackfillPerAccount,
+ RampUpDays = v.RampUpDays,
+ };
+ }
+
+ private static TimeOnly ParseTime(string? text, string what)
+ {
+ var value = text?.Trim().Replace('.', ':');
+ if (value == "24:00")
+ {
+ return new TimeOnly(0, 0);
+ }
+
+ return TimeOnly.TryParseExact(value, ["H:mm", "HH:mm"], CultureInfo.InvariantCulture, DateTimeStyles.None, out var time)
+ ? time
+ : throw new BadRequestException($"{what} va scritto come ora e minuti, per esempio 07:30.");
+ }
+
+ public static string ProfileName(CautionProfileKind kind) => kind switch
+ {
+ CautionProfileKind.Prudent => "prudent",
+ CautionProfileKind.Balanced => "balanced",
+ CautionProfileKind.Fast => "fast",
+ _ => "custom",
+ };
+
+ public static CautionProfileKind? ParseProfile(string? text) => text?.ToLowerInvariant() switch
+ {
+ "prudent" => CautionProfileKind.Prudent,
+ "balanced" => CautionProfileKind.Balanced,
+ "fast" => CautionProfileKind.Fast,
+ "custom" => CautionProfileKind.Custom,
+ _ => null,
+ };
+
+ public static string Pace(GesturePace pace) => pace switch
+ {
+ GesturePace.Slow => "slow",
+ GesturePace.Brisk => "brisk",
+ _ => "natural",
+ };
+
+ // ---------------------------------------------------------------------------------------------- Notifiche
+
+ private static async Task NotificationsAsync(HttpContext context, Deps d, CancellationToken ct)
+ {
+ var settings = await AlertSettingsStore.LoadAsync(d.Storage.Settings, ct).ConfigureAwait(false);
+ var e = settings.Events;
+ var sender = d.Services.GetService(typeof(IAlertTestSender));
+ return new NotificationSettingsDto(
+ new AlertEventsDto(e.Verification, e.Disconnection, e.Throttle, e.BackfillDone, e.DiskLow, e.UnknownFormat),
+ settings.WindowsNotifications,
+ SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, d.Clock).Notifications,
+ settings.TelegramChatId,
+ !string.IsNullOrWhiteSpace(settings.TelegramToken),
+ sender is not null and not TelegramNotAvailableYet);
+ }
+
+ // ---------------------------------------------------------------------------------------------- Dati
+
+ public static DataSettingsDto Data(Deps d)
+ {
+ ArgumentNullException.ThrowIfNull(d);
+ var data = d.Library.Data;
+ var (used, measuring) = d.Sizes.Get(data.Root);
+ var now = d.Clock.Now;
+ var zone = d.Clock.LocalZone;
+ var backups = new DailyBackup(d.Storage.Maintenance, d.Clock, data.Backups).List()
+ .Select(b => new BackupDto(
+ ApiMapping.Day(b.Day),
+ Path.GetFileName(b.Path),
+ b.Bytes,
+ ApiMapping.Local(new DateTimeOffset(File.GetLastWriteTimeUtc(b.Path), TimeSpan.Zero), now, zone)))
+ .ToList();
+ long? databaseBytes = null;
+ var database = d.Storage.Maintenance.DatabasePath;
+ try
+ {
+ databaseBytes = new FileInfo(database).Length + (File.Exists(database + "-wal") ? new FileInfo(database + "-wal").Length : 0);
+ }
+ catch (IOException)
+ {
+ // size unknown
+ }
+
+ return new DataSettingsDto(
+ new FolderInfoDto(data.Root, FolderSizes.FreeBytes(data.Root), used, measuring),
+ database,
+ databaseBytes,
+ data.Backups,
+ backups,
+ DailyBackup.DefaultKeepDays,
+ Rebuild(d.Rebuild.State, d.Clock));
+ }
+
+ public static RebuildStatusDto Rebuild(RebuildState state, IClock clock)
+ {
+ ArgumentNullException.ThrowIfNull(state);
+ ArgumentNullException.ThrowIfNull(clock);
+ var lines = new List();
+ if (state.Report is { } r)
+ {
+ lines.Add($"Cartelle di account lette: {ItalianText.Number(r.AccountFolders)}.");
+ lines.Add($"Account ritrovati: {ItalianText.Number(r.AccountsMatched)}; ricreati: {ItalianText.Number(r.AccountsCreated)}"
+ + (r.AccountsCreated > 0 ? " (sono «In pausa»: riattivali dalla pagina Account)." : "."));
+ lines.Add($"Elementi aggiunti al database: {ItalianText.Number(r.EntriesCreated)}; già presenti: {ItalianText.Number(r.EntriesAlreadyPresent)}; eliminazioni rispettate: {ItalianText.Number(r.EntriesDeleted)}.");
+ lines.Add($"File controllati: {ItalianText.Number(r.FilesVerified)}; mancanti sul disco: {ItalianText.Number(r.FilesMissing)}; diversi da quanto annotato: {ItalianText.Number(r.HashMismatches)}; non annotati nel giornale: {ItalianText.Number(r.UntrackedFiles)}.");
+ if (r.InvalidLines > 0)
+ {
+ lines.Add($"Righe illeggibili nei file _febe.jsonl: {ItalianText.Number(r.InvalidLines)}.");
+ }
+
+ if (r.FoldersWithoutJournal.Count > 0)
+ {
+ lines.Add($"Cartelle senza _febe.jsonl, non lette: {string.Join(", ", r.FoldersWithoutJournal.Take(20))}{(r.FoldersWithoutJournal.Count > 20 ? "…" : string.Empty)}. Per portarle in libreria usa Importa.");
+ }
+
+ lines.AddRange(r.Notes);
+ }
+
+ return new RebuildStatusDto(
+ state.Running,
+ state.Folder,
+ state.FoldersDone,
+ state.FoldersTotal,
+ state.FilesChecked,
+ lines,
+ state.Error is null ? null : $"La ricostruzione si è fermata: {state.Error}. Nessun file è stato toccato; puoi riprovare.",
+ state.FinishedAt is { } at ? ApiMapping.Local(at, clock.Now, clock.LocalZone) : null);
+ }
+
+ // ---------------------------------------------------------------------------------------------- helpers
+
+ private static bool SamePath(string a, string b) =>
+ string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(a)), Path.TrimEndingDirectorySeparator(Path.GetFullPath(b)), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
+
+ private static bool IsSameOrInside(string path, string folder)
+ {
+ var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
+ var p = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
+ var f = Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
+ return string.Equals(p, f, comparison) || p.StartsWith(f + Path.DirectorySeparatorChar, comparison);
+ }
+
+ /// The services the settings endpoints share.
+ public sealed record Deps(
+ IServiceProvider Services,
+ FebeWebOptions Options,
+ IFebeStorage Storage,
+ FebeLibrary Library,
+ IClock Clock,
+ INativeShell Shell,
+ IBrowserWindow Browser,
+ FolderSizes Sizes,
+ RebuildJob Rebuild,
+ ImportHub Import,
+ LibraryChanges Changes)
+ {
+ public static Deps From(IServiceProvider services)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+ T Get() where T : notnull => (T)(services.GetService(typeof(T)) ?? throw new InvalidOperationException(typeof(T).Name + " non è registrato."));
+ return new Deps(services, Get(), Get(), Get(), Get(), Get(), Get(), Get(), Get(), Get(), Get());
+ }
+ }
+}
diff --git a/src/Febe.Web/Api/SystemApi.cs b/src/Febe.Web/Api/SystemApi.cs
index 20ad6b8..4c1128a 100644
--- a/src/Febe.Web/Api/SystemApi.cs
+++ b/src/Febe.Web/Api/SystemApi.cs
@@ -2,12 +2,14 @@ using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
+using Febe.Web.Connection;
using Febe.Web.Demo;
using Febe.Web.Hosting;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
+using Microsoft.Extensions.DependencyInjection;
namespace Febe.Web.Api;
@@ -77,7 +79,8 @@ public static class SystemApi
options.Demo ? DemoRequest.SceneName(DemoRequest.Scene(context)) : null,
options.Demo ? DemoRequest.SceneNames : [],
clock.Now.ToUnixTimeMilliseconds(),
- ApiMapping.Day(LocalCalendar.Today(clock.Now, clock.LocalZone)));
+ ApiMapping.Day(LocalCalendar.Today(clock.Now, clock.LocalZone)),
+ context.RequestServices.GetService()?.Current ?? []);
}
/// The sprite: each Lucide file's drawing inside a symbol; stroke and fill come from the CSS of svg.ic.
diff --git a/src/Febe.Web/Connection/UnavailableConnectionService.cs b/src/Febe.Web/Connection/UnavailableConnectionService.cs
new file mode 100644
index 0000000..d6e1da0
--- /dev/null
+++ b/src/Febe.Web/Connection/UnavailableConnectionService.cs
@@ -0,0 +1,23 @@
+using Febe.Web.Api;
+
+namespace Febe.Web.Connection;
+
+///
+/// The default when the composition registers none: «browser non disponibile». The
+/// pages say so and offer nothing that would pretend to work.
+///
+public sealed class UnavailableConnectionService : IConnectionService
+{
+ public const string Message = "Il browser di Febe non è disponibile: il programma non lo ha avviato. Controlla il registro e riavvia Febe; se il problema resta, guarda la pagina dei problemi comuni nella guida.";
+
+ public Task GetStatusAsync(CancellationToken ct) =>
+ Task.FromResult(new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null));
+
+ public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => throw new BadRequestException(Message);
+
+ public Task FinishAsync(CancellationToken ct) => Task.FromResult(new FinishResult(false, Message));
+
+ public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
+
+ public Task DisconnectAsync(CancellationToken ct) => throw new BadRequestException(Message);
+}
diff --git a/src/Febe.Web/Demo/DemoEngine.cs b/src/Febe.Web/Demo/DemoEngine.cs
index 461fa1d..1e53c4d 100644
--- a/src/Febe.Web/Demo/DemoEngine.cs
+++ b/src/Febe.Web/Demo/DemoEngine.cs
@@ -23,6 +23,13 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
public DemoScene CurrentScene => DemoRequest.Scene(accessor.HttpContext);
+ /// When the stop of the scene «fermo» happened: just before the end of the last session of the day.
+ public DateTimeOffset StopInstant(DateTimeOffset now)
+ {
+ var sessions = world.Today.Where(s => s.End <= now).ToList();
+ return sessions.Count > 0 ? sessions[^1].End - TimeSpan.FromSeconds(40) : now - TimeSpan.FromMinutes(25);
+ }
+
public async Task GetSnapshotAsync(CancellationToken ct = default)
{
var scene = CurrentScene;
@@ -31,8 +38,8 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
var day = LocalCalendar.Today(now, zone);
var (dayStart, dayEnd) = LocalCalendar.DayBounds(day, zone);
var inWindow = now >= world.WindowStart && now < world.WindowEnd;
- var sessions = scene == DemoScene.Disconnected ? [] : world.Today.Where(s => s.End <= now).ToList();
- var stopAt = sessions.Count > 0 ? sessions[^1].End - TimeSpan.FromSeconds(40) : now - TimeSpan.FromMinutes(25);
+ var sessions = scene is DemoScene.Disconnected or DemoScene.Error ? [] : world.Today.Where(s => s.End <= now).ToList();
+ var stopAt = StopInstant(now);
var current = scene == DemoScene.Session
? new DemoSession(now - TimeSpan.FromMinutes(2.5), now, 2, 6, 0, 18_000_000, 2)
: null;
@@ -68,6 +75,12 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
$"Ho fermato tutto {ItalianText.At(stopAt, zone)} e non riparto da solo. Apri il browser, completa la verifica a mano, poi premi «Riprendi».",
true);
break;
+ case DemoScene.Error:
+ mode = EngineMode.Off;
+ headline = "Motore spento";
+ details = ["Il motore non parte finché il problema di configurazione non è risolto."];
+ sidebar = "Problema di configurazione";
+ break;
case DemoScene.Disconnected:
mode = EngineMode.NotConnected;
headline = "Non collegato";
@@ -145,7 +158,7 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
var all = current is null ? sessions : [.. sessions, current];
var minutes = all.Sum(s => (s.End - s.Start).TotalMinutes);
- var newEntries = scene == DemoScene.Disconnected ? 0 : world.DiscoveredToday + (current?.NewEntries ?? 0);
+ var newEntries = scene is DemoScene.Disconnected or DemoScene.Error ? 0 : world.DiscoveredToday + (current?.NewEntries ?? 0);
var summary = string.Join(", ", new[]
{
ItalianText.Count(all.Count, "sessione", "sessioni"),
@@ -153,12 +166,12 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
ItalianText.Count(newEntries, "contenuto nuovo", "contenuti nuovi"),
"nessun rallentamento",
});
- var strip = new DayStrip(day, dayStart, dayEnd, now, scene == DemoScene.Disconnected ? "Nessuna sessione oggi: Febe non è collegato" : summary, [.. spans.OrderBy(s => s.Start).ThenBy(s => s.Kind)]);
+ var strip = new DayStrip(day, dayStart, dayEnd, now, scene is DemoScene.Disconnected or DemoScene.Error ? "Nessuna sessione oggi: Febe non è collegato" : summary, [.. spans.OrderBy(s => s.Start).ThenBy(s => s.Kind)]);
// Budgets.
var lastHour = all.Where(s => s.End > now - TimeSpan.FromHours(1)).ToList();
var stopped = scene == DemoScene.Stopped ? "Fermo " + ItalianText.Since(stopAt, zone) : null;
- var disconnected = scene == DemoScene.Disconnected;
+ var disconnected = scene is DemoScene.Disconnected or DemoScene.Error;
long Used(ActionKind kind) => disconnected ? 0 : kind switch
{
ActionKind.Home => all.Count,
@@ -229,7 +242,7 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
{
case DemoScene.Stopped:
return new CheckNowResult(CheckNowStatus.Refused, "Febe è fermo per una verifica: completala nel browser e premi «Riprendi». Il controllo non parte.");
- case DemoScene.Disconnected:
+ case DemoScene.Disconnected or DemoScene.Error:
return new CheckNowResult(CheckNowStatus.Refused, "Febe non è collegato a Instagram: collegalo prima di chiedere un controllo.");
}
@@ -278,11 +291,11 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
private IReadOnlyList Queue(DemoScene scene, IReadOnlyList accounts, DateTimeOffset now, TimeZoneInfo zone, DateTimeOffset? next)
{
- var suspended = scene is DemoScene.Stopped or DemoScene.Disconnected;
+ var suspended = scene is DemoScene.Stopped or DemoScene.Disconnected or DemoScene.Error;
var items = new List();
var id = 1L;
string When(DateTimeOffset? at) => suspended ? "Sospeso" : at is { } a ? (scene == DemoScene.Session && a <= now + TimeSpan.FromMinutes(4) ? "In questa sessione" : ItalianText.Around(a, now, zone)) : "Sospeso";
- if (scene == DemoScene.Disconnected)
+ if (scene is DemoScene.Disconnected or DemoScene.Error)
{
return items;
}
@@ -307,13 +320,14 @@ public sealed class DemoEngine(IClock clock, DemoWorld world, IFebeStorage stora
items.Add(new QueueItem(id++, account.State == AccountState.Backfilling ? EngineTaskKind.Backfill : EngineTaskKind.ProfileCheck, account.Id, ItalianText.Handle(account.Username), detail, suspended ? null : at, When(at), false, suspended));
}
- return items;
+ // In time order, as «In coda» reads (mockup 06); suspended items keep their order.
+ return [.. items.OrderBy(i => i.Around ?? DateTimeOffset.MaxValue)];
}
private IReadOnlyList Recent(DemoScene scene, DateTimeOffset now, TimeZoneInfo zone, string marta, DateTimeOffset stopAt)
{
var list = new List();
- if (scene == DemoScene.Disconnected)
+ if (scene is DemoScene.Disconnected or DemoScene.Error)
{
return list;
}
diff --git a/src/Febe.Web/Demo/DemoHost.cs b/src/Febe.Web/Demo/DemoHost.cs
index 951934e..acecd6b 100644
--- a/src/Febe.Web/Demo/DemoHost.cs
+++ b/src/Febe.Web/Demo/DemoHost.cs
@@ -1,8 +1,10 @@
using Febe.Core.Abstractions;
using Febe.Core.Engine;
+using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Data;
+using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
@@ -27,11 +29,13 @@ public sealed record DemoOptions(int Port = FebeListen.DefaultPort, TimeZoneInfo
public sealed class DemoHost : IAsyncDisposable
{
private readonly FebeDatabase _database;
+ private readonly ImportService _import;
- private DemoHost(string root, FebeDatabase database, WebApplication app, DemoWorld world, Uri address)
+ private DemoHost(string root, FebeDatabase database, ImportService import, WebApplication app, DemoWorld world, Uri address)
{
Root = root;
_database = database;
+ _import = import;
App = app;
World = world;
Address = address;
@@ -55,6 +59,7 @@ public sealed class DemoHost : IAsyncDisposable
var root = Path.Combine(options.Root ?? Path.GetTempPath(), "febe-dimostrazione-" + Guid.NewGuid().ToString("N")[..10]);
Directory.CreateDirectory(root);
FebeDatabase? database = null;
+ ImportService? import = null;
try
{
var clock = new SystemClock(options.Zone ?? TimeZoneInfo.Local);
@@ -65,6 +70,8 @@ public sealed class DemoHost : IAsyncDisposable
database = await FebeDatabase.OpenAsync(data.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);
+ import = await DemoImport.PrepareAsync(root, database, world, layout, data, clock, ct).ConfigureAwait(false);
+ var demoImport = import;
var library = new FebeLibrary(database, data, layout, clock);
var web = new FebeWebOptions
{
@@ -88,12 +95,23 @@ public sealed class DemoHost : IAsyncDisposable
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton(sp => sp.GetRequiredService());
services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton(demoImport);
});
await app.StartAsync(ct).ConfigureAwait(false);
- return new DemoHost(root, database, app, world, FebeWebHost.BoundAddress(app));
+ return new DemoHost(root, database, import, app, world, FebeWebHost.BoundAddress(app));
}
catch
{
+ if (import is not null)
+ {
+ await import.DisposeAsync().ConfigureAwait(false);
+ }
+
if (database is not null)
{
await database.DisposeAsync().ConfigureAwait(false);
@@ -113,6 +131,7 @@ public sealed class DemoHost : IAsyncDisposable
finally
{
await App.DisposeAsync().ConfigureAwait(false);
+ await _import.DisposeAsync().ConfigureAwait(false);
await _database.DisposeAsync().ConfigureAwait(false);
TryDelete(Root);
}
diff --git a/src/Febe.Web/Demo/DemoImport.cs b/src/Febe.Web/Demo/DemoImport.cs
new file mode 100644
index 0000000..d6f69cb
--- /dev/null
+++ b/src/Febe.Web/Demo/DemoImport.cs
@@ -0,0 +1,163 @@
+using System.Globalization;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Import;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+
+namespace Febe.Web.Demo;
+
+///
+/// The import of the demo (spec §10.6: «/importa?passo=3»): a source folder generated in the temporary folder, with
+/// account folders whose files are partly already in the library, partly smaller or larger copies of library photos
+/// (probable duplicates), partly new, plus a folder without an account name and a few files that are neither photos
+/// nor videos. The analysis runs at start, so the review (step 3) is ready. Nothing outside the temporary folder.
+///
+internal static class DemoImport
+{
+ /// Name of the source folder, under the demo's «importa» root.
+ public const string SourceName = "Backup del vecchio disco";
+
+ public static async Task PrepareAsync(string root, IFebeStorage storage, DemoWorld world, LibraryLayout layout, DataFolderLayout data, IClock clock, CancellationToken ct)
+ {
+ var importRoot = Path.Combine(root, "importa");
+ var source = Path.Combine(importRoot, SourceName);
+ Directory.CreateDirectory(source);
+ await WriteSourceAsync(source, storage, world, clock, ct).ConfigureAwait(false);
+
+ var service = new ImportService(new ImportEnvironment
+ {
+ Storage = storage,
+ Layout = layout,
+ Naming = LibraryNaming.Default,
+ Journal = new AccountJournal(clock),
+ Clock = clock,
+ Thumbnails = new ThumbnailStore(data.Thumbnails),
+ Sources = new ImportSourceOptions { Root = importRoot, RootIsReadOnly = false },
+ DataFolder = data.Root,
+ Parallelism = 2,
+ });
+ await service.RecoverAsync(ct).ConfigureAwait(false);
+ var run = await service.StartAsync(SourceName, null, ct).ConfigureAwait(false);
+ await service.WaitAsync(run.Id, ct).ConfigureAwait(false);
+ return service;
+ }
+
+ private static async Task WriteSourceAsync(string source, IFebeStorage storage, DemoWorld world, IClock clock, CancellationToken ct)
+ {
+ var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
+ var zone = clock.LocalZone;
+ var random = new Random(909);
+ var jobs = new List<(string Path, Func Make)>();
+
+ async Task FromLibraryAsync(string username, string folder, int identical, double[] variants)
+ {
+ var account = accounts.FirstOrDefault(a => a.Username == username);
+ if (account is null)
+ {
+ return;
+ }
+
+ var entries = await storage.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 300 }, ct).ConfigureAwait(false);
+ var used = new HashSet(StringComparer.Ordinal);
+ var picked = new List<(Entry Entry, string File)>();
+ foreach (var entry in entries.Skip(30))
+ {
+ var media = await storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
+ if (media.FirstOrDefault() is { Kind: MediaKind.Photo, Sha256: { } sha }
+ && world.Pictures.TryGetValue(sha, out var file) && used.Add(sha))
+ {
+ picked.Add((entry, file));
+ }
+
+ if (picked.Count >= identical + variants.Length)
+ {
+ break;
+ }
+ }
+
+ for (var i = 0; i < picked.Count; i++)
+ {
+ var (entry, file) = picked[i];
+ var name = Path.Combine(folder, FileName(entry, zone) + ".jpg");
+ if (i < identical)
+ {
+ jobs.Add((name, () => File.ReadAllBytes(file)));
+ }
+ else
+ {
+ var scale = variants[i - identical];
+ jobs.Add((name, () => DemoDuplicates.Variant(File.ReadAllBytes(file), scale, scale > 1 ? 90 : 70)?.Bytes));
+ }
+ }
+ }
+
+ void New(string folder, int count, DemoSubject[] subjects, int year, PictureShape shape = PictureShape.Portrait)
+ {
+ for (var i = 0; i < count; i++)
+ {
+ var subject = subjects[i % subjects.Length];
+ var seed = random.Next(1000, 900_000);
+ var (width, height) = DemoPictures.Size(i % 3 == 2 ? PictureShape.Square : shape);
+ var day = new DateTime(year, 1 + random.Next(12), 1 + random.Next(28), 8 + random.Next(13), random.Next(60), random.Next(60), DateTimeKind.Unspecified);
+ var name = Path.Combine(folder, "IMG_" + day.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture) + ".jpg");
+ jobs.Add((name, () => DemoImages.Render(subject, seed, width, height)));
+ }
+ }
+
+ var marta = Path.Combine(source, "marta.demo");
+ var luca = Path.Combine(source, "luca.viaggi.demo");
+ var old = Path.Combine(source, "vecchio.profilo.demo");
+ var friends = Path.Combine(source, "amici.del.liceo.demo");
+ var loose = Path.Combine(source, "Foto sparse");
+ foreach (var folder in new[] { marta, luca, old, friends, loose, Path.Combine(friends, "copie") })
+ {
+ Directory.CreateDirectory(folder);
+ }
+
+ await FromLibraryAsync("marta.demo", marta, 5, [1.25, 0.7]).ConfigureAwait(false);
+ await FromLibraryAsync("luca.viaggi.demo", luca, 3, [0.75]).ConfigureAwait(false);
+ New(marta, 6, [DemoSubject.Flowers, DemoSubject.Food, DemoSubject.Portrait, DemoSubject.Sunset], 2024);
+ New(luca, 5, [DemoSubject.Mountains, DemoSubject.Sea, DemoSubject.Road], 2023);
+ New(old, 9, [DemoSubject.Hills, DemoSubject.Houses, DemoSubject.Sea, DemoSubject.Portrait], 2018);
+ New(friends, 7, [DemoSubject.Concert, DemoSubject.Bokeh, DemoSubject.Portrait, DemoSubject.CityNight], 2012);
+ New(loose, 5, [DemoSubject.Leaves, DemoSubject.Room, DemoSubject.Food], 2021, PictureShape.Landscape);
+
+ var results = new byte[]?[jobs.Count];
+ Parallel.For(0, jobs.Count, new ParallelOptions { MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount, 1, 4) }, i => results[i] = jobs[i].Make());
+ for (var i = 0; i < jobs.Count; i++)
+ {
+ if (results[i] is { } bytes)
+ {
+ var path = jobs[i].Path;
+ for (var n = 2; File.Exists(path); n++)
+ {
+ path = Path.Combine(Path.GetDirectoryName(jobs[i].Path)!, $"{Path.GetFileNameWithoutExtension(jobs[i].Path)} ({n}).jpg");
+ }
+
+ await File.WriteAllBytesAsync(path, bytes, ct).ConfigureAwait(false);
+ }
+ }
+
+ // An identical copy inside the source, and files that are neither photos nor videos.
+ var firstFriend = Directory.EnumerateFiles(friends, "*.jpg").Order(StringComparer.Ordinal).FirstOrDefault();
+ if (firstFriend is not null)
+ {
+ File.Copy(firstFriend, Path.Combine(friends, "copie", Path.GetFileName(firstFriend)), overwrite: false);
+ }
+
+ await File.WriteAllTextAsync(Path.Combine(loose, "note del viaggio.txt"), "Appunti: treno delle 7:40, poi a piedi fino al lago.\n", ct).ConfigureAwait(false);
+ await File.WriteAllBytesAsync(Path.Combine(loose, "ricevuta.pdf"), "%PDF-1.4\n% documento dimostrativo\n"u8.ToArray(), ct).ConfigureAwait(false);
+ await File.WriteAllTextAsync(Path.Combine(old, "leggimi.txt"), "Foto del vecchio profilo, salvate a mano.\n", ct).ConfigureAwait(false);
+ }
+
+ ///
+ /// «2025-10-13_18-22-05_DBx3kQ2_1», the name Febe itself gives (default scheme): date and code are read from it
+ /// (spec §9.2), so the review can say how many entries it recognized.
+ ///
+ private static string FileName(Entry entry, TimeZoneInfo zone)
+ {
+ var local = LocalCalendar.ToLocal(entry.PublishedAt, zone).ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture);
+ return string.IsNullOrEmpty(entry.Code) ? local : $"{local}_{entry.Code}_1";
+ }
+}
diff --git a/src/Febe.Web/Demo/DemoPart2.cs b/src/Febe.Web/Demo/DemoPart2.cs
new file mode 100644
index 0000000..b63e22c
--- /dev/null
+++ b/src/Febe.Web/Demo/DemoPart2.cs
@@ -0,0 +1,287 @@
+using System.Security.Cryptography;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Web.Api;
+using Febe.Web.Connection;
+using Febe.Web.Engine;
+using Febe.Web.Library;
+using Microsoft.AspNetCore.Http;
+using SkiaSharp;
+
+namespace Febe.Web.Demo;
+
+/// The scene «errore» simulates a missing password (spec §11): the interface shows only the problem page.
+public sealed class DemoConfigurationProblems(IHttpContextAccessor accessor) : IConfigurationProblems
+{
+ public static ConfigurationProblem MissingPassword { get; } = new(
+ "password-mancante",
+ "Manca la password dell'interfaccia",
+ "Febe non ha avviato il motore né il browser: senza password chiunque sulla rete di casa potrebbe aprire l'interfaccia e la vista remota del browser, con la tua sessione di Instagram.",
+ "Imposta la variabile FEBE_PASSWORD del contenitore (su Unraid: modifica il contenitore, campo «Password dell'interfaccia»), poi riavvialo. È la password che scriverai per entrare in Febe.");
+
+ public IReadOnlyList Current =>
+ DemoRequest.Scene(accessor.HttpContext) == DemoScene.Error ? [MissingPassword] : [];
+}
+
+///
+/// The link to Instagram in the demo, driven by the scene: «scollegato» is not connected (login page in the view),
+/// «fermo» needs a verification, the others are connected as @tuo.profilo. There is no browser: nothing is opened and
+/// «Ho finito» says so plainly.
+///
+public sealed class DemoConnectionService(IHttpContextAccessor accessor, DemoWorld world) : IConnectionService
+{
+ public const string LoginUrl = "https://www.instagram.com/accounts/login/";
+ public const string ChallengeUrl = "https://www.instagram.com/challenge/";
+
+ private DemoScene Scene => DemoRequest.Scene(accessor.HttpContext);
+
+ public Task GetStatusAsync(CancellationToken ct) => Task.FromResult(Scene switch
+ {
+ DemoScene.Disconnected => new ConnectionStatus(ConnectionState.NotConnected, null, null, false, LoginUrl),
+ DemoScene.Stopped => new ConnectionStatus(ConnectionState.VerificationRequired, world.MineUsername, "Il tuo profilo", false, ChallengeUrl),
+ DemoScene.Error => new ConnectionStatus(ConnectionState.BrowserUnavailable, null, null, false, null),
+ _ => new ConnectionStatus(ConnectionState.Connected, world.MineUsername, "Il tuo profilo", false, null),
+ });
+
+ public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct) => Task.CompletedTask;
+
+ public Task FinishAsync(CancellationToken ct) => Task.FromResult(Scene switch
+ {
+ DemoScene.Disconnected or DemoScene.Stopped or DemoScene.Error => new FinishResult(
+ false,
+ "Dimostrazione: qui non c'è un browser vero, quindi Febe non può controllare l'accesso. Nella versione vera verifica che la sessione esista e nasconde il browser."),
+ _ => new FinishResult(true, $"Sei collegato come @{world.MineUsername}."),
+ });
+
+ public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
+
+ public Task DisconnectAsync(CancellationToken ct) =>
+ throw new BadRequestException("Dimostrazione: Febe non si scollega davvero. Nella versione vera ferma il motore e cancella il profilo del browser con la sessione.");
+}
+
+/// A frame of the demo browser during the scene «sessione»: three demo stories on a dark page (never Instagram's page).
+public sealed class DemoBrowserPreview(IHttpContextAccessor accessor, DemoWorld world, IClock clock) : IBrowserPreview
+{
+ private readonly Lazy _frame = new(() => Compose(world));
+
+ public Task GetLatestAsync(CancellationToken ct)
+ {
+ if (DemoRequest.Scene(accessor.HttpContext) != DemoScene.Session || _frame.Value is not { } jpeg)
+ {
+ return Task.FromResult(null);
+ }
+
+ return Task.FromResult(new BrowserFrame(jpeg, "https://www.instagram.com/stories/marta.demo/", clock.Now - TimeSpan.FromSeconds(2)));
+ }
+
+ private static byte[]? Compose(DemoWorld world)
+ {
+ var files = world.StoryPictures.Where(File.Exists).Take(3).Select(File.ReadAllBytes).ToList();
+ if (files.Count == 0)
+ {
+ return null;
+ }
+
+ const int width = 640;
+ const int height = 360;
+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(bitmap))
+ {
+ canvas.Clear(new SKColor(0x1A, 0x1A, 0x1A));
+ var tall = height - 40f;
+ var wide = tall * 9 / 16;
+ var gap = 26f;
+ var left = (width - (3 * wide) - (2 * gap)) / 2;
+ using var dim = new SKPaint { Color = new SKColor(0, 0, 0, 110) };
+ for (var i = 0; i < files.Count; i++)
+ {
+ using var image = SKImage.FromEncodedData(files[i]);
+ if (image is null)
+ {
+ continue;
+ }
+
+ var scale = i == 1 ? 1f : 0.82f;
+ var w = wide * scale;
+ var h = tall * scale;
+ var x = left + (i * (wide + gap)) + ((wide - w) / 2);
+ var y = (height - h) / 2;
+ var rect = new SKRect(x, y, x + w, y + h);
+ canvas.DrawImage(image, rect, new SKSamplingOptions(SKCubicResampler.Mitchell));
+ if (i != 1)
+ {
+ canvas.DrawRect(rect, dim);
+ }
+ }
+ }
+
+ using var frame = SKImage.FromBitmap(bitmap);
+ using var encoded = frame.Encode(SKEncodedImageFormat.Jpeg, 80);
+ return encoded.ToArray();
+ }
+}
+
+/// The stops of the demo: an old throttle, and the verification of the scene «fermo».
+public sealed class DemoIncidentHistory(IHttpContextAccessor accessor, DemoEngine engine, IClock clock) : IIncidentHistory
+{
+ public Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct)
+ {
+ var scene = DemoRequest.Scene(accessor.HttpContext);
+ var now = clock.Now;
+ var list = new List();
+ if (scene is DemoScene.Disconnected or DemoScene.Error)
+ {
+ return Task.FromResult>(list);
+ }
+
+ if (scene == DemoScene.Stopped)
+ {
+ list.Add(new Incident
+ {
+ Id = 2,
+ At = engine.StopInstant(now),
+ Level = SignalLevel.Challenge,
+ Signal = "challenge-url",
+ Url = DemoConnectionService.ChallengeUrl,
+ Note = "Pagina di verifica aperta durante @giulia.corre.demo",
+ });
+ }
+
+ var throttle = LocalCalendar.StartOfDay(LocalCalendar.Today(now, clock.LocalZone).AddDays(-3), clock.LocalZone) + TimeSpan.FromHours(18.4);
+ list.Add(new Incident
+ {
+ Id = 1,
+ At = throttle,
+ Level = SignalLevel.Throttle,
+ Signal = "http-429",
+ Url = "https://www.instagram.com/",
+ StoppedUntil = throttle + TimeSpan.FromHours(1),
+ ResolvedAt = throttle + TimeSpan.FromHours(1),
+ Note = "Risposta «troppe richieste» durante il giro dei profili che segui",
+ });
+ return Task.FromResult>(list.Where(i => i.At >= from && i.At < to).OrderByDescending(i => i.At).ToList());
+ }
+}
+
+/// «Cambia…» of the Data folder in the demo (desktop look): records nothing.
+public sealed class DemoDataFolderChange(IHttpContextAccessor accessor) : IDataFolderChange
+{
+ public bool CanChange => DemoRequest.Edition(accessor.HttpContext) != FebeEdition.Docker;
+
+ public Task RequestChangeAsync(string newFolder, CancellationToken ct) =>
+ Task.FromResult("Dimostrazione: nella versione per Windows la nuova cartella dei dati varrebbe dal prossimo avvio di Febe. Qui non è cambiato nulla.");
+}
+
+///
+/// Probable duplicates after a download for the demo (spec §9.5): for a few accounts a recent photo becomes a smaller,
+/// recompressed copy of an older one, and the pair waits for Alberto in the review.
+///
+internal static class DemoDuplicates
+{
+ public static async Task> SeedAsync(IFebeStorage storage, ThumbnailStore thumbnails, string folder, DateTimeOffset now, CancellationToken ct)
+ {
+ var extra = new Dictionary(StringComparer.Ordinal);
+ var accounts = await storage.Accounts.ListAsync(ct).ConfigureAwait(false);
+ var scale = 0.8;
+ foreach (var username in new[] { "marta.demo", "luca.viaggi.demo", "giulia.corre.demo" })
+ {
+ var account = accounts.FirstOrDefault(a => a.Username == username);
+ if (account is null)
+ {
+ continue;
+ }
+
+ var posts = await storage.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 400 }, ct).ConfigureAwait(false);
+ var singles = new List<(Entry Entry, Media Media)>();
+ foreach (var entry in posts.Where(e => e.Provenance == Provenance.Downloaded))
+ {
+ var media = await storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
+ if (media.Count == 1 && media[0] is { Kind: MediaKind.Photo, Sha256: not null } photo)
+ {
+ singles.Add((entry, photo));
+ }
+
+ if (singles.Count >= 40)
+ {
+ break;
+ }
+ }
+
+ if (singles.Count < 10)
+ {
+ continue;
+ }
+
+ var candidate = singles[0];
+ var existing = singles.Skip(8).First(s => s.Media.Sha256 != candidate.Media.Sha256);
+ var source = Path.Combine(folder, existing.Media.Sha256 + ".jpg");
+ if (!File.Exists(source))
+ {
+ continue;
+ }
+
+ var variant = Variant(File.ReadAllBytes(source), scale, 68);
+ if (variant is null)
+ {
+ continue;
+ }
+
+ scale -= 0.12;
+ var sha = Convert.ToHexStringLower(SHA256.HashData(variant.Value.Bytes));
+ var path = Path.Combine(folder, sha + ".jpg");
+ await File.WriteAllBytesAsync(path, variant.Value.Bytes, ct).ConfigureAwait(false);
+ using (var stream = new MemoryStream(variant.Value.Bytes))
+ {
+ thumbnails.Create(sha, stream);
+ }
+
+ ulong? hash;
+ using (var stream = new MemoryStream(variant.Value.Bytes))
+ {
+ hash = PerceptualHash.Compute(stream);
+ }
+
+ extra[sha] = path;
+ await storage.Media.UpdateAsync(
+ candidate.Media with { Sha256 = sha, Width = variant.Value.Width, Height = variant.Value.Height, Bytes = variant.Value.Bytes.Length, PerceptualHash = hash },
+ ct).ConfigureAwait(false);
+ await storage.Duplicates.AddAsync(
+ new DuplicatePair
+ {
+ Origin = DuplicateOrigin.Download,
+ Reason = DuplicateReason.VisuallySimilar,
+ ExistingMediaId = existing.Media.Id,
+ CandidateMediaId = candidate.Media.Id,
+ Distance = hash is { } h && existing.Media.PerceptualHash is { } e ? PerceptualHash.Distance(h, e) : null,
+ CreatedAt = candidate.Entry.DownloadedAt ?? now,
+ },
+ ct).ConfigureAwait(false);
+ }
+
+ return extra;
+ }
+
+ /// The picture resized by and recompressed: the same photo saved again, smaller.
+ public static (byte[] Bytes, int Width, int Height)? Variant(byte[] jpeg, double scale, int quality)
+ {
+ using var image = SKImage.FromEncodedData(jpeg);
+ if (image is null)
+ {
+ return null;
+ }
+
+ var width = Math.Max(16, (int)Math.Round(image.Width * scale));
+ var height = Math.Max(16, (int)Math.Round(image.Height * scale));
+ using var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
+ using (var canvas = new SKCanvas(bitmap))
+ {
+ canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell));
+ }
+
+ using var result = SKImage.FromBitmap(bitmap);
+ using var encoded = result.Encode(SKEncodedImageFormat.Jpeg, quality);
+ return (encoded.ToArray(), width, height);
+ }
+}
diff --git a/src/Febe.Web/Demo/DemoRequest.cs b/src/Febe.Web/Demo/DemoRequest.cs
index 65616eb..41b4898 100644
--- a/src/Febe.Web/Demo/DemoRequest.cs
+++ b/src/Febe.Web/Demo/DemoRequest.cs
@@ -16,6 +16,9 @@ public enum DemoScene
/// «scollegato»: no Instagram session yet.
Disconnected,
+
+ /// «errore»: a configuration problem (missing password): the interface shows only the problem page.
+ Error,
}
///
@@ -33,7 +36,7 @@ public static class DemoRequest
private const string SceneItem = "febe.demo.scena";
private const string EditionItem = "febe.demo.veste";
- public static IReadOnlyList SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato"];
+ public static IReadOnlyList SceneNames { get; } = ["normale", "sessione", "fermo", "scollegato", "errore"];
public static DemoScene? ParseScene(string? text) => text?.Trim().ToLowerInvariant() switch
{
@@ -41,6 +44,7 @@ public static class DemoRequest
"sessione" => DemoScene.Session,
"fermo" => DemoScene.Stopped,
"scollegato" => DemoScene.Disconnected,
+ "errore" => DemoScene.Error,
_ => null,
};
@@ -49,6 +53,7 @@ public static class DemoRequest
DemoScene.Session => "sessione",
DemoScene.Stopped => "fermo",
DemoScene.Disconnected => "scollegato",
+ DemoScene.Error => "errore",
_ => "normale",
};
diff --git a/src/Febe.Web/Demo/DemoSeeder.cs b/src/Febe.Web/Demo/DemoSeeder.cs
index 2f23360..1875e82 100644
--- a/src/Febe.Web/Demo/DemoSeeder.cs
+++ b/src/Febe.Web/Demo/DemoSeeder.cs
@@ -59,6 +59,9 @@ public sealed class DemoWorld
public required long MineId { get; init; }
public required string MineUsername { get; init; }
+
+ /// Sample pictures in the proportions of a story (the browser preview of the demo).
+ public IReadOnlyList StoryPictures { get; init; } = [];
}
///
@@ -551,11 +554,13 @@ public static class DemoSeeder
.ToList();
var mine = accounts.First(a => a.Spec.Mine).Account;
+ var variants = await DemoDuplicates.SeedAsync(storage, thumbnails, pictures, now, ct).ConfigureAwait(false);
return new DemoWorld
{
SeededAt = now,
Zone = zone,
- Pictures = pool.Files,
+ Pictures = pool.Files.Concat(variants).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal),
+ StoryPictures = [.. pool.All.Where(p => p.Shape == PictureShape.Story).Select(p => p.Path)],
WindowStart = windowToday.Start,
WindowEnd = windowToday.End,
NextWindowStart = nextWindow,
@@ -840,6 +845,7 @@ public static class DemoSeeder
RelativePath = relative,
Bytes = isVideo ? random.Next(2_000_000, 38_000_000) : picture.Bytes,
Sha256 = picture.Sha256,
+ PerceptualHash = isVideo ? null : picture.PerceptualHash,
HasThumbnail = true,
DownloadedAt = entry.DownloadedAt,
});
@@ -938,7 +944,7 @@ public enum PictureShape
}
/// A sample picture on disk.
-public sealed record DemoPicture(DemoSubject Subject, PictureShape Shape, string Path, string Sha256, int Width, int Height, long Bytes);
+public sealed record DemoPicture(DemoSubject Subject, PictureShape Shape, string Path, string Sha256, int Width, int Height, long Bytes, ulong? PerceptualHash = null);
/// The shared sample pictures of the demo, with their thumbnails.
public sealed class DemoPictures
@@ -998,7 +1004,13 @@ public sealed class DemoPictures
thumbnails.Create(sha, stream);
}
- results[i] = new DemoPicture(subject, shape, path, sha, width, height, bytes.Length);
+ ulong? hash;
+ using (var stream = new MemoryStream(bytes))
+ {
+ hash = Febe.Core.Library.PerceptualHash.Compute(stream);
+ }
+
+ results[i] = new DemoPicture(subject, shape, path, sha, width, height, bytes.Length, hash);
});
return new DemoPictures(results);
}
diff --git a/src/Febe.Web/Engine/BrowserPreview.cs b/src/Febe.Web/Engine/BrowserPreview.cs
new file mode 100644
index 0000000..1280f62
--- /dev/null
+++ b/src/Febe.Web/Engine/BrowserPreview.cs
@@ -0,0 +1,24 @@
+namespace Febe.Web.Engine;
+
+/// A still frame of Febe's browser for the Attività page (mockup 06: one frame every few seconds, not a video).
+/// The frame, JPEG encoded.
+/// Address of the page, without query string.
+/// When the frame was taken.
+public sealed record BrowserFrame(byte[] Jpeg, string? Url, DateTimeOffset At);
+
+///
+/// The latest frame of Febe's browser, for the preview of the Attività page. Implemented by the composition over the
+/// browser host (Docker: the screencast of the remote view; Windows: the WebView2). Taking frames is never an action
+/// toward the site: it reads what the browser already shows.
+///
+public interface IBrowserPreview
+{
+ /// The latest frame, or null when there is none (no browser, blank rest page, no frame yet).
+ Task GetLatestAsync(CancellationToken ct);
+}
+
+/// No preview (default): the page shows a neutral box with the state of the browser.
+public sealed class NoBrowserPreview : IBrowserPreview
+{
+ public Task GetLatestAsync(CancellationToken ct) => Task.FromResult(null);
+}
diff --git a/src/Febe.Web/Engine/EngineSettingsControl.cs b/src/Febe.Web/Engine/EngineSettingsControl.cs
new file mode 100644
index 0000000..7f3d7f2
--- /dev/null
+++ b/src/Febe.Web/Engine/EngineSettingsControl.cs
@@ -0,0 +1,29 @@
+using Febe.Core.Engine;
+using Febe.Core.Storage;
+
+namespace Febe.Web.Engine;
+
+///
+/// «Limiti e comportamento» (mockup 07, spec §7.5): stores new engine settings and applies them. A separate interface
+/// from so that existing implementations stay as they are.
+///
+public interface IEngineSettingsControl
+{
+ ///
+ /// Validates, stores and applies the settings. Throws with Italian messages when a
+ /// value is outside the limits of spec §7.5 (the API answers 400 with that message).
+ ///
+ Task ApplyAsync(EngineSettings settings, CancellationToken ct);
+}
+
+/// The real engine: stores the settings and replans at once ().
+public sealed class EngineHostSettingsControl(EngineHost host) : IEngineSettingsControl
+{
+ public Task ApplyAsync(EngineSettings settings, CancellationToken ct) => host.ApplySettingsAsync(settings, ct);
+}
+
+/// No engine in this process: the settings are stored and the engine reads them when it starts.
+public sealed class StoredEngineSettingsControl(IFebeStorage storage) : IEngineSettingsControl
+{
+ public Task ApplyAsync(EngineSettings settings, CancellationToken ct) => EngineSettingsStore.SaveAsync(storage.Settings, settings, ct);
+}
diff --git a/src/Febe.Web/Engine/IncidentHistory.cs b/src/Febe.Web/Engine/IncidentHistory.cs
new file mode 100644
index 0000000..bdcc45a
--- /dev/null
+++ b/src/Febe.Web/Engine/IncidentHistory.cs
@@ -0,0 +1,21 @@
+using Febe.Core.Domain;
+using Febe.Core.Storage;
+
+namespace Febe.Web.Engine;
+
+/// The stops of the last days for the Attività page (spec §7.6: «nella cronologia della pagina Attività»).
+public interface IIncidentHistory
+{
+ /// Incidents that started in [from, to), newest first.
+ Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct);
+}
+
+/// The incidents of the database (table incident).
+public sealed class StoredIncidentHistory(IFebeStorage storage) : IIncidentHistory
+{
+ public async Task> ListAsync(DateTimeOffset from, DateTimeOffset to, CancellationToken ct)
+ {
+ var list = await storage.Incidents.ListAsync(from, to, ct).ConfigureAwait(false);
+ return [.. list.OrderByDescending(i => i.At)];
+ }
+}
diff --git a/src/Febe.Web/FebeWeb.cs b/src/Febe.Web/FebeWeb.cs
index 551461c..d1df189 100644
--- a/src/Febe.Web/FebeWeb.cs
+++ b/src/Febe.Web/FebeWeb.cs
@@ -1,10 +1,15 @@
using System.Net;
using Febe.Core.Abstractions;
+using Febe.Core.Alerts;
using Febe.Core.Engine;
+using Febe.Core.Import;
+using Febe.Core.Storage;
using Febe.Web.Api;
+using Febe.Web.Connection;
using Febe.Web.Demo;
using Febe.Web.Engine;
using Febe.Web.Hosting;
+using Febe.Web.Import;
using Febe.Web.Library;
using Febe.Web.Native;
using Febe.Web.Security;
@@ -58,6 +63,18 @@ public static class FebeWeb
services.TryAddSingleton();
services.TryAddSingleton(sp => sp.GetRequiredService());
services.TryAddSingleton(sp => sp.GetRequiredService());
+ services.TryAddSingleton(sp => new StoredEngineSettingsControl(sp.GetRequiredService()));
+ services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton(sp => new StoredIncidentHistory(sp.GetRequiredService()));
+ services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton();
+ services.TryAddSingleton(sp => sp.GetService() is { } import
+ ? new ImportHub(import, sp.GetRequiredService(), sp.GetRequiredService())
+ : new ImportHub(sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), options, sp.GetRequiredService()));
services.AddHttpContextAccessor();
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
{
@@ -111,6 +128,11 @@ public static class FebeWeb
LibraryApi.Map(endpoints);
AccountsApi.Map(endpoints);
AccessApi.Map(endpoints);
+ ConnectionApi.Map(endpoints);
+ ActivityApi.Map(endpoints);
+ SettingsApi.Map(endpoints);
+ ImportApi.Map(endpoints);
+ DuplicatesApi.Map(endpoints);
endpoints.Map("/api/{**rest}", static context =>
{
diff --git a/src/Febe.Web/FebeWebOptions.cs b/src/Febe.Web/FebeWebOptions.cs
index 39e792d..e92da23 100644
--- a/src/Febe.Web/FebeWebOptions.cs
+++ b/src/Febe.Web/FebeWebOptions.cs
@@ -77,6 +77,12 @@ public sealed record FebeWebOptions
/// Demo mode (spec §10.6): fake engine, temporary library, scenes chosen by address.
public bool Demo { get; init; }
+ ///
+ /// Docker: root of the import sources, the read-only volume (spec §9.1, §11). Used when the composition does not
+ /// register its own ImportService; ignored on the desktop, where any folder can be chosen.
+ ///
+ public string ImportRoot { get; init; } = "/importa";
+
/// Program version shown in the interface.
public string Version { get; init; } = typeof(FebeWebOptions).Assembly.GetCustomAttribute()?.InformationalVersion?.Split('+')[0] ?? "0.0.0";
diff --git a/src/Febe.Web/Import/ImportHub.cs b/src/Febe.Web/Import/ImportHub.cs
new file mode 100644
index 0000000..55fe82b
--- /dev/null
+++ b/src/Febe.Web/Import/ImportHub.cs
@@ -0,0 +1,140 @@
+using Febe.Core.Abstractions;
+using Febe.Core.Import;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+using Febe.Web.Library;
+
+namespace Febe.Web.Import;
+
+///
+/// The import of the web host (spec §9, mockup 09). When the composition registers its own
+/// that one is used as it is; otherwise the hub builds one over the library of the web host (same thumbnails, journal
+/// and hash index), with the sources of the shell (Docker: , read-only; desktop:
+/// any folder), and builds it again when the library settings change while no job runs.
+/// Library changes of a finished copy reach the open pages as libreria events.
+///
+public sealed class ImportHub : IAsyncDisposable
+{
+ private readonly SemaphoreSlim _gate = new(1, 1);
+ private readonly IFebeStorage? _storage;
+ private readonly FebeLibrary? _library;
+ private readonly IClock _clock;
+ private readonly FebeWebOptions? _options;
+ private readonly LibraryChanges _changes;
+ private readonly bool _owned;
+ private ImportService? _service;
+ private bool _stale;
+
+ /// Uses a service built by the composition (never rebuilt nor disposed here).
+ public ImportHub(ImportService service, IClock clock, LibraryChanges changes, string? sourceRoot = null)
+ {
+ _service = service ?? throw new ArgumentNullException(nameof(service));
+ _clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ _changes = changes ?? throw new ArgumentNullException(nameof(changes));
+ SourceRoot = sourceRoot ?? service.Sources.Root;
+ _service.ProgressChanged += OnProgress;
+ }
+
+ /// Builds its own service over the library of the web host.
+ public ImportHub(IFebeStorage storage, FebeLibrary library, IClock clock, FebeWebOptions options, LibraryChanges changes)
+ {
+ _storage = storage ?? throw new ArgumentNullException(nameof(storage));
+ _library = library ?? throw new ArgumentNullException(nameof(library));
+ _clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ _options = options ?? throw new ArgumentNullException(nameof(options));
+ _changes = changes ?? throw new ArgumentNullException(nameof(changes));
+ _owned = true;
+ SourceRoot = options.Edition == FebeEdition.Docker ? options.ImportRoot : null;
+ }
+
+ /// Docker: the root of the sources (the page lists its subfolders). Null: any folder (native picker).
+ public string? SourceRoot { get; }
+
+ /// The service, built at the first use.
+ public async Task GetAsync(CancellationToken ct = default)
+ {
+ if (_service is { } ready && !_stale)
+ {
+ return ready;
+ }
+
+ await _gate.WaitAsync(ct).ConfigureAwait(false);
+ try
+ {
+ if (_service is not null && _stale && _owned && _service.ActiveRunId is null)
+ {
+ _service.ProgressChanged -= OnProgress;
+ await _service.DisposeAsync().ConfigureAwait(false);
+ _service = null;
+ }
+
+ _stale = false;
+ if (_service is null)
+ {
+ var service = await BuildAsync(ct).ConfigureAwait(false);
+ service.ProgressChanged += OnProgress;
+ await service.RecoverAsync(ct).ConfigureAwait(false);
+ _service = service;
+ }
+
+ return _service;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ /// The library settings changed (folder, naming): the next use builds a new service when none is working.
+ public void LibrarySettingsChanged()
+ {
+ if (_owned)
+ {
+ _stale = true;
+ }
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ if (_service is { } service)
+ {
+ service.ProgressChanged -= OnProgress;
+ if (_owned)
+ {
+ await service.DisposeAsync().ConfigureAwait(false);
+ }
+ }
+
+ _gate.Dispose();
+ }
+
+ private async Task BuildAsync(CancellationToken ct)
+ {
+ var storage = _storage!;
+ var library = _library!;
+ var settings = await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false);
+ return new ImportService(new ImportEnvironment
+ {
+ Storage = storage,
+ Layout = library.Layout,
+ Naming = settings.Naming,
+ Journal = library.Journal,
+ Clock = _clock,
+ Thumbnails = library.Thumbnails,
+ HashIndex = library.HashIndex,
+ Frames = VideoFrameExtractor.TryCreate(),
+ VideoProbe = FfprobeVideoMetadataProbe.TryCreate(),
+ SetFileTimeToPublication = settings.SetFileTimeToPublication,
+ Sources = SourceRoot is { } root ? ImportSourceOptions.Docker(root) : ImportSourceOptions.AnyFolder,
+ DataFolder = library.Data.Root,
+ });
+ }
+
+ private void OnProgress(object? sender, ImportProgress progress)
+ {
+ if (progress.Phase == ImportPhase.Finished && progress.Copied > 0)
+ {
+ _changes.Publish(new LibraryChange(_clock.Now, null, "import"));
+ }
+ }
+}
diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md
index 80738dd..6ca86d1 100644
--- a/src/Febe.Web/LEGGIMI.md
+++ b/src/Febe.Web/LEGGIMI.md
@@ -2,7 +2,7 @@
L'applicazione web di Febe, la stessa per le due vesti (§5): API sotto `/api`, eventi a `/api/eventi`, l'interfaccia
in `wwwroot/` incorporata nell'assembly e servita senza pacchetti in più, le pagine agli indirizzi italiani.
-Qui sotto le convenzioni per chi continua il lavoro (parte 2 dell'interfaccia, composizione di Server e Desktop).
+Qui sotto le convenzioni per chi continua il lavoro (composizione di Server e Desktop, rifiniture).
## Struttura
@@ -13,8 +13,10 @@ Qui sotto le convenzioni per chi continua il lavoro (parte 2 dell'interfaccia, c
| `Hosting/` | `EmbeddedWwwroot`: `IFileProvider` sulle risorse incorporate `wwwroot/…` (o su una cartella, per sviluppo) |
| `Security/` | Controlli di §13.1: Host, Origin, gettone del desktop, password e blocco della veste Docker, intestazioni |
| `Api/` | Endpoint minimi, DTO (`Dtos.cs`), contesto JSON generato (`FebeJsonContext`), conversioni (`ApiMapping`) |
-| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker` |
-| `Library/` | `FebeLibrary` (archivio + disposizione), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente |
+| `Engine/` | `IEngineControl` (comandi al motore), `EngineHostControl`, `OfflineEngine` (nessun motore), `BrowserUseTracker`, `IEngineSettingsControl` (limiti al motore), `IBrowserPreview` (anteprima), `IIncidentHistory` (incidenti) |
+| `Library/` | `FebeLibrary` (archivio + disposizione, `HashIndex`, `DownloadDuplicates`), `LibraryChanges`, esportazione CSV, collegamenti a Instagram, nomi utente, `IDataFolderChange`, `FolderSizes`, `RebuildJob` |
+| `Connection/` | Contratto condiviso con il lato server del collegamento: `IConnectionService`, `IConfigurationProblems`, `PROTOCOLLO.md` (vista remota `/api/vista`); `UnavailableConnectionService` è il ripiego |
+| `Import/` | `ImportHub`: l'`ImportService` registrato dalla composizione, oppure uno costruito sulla libreria |
| `Native/` | `INativeShell` (funzioni del sistema) e `IBrowserWindow` (finestra del browser), con le versioni «niente» |
| `Demo/` | Modalità dimostrativa: dati finti coerenti, motore finto con scene, guscio finto |
| `wwwroot/` | Interfaccia: HTML, CSS, moduli ES senza framework né build |
@@ -47,6 +49,27 @@ var address = FebeWebHost.BoundAddress(app);
queste ultime le pubblica già l'API).
- `IMediaFileResolver` trova il file su disco di un media (di serie: disposizione della libreria e cartelle per account).
+### Punti di estensione della seconda parte
+
+Tutti con un ripiego registrato con `TryAdd`; la composizione registra i propri prima di `AddFebeWeb`.
+
+| Servizio | Ripiego | Chi lo sostituisce |
+|---|---|---|
+| `IConnectionService` (`Connection/`) | `UnavailableConnectionService`: stato `BrowserUnavailable`, «Collegati» e «Scollega» rispondono 400 con un messaggio italiano | Server (vista remota) e Desktop (finestra WebView2): l'implementazione vera e `/api/vista` sono di quel lavoro |
+| `IConfigurationProblems` | `NoConfigurationProblems` (nessun problema) | Server: password mancante, cartelle non scrivibili… Se l'elenco non è vuoto l'interfaccia mostra solo la pagina di errore |
+| `IEngineSettingsControl` | `StoredEngineSettingsControl`: salva le impostazioni del motore nell'archivio | `new EngineHostSettingsControl(engineHost)`: le applica anche al motore che gira |
+| `IBrowserPreview` | `NoBrowserPreview` (nessuna anteprima) | Chi ha il browser: `GetLatestAsync` restituisce l'ultima schermata JPEG (`BrowserFrame`) con l'indirizzo |
+| `IIncidentHistory` | `StoredIncidentHistory` (dall'archivio) | Di solito nessuno |
+| `IAlertTestSender` (Core) | `TelegramNotAvailableYet`: nessun messaggio parte, la risposta lo dice | M8, l'invio vero dei messaggi Telegram |
+| `IDataFolderChange` | `FixedDataFolder`: la cartella dei dati non si cambia dall'interfaccia | Desktop (M6): sposta la cartella al riavvio |
+| `ImportService` (Core) | `ImportHub` ne costruisce uno sulla libreria (Docker: solo sotto `FebeWebOptions.ImportRoot`, di serie `/importa`; desktop: qualsiasi cartella) | La composizione, se vuole opzioni diverse (ffmpeg, cartella sorgente) |
+
+- `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`.
+- La pausa di Alberto nel browser: `POST /api/connection/begin` mette il motore in `UserIsDriving` ma **non** segna il
+ browser come usato; lo segna `finish` (e restano `POST /api/browser/show` e `/api/browser/used`), così «Riprendi»
+ dopo una verifica si accende solo quando Alberto ha davvero finito.
+
### Opzioni e sicurezza (§13.1)
| Veste | Opzioni | Effetto |
@@ -70,7 +93,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| Endpoint | Uso |
|---|---|
-| `GET /api/capabilities` | Veste, accesso, cosa sa fare il guscio (`showInFolder`, `pickFolder`, `foldersReadOnly`, `autostart`, `browserWindow`), versione, ora e giorno del server |
+| `GET /api/capabilities` | Veste, accesso, cosa sa fare il guscio (`showInFolder`, `pickFolder`, `foldersReadOnly`, `autostart`, `browserWindow`), versione, ora e giorno del server, `problems` (da `IConfigurationProblems`, di solito vuoto) |
| `GET/PUT /api/preferences` | Tema (`chiaro`, `scuro`, `sistema`) |
| `GET /api/engine`, `POST /api/engine/pause`, `/resume` | Istantanea del motore, collegamento, `canResume` |
| `POST /api/browser/show`, `/api/browser/used` | «Apri il browser» (desktop), uso del browser |
@@ -84,6 +107,19 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe.
| `POST /api/accounts/{id}/plan`, `PUT /{id}/settings`, `POST /{id}/keep-updated`, `/pause`, `/resume`, `/check-now`, `/remove`, `/pick-folder`, `/open-on-instagram` | Impostazioni dell'account e comandi |
| `GET /api/following`, `POST /api/following/read`, `POST /api/accounts/parse`, `POST /api/accounts` | Dialogo «Aggiungi account» |
| `GET /accesso`, `POST /api/accesso`, `POST /api/uscita` | Accesso con password |
+| `GET /api/connection`, `POST /api/connection/begin` (`{ openLogin }`), `/finish`, `/cancel`, `/disconnect` | Collegamento a Instagram (`IConnectionService`, §6.4): stato `notConnected`, `connected`, `verificationRequired`, `browserUnavailable` |
+| `GET /api/engine/incidents` | Incidenti degli ultimi 14 giorni (rallentamenti, verifiche, arresti), con un consiglio dopo 3 rallentamenti in 7 giorni |
+| `GET /api/browser/preview`, `GET /api/browser/preview/frame` | Anteprima del browser in Attività: indirizzo e immagine JPEG (`no-store`, 404 se non c'è) |
+| `GET /api/duplicates/count`, `GET /api/duplicates?after=`, `POST /api/duplicates/{pairId}` (`{ decision, applyToAll }`) | Doppioni dopo uno scaricamento (§9.5): `keepLarger`, `keepExisting`, `keepBoth`; niente si decide da solo |
+| `GET/PUT /api/settings/general`, `POST /api/settings/naming-preview`, `/pick-folder`, `/data-folder` | Cartelle (cambio della libreria solo desktop), schema dei nomi con anteprima, tema, avvio, area di notifica |
+| `GET/PUT /api/settings/limits` | Profilo di prudenza, orari, sessioni, tetti, avvio graduale; le regole di §7.5 rispondono 400 con i messaggi italiani |
+| `GET/PUT /api/settings/notifications`, `POST /api/settings/notifications/test` | Avvisi (§13.3). Il gettone Telegram non torna mai indietro (solo `telegramTokenSet`), un campo vuoto lo lascia com'è |
+| `GET /api/settings/data`, `POST /api/settings/backups`, `GET/POST /api/settings/rebuild` (`{ confirm: "ricostruisci" }`) | Cartella dei dati, copie del database, ricostruzione dalla libreria con avanzamento e resoconto |
+| `GET /api/about` | Versione, veste, cartelle, indirizzi della guida (wiki) e del repository |
+| `GET /api/import`, `GET /api/import/sources?path=`, `POST /api/import/pick-folder`, `/inspect`, `/start` | Importa, passo 1: elenco delle importazioni, cartelle sotto `/importa` (Docker) o scelta nativa (desktop) |
+| `GET /api/import/{id}/progress`, `POST /{id}/interrupt`, `/resume` | Passi 2 e 4: avanzamento, interruzione e ripresa |
+| `GET /api/import/{id}/review`, `PUT /{id}/folders`, `PUT /{id}/mode`, `GET /{id}/duplicates?after=&all=`, `POST /{id}/duplicates/{pairId}`, `GET /api/import/files/{fileId}/preview` | Passo 3: contatori, cartelle → account, Copia/Sposta, doppioni con anteprime |
+| `POST /api/import/{id}/copy`, `GET /{id}/report`, `GET /{id}/report.csv`, `POST /{id}/discard` | Copia, resoconto, CSV (UTF-8 con BOM, `;`), abbandono di un'importazione non copiata |
| `GET /icone/tutte.svg` | Tutte le icone Lucide di `wwwroot/icone` in un solo sprite (``) |
Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON.
@@ -107,9 +143,14 @@ Moduli ES, nessuna dipendenza, nessuna build. Durante lo sviluppo si servono da
- `page.signal`: da passare a `api()` (le richieste si annullano uscendo); `page.onEngine(fn)`, `page.onLibrary(fn)`,
`page.onLeave(fn)`.
La striscia rossa di arresto (mockup 11) la mette la cornice su ogni pagina, da sola.
-4. Pagine ancora da fare (segnaposto in `pages/placeholder.js`): `/attivita`, `/importa` (deve leggere
- `route.query.get('passo')`, la dimostrazione apre `/importa?passo=3`), `/impostazioni/{generali|limiti|collegamento|notifiche|dati|informazioni}`,
- `/browser` (vista remota della veste Docker).
+4. Pagine della seconda parte: `pages/activity.js` (`/attivita`, con `day-strip.js` per la striscia del giorno),
+ `pages/settings.js` (`/impostazioni/{generali|limiti|collegamento|notifiche|dati|informazioni}`, un modulo
+ `settings-*.js` per sezione; `connection.js` per il collegamento), `pages/browser.js` (`/browser`, vista remota della
+ veste Docker, `remote-view.js` parla con `/api/vista` secondo `Connection/PROTOCOLLO.md`), `pages/import.js`
+ (`/importa`, `?passo=1|3`, `?id=N`), `pages/duplicates.js` (`/doppioni`), `pages/compare.js` (confronto dei doppioni,
+ usato da Importa e da `/doppioni`), `pages/welcome.js` (primo avvio, dalla libreria vuota e non collegata),
+ `pages/problems.js` (pagina di errore quando `caps().problems` non è vuoto). `pages/placeholder.js` ora dice solo
+ «Pagina non trovata».
### Moduli comuni (`js/core/`)
@@ -147,8 +188,13 @@ virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `p
cartella temporanea con dati e libreria finti (38 account, circa 18.000 elementi), cancellata alla chiusura. Non
scrive mai nella libreria vera e non usa la rete.
-- Scene del motore: `?scena=normale|sessione|fermo|scollegato`; tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|docker`.
-- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`, `/importa?passo=3` (da fare).
+- Scene del motore: `?scena=normale|sessione|fermo|scollegato|errore` (`errore`: password mancante, pagina di errore
+ di configurazione); tema: `?tema=chiaro|scuro`; veste: `?veste=desktop|windows|docker`.
+- Indirizzi diretti: `/account?dialogo=aggiungi`, `/account/3/impostazioni`, `/account/2?tipo=storie`,
+ `/importa?passo=3` (revisione di un'importazione già analizzata), `/doppioni`, `/impostazioni/collegamento?scena=scollegato&veste=docker`.
+- Seconda parte (`Demo/DemoPart2.cs`, `Demo/DemoImport.cs`): collegamento, anteprima del browser e incidenti secondo la
+ scena; tre doppioni dopo uno scaricamento; una sorgente da importare generata in `importa/Backup del vecchio disco`
+ (copie identiche, varianti, cartelle senza account, file non riconosciuti) e già analizzata all'avvio.
- I dati stanno in `Demo/DemoSeeder.cs` (`Specs`); le prove `tests/Febe.Tests/Web/DemoTests.cs` controllano che i
conti tornino.
@@ -163,4 +209,6 @@ rimaste dai mockup sono in `docs/schermate/differenze.md`.
`tests/Febe.Tests/Web/` avvia Kestrel vero su una porta libera di 127.0.0.1 (`Support/WebTestServer.cs`), con
archivio e libreria temporanei e orologio manuale; `DemoTests` avvia una dimostrazione intera una volta per classe.
+Le prove della seconda parte (`ConnectionApiTests`, `SettingsApiTests`, `ActivityApiTests`, `ImportApiTests`,
+`DemoPart2Tests`) usano gli aiuti di `Part2Support/`.
`dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Web"`.
diff --git a/src/Febe.Web/Library/DataFolderServices.cs b/src/Febe.Web/Library/DataFolderServices.cs
new file mode 100644
index 0000000..7e27485
--- /dev/null
+++ b/src/Febe.Web/Library/DataFolderServices.cs
@@ -0,0 +1,234 @@
+using System.Collections.Concurrent;
+using Febe.Core.Abstractions;
+using Febe.Core.Library;
+using Febe.Core.Storage;
+
+namespace Febe.Web.Library;
+
+///
+/// «Cambia…» of the Data folder (Impostazioni, Generali; spec §4.7, §8.2). The Data folder holds the database and the
+/// browser profile with the Instagram session: it cannot move while Febe runs, so the shell records the choice and uses
+/// it at the next start. The desktop implements it (M6); Docker changes it from the container (read-only here).
+///
+public interface IDataFolderChange
+{
+ /// The shell can record a new Data folder.
+ bool CanChange { get; }
+
+ /// Records the new folder for the next start; returns the Italian message for the page.
+ Task RequestChangeAsync(string newFolder, CancellationToken ct);
+}
+
+/// Default: the Data folder is fixed by the composition (Docker volume, command line).
+public sealed class FixedDataFolder : IDataFolderChange
+{
+ public bool CanChange => false;
+
+ public Task RequestChangeAsync(string newFolder, CancellationToken ct) =>
+ throw new Api.BadRequestException("La cartella dei dati qui non si cambia dall'interfaccia: si sceglie quando si avvia Febe (in Docker, con il volume /dati).");
+}
+
+/// Setting keys of the desktop shell, edited from the interface.
+public static class DesktopSettingKeys
+{
+ /// «Chiudendo la finestra, Febe resta attivo nell'area di notifica» (true/false, default true). Read by the desktop (M6).
+ public const string KeepInTray = "desktop.resta-nell-area-di-notifica";
+}
+
+/// Sizes of folders, measured in the background and kept for a while (a big thumbnails folder takes seconds).
+public sealed class FolderSizes(IClock clock)
+{
+ /// How long a measure stays good.
+ public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10);
+
+ private readonly ConcurrentDictionary _measures = new(StringComparer.Ordinal);
+
+ /// The last known size of a folder (null while the first measure runs); starts a new measure when stale.
+ public (long? Bytes, bool Measuring) Get(string folder)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(folder);
+ var now = clock.Now;
+ var measure = _measures.GetOrAdd(folder, _ => new Measure());
+ lock (measure)
+ {
+ if (!measure.Running && (measure.Bytes is null || now - measure.At > Lifetime))
+ {
+ measure.Running = true;
+ _ = Task.Run(() =>
+ {
+ var bytes = SizeOf(folder);
+ lock (measure)
+ {
+ measure.Bytes = bytes;
+ measure.At = clock.Now;
+ measure.Running = false;
+ }
+ });
+ }
+
+ return (measure.Bytes, measure.Running);
+ }
+ }
+
+ /// Forgets a measure (after a backup or a rebuild).
+ public void Invalidate(string folder) => _measures.TryRemove(folder, out _);
+
+ /// Total size of the files below a folder; unreadable parts are skipped.
+ public static long SizeOf(string folder)
+ {
+ if (!Directory.Exists(folder))
+ {
+ return 0;
+ }
+
+ long total = 0;
+ try
+ {
+ foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }))
+ {
+ try
+ {
+ total += file.Length;
+ }
+ catch (IOException)
+ {
+ // the file went away while counting
+ }
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // keep what was counted
+ }
+
+ return total;
+ }
+
+ /// Free bytes on the disk that holds ; null when unknown.
+ public static long? FreeBytes(string path)
+ {
+ try
+ {
+ var full = Path.GetFullPath(path);
+ DriveInfo? best = null;
+ foreach (var drive in DriveInfo.GetDrives())
+ {
+ string root;
+ try
+ {
+ root = drive.RootDirectory.FullName;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ continue;
+ }
+
+ if (Inside(full, root) && (best is null || root.Length > best.RootDirectory.FullName.Length))
+ {
+ best = drive;
+ }
+ }
+
+ return best is { IsReady: true } ? best.AvailableFreeSpace : null;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
+ {
+ return null;
+ }
+ }
+
+ private static bool Inside(string path, string root)
+ {
+ var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
+ var r = Path.TrimEndingDirectorySeparator(root);
+ return r.Length == 0 || string.Equals(path, r, comparison) || path.StartsWith(r + Path.DirectorySeparatorChar, comparison) || r == "/";
+ }
+
+ private sealed class Measure
+ {
+ public long? Bytes { get; set; }
+
+ public DateTimeOffset At { get; set; }
+
+ public bool Running { get; set; }
+ }
+}
+
+///
+/// «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).
+///
+public sealed class RebuildJob(IFebeStorage storage, FebeLibrary library, IClock clock, LibraryChanges changes)
+{
+ private readonly Lock _gate = new();
+ private Task? _task;
+
+ public RebuildState State { get; private set; } = RebuildState.Idle;
+
+ public bool Running
+ {
+ get
+ {
+ lock (_gate)
+ {
+ return _task is { IsCompleted: false };
+ }
+ }
+ }
+
+ /// Starts the rebuild; false when one is already running.
+ public bool TryStart()
+ {
+ lock (_gate)
+ {
+ if (_task is { IsCompleted: false })
+ {
+ return false;
+ }
+
+ State = RebuildState.Idle with { Running = true, StartedAt = clock.Now };
+ _task = Task.Run(RunAsync);
+ return true;
+ }
+ }
+
+ /// Waits for the running rebuild (tests).
+ public Task WaitAsync() => _task ?? Task.CompletedTask;
+
+ private async Task RunAsync()
+ {
+ var progress = new SyncProgress(p => State = State with { Folder = p.Folder, FoldersDone = p.FoldersDone, FoldersTotal = p.FoldersTotal, FilesChecked = p.FilesChecked });
+ try
+ {
+ var rebuilder = new LibraryRebuilder(storage, library.Layout, clock, library.Thumbnails, VideoFrameExtractor.TryCreate(), library.HashIndex);
+ var report = await rebuilder.RebuildAsync(new RebuildOptions(), progress).ConfigureAwait(false);
+ State = State with { Running = false, Report = report, FinishedAt = clock.Now };
+ changes.Publish(new LibraryChange(clock.Now, null, "rebuild"));
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
+ {
+ State = State with { Running = false, Error = ex.Message, FinishedAt = clock.Now };
+ }
+ }
+
+ /// Progress reported on the calling thread (no synchronization context to post to).
+ private sealed class SyncProgress(Action action) : IProgress
+ {
+ public void Report(T value) => action(value);
+ }
+}
+
+/// The state of the rebuild for the page.
+public sealed record RebuildState(
+ bool Running,
+ DateTimeOffset? StartedAt,
+ string? Folder,
+ int FoldersDone,
+ int FoldersTotal,
+ int FilesChecked,
+ RebuildReport? Report,
+ string? Error,
+ DateTimeOffset? FinishedAt)
+{
+ public static RebuildState Idle { get; } = new(false, null, null, 0, 0, 0, null, null, null);
+}
diff --git a/src/Febe.Web/Library/FebeLibrary.cs b/src/Febe.Web/Library/FebeLibrary.cs
index 1fec74a..000b0f9 100644
--- a/src/Febe.Web/Library/FebeLibrary.cs
+++ b/src/Febe.Web/Library/FebeLibrary.cs
@@ -38,6 +38,12 @@ public sealed class FebeLibrary
public AccountJournal Journal { get; }
+ /// The in-memory index of perceptual hashes shared with the collection, when the composition passed one.
+ public PerceptualHashIndex? HashIndex => _index;
+
+ /// The review of probable duplicates found after a download (spec §9.5), on Alberto's explicit choice only.
+ public DownloadDuplicateReview DownloadDuplicates => new(_storage, _layout, Journal, _clock, Thumbnails, _index);
+
/// «Elimina dalla libreria», on Alberto's explicit choice only (rule 12).
public LibraryDeletion Deletion => new(_storage, _layout, Journal, _clock, Thumbnails, _index);
diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css
index 13bee69..1a8c3c1 100644
--- a/src/Febe.Web/wwwroot/css/febe.css
+++ b/src/Febe.Web/wwwroot/css/febe.css
@@ -576,8 +576,333 @@ a.stato:hover{border-color:var(--bordo-forte)}
.aggiungi .problemi{margin-top:10px;font-size:12.5px;color:var(--rosso);display:flex;flex-direction:column;gap:3px}
.aggiungi .riconosciuti{margin-top:10px;font-size:12.5px;color:var(--testo-2)}
-/* ---------- pagine segnaposto per la seconda parte ---------- */
-.prossimamente{max-width:620px}
+/* ==========================================================================
+ Parte 2 dell'interfaccia: Attività, Impostazioni, Collegamento, Browser,
+ Importa, doppioni, primo avvio, problemi di configurazione.
+ ========================================================================== */
+
+/* ---------- comuni ---------- */
+.piccolo{font-size:12.5px}
+.errore-testo{color:var(--rosso);font-size:12.5px;margin:4px 0 0}
+.avviso-testo{color:var(--ambra);font-size:12.5px;margin:4px 0 0}
+.riga-azione{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:12px}
+.testa-blocco{display:flex;align-items:baseline;gap:12px;margin:0 0 10px;flex-wrap:wrap;min-width:0}
+.testa-blocco h2{margin:0;font-size:15px;font-weight:650}
+.testa-blocco > .muto{font-size:13px}
+.testa-blocco .destra,.testa-blocco .legenda{margin-left:auto}
+.testa-sez{margin-bottom:12px}
+.testa-sez .et{vertical-align:2px;margin-left:6px;font-weight:550}
+.vuoto-elenco{margin:0;padding:16px;color:var(--testo-2);font-size:13.5px}
+.elenco-attivita{list-style:none;margin:0;padding:0}
+.elenco-attivita li{display:flex;align-items:center;gap:14px;padding:10px 16px;border-bottom:1px solid var(--bordo);min-height:56px}
+.elenco-attivita li:last-child{border-bottom:0}
+.elenco-attivita .quando{width:100px;flex:none;color:var(--testo-2);font-size:12.5px}
+.elenco-attivita .chi-cosa{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}
+.elenco-attivita .chi-cosa b{font-weight:600;font-size:13.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.elenco-attivita .chi-cosa > span{font-size:12.5px;color:var(--testo-2);overflow:hidden;text-overflow:ellipsis}
+.elenco-attivita .codice{font-weight:400;color:var(--testo-3);font-size:12px;margin-left:4px}
+.elenco-semplice{list-style:none;margin:0;padding:6px 0}
+.elenco-semplice li{display:flex;justify-content:space-between;gap:16px;padding:7px 16px;font-size:13.5px;border-bottom:1px solid var(--bordo)}
+.elenco-semplice li:last-child{border-bottom:0}
+.due-colonne{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px}
+.due-colonne h2{margin:0 0 10px;font-size:15px;font-weight:650}
+.blocco h2{margin:0 0 10px;font-size:15px;font-weight:650}
+.avviso-azione{align-items:center}
+.avviso-azione > span{flex:1}
+.testa .destra .btn svg.ic{flex:none}
+.dati-db{display:grid;grid-template-columns:110px 1fr;gap:6px 14px;margin:12px 0 0;font-size:13px}
+.dati-db dt{color:var(--testo-2)}
+.dati-db dd{margin:0;overflow-wrap:anywhere}
+.molla{flex:1}
+
+/* ---------- striscia della giornata: legenda ---------- */
+.legenda i.l-sess{background:var(--accento)}
+.legenda i.l-prev{border:1.5px dashed var(--accento)}
+.legenda i.l-freno{background:var(--ambra-pieno)}
+.legenda i.l-fermo{background:repeating-linear-gradient(135deg,var(--rosso) 0 2px,transparent 2px 4px)}
+.legenda i.l-notte{background:repeating-linear-gradient(135deg,var(--testo-3) 0 1px,transparent 1px 4px);opacity:.6}
+.striscia .fermo{z-index:1}
+.striscia .adesso{z-index:2}
+.striscia .freno{opacity:.95}
+
+/* ---------- attività ---------- */
+.attivita{display:flex;flex-direction:column;gap:24px;padding-bottom:8px}
+.attivita > div:empty{display:none}
+[data-pagina=attivita] .arresto .riprendi-arresto{display:none}
+.ora-pannello{display:flex;align-items:center;gap:24px;padding:18px 18px 18px 24px;min-height:142px}
+.ora-testo{flex:1;min-width:0}
+.ora-testo .riga{display:flex;align-items:center;gap:10px}
+.ora-testo .riga b{font-size:17px;font-weight:650}
+.ora-testo .cosa{margin:10px 0 0 18px;font-weight:550;font-size:14.5px}
+.ora-testo .dettaglio{margin:5px 0 0 18px;color:var(--testo-2);font-size:13px}
+.anteprima{margin:0;flex:none;width:266px;border:1px solid var(--bordo-forte);border-radius:8px;overflow:hidden;background:var(--superficie)}
+.anteprima figcaption{display:flex;align-items:center;gap:6px;height:24px;padding:0 9px;font-size:11.5px;color:var(--testo-2);border-bottom:1px solid var(--bordo);white-space:nowrap;overflow:hidden}
+.anteprima figcaption .indirizzo{overflow:hidden;text-overflow:ellipsis}
+.anteprima .quadro{height:116px;background:#161616;position:relative}
+.anteprima img{display:block;width:100%;height:100%;object-fit:cover}
+.segnaposto-anteprima{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:rgba(255,255,255,.72);font-size:12px;text-align:center;padding:0 18px;line-height:1.35}
+.segnaposto-anteprima svg.ic{color:rgba(255,255,255,.6)}
+[data-tema="scuro"] .segnaposto-anteprima svg.ic{color:var(--rosso)}
+.tetti{display:grid;grid-template-columns:repeat(4,minmax(0,1fr))}
+.tetto{padding:14px 18px 15px;border-left:1px solid var(--bordo);display:flex;flex-direction:column;gap:7px;min-width:0}
+.tetto:first-child{border-left:0}
+.tetto .nome{font-size:13px;color:var(--testo-2)}
+.tetto .valore{display:flex;align-items:baseline;gap:6px;margin-top:-1px}
+.tetto .valore b{font-size:20px;font-weight:650}
+.tetto .valore span{font-size:12.5px;color:var(--testo-2)}
+.tetto .nota{font-size:12px;color:var(--testo-2);display:flex;align-items:center;gap:4px}
+.tetto .nota svg{color:var(--ambra)}
+.tutti-tetti{width:min(720px,calc(100vw - 32px))}
+.tutti-tetti .tab td{vertical-align:top}
+.tutti-tetti .cella-tetto{display:flex;flex-direction:column;gap:6px;min-width:130px;padding-top:2px}
+.tutti-tetti .contenuto > .aiuto{margin-bottom:12px}
+
+/* ---------- impostazioni ---------- */
+.imp{height:auto;min-height:100%;align-items:start}
+.imp > nav{position:sticky;top:0}
+.imp .cont{width:100%}
+.imp .sezione{padding:18px 0 20px}
+.imp .sezione:first-child{padding-top:6px}
+.cartella-impostazioni + .cartella-impostazioni{margin-top:16px}
+.titolo-campo{display:block;font-weight:600;font-size:14px;margin-bottom:2px}
+.riga-cartella{display:flex;align-items:center;gap:12px;margin-top:10px}
+.riga-cartella .campo{flex:1;height:34px}
+.riga-cartella .spazio{margin-left:auto;min-width:110px;text-align:right;color:var(--testo-2);font-size:12.5px;white-space:nowrap}
+.nomi-file{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:24px;margin-top:4px}
+.colonna-nomi .etichetta{margin-top:14px}
+.colonna-nomi .etichetta:first-child{margin-top:0}
+.colonna-nomi .campo input{font-size:13.5px}
+.colonna-nomi .segnaposto{margin-top:10px}
+.data-file{margin-top:12px}
+.albero{padding:11px 16px;font-size:13.5px;line-height:1.25}
+.albero .ramo{display:flex;align-items:center;gap:8px;padding:2.5px 0;min-width:0}
+.albero .ramo span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.albero .ramo svg{color:var(--testo-2)}
+.albero .livello-1{padding-left:22px}
+.albero .livello-2{padding-left:44px}
+.albero .radice b{font-weight:600}
+.problemi-schema:empty{display:none}
+.problemi-schema{margin-top:8px}
+.aspetto{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:24px}
+.aspetto .lingua{width:220px}
+.leve{display:flex;flex-direction:column;gap:12px}
+.elenco-leve{display:flex;flex-direction:column;gap:14px}
+.leva-riga .aiuto{margin:3px 0 0 46px}
+.campi-telegram{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:20px}
+.campi-telegram .aiuto{margin-top:6px}
+.riga-campo{display:flex;gap:8px;align-items:center}
+.riga-campo .campo{flex:1}
+.licenze{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px;font-size:13.5px}
+.licenze a{margin-left:8px}
+.marchio-grande{display:flex;align-items:center;gap:14px}
+.marchio-grande svg{width:44px;height:44px}
+.marchio-grande b{display:block;font-size:20px;font-weight:650}
+.resoconto-ricostruzione{padding:14px 16px;margin-top:12px}
+.resoconto-ricostruzione ul{margin:8px 0 0;padding-left:18px;font-size:13.5px;display:flex;flex-direction:column;gap:3px}
+.avanzamento-blocco{margin-top:12px}
+.avanzamento-blocco p{margin:0 0 8px}
+.tabella-tetti .tab td{padding-top:9px;padding-bottom:9px}
+.tabella-tetti .tab td:first-child{width:46%}
+.tabella-tetti .campo.numero{width:120px;height:32px}
+.tabella-tetti .campo.numero input{text-align:right}
+.tabella-tetti .riga-graduale .leva{font-weight:500}
+.tabella-tetti .informativa td{color:var(--testo-2)}
+.tabella-tetti .informativa svg{vertical-align:-1px}
+.tab .num,.tab th.num{text-align:right}
+
+/* limiti: profili */
+.avviso-limiti{margin-bottom:18px}
+.profili{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
+.profilo{display:flex;flex-direction:column;gap:6px;padding:14px 16px;border:1px solid var(--bordo);border-radius:var(--r-pannello);background:var(--superficie);cursor:pointer;position:relative;min-width:0}
+.profilo:hover{border-color:var(--bordo-forte)}
+.profilo.scelto{border-color:var(--accento);box-shadow:0 0 0 1px var(--accento)}
+.profilo:has(input:focus-visible){outline:2px solid var(--accento);outline-offset:2px}
+.profilo .testa-profilo{display:flex;align-items:center;gap:10px}
+.profilo .testa-profilo b{font-weight:650;font-size:14.5px}
+.profilo .testa-profilo .et{margin-left:auto}
+.profilo input:checked ~ .testa-profilo .tondo,.profilo .tondo.si{border-color:var(--accento)}
+.profilo input:checked ~ .testa-profilo .tondo::after,.profilo .tondo.si::after{content:"";position:absolute;inset:3px;border-radius:50%;background:var(--accento)}
+.profilo p{margin:0;font-size:13px;color:var(--testo-2)}
+.profilo .riassunto{border-top:1px solid var(--bordo);padding-top:9px;margin-top:4px;color:var(--testo);font-size:12.5px}
+.profilo .riassunto b{font-weight:650}
+.su-misura{margin-top:12px;cursor:default}
+/* limiti: fascia oraria */
+.fascia-barra{position:relative;height:40px;border-radius:6px;border:1px solid var(--bordo);background:repeating-linear-gradient(135deg,var(--tratteggio) 0 2px,transparent 2px 7px),var(--fondo);overflow:visible}
+.fascia-barra .tacca{position:absolute;top:0;bottom:0;width:1px;background:var(--bordo)}
+.fascia-barra .banda{position:absolute;top:0;bottom:0;background:var(--accento-tinta);border-top:1px solid var(--accento-bordo);border-bottom:1px solid var(--accento-bordo)}
+.fascia-barra .maniglia{position:absolute;top:-3px;bottom:-3px;width:5px;margin-left:-2.5px;border-radius:3px;background:var(--accento);cursor:ew-resize;touch-action:none}
+.riga-fascia{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-top:8px}
+.etichetta-riga{font-size:13.5px;color:var(--testo-2)}
+.campo.ora{width:78px}
+.campo.ora input{font-variant-numeric:tabular-nums}
+.giorni-etichetta{margin-left:20px}
+.giorni{display:flex;gap:6px}
+.cerchio-giorno{width:30px;height:30px;border-radius:50%;border:1px solid var(--bordo-forte);background:var(--superficie);color:var(--testo-2);font-weight:600;font-size:12.5px;display:inline-flex;align-items:center;justify-content:center;padding:0}
+.cerchio-giorno.si{background:var(--accento-tinta);border-color:var(--accento-bordo);color:var(--accento-scuro)}
+.riga-sposta{display:flex;align-items:center;gap:8px;margin-top:14px;flex-wrap:wrap}
+.campo.numero.corto{width:70px;height:30px}
+/* limiti: cursori */
+.cursori{display:grid;grid-template-columns:200px minmax(0,1fr) 150px;align-items:center;gap:14px 18px}
+.cursori .errore-testo{grid-column:2 / span 2;margin-top:-8px}
+.cursori .errore-testo[hidden]{display:none}
+.valore-cursore{font-size:13px;color:var(--testo-2);font-variant-numeric:tabular-nums}
+.doppio{position:relative;height:22px}
+.doppio .binario{position:absolute;left:0;right:0;top:50%;height:3px;margin-top:-1.5px;border-radius:2px;background:var(--bordo-forte)}
+.doppio .tratto{position:absolute;top:50%;height:3px;margin-top:-1.5px;border-radius:2px;background:var(--accento)}
+.doppio input[type=range]{position:absolute;inset:0;width:100%;height:22px;margin:0;background:transparent;pointer-events:none;-webkit-appearance:none;appearance:none}
+.doppio input[type=range]::-webkit-slider-runnable-track{background:transparent;height:3px}
+.doppio input[type=range]::-moz-range-track{background:transparent}
+.doppio input[type=range]::-webkit-slider-thumb{pointer-events:auto;-webkit-appearance:none;width:16px;height:16px;margin-top:-6.5px;border-radius:50%;background:var(--superficie);border:2px solid var(--accento);box-shadow:0 1px 2px rgba(0,0,0,.2);cursor:pointer}
+.doppio input[type=range]::-moz-range-thumb{pointer-events:auto;width:13px;height:13px;border-radius:50%;background:var(--superficie);border:2px solid var(--accento);cursor:pointer}
+.doppio input[type=range]:focus-visible{outline:none}
+.doppio input[type=range]:focus-visible::-webkit-slider-thumb{box-shadow:0 0 0 3px var(--accento-tinta)}
+.singolo input.cursore.lungo{width:100%}
+input[type=range].cursore.lungo::-webkit-slider-runnable-track{background:linear-gradient(90deg,var(--accento) 0 var(--pieno,50%),var(--bordo-forte) var(--pieno,50%))}
+input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento);border-width:2px}
+
+/* ---------- collegamento e browser ---------- */
+.pagina-collegamento{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:28px;min-height:100%;align-items:stretch}
+.collega-sinistra{display:flex;flex-direction:column;min-width:0}
+.collega-destra{display:flex;flex-direction:column;gap:12px;min-width:0;padding-top:2px}
+.collega-destra h2.sez{margin-bottom:12px}
+.collega-destra .avviso{font-size:13.5px;line-height:1.5;padding:13px 16px}
+.nota-password{background:var(--accento-tinta)}
+.passi-collegamento{list-style:none;margin:0 0 8px;padding:0;display:flex;flex-direction:column;gap:18px}
+.passi-collegamento li{display:flex;gap:14px}
+.passi-collegamento .numero{width:24px;height:24px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--accento-tinta);color:var(--accento-scuro);font-weight:650;font-size:12.5px;margin-top:1px}
+.passi-collegamento b{display:block;font-weight:650;font-size:14px}
+.passi-collegamento p{margin:3px 0 0;color:var(--testo-2);font-size:13px}
+.bottoni-collegamento{display:grid;grid-template-columns:1fr 1.3fr;gap:12px;margin-top:auto}
+.bottoni-collegamento .btn{justify-content:center}
+.vista{flex:1;display:flex;flex-direction:column;border:1px solid var(--bordo-forte);border-radius:var(--r-pannello);background:var(--superficie);overflow:hidden;min-height:420px}
+.vista-barra{display:flex;align-items:center;gap:6px;padding:8px 10px;border-bottom:1px solid var(--bordo);background:var(--superficie)}
+.vista-barra .btn.solo{width:32px;height:32px}
+.vista-indirizzo{flex:1;min-width:0;display:flex;align-items:center;gap:8px;height:30px;padding:0 12px;border-radius:15px;background:var(--rialzo);border:1px solid var(--bordo);font-size:13px;color:var(--testo-2);white-space:nowrap;overflow:hidden}
+.vista-indirizzo svg{color:var(--verde)}
+.vista-indirizzo b{color:var(--testo);font-weight:500}
+.vista-area{flex:1;position:relative;display:flex;align-items:center;justify-content:center;background:var(--fondo);min-height:0}
+.vista-schermo{display:block;max-width:100%;max-height:100%;cursor:default;background:#fff}
+.vista-schermo:focus-visible{outline:3px solid var(--accento);outline-offset:-3px}
+.vista-stato{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:24px}
+.vista-segnaposto{display:flex;flex-direction:column;align-items:center;gap:14px;text-align:center;color:var(--testo-2);max-width:440px}
+.vista-segnaposto p{margin:0;line-height:1.5}
+.vista-segnaposto h2{margin:0;color:var(--testo);font-size:17px;font-weight:650}
+.vista-segnaposto svg.ic.l{color:var(--testo-3)}
+.scheletro{width:320px;max-width:100%;padding:26px 28px;border:1.5px dashed var(--bordo-forte);border-radius:8px;background:var(--superficie);display:flex;flex-direction:column;align-items:center;gap:12px}
+.scheletro i{display:block;border-radius:5px;background:var(--bordo)}
+.scheletro .s1{width:46%;height:20px;margin-bottom:10px}
+.scheletro .s2{width:100%;height:34px;background:var(--rialzo);border:1px solid var(--bordo)}
+.scheletro .s3{width:100%;height:34px;background:var(--bordo-forte)}
+.scheletro .s4{width:62%;height:9px;margin-top:10px}
+.vista-finestra{align-items:center;justify-content:center}
+.vista-finestra .vista-segnaposto{padding:40px 24px}
+.collegato{padding:22px 24px}
+.chi-collegato{display:flex;align-items:center;gap:14px}
+.chi-collegato h2{margin:0;font-size:17px;font-weight:650}
+.collegato > p{margin:14px 0 0;color:var(--testo-2)}
+.azioni-collegato{display:flex;gap:10px;margin-top:18px;flex-wrap:wrap}
+.pagina-browser{display:flex;flex-direction:column;gap:14px;height:100%}
+.pagina-browser > div:empty{display:none}
+.pagina-browser .vista{min-height:460px}
+
+/* ---------- importa ---------- */
+.passi-import{display:flex;align-items:center;gap:0;list-style:none;margin:0;padding:0}
+.passi-import li{display:flex;align-items:center;gap:7px;font-size:13px;color:var(--testo-2);white-space:nowrap}
+.passi-import li + li::before{content:"";width:22px;height:1px;background:var(--bordo-forte);margin:0 10px}
+.passi-import .cerchio{width:20px;height:20px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:650;border:1px solid var(--bordo-forte);color:var(--testo-2);background:var(--superficie)}
+.passi-import .fatto .cerchio{background:var(--verde);border-color:var(--verde);color:#fff}
+[data-tema="scuro"] .passi-import .fatto .cerchio{color:#0F2A1D}
+.passi-import .fatto .cerchio svg{width:11px;height:11px;stroke-width:3}
+.passi-import .qui{color:var(--testo);font-weight:650}
+.passi-import .qui .cerchio{background:var(--accento);border-color:var(--accento);color:var(--su-accento)}
+.riga-sorgente{display:flex;align-items:center;gap:10px;margin-bottom:14px;flex-wrap:wrap;min-width:0}
+.riga-sorgente svg{color:var(--testo-2)}
+.riga-sorgente > b{font-weight:600}
+.riga-sorgente > .muto{font-size:13px}
+.riga-sorgente .destra{margin-left:auto}
+.contatori{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin-bottom:22px}
+.contatore{padding:14px 18px;border-left:1px solid var(--bordo);display:flex;flex-direction:column;gap:2px;min-width:0}
+.contatore:first-child{border-left:0}
+.contatore .riga{display:flex;align-items:center;gap:8px}
+.contatore .riga b{font-size:19px;font-weight:650}
+.contatore .nome{font-weight:600;font-size:13.5px;margin-top:2px}
+.contatore .muto{font-size:12.5px}
+.spia.grigio{background:var(--bordo-forte)}
+.revisione-colonne{display:grid;grid-template-columns:minmax(0,1fr) 380px;gap:24px;align-items:start}
+.cartelle-account h2{margin:0 0 10px;font-size:15px;font-weight:650}
+.cartelle-account .tab td{padding-top:9px;padding-bottom:9px}
+.cartelle-account .tab td b{font-weight:600}
+.cartelle-account .col-va{width:46%}
+.cartelle-account .campo.scelta{height:32px;width:100%}
+.cartelle-account .campo.scelta select{width:100%;text-overflow:ellipsis}
+.cartelle-account > div:last-child .avviso{margin-top:14px}
+.salva .fuori{color:var(--testo-2);font-size:13px;max-width:440px;text-align:right}
+.importa-barra-modo{white-space:nowrap}
+.indietro + .testa{padding-top:12px}
+.confronto .navigazione .btn.solo{width:28px;height:28px}
+.elenco-attivita.largo .quando{width:150px}
+.salva .gruppo{flex:none}
+.importa-sorgente,.importa-avanzamento,.importa-resoconto{max-width:880px}
+.importa-sorgente .sezione:first-child{padding-top:4px}
+.sfoglia{margin-top:14px;overflow:hidden}
+.sfoglia-testa{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid var(--bordo);font-size:13px;color:var(--testo-2)}
+.sfoglia-testa .destra{margin-left:auto}
+.sfoglia-elenco{list-style:none;margin:0;padding:0;max-height:340px;overflow:auto}
+.sfoglia-elenco li{display:flex;align-items:center;border-bottom:1px solid var(--bordo)}
+.sfoglia-elenco li:last-child{border-bottom:0}
+.sfoglia-voce{flex:1;display:flex;align-items:center;gap:10px;padding:10px 14px;border:0;background:transparent;text-align:left;font-size:13.5px;color:var(--testo)}
+.sfoglia-voce:hover{background:var(--rialzo)}
+.sfoglia-voce svg{color:var(--testo-2)}
+.scelta-cartella{padding:16px;margin-top:14px;display:flex;flex-direction:column;gap:10px}
+.scelta-cartella .riga-cartella{margin-top:0}
+.avanzamento-import{padding:20px 22px}
+.grande-misura{height:8px;border-radius:4px;margin:14px 0 8px}
+.grande-misura i{border-radius:4px}
+.conteggio{margin:0;font-weight:600}
+.file-corrente{margin:4px 0 0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.avanzamento-import .riga-azione .avviso{margin:0}
+.importa-resoconto .due-colonne{margin:20px 0}
+.importa-resoconto .blocco{margin-bottom:18px}
+/* confronto dei doppioni */
+.confronto .navigazione{display:flex;align-items:center;gap:2px}
+.confronto .navigazione .muto{margin-right:6px;font-size:13px}
+.confronto-corpo{padding:16px}
+.lati{display:grid;grid-template-columns:1fr 1fr;gap:12px}
+.lato{margin:0;display:flex;flex-direction:column;gap:7px;min-width:0}
+.titolo-lato{display:flex;align-items:center;gap:8px;font-size:13px;min-height:20px}
+.titolo-lato b{font-weight:600}
+.titolo-lato .et{margin-left:auto}
+.immagine-lato{aspect-ratio:1/1.05;border-radius:var(--r-tessera);overflow:hidden;background:var(--fondo);display:flex;align-items:center;justify-content:center}
+.immagine-lato img{width:100%;height:100%;object-fit:cover;display:block}
+.senza-anteprima{display:flex;flex-direction:column;align-items:center;gap:6px;color:var(--testo-3);font-size:12px;text-align:center;padding:10px}
+.dati-lato{display:flex;flex-direction:column;gap:1px;font-size:12px;min-width:0}
+.dati-lato .percorso{color:var(--testo-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.motivo{margin:12px 0 0}
+.scelte-doppione{display:flex;flex-direction:column;gap:10px;margin-top:12px}
+.scelte-doppione .voce{font-size:13.5px}
+.applica-tutti{border-top:1px solid var(--bordo);margin-top:14px;padding-top:12px;font-size:13.5px}
+.pagina-doppioni{max-width:760px}
+.pagina-doppioni > .aiuto{margin-bottom:16px}
+.pagina-doppioni .immagine-lato{aspect-ratio:4/3}
+
+/* ---------- primo avvio e problemi ---------- */
+.benvenuto{display:flex;flex-direction:column;align-items:center;text-align:center;gap:12px;padding:72px 20px 40px;max-width:620px;margin:0 auto}
+.benvenuto h2{margin:6px 0 0;font-size:22px;font-weight:650}
+.benvenuto p{margin:0;color:var(--testo-2);line-height:1.55}
+.marchio-benvenuto svg{width:52px;height:52px}
+.bottoni-benvenuto{display:flex;gap:12px;margin-top:14px;flex-wrap:wrap;justify-content:center}
+.nota-benvenuto{font-size:12.5px;margin-top:18px!important}
+.pagina-problemi{max-width:720px;margin:0 auto;padding:40px 24px;display:flex;flex-direction:column;gap:14px;min-height:100vh}
+.problemi-testa{display:flex;align-items:center;gap:10px;margin-bottom:12px}
+.problemi-testa .marchio-piccolo svg{width:26px;height:26px;display:block}
+.problemi-testa b{font-size:17px;font-weight:650}
+.pagina-problemi h1{margin:0;font-size:24px;font-weight:650}
+.problema{padding:18px 20px;border-color:color-mix(in srgb,var(--rosso) 35%,var(--bordo))}
+.problema h2{display:flex;align-items:center;gap:10px;margin:0 0 6px;font-size:16px;font-weight:650}
+.problema h2 svg{color:var(--rosso)}
+.problema h3{margin:12px 0 2px;font-size:13px;font-weight:600;color:var(--testo-2)}
+.problema p{margin:0;line-height:1.5}
+.problema .rimedio{font-weight:500}
/* ---------- finestra stretta e telefono ---------- */
@media (max-width:1000px){
@@ -644,6 +969,75 @@ a.stato:hover{border-color:var(--bordo-forte)}
.brevi{bottom:72px}
}
+/* ---------- parte 2: finestra stretta e telefono ---------- */
+@media (max-width:1180px){
+ .revisione-colonne{grid-template-columns:minmax(0,1fr) 320px}
+ .pagina-collegamento{grid-template-columns:minmax(0,1fr) 300px}
+ .salva .destra{flex-wrap:wrap;justify-content:flex-end;align-items:center;row-gap:6px}
+ .salva .destra .fuori{flex-basis:100%;max-width:none}
+}
+@media (max-width:1000px){
+ .imp{grid-template-columns:1fr;gap:6px}
+ .imp > nav{position:static;flex-direction:row;overflow-x:auto;gap:4px;padding:0 0 10px;margin-bottom:4px;border-bottom:1px solid var(--bordo)}
+ .imp > nav > a{flex:none}
+ .revisione-colonne,.pagina-collegamento{grid-template-columns:1fr}
+ .bottoni-collegamento{margin-top:8px}
+ .ora-pannello .anteprima{width:220px}
+ .cursori{grid-template-columns:150px minmax(0,1fr) 120px}
+ .passi-import li + li::before{width:12px;margin:0 6px}
+}
+@media (max-width:560px){
+ .testa .testo-btn{display:none}
+ .testa .destra .btn{padding:0 9px}
+ .testa .destra .btn svg.ic{margin:0}
+ .attivita{gap:20px}
+ .ora-pannello{flex-direction:column;align-items:stretch;padding:14px 16px;min-height:0}
+ .ora-pannello .anteprima{display:none}
+ .tetti{grid-template-columns:repeat(2,minmax(0,1fr))}
+ .tetto{padding:12px 14px}
+ .tetto:nth-child(3){border-left:0}
+ .tetto:nth-child(n+3){border-top:1px solid var(--bordo)}
+ .due-colonne{grid-template-columns:1fr}
+ .testa-blocco .legenda{margin-left:0;width:100%;flex-wrap:wrap;gap:10px;font-size:12px}
+ .elenco-attivita li{padding:10px 12px;gap:10px}
+ .elenco-attivita .quando{width:72px}
+ .contatori{grid-template-columns:repeat(2,minmax(0,1fr))}
+ .contatore:nth-child(3){border-left:0}
+ .contatore:nth-child(n+3){border-top:1px solid var(--bordo)}
+ .nomi-file,.aspetto,.campi-telegram,.profili{grid-template-columns:1fr}
+ .cursori{grid-template-columns:1fr;gap:4px}
+ .cursori .valore-cursore{margin-bottom:10px}
+ .cursori .errore-testo{grid-column:1}
+ .riga-cartella{flex-wrap:wrap}
+ .riga-cartella .campo{flex-basis:100%}
+ .riga-cartella .spazio{min-width:0;text-align:left;margin-left:0}
+ .giorni-etichetta{margin-left:0}
+ .passi-import .nome{display:none}
+ .passi-import .qui .nome{display:inline}
+ .tabella-tetti .campo.numero{width:84px}
+ .tabella-tetti .tab td:first-child{width:auto}
+ .tabella-tetti .tab td,.tabella-tetti .tab th{padding-left:10px;padding-right:10px}
+ .salva .nota{flex-basis:100%}
+ .salva .nota.importa-barra-modo{white-space:normal;flex:1 1 0;min-width:0;font-size:12.5px}
+ .salva .destra{width:100%;margin-left:0}
+ .salva .destra .fuori{text-align:left}
+ .esporta-csv .testo-csv{display:none}
+ .esporta-csv{padding:0 10px}
+ .cartelle-account .tab thead{display:none}
+ .cartelle-account .tab,.cartelle-account .tab tbody{display:block}
+ .cartelle-account .tab tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px 12px;padding:12px 14px;border-bottom:1px solid var(--bordo)}
+ .cartelle-account .tab tr:last-child{border-bottom:0}
+ .cartelle-account .tab td{display:block;padding:0;border:0;text-align:left;order:2}
+ .cartelle-account .tab td:first-child{grid-column:1/-1;order:0}
+ .cartelle-account .tab td.col-va{grid-column:1/-1;width:auto;order:1}
+ .cartelle-account .tab td.num::before{content:attr(data-etichetta);display:block;font-size:11.5px;color:var(--testo-2)}
+ .riga-sorgente > b{flex:1 1 0;min-width:0;overflow-wrap:anywhere}
+ .riga-sorgente > .muto{flex-basis:100%}
+ .vista{min-height:360px}
+ .vista-barra > .et{display:none}
+ .benvenuto{padding-top:40px}
+}
+
/* ---------- animazioni: solo in risposta a un gesto, e mai con le animazioni ridotte ---------- */
@keyframes febe-compare{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
.dialogo,.menu,.breve{animation:febe-compare .14s ease-out}
diff --git a/src/Febe.Web/wwwroot/js/app.js b/src/Febe.Web/wwwroot/js/app.js
index 1776087..df062b0 100644
--- a/src/Febe.Web/wwwroot/js/app.js
+++ b/src/Febe.Web/wwwroot/js/app.js
@@ -1,12 +1,13 @@
// Start of the interface: texts, icons, capabilities of the shell, theme, frame, events, router.
import { api, initCarried, setAccess } from './core/api.js';
-import { setCapabilities } from './core/context.js';
+import { caps, setCapabilities } from './core/context.js';
import { loadIcons, h, fill } from './core/dom.js';
import { startEvents } from './core/engine.js';
import { buildShell, startRouter } from './core/shell.js';
import { loadTexts, t } from './core/text.js';
import { initTheme } from './core/theme.js';
+import { showProblems } from './pages/problems.js';
async function boot() {
initCarried();
@@ -26,6 +27,13 @@ async function boot() {
// the defaults describe a plain browser
}
initTheme();
+ const problems = caps().problems || [];
+ if (problems.length) {
+ // Spec §8.2, §11: with a configuration problem the interface shows only the page that explains it.
+ showProblems(root, problems);
+ document.documentElement.removeAttribute('aria-busy');
+ return;
+ }
buildShell(root);
startEvents();
startRouter();
diff --git a/src/Febe.Web/wwwroot/js/core/context.js b/src/Febe.Web/wwwroot/js/core/context.js
index 28148c3..4b32c5a 100644
--- a/src/Febe.Web/wwwroot/js/core/context.js
+++ b/src/Febe.Web/wwwroot/js/core/context.js
@@ -17,6 +17,7 @@ let capabilities = {
scenes: [],
now: Date.now(),
today: '',
+ problems: [],
};
let skew = 0;
diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js
index d891572..3aeb286 100644
--- a/src/Febe.Web/wwwroot/js/core/shell.js
+++ b/src/Febe.Web/wwwroot/js/core/shell.js
@@ -213,7 +213,7 @@ function renderBanner(frame, state) {
return;
}
const isError = banner.level === 'Error';
- const resume = h('button.btn', {
+ const resume = h('button.btn.riprendi-arresto', {
type: 'button',
disabled: !state.canResume,
title: state.canResume ? null : t('arresto.riprendiSpento'),
diff --git a/src/Febe.Web/wwwroot/js/pages/activity.js b/src/Febe.Web/wwwroot/js/pages/activity.js
new file mode 100644
index 0000000..544f58a
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/activity.js
@@ -0,0 +1,306 @@
+// Attività (mockups 06 and 11, spec §7.9): what the engine is doing now with a still frame of the browser every few
+// seconds, the strip of the day, «Limiti di oggi» with the four main budgets and «Tutti i tetti», the queue with
+// «verso le» times, «Appena fatto» with the outcomes, and the stops of the last days. It updates by itself from the
+// event stream (the demo asks every 30 seconds). The red strip of a stop is drawn by the page frame.
+
+import { api, withCarried } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { dotOf, refreshEngine } from '../core/engine.js';
+import { openBrowser } from '../core/shell.js';
+import { t, at, capitalize } from '../core/text.js';
+import { dialog, label, showError, toast } from '../core/ui.js';
+import { dayStrip } from './day-strip.js';
+
+const STOPPED = ['StoppedForVerification', 'Disconnected'];
+
+export default {
+ async mount(page) {
+ page.title(t('attivita.titolo'));
+ const notice = h('div');
+ const now = h('section.ora-pannello.pannello');
+ const preview = previewBox(page);
+ const today = h('section.blocco');
+ const budgets = h('section.blocco');
+ const lists = h('div.due-colonne');
+ const incidents = h('section.blocco');
+ // On this page «Riprendi» is in the title row: the red strip keeps only «Apri il browser» (mockup 11).
+ page.root.dataset.pagina = 'attivita';
+ fill(page.body, h('div.attivita', now, today, budgets, lists, notice, incidents));
+
+ let latest = null;
+ page.onEngine((state) => {
+ latest = state;
+ drawActions(page, state);
+ drawNow(now, preview, state);
+ drawToday(today, state);
+ drawBudgets(budgets, state);
+ drawLists(lists, state);
+ preview.update(state);
+ });
+
+ async function loadSide() {
+ try {
+ const [counts, history] = await Promise.all([
+ api('/api/duplicates/count', { signal: page.signal }),
+ api('/api/engine/incidents', { signal: page.signal }),
+ ]);
+ drawNotice(notice, counts);
+ drawIncidents(incidents, history);
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ }
+ }
+ await loadSide();
+ page.onLibrary(() => loadSide());
+ const timer = setInterval(() => {
+ if (latest && document.visibilityState === 'visible') loadSide();
+ }, 60000);
+ page.onLeave(() => clearInterval(timer));
+ },
+};
+
+// ------------------------------------------------------------------------------------------------- title actions
+
+function drawActions(page, state) {
+ const s = state.snapshot;
+ const resume = async () => {
+ try {
+ const result = await api('/api/engine/resume', { method: 'POST' });
+ toast(result.message, result.resumed ? '' : 'errore');
+ refreshEngine();
+ } catch (error) {
+ showError(error);
+ }
+ };
+ const pause = async () => {
+ try {
+ const result = await api('/api/engine/pause', { method: 'POST' });
+ toast(result.message);
+ refreshEngine();
+ } catch (error) {
+ showError(error);
+ }
+ };
+ const needsResume = s.mode === 'Paused' || (s.banner && s.banner.needsResume);
+ const first = needsResume
+ ? h('button.btn', {
+ type: 'button', onclick: resume, disabled: s.mode !== 'Paused' && !state.canResume,
+ title: s.mode !== 'Paused' && !state.canResume ? t('arresto.riprendiSpento') : null, 'aria-label': t('attivita.riprendi'),
+ }, icon('rotate-cw'), h('span.testo-btn', t('attivita.riprendi')))
+ : h('button.btn', {
+ type: 'button', onclick: pause, disabled: ['Off', 'NotConnected'].includes(s.mode), 'aria-label': t('attivita.pausa'),
+ }, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
+ page.actions(first, h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))));
+}
+
+// ------------------------------------------------------------------------------------------------- now
+
+function drawNow(box, preview, state) {
+ const s = state.snapshot;
+ const dot = dotOf(s.mode);
+ const [first, ...rest] = s.details || [];
+ fill(box,
+ h('div.ora-testo',
+ h('div.riga', h(`span.spia${dot ? '.' + dot : ''}`, { 'aria-hidden': 'true' }), h('b', s.headline)),
+ first ? h('p.cosa', first) : null,
+ rest.length ? h('p.dettaglio', rest.join(' ')) : null,
+ s.reductionNote ? h('p.dettaglio', s.reductionNote) : null),
+ preview.element);
+}
+
+/** The still frame of the browser: one image every few seconds, never a video (mockup 06). */
+function previewBox(page) {
+ const address = h('span.indirizzo.dati');
+ const image = h('img', { alt: t('attivita.anteprima'), hidden: true });
+ const placeholder = h('div.segnaposto-anteprima');
+ const element = h('figure.anteprima', h('figcaption', icon('lock', 'xs'), address), h('div.quadro', image, placeholder));
+ let mode = null;
+ let frameUrl = null;
+ let timer = 0;
+ let stopped = false;
+
+ function placeholderFor(m) {
+ if (m === 'StoppedForVerification') return ['shield-alert', t('attivita.anteprimaVerifica'), 'https://www.instagram.com/challenge/'];
+ if (m === 'Disconnected' || m === 'NotConnected') return ['user', t('attivita.anteprimaAccesso'), null];
+ if (m === 'Off') return ['square', t('attivita.anteprimaSpenta'), null];
+ if (m === 'InSession' || m === 'UserDriving') return ['hourglass', t('attivita.anteprimaAttesa'), null];
+ return ['moon', t('attivita.anteprimaVuota'), 'about:blank'];
+ }
+
+ async function load() {
+ clearTimeout(timer);
+ if (stopped) return;
+ try {
+ const result = await api('/api/browser/preview', { signal: page.signal });
+ if (result.hasFrame && result.frame) {
+ if (result.frame !== frameUrl) {
+ frameUrl = result.frame;
+ image.src = withCarried(result.frame);
+ }
+ image.hidden = false;
+ placeholder.hidden = true;
+ address.textContent = shortUrl(result.url);
+ } else {
+ showPlaceholder();
+ }
+ } catch (error) {
+ if (error.name === 'AbortError') return;
+ showPlaceholder();
+ }
+ const busy = ['InSession', 'UserDriving', ...STOPPED].includes(mode);
+ timer = setTimeout(load, busy ? 5000 : 30000);
+ }
+
+ function showPlaceholder() {
+ frameUrl = null;
+ image.hidden = true;
+ image.removeAttribute('src');
+ const [name, text, url] = placeholderFor(mode);
+ fill(placeholder, icon(name, 'l'), h('span', text));
+ placeholder.hidden = false;
+ address.textContent = url ? shortUrl(url) : '';
+ }
+
+ page.onLeave(() => {
+ stopped = true;
+ clearTimeout(timer);
+ });
+
+ return {
+ element,
+ update(state) {
+ const changed = state.snapshot.mode !== mode;
+ mode = state.snapshot.mode;
+ if (changed) load();
+ },
+ };
+}
+
+function shortUrl(url) {
+ if (!url) return '';
+ return url.replace(/^https?:\/\/(www\.)?/, '').replace(/\/$/, '');
+}
+
+// ------------------------------------------------------------------------------------------------- strip
+
+function drawToday(box, state) {
+ const s = state.snapshot;
+ const { strip, hours, legend } = dayStrip(s.today, { stopOpen: STOPPED.includes(s.mode) });
+ fill(box,
+ h('div.testa-blocco', h('h2', t('attivita.oggi')), h('span.muto', s.today.summary), legend),
+ strip, hours);
+}
+
+// ------------------------------------------------------------------------------------------------- budgets
+
+function drawBudgets(box, state) {
+ const s = state.snapshot;
+ const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
+ const profile = frozen ? t('attivita.congelati', { profilo: s.profileLine }) : s.profileLine;
+ fill(box,
+ h('div.testa-blocco',
+ h('h2', t('attivita.limiti')),
+ h('span.muto', profile),
+ s.reductionNote ? label(s.reductionNote, 'ambra') : null,
+ h('button.btn.collegamento.destra', { type: 'button', onclick: () => allBudgets(state) }, t('attivita.tuttiTetti'))),
+ h('div.tetti.pannello', s.mainBudgets.map((b) => budgetCard(b, frozen))));
+}
+
+function budgetCard(b, frozen) {
+ const meterClass = frozen && b.kind !== 'DataDownload' ? '.grigio' : b.amber ? '.ambra' : '';
+ return h('div.tetto',
+ h('span.nome', b.label),
+ h('div.valore', h('b.dati', b.usedText), h('span', b.limitText)),
+ h(`div.misura${meterClass}`, {
+ role: 'meter', 'aria-label': b.label, 'aria-valuemin': '0', 'aria-valuemax': String(b.limitToday), 'aria-valuenow': String(b.usedToday),
+ }, h('i', { style: { width: `${Math.max(0, Math.min(1, b.ratio)) * 100}%` } })),
+ h('span.nota', b.amber ? h('span', icon('triangle-alert', 'xs'), ' ', b.note) : b.note));
+}
+
+function allBudgets(state) {
+ const s = state.snapshot;
+ const frozen = Boolean(s.banner) || STOPPED.includes(s.mode) || s.mode === 'Throttled';
+ const cell = (used, limit, text, ratio, amber) => h('td',
+ h('div.cella-tetto',
+ h('span.dati', text),
+ limit != null ? h(`div.misura.fine${frozen ? '.grigio' : amber ? '.ambra' : ''}`, h('i', { style: { width: `${Math.max(0, Math.min(1, ratio)) * 100}%` } })) : null));
+ dialog({
+ title: t('attivita.tetti.titolo'),
+ className: 'tutti-tetti',
+ build: (close) => ({
+ body: h('div.contenuto',
+ h('p.aiuto', t('attivita.tetti.aiuto')),
+ h('table.tab',
+ h('thead', h('tr', h('th', t('attivita.tetti.categoria')), h('th', t('attivita.tetti.ora')), h('th', t('attivita.tetti.giorno')))),
+ h('tbody', s.allBudgets.map((b) => h('tr',
+ h('td', h('b', b.label), b.amber ? h('div', label(b.note, 'ambra')) : b.note.startsWith(t('attivita.tetti.ora')) ? null : h('div.muto.piccolo', b.note)),
+ b.limitPerHour == null
+ ? h('td.muto', '—')
+ : cell(b.usedLastHour, b.limitPerHour, t('attivita.tetti.di', { usati: b.usedLastHour, limite: b.limitPerHour }), b.limitPerHour ? b.usedLastHour / b.limitPerHour : 0, b.limitPerHour && b.usedLastHour / b.limitPerHour >= 0.8),
+ cell(b.usedToday, b.limitToday, `${b.usedText} ${b.limitText}`, b.ratio, b.ratio >= 0.8)))))),
+ footer: h('footer',
+ h('a.btn.nudo', { href: withCarried('/impostazioni/limiti'), onclick: () => close() }, icon('sliders-horizontal'), t('attivita.tetti.cambia')),
+ h('div.destra', h('button.btn.primo', { type: 'button', onclick: () => close() }, t('comune.chiudi')))),
+ }),
+ });
+}
+
+// ------------------------------------------------------------------------------------------------- queue and latest actions
+
+function badgeKind(text) {
+ const v = String(text || '').toLowerCase();
+ if (v.includes('in corso')) return 'accento';
+ if (v.includes('scaricat') || v.includes('nuov')) return 'verde';
+ if (v.includes('tutto fermo') || v.includes('verifica') || v.includes('non riuscit')) return 'rosso';
+ if (v.includes('fermo') || v.includes('rallent') || v.includes('tetto')) return 'ambra';
+ return '';
+}
+
+function drawLists(box, state) {
+ const s = state.snapshot;
+ const queue = s.queue.length
+ ? h('ul.elenco-attivita', s.queue.map((q) => h('li',
+ h('span.quando.dati', q.when),
+ h('div.chi-cosa', h('b', q.title), h('span', q.detail)),
+ q.suspended ? label(t('account.sospeso')) : q.isManual ? label(t('attivita.chiesto'), 'accento') : null)))
+ : h('p.vuoto-elenco', t('attivita.codaVuota'));
+ const recent = s.recentActions.length
+ ? h('ul.elenco-attivita', s.recentActions.map((r) => h('li',
+ h('span.quando.dati', r.time),
+ h('div.chi-cosa', h('b', r.title), h('span', r.detail)),
+ r.badge ? label(r.badge, badgeKind(r.badge)) : null)))
+ : h('p.vuoto-elenco', t('attivita.fattoVuoto'));
+ fill(box,
+ h('section', h('h2', t('attivita.coda')), h('div.pannello', queue)),
+ h('section', h('h2', t('attivita.fatto')), h('div.pannello', recent)));
+}
+
+// ------------------------------------------------------------------------------------------------- side information
+
+function drawNotice(box, counts) {
+ if (!counts || !counts.download) {
+ box.replaceChildren();
+ return;
+ }
+ fill(box, h('div.avviso.ambra.avviso-azione', icon('layers', 's'),
+ h('span', t('attivita.doppioni', { n: counts.download })),
+ h('a.btn.piccolo', { href: withCarried('/doppioni') }, t('attivita.decidi'))));
+}
+
+function drawIncidents(box, history) {
+ const items = history.items || [];
+ fill(box,
+ h('div.testa-blocco', h('h2', t('attivita.arresti')), h('span.muto', t('attivita.arrestiAiuto'))),
+ history.advice ? h('div.avviso.ambra', { style: { marginBottom: '10px' } }, icon('triangle-alert', 's'), h('span', history.advice)) : null,
+ items.length
+ ? h('div.pannello', h('ul.elenco-attivita.largo', items.map((i) => h('li',
+ h('span.quando.dati', capitalize(at(i.at))),
+ h('div.chi-cosa',
+ h('b', i.title, ' ', h('span.codice.dati', i.signal)),
+ h('span', [i.note, i.url ? i.url.replace(/^https?:\/\/(www\.)?/, '') : null].filter(Boolean).join(' · '))),
+ i.open
+ ? label(t('attivita.aperto'), i.level === 'throttle' ? 'ambra' : 'rosso')
+ : h('span.muto.piccolo', i.resolvedAt ? t('attivita.risolto', { quando: at(i.resolvedAt) }) : i.stoppedUntil ? t('attivita.fermoFino', { quando: at(i.stoppedUntil) }) : '')))))
+ : h('p.vuoto-elenco.pannello', t('attivita.arrestiVuoti')));
+}
+
diff --git a/src/Febe.Web/wwwroot/js/pages/browser.js b/src/Febe.Web/wwwroot/js/pages/browser.js
new file mode 100644
index 0000000..70aefe7
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/browser.js
@@ -0,0 +1,41 @@
+// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
+// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
+// engine is still; «Ho finito» lets «Riprendi» become active after a verification.
+
+import { api } from '../core/api.js';
+import { caps } from '../core/context.js';
+import { h, icon, fill } from '../core/dom.js';
+import { navigate } from '../core/shell.js';
+import { t } from '../core/text.js';
+import { toast } from '../core/ui.js';
+import { beginDriving, finishDriving, passwordNote, windowPanel } from './connection.js';
+import { remoteView } from './remote-view.js';
+
+export default {
+ async mount(page) {
+ page.title(t('browser.titolo'));
+ const windows = caps().browserWindow;
+ let status = null;
+ try {
+ status = await api('/api/connection', { signal: page.signal });
+ } catch {
+ // the view says whether the browser answers
+ }
+ beginDriving(false);
+ const message = h('div', { 'aria-live': 'polite' });
+ const done = async () => {
+ const result = await finishDriving();
+ if (!result) return;
+ toast(result.message, result.connected ? '' : 'errore');
+ if (result.connected) navigate('/attivita');
+ else fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
+ };
+ page.saveBar(h('div', { style: { display: 'contents' } },
+ h('span.nota', t('browser.aiuto')),
+ h('div.destra', h('button.btn.primo.grande', { type: 'button', onclick: done }, t('impostazioni.collegamento.hoFinito')))));
+ fill(page.body, h('div.pagina-browser',
+ message,
+ windows ? windowPanel() : remoteView(page, { url: status && status.currentUrl, login: status && status.state === 'notConnected' }).element,
+ passwordNote(windows)));
+ },
+};
diff --git a/src/Febe.Web/wwwroot/js/pages/compare.js b/src/Febe.Web/wwwroot/js/pages/compare.js
new file mode 100644
index 0000000..f92e3ae
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/compare.js
@@ -0,0 +1,142 @@
+// The comparison of a probable duplicate (mockup 09, right column; spec §9.3, §9.5): the two files side by side with
+// sizes, dates and accounts, the «Più grande» badge, the three choices and «Fai lo stesso per gli altri». Nothing is
+// chosen in advance. Used by Importa (decisions applied by the copy) and by the review after a download (decisions
+// applied at once, so that one asks for an explicit «Applica la scelta»).
+
+import { h, icon, fill } from '../core/dom.js';
+import { t, bytes, shortDay } from '../core/text.js';
+import { caps } from '../core/context.js';
+import { checkbox, label, radio } from '../core/ui.js';
+
+const CHOICES = [
+ { value: 'keepLarger', key: 'tieniGrande' },
+ { value: 'keepExisting', key: 'tieniLibreria' },
+ { value: 'keepBoth', key: 'tieniEntrambi' },
+];
+
+/**
+ * A comparison panel over a list of cases loaded page by page.
+ * options: load(after) → Promise<{ cases, pending }>; decide(caseItem, decision, applyAll) → Promise<{ pending, reload }>;
+ * labels: { existing, existingInSource, candidate } texts; confirm: true to ask for «Applica la scelta» before deciding.
+ */
+export function comparePanel({ load, decide, labels, confirm = false, empty }) {
+ const counter = h('span.muto.dati');
+ const prev = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('importa.doppioni.precedente'), title: t('importa.doppioni.precedente'), onclick: () => go(-1) }, icon('chevron-left'));
+ const next = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('importa.doppioni.successivo'), title: t('importa.doppioni.successivo'), onclick: () => go(1) }, icon('chevron-right'));
+ const body = h('div.confronto-corpo', { 'aria-live': 'polite' });
+ const element = h('section.confronto',
+ h('div.testa-blocco', h('h2', t('importa.doppioni.titolo')), h('div.destra.navigazione', counter, prev, next)),
+ h('div.pannello', body));
+ let cases = [];
+ let index = 0;
+ let pending = 0;
+ let total = 0;
+ let more = true;
+ let applyAll = false;
+
+ async function fetchMore() {
+ if (!more) return;
+ const after = cases.length ? cases[cases.length - 1].pairId : 0;
+ const page = await load(after);
+ if (page.cases.length === 0) more = false;
+ cases = cases.concat(page.cases);
+ pending = page.pending;
+ total = Math.max(total, cases.length, pending + cases.filter((c) => c.decision !== 'pending').length);
+ }
+
+ async function go(step) {
+ const target = index + step;
+ if (target >= cases.length && more) await fetchMore();
+ if (target < 0 || target >= cases.length) return;
+ index = target;
+ draw();
+ }
+
+ function side(s, title, larger) {
+ const image = s.image
+ ? h('img', { src: s.image, alt: '', loading: 'lazy' })
+ : h('div.senza-anteprima', icon(s.kind === 'video' ? 'clapperboard' : 'image', 'l'), h('span', t('importa.doppioni.senzaAnteprima')));
+ const size = s.width && s.height ? t('importa.doppioni.misure', { l: s.width, a: s.height, peso: bytes(s.bytes || 0) }) : bytes(s.bytes || 0);
+ const where = [s.username, s.date ? shortDay(s.date.day, caps().today) : null].filter(Boolean).join(', ');
+ return h('figure.lato',
+ h('figcaption.titolo-lato', h('b', title), larger ? label(t('importa.doppioni.piuGrande'), 'verde') : null),
+ h('div.immagine-lato', image),
+ h('div.dati-lato', h('span.dati', size), where ? h('span.muto', where) : null, s.path ? h('span.percorso.dati', { title: s.path }, s.path) : null));
+ }
+
+ function draw() {
+ prev.disabled = index <= 0;
+ next.disabled = index >= cases.length - 1 && !more;
+ if (!cases.length) {
+ counter.textContent = '';
+ fill(body, h('p.vuoto-elenco', empty || t('importa.doppioni.nessuno')));
+ return;
+ }
+ const c = cases[index];
+ counter.textContent = t('importa.doppioni.diN', { n: index + 1, totale: total });
+ const name = `scelta-${c.pairId}`;
+ let chosen = c.decision !== 'pending' ? c.decision : null;
+ const apply = h('button.btn.primo', { type: 'button', disabled: true, onclick: () => submit(chosen) }, t('doppioni.conferma'));
+ const radios = CHOICES.map((choice) => radio({
+ name,
+ value: choice.value,
+ checked: c.decision === choice.value,
+ label: t(`importa.doppioni.${choice.key}`),
+ onchange: (v) => {
+ chosen = v;
+ if (confirm) apply.disabled = false;
+ else submit(v);
+ },
+ }));
+ const others = Math.max(0, pending - (c.decision === 'pending' ? 1 : 0));
+ const all = others > 0
+ ? checkbox({ checked: applyAll, label: others === 1 ? t('importa.doppioni.applicaUno') : t('importa.doppioni.applicaTutti', { n: others }), onchange: (v) => { applyAll = v; } })
+ : null;
+ fill(body,
+ h('div.lati',
+ side(c.existing, c.existing.inLibrary ? labels.existing : labels.existingInSource, !c.candidateIsLarger && sizeKnown(c)),
+ side(c.candidate, labels.candidate, c.candidateIsLarger)),
+ h('p.motivo.muto.piccolo', icon('info', 'xs'), ' ', t(`importa.doppioni.motivi.${c.reason}`)),
+ h('div.scelte-doppione', { role: 'radiogroup', 'aria-label': t('importa.doppioni.titolo') }, radios),
+ all ? h('div.applica-tutti', all) : null,
+ confirm ? h('div.riga-azione', apply) : null,
+ pending === 0 ? h('p.muto.piccolo', icon('circle-check', 'xs'), ' ', t('importa.doppioni.fatti')) : null);
+ }
+
+ function sizeKnown(c) {
+ return Boolean(c.existing.width && c.candidate.width) && !c.candidateIsLarger && (c.existing.width * c.existing.height > c.candidate.width * c.candidate.height || (c.existing.bytes || 0) > (c.candidate.bytes || 0));
+ }
+
+ async function submit(decision) {
+ if (!decision) return;
+ const c = cases[index];
+ const result = await decide(c, decision, applyAll);
+ if (!result) return;
+ pending = result.pending;
+ if (result.reload) {
+ cases = [];
+ more = true;
+ index = 0;
+ total = 0;
+ await fetchMore();
+ } else {
+ c.decision = decision;
+ if (index < cases.length - 1) index += 1;
+ }
+ applyAll = false;
+ draw();
+ }
+
+ return {
+ element,
+ async start() {
+ await fetchMore();
+ const firstPending = cases.findIndex((c) => c.decision === 'pending');
+ index = firstPending >= 0 ? firstPending : 0;
+ draw();
+ },
+ get pending() {
+ return pending;
+ },
+ };
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/connection.js b/src/Febe.Web/wwwroot/js/pages/connection.js
new file mode 100644
index 0000000..f34bba9
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/connection.js
@@ -0,0 +1,182 @@
+// Collegamento a Instagram (mockup 10, spec §4.1, §10.3). Docker: the large remote view of the server's browser with
+// the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without
+// being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di
+// Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and
+// «Scollega» with its confirmation. While Alberto uses the browser the engine is still.
+
+import { api } from '../core/api.js';
+import { caps } from '../core/context.js';
+import { h, icon, fill } from '../core/dom.js';
+import { refreshEngine } from '../core/engine.js';
+import { navigate } from '../core/shell.js';
+import { t } from '../core/text.js';
+import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js';
+import { remoteView } from './remote-view.js';
+
+const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' };
+
+/** Starts using the browser (the engine is still); with openLogin the real login page is loaded. */
+export async function beginDriving(openLogin) {
+ try {
+ await api('/api/connection/begin', { method: 'POST', body: { openLogin } });
+ return true;
+ } catch (error) {
+ showError(error);
+ return false;
+ }
+}
+
+/** The area that replaces the remote view on Windows: the browser is its own window. */
+export function windowPanel() {
+ return h('div.vista.vista-finestra',
+ h('div.vista-segnaposto',
+ icon('app-window', 'l'),
+ h('h2', t('impostazioni.collegamento.finestra')),
+ h('p', t('impostazioni.collegamento.finestraTesto')),
+ h('button.btn.primo', { type: 'button', onclick: () => beginDriving(false) }, icon('app-window', 's'), t('impostazioni.collegamento.primoPiano'))));
+}
+
+/** «Ho finito»: Febe checks the session and hides the browser. Returns the answer of the server. */
+export async function finishDriving() {
+ try {
+ const result = await api('/api/connection/finish', { method: 'POST' });
+ refreshEngine();
+ return result;
+ } catch (error) {
+ showError(error);
+ return null;
+ }
+}
+
+export async function mountConnection(page) {
+ page.back(t('pagine.impostazioni'), '/impostazioni');
+ page.title(t('impostazioni.collegamento.titolo'));
+ const stateLabel = h('span');
+ page.head.insertBefore(stateLabel, page.head.children[1] || null);
+ const left = h('div.collega-sinistra');
+ const right = h('div.collega-destra');
+ fill(page.body, h('div.pagina-collegamento', left, right));
+ const windows = caps().browserWindow;
+
+ let status = await api('/api/connection', { signal: page.signal });
+ async function draw() {
+ fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || ''));
+ if (status.state === 'connected') drawConnected();
+ else if (status.state === 'browserUnavailable') drawUnavailable();
+ else drawLogin();
+ }
+
+ // ------------------------------------------------------------------------------------------- login or verification
+ function drawLogin() {
+ const verification = status.state === 'verificationRequired';
+ beginDriving(!verification);
+ fill(left, windows ? windowPanel() : remoteView(page, { url: status.currentUrl, login: !verification }).element);
+ const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi');
+ const message = h('div', { 'aria-live': 'polite' });
+ fill(right,
+ verification
+ ? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto')))
+ : h('div',
+ h('h2.sez', t('impostazioni.collegamento.come')),
+ h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))),
+ passwordNote(windows),
+ h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
+ message,
+ h('div.molla'),
+ h('div.bottoni-collegamento',
+ h('button.btn.grande', { type: 'button', onclick: cancel }, t('impostazioni.collegamento.annulla')),
+ h('button.btn.primo.grande', { type: 'button', onclick: () => finish(message) }, t('impostazioni.collegamento.hoFinito'))));
+ }
+
+ async function cancel() {
+ try {
+ await api('/api/connection/cancel', { method: 'POST' });
+ } catch (error) {
+ showError(error);
+ }
+ navigate('/impostazioni');
+ }
+
+ async function finish(message) {
+ const result = await finishDriving();
+ if (!result) return;
+ if (result.connected) {
+ toast(result.message);
+ status = await api('/api/connection', { signal: page.signal });
+ draw();
+ } else {
+ fill(message, h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', result.message)));
+ }
+ }
+
+ // ------------------------------------------------------------------------------------------- connected
+ function drawConnected() {
+ fill(left, h('div.pannello.collegato',
+ h('div.chi-collegato', avatar(status.username || '', 'g'),
+ h('div', h('h2', t('impostazioni.collegamento.collegatoCome', { nome: status.username || '' })), status.displayName ? h('span.muto', status.displayName) : null)),
+ h('p', t('impostazioni.collegamento.collegatoTesto')),
+ h('div.azioni-collegato',
+ h('button.btn', { type: 'button', onclick: useBrowser }, icon('app-window', 's'), t('impostazioni.collegamento.usaBrowser')),
+ h('button.btn.pericolo', { type: 'button', onclick: disconnect }, icon('log-out', 's'), t('impostazioni.collegamento.scollega'))),
+ h('p.aiuto.piccolo', t('impostazioni.collegamento.usaBrowserTesto'))));
+ fill(right,
+ passwordNote(windows),
+ h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
+ h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))));
+ }
+
+ async function useBrowser() {
+ if (windows) {
+ await beginDriving(false);
+ } else {
+ navigate('/browser');
+ }
+ }
+
+ async function disconnect() {
+ const choice = await confirmDialog({
+ title: t('impostazioni.collegamento.scollegaTitolo'),
+ text: t('impostazioni.collegamento.scollegaTesto'),
+ buttons: [
+ { label: t('comune.annulla'), value: 'no', kind: 'nudo', autofocus: true },
+ { label: t('impostazioni.collegamento.usaPrima'), value: 'browser', kind: '' },
+ { label: t('impostazioni.collegamento.scollegaConferma'), value: 'yes', kind: 'pericolo' },
+ ],
+ });
+ if (choice === 'browser') {
+ useBrowser();
+ return;
+ }
+ if (choice !== 'yes') return;
+ try {
+ await api('/api/connection/disconnect', { method: 'POST' });
+ toast(t('impostazioni.collegamento.scollegato'));
+ refreshEngine();
+ status = await api('/api/connection', { signal: page.signal });
+ draw();
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ // ------------------------------------------------------------------------------------------- unavailable
+ function drawUnavailable() {
+ fill(left, h('div.vista.vista-finestra', h('div.vista-segnaposto',
+ icon('octagon-alert', 'l'),
+ h('h2', t('impostazioni.collegamento.nonDisponibileTitolo')),
+ h('p', t('impostazioni.collegamento.nonDisponibileTesto')))));
+ fill(right, passwordNote(windows), h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))));
+ }
+
+ await draw();
+}
+
+/** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */
+export function passwordNote(windows) {
+ return h('div.avviso.nota-password', icon('shield-check', 's'),
+ h('span', h('b', t('impostazioni.collegamento.passwordTitolo')), ' ', t(windows ? 'impostazioni.collegamento.passwordWindows' : 'impostazioni.collegamento.passwordDocker')));
+}
+
+export default {
+ mount: (page) => mountConnection(page),
+};
diff --git a/src/Febe.Web/wwwroot/js/pages/day-strip.js b/src/Febe.Web/wwwroot/js/pages/day-strip.js
new file mode 100644
index 0000000..4fb8c04
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/day-strip.js
@@ -0,0 +1,91 @@
+// The strip of the day (spec §10.1, §7.9; mockups 06 and 11): a 24-hour bar with the sessions as irregular strokes,
+// the current session highlighted, the planned ones dashed (indicative), night and outside-window hatched, throttles
+// in amber, stops as a red hatch, the «adesso» line, hour ticks and a legend. Every stretch keeps its Italian label
+// from the server as a tooltip; a hidden list repeats them for screen readers.
+
+import { h } from '../core/dom.js';
+import { t } from '../core/text.js';
+
+const HOURS = [0, 3, 6, 9, 12, 15, 18, 21, 24];
+
+/** Milliseconds of a time from the API (ISO text or number). */
+export function ms(value) {
+ return typeof value === 'number' ? value : Date.parse(value);
+}
+
+/** A small deterministic wobble (0..1) from a number: strokes look drawn by hand but stay put between updates. */
+function wobble(n) {
+ const x = Math.sin(n * 12.9898) * 43758.5453;
+ return x - Math.floor(x);
+}
+
+/**
+ * Draws the strip of a DayStrip. Options: stopOpen (an open stop runs to the end of the day, mockup 11).
+ * Returns { strip, hours, legend } so the page can place the legend in its header row.
+ */
+export function dayStrip(day, { stopOpen = false } = {}) {
+ const start = ms(day.start);
+ const end = ms(day.end);
+ const now = ms(day.now);
+ const span = Math.max(1, end - start);
+ const pos = (value) => Math.min(100, Math.max(0, ((ms(value) - start) / span) * 100));
+ const bar = h('div.striscia', { role: 'img', 'aria-label': `${t('attivita.striscia')}: ${day.summary}` });
+ for (const hour of HOURS.slice(1, -1)) bar.append(h('span.tacca', { style: { left: `${(hour / 24) * 100}%` } }));
+
+ const kinds = new Set();
+ const spoken = [];
+ for (const s of day.spans) {
+ const left = pos(s.start);
+ let right = pos(s.end);
+ if (s.kind === 'Stop' && stopOpen && ms(s.end) >= now - 60000) right = 100;
+ const width = Math.max(0, right - left);
+ const style = { left: `${left}%`, width: `${width}%` };
+ let el = null;
+ switch (s.kind) {
+ case 'OutsideWindow':
+ el = h('span.notte', { style });
+ kinds.add('riposo');
+ break;
+ case 'Session':
+ case 'CurrentSession':
+ case 'PlannedSession': {
+ const w = wobble(ms(s.start) / 60000);
+ const inset = 6 + Math.round(w * 4);
+ el = h(`span.sess${s.kind === 'CurrentSession' ? '.ora' : ''}${s.kind === 'PlannedSession' ? '.prev' : ''}`,
+ { style: { ...style, top: `${inset}px`, bottom: `${6 + Math.round((1 - w) * 4)}px` } });
+ kinds.add(s.kind === 'PlannedSession' ? 'prossime' : 'sessione');
+ break;
+ }
+ case 'Throttle':
+ el = h('span.freno', { style });
+ kinds.add('rallentamento');
+ break;
+ case 'Stop':
+ el = h('span.fermo', { style });
+ kinds.add('fermo');
+ break;
+ default:
+ break; // rest between sessions is the plain background
+ }
+ if (el) {
+ el.title = s.label;
+ bar.append(el);
+ if (s.kind !== 'OutsideWindow') spoken.push(s.label);
+ }
+ }
+ if (now >= start && now <= end) {
+ bar.append(h('span.adesso', { style: { left: `${pos(now)}%` }, title: t('attivita.adesso') }));
+ }
+ bar.append(h('ul.vh', spoken.map((label) => h('li', label))));
+
+ const hours = h('div.ore', { 'aria-hidden': 'true' }, HOURS.map((hour) => h('span', { style: { left: `${(hour / 24) * 100}%` } }, String(hour))));
+ const items = [
+ ['sessione', h('i.l-sess')],
+ ['prossime', h('i.l-prev')],
+ ['rallentamento', h('i.l-freno')],
+ ['fermo', h('i.l-fermo')],
+ ['riposo', h('i.l-notte')],
+ ].filter(([key]) => key === 'sessione' || kinds.has(key));
+ const legend = h('div.legenda', items.map(([key, swatch]) => h('span', swatch, t(`attivita.legenda.${key}`))));
+ return { strip: bar, hours, legend };
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/duplicates.js b/src/Febe.Web/wwwroot/js/pages/duplicates.js
new file mode 100644
index 0000000..ecb33fa
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/duplicates.js
@@ -0,0 +1,35 @@
+// Doppioni da decidere (spec §9.5, §10.3): after a download, a photo that looks like one already in the same account
+// waits here for Alberto, with the same comparison as mockup 09. Both files stay until he chooses; the choice is
+// applied at once (so it asks for «Applica la scelta»), and what he discards is remembered and never downloaded again.
+
+import { api } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { refreshEngine } from '../core/engine.js';
+import { t } from '../core/text.js';
+import { showError, toast } from '../core/ui.js';
+import { comparePanel } from './compare.js';
+
+export default {
+ async mount(page) {
+ page.title(t('doppioni.titolo'));
+ const panel = comparePanel({
+ load: (after) => api(`/api/duplicates?after=${after}`, { signal: page.signal }),
+ decide: async (c, decision, applyAll) => {
+ try {
+ const result = await api(`/api/duplicates/${c.pairId}`, { method: 'POST', body: { decision, applyToAll: applyAll } });
+ toast(result.message, result.problems.length ? 'errore' : '');
+ refreshEngine();
+ return { pending: result.pending, reload: true };
+ } catch (error) {
+ showError(error);
+ return null;
+ }
+ },
+ labels: { existing: t('doppioni.esistente'), existingInSource: t('doppioni.esistente'), candidate: t('doppioni.nuovo') },
+ confirm: true,
+ empty: t('doppioni.nessunoTesto'),
+ });
+ fill(page.body, h('div.pagina-doppioni', h('p.aiuto', icon('info', 'xs'), ' ', t('doppioni.aiuto')), panel.element));
+ await panel.start();
+ },
+};
diff --git a/src/Febe.Web/wwwroot/js/pages/import.js b/src/Febe.Web/wwwroot/js/pages/import.js
new file mode 100644
index 0000000..2c6be5f
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/import.js
@@ -0,0 +1,515 @@
+// Importa (mockup 09; spec §9.1, §9.3, §9.4): the four steps in the header (Sorgente, Analisi, Revisione, Copia).
+// 1 a folder (desktop: native picker; Docker: the subfolders of /importa); 2 the read-only analysis with a progress
+// bar, «Interrompi» and «Riprendi»; 3 the review: counters, folders → accounts (a folder without account blocks only its
+// files), the comparison of probable duplicates with nothing chosen in advance, Copia/Sposta («Sposta» hidden for a
+// read-only source), «Importa N file» with the «N restano fuori» line; 4 the copy, then the report with the CSV.
+// Addresses: /importa (the import in progress, or step 1), /importa?passo=1 (a new source), ?passo=3 (the review of
+// the latest import), ?id=N (a given import).
+
+import { api, withCarried } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { navigate, setQuery } from '../core/shell.js';
+import { t, number, bytes, at, capitalize } from '../core/text.js';
+import { checkbox, confirmDialog, dialog, segmented, showError, toast } from '../core/ui.js';
+import { comparePanel } from './compare.js';
+
+const STEPS = ['sorgente', 'analisi', 'revisione', 'copia'];
+const STEP_OF = { analyzing: 2, analysisInterrupted: 2, reviewing: 3, copying: 4, copyInterrupted: 4, completed: 4, cancelled: 1 };
+
+export default {
+ async mount(page, route) {
+ page.title(t('importa.titolo'));
+ const steps = h('ol.passi-import', { 'aria-label': t('importa.passiEtichetta') });
+ page.actions(steps);
+ const overview = await api('/api/import', { signal: page.signal });
+ const wanted = route.query.get('passo');
+ const id = Number(route.query.get('id')) || null;
+ let run = id ? overview.runs.find((r) => r.id === id) : null;
+ if (!run && wanted !== '1') {
+ run = overview.runs.find((r) => r.running)
+ || (wanted === '3' ? overview.runs.find((r) => r.state === 'reviewing') : null)
+ || overview.runs.find((r) => ['analyzing', 'analysisInterrupted', 'reviewing', 'copying', 'copyInterrupted'].includes(r.state));
+ }
+
+ const ctx = { page, overview, steps };
+ if (!run) return sourceStep(ctx);
+ return showRun(ctx, run, wanted);
+ },
+};
+
+function drawSteps(ctx, current) {
+ fill(ctx.steps, STEPS.map((key, i) => {
+ const n = i + 1;
+ const done = n < current || (n === 4 && current === 5);
+ const here = n === current;
+ return h(`li${done ? '.fatto' : ''}${here ? '.qui' : ''}`, { 'aria-current': here ? 'step' : null },
+ h('span.cerchio', done ? icon('check', 'xs') : String(n)),
+ h('span.nome', t(`importa.passi.${key}`)),
+ done ? h('span.vh', t('importa.fatto')) : null);
+ }));
+}
+
+function showRun(ctx, run, wanted) {
+ const step = STEP_OF[run.state] || 1;
+ if (step === 2) return analysisStep(ctx, run);
+ if (step === 3) return reviewStep(ctx, run);
+ if (step === 4) return copyStep(ctx, run, wanted);
+ return sourceStep(ctx);
+}
+
+// ------------------------------------------------------------------------------------------------- step 1: source
+
+async function sourceStep(ctx) {
+ const { page, overview } = ctx;
+ drawSteps(ctx, 1);
+ page.saveBar(null);
+ const chosen = h('div.sorgente-scelta', { 'aria-live': 'polite' });
+ let info = null;
+ let stogram = false;
+
+ async function inspect(path) {
+ try {
+ info = await api('/api/import/inspect', { method: 'POST', body: { path }, signal: page.signal });
+ stogram = false;
+ drawChosen();
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ }
+ }
+
+ function drawChosen() {
+ if (!info) {
+ chosen.replaceChildren();
+ return;
+ }
+ fill(chosen, h('div.pannello.scelta-cartella',
+ h('div.riga-cartella', h('div.campo.sola', icon('folder', 's'), h('span.val.dati', info.displayPath))),
+ info.readOnly ? h('p.aiuto.piccolo', icon('lock', 'xs'), ' ', t('importa.sorgente.solaLettura')) : null,
+ info.looksLikeFebeLibrary ? h('div.avviso', icon('info', 's'), h('span', t('importa.sorgente.febe'))) : null,
+ info.looksLikeStogram ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.sorgente.stogramAiuto'))) : null,
+ info.looksLikeStogram ? checkbox({ checked: false, label: t('importa.sorgente.stogram'), onchange: (v) => { stogram = v; } }) : null,
+ h('div.riga-azione', h('button.btn.primo', { type: 'button', onclick: start }, icon('search', 's'), t('importa.sorgente.analizza')))));
+ }
+
+ async function start() {
+ try {
+ const run = await api('/api/import/start', { method: 'POST', body: { path: info.path, stogram } });
+ setQuery({ passo: null, id: String(run.id) }, { replace: true });
+ analysisStep(ctx, run);
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ // Docker: the subfolders of the root; desktop: the native picker.
+ const picker = h('div');
+ if (overview.sourceRoot) {
+ const browse = async (path) => {
+ try {
+ const list = await api(`/api/import/sources${path ? `?path=${encodeURIComponent(path)}` : ''}`, { signal: page.signal });
+ fill(picker, h('div.pannello.sfoglia',
+ h('div.sfoglia-testa', icon('folder-open', 's'), h('span.dati', list.displayPath),
+ list.parent != null ? h('button.btn.nudo.piccolo.destra', { type: 'button', onclick: () => browse(list.parent || null) }, icon('arrow-left', 's'), t('importa.sorgente.su')) : null),
+ list.folders.length
+ ? h('ul.sfoglia-elenco', list.folders.map((f) => h('li',
+ h('button.sfoglia-voce', { type: 'button', onclick: () => inspect(f.path) }, icon('folder', 's'), h('span', f.name)),
+ f.hasSubfolders ? h('button.btn.nudo.solo', { type: 'button', 'aria-label': `${t('importa.sorgente.apri')} ${f.name}`, onclick: () => browse(f.path) }, icon('chevron-right', 's')) : null)))
+ : h('p.vuoto-elenco', t('importa.sorgente.vuota'))));
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ }
+ };
+ await browse(null);
+ } else {
+ fill(picker, h('div.riga-azione', h('button.btn.primo.grande', {
+ type: 'button',
+ disabled: !overview.pickFolder,
+ onclick: async () => {
+ try {
+ const result = await api('/api/import/pick-folder', { method: 'POST' });
+ if (result.path) inspect(result.path);
+ } catch (error) {
+ showError(error);
+ }
+ },
+ }, icon('folder-open', 's'), t('importa.sorgente.scegli'))));
+ }
+
+ const previous = overview.runs.length
+ ? h('div.sezione',
+ h('h2.sez', t('importa.sorgente.precedenti')),
+ h('div.pannello', h('ul.elenco-attivita', overview.runs.map((r) => h('li',
+ h('span.quando.dati', capitalize(at(r.started))),
+ h('div.chi-cosa', h('b.dati', r.displayPath), h('span', t(`importa.sorgente.stati.${r.state}`))),
+ h('a.btn.piccolo', { href: withCarried(`/importa?id=${r.id}`) }, t('importa.sorgente.apri')))))))
+ : null;
+
+ fill(page.body, h('div.importa-sorgente',
+ h('div.sezione',
+ h('h2.sez', t('importa.sorgente.titolo')),
+ h('p.aiuto', t('importa.sorgente.aiuto')),
+ overview.sourceRoot ? h('p.aiuto', t('importa.sorgente.aiutoDocker', { radice: overview.sourceRoot })) : null,
+ picker,
+ chosen),
+ previous));
+}
+
+// ------------------------------------------------------------------------------------------------- step 2: analysis
+
+function progressCard(ctx, run, { title, help, counting, interruptedText, resumeLabel }) {
+ const { page } = ctx;
+ const bar = h('div.misura.grande-misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100' }, h('i'));
+ const count = h('p.conteggio.dati');
+ const current = h('p.aiuto.piccolo.file-corrente');
+ const found = h('p.aiuto');
+ const buttons = h('div.riga-azione');
+ const card = h('div.pannello.avanzamento-import', h('h2.sez', title), h('p.aiuto', help), bar, count, current, found, buttons);
+ fill(page.body, h('div.importa-avanzamento', h('div.riga-sorgente', icon('folder', 's'), h('b.dati', run.displayPath)), card));
+ let timer = 0;
+ let stopped = false;
+ page.onLeave(() => {
+ stopped = true;
+ clearTimeout(timer);
+ });
+
+ return async function poll(onDone) {
+ if (stopped) return;
+ let progress;
+ try {
+ progress = await api(`/api/import/${run.id}/progress`, { signal: page.signal });
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ return;
+ }
+ const percent = Math.round(progress.fraction * 100);
+ bar.firstChild.style.width = `${percent}%`;
+ bar.setAttribute('aria-valuenow', String(percent));
+ count.textContent = progress.phase === 'listing' ? t('importa.analisi.elenco') : counting(progress);
+ current.textContent = progress.currentFile ? t('importa.analisi.ora', { file: progress.currentFile }) : '';
+ const o = progress.outcomes;
+ found.textContent = t('importa.analisi.trovati', { nuovi: number(o.new), gia: number(o.alreadyInLibrary + o.identicalInSource), doppioni: number(o.probableDuplicates), altri: number(o.unrecognized) });
+ const interrupted = progress.state === 'analysisInterrupted' || progress.state === 'copyInterrupted';
+ if (progress.running) {
+ fill(buttons, h('button.btn', { type: 'button', onclick: interrupt }, icon('pause', 's'), t('importa.analisi.interrompi')));
+ } else if (interrupted) {
+ fill(buttons,
+ h('p.avviso.ambra', icon('pause', 's'), h('span', interruptedText)),
+ h('button.btn.primo', { type: 'button', onclick: resume }, icon('play', 's'), resumeLabel),
+ h('button.btn.nudo', { type: 'button', onclick: discard }, t('importa.analisi.annulla')));
+ }
+ if (progress.error && !progress.running) fill(current, h('span.errore-testo', progress.error));
+ if (!progress.running && !interrupted) {
+ onDone(progress);
+ return;
+ }
+ timer = setTimeout(() => poll(onDone), progress.running ? 1000 : 5000);
+ };
+
+ async function interrupt() {
+ try {
+ const result = await api(`/api/import/${run.id}/interrupt`, { method: 'POST' });
+ toast(result.message);
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ async function resume() {
+ try {
+ await api(`/api/import/${run.id}/resume`, { method: 'POST' });
+ navigate(`/importa?id=${run.id}`, { replace: true });
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ async function discard() {
+ const ok = await confirmDialog({
+ title: t('importa.analisi.annullaTitolo'),
+ text: t('importa.analisi.annullaTesto'),
+ buttons: [
+ { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
+ { label: t('importa.analisi.annulla'), value: true, kind: 'pericolo' },
+ ],
+ });
+ if (!ok) return;
+ try {
+ const result = await api(`/api/import/${run.id}/discard`, { method: 'POST' });
+ toast(result.message);
+ navigate('/importa?passo=1', { replace: true });
+ } catch (error) {
+ showError(error);
+ }
+ }
+}
+
+function analysisStep(ctx, run) {
+ drawSteps(ctx, 2);
+ ctx.page.saveBar(null);
+ const poll = progressCard(ctx, run, {
+ title: t('importa.analisi.titolo'),
+ help: t('importa.analisi.aiuto'),
+ counting: (p) => t('importa.analisi.conteggio', { fatti: number(p.filesDone), totale: number(p.filesTotal) }),
+ interruptedText: t('importa.analisi.interrotta'),
+ resumeLabel: t('importa.analisi.riprendi'),
+ });
+ poll(() => reviewStep(ctx, run));
+}
+
+// ------------------------------------------------------------------------------------------------- step 3: review
+
+async function reviewStep(ctx, run) {
+ const { page } = ctx;
+ drawSteps(ctx, 3);
+ let review;
+ try {
+ review = await api(`/api/import/${run.id}/review`, { signal: page.signal });
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ return;
+ }
+
+ const counters = h('div.contatori.pannello');
+ const table = h('tbody');
+ const notes = h('div');
+ const compare = comparePanel({
+ load: (after) => api(`/api/import/${run.id}/duplicates?all=true&after=${after}`, { signal: page.signal }),
+ decide: async (c, decision, applyAll) => {
+ try {
+ const result = await api(`/api/import/${run.id}/duplicates/${c.pairId}`, { method: 'POST', body: { decision, applyToAll: applyAll } });
+ review = await api(`/api/import/${run.id}/review`, { signal: page.signal });
+ drawCounters();
+ drawBar();
+ return { pending: result.pending, reload: applyAll };
+ } catch (error) {
+ showError(error);
+ return null;
+ }
+ },
+ labels: { existing: t('importa.doppioni.inLibreria'), existingInSource: t('importa.doppioni.nellaSorgente'), candidate: t('importa.doppioni.daImportare') },
+ });
+
+ function counter(kind, value, key) {
+ return h('div.contatore', h('div.riga', h(`span.spia${kind ? '.' + kind : ''}`, { 'aria-hidden': 'true' }), h('b.dati', number(value))),
+ h('span.nome', t(`importa.revisione.contatori.${key}.titolo`)), h('span.muto', t(`importa.revisione.contatori.${key}.testo`)));
+ }
+
+ function drawCounters() {
+ const o = review.outcomes;
+ fill(counters,
+ counter('verde', o.new, 'new'),
+ counter('', o.alreadyInLibrary + o.identicalInSource, 'already'),
+ counter('ambra', o.probableDuplicates, 'dup'),
+ counter('grigio', o.unrecognized, 'unrec'));
+ }
+
+ function targetSelect(folder) {
+ const select = h('select', { 'aria-label': `${t('importa.revisione.colonne.va')}: ${folder.displayName || review.displayPath}` });
+ const target = folder.target;
+ const proposed = target.kind === 'newArchiveAccount' ? target.username
+ : folder.probableAccount && !review.accounts.some((a) => a.username === folder.probableAccount) ? folder.probableAccount : null;
+ select.append(h('option', { value: 'none' }, t('importa.revisione.scegli')));
+ if (proposed) select.append(h('option', { value: `new:${proposed}`, title: `@${proposed}` }, t('importa.revisione.nuovo')));
+ select.append(h('option', { value: 'ask' }, t('importa.revisione.nuovoAltro')));
+ select.append(h('optgroup', { label: t('importa.revisione.esistenti') }, review.accounts.map((a) => h('option', { value: `id:${a.id}` }, `@${a.username}`))));
+ select.value = target.kind === 'existing' ? `id:${target.accountId}` : target.kind === 'newArchiveAccount' ? `new:${target.username}` : 'none';
+ select.addEventListener('change', async () => {
+ const v = select.value;
+ let body;
+ if (v === 'none') body = { folder: folder.folder, kind: 'none' };
+ else if (v.startsWith('id:')) body = { folder: folder.folder, kind: 'existing', accountId: Number(v.slice(3)) };
+ else if (v.startsWith('new:')) body = { folder: folder.folder, kind: 'newArchiveAccount', username: v.slice(4) };
+ else {
+ const name = await askName(proposed || folder.displayName || '');
+ if (!name) {
+ drawTable();
+ return;
+ }
+ body = { folder: folder.folder, kind: 'newArchiveAccount', username: name };
+ }
+ try {
+ review = await api(`/api/import/${run.id}/folders`, { method: 'PUT', body });
+ drawAll();
+ } catch (error) {
+ showError(error);
+ drawTable();
+ }
+ });
+ const blocked = folder.blocked && folder.files > folder.unrecognized;
+ return h(`label.campo.scelta${blocked ? '.errore' : ''}`, { title: target.kind === 'newArchiveAccount' ? t('importa.revisione.nuovoNome', { nome: target.username }) : null }, select, icon('chevron-down', 's'));
+ }
+
+ function drawTable() {
+ fill(table, review.folders.map((f) => h('tr',
+ h('td', h('b', f.displayName || review.displayPath), f.blocked && !f.probableAccount ? h('div.muto.piccolo', t('importa.revisione.nessunNome')) : null),
+ h('td.num.dati', { 'data-etichetta': t('importa.revisione.colonne.file') }, number(f.files)),
+ h('td.col-va', targetSelect(f)),
+ h('td.num.dati', { 'data-etichetta': t('importa.revisione.colonne.nuovi') }, number(f.new)),
+ h('td.num.dati', { 'data-etichetta': t('importa.revisione.colonne.presenti') }, number(f.alreadyInLibrary)))));
+ }
+
+ function drawNotes() {
+ fill(notes,
+ review.recognized > 0 ? h('div.avviso', icon('info', 's'), h('span', t('importa.revisione.riconosciuti', { n: number(review.recognized) }))) : null,
+ review.stogramHypothesis ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.stogram'))) : null);
+ }
+
+ // The fixed bar: Copia/Sposta, what stays out, CSV, «Importa N file».
+ let mode = review.plan.mode;
+ function drawBar() {
+ const plan = review.plan;
+ const modes = review.canMove
+ ? segmented({
+ label: t('importa.barra.modo'),
+ value: mode,
+ options: [{ value: 'copy', label: t('importa.barra.copia') }, { value: 'move', label: t('importa.barra.sposta') }],
+ onchange: async (v) => {
+ try {
+ review.plan = await api(`/api/import/${run.id}/mode`, { method: 'PUT', body: { mode: v } });
+ mode = v;
+ drawBar();
+ } catch (error) {
+ showError(error);
+ }
+ },
+ })
+ : h('div.gruppo', h('span.qui', t('importa.barra.copia')));
+ page.saveBar(h('div', { style: { display: 'contents' } },
+ modes,
+ h('span.nota.importa-barra-modo', t(mode === 'move' ? 'importa.barra.spostaAiuto' : 'importa.barra.copiaAiuto')),
+ h('div.destra',
+ plan.leftOutLabel ? h('span.nota.fuori', plan.leftOutLabel) : null,
+ h('a.btn.esporta-csv', { href: `/api/import/${run.id}/report.csv`, download: '', title: t('importa.barra.esporta') }, icon('file-down', 's'), h('span.testo-csv', t('importa.barra.esporta'))),
+ h('button.btn.primo', { type: 'button', disabled: plan.toImport === 0, onclick: startCopy }, plan.buttonLabel))));
+ }
+
+ async function startCopy() {
+ if (mode === 'move') {
+ const ok = await confirmDialog({
+ title: t('importa.sposta.titolo'),
+ text: t('importa.sposta.testo'),
+ buttons: [
+ { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
+ { label: t('importa.sposta.conferma'), value: true, kind: 'primo' },
+ ],
+ });
+ if (!ok) return;
+ }
+ try {
+ const updated = await api(`/api/import/${run.id}/copy`, { method: 'POST', body: { mode } });
+ copyStep(ctx, updated);
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ function drawAll() {
+ drawCounters();
+ drawTable();
+ drawNotes();
+ drawBar();
+ }
+
+ drawAll();
+ fill(page.body, h('div.importa-revisione',
+ h('div.riga-sorgente', icon('folder', 's'), h('b.dati', review.displayPath), h('span.muto', review.headline),
+ h('a.btn.collegamento.destra', { href: withCarried('/importa?passo=1') }, t('importa.revisione.cambia'))),
+ counters,
+ h('div.revisione-colonne',
+ h('section.cartelle-account',
+ h('h2', t('importa.revisione.cartelle')),
+ h('div.pannello', h('table.tab',
+ h('thead', h('tr',
+ h('th', t('importa.revisione.colonne.cartella')),
+ h('th.num', t('importa.revisione.colonne.file')),
+ h('th', t('importa.revisione.colonne.va')),
+ h('th.num', t('importa.revisione.colonne.nuovi')),
+ h('th.num', t('importa.revisione.colonne.presenti')))),
+ table)),
+ notes),
+ compare.element)));
+ await compare.start();
+}
+
+// ------------------------------------------------------------------------------------------------- step 4: copy and report
+
+function copyStep(ctx, run) {
+ if (run.state === 'completed' || run.state === 'cancelled') return reportStep(ctx, run);
+ drawSteps(ctx, 4);
+ ctx.page.saveBar(null);
+ const poll = progressCard(ctx, run, {
+ title: t('importa.copia.titolo'),
+ help: t('importa.copia.aiuto'),
+ counting: (p) => t('importa.copia.conteggio', { fatti: number(p.filesDone), totale: number(p.filesTotal), copiati: number(p.copied) }),
+ interruptedText: t('importa.copia.interrotta'),
+ resumeLabel: t('importa.copia.riprendi'),
+ });
+ poll(async () => {
+ const latest = await api(`/api/import/${run.id}/progress`, { signal: ctx.page.signal });
+ reportStep(ctx, { ...run, state: latest.state });
+ });
+}
+
+async function reportStep(ctx, run) {
+ const { page } = ctx;
+ drawSteps(ctx, 5);
+ page.saveBar(null);
+ let report;
+ try {
+ report = await api(`/api/import/${run.id}/report`, { signal: page.signal });
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ return;
+ }
+ const big = (value, key, kind = '') => h('div.contatore', h('div.riga', kind ? h(`span.spia.${kind}`, { 'aria-hidden': 'true' }) : null, h('b.dati', number(value))), h('span.nome', t(`importa.resoconto.${key}`)));
+ const accounts = (items) => items.length
+ ? h('ul.elenco-semplice', items.map((a) => h('li', h('span', `@${a.username}`), h('span.dati', number(a.files)))))
+ : h('p.muto', t('importa.resoconto.nessuno'));
+ const done = report.run.completed ? at(report.run.completed) : '';
+ fill(page.body, h('div.importa-resoconto',
+ h('div.riga-sorgente', icon('folder', 's'), h('b.dati', report.displayPath),
+ h('span.muto', report.run.state === 'cancelled' ? t('importa.resoconto.annullata') : t('importa.resoconto.completata', { quando: done }))),
+ h('div.contatori.pannello',
+ big(report.copied, 'copiati', 'verde'),
+ big(report.skipped, 'saltati'),
+ big(report.leftOut, 'fuori', report.leftOut ? 'ambra' : ''),
+ big(report.failed, 'falliti', report.failed ? 'rosso' : '')),
+ report.moved || report.replaced
+ ? h('p.aiuto', [report.moved ? `${t('importa.resoconto.spostati')}: ${number(report.moved)}` : null, report.replaced ? `${t('importa.resoconto.sostituiti')}: ${number(report.replaced)}` : null].filter(Boolean).join(' · '), ` · ${bytes(report.bytesCopied)}`)
+ : h('p.aiuto', bytes(report.bytesCopied)),
+ h('div.due-colonne',
+ h('section', h('h2', t('importa.resoconto.perAccount')), h('div.pannello', accounts(report.importedByAccount))),
+ h('section', h('h2', t('importa.resoconto.giaPerAccount')), h('div.pannello', accounts(report.alreadyInLibraryByAccount)))),
+ report.unrecognized.length ? h('section.blocco', h('h2', t('importa.resoconto.nonRiconosciuti')),
+ h('div.pannello', h('ul.elenco-semplice', report.unrecognized.map((u) => h('li.dati', u))))) : null,
+ report.problems.length ? h('section.blocco', h('h2', t('importa.resoconto.problemi')),
+ h('div.pannello', h('ul.elenco-semplice', report.problems.map((p) => h('li', h('span.dati', p.path), h('span.muto', p.note)))))) : null,
+ h('div.riga-azione',
+ h('a.btn', { href: `/api/import/${run.id}/report.csv`, download: '' }, icon('file-down', 's'), t('importa.barra.esporta')),
+ report.leftOut > 0 && report.run.state === 'completed' ? h('button.btn', { type: 'button', onclick: () => reviewStep(ctx, report.run) }, t('importa.resoconto.rimasti')) : null,
+ h('a.btn', { href: withCarried('/importa?passo=1') }, icon('plus', 's'), t('importa.resoconto.nuova')),
+ h('a.btn.primo', { href: withCarried('/libreria?provenienza=importati') }, icon('layout-grid', 's'), t('importa.resoconto.libreria')))));
+}
+
+/** The name of a new «Solo archivio» account (a user name: letters, digits, dots and underscores). */
+function askName(proposed) {
+ return dialog({
+ title: t('importa.revisione.nuovoChiedi'),
+ className: 'piccolo',
+ build: (close) => {
+ const input = h('input.dati', { type: 'text', value: proposed, autocomplete: 'off', spellcheck: 'false', id: 'nuovo-account' });
+ const ok = () => {
+ const name = input.value.trim().replace(/^@/, '');
+ if (/^[A-Za-z0-9._]{1,30}$/.test(name)) close(name);
+ else input.parentElement.classList.add('errore');
+ };
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter') ok(); });
+ return {
+ body: h('div.contenuto', h('label.etichetta', { for: 'nuovo-account' }, t('importa.revisione.nuovoChiedi')), h('label.campo', input), h('p.aiuto.piccolo', t('importa.revisione.nomeRegole'))),
+ footer: h('footer', h('div.destra',
+ h('button.btn.nudo', { type: 'button', onclick: () => close(null) }, t('comune.annulla')),
+ h('button.btn.primo', { type: 'button', onclick: ok }, t('importa.revisione.nuovo')))),
+ };
+ },
+ });
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/library.js b/src/Febe.Web/wwwroot/js/pages/library.js
index 36c82a9..f98980d 100644
--- a/src/Febe.Web/wwwroot/js/pages/library.js
+++ b/src/Febe.Web/wwwroot/js/pages/library.js
@@ -1,13 +1,15 @@
// Libreria (mockup 01, spec §4.6): every entry by publication day, filters by kind, account, period and provenance,
// search by account name and caption, tile size, multiple selection to export or delete, viewer on click.
-import { api, download } from '../core/api.js';
+import { api, download, withCarried } from '../core/api.js';
import { caps } from '../core/context.js';
import { h, icon, fill, later, local } from '../core/dom.js';
import { setQuery } from '../core/shell.js';
import { t, number, shortDay, parseDay } from '../core/text.js';
import { menu, showError, toast, confirmDialog } from '../core/ui.js';
+import { engineState } from '../core/engine.js';
import { Mosaic } from './mosaic.js';
+import { welcome } from './welcome.js';
import { openViewer } from './viewer.js';
const KINDS = [
@@ -89,11 +91,19 @@ export default {
const size = local.get('libreria.tessere', 160);
const slider = h('input.cursore', { type: 'range', min: '96', max: '300', step: '4', value: String(size), 'aria-label': t('libreria.grandezza') });
const selectButton = h('button.btn', { type: 'button', 'aria-pressed': 'false' }, icon('circle-check'), h('span', t('libreria.seleziona')));
+ // Probable duplicates after a download wait for Alberto (spec §9.5): a short link to their review.
+ const duplicates = h('a.btn.nudo.piccolo.doppioni-link', { href: withCarried('/doppioni'), hidden: true });
+ api('/api/duplicates/count', { signal: page.signal }).then((counts) => {
+ if (!counts.download) return;
+ fill(duplicates, icon('layers', 's'), t('libreria.doppioni', { n: counts.download }));
+ duplicates.hidden = false;
+ }).catch(() => {});
page.tools(h('div', { style: { display: 'contents' } },
chips,
h('div.scelte-menu.solo-largo', accountButton, periodButton, provenanceButton),
filtersButton,
h('div.destra',
+ duplicates,
h('div.grandezza.solo-largo', { title: t('libreria.grandezza') }, icon('grid-3x3', 's'), slider, icon('square', 's')),
selectButton)));
@@ -323,7 +333,9 @@ export default {
onEmpty: () => fill(host, filtersActive()
? h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')))
- : h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
+ : notConnected()
+ ? welcome()
+ : h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
});
try {
await mosaic.start();
@@ -371,3 +383,9 @@ export async function confirmDelete(ids) {
return null;
}
}
+
+/** First start (spec §10.3): not connected to Instagram, so the empty library offers the two ways to begin. */
+function notConnected() {
+ const state = engineState();
+ return Boolean(state && state.connection && state.connection.state === 'notConnected');
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/placeholder.js b/src/Febe.Web/wwwroot/js/pages/placeholder.js
index 95ac3e0..fcb1f54 100644
--- a/src/Febe.Web/wwwroot/js/pages/placeholder.js
+++ b/src/Febe.Web/wwwroot/js/pages/placeholder.js
@@ -1,5 +1,4 @@
-// Pages that arrive with the second part of the interface (Attività, Importa, Impostazioni, Browser), and the page for
-// unknown addresses. The next agent replaces each route of js/routes.js with its own module.
+// The page for unknown addresses («Pagina non trovata»).
import { h, icon, fill } from '../core/dom.js';
import { withCarried } from '../core/api.js';
@@ -14,8 +13,6 @@ export default {
h('a.btn', { href: withCarried('/libreria') }, t('pagine.vaiLibreria'))));
return;
}
- const title = route.params.section ? `${t('pagine.impostazioni')}: ${t(`pagine.sezioni.${route.params.section}`)}` : t(`pagine.${key}`);
- page.title(title);
- fill(page.body, h('div.vuoto-pagina.prossimamente', icon('hourglass'), h('h2', title), h('p', t('pagine.prossimamente'))));
+ page.title(t(`pagine.${key}`));
},
};
diff --git a/src/Febe.Web/wwwroot/js/pages/problems.js b/src/Febe.Web/wwwroot/js/pages/problems.js
new file mode 100644
index 0000000..0df3e7e
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/problems.js
@@ -0,0 +1,22 @@
+// The configuration error page (spec §8.2, §11): when GET /api/capabilities lists problems (missing FEBE_PASSWORD,
+// Data folder not writable or on a network share, WebView2 missing) the engine does not start and the interface shows
+// only this page: for each problem what is wrong, what Febe did and what to do.
+
+import { h, icon, fill, brand } from '../core/dom.js';
+import { t } from '../core/text.js';
+
+export function showProblems(root, problems) {
+ document.title = t('app.titoloPagina', { pagina: t('problemi.titolo') });
+ fill(root, h('main.pagina-problemi', { id: 'contenuto' },
+ h('div.problemi-testa', h('span.marchio-piccolo', brand()), h('b', t('app.nome'))),
+ h('h1', t('problemi.titolo')),
+ h('p.aiuto', t('problemi.aiuto', { n: problems.length })),
+ problems.map((p) => h('section.pannello.problema', { 'data-codice': p.code },
+ h('h2', icon('octagon-alert', 'l'), h('span', p.title)),
+ h('h3', t('problemi.cosa')),
+ h('p', p.message),
+ h('h3', t('problemi.rimedio')),
+ h('p.rimedio', p.remedy))),
+ h('div.riga-azione', h('button.btn.primo', { type: 'button', onclick: () => location.reload() }, icon('refresh-cw', 's'), t('problemi.ricarica'))),
+ h('p.aiuto.piccolo', t('problemi.guida'))));
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/remote-view.js b/src/Febe.Web/wwwroot/js/pages/remote-view.js
new file mode 100644
index 0000000..64cda1d
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/remote-view.js
@@ -0,0 +1,178 @@
+// The remote view of Febe's browser (Docker; spec §4.1, §11, mockup 10; protocol in src/Febe.Web/Connection/PROTOCOLLO.md):
+// JPEG frames from the WebSocket /api/vista drawn on a canvas, mouse and keyboard sent back as relative coordinates and
+// key messages. Keys are never logged or kept here: they go straight to the socket. The page of Instagram is never
+// redrawn or imitated: without a browser (demo, or the server not answering) the area shows a neutral placeholder.
+
+import { caps } from '../core/context.js';
+import { h, icon, fill, perFrame } from '../core/dom.js';
+import { t } from '../core/text.js';
+import { label } from '../core/ui.js';
+
+const BUTTONS = ['left', 'middle', 'right'];
+
+/** Modifier bits of the DevTools protocol: Alt 1, Ctrl 2, Meta 4, Shift 8. */
+function modifiers(e) {
+ return (e.altKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.metaKey ? 4 : 0) | (e.shiftKey ? 8 : 0);
+}
+
+/**
+ * Builds the remote view. options: url (address to show before the first frame), login (the placeholder speaks of the
+ * login page). Returns { element, close }. The socket closes when the page is left.
+ */
+export function remoteView(page, { url = null, login = false } = {}) {
+ const address = h('span.dati');
+ const back = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.indietro'), title: t('browser.indietro'), onclick: () => send({ type: 'navigate', action: 'back' }) }, icon('arrow-left'));
+ const reload = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.ricarica'), title: t('browser.ricarica'), onclick: () => send({ type: 'navigate', action: 'reload' }) }, icon('rotate-cw'));
+ const bar = h('div.vista-barra',
+ back, reload,
+ h('div.vista-indirizzo', { 'aria-label': t('browser.indirizzo') }, icon('lock', 's'), address),
+ label(t('browser.vista')));
+ const canvas = h('canvas.vista-schermo', { tabindex: '0', 'aria-label': t('browser.schermo'), hidden: true, width: '1280', height: '900' });
+ const status = h('div.vista-stato');
+ const area = h('div.vista-area', canvas, status);
+ const element = h('div.vista', bar, area);
+ const context = canvas.getContext('2d');
+ let socket = null;
+ let closed = false;
+ let frames = 0;
+
+ function showAddress(value) {
+ if (!value) {
+ address.replaceChildren();
+ return;
+ }
+ const clean = String(value).replace(/^https?:\/\//, '');
+ const slash = clean.indexOf('/');
+ fill(address, h('b', slash < 0 ? clean : clean.slice(0, slash)), slash < 0 ? '' : clean.slice(slash));
+ }
+
+ /** The neutral placeholder of mockup 10: never a drawing of Instagram's page. */
+ function placeholder() {
+ canvas.hidden = true;
+ fill(status, h('div.vista-segnaposto',
+ h('div.scheletro', { 'aria-hidden': 'true' }, h('i.s1'), h('i.s2'), h('i.s2'), h('i.s3'), h('i.s4')),
+ h('p', t(login ? 'browser.segnapostoAccesso' : 'browser.segnaposto'))));
+ status.hidden = false;
+ }
+
+ function failure() {
+ canvas.hidden = true;
+ fill(status, h('div.vista-segnaposto',
+ icon('triangle-alert', 'l'),
+ h('p', t('browser.nonRisponde')),
+ h('button.btn', { type: 'button', onclick: connect }, icon('refresh-cw', 's'), t('browser.riprova'))));
+ status.hidden = false;
+ }
+
+ function send(message) {
+ if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
+ }
+
+ function connect() {
+ if (closed) return;
+ if (caps().demo) {
+ placeholder();
+ return;
+ }
+ fill(status, h('div.vista-segnaposto', icon('hourglass', 'l'), h('p', t('browser.collegamento'))));
+ status.hidden = false;
+ const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
+ try {
+ socket = new WebSocket(`${scheme}://${location.host}/api/vista`);
+ } catch {
+ failure();
+ return;
+ }
+ socket.binaryType = 'blob';
+ socket.addEventListener('message', async (e) => {
+ if (typeof e.data === 'string') {
+ try {
+ const meta = JSON.parse(e.data);
+ if (meta.type === 'meta') {
+ if (meta.width && meta.height && (canvas.width !== meta.width || canvas.height !== meta.height)) {
+ canvas.width = meta.width;
+ canvas.height = meta.height;
+ }
+ showAddress(meta.url);
+ }
+ } catch {
+ // not a message of the protocol
+ }
+ return;
+ }
+ try {
+ const bitmap = await createImageBitmap(e.data);
+ context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
+ bitmap.close();
+ frames += 1;
+ if (frames === 1) {
+ canvas.hidden = false;
+ status.hidden = true;
+ }
+ } catch {
+ // a frame that cannot be decoded is skipped
+ }
+ });
+ socket.addEventListener('close', () => {
+ socket = null;
+ if (!closed) failure();
+ });
+ }
+
+ // ------------------------------------------------------------------------------------------- input
+ function point(e) {
+ const rect = canvas.getBoundingClientRect();
+ return {
+ x: Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width)),
+ y: Math.min(1, Math.max(0, (e.clientY - rect.top) / rect.height)),
+ };
+ }
+ const move = perFrame((e) => send({ type: 'mouse', action: 'move', ...point(e), button: 'left', deltaX: 0, deltaY: 0, clickCount: 0 }));
+ canvas.addEventListener('mousemove', move);
+ canvas.addEventListener('mousedown', (e) => {
+ canvas.focus();
+ e.preventDefault();
+ send({ type: 'mouse', action: 'down', ...point(e), button: BUTTONS[e.button] || 'left', deltaX: 0, deltaY: 0, clickCount: e.detail || 1 });
+ });
+ canvas.addEventListener('mouseup', (e) => {
+ e.preventDefault();
+ send({ type: 'mouse', action: 'up', ...point(e), button: BUTTONS[e.button] || 'left', deltaX: 0, deltaY: 0, clickCount: e.detail || 1 });
+ });
+ canvas.addEventListener('contextmenu', (e) => e.preventDefault());
+ canvas.addEventListener('wheel', (e) => {
+ e.preventDefault();
+ const scale = e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? 800 : 1;
+ send({ type: 'mouse', action: 'wheel', ...point(e), button: 'left', deltaX: Math.round(e.deltaX * scale), deltaY: Math.round(e.deltaY * scale), clickCount: 0 });
+ }, { passive: false });
+ canvas.addEventListener('keydown', (e) => {
+ // Ctrl/Cmd+V goes through the paste event below (the clipboard is Alberto's, not the server's).
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') return;
+ e.preventDefault();
+ const printable = e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
+ send({ type: 'key', action: 'down', key: e.key, code: e.code, text: printable ? e.key : '', modifiers: modifiers(e) });
+ });
+ canvas.addEventListener('keyup', (e) => {
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'v') return;
+ e.preventDefault();
+ send({ type: 'key', action: 'up', key: e.key, code: e.code, text: '', modifiers: modifiers(e) });
+ });
+ const onPaste = (e) => {
+ if (document.activeElement !== canvas) return;
+ e.preventDefault();
+ const text = (e.clipboardData && e.clipboardData.getData('text')) || '';
+ for (const ch of text) send({ type: 'key', action: 'char', key: ch, code: '', text: ch, modifiers: 0 });
+ };
+ document.addEventListener('paste', onPaste);
+
+ function close() {
+ closed = true;
+ document.removeEventListener('paste', onPaste);
+ if (socket) socket.close();
+ socket = null;
+ }
+ page.onLeave(close);
+
+ showAddress(url);
+ connect();
+ return { element, close, showAddress };
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-about.js b/src/Febe.Web/wwwroot/js/pages/settings-about.js
new file mode 100644
index 0000000..4a54508
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/settings-about.js
@@ -0,0 +1,32 @@
+// Impostazioni, Informazioni: version and shell, where the guide is (the wiki of the repository), the folders, the
+// statement on the risk for the account (spec §1, §15 «che cosa la guida deve dire»), the licenses of what Febe
+// carries inside (Archivo OFL, Lucide ISC, SQLite, SkiaSharp, .NET, WebView2).
+
+import { api } from '../core/api.js';
+import { h, icon, fill, brand } from '../core/dom.js';
+import { t } from '../core/text.js';
+import { heading } from './settings.js';
+
+export default async function about(page, box) {
+ const data = await api('/api/about', { signal: page.signal });
+ const components = t('impostazioni.informazioni.componenti');
+ fill(box,
+ h('div.sezione.informazioni',
+ h('div.marchio-grande', brand(), h('div', h('b', t('app.nome')), h('span.muto', `${t('impostazioni.informazioni.versione')} ${data.version} · ${t(`impostazioni.informazioni.vesti.${data.edition}`)}`)))),
+ h('div.sezione',
+ heading(t('impostazioni.informazioni.guida'), t('impostazioni.informazioni.guidaTesto')),
+ h('a.btn', { href: data.guide, target: '_blank', rel: 'noopener noreferrer' }, icon('external-link', 's'), t('impostazioni.informazioni.apriGuida'))),
+ h('div.sezione',
+ heading(t('impostazioni.informazioni.cartelle')),
+ h('dl.dati-db',
+ h('dt', t('impostazioni.informazioni.cartellaLibreria')), h('dd.dati', data.libraryFolder),
+ h('dt', t('impostazioni.informazioni.cartellaDati')), h('dd.dati', data.dataFolder))),
+ h('div.sezione',
+ heading(t('impostazioni.informazioni.rischioTitolo')),
+ h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.informazioni.rischio')))),
+ h('div.sezione',
+ heading(t('impostazioni.informazioni.licenze'), t('impostazioni.informazioni.licenzeAiuto')),
+ h('ul.licenze', (Array.isArray(components) ? components : []).map((c) => h('li',
+ h('b', c.nome), h('span.muto', ` — ${c.testo}`),
+ c.file ? h('a', { href: c.file, target: '_blank', rel: 'noopener' }, t('impostazioni.informazioni.leggiLicenza')) : null)))));
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-data.js b/src/Febe.Web/wwwroot/js/pages/settings-data.js
new file mode 100644
index 0000000..c4ced55
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/settings-data.js
@@ -0,0 +1,133 @@
+// Impostazioni, Dati e copie di sicurezza (spec §8.2, §8.5): the Data folder with its size and the warning that whoever
+// has it (or a copy) has the Instagram session; the seven daily copies of the database with «Fai una copia adesso»;
+// «Ricostruisci il database dalla libreria» with a strong confirmation (the word typed by Alberto), progress and report.
+
+import { api } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { t, bytes, number, at, dayName } from '../core/text.js';
+import { caps } from '../core/context.js';
+import { dialog, showError, toast } from '../core/ui.js';
+import { heading } from './settings.js';
+
+export default async function dataSettings(page, box) {
+ let data = await api('/api/settings/data', { signal: page.signal });
+ let timer = 0;
+ page.onLeave(() => clearTimeout(timer));
+
+ const folder = h('div');
+ const backups = h('div');
+ const rebuild = h('div');
+
+ function drawFolder() {
+ const d = data.data;
+ const space = d.usedBytes == null
+ ? t('impostazioni.dati.spazioMisura')
+ : t('impostazioni.dati.spazio', { usati: bytes(d.usedBytes), liberi: d.freeBytes == null ? '—' : bytes(d.freeBytes) });
+ fill(folder,
+ h('div.riga-cartella', h('div.campo.sola', { title: d.path }, icon('folder', 's'), h('span.val.dati', d.path)), h('span.spazio.dati', space)),
+ h('dl.dati-db',
+ h('dt', t('impostazioni.dati.database')), h('dd.dati', data.database, data.databaseBytes != null ? ` · ${bytes(data.databaseBytes)}` : '')),
+ h('div.avviso.ambra', { style: { marginTop: '14px' } }, icon('shield-alert', 's'), h('span', t('impostazioni.dati.sessione'))));
+ }
+
+ function drawBackups() {
+ const rows = data.backups.map((b) => h('tr',
+ h('td', dayName(b.day, caps().today)),
+ h('td.dati', b.name),
+ h('td.dati.num', bytes(b.bytes)),
+ h('td.muto', at(b.modified))));
+ fill(backups,
+ h('p.aiuto', t('impostazioni.dati.copieAiuto', { cartella: data.backupsFolder, n: data.keepDays })),
+ h('div.riga-azione', h('button.btn', { type: 'button', onclick: backupNow }, icon('copy', 's'), t('impostazioni.dati.faiCopia'))),
+ rows.length
+ ? h('div.pannello', h('table.tab',
+ h('thead', h('tr', h('th', t('impostazioni.dati.colonne.giorno')), h('th', t('impostazioni.dati.colonne.file')), h('th.num', t('impostazioni.dati.colonne.peso')), h('th', t('impostazioni.dati.colonne.fatta')))),
+ h('tbody', rows)))
+ : h('p.vuoto-elenco.pannello', t('impostazioni.dati.nessunaCopia')));
+ }
+
+ function drawRebuild() {
+ const r = data.rebuild;
+ const status = [];
+ if (r.running) {
+ const ratio = r.foldersTotal ? r.foldersDone / r.foldersTotal : 0;
+ status.push(h('div.avanzamento-blocco',
+ h('p', t('impostazioni.dati.inCorso', { fatte: number(r.foldersDone), totale: number(r.foldersTotal), file: number(r.filesChecked) })),
+ h('div.misura', { role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': String(r.foldersTotal || 1), 'aria-valuenow': String(r.foldersDone) }, h('i', { style: { width: `${ratio * 100}%` } })),
+ r.folder ? h('p.aiuto.piccolo', t('impostazioni.dati.inCorsoCartella', { cartella: r.folder })) : null));
+ } else if (r.error) {
+ status.push(h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', r.error)));
+ } else if (r.finishedAt) {
+ status.push(h('div.pannello.resoconto-ricostruzione',
+ h('b', t('impostazioni.dati.finita', { quando: at(r.finishedAt) })),
+ h('ul', r.lines.map((line) => h('li', line)))));
+ }
+ fill(rebuild,
+ h('p.aiuto', t('impostazioni.dati.ricostruisciAiuto')),
+ h('div.riga-azione', h('button.btn.pericolo', { type: 'button', disabled: r.running, onclick: confirmRebuild }, icon('history', 's'), t('impostazioni.dati.ricostruisciBtn'))),
+ status);
+ clearTimeout(timer);
+ if (r.running) timer = setTimeout(reload, 1500);
+ else if (data.data.usedBytes == null) timer = setTimeout(reload, 1000); // the size is still being measured
+ }
+
+ async function reload() {
+ try {
+ data = await api('/api/settings/data', { signal: page.signal });
+ drawFolder();
+ drawBackups();
+ drawRebuild();
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ }
+ }
+
+ async function backupNow() {
+ try {
+ const result = await api('/api/settings/backups', { method: 'POST' });
+ toast(result.message);
+ await reload();
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ async function confirmRebuild() {
+ const word = t('impostazioni.dati.confParola');
+ const ok = await dialog({
+ title: t('impostazioni.dati.confTitolo'),
+ className: 'piccolo',
+ build: (close) => {
+ const input = h('input', { type: 'text', id: 'conferma-ricostruzione', autocomplete: 'off', spellcheck: 'false' });
+ const go = h('button.btn.pericolo.pieno', { type: 'button', disabled: true, onclick: () => close(true) }, t('impostazioni.dati.confBtn'));
+ input.addEventListener('input', () => { go.disabled = input.value.trim().toLowerCase() !== word; });
+ input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !go.disabled) close(true); });
+ return {
+ body: h('div.contenuto',
+ h('p', t('impostazioni.dati.confTesto')),
+ h('label.etichetta', { for: 'conferma-ricostruzione' }, t('impostazioni.dati.confScrivi')),
+ h('label.campo', input)),
+ footer: h('footer', h('div.destra',
+ h('button.btn.nudo', { type: 'button', onclick: () => close(false), autofocus: true }, t('comune.annulla')),
+ go)),
+ };
+ },
+ });
+ if (!ok) return;
+ try {
+ const result = await api('/api/settings/rebuild', { method: 'POST', body: { confirm: word } });
+ toast(result.message);
+ await reload();
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ drawFolder();
+ drawBackups();
+ drawRebuild();
+ fill(box,
+ h('div.sezione', heading(t('impostazioni.dati.cartella'), t('impostazioni.dati.contiene')), folder),
+ h('div.sezione', heading(t('impostazioni.dati.copie')), backups),
+ h('div.sezione', heading(t('impostazioni.dati.ricostruisci')), rebuild));
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-general.js b/src/Febe.Web/wwwroot/js/pages/settings-general.js
new file mode 100644
index 0000000..a48d72f
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/settings-general.js
@@ -0,0 +1,225 @@
+// Impostazioni, Generali (mockup 08, spec §4.7, §10.5, §12): the Libreria and Dati folders with «Cambia…» (desktop:
+// native picker; Docker: read-only with the note), free and used space; the two naming schemes with the live «Risultato»
+// tree, the placeholders and the errors; «Imposta la data del file a quella di pubblicazione»; theme and language;
+// the «Avvio» block on Windows only.
+
+import { api } from '../core/api.js';
+import { h, icon, fill, later } from '../core/dom.js';
+import { t, bytes } from '../core/text.js';
+import { saveTheme, themeChoice } from '../core/theme.js';
+import { checkbox, confirmDialog, label, segmented, showError, toast, toggle } from '../core/ui.js';
+import { guardChanges, heading } from './settings.js';
+
+export default async function general(page, box) {
+ let data = await api('/api/settings/general', { signal: page.signal });
+ let saved = { naming: data.namingScheme, highlight: data.highlightScheme, setFileTime: data.setFileTime };
+ const form = { ...saved };
+ const dirty = () => form.naming !== saved.naming || form.highlight !== saved.highlight || form.setFileTime !== saved.setFileTime;
+ guardChanges(page, dirty);
+
+ // ------------------------------------------------------------------------------------------- folders
+ const folders = h('div');
+ function drawFolders() {
+ const row = (title, help, folder, side, onChange, canChange) => h('div.cartella-impostazioni',
+ h('b.titolo-campo', title),
+ h('p.aiuto', help),
+ h('div.riga-cartella',
+ h('div.campo.sola', { title: folder.path }, icon('folder', 's'), h('span.val.dati', folder.path)),
+ canChange ? h('button.btn', { type: 'button', onclick: onChange }, t('impostazioni.generali.cambia')) : null,
+ h('span.spazio.dati', side)));
+ const free = data.library.freeBytes != null ? t('impostazioni.generali.liberi', { n: bytes(data.library.freeBytes) }) : '';
+ const used = data.data.usedBytes != null ? t('impostazioni.generali.usati', { n: bytes(data.data.usedBytes) }) : data.data.measuring ? t('impostazioni.generali.misura') : '';
+ fill(folders,
+ row(t('impostazioni.generali.libreria'), t('impostazioni.generali.libreriaAiuto'), data.library, free, changeLibrary, !data.foldersReadOnly && data.canPickFolder),
+ row(t('impostazioni.generali.dati'), t('impostazioni.generali.datiAiuto'), data.data, used, changeData, data.canChangeDataFolder),
+ data.foldersReadOnly ? h('div.avviso', { style: { marginTop: '12px' } }, icon('info', 's'), h('span', t('impostazioni.generali.dockerNota'))) : null);
+ }
+
+ async function pick(which) {
+ try {
+ const result = await api('/api/settings/pick-folder', { method: 'POST', body: { which } });
+ return result.path || null;
+ } catch (error) {
+ showError(error);
+ return null;
+ }
+ }
+
+ async function changeLibrary() {
+ const path = await pick('library');
+ if (!path) return;
+ const ok = await confirmDialog({
+ title: t('impostazioni.generali.nuovaLibreria'),
+ text: t('impostazioni.generali.nuovaLibreriaTesto', { percorso: path }),
+ buttons: [
+ { label: t('comune.annulla'), value: false, kind: 'nudo' },
+ { label: t('impostazioni.generali.usaCartella'), value: true, kind: 'primo', autofocus: true },
+ ],
+ });
+ if (!ok) return;
+ await put({ libraryFolder: path });
+ }
+
+ async function changeData() {
+ const path = await pick('data');
+ if (!path) return;
+ const ok = await confirmDialog({
+ title: t('impostazioni.generali.nuoviDati'),
+ text: t('impostazioni.generali.nuoviDatiTesto', { percorso: path }),
+ buttons: [
+ { label: t('comune.annulla'), value: false, kind: 'nudo' },
+ { label: t('impostazioni.generali.usaCartella'), value: true, kind: 'primo', autofocus: true },
+ ],
+ });
+ if (!ok) return;
+ try {
+ const result = await api('/api/settings/data-folder', { method: 'POST', body: { path } });
+ toast(result.message);
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ /** Saves with the stored naming values plus the given changes (folders and switches act at once). */
+ async function put(changes, { withForm = false } = {}) {
+ const body = {
+ libraryFolder: null,
+ namingScheme: withForm ? form.naming : saved.naming,
+ highlightScheme: withForm ? form.highlight : saved.highlight,
+ setFileTime: withForm ? form.setFileTime : saved.setFileTime,
+ autostart: null,
+ keepInTray: null,
+ ...changes,
+ };
+ try {
+ data = await api('/api/settings/general', { method: 'PUT', body });
+ saved = { naming: data.namingScheme, highlight: data.highlightScheme, setFileTime: data.setFileTime };
+ if (withForm) Object.assign(form, saved);
+ drawFolders();
+ drawSaveBar();
+ toast(t('impostazioni.salvate'));
+ return true;
+ } catch (error) {
+ showError(error);
+ return false;
+ }
+ }
+
+ // ------------------------------------------------------------------------------------------- naming
+ const naming = h('input.dati', { type: 'text', value: form.naming, id: 'schema', spellcheck: 'false', autocomplete: 'off' });
+ const highlight = h('input.dati', { type: 'text', value: form.highlight, id: 'schema-evidenza', spellcheck: 'false', autocomplete: 'off' });
+ const namingField = h('label.campo', naming);
+ const highlightField = h('label.campo', highlight);
+ const problems = h('div.problemi-schema', { 'aria-live': 'polite' });
+ const tree = h('div.albero.pannello', { 'aria-label': t('impostazioni.generali.risultato') });
+ const setTime = checkbox({ checked: form.setFileTime, label: t('impostazioni.generali.dataFile'), onchange: (v) => { form.setFileTime = v; drawSaveBar(); } });
+
+ function drawTree(preview) {
+ const errors = preview.errors || [];
+ namingField.classList.toggle('errore', errors.some((e) => e.startsWith('Schema:')));
+ highlightField.classList.toggle('errore', errors.some((e) => !e.startsWith('Schema:')));
+ fill(problems,
+ errors.map((e) => h('p.errore-testo', icon('octagon-alert', 'xs'), ' ', e)),
+ (preview.warnings || []).map((w) => h('p.avviso-testo', icon('triangle-alert', 'xs'), ' ', w)));
+ fill(tree,
+ h('div.ramo.radice', icon('folder', 's'), h('b', preview.accountFolder)),
+ preview.folders.map((f) => [
+ f.path.length ? h('div.ramo.livello-1', icon('folder', 's'), h('span', f.path.join(' \\ '))) : 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))),
+ ]));
+ }
+
+ const refresh = later(async () => {
+ try {
+ drawTree(await api('/api/settings/naming-preview', { method: 'POST', body: { namingScheme: form.naming, highlightScheme: form.highlight }, signal: page.signal }));
+ } catch (error) {
+ if (error.name !== 'AbortError') showError(error);
+ }
+ }, 150);
+ page.onLeave(() => refresh.cancel());
+ naming.addEventListener('input', () => { form.naming = naming.value; drawSaveBar(); refresh(); });
+ highlight.addEventListener('input', () => { form.highlight = highlight.value; drawSaveBar(); refresh(); });
+
+ // ------------------------------------------------------------------------------------------- save bar
+ function drawSaveBar() {
+ if (!dirty()) {
+ page.saveBar(null);
+ return;
+ }
+ page.saveBar(h('div', { style: { display: 'contents' } },
+ h('span.nota', t('impostazioni.modifiche')),
+ h('div.destra',
+ h('button.btn', { type: 'button', onclick: discard }, t('impostazioni.annulla')),
+ h('button.btn.primo', { type: 'button', onclick: () => put({}, { withForm: true }) }, icon('check'), t('impostazioni.salva')))));
+ }
+
+ function discard() {
+ Object.assign(form, saved);
+ naming.value = form.naming;
+ highlight.value = form.highlight;
+ setTime.input.checked = form.setFileTime;
+ drawSaveBar();
+ refresh();
+ }
+
+ // ------------------------------------------------------------------------------------------- appearance and start
+ const theme = segmented({
+ label: t('impostazioni.generali.tema'),
+ value: themeChoice(),
+ options: [
+ { value: 'chiaro', label: t('impostazioni.generali.temi.chiaro'), icon: 'sun' },
+ { value: 'scuro', label: t('impostazioni.generali.temi.scuro'), icon: 'moon' },
+ { value: 'sistema', label: t('impostazioni.generali.temi.sistema'), icon: 'monitor' },
+ ],
+ onchange: async (v) => {
+ try {
+ await saveTheme(v);
+ } catch (error) {
+ showError(error);
+ }
+ },
+ });
+ const language = h('label.campo.scelta.lingua', h('select', { id: 'lingua', 'aria-describedby': 'lingua-nota' }, h('option', { value: 'it', selected: true }, t('impostazioni.generali.italiano'))), icon('chevron-down', 's'));
+
+ const start = data.autostart == null ? null : h('div.sezione',
+ h('div.testa-sez', h('h2.sez', t('impostazioni.generali.avvio'), ' ', label(t('impostazioni.generali.soloWindows')))),
+ h('div.leve',
+ toggle({ checked: data.autostart, label: t('impostazioni.generali.accensione'), onchange: (v) => put({ autostart: v }) }),
+ toggle({ checked: data.keepInTray, label: t('impostazioni.generali.area'), onchange: (v) => put({ keepInTray: v }) })));
+
+ drawFolders();
+ drawTree(data.preview);
+ fill(box,
+ h('div.sezione', heading(t('impostazioni.generali.cartelle')), folders),
+ h('div.sezione',
+ heading(t('impostazioni.generali.nomi'), t('impostazioni.generali.nomiAiuto')),
+ h('div.nomi-file',
+ h('div.colonna-nomi',
+ h('label.etichetta', { for: 'schema' }, t('impostazioni.generali.schema')), namingField,
+ h('label.etichetta', { for: 'schema-evidenza' }, t('impostazioni.generali.schemaEvidenza')), highlightField,
+ h('p.aiuto.segnaposto', t('impostazioni.generali.segnaposto', { elenco: data.placeholders.join(', ') })),
+ problems,
+ h('div.data-file', setTime)),
+ h('div.colonna-albero', h('span.etichetta', t('impostazioni.generali.risultato')), tree))),
+ h('div.sezione',
+ heading(t('impostazioni.generali.aspetto')),
+ h('div.aspetto',
+ h('div', h('span.etichetta', t('impostazioni.generali.tema')), theme),
+ h('div', h('label.etichetta', { for: 'lingua' }, t('impostazioni.generali.lingua')), language,
+ h('p.aiuto.piccolo', { id: 'lingua-nota' }, t('impostazioni.generali.linguaNota'))))),
+ start);
+
+ // The used size of the Data folder is measured in the background: ask again once.
+ if (data.data.measuring && data.data.usedBytes == null) {
+ const timer = setTimeout(async () => {
+ try {
+ const again = await api('/api/settings/general', { signal: page.signal });
+ data = { ...data, data: again.data, library: again.library };
+ drawFolders();
+ } catch {
+ // keep «calcolo…»
+ }
+ }, 1000);
+ page.onLeave(() => clearTimeout(timer));
+ }
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-limits.js b/src/Febe.Web/wwwroot/js/pages/settings-limits.js
new file mode 100644
index 0000000..d92e82c
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/settings-limits.js
@@ -0,0 +1,413 @@
+// Impostazioni, Limiti e comportamento (mockup 07, spec §7.2, §7.5, §7.7): the honest note on the values, the profile
+// cards (Prudente, Equilibrato, Rapido with confirmation and «Più rischio», Su misura when Alberto changes a value),
+// the active window with its daily shift and the active days as initials, session and pause ranges, the gesture
+// pace, every budget of §7.5, the gradual start, the fixed stops (informative), and the fixed save bar. The limits
+// of §7.5 are checked here with Italian messages and again by the server.
+
+import { api } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { refreshEngine } from '../core/engine.js';
+import { t, list, number, decimal } from '../core/text.js';
+import { checkbox, confirmDialog, label, showError, toast, toggle } from '../core/ui.js';
+import { guardChanges, heading } from './settings.js';
+
+const PACES = ['slow', 'natural', 'brisk'];
+const DAY_ORDER = [1, 2, 3, 4, 5, 6, 0]; // Monday first; the API counts from Sunday = 0
+
+export default async function limits(page, box) {
+ let data = await api('/api/settings/limits', { signal: page.signal });
+ const snapshot = () => JSON.stringify({ profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays].sort() });
+ let form = fromData(data);
+ let original = snapshot();
+ const dirty = () => snapshot() !== original;
+ guardChanges(page, dirty);
+ const rules = data.rules;
+ let errors = {};
+
+ function fromData(d) {
+ return {
+ profile: d.profile,
+ values: structuredClone(d.current),
+ pace: d.pace,
+ gradualStart: d.gradualStart,
+ activeDays: new Set(d.activeDays),
+ jitterOn: d.current.jitterMinutes > 0,
+ };
+ }
+
+ /** Any edit turns the profile into «Su misura» (spec §7.5). */
+ function edited() {
+ form.profile = 'custom';
+ form.values.kind = 'custom';
+ validate();
+ drawCards();
+ drawWindow();
+ drawSaveBar();
+ }
+
+ // ------------------------------------------------------------------------------------------- profile cards
+ const cards = h('div.profili', { role: 'radiogroup', 'aria-label': t('impostazioni.limiti.profilo') });
+ const customCard = h('div');
+ function drawCards() {
+ fill(cards, data.presets.map((p) => {
+ const input = h('input.vh', { type: 'radio', name: 'profilo', value: p.kind, checked: form.profile === p.kind });
+ input.addEventListener('change', () => choose(p));
+ const budget = (kind) => p.budgets.find((b) => b.kind === kind)?.perDay ?? 0;
+ return h(`label.profilo${form.profile === p.kind ? '.scelto' : ''}`,
+ input,
+ h('div.testa-profilo', h('span.tondo', { 'aria-hidden': 'true' }), h('b', p.name),
+ p.kind === 'prudent' ? label(t('impostazioni.limiti.consigliato'), 'accento') : null,
+ p.kind === 'fast' ? label(t('impostazioni.limiti.piuRischio'), 'ambra') : null),
+ h('p', t(`impostazioni.limiti.profili.${p.kind}`)),
+ h('p.riassunto', riassunto(budget('ProfileOpen'), budget('StoryView'), budget('BackfillPage'))));
+ }));
+ fill(customCard, form.profile === 'custom'
+ ? h('div.profilo.scelto.su-misura', h('div.testa-profilo', h('span.tondo.si', { 'aria-hidden': 'true' }), h('b', t('impostazioni.limiti.suMisura'))),
+ h('p', t('impostazioni.limiti.suMisuraTesto')))
+ : null);
+ }
+
+ function riassunto(profiles, stories, history) {
+ const text = t('impostazioni.limiti.riassunto', { profili: '\u0001', storie: '\u0002', storico: '\u0003' });
+ return text.split(/([\u0001-\u0003])/).map((part) => part === '\u0001' ? h('b', number(profiles)) : part === '\u0002' ? h('b', number(stories)) : part === '\u0003' ? h('b', number(history)) : part);
+ }
+
+ async function choose(preset) {
+ if (preset.kind === 'fast' && form.profile !== 'fast') {
+ const ok = await confirmDialog({
+ title: t('impostazioni.limiti.rapidoTitolo'),
+ text: t('impostazioni.limiti.rapidoTesto'),
+ buttons: [
+ { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
+ { label: t('impostazioni.limiti.rapidoConferma'), value: true, kind: 'primo' },
+ ],
+ });
+ if (!ok) {
+ drawCards();
+ return;
+ }
+ }
+ form.profile = preset.kind;
+ form.values = structuredClone(preset);
+ form.jitterOn = preset.jitterMinutes > 0;
+ drawAll();
+ }
+
+ // ------------------------------------------------------------------------------------------- window and days
+ const windowBar = h('div.fascia-barra');
+ // Text fields with 24-hour times (a time input would follow the browser's locale, possibly with AM/PM).
+ const timeField = (id) => h('input.dati', { type: 'text', id, inputmode: 'numeric', maxlength: '5', placeholder: '07:30', autocomplete: 'off', spellcheck: 'false' });
+ const startInput = timeField('fascia-inizio');
+ const endInput = timeField('fascia-fine');
+ const readTime = (input, key) => {
+ const value = input.value.trim().replace('.', ':');
+ const m = /^(\d{1,2}):?(\d{2})$/.exec(value);
+ form.values[key] = m && Number(m[1]) <= 24 && Number(m[2]) < 60 ? `${m[1].padStart(2, '0')}:${m[2]}` : value;
+ edited();
+ };
+ startInput.addEventListener('change', () => readTime(startInput, 'windowStart'));
+ endInput.addEventListener('change', () => readTime(endInput, 'windowEnd'));
+ const days = h('div.giorni', { role: 'group', 'aria-label': t('impostazioni.limiti.giorni') });
+ const jitterInput = h('input.dati', { type: 'number', min: '0', max: String(rules.maxJitterMinutes), step: '5', id: 'sposta', inputmode: 'numeric' });
+ jitterInput.addEventListener('input', () => { form.values.jitterMinutes = toInt(jitterInput.value); edited(); });
+ const jitterBox = checkbox({
+ checked: form.jitterOn,
+ labelNode: h('span', t('impostazioni.limiti.sposta')),
+ onchange: (v) => {
+ form.jitterOn = v;
+ form.values.jitterMinutes = v ? Math.max(5, toInt(jitterInput.value) || 30) : 0;
+ jitterInput.value = form.values.jitterMinutes;
+ jitterInput.disabled = !v;
+ edited();
+ },
+ });
+ const windowError = h('p.errore-testo', { hidden: true });
+
+ function minutesOf(text) {
+ const m = /^(\d{1,2}):(\d{2})$/.exec(String(text || ''));
+ if (!m || Number(m[1]) > 24 || Number(m[2]) > 59) return null;
+ return (Number(m[1]) * 60 + Number(m[2])) % 1440;
+ }
+ function textOf(minutes) {
+ const v = ((Math.round(minutes) % 1440) + 1440) % 1440;
+ return `${String(Math.floor(v / 60)).padStart(2, '0')}:${String(v % 60).padStart(2, '0')}`;
+ }
+
+ function drawWindow() {
+ const start = minutesOf(form.values.windowStart) ?? 0;
+ let end = minutesOf(form.values.windowEnd) ?? start;
+ if (end === 0) end = 1440;
+ const bands = end > start ? [[start, end]] : [[start, 1440], [0, end]];
+ const pct = (m) => `${(m / 1440) * 100}%`;
+ fill(windowBar,
+ [3, 6, 9, 12, 15, 18, 21].map((hour) => h('span.tacca', { style: { left: pct(hour * 60) } })),
+ bands.map(([a, b]) => h('span.banda', { style: { left: pct(a), width: pct(b - a) } })),
+ handle('inizio', start), handle('fine', end % 1440 === 0 && end === 1440 ? 1440 : end));
+ if (document.activeElement !== startInput) startInput.value = minutesOf(form.values.windowStart) == null ? form.values.windowStart : textOf(start);
+ if (document.activeElement !== endInput) endInput.value = minutesOf(form.values.windowEnd) == null ? form.values.windowEnd : textOf(end);
+ jitterInput.value = form.values.jitterMinutes;
+ jitterInput.disabled = !form.jitterOn;
+ jitterBox.input.checked = form.jitterOn;
+ fill(days, DAY_ORDER.map((day, i) => {
+ const on = form.activeDays.has(day);
+ return h(`button.cerchio-giorno${on ? '.si' : ''}`, {
+ type: 'button', 'aria-pressed': String(on), 'aria-label': list('impostazioni.limiti.nomiGiorni')[i], title: list('impostazioni.limiti.nomiGiorni')[i],
+ onclick: () => {
+ if (on) form.activeDays.delete(day);
+ else form.activeDays.add(day);
+ edited();
+ },
+ }, list('impostazioni.limiti.iniziali')[i]);
+ }));
+ const message = errors.window || errors.days || errors.jitter;
+ windowError.hidden = !message;
+ windowError.textContent = message || '';
+ startInput.parentElement?.classList.toggle('errore', Boolean(errors.window));
+ endInput.parentElement?.classList.toggle('errore', Boolean(errors.window));
+ }
+
+ /** A draggable handle of the window bar (15-minute steps); the time fields stay the precise way. */
+ function handle(which, minutes) {
+ const el = h('span.maniglia', { style: { left: `${(minutes / 1440) * 100}%` }, 'aria-hidden': 'true' });
+ el.addEventListener('pointerdown', (e) => {
+ e.preventDefault();
+ el.setPointerCapture(e.pointerId);
+ const rect = windowBar.getBoundingClientRect();
+ const move = (ev) => {
+ const ratio = Math.min(1, Math.max(0, (ev.clientX - rect.left) / rect.width));
+ const value = Math.round((ratio * 1440) / 15) * 15;
+ if (which === 'inizio') form.values.windowStart = textOf(value);
+ else form.values.windowEnd = textOf(value);
+ edited();
+ };
+ const up = () => {
+ el.removeEventListener('pointermove', move);
+ el.removeEventListener('pointerup', up);
+ };
+ el.addEventListener('pointermove', move);
+ el.addEventListener('pointerup', up);
+ });
+ return el;
+ }
+
+ // ------------------------------------------------------------------------------------------- sessions, pauses, pace
+ const sessionRange = rangePair('sessione', 1, rules.maxSessionMinutes, () => [form.values.sessionMinMinutes, form.values.sessionMaxMinutes], (a, b) => {
+ form.values.sessionMinMinutes = a;
+ form.values.sessionMaxMinutes = b;
+ edited();
+ });
+ const pauseRange = rangePair('pausa', rules.minPauseMinutes, 180, () => [form.values.pauseMinMinutes, form.values.pauseMaxMinutes], (a, b) => {
+ form.values.pauseMinMinutes = a;
+ form.values.pauseMaxMinutes = b;
+ edited();
+ });
+ const paceInput = h('input.cursore.lungo', { type: 'range', min: '0', max: '2', step: '1', id: 'ritmo', 'aria-valuetext': '' });
+ const paceText = h('span.valore-cursore');
+ paceInput.addEventListener('input', () => {
+ form.pace = PACES[Number(paceInput.value)];
+ validate();
+ drawPace();
+ drawSaveBar();
+ });
+ function drawPace() {
+ paceInput.value = String(PACES.indexOf(form.pace));
+ paceText.textContent = t(`impostazioni.limiti.ritmi.${form.pace}`);
+ paceInput.setAttribute('aria-valuetext', paceText.textContent);
+ paceInput.style.setProperty('--pieno', `${(PACES.indexOf(form.pace) / 2) * 100}%`);
+ }
+
+ /** Two thumbs on one track (minimum and maximum), with the text «da 2 a 10 minuti». */
+ function rangePair(name, min, max, get, set) {
+ const low = h('input.cursore', { type: 'range', min: String(min), max: String(max), step: '1', 'aria-label': `${t(`impostazioni.limiti.${name === 'sessione' ? 'durata' : 'pausa'}`)}, ${t('impostazioni.limiti.minimo')}` });
+ const high = h('input.cursore', { type: 'range', min: String(min), max: String(max), step: '1', 'aria-label': `${t(`impostazioni.limiti.${name === 'sessione' ? 'durata' : 'pausa'}`)}, ${t('impostazioni.limiti.massimo')}` });
+ const fillBar = h('span.tratto');
+ const text = h('span.valore-cursore');
+ const error = h('p.errore-testo', { hidden: true });
+ const track = h('div.doppio', h('span.binario'), fillBar, low, high);
+ const sync = () => {
+ const [a, b] = get();
+ low.value = String(Math.max(min, Math.min(max, a)));
+ high.value = String(Math.max(min, Math.min(max, b)));
+ const left = ((Number(low.value) - min) / (max - min)) * 100;
+ const right = ((Number(high.value) - min) / (max - min)) * 100;
+ fillBar.style.left = `${left}%`;
+ fillBar.style.width = `${Math.max(0, right - left)}%`;
+ text.textContent = t('impostazioni.limiti.daA', { a, b });
+ low.setAttribute('aria-valuetext', `${a} ${t('impostazioni.limiti.minuti')}`);
+ high.setAttribute('aria-valuetext', `${b} ${t('impostazioni.limiti.minuti')}`);
+ const message = errors[name];
+ error.hidden = !message;
+ error.textContent = message || '';
+ };
+ low.addEventListener('input', () => {
+ const a = Number(low.value);
+ const [, b] = get();
+ set(a, Math.max(a, b));
+ });
+ high.addEventListener('input', () => {
+ const b = Number(high.value);
+ const [a] = get();
+ set(Math.min(a, b), b);
+ });
+ return { track, text, error, sync };
+ }
+
+ // ------------------------------------------------------------------------------------------- budgets table
+ const table = h('tbody');
+ const cells = new Map();
+ function paintErrors() {
+ for (const [key, ref] of cells) {
+ ref.field.classList.toggle('errore', Boolean(errors[key]));
+ ref.message.hidden = !errors[key];
+ ref.message.textContent = errors[key] || '';
+ }
+ }
+ function drawTable() {
+ cells.clear();
+ const v = form.values;
+ const numberCell = (value, max, onInput, key, unit) => {
+ const input = h('input.dati', { type: 'number', min: '0', max: String(max), step: unit === 'gb' ? '0.5' : '1', value: String(value), inputmode: unit === 'gb' ? 'decimal' : 'numeric', 'aria-label': key });
+ input.addEventListener('input', () => onInput(input.value));
+ const field = h('label.campo.numero', input, unit ? h('span.unita', t(`impostazioni.limiti.${unit}`)) : null);
+ const message = h('div.errore-testo', { hidden: true });
+ cells.set(key, { field, message });
+ return h('td', field, message);
+ };
+ const rows = v.budgets.map((b) => h('tr',
+ h('td', b.label),
+ numberCell(b.perHour, b.maxPerHour, (x) => { b.perHour = toInt(x); edited(); }, `${b.kind}-ora`),
+ numberCell(b.perDay, b.maxPerDay, (x) => { b.perDay = toInt(x); edited(); }, `${b.kind}-giorno`)));
+ rows.push(h('tr',
+ h('td', t('impostazioni.limiti.dati')),
+ h('td.muto', '—'),
+ numberCell(decimal(v.dataPerDayGb, 2).replace(',', '.'), rules.maxDataPerDayGb, (x) => { v.dataPerDayGb = String(x).trim() === '' ? NaN : Number(String(x).replace(',', '.')); edited(); }, 'dati', 'gb')));
+ rows.push(h('tr',
+ h('td', t('impostazioni.limiti.storico'), h('div.muto.piccolo', t('impostazioni.limiti.storicoNota'))),
+ h('td.muto', '—'),
+ numberCell(v.backfillPerAccount, rules.maxBackfillPerAccount, (x) => { v.backfillPerAccount = toInt(x); edited(); }, 'storico', 'post')));
+ const gradual = toggle({ checked: form.gradualStart, label: t('impostazioni.limiti.graduale'), onchange: (on) => { form.gradualStart = on; validate(); drawTable(); drawSaveBar(); } });
+ rows.push(h('tr.riga-graduale',
+ h('td', gradual, h('div.muto.piccolo', t('impostazioni.limiti.gradualeAiuto'))),
+ h('td.muto', '—'),
+ form.gradualStart ? numberCell(v.rampUpDays, rules.maxRampUpDays, (x) => { v.rampUpDays = toInt(x); edited(); }, 'graduale', 'giorniGraduale') : h('td.muto', '—')));
+ rows.push(h('tr.informativa',
+ h('td', h('span', icon('lock', 'xs'), ' ', t('impostazioni.limiti.arresti')), h('div.muto.piccolo', t('impostazioni.limiti.arrestiTesto'))),
+ h('td.muto', data.stops.join(' · ')),
+ h('td.muto', t('impostazioni.limiti.arrestiFissi'))));
+ fill(table, rows);
+ paintErrors();
+ }
+
+ // ------------------------------------------------------------------------------------------- validation
+ function validate() {
+ const v = form.values;
+ const e = {};
+ const start = minutesOf(v.windowStart);
+ const end = minutesOf(v.windowEnd);
+ if (start == null || end == null) e.window = t('impostazioni.limiti.errori.ora');
+ else {
+ let length = end - start;
+ if (length <= 0) length += 1440;
+ if (length > rules.maxWindowHours * 60) e.window = t('impostazioni.limiti.errori.fascia', { n: rules.maxWindowHours });
+ }
+ if (form.activeDays.size === 0) e.days = t('impostazioni.limiti.errori.giorni');
+ if (!(v.jitterMinutes >= 0 && v.jitterMinutes <= rules.maxJitterMinutes)) e.jitter = t('impostazioni.limiti.errori.sposta', { n: rules.maxJitterMinutes });
+ if (v.sessionMaxMinutes > rules.maxSessionMinutes) e.sessione = t('impostazioni.limiti.errori.sessione', { n: rules.maxSessionMinutes });
+ else if (v.sessionMinMinutes < 1) e.sessione = t('impostazioni.limiti.errori.sessioneMin');
+ else if (v.sessionMinMinutes > v.sessionMaxMinutes) e.sessione = t('impostazioni.limiti.errori.minMax');
+ if (v.pauseMinMinutes < rules.minPauseMinutes) e.pausa = t('impostazioni.limiti.errori.pausa', { n: rules.minPauseMinutes });
+ else if (v.pauseMinMinutes > v.pauseMaxMinutes) e.pausa = t('impostazioni.limiti.errori.minMax');
+ for (const b of v.budgets) {
+ if (!Number.isInteger(b.perHour) || b.perHour < 0) e[`${b.kind}-ora`] = t('impostazioni.limiti.errori.numero');
+ else if (b.perHour > b.maxPerHour) e[`${b.kind}-ora`] = t('impostazioni.limiti.errori.tetto', { max: number(b.maxPerHour) });
+ if (!Number.isInteger(b.perDay) || b.perDay < 0) e[`${b.kind}-giorno`] = t('impostazioni.limiti.errori.numero');
+ else if (b.perDay > b.maxPerDay) e[`${b.kind}-giorno`] = t('impostazioni.limiti.errori.tetto', { max: number(b.maxPerDay) });
+ }
+ if (!(v.dataPerDayGb >= 0)) e.dati = t('impostazioni.limiti.errori.numero');
+ else if (v.dataPerDayGb > rules.maxDataPerDayGb) e.dati = t('impostazioni.limiti.errori.tetto', { max: `${decimal(rules.maxDataPerDayGb, 1)} GB` });
+ if (!Number.isInteger(v.backfillPerAccount) || v.backfillPerAccount < 0) e.storico = t('impostazioni.limiti.errori.numero');
+ else if (v.backfillPerAccount > rules.maxBackfillPerAccount) e.storico = t('impostazioni.limiti.errori.tetto', { max: `${number(rules.maxBackfillPerAccount)} post` });
+ if (form.gradualStart && !(Number.isInteger(v.rampUpDays) && v.rampUpDays >= 0 && v.rampUpDays <= rules.maxRampUpDays)) e.graduale = t('impostazioni.limiti.errori.graduale', { n: rules.maxRampUpDays });
+ errors = e;
+ sessionRange.sync();
+ pauseRange.sync();
+ paintErrors();
+ }
+
+ // ------------------------------------------------------------------------------------------- save bar
+ function drawSaveBar() {
+ const changed = dirty();
+ const invalid = Object.keys(errors).length > 0;
+ page.saveBar(h('div', { style: { display: 'contents' } },
+ h('span.nota', invalid ? h('span.errore-testo', icon('octagon-alert', 'xs'), ' ', t('impostazioni.limiti.errori.correggi')) : t(changed ? 'impostazioni.modifiche' : 'impostazioni.nessunaModifica')),
+ h('div.destra',
+ h('button.btn', { type: 'button', disabled: !changed, onclick: discard }, t('impostazioni.annulla')),
+ h('button.btn.primo', { type: 'button', disabled: !changed || invalid, onclick: save }, icon('check'), t('impostazioni.salva')))));
+ }
+
+ function discard() {
+ form = fromData(data);
+ drawAll();
+ }
+
+ async function save() {
+ try {
+ data = await api('/api/settings/limits', {
+ method: 'PUT',
+ body: { profile: form.profile, values: form.values, pace: form.pace, gradualStart: form.gradualStart, activeDays: [...form.activeDays] },
+ });
+ form = fromData(data);
+ original = snapshot();
+ drawAll();
+ toast(t('impostazioni.limiti.salvati'));
+ refreshEngine();
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ function drawAll() {
+ validate();
+ drawCards();
+ drawWindow();
+ drawPace();
+ drawTable();
+ drawSaveBar();
+ }
+
+ drawAll();
+ original = snapshot();
+ drawSaveBar();
+
+ fill(box,
+ h('div.avviso.ambra.avviso-limiti', icon('triangle-alert', 's'), h('span', t('impostazioni.limiti.avviso'))),
+ h('div.sezione', heading(t('impostazioni.limiti.profilo'), t('impostazioni.limiti.profiloAiuto')), cards, customCard),
+ h('div.sezione',
+ heading(t('impostazioni.limiti.orari'), t('impostazioni.limiti.orariAiuto')),
+ windowBar,
+ h('div.ore', { 'aria-hidden': 'true' }, [0, 3, 6, 9, 12, 15, 18, 21, 24].map((hour) => h('span', { style: { left: `${(hour / 24) * 100}%` } }, String(hour)))),
+ h('div.riga-fascia',
+ h('label.etichetta-riga', { for: 'fascia-inizio' }, t('impostazioni.limiti.dalle')), h('span.campo.ora', startInput),
+ h('label.etichetta-riga', { for: 'fascia-fine' }, t('impostazioni.limiti.alle')), h('span.campo.ora', endInput),
+ h('span.etichetta-riga.giorni-etichetta', t('impostazioni.limiti.giorni')), days),
+ h('div.riga-sposta', jitterBox, h('span.campo.numero.corto', jitterInput), h('span.muto', t('impostazioni.limiti.minuti'))),
+ windowError),
+ h('div.sezione',
+ heading(t('impostazioni.limiti.sessioni'), t('impostazioni.limiti.sessioniAiuto')),
+ h('div.cursori',
+ h('span.etichetta-riga', t('impostazioni.limiti.durata')), sessionRange.track, sessionRange.text, sessionRange.error,
+ h('span.etichetta-riga', t('impostazioni.limiti.pausa')), pauseRange.track, pauseRange.text, pauseRange.error,
+ h('label.etichetta-riga', { for: 'ritmo' }, t('impostazioni.limiti.ritmo')), h('div.singolo', paceInput), paceText)),
+ h('div.sezione',
+ heading(t('impostazioni.limiti.tetti'), t('impostazioni.limiti.tettiAiuto')),
+ h('div.pannello.tabella-tetti', h('table.tab',
+ h('thead', h('tr', h('th', t('impostazioni.limiti.colonne.attivita')), h('th', t('impostazioni.limiti.colonne.ora')), h('th', t('impostazioni.limiti.colonne.giorno')))),
+ table))));
+}
+
+function toInt(text) {
+ const trimmed = String(text).trim();
+ if (trimmed === '') return NaN;
+ const n = Number(trimmed);
+ return Number.isFinite(n) ? Math.round(n) : NaN;
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings-notifications.js b/src/Febe.Web/wwwroot/js/pages/settings-notifications.js
new file mode 100644
index 0000000..d43587f
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/settings-notifications.js
@@ -0,0 +1,101 @@
+// Impostazioni, Notifiche (spec §13.3): which events notify, Windows notifications (desktop only), Telegram with the
+// bot token (masked, never shown again once saved, never logged) and the chat identifier, and «Invia una prova».
+// The Telegram sender arrives with milestone M8: until then the server answers plainly that nothing was sent.
+
+import { api } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { t } from '../core/text.js';
+import { label, showError, toast, toggle } from '../core/ui.js';
+import { guardChanges, heading } from './settings.js';
+
+const EVENTS = ['verification', 'disconnection', 'throttle', 'backfillDone', 'diskLow', 'unknownFormat'];
+
+export default async function notifications(page, box) {
+ let data = await api('/api/settings/notifications', { signal: page.signal });
+ let form = fromData(data);
+ let original = JSON.stringify(form);
+ const dirty = () => JSON.stringify(form) !== original;
+ guardChanges(page, dirty);
+
+ function fromData(d) {
+ return { events: { ...d.events }, windows: d.windows, chat: d.telegramChatId || '', token: '', removeToken: false };
+ }
+
+ const tokenInput = h('input.dati', { type: 'password', id: 'gettone', autocomplete: 'off', spellcheck: 'false' });
+ const chatInput = h('input.dati', { type: 'text', id: 'chat', autocomplete: 'off', spellcheck: 'false', inputmode: 'text' });
+ tokenInput.addEventListener('input', () => { form.token = tokenInput.value; form.removeToken = false; drawSaveBar(); drawTokenNote(); });
+ chatInput.addEventListener('input', () => { form.chat = chatInput.value; drawSaveBar(); });
+ const tokenNote = h('p.aiuto.piccolo');
+ const removeButton = h('button.btn.nudo.piccolo', { type: 'button', onclick: () => { form.removeToken = true; form.token = ''; tokenInput.value = ''; drawSaveBar(); drawTokenNote(); } }, icon('x', 's'), t('impostazioni.notifiche.togliGettone'));
+
+ function drawTokenNote() {
+ tokenInput.placeholder = data.telegramTokenSet && !form.removeToken ? t('impostazioni.notifiche.gettoneSalvato') : t('impostazioni.notifiche.gettoneVuoto');
+ removeButton.hidden = !data.telegramTokenSet || form.removeToken;
+ tokenNote.textContent = form.removeToken ? t('impostazioni.notifiche.gettoneTolto') : t('impostazioni.notifiche.gettoneNota');
+ }
+
+ async function test(channel) {
+ try {
+ const result = await api('/api/settings/notifications/test', { method: 'POST', body: { channel } });
+ toast(result.message, result.sent ? '' : 'errore');
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ function drawSaveBar() {
+ if (!dirty()) {
+ page.saveBar(null);
+ return;
+ }
+ page.saveBar(h('div', { style: { display: 'contents' } },
+ h('span.nota', t('impostazioni.modifiche')),
+ h('div.destra',
+ h('button.btn', { type: 'button', onclick: () => { form = fromData(data); draw(); } }, t('impostazioni.annulla')),
+ h('button.btn.primo', { type: 'button', onclick: save }, icon('check'), t('impostazioni.salva')))));
+ }
+
+ async function save() {
+ try {
+ data = await api('/api/settings/notifications', {
+ method: 'PUT',
+ body: { events: form.events, windows: form.windows, telegramChatId: form.chat.trim() || null, telegramToken: form.token.trim() || null, removeTelegramToken: form.removeToken },
+ });
+ form = fromData(data);
+ original = JSON.stringify(form);
+ draw();
+ toast(t('impostazioni.salvate'));
+ } catch (error) {
+ showError(error);
+ }
+ }
+
+ function draw() {
+ tokenInput.value = form.token;
+ chatInput.value = form.chat;
+ drawTokenNote();
+ fill(box,
+ h('div.sezione',
+ heading(t('impostazioni.notifiche.quando'), t('impostazioni.notifiche.quandoAiuto')),
+ h('div.elenco-leve', EVENTS.map((key) => h('div.leva-riga',
+ toggle({ checked: form.events[key], label: t(`impostazioni.notifiche.eventi.${key}`), onchange: (v) => { form.events[key] = v; drawSaveBar(); } }),
+ h('p.aiuto.piccolo', t(`impostazioni.notifiche.eventiAiuto.${key}`)))))),
+ h('div.sezione',
+ h('div.testa-sez', h('h2.sez', t('impostazioni.notifiche.windows'), ' ', data.windowsAvailable ? null : label(t('impostazioni.notifiche.soloWindows'))),
+ h('p.aiuto', t('impostazioni.notifiche.windowsTesto'))),
+ h('div.riga-azione',
+ toggle({ checked: form.windows && data.windowsAvailable, disabled: !data.windowsAvailable, label: t('impostazioni.notifiche.windows'), onchange: (v) => { form.windows = v; drawSaveBar(); } }),
+ data.windowsAvailable ? h('button.btn.piccolo', { type: 'button', onclick: () => test('windows') }, icon('bell', 's'), t('impostazioni.notifiche.prova')) : null)),
+ h('div.sezione',
+ heading(t('impostazioni.notifiche.telegram'), t('impostazioni.notifiche.telegramAiuto')),
+ data.telegramAvailable ? null : h('div.avviso', { style: { marginBottom: '14px' } }, icon('info', 's'), h('span', t('impostazioni.notifiche.nonAncora'))),
+ h('div.campi-telegram',
+ h('div', h('label.etichetta', { for: 'gettone' }, t('impostazioni.notifiche.gettone')), h('div.riga-campo', h('label.campo', icon('key-round', 's'), tokenInput), removeButton), tokenNote),
+ h('div', h('label.etichetta', { for: 'chat' }, t('impostazioni.notifiche.chat')), h('label.campo', chatInput), h('p.aiuto.piccolo', t('impostazioni.notifiche.chatEsempio')))),
+ h('div.riga-azione', h('button.btn', { type: 'button', onclick: () => test('telegram') }, icon('bell', 's'), t('impostazioni.notifiche.prova')))));
+ chatInput.placeholder = t('impostazioni.notifiche.chatEsempio');
+ drawSaveBar();
+ }
+
+ draw();
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/settings.js b/src/Febe.Web/wwwroot/js/pages/settings.js
new file mode 100644
index 0000000..3384535
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/settings.js
@@ -0,0 +1,74 @@
+// 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» is a page of its own (mockup 10: back link, no sub-menu).
+
+import { withCarried } from '../core/api.js';
+import { h, icon, fill } from '../core/dom.js';
+import { confirmDialog } from '../core/ui.js';
+import { t } from '../core/text.js';
+
+export const SECTIONS = [
+ { key: 'generali', icon: 'sliders-horizontal', load: () => import('./settings-general.js') },
+ { key: 'limiti', icon: 'gauge', load: () => import('./settings-limits.js') },
+ { key: 'collegamento', icon: 'key-round', load: null },
+ { key: 'notifiche', icon: 'bell', load: () => import('./settings-notifications.js') },
+ { key: 'dati', icon: 'database', load: () => import('./settings-data.js') },
+ { key: 'informazioni', icon: 'info', load: () => import('./settings-about.js') },
+];
+
+export default {
+ async mount(page, route) {
+ const key = route.params.section;
+ if (key === 'collegamento') {
+ const connection = await import('./connection.js');
+ return connection.mountConnection(page, route);
+ }
+ const section = SECTIONS.find((s) => s.key === key) || SECTIONS[0];
+ page.title(t('impostazioni.titolo'));
+ document.title = t('app.titoloPagina', { pagina: `${t(`pagine.sezioni.${section.key}`)} · ${t('impostazioni.titolo')}` });
+ const nav = h('nav.sotto-menu', { 'aria-label': t('impostazioni.sezioni') }, SECTIONS.map((s) => h(`a${s.key === section.key ? '.qui' : ''}`, {
+ href: withCarried(`/impostazioni/${s.key}`), 'aria-current': s.key === section.key ? 'page' : null,
+ }, icon(s.icon), h('span', t(`pagine.sezioni.${s.key}`)))));
+ const content = h('div.cont');
+ fill(page.body, h('div.imp', nav, content));
+ const module = await section.load();
+ return module.default(page, content, route);
+ },
+};
+
+/**
+ * Unsaved changes: asks before leaving the page (and before closing the tab). isDirty() → boolean.
+ * Returns allow(): call it after saving or discarding so the next navigation does not ask.
+ */
+export function guardChanges(page, isDirty) {
+ let allowed = false;
+ page.guard(async () => {
+ if (allowed || !isDirty()) return true;
+ const choice = await confirmDialog({
+ title: t('impostazioni.modifiche'),
+ text: t('impostazioni.esci'),
+ buttons: [
+ { label: t('comune.annulla'), value: false, kind: 'nudo', autofocus: true },
+ { label: t('impostazioni.lascia'), value: true, kind: 'pericolo' },
+ ],
+ });
+ if (choice) allowed = true;
+ return Boolean(choice);
+ });
+ const beforeUnload = (e) => {
+ if (!allowed && isDirty()) {
+ e.preventDefault();
+ e.returnValue = '';
+ }
+ };
+ window.addEventListener('beforeunload', beforeUnload);
+ page.onLeave(() => window.removeEventListener('beforeunload', beforeUnload));
+ return () => {
+ allowed = true;
+ };
+}
+
+/** A section heading with its help line. */
+export function heading(title, help, ...extra) {
+ return h('div.testa-sez', h('h2.sez', title, ...extra), help ? h('p.aiuto', help) : null);
+}
diff --git a/src/Febe.Web/wwwroot/js/pages/welcome.js b/src/Febe.Web/wwwroot/js/pages/welcome.js
new file mode 100644
index 0000000..6232a78
--- /dev/null
+++ b/src/Febe.Web/wwwroot/js/pages/welcome.js
@@ -0,0 +1,17 @@
+// Primo avvio (spec §10.3: «la schermata vuota del mockup 13 con i due pulsanti»): when Febe is not connected to
+// Instagram and the library is empty, the library shows this instead of an empty mosaic.
+
+import { withCarried } from '../core/api.js';
+import { h, icon, brand } from '../core/dom.js';
+import { t } from '../core/text.js';
+
+export function welcome() {
+ return h('div.benvenuto',
+ h('div.marchio-benvenuto', brand()),
+ h('h2', t('benvenuto.titolo')),
+ h('p', t('benvenuto.testo')),
+ h('div.bottoni-benvenuto',
+ h('a.btn.primo.grande', { href: withCarried('/impostazioni/collegamento') }, icon('key-round', 's'), t('benvenuto.collegati')),
+ h('a.btn.grande', { href: withCarried('/importa?passo=1') }, icon('folder-input', 's'), t('benvenuto.importa'))),
+ h('p.nota-benvenuto', icon('triangle-alert', 'xs'), ' ', t('benvenuto.nota')));
+}
diff --git a/src/Febe.Web/wwwroot/js/routes.js b/src/Febe.Web/wwwroot/js/routes.js
index e55ca33..cff56ac 100644
--- a/src/Febe.Web/wwwroot/js/routes.js
+++ b/src/Febe.Web/wwwroot/js/routes.js
@@ -2,21 +2,19 @@
// module that draws it (loaded on demand). The server answers every address without an extension with index.html,
// so a new page needs only a line here and its module in js/pages/ (see src/Febe.Web/LEGGIMI.md).
-const placeholder = () => import('./pages/placeholder.js');
-
export const routes = [
{ pattern: /^\/$/, redirect: '/libreria' },
{ pattern: /^\/libreria\/?$/, nav: 'libreria', page: () => import('./pages/library.js') },
{ pattern: /^\/account\/?$/, nav: 'account', page: () => import('./pages/accounts.js') },
{ pattern: /^\/account\/(?\d+)(?:\/(?contenuti|impostazioni|cronologia))?\/?$/, nav: 'account', page: () => import('./pages/account.js') },
- { pattern: /^\/attivita\/?$/, nav: 'attivita', page: placeholder, data: { key: 'attivita' } },
- { pattern: /^\/importa\/?$/, nav: 'importa', page: placeholder, data: { key: 'importa' } },
+ { pattern: /^\/attivita\/?$/, nav: 'attivita', page: () => import('./pages/activity.js') },
+ { pattern: /^\/importa\/?$/, nav: 'importa', page: () => import('./pages/import.js') },
+ { pattern: /^\/doppioni\/?$/, nav: 'attivita', page: () => import('./pages/duplicates.js') },
{ pattern: /^\/impostazioni\/?$/, redirect: '/impostazioni/generali' },
{
pattern: /^\/impostazioni\/(?generali|limiti|collegamento|notifiche|dati|informazioni)\/?$/,
nav: 'impostazioni',
- page: placeholder,
- data: { key: 'impostazioni' },
+ page: () => import('./pages/settings.js'),
},
- { pattern: /^\/browser\/?$/, nav: 'attivita', page: placeholder, data: { key: 'browser' } },
+ { pattern: /^\/browser\/?$/, nav: 'attivita', page: () => import('./pages/browser.js') },
];
diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json
index 2d79f8b..d516601 100644
--- a/src/Febe.Web/wwwroot/testi/it.json
+++ b/src/Febe.Web/wwwroot/testi/it.json
@@ -130,6 +130,7 @@
"nessuno": "Nessun elemento con questi filtri",
"nessunoTesto": "Cambia o togli un filtro per vedere altro.",
"togliFiltri": "Togli i filtri",
+ "doppioni": "1 doppione da decidere|{n} doppioni da decidere",
"tessera": "{tipo} di @{account}, {quando}",
"tesseraFile": "{n} file",
"tesseraDurata": "video di {durata}",
@@ -484,5 +485,479 @@
"aiuto": "È la password scelta per il contenitore (FEBE_PASSWORD).",
"sbagliata": "Password sbagliata.",
"uscita": "Esci"
+ },
+ "attivita": {
+ "titolo": "Attività",
+ "pausa": "Metti in pausa",
+ "riprendi": "Riprendi",
+ "apriBrowser": "Apri il browser",
+ "anteprima": "Anteprima del browser di Febe",
+ "anteprimaOra": "Immagine delle {ora}",
+ "anteprimaVuota": "Il browser è sulla pagina vuota fino alla prossima sessione",
+ "anteprimaVerifica": "Pagina di verifica di Instagram",
+ "anteprimaAccesso": "Pagina di accesso di Instagram",
+ "anteprimaSpenta": "Il browser di Febe non è in funzione",
+ "anteprimaAttesa": "Anteprima in arrivo",
+ "oggi": "Oggi",
+ "striscia": "Striscia della giornata",
+ "adesso": "adesso",
+ "legenda": {
+ "sessione": "Sessione",
+ "prossime": "Prossime, orario indicativo",
+ "rallentamento": "Rallentamento",
+ "fermo": "Fermo",
+ "riposo": "Riposo"
+ },
+ "limiti": "Limiti di oggi",
+ "congelati": "{profilo}, conteggi congelati",
+ "tuttiTetti": "Tutti i tetti",
+ "tetti": {
+ "titolo": "Tutti i tetti",
+ "aiuto": "I tetti orari valgono sugli ultimi 60 minuti, quelli giornalieri sul giorno di calendario. Sopra l'80% il segno diventa ambra; raggiunto un tetto, quel tipo di attività si ferma fino all'ora o al giorno dopo.",
+ "categoria": "Categoria",
+ "ora": "In questa ora",
+ "giorno": "Oggi",
+ "di": "{usati} di {limite}",
+ "cambia": "Cambia i limiti"
+ },
+ "coda": "In coda",
+ "codaVuota": "La coda è vuota.",
+ "fatto": "Appena fatto",
+ "fattoVuoto": "Nessuna azione nelle ultime ore.",
+ "arresti": "Arresti e rallentamenti",
+ "arrestiAiuto": "Gli ultimi 14 giorni. Le durate dei fermi sono fisse: 1 ora, 6 ore, 24 ore.",
+ "arrestiVuoti": "Nessun arresto negli ultimi 14 giorni.",
+ "aperto": "In corso",
+ "risolto": "Risolto {quando}",
+ "fermoFino": "Fermo fino {quando}",
+ "doppioni": "1 doppione probabile dopo gli ultimi scaricamenti aspetta la tua scelta.|{n} doppioni probabili dopo gli ultimi scaricamenti aspettano la tua scelta.",
+ "decidi": "Decidi",
+ "chiesto": "Chiesto da te"
+ },
+ "impostazioni": {
+ "titolo": "Impostazioni",
+ "sezioni": "Sezioni delle impostazioni",
+ "modifiche": "Modifiche non salvate",
+ "nessunaModifica": "Nessuna modifica",
+ "annulla": "Annulla le modifiche",
+ "salva": "Salva",
+ "salvate": "Impostazioni salvate.",
+ "esci": "Hai modifiche non salvate. Vuoi lasciarle?",
+ "lascia": "Lascia le modifiche",
+ "generali": {
+ "cartelle": "Cartelle",
+ "libreria": "Libreria",
+ "libreriaAiuto": "Qui finiscono foto e video, una cartella per account.",
+ "dati": "Dati di Febe",
+ "datiAiuto": "Database, sessione del browser, miniature e registro. Deve stare su un disco locale, non in rete.",
+ "cambia": "Cambia…",
+ "liberi": "{n} liberi",
+ "usati": "{n} usati",
+ "misura": "calcolo…",
+ "dockerNota": "In Docker le cartelle si cambiano dal contenitore, con i volumi /libreria e /dati: qui sono in sola lettura.",
+ "nuovaLibreria": "Usare questa cartella per la libreria?",
+ "nuovaLibreriaTesto": "I nuovi file andranno in {percorso}. Gli account che hanno già file restano nelle loro cartelle: Febe non sposta nessun file.",
+ "usaCartella": "Usa questa cartella",
+ "nuoviDati": "Cambiare la cartella dei dati?",
+ "nuoviDatiTesto": "Dentro ci sono il database e la sessione del browser. La nuova cartella vale dal prossimo avvio di Febe: {percorso}.",
+ "nomi": "Nomi dei file",
+ "nomiAiuto": "Vale per i prossimi download: i file già salvati non vengono rinominati.",
+ "schema": "Schema",
+ "schemaEvidenza": "Schema per le raccolte in evidenza",
+ "risultato": "Risultato",
+ "segnaposto": "Segnaposto: {elenco}.",
+ "dataFile": "Imposta la data del file a quella di pubblicazione",
+ "predefinito": "Torna allo schema predefinito",
+ "aspetto": "Aspetto",
+ "tema": "Tema",
+ "temi": { "chiaro": "Chiaro", "scuro": "Scuro", "sistema": "Come il sistema" },
+ "lingua": "Lingua",
+ "italiano": "Italiano",
+ "linguaNota": "Per ora c'è solo l'italiano.",
+ "avvio": "Avvio",
+ "soloWindows": "Solo versione Windows",
+ "accensione": "Avvia Febe all'accensione del computer",
+ "area": "Chiudendo la finestra, Febe resta attivo nell'area di notifica"
+ },
+ "limiti": {
+ "avviso": "Instagram non pubblica limiti ufficiali. Questi valori sono stime di partenza scelte con prudenza, non limiti ufficiali né misure: riducono il rischio di rallentamenti e verifiche, senza azzerarlo, e vanno ritoccati guardando che cosa succede.",
+ "profilo": "Profilo di prudenza",
+ "profiloAiuto": "Scegli un punto di partenza per orari, pause e tetti. Se poi cambi un valore, il profilo diventa «Su misura».",
+ "profili": {
+ "prudent": "Poche visite brevi, lunghe pause, storico lento.",
+ "balanced": "Più controlli durante il giorno, storico più svelto.",
+ "fast": "Per recuperare in fretta. Più probabili rallentamenti e verifiche.",
+ "custom": "I valori che hai cambiato tu."
+ },
+ "consigliato": "Consigliato",
+ "piuRischio": "Più rischio",
+ "riassunto": "{profili} profili, {storie} storie, {storico} pagine di storico al giorno",
+ "suMisura": "Su misura",
+ "suMisuraTesto": "I valori qui sotto sono tuoi. Scegli un profilo per tornare ai suoi valori.",
+ "rapidoTitolo": "Passare al profilo «Rapido»?",
+ "rapidoTesto": "Con «Rapido» Febe lavora più a lungo e più spesso: recupera prima, ma rallentamenti e verifiche diventano più probabili. Instagram non dice dove sono i limiti: questi valori sono stime.",
+ "rapidoConferma": "Usa «Rapido»",
+ "orari": "Orari",
+ "orariAiuto": "Febe si collega solo in questa fascia. Fuori è tutto fermo, come per una persona che dorme.",
+ "dalle": "Dalle",
+ "alle": "alle",
+ "giorni": "Giorni",
+ "iniziali": ["L", "M", "M", "G", "V", "S", "D"],
+ "nomiGiorni": ["lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato", "domenica"],
+ "sposta": "Sposta ogni giorno inizio e fine fino a",
+ "minuti": "minuti",
+ "fascia": "Fascia oraria",
+ "sessioni": "Sessioni e pause",
+ "sessioniAiuto": "Ogni volta la durata viene estratta a caso dentro questi estremi, senza mai ripetere uno schema fisso.",
+ "durata": "Durata di una sessione",
+ "pausa": "Pausa tra le sessioni",
+ "ritmo": "Ritmo dei gesti",
+ "daA": "da {a} a {b} minuti",
+ "minimo": "minimo",
+ "massimo": "massimo",
+ "ritmi": { "slow": "Lento", "natural": "Naturale", "brisk": "Svelto" },
+ "tetti": "Tetti",
+ "tettiAiuto": "Raggiunto un tetto, quel tipo di attività si ferma fino all'ora o al giorno dopo; le altre proseguono.",
+ "colonne": { "attivita": "Attività", "ora": "All'ora", "giorno": "Al giorno" },
+ "dati": "Dati scaricati",
+ "storico": "Storico per account",
+ "storicoNota": "Valore di partenza del limite di ogni account",
+ "post": "post",
+ "gb": "GB",
+ "graduale": "Avvio graduale",
+ "gradualeAiuto": "Nei primi giorni dopo il collegamento e dopo ogni verifica i tetti partono dalla metà e risalgono piano fino al valore pieno.",
+ "giorniGraduale": "giorni",
+ "arresti": "Arresti dopo un rallentamento",
+ "arrestiTesto": "1 ora la prima volta, 6 ore la seconda nelle 24 ore, 24 ore la terza; poi tetti dimezzati per 48 ore.",
+ "arrestiFissi": "Non si modificano",
+ "salvati": "Limiti salvati: valgono da subito.",
+ "errori": {
+ "pausa": "La pausa minima non può scendere sotto i {n} minuti.",
+ "sessione": "Una sessione non può durare più di {n} minuti.",
+ "sessioneMin": "Una sessione dura almeno 1 minuto.",
+ "fascia": "La fascia oraria non può superare le {n} ore.",
+ "ora": "Scrivi l'ora come 07:30.",
+ "minMax": "Il minimo non può superare il massimo.",
+ "tetto": "Al massimo {max}: il doppio di «Rapido».",
+ "numero": "Serve un numero, zero o più.",
+ "giorni": "Serve almeno un giorno attivo.",
+ "sposta": "Lo spostamento va da 0 a {n} minuti.",
+ "graduale": "Da 0 a {n} giorni.",
+ "correggi": "Correggi i valori segnati in rosso, poi salva."
+ }
+ },
+ "collegamento": {
+ "titolo": "Collegamento a Instagram",
+ "stati": {
+ "notConnected": "Non collegato",
+ "connected": "Collegato",
+ "verificationRequired": "Verifica richiesta",
+ "browserUnavailable": "Browser non disponibile"
+ },
+ "come": "Come collegarti",
+ "passi": [
+ {
+ "titolo": "Accedi nella pagina qui accanto",
+ "testo": "Nome utente, password e, se l'hai attivata, la verifica in due passaggi."
+ },
+ { "titolo": "Aspetta la tua pagina iniziale", "testo": "Se Instagram chiede di salvare l'accesso, accetta." },
+ { "titolo": "Premi «Ho finito»", "testo": "Febe verifica che l'accesso sia riuscito e nasconde il browser." }
+ ],
+ "passiWindows": [
+ {
+ "titolo": "Accedi nella finestra «Browser di Febe»",
+ "testo": "Nome utente, password e, se l'hai attivata, la verifica in due passaggi."
+ },
+ { "titolo": "Aspetta la tua pagina iniziale", "testo": "Se Instagram chiede di salvare l'accesso, accetta." },
+ { "titolo": "Premi «Ho finito»", "testo": "Febe verifica che l'accesso sia riuscito e nasconde il browser." }
+ ],
+ "passwordTitolo": "La password va solo a Instagram.",
+ "passwordDocker": "Qui la scrivi a distanza: i tasti passano dal server di Febe, che li inoltra al browser senza registrarli né salvarli. Resta solo la sessione del browser, nella cartella dei dati.",
+ "passwordWindows": "La scrivi direttamente nella sua pagina: Febe non la riceve e non la salva. Resta solo la sessione del browser, nella cartella dei dati.",
+ "rischio": "Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il rischio per il tuo account, ma non può azzerarlo.",
+ "unMotore": "Usa un solo Febe per account: il contenitore e la versione per Windows non vanno collegati insieme allo stesso profilo.",
+ "finestra": "Il browser di Febe è aperto in un'altra finestra",
+ "finestraTesto": "Accedi lì: quello che scrivi va direttamente alla pagina di Instagram.",
+ "primoPiano": "Portalo in primo piano",
+ "annulla": "Annulla",
+ "hoFinito": "Ho finito",
+ "collegatoCome": "Collegato come @{nome}",
+ "collegatoTesto": "La sessione resta nel profilo del browser, nella cartella dei dati: sopravvive ai riavvii. Febe non conserva password né codici.",
+ "usaBrowser": "Usa il browser",
+ "usaBrowserTesto": "Per controllare qualcosa a mano. Mentre usi il browser il motore resta fermo.",
+ "scollega": "Scollega…",
+ "scollegaTitolo": "Scollegare Febe da Instagram?",
+ "scollegaTesto": "Febe ferma il motore e cancella il profilo del suo browser, con la sessione. Per chiudere la sessione anche dal lato di Instagram, prima esci dal sito usando tu il browser (menu del profilo, «Esci»), poi torna qui.",
+ "scollegaConferma": "Scollega e cancella la sessione",
+ "usaPrima": "Usa prima il browser",
+ "scollegato": "Febe è scollegato da Instagram.",
+ "verificaTitolo": "Instagram chiede una verifica",
+ "verificaTesto": "Completala a mano nella pagina qui accanto, poi premi «Ho finito» e infine «Riprendi».",
+ "nonDisponibileTitolo": "Il browser di Febe non è disponibile",
+ "nonDisponibileTesto": "Febe non ha avviato il suo browser, quindi per ora non ci si può collegare. Controlla il registro e riavvia Febe; se il problema resta, guarda la pagina dei problemi comuni nella guida.",
+ "fermoMentre": "Mentre usi il browser il motore resta fermo."
+ },
+ "notifiche": {
+ "quando": "Quando avvisarti",
+ "quandoAiuto": "La striscia in cima alle pagine c'è sempre; qui scegli che cosa ti raggiunge anche fuori da Febe.",
+ "eventi": {
+ "verification": "Verifica richiesta",
+ "disconnection": "Disconnessione da Instagram",
+ "throttle": "Fermo per rallentamento e ripresa",
+ "backfillDone": "Storico di un account completato",
+ "diskLow": "Disco quasi pieno",
+ "unknownFormat": "Formato non riconosciuto"
+ },
+ "eventiAiuto": {
+ "verification": "Febe si è fermato e serve che tu completi la verifica nel browser.",
+ "disconnection": "La sessione di Instagram non c'è più: serve un nuovo accesso.",
+ "throttle": "Instagram ha chiesto di rallentare: Febe aspetta, poi riparte da solo.",
+ "backfillDone": "Tutti i contenuti passati di un account sono in libreria.",
+ "diskLow": "La libreria o la cartella dei dati stanno finendo lo spazio.",
+ "unknownFormat": "Le risposte di Instagram sono cambiate: alcune ricette sono sospese."
+ },
+ "windows": "Notifiche di Windows",
+ "windowsTesto": "Mostra gli avvisi nell'angolo dello schermo.",
+ "soloWindows": "Solo versione Windows",
+ "prova": "Invia una prova",
+ "telegram": "Telegram",
+ "telegramAiuto": "Facoltativo. Crea un bot con BotFather, scrivigli un messaggio, poi copia qui il suo gettone e l'identificativo della chat.",
+ "gettone": "Gettone del bot",
+ "gettoneSalvato": "Gettone salvato: per cambiarlo scrivine uno nuovo",
+ "gettoneVuoto": "Incolla il gettone di BotFather",
+ "togliGettone": "Togli il gettone",
+ "gettoneTolto": "Il gettone verrà tolto quando salvi.",
+ "chat": "Identificativo della chat",
+ "chatEsempio": "Per esempio 123456789",
+ "gettoneNota": "Il gettone resta nella cartella dei dati di Febe: non finisce nei registri e non viene più mostrato.",
+ "nonAncora": "L'invio dei messaggi Telegram arriva con una prossima versione di Febe: per ora le impostazioni si salvano soltanto."
+ },
+ "dati": {
+ "cartella": "Cartella dei dati",
+ "contiene": "Database, profilo del browser con la sessione di Instagram, miniature, registro e copie del database.",
+ "spazio": "{usati} usati, {liberi} liberi sul disco",
+ "spazioMisura": "Misura in corso…",
+ "sessione": "Chi ha accesso a questa cartella, o a una sua copia, ha accesso alla tua sessione di Instagram: tienila al sicuro e non condividerla.",
+ "database": "Database",
+ "copie": "Copie del database",
+ "copieAiuto": "Una copia al giorno, fatta da sola, nella cartella {cartella}; si tengono gli ultimi {n} giorni.",
+ "nessunaCopia": "Nessuna copia ancora.",
+ "faiCopia": "Fai una copia adesso",
+ "colonne": { "giorno": "Giorno", "file": "File", "peso": "Peso", "fatta": "Fatta" },
+ "ricostruisci": "Ricostruisci il database dalla libreria",
+ "ricostruisciAiuto": "Serve se il database si è perso o rovinato: Febe rilegge le cartelle degli account e i loro file _febe.jsonl, ricalcola impronte e miniature e rispetta le eliminazioni. Non riscarica nulla e non sposta né cancella file.",
+ "ricostruisciBtn": "Ricostruisci…",
+ "confTitolo": "Ricostruire il database dalla libreria?",
+ "confTesto": "Con una libreria grande può durare a lungo. Gli elementi già presenti restano come sono; gli account ricreati tornano «In pausa». Prima conviene fare una copia del database.",
+ "confScrivi": "Per confermare scrivi «ricostruisci»",
+ "confParola": "ricostruisci",
+ "confBtn": "Ricostruisci il database",
+ "inCorso": "Ricostruzione in corso: {fatte} di {totale} cartelle, {file} file controllati.",
+ "inCorsoCartella": "Ora: {cartella}",
+ "finita": "Ricostruzione finita {quando}.",
+ "resoconto": "Resoconto"
+ },
+ "informazioni": {
+ "programma": "Programma",
+ "versione": "Versione",
+ "veste": "Veste",
+ "vesti": { "Docker": "Docker, sul server di casa", "Windows": "Windows" },
+ "guida": "Guida per l'uso",
+ "guidaTesto": "La guida è nel wiki del repository di Febe.",
+ "apriGuida": "Apri la guida",
+ "cartelle": "Cartelle",
+ "cartellaDati": "Dati",
+ "cartellaLibreria": "Libreria",
+ "rischioTitolo": "Il rischio per il tuo account",
+ "rischio": "Scaricare contenuti con un programma è contro le condizioni d'uso di Instagram: il rischio concreto è la limitazione o la chiusura dell'account. Febe lo riduce andando piano, usando un browser vero in cui accedi tu e fermandosi al primo segnale, ma non può azzerarlo. Le storie aperte da Febe risultano viste. I contenuti restano dei loro autori: Febe è un archivio privato.",
+ "licenze": "Licenze",
+ "licenzeAiuto": "Febe usa questi componenti, copiati nel programma con le loro licenze:",
+ "componenti": [
+ { "nome": "Archivo", "testo": "carattere, SIL Open Font License 1.1", "file": "/caratteri/LICENZA-OFL.txt" },
+ { "nome": "Lucide", "testo": "icone, licenza ISC", "file": "/icone/LICENZA-ISC.txt" },
+ { "nome": "SQLite e Microsoft.Data.Sqlite", "testo": "database, pubblico dominio e licenza MIT" },
+ { "nome": "SkiaSharp", "testo": "miniature e impronte delle immagini, licenza MIT" },
+ { "nome": ".NET e ASP.NET Core", "testo": "licenza MIT" },
+ { "nome": "WebView2", "testo": "solo versione Windows, licenza Microsoft" }
+ ],
+ "leggiLicenza": "Leggi la licenza"
+ }
+ },
+ "browser": {
+ "titolo": "Browser di Febe",
+ "aiuto": "Mentre usi il browser il motore resta fermo. Quando hai finito, premi «Ho finito».",
+ "vista": "Browser di Febe, vista remota",
+ "segnaposto": "Qui compare la vera pagina di Instagram, caricata dal sito. Febe non la ridisegna e non la imita.",
+ "segnapostoAccesso": "Qui compare la vera pagina di accesso di Instagram, caricata dal sito. Febe non la ridisegna e non la imita.",
+ "indietro": "Indietro",
+ "ricarica": "Ricarica",
+ "indirizzo": "Indirizzo della pagina",
+ "collegamento": "Collegamento alla vista remota…",
+ "nonRisponde": "La vista remota non risponde: il browser di Febe non è raggiungibile in questo momento.",
+ "riprova": "Riprova",
+ "schermo": "Pagina del browser di Febe: clicca per usarla con mouse e tastiera"
+ },
+ "importa": {
+ "titolo": "Importa",
+ "passi": { "sorgente": "Sorgente", "analisi": "Analisi", "revisione": "Revisione", "copia": "Copia" },
+ "passiEtichetta": "Passi dell'importazione",
+ "fatto": "fatto",
+ "sorgente": {
+ "titolo": "Scegli la cartella da importare",
+ "aiuto": "Febe la legge senza toccarla: niente viene copiato o spostato finché non lo decidi tu.",
+ "aiutoDocker": "Si importa dalle cartelle di {radice}: gli originali restano dove sono.",
+ "scegli": "Scegli una cartella…",
+ "analizza": "Analizza questa cartella",
+ "vuota": "Nessuna cartella qui dentro.",
+ "su": "Cartella superiore",
+ "scelta": "Cartella scelta",
+ "solaLettura": "In sola lettura: si può solo copiare.",
+ "stogram": "Leggi i nomi alla maniera di 4K Stogram (ipotesi da verificare)",
+ "stogramAiuto": "Sembra una libreria di 4K Stogram. Il riconoscitore dei suoi nomi è un'ipotesi non ancora provata su file veri: se lo usi, controlla date e codici nella revisione.",
+ "febe": "Sembra una libreria di Febe: date e codici si leggono dai suoi file _febe.jsonl.",
+ "precedenti": "Importazioni precedenti",
+ "apri": "Apri",
+ "stati": {
+ "analyzing": "Analisi in corso",
+ "analysisInterrupted": "Analisi interrotta",
+ "reviewing": "Da rivedere",
+ "copying": "Copia in corso",
+ "copyInterrupted": "Copia interrotta",
+ "completed": "Completata",
+ "cancelled": "Annullata"
+ }
+ },
+ "analisi": {
+ "titolo": "Analisi in corso",
+ "aiuto": "Sola lettura: nessun file viene copiato o spostato. Puoi interrompere e riprendere quando vuoi.",
+ "conteggio": "{fatti} di {totale} file",
+ "elenco": "Elenco dei file della cartella…",
+ "ora": "Ora: {file}",
+ "interrompi": "Interrompi",
+ "riprendi": "Riprendi l'analisi",
+ "interrotta": "Analisi interrotta: riprende da dove era rimasta.",
+ "annulla": "Annulla l'importazione",
+ "annullaTitolo": "Annullare questa importazione?",
+ "annullaTesto": "Febe dimentica l'analisi fatta. Nessun file della sorgente viene toccato.",
+ "annullata": "Importazione annullata: nessun file della sorgente è stato toccato.",
+ "trovati": "Finora: {nuovi} nuovi, {gia} già in libreria, {doppioni} doppioni probabili, {altri} non riconosciuti."
+ },
+ "revisione": {
+ "cambia": "Cambia sorgente",
+ "contatori": {
+ "new": { "titolo": "Nuovi", "testo": "Non ci sono in libreria" },
+ "already": { "titolo": "Già in libreria", "testo": "Identici, verranno saltati" },
+ "dup": { "titolo": "Doppioni probabili", "testo": "Stessa immagine, file diverso: decidi tu" },
+ "unrec": { "titolo": "Non riconosciuti", "testo": "Né foto né video, ignorati" }
+ },
+ "cartelle": "Cartelle e account",
+ "colonne": {
+ "cartella": "Cartella sorgente",
+ "file": "File",
+ "va": "Va in",
+ "nuovi": "Nuovi",
+ "presenti": "Già presenti"
+ },
+ "scegli": "Scegli un account…",
+ "nuovo": "Nuovo account, solo archivio",
+ "nuovoNome": "Nuovo, solo archivio: @{nome}",
+ "nuovoChiedi": "Nome del nuovo account «Solo archivio»",
+ "nuovoAltro": "Nuovo account, solo archivio, con un altro nome…",
+ "nomeRegole": "Un nome utente: lettere, cifre, punti e trattini bassi, al massimo 30 caratteri.",
+ "nessunNome": "Nessun nome di account riconosciuto",
+ "esistenti": "Account in Febe",
+ "riconosciuti": "Dai nomi dei file Febe ha ricavato data e codice di {n} elementi: quando terrà aggiornati questi account non li riscaricherà.",
+ "stogram": "I nomi sono stati letti con l'ipotesi su 4K Stogram, non ancora verificata: controlla date e codici prima di importare."
+ },
+ "doppioni": {
+ "titolo": "Doppioni probabili",
+ "diN": "{n} di {totale}",
+ "precedente": "Doppione precedente",
+ "successivo": "Doppione successivo",
+ "inLibreria": "In libreria",
+ "nellaSorgente": "Già nella sorgente",
+ "daImportare": "Da importare",
+ "piuGrande": "Più grande",
+ "misure": "{l} × {a}, {peso}",
+ "dove": "{account}, {giorno}",
+ "tieniGrande": "Tieni il più grande e scarta l'altro",
+ "tieniLibreria": "Tieni quello già in libreria",
+ "tieniEntrambi": "Tienili entrambi",
+ "applicaTutti": "Fai lo stesso per gli altri {n}",
+ "applicaUno": "Fai lo stesso per l'altro",
+ "togli": "Togli la scelta",
+ "nessuno": "Nessun doppione probabile in questa importazione.",
+ "fatti": "Hai deciso tutti i doppioni probabili.",
+ "motivi": {
+ "sameInstagramId": "Stesso codice di Instagram, file diverso",
+ "visuallySimilar": "Stessa immagine, file diverso"
+ },
+ "senzaAnteprima": "Anteprima non disponibile",
+ "decisi": "Scelta fatta"
+ },
+ "barra": {
+ "modo": "Copia o sposta",
+ "copia": "Copia",
+ "sposta": "Sposta",
+ "copiaAiuto": "Gli originali restano dove sono.",
+ "spostaAiuto": "Ogni originale si cancella solo dopo aver verificato la sua copia.",
+ "esporta": "Esporta l'elenco in CSV"
+ },
+ "sposta": {
+ "titolo": "Importare e spostare?",
+ "testo": "Ogni originale si cancella dalla sorgente solo dopo che la sua copia in libreria è stata riletta e verificata con lo SHA-256. I file saltati non si toccano.",
+ "conferma": "Importa e sposta"
+ },
+ "copia": {
+ "titolo": "Copia in corso",
+ "aiuto": "Ogni file viene copiato con un nome temporaneo, verificato e poi rinominato. Puoi interrompere e riprendere.",
+ "conteggio": "{fatti} di {totale} file, {copiati} copiati",
+ "interrotta": "Copia interrotta: riprende da dove era rimasta.",
+ "riprendi": "Riprendi la copia"
+ },
+ "resoconto": {
+ "titolo": "Resoconto",
+ "completata": "Importazione completata {quando}.",
+ "annullata": "Importazione annullata.",
+ "copiati": "Copiati in libreria",
+ "spostati": "di cui spostati",
+ "sostituiti": "di cui sostituiti",
+ "saltati": "Saltati",
+ "fuori": "Rimasti fuori",
+ "falliti": "Non riusciti",
+ "perAccount": "Importati per account",
+ "giaPerAccount": "Già in libreria, per account",
+ "nonRiconosciuti": "Non riconosciuti",
+ "problemi": "Da guardare",
+ "nessuno": "Nessuno",
+ "nuova": "Nuova importazione",
+ "libreria": "Apri la libreria",
+ "rimasti": "Torna alla revisione dei rimasti",
+ "altri": "e altri, nel CSV"
+ }
+ },
+ "doppioni": {
+ "titolo": "Doppioni da decidere",
+ "aiuto": "Dopo uno scaricamento Febe ha trovato foto che sembrano la stessa immagine salvata due volte nello stesso account. Restano entrambe finché non scegli: niente si cancella da solo, e ciò che scarti non viene riscaricato.",
+ "nessuno": "Nessun doppione da decidere",
+ "nessunoTesto": "Quando Febe trova la stessa foto salvata due volte, la mette qui e aspetta la tua scelta.",
+ "esistente": "Già in libreria",
+ "nuovo": "Appena scaricato",
+ "conferma": "Applica la scelta"
+ },
+ "benvenuto": {
+ "titolo": "Benvenuto in Febe",
+ "testo": "Febe conserva sul tuo disco foto, video e storie degli account che scegli, e li tiene aggiornati poco per volta. Per cominciare collega il tuo account di Instagram, oppure porta in libreria le foto e i video che hai già.",
+ "collegati": "Collegati a Instagram",
+ "importa": "Importa foto e video che hai già",
+ "nota": "Scaricare con un programma è contro le condizioni d'uso di Instagram: Febe va piano per ridurre il rischio, ma non può azzerarlo."
+ },
+ "problemi": {
+ "titolo": "Febe non può partire",
+ "aiuto": "Il motore è fermo finché questo problema non è risolto. Nessun dato è andato perso.|Il motore è fermo finché questi problemi non sono risolti. Nessun dato è andato perso.",
+ "cosa": "Che cosa è successo",
+ "rimedio": "Che cosa fare",
+ "ricarica": "Ricarica la pagina",
+ "guida": "Altri problemi comuni sono spiegati nella guida."
}
}
diff --git a/tests/Febe.Tests/Library/DownloadDuplicateReviewTests.cs b/tests/Febe.Tests/Library/DownloadDuplicateReviewTests.cs
new file mode 100644
index 0000000..dfbc857
--- /dev/null
+++ b/tests/Febe.Tests/Library/DownloadDuplicateReviewTests.cs
@@ -0,0 +1,123 @@
+using Febe.Core.Domain;
+using Febe.Core.Library;
+using Febe.Tests.Support;
+
+namespace Febe.Tests.Library;
+
+///
+/// The review of probable duplicates found after a download (spec §9.5): nothing is decided in advance, both files stay
+/// until Alberto chooses, and only his choice removes a file (rule 12) — the whole entry when it had one file (remembered,
+/// so it is not downloaded again), only that position for a series.
+///
+[TestClass]
+public sealed class DownloadDuplicateReviewTests
+{
+ private static readonly int[] Scenes = [100, 237, 391];
+
+ private static async Task<(TestLibrary Lib, Account Account, EntryWithMedia Older, EntryWithMedia Newer)> TwoSimilarAsync(TempFolder temp, bool newerIsSeries = false)
+ {
+ var lib = await TestLibrary.CreateAsync(temp);
+ var account = await lib.Db.Accounts.AddAsync(Make.Account("doppie.prova"));
+ var older = await lib.SaveAsync(account, Make.Entry(account.Id, "100", Make.T0 - TimeSpan.FromDays(3)), [TestFile.Photo(1, 41, 1080, 1350)]);
+ IReadOnlyList files = newerIsSeries
+ ? [TestFile.Photo(1, 41, 720, 900), TestFile.Photo(2, 77, 1080, 1080)]
+ : [TestFile.Photo(1, 41, 720, 900)];
+ var newer = await lib.SaveAsync(account, Make.Entry(account.Id, "200", Make.T0), files);
+ return (lib, account, older, newer);
+ }
+
+ private static DownloadDuplicateReview Review(TestLibrary lib) => new(lib.Db, lib.Layout, lib.Journal, lib.Clock, lib.Thumbnails, lib.Index);
+
+ [TestMethod]
+ public async Task ThePairWaitsWithNothingDecidedAndBothFilesStay()
+ {
+ using var temp = new TempFolder("doppioni");
+ var (lib, account, older, newer) = await TwoSimilarAsync(temp);
+ await using var _ = lib;
+ var review = Review(lib);
+ Assert.AreEqual(1, await review.CountPendingAsync());
+ var cases = await review.ListAsync();
+ Assert.HasCount(1, cases);
+ var c = cases[0];
+ Assert.AreEqual(DuplicateDecision.Pending, c.Pair.Decision);
+ Assert.AreEqual(older.Media[0].Id, c.Existing.MediaId);
+ Assert.AreEqual(newer.Media[0].Id, c.Candidate.MediaId);
+ Assert.IsFalse(c.CandidateIsLarger, "the file already there has more pixels");
+ Assert.AreEqual("doppie.prova", c.Existing.Username);
+ Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, older.Media[0].RelativePath!)));
+ Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, newer.Media[0].RelativePath!)));
+
+ var result = await review.DecideAsync(c.Pair.Id, DuplicateDecision.KeepBoth);
+ Assert.AreEqual(1, result.Decided);
+ Assert.AreEqual(0, result.FilesRemoved);
+ Assert.AreEqual(0, await review.CountPendingAsync());
+ Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, newer.Media[0].RelativePath!)), "«Tienili entrambi» removes nothing");
+ await Assert.ThrowsExactlyAsync(() => review.DecideAsync(9999, DuplicateDecision.KeepBoth));
+ await Assert.ThrowsExactlyAsync(() => review.DecideAsync(c.Pair.Id, DuplicateDecision.Pending));
+ }
+
+ [TestMethod]
+ public async Task KeepTheLargerRemovesTheSmallerEntryAndRemembersIt()
+ {
+ using var temp = new TempFolder("doppioni");
+ var (lib, account, older, newer) = await TwoSimilarAsync(temp);
+ await using var _ = lib;
+ var review = Review(lib);
+ var c = (await review.ListAsync())[0];
+ var result = await review.DecideAsync(c.Pair.Id, DuplicateDecision.KeepLarger);
+ Assert.AreEqual(1, result.FilesRemoved);
+ Assert.IsEmpty(result.Problems);
+ Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, older.Media[0].RelativePath!)), "the larger stays");
+ Assert.IsFalse(File.Exists(lib.Layout.FullPath(account, newer.Media[0].RelativePath!)), "the smaller goes, by Alberto's choice");
+ var entry = await lib.Db.Entries.GetAsync(newer.Entry.Id);
+ Assert.AreEqual(EntryState.Deleted, entry!.State, "remembered: it is not downloaded again");
+ Assert.AreEqual(DuplicateDecision.KeepLarger, (await lib.Db.Duplicates.GetAsync(c.Pair.Id))!.Decision);
+ }
+
+ [TestMethod]
+ public async Task AFileOfASeriesLeavesOnlyItsPosition()
+ {
+ using var temp = new TempFolder("doppioni");
+ var (lib, account, older, newer) = await TwoSimilarAsync(temp, newerIsSeries: true);
+ await using var _ = lib;
+ var review = Review(lib);
+ var c = (await review.ListAsync()).Single(x => x.Candidate.EntryId == newer.Entry.Id);
+ Assert.AreEqual(2, c.Candidate.FilesInEntry);
+ var result = await review.DecideAsync(c.Pair.Id, DuplicateDecision.KeepExisting);
+ Assert.AreEqual(1, result.FilesRemoved);
+ var stored = (await lib.Db.Entries.GetWithMediaAsync(newer.Entry.Id))!;
+ Assert.AreNotEqual(EntryState.Deleted, stored.Entry.State, "the entry stays with its other file");
+ Assert.AreEqual(MediaState.Deleted, stored.Media.Single(m => m.Position == 1).State);
+ Assert.IsFalse(File.Exists(lib.Layout.FullPath(account, newer.Media.Single(m => m.Position == 1).RelativePath!)));
+ Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, newer.Media.Single(m => m.Position == 2).RelativePath!)));
+ Assert.IsTrue(File.Exists(lib.Layout.FullPath(account, older.Media[0].RelativePath!)));
+
+ // The journal received the entry again with only the file that remains: a rebuild keeps the choice.
+ var journal = await File.ReadAllLinesAsync(AccountJournal.PathFor(lib.Layout.AccountFolder(account)));
+ var last = journal.Last(l => l.Contains("\"200\"", StringComparison.Ordinal));
+ StringAssert.Contains(last, newer.Media.Single(m => m.Position == 2).RelativePath!);
+ Assert.DoesNotContain(newer.Media.Single(m => m.Position == 1).RelativePath!, last);
+ }
+
+ [TestMethod]
+ public async Task OneChoiceCanGoToEveryPendingPair()
+ {
+ using var temp = new TempFolder("doppioni");
+ var lib = await TestLibrary.CreateAsync(temp);
+ await using var _ = lib;
+ var account = await lib.Db.Accounts.AddAsync(Make.Account("molte.prova"));
+ for (var i = 0; i < 3; i++)
+ {
+ await lib.SaveAsync(account, Make.Entry(account.Id, $"a{i}", Make.T0 - TimeSpan.FromDays(10 + i)), [TestFile.Photo(1, Scenes[i], 1080, 1350)]);
+ await lib.SaveAsync(account, Make.Entry(account.Id, $"b{i}", Make.T0 - TimeSpan.FromDays(i)), [TestFile.Photo(1, Scenes[i], 640, 800)]);
+ }
+
+ var review = Review(lib);
+ Assert.AreEqual(3, await review.CountPendingAsync());
+ var first = (await review.ListAsync())[0];
+ var result = await review.DecideAsync(first.Pair.Id, DuplicateDecision.KeepExisting, applyToAllPending: true);
+ Assert.AreEqual(3, result.Decided);
+ Assert.AreEqual(3, result.FilesRemoved);
+ Assert.AreEqual(0, await review.CountPendingAsync());
+ }
+}
diff --git a/tests/Febe.Tests/Web/ActivityApiTests.cs b/tests/Febe.Tests/Web/ActivityApiTests.cs
new file mode 100644
index 0000000..19b7b72
--- /dev/null
+++ b/tests/Febe.Tests/Web/ActivityApiTests.cs
@@ -0,0 +1,117 @@
+using System.Net;
+using Febe.Core.Abstractions;
+using Febe.Core.Domain;
+using Febe.Core.Library;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Part2Support;
+using Febe.Tests.Web.Support;
+using Febe.Web.Engine;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Febe.Tests.Web;
+
+///
+/// What the Attività page reads beside the engine snapshot (spec §7.6, §7.9, §9.5): the stops of the last days with the
+/// advice after three throttles, the still frame of the browser, and the review of probable duplicates after a download.
+///
+[TestClass]
+public sealed class ActivityApiTests
+{
+ [TestMethod]
+ public async Task TheStopsOfTheLastDaysWithTheAdviceAfterThreeThrottles()
+ {
+ await using var server = await Part2.StartAsync();
+ Assert.AreEqual(0, (await server.GetJsonAsync("/api/engine/incidents")).GetProperty("items").GetArrayLength());
+ var now = server.Clock.Now;
+ for (var i = 1; i <= 3; i++)
+ {
+ var at = now - TimeSpan.FromDays(i);
+ var incident = await server.Db.Incidents.OpenAsync(new Incident { At = at, Level = SignalLevel.Throttle, Signal = "http-429", Url = "https://www.instagram.com/x/?firmato=1", StoppedUntil = at + TimeSpan.FromHours(1) });
+ await server.Db.Incidents.ResolveAsync(incident.Id, at + TimeSpan.FromHours(1));
+ }
+
+ await server.Db.Incidents.OpenAsync(new Incident { At = now - TimeSpan.FromMinutes(5), Level = SignalLevel.Challenge, Signal = "challenge-url", Url = "https://www.instagram.com/challenge/" });
+ var list = await server.GetJsonAsync("/api/engine/incidents");
+ var items = list.Items("items").ToList();
+ Assert.HasCount(4, items);
+ Assert.AreEqual("challenge", items[0].Str("level"), "newest first");
+ Assert.IsTrue(items[0].Bool("open"));
+ Assert.AreEqual("Verifica richiesta", items[0].Str("title"));
+ Assert.AreEqual("https://www.instagram.com/x/", items[1].Str("url"), "addresses without their query string");
+ Assert.AreEqual(3, list.Int("throttlesLastWeek"));
+ StringAssert.Contains(list.Str("advice"), "profilo più prudente");
+ }
+
+ [TestMethod]
+ public async Task ThePreviewIsAFrameWhenTheShellHasOne()
+ {
+ await using (var none = await Part2.StartAsync())
+ {
+ var empty = await none.GetJsonAsync("/api/browser/preview");
+ Assert.IsFalse(empty.Bool("hasFrame"));
+ var (status, _, _) = await none.GetAsync("/api/browser/preview/frame");
+ Assert.AreEqual(HttpStatusCode.NotFound, status);
+ }
+
+ var jpeg = TestFile.PhotoBytes(5, 320, 180);
+ var preview = new FixedPreview(new BrowserFrame(jpeg, "https://www.instagram.com/stories/marta.prova/?segreto=1", Make.T0));
+ await using var server = await Part2.StartAsync(services: s => s.AddSingleton(preview));
+ var dto = await server.GetJsonAsync("/api/browser/preview");
+ Assert.IsTrue(dto.Bool("hasFrame"));
+ Assert.AreEqual("https://www.instagram.com/stories/marta.prova/", dto.Str("url"));
+ using var response = await server.Client.GetAsync(dto.Str("frame"));
+ Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
+ Assert.AreEqual("image/jpeg", response.Content.Headers.ContentType?.MediaType);
+ Assert.AreEqual("no-store", response.Headers.CacheControl?.ToString());
+ CollectionAssert.AreEqual(jpeg, await response.Content.ReadAsByteArrayAsync());
+ }
+
+ [TestMethod]
+ public async Task ProbableDuplicatesAfterADownloadWaitForAlbertoAndHisChoiceIsApplied()
+ {
+ await using var server = await Part2.StartAsync();
+ var index = new PerceptualHashIndex();
+ var journal = new AccountJournal(server.Clock);
+ var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, journal, server.Clock, server.Library.Thumbnails, index);
+ var account = await server.Db.Accounts.AddAsync(Make.Account("doppia.prova"));
+ async Task SaveAsync(string id, DateTimeOffset at, int width, int height)
+ {
+ var added = await server.Db.Entries.AddAsync(Make.Entry(account.Id, id, at), [Make.Photo(1)]);
+ var bytes = TestFile.PhotoBytes(61, width, height);
+ await ingest.SaveMediaAsync(account, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = new MemoryStream(bytes), Extension = ".jpg" });
+ await ingest.AppendJournalAsync(added.Stored.Entry.Id);
+ return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!;
+ }
+
+ var older = await SaveAsync("1", Make.T0 - TimeSpan.FromDays(2), 1080, 1350);
+ var newer = await SaveAsync("2", Make.T0, 720, 900);
+ var counts = await server.GetJsonAsync("/api/duplicates/count");
+ Assert.AreEqual(1, counts.Int("download"));
+ Assert.AreEqual(0, counts.Int("import"));
+
+ var page = await server.GetJsonAsync("/api/duplicates");
+ var c = page.Items("cases").Single();
+ Assert.AreEqual("pending", c.Str("decision"), "nothing is chosen in advance");
+ Assert.AreEqual("visuallySimilar", c.Str("reason"));
+ Assert.IsFalse(c.Bool("candidateIsLarger"));
+ StringAssert.StartsWith(c.GetProperty("existing").Str("image"), "/api/thumbnails/");
+ Assert.AreEqual(1080, c.GetProperty("existing").Int("width"));
+
+ var (badStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/duplicates/{c.Long("pairId")}", new { decision = "pending", applyToAll = false });
+ Assert.AreEqual(HttpStatusCode.BadRequest, badStatus);
+ var (status, result) = await server.SendJsonAsync(HttpMethod.Post, $"/api/duplicates/{c.Long("pairId")}", new { decision = "keepLarger", applyToAll = false });
+ Assert.AreEqual(HttpStatusCode.OK, status);
+ Assert.AreEqual(1, result.Int("filesRemoved"));
+ Assert.AreEqual(0, result.Int("pending"));
+ Assert.IsTrue(File.Exists(server.Library.Layout.FullPath(account, older.Media[0].RelativePath!)));
+ Assert.IsFalse(File.Exists(server.Library.Layout.FullPath(account, newer.Media[0].RelativePath!)));
+ Assert.AreEqual(EntryState.Deleted, (await server.Db.Entries.GetAsync(newer.Entry.Id))!.State);
+ var (missing, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/duplicates/{c.Long("pairId") + 50}", new { decision = "keepBoth", applyToAll = false });
+ Assert.AreEqual(HttpStatusCode.NotFound, missing);
+ }
+
+ private sealed class FixedPreview(BrowserFrame frame) : IBrowserPreview
+ {
+ public Task GetLatestAsync(CancellationToken ct) => Task.FromResult(frame);
+ }
+}
diff --git a/tests/Febe.Tests/Web/ConnectionApiTests.cs b/tests/Febe.Tests/Web/ConnectionApiTests.cs
new file mode 100644
index 0000000..8dff6e2
--- /dev/null
+++ b/tests/Febe.Tests/Web/ConnectionApiTests.cs
@@ -0,0 +1,102 @@
+using System.Net;
+using Febe.Tests.Web.Part2Support;
+using Febe.Tests.Web.Support;
+using Febe.Web.Connection;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Febe.Tests.Web;
+
+///
+/// The link to Instagram over (Connection/PROTOCOLLO.md, spec §4.1): the default
+/// «browser non disponibile» when the composition registers none, a registered service used as it is, the Origin
+/// check on the commands (§13.1), and the configuration problems of /api/capabilities (§8.2, §11).
+///
+[TestClass]
+public sealed class ConnectionApiTests
+{
+ [TestMethod]
+ public async Task WithoutAServiceTheBrowserIsUnavailableAndCommandsSaySo()
+ {
+ await using var server = await Part2.StartAsync();
+ var status = await server.GetJsonAsync("/api/connection");
+ Assert.AreEqual("browserUnavailable", status.Str("state"));
+ Assert.IsFalse(status.Bool("userIsDriving"));
+
+ var (beginStatus, begin) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/begin", new { openLogin = true });
+ Assert.AreEqual(HttpStatusCode.BadRequest, beginStatus);
+ StringAssert.Contains(begin.Str("message"), "browser di Febe non è disponibile");
+
+ var (finishStatus, finish) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/finish");
+ Assert.AreEqual(HttpStatusCode.OK, finishStatus);
+ Assert.IsFalse(finish.Bool("connected"));
+ Assert.IsFalse(string.IsNullOrWhiteSpace(finish.Str("message")));
+
+ var (cancelStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
+ Assert.AreEqual(HttpStatusCode.NoContent, cancelStatus);
+ var (disconnectStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/disconnect");
+ Assert.AreEqual(HttpStatusCode.BadRequest, disconnectStatus);
+ }
+
+ [TestMethod]
+ public async Task ARegisteredServiceIsUsedAndHoFinitoLetsRiprendiActivate()
+ {
+ var connection = new RecordingConnection();
+ await using var server = await Part2.StartAsync(services: s => s.AddSingleton(connection));
+
+ var status = await server.GetJsonAsync("/api/connection");
+ Assert.AreEqual("notConnected", status.Str("state"));
+ Assert.AreEqual("https://www.instagram.com/accounts/login/", status.Str("currentUrl"));
+
+ var (beginStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/begin", new { openLogin = true });
+ Assert.AreEqual(HttpStatusCode.NoContent, beginStatus);
+ Assert.IsTrue((await server.GetJsonAsync("/api/connection")).Bool("userIsDriving"));
+
+ var (finishStatus, finish) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/finish");
+ Assert.AreEqual(HttpStatusCode.OK, finishStatus);
+ Assert.IsTrue(finish.Bool("connected"));
+ Assert.AreEqual("connected", (await server.GetJsonAsync("/api/connection")).Str("state"));
+ Assert.IsNotNull(server.App.Services.GetRequiredService().LastUsedAt, "«Ho finito» counts as having used the browser");
+
+ await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
+ await server.SendJsonAsync(HttpMethod.Post, "/api/connection/disconnect");
+ CollectionAssert.AreEqual(new[] { "begin:True", "finish", "cancel", "disconnect" }, connection.Calls);
+ }
+
+ [TestMethod]
+ public async Task CommandsFromAnotherPageAreRefused()
+ {
+ var connection = new RecordingConnection();
+ await using var server = await Part2.StartAsync(services: s => s.AddSingleton(connection));
+ foreach (var path in new[] { "/api/connection/begin", "/api/connection/finish", "/api/connection/disconnect" })
+ {
+ using var request = server.Request(HttpMethod.Post, path, new { openLogin = true }, origin: "http://altro.example");
+ using var response = await server.Client.SendAsync(request);
+ Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path);
+ }
+
+ using var crossSite = server.Request(HttpMethod.Post, "/api/connection/disconnect", origin: null);
+ crossSite.Headers.Add("Sec-Fetch-Site", "cross-site");
+ using var crossResponse = await server.Client.SendAsync(crossSite);
+ Assert.AreEqual(HttpStatusCode.Forbidden, crossResponse.StatusCode);
+ Assert.IsEmpty(connection.Calls, "no command reached the service");
+ }
+
+ [TestMethod]
+ public async Task CapabilitiesListTheConfigurationProblems()
+ {
+ await using (var clean = await Part2.StartAsync())
+ {
+ var caps = await clean.GetJsonAsync("/api/capabilities");
+ Assert.AreEqual(0, caps.GetProperty("problems").GetArrayLength(), "the default registration has no problems");
+ }
+
+ var problem = new ConfigurationProblem("password-mancante", "Manca la password dell'interfaccia", "Il motore non è partito.", "Imposta FEBE_PASSWORD e riavvia.");
+ await using var server = await Part2.StartAsync(services: s => s.AddSingleton(new FixedProblems(problem)));
+ var listed = (await server.GetJsonAsync("/api/capabilities")).Items("problems").ToList();
+ Assert.HasCount(1, listed);
+ Assert.AreEqual("password-mancante", listed[0].Str("code"));
+ Assert.AreEqual(problem.Title, listed[0].Str("title"));
+ Assert.AreEqual(problem.Message, listed[0].Str("message"));
+ Assert.AreEqual(problem.Remedy, listed[0].Str("remedy"));
+ }
+}
diff --git a/tests/Febe.Tests/Web/DemoPart2Tests.cs b/tests/Febe.Tests/Web/DemoPart2Tests.cs
new file mode 100644
index 0000000..1f6d0a8
--- /dev/null
+++ b/tests/Febe.Tests/Web/DemoPart2Tests.cs
@@ -0,0 +1,148 @@
+using System.Net;
+using System.Text.Json;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Support;
+using Febe.Web.Demo;
+
+namespace Febe.Tests.Web;
+
+///
+/// The demo of the second part (spec §10.6): every page works with coherent fake data and the scenes normale,
+/// sessione, fermo, scollegato and errore; /importa?passo=3 has a realistic review; there are duplicates to decide.
+///
+[TestClass]
+public sealed class DemoPart2Tests
+{
+ private static TempFolder? s_temp;
+ private static DemoHost? s_demo;
+ private static HttpClient? s_client;
+
+ private static HttpClient Client => s_client ?? throw new InvalidOperationException("demo not started");
+
+ [ClassInitialize]
+ public static async Task StartDemoAsync(TestContext context)
+ {
+ s_temp = new TempFolder("demo2");
+ s_demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, s_temp.Path));
+ s_client = new HttpClient { BaseAddress = s_demo.Address, Timeout = TimeSpan.FromSeconds(60) };
+ }
+
+ [ClassCleanup]
+ public static async Task StopDemoAsync()
+ {
+ s_client?.Dispose();
+ if (s_demo is not null)
+ {
+ await s_demo.DisposeAsync();
+ }
+
+ s_temp?.Dispose();
+ }
+
+ private static async Task GetAsync(string path)
+ {
+ using var response = await Client.GetAsync(path);
+ var text = await response.Content.ReadAsStringAsync();
+ Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
+ return JsonDocument.Parse(text).RootElement.Clone();
+ }
+
+ [TestMethod]
+ public async Task TheConnectionFollowsTheScene()
+ {
+ Assert.AreEqual("connected", (await GetAsync("/api/connection?scena=normale")).Str("state"));
+ Assert.AreEqual("tuo.profilo", (await GetAsync("/api/connection?scena=sessione")).Str("username"));
+ var login = await GetAsync("/api/connection?scena=scollegato");
+ Assert.AreEqual("notConnected", login.Str("state"));
+ StringAssert.Contains(login.Str("currentUrl"), "/accounts/login/");
+ Assert.AreEqual("verificationRequired", (await GetAsync("/api/connection?scena=fermo")).Str("state"));
+
+ using var request = new HttpRequestMessage(HttpMethod.Post, "/api/connection/finish?scena=scollegato");
+ request.Headers.Add("Origin", s_demo!.Address.GetLeftPart(UriPartial.Authority));
+ using var response = await Client.SendAsync(request);
+ var finish = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
+ Assert.IsFalse(finish.Bool("connected"), "no real browser in the demo: it says so");
+ StringAssert.StartsWith(finish.Str("message"), "Dimostrazione");
+ }
+
+ [TestMethod]
+ public async Task TheSceneErroreShowsOnlyTheMissingPassword()
+ {
+ var problems = (await GetAsync("/api/capabilities?scena=errore")).Items("problems").ToList();
+ Assert.HasCount(1, problems);
+ Assert.AreEqual("password-mancante", problems[0].Str("code"));
+ StringAssert.Contains(problems[0].Str("remedy"), "FEBE_PASSWORD");
+ Assert.AreEqual(0, (await GetAsync("/api/capabilities?scena=normale")).GetProperty("problems").GetArrayLength());
+ Assert.AreEqual("Off", (await GetAsync("/api/engine?scena=errore")).GetProperty("snapshot").Str("mode"));
+ }
+
+ [TestMethod]
+ public async Task TheImportReviewIsReadyWithEveryKindOfRow()
+ {
+ var overview = await GetAsync("/api/import");
+ var run = overview.Items("runs").Single(r => r.Str("state") == "reviewing");
+ var review = await GetAsync($"/api/import/{run.Long("id")}/review");
+ var outcomes = review.GetProperty("outcomes");
+ Assert.IsGreaterThan(0, outcomes.Int("new"));
+ Assert.IsGreaterThan(0, outcomes.Int("alreadyInLibrary"));
+ Assert.IsGreaterThan(0, outcomes.Int("probableDuplicates"));
+ Assert.IsGreaterThan(0, outcomes.Int("unrecognized"));
+ Assert.IsGreaterThan(0, review.Int("recognized"), "names in Febe's own scheme give date and code");
+ var folders = review.Items("folders").ToList();
+ Assert.IsTrue(folders.Any(f => f.Bool("blocked")), "a folder without account name");
+ Assert.IsTrue(folders.Any(f => f.GetProperty("target").Str("kind") == "existing"));
+ Assert.IsTrue(folders.Any(f => f.GetProperty("target").Str("kind") == "newArchiveAccount"));
+ Assert.IsNotNull(review.GetProperty("plan").Str("leftOutLabel"));
+ var duplicates = await GetAsync($"/api/import/{run.Long("id")}/duplicates?all=true");
+ Assert.IsTrue(duplicates.Items("cases").All(c => c.Str("decision") == "pending"), "nothing is chosen in advance");
+ }
+
+ [TestMethod]
+ public async Task DuplicatesAfterADownloadWaitInTheReview()
+ {
+ Assert.AreEqual(3, (await GetAsync("/api/duplicates/count")).Int("download"));
+ var page = await GetAsync("/api/duplicates");
+ Assert.HasCount(3, page.Items("cases").ToList());
+ foreach (var c in page.Items("cases"))
+ {
+ Assert.AreEqual(c.GetProperty("existing").Str("username"), c.GetProperty("candidate").Str("username"), "a download pair is inside one account");
+ using var image = await Client.GetAsync(c.GetProperty("candidate").Str("image"));
+ Assert.AreEqual(HttpStatusCode.OK, image.StatusCode, "the thumbnail of the downloaded copy exists");
+ }
+ }
+
+ [TestMethod]
+ public async Task TheBrowserPreviewAndTheStopsFollowTheScene()
+ {
+ var session = await GetAsync("/api/browser/preview?scena=sessione");
+ Assert.IsTrue(session.Bool("hasFrame"));
+ using (var frame = await Client.GetAsync(session.Str("frame") + "&scena=sessione"))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, frame.StatusCode);
+ Assert.AreEqual("image/jpeg", frame.Content.Headers.ContentType?.MediaType);
+ }
+
+ Assert.IsFalse((await GetAsync("/api/browser/preview?scena=normale")).Bool("hasFrame"), "between sessions the browser rests on a blank page");
+ var stopped = (await GetAsync("/api/engine/incidents?scena=fermo")).Items("items").ToList();
+ Assert.IsTrue(stopped.Any(i => i.Bool("open") && i.Str("level") == "challenge"));
+ var normal = (await GetAsync("/api/engine/incidents?scena=normale")).Items("items").ToList();
+ Assert.IsTrue(normal.All(i => !i.Bool("open")));
+ }
+
+ [TestMethod]
+ public async Task EverySettingsPageHasItsData()
+ {
+ Assert.AreEqual("prudent", (await GetAsync("/api/settings/limits")).Str("profile"));
+ var general = await GetAsync("/api/settings/general?veste=desktop");
+ Assert.IsFalse(general.Bool("foldersReadOnly"));
+ Assert.IsTrue(general.Bool("canChangeDataFolder"));
+ Assert.IsTrue(general.GetProperty("autostart").ValueKind is JsonValueKind.True or JsonValueKind.False, "«Avvio» on the desktop look");
+ var docker = await GetAsync("/api/settings/general?veste=docker");
+ Assert.IsTrue(docker.Bool("foldersReadOnly"));
+ Assert.AreEqual(JsonValueKind.Null, docker.GetProperty("autostart").ValueKind);
+ Assert.AreEqual("marta.demo", general.GetProperty("preview").Str("accountFolder"), "the preview of mockup 08");
+ await GetAsync("/api/settings/notifications");
+ await GetAsync("/api/settings/data");
+ Assert.AreEqual("Windows", (await GetAsync("/api/about?veste=desktop")).Str("edition"));
+ }
+}
diff --git a/tests/Febe.Tests/Web/ImportApiTests.cs b/tests/Febe.Tests/Web/ImportApiTests.cs
new file mode 100644
index 0000000..7908a86
--- /dev/null
+++ b/tests/Febe.Tests/Web/ImportApiTests.cs
@@ -0,0 +1,174 @@
+using System.Net;
+using System.Text;
+using System.Text.Json;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Part2Support;
+using Febe.Tests.Web.Support;
+using Febe.Web;
+
+namespace Febe.Tests.Web;
+
+///
+/// Importa over the API (spec §9, mockup 09): the web host builds its own ImportService over the library when the
+/// composition registers none; the four steps work end to end; a folder without account blocks only its files; the
+/// duplicates wait with nothing decided; the report and its CSV; the import's own errors become Italian answers.
+///
+[TestClass]
+public sealed class ImportApiTests
+{
+ private static async Task WaitForStateAsync(WebTestServer server, long id, params string[] states)
+ {
+ JsonElement progress = default;
+ await Part2.WaitUntilAsync(async () =>
+ {
+ progress = await server.GetJsonAsync($"/api/import/{id}/progress");
+ return !progress.Bool("running") && states.Contains(progress.Str("state"));
+ }, "import state " + string.Join("/", states));
+ return progress;
+ }
+
+ [TestMethod]
+ public async Task TheFourStepsFromSourceToReport()
+ {
+ await using var server = await Part2.StartAsync(FebeEdition.Desktop);
+ var source = server.Temp.Combine("vecchio-disco");
+ Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240612_101500.jpg"), 11);
+ Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240613_101500.jpg"), 12);
+ Part2.WritePhoto(Path.Combine(source, "anna.prova", "IMG_20240614_101500.jpg"), 13, 600, 733);
+ Part2.WritePhoto(Path.Combine(source, "Foto sparse", "IMG_20220101_120000.jpg"), 13, 900, 1100);
+ await File.WriteAllTextAsync(Path.Combine(source, "Foto sparse", "note.txt"), "appunti");
+
+ var overview = await server.GetJsonAsync("/api/import");
+ Assert.AreEqual(0, overview.GetProperty("runs").GetArrayLength());
+ Assert.AreEqual(JsonValueKind.Null, overview.GetProperty("sourceRoot").ValueKind, "desktop: any folder");
+
+ var (inspectStatus, info) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = source });
+ Assert.AreEqual(HttpStatusCode.OK, inspectStatus);
+ Assert.IsTrue(info.Bool("canMove"));
+ CollectionAssert.AreEquivalent(new[] { "anna.prova", "Foto sparse" }, info.Items("folders").Select(f => f.GetString()).ToArray());
+
+ // Step 2: the analysis, read-only.
+ var (startStatus, run) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/start", new { path = source, stogram = false });
+ Assert.AreEqual(HttpStatusCode.OK, startStatus);
+ var id = run.Long("id");
+ await WaitForStateAsync(server, id, "reviewing");
+ Assert.HasCount(5, Directory.GetFiles(source, "*", SearchOption.AllDirectories), "the analysis touches nothing");
+
+ // Step 3: the review.
+ var review = await server.GetJsonAsync($"/api/import/{id}/review");
+ Assert.AreEqual(5, review.Int("files"));
+ Assert.AreEqual(1, review.GetProperty("outcomes").Int("unrecognized"));
+ Assert.IsTrue(review.Bool("canMove"));
+ var folders = review.Items("folders").ToDictionary(f => f.Str("displayName"));
+ Assert.AreEqual("newArchiveAccount", folders["anna.prova"].GetProperty("target").Str("kind"));
+ Assert.AreEqual("none", folders["Foto sparse"].GetProperty("target").Str("kind"));
+ Assert.IsTrue(folders["Foto sparse"].Bool("blocked"), "a folder without account blocks only its files");
+ StringAssert.Contains(review.GetProperty("plan").Str("leftOutLabel"), "aspettano la tua decisione", "a duplicate without decision waits");
+
+ // The two copies of scene 13 are a probable duplicate inside the source: nothing decided in advance.
+ var duplicates = await server.GetJsonAsync($"/api/import/{id}/duplicates?all=true");
+ var pair = duplicates.Items("cases").Single();
+ Assert.AreEqual("pending", pair.Str("decision"));
+ Assert.IsTrue(pair.Bool("insideSource"));
+ StringAssert.StartsWith(pair.GetProperty("candidate").Str("image"), "/api/import/files/");
+ using (var preview = await server.Client.GetAsync(pair.GetProperty("candidate").Str("image")))
+ {
+ Assert.AreEqual(HttpStatusCode.OK, preview.StatusCode);
+ Assert.AreEqual("image/jpeg", preview.Content.Headers.ContentType?.MediaType);
+ }
+
+ var (decideStatus, decided) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/duplicates/{pair.Long("pairId")}", new { decision = "keepBoth", applyToAll = false });
+ Assert.AreEqual(HttpStatusCode.OK, decideStatus);
+ Assert.AreEqual(0, decided.Int("pending"));
+ var afterDecision = await server.GetJsonAsync($"/api/import/{id}/review");
+ StringAssert.Contains(afterDecision.GetProperty("plan").Str("leftOutLabel"), "1 cartella senza account");
+
+ var (targetStatus, updated) = await server.SendJsonAsync(HttpMethod.Put, $"/api/import/{id}/folders", new { folder = folders["Foto sparse"].Str("folder"), kind = "newArchiveAccount", username = "sparse.prova" });
+ Assert.AreEqual(HttpStatusCode.OK, targetStatus);
+ var updatedPlan = updated.GetProperty("plan");
+ Assert.AreEqual(JsonValueKind.Null, updatedPlan.GetProperty("leftOutLabel").ValueKind);
+ Assert.AreEqual(4, updatedPlan.Int("toImport"));
+ Assert.AreEqual("Importa 4 file", updatedPlan.Str("buttonLabel"));
+
+ var (modeStatus, modePlan) = await server.SendJsonAsync(HttpMethod.Put, $"/api/import/{id}/mode", new { mode = "copy" });
+ Assert.AreEqual(HttpStatusCode.OK, modeStatus);
+ Assert.AreEqual("copy", modePlan.Str("mode"));
+
+ // Step 4: the copy, then the report and the CSV.
+ var (copyStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/copy", new { mode = "copy" });
+ Assert.AreEqual(HttpStatusCode.OK, copyStatus);
+ await WaitForStateAsync(server, id, "completed");
+ var report = await server.GetJsonAsync($"/api/import/{id}/report");
+ Assert.AreEqual(4, report.Int("copied"));
+ Assert.AreEqual(0, report.Int("failed"));
+ Assert.HasCount(5, Directory.GetFiles(source, "*", SearchOption.AllDirectories), "«Copia» leaves the originals where they are");
+ var accounts = await server.GetJsonAsync("/api/accounts");
+ Assert.IsTrue(accounts.Items("accounts").Any(a => a.Str("username") == "sparse.prova" && a.Str("state") == "archiveOnly"));
+
+ using var csv = await server.Client.GetAsync($"/api/import/{id}/report.csv");
+ Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
+ Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
+ var bytes = await csv.Content.ReadAsByteArrayAsync();
+ CollectionAssert.AreEqual(Encoding.UTF8.GetPreamble(), bytes.Take(3).ToArray(), "UTF-8 with BOM for Excel");
+ StringAssert.Contains(Encoding.UTF8.GetString(bytes), ";");
+ StringAssert.Contains(csv.Content.Headers.ContentDisposition?.ToString() ?? string.Empty, ".csv");
+ }
+
+ [TestMethod]
+ public async Task TheAnalysisCanBeInterruptedResumedAndDiscarded()
+ {
+ await using var server = await Part2.StartAsync(FebeEdition.Desktop);
+ var source = server.Temp.Combine("sorgente");
+ for (var i = 0; i < 6; i++)
+ {
+ Part2.WritePhoto(Path.Combine(source, "luca.prova", $"IMG_2024061{i}_101500.jpg"), 200 + i, 500, 600);
+ }
+
+ var (_, run) = await server.SendJsonAsync(HttpMethod.Post, "/api/import/start", new { path = source, stogram = false });
+ var id = run.Long("id");
+ var (interruptStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/interrupt");
+ Assert.AreEqual(HttpStatusCode.OK, interruptStatus);
+ var state = (await WaitForStateAsync(server, id, "analysisInterrupted", "reviewing")).Str("state");
+ if (state == "analysisInterrupted")
+ {
+ var (resumeStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/resume");
+ Assert.AreEqual(HttpStatusCode.OK, resumeStatus);
+ await WaitForStateAsync(server, id, "reviewing");
+ }
+
+ var (againStatus, again) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/resume");
+ Assert.AreEqual(HttpStatusCode.BadRequest, againStatus, "nothing to resume once reviewing");
+ Assert.IsFalse(string.IsNullOrWhiteSpace(again.Str("message")));
+
+ var (discardStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/import/{id}/discard");
+ Assert.AreEqual(HttpStatusCode.OK, discardStatus);
+ var (gone, _, _) = await server.GetAsync($"/api/import/{id}/review");
+ Assert.AreEqual(HttpStatusCode.NotFound, gone, "nothing copied: the import disappears");
+ Assert.HasCount(6, Directory.GetFiles(source, "*", SearchOption.AllDirectories));
+ }
+
+ [TestMethod]
+ public async Task ErrorsOfTheImportAreItalianAnswers()
+ {
+ await using (var desktop = await Part2.StartAsync(FebeEdition.Desktop))
+ {
+ var (status, error) = await desktop.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = desktop.Temp.Combine("non-esiste") });
+ Assert.AreEqual(HttpStatusCode.BadRequest, status);
+ Assert.IsFalse(string.IsNullOrWhiteSpace(error.Str("message")));
+ var (dataStatus, _) = await desktop.SendJsonAsync(HttpMethod.Post, "/api/import/inspect", new { path = desktop.Library.Data.Root });
+ Assert.AreEqual(HttpStatusCode.BadRequest, dataStatus, "the Data folder is never a source");
+ var (missing, _, _) = await desktop.GetAsync("/api/import/4242/review");
+ Assert.AreEqual(HttpStatusCode.NotFound, missing);
+ var (sources, _, _) = await desktop.GetAsync("/api/import/sources");
+ Assert.AreEqual(HttpStatusCode.BadRequest, sources, "desktop: the native picker, no listing");
+ }
+
+ // Docker: the sources live under /importa (absent on this machine: the listing says so).
+ await using var docker = await Part2.StartAsync();
+ var overview = await docker.GetJsonAsync("/api/import");
+ Assert.AreEqual("/importa", overview.Str("sourceRoot"));
+ Assert.IsFalse(overview.Bool("pickFolder"));
+ var (pick, _) = await docker.SendJsonAsync(HttpMethod.Post, "/api/import/pick-folder");
+ Assert.AreEqual(HttpStatusCode.BadRequest, pick);
+ }
+}
diff --git a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs
new file mode 100644
index 0000000..2aa4ae3
--- /dev/null
+++ b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs
@@ -0,0 +1,103 @@
+using System.Net;
+using System.Text.Json;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Support;
+using Febe.Web;
+using Febe.Web.Connection;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Febe.Tests.Web.Part2Support;
+
+/// Helpers of the tests of the second part of the interface (Attività, Impostazioni, Importa, Collegamento).
+internal static class Part2
+{
+ /// A web server for one test, imitating the given shell (Docker by default, like a real container).
+ public static Task StartAsync(FebeEdition edition = FebeEdition.Docker, Action? services = null) =>
+ WebTestServer.StartAsync(new FebeWebOptions { Access = AccessMode.None, Edition = edition }, services);
+
+ /// Polls until the condition holds (background jobs: analysis, copy, rebuild).
+ public static async Task WaitUntilAsync(Func> condition, string what, int seconds = 60)
+ {
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
+ while (DateTime.UtcNow < deadline)
+ {
+ if (await condition())
+ {
+ return;
+ }
+
+ await Task.Delay(100);
+ }
+
+ Assert.Fail($"timeout: {what}");
+ }
+
+ /// GET that returns status and body without asserting.
+ public static async Task<(HttpStatusCode Status, string Text, JsonElement Json)> GetAsync(this WebTestServer server, string path)
+ {
+ using var response = await server.Client.GetAsync(path);
+ var text = await response.Content.ReadAsStringAsync();
+ var json = text.Length > 0 && (response.Content.Headers.ContentType?.MediaType?.Contains("json", StringComparison.Ordinal) ?? false)
+ ? JsonDocument.Parse(text).RootElement.Clone()
+ : default;
+ return (response.StatusCode, text, json);
+ }
+
+ /// A command whose body is returned as text too (to check what it does not contain).
+ public static async Task<(HttpStatusCode Status, string Text)> SendTextAsync(this WebTestServer server, HttpMethod method, string path, object? body = null, string? origin = "")
+ {
+ using var request = server.Request(method, path, body, origin);
+ using var response = await server.Client.SendAsync(request);
+ return (response.StatusCode, await response.Content.ReadAsStringAsync());
+ }
+
+ /// Writes a JPEG of a generated scene.
+ public static void WritePhoto(string path, int scene, int width = 900, int height = 1100)
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ File.WriteAllBytes(path, TestFile.PhotoBytes(scene, width, height));
+ }
+}
+
+/// Configuration problems chosen by the test.
+internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IConfigurationProblems
+{
+ public IReadOnlyList Current { get; } = problems;
+}
+
+/// A connection service that records what the API asks.
+internal sealed class RecordingConnection : IConnectionService
+{
+ public List Calls { get; } = [];
+
+ public ConnectionStatus Status { get; set; } = new(ConnectionState.NotConnected, null, null, false, "https://www.instagram.com/accounts/login/");
+
+ public Task GetStatusAsync(CancellationToken ct) => Task.FromResult(Status);
+
+ public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
+ {
+ Calls.Add("begin:" + openLogin);
+ Status = Status with { UserIsDriving = true };
+ return Task.CompletedTask;
+ }
+
+ public Task FinishAsync(CancellationToken ct)
+ {
+ Calls.Add("finish");
+ Status = new ConnectionStatus(ConnectionState.Connected, "tuo.profilo", "Il tuo profilo", false, null);
+ return Task.FromResult(new FinishResult(true, "Sei collegato come @tuo.profilo."));
+ }
+
+ public Task CancelAsync(CancellationToken ct)
+ {
+ Calls.Add("cancel");
+ return Task.CompletedTask;
+ }
+
+ public Task DisconnectAsync(CancellationToken ct)
+ {
+ Calls.Add("disconnect");
+ Status = new ConnectionStatus(ConnectionState.NotConnected, null, null, false, null);
+ return Task.CompletedTask;
+ }
+}
diff --git a/tests/Febe.Tests/Web/SettingsApiTests.cs b/tests/Febe.Tests/Web/SettingsApiTests.cs
new file mode 100644
index 0000000..9e0dbf2
--- /dev/null
+++ b/tests/Febe.Tests/Web/SettingsApiTests.cs
@@ -0,0 +1,282 @@
+using System.Net;
+using Febe.Core.Alerts;
+using Febe.Core.Engine;
+using Febe.Core.Library;
+using Febe.Tests.Support;
+using Febe.Tests.Web.Part2Support;
+using Febe.Tests.Web.Support;
+using Febe.Web;
+using Febe.Web.Native;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Febe.Tests.Web;
+
+///
+/// Impostazioni over the API (spec §4.7, §7.5, §8.5, §13.3): naming schemes with their preview and errors, the library
+/// folder (desktop only, existing accounts keep their folders), the limits of §7.5 with Italian messages, the
+/// notifications (the bot token is never sent back), backups and the rebuild of the database.
+///
+[TestClass]
+public sealed class SettingsApiTests
+{
+ [TestMethod]
+ public async Task GeneralShowsTheSchemesWithPreviewAndRefusesWrongOnes()
+ {
+ await using var server = await Part2.StartAsync();
+ await server.Db.Accounts.AddAsync(Make.Account("marta.prova"));
+ var general = await server.GetJsonAsync("/api/settings/general");
+ Assert.AreEqual(NamingScheme.DefaultGeneral, general.Str("namingScheme"));
+ Assert.AreEqual(NamingScheme.DefaultHighlight, general.Str("highlightScheme"));
+ Assert.IsTrue(general.Bool("foldersReadOnly"), "Docker: folders change from the container");
+ Assert.IsTrue(general.Bool("setFileTime"));
+ Assert.AreEqual(JsonValueKindNull, general.GetProperty("autostart").ValueKind, "the «Avvio» block exists only on Windows");
+ var preview = general.GetProperty("preview");
+ Assert.AreEqual("marta.prova", preview.Str("accountFolder"));
+ Assert.IsTrue(preview.Items("folders").Any(f => f.Items("files").Any(x => x.Str("name").EndsWith("_DBx3kQ2_2.jpg", StringComparison.Ordinal))));
+
+ var bad = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/naming-preview", new { namingScheme = "{account}\\{sconosciuto}", highlightScheme = NamingScheme.DefaultHighlight });
+ Assert.AreEqual(HttpStatusCode.OK, bad.Status);
+ Assert.IsTrue(bad.Body.Items("errors").Any(e => e.GetString()!.StartsWith("Schema:", StringComparison.Ordinal)));
+
+ var (status, error) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
+ new { namingScheme = "{account}\\{sconosciuto}", highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
+ Assert.AreEqual(HttpStatusCode.BadRequest, status);
+ StringAssert.StartsWith(error.Str("message"), "Schema:");
+
+ const string scheme = @"{account}\{tipo}\{data}_{codice}_{n}";
+ var (okStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general", new { namingScheme = scheme, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = false });
+ Assert.AreEqual(HttpStatusCode.OK, okStatus);
+ Assert.AreEqual(scheme, saved.Str("namingScheme"));
+ Assert.IsFalse(saved.Bool("setFileTime"));
+ var stored = await LibrarySettings.LoadAsync(server.Db.Settings, server.Library.Layout.Root);
+ Assert.AreEqual(scheme, stored.Naming.General.Text);
+ Assert.IsFalse(stored.SetFileTimeToPublication);
+ }
+
+ private const System.Text.Json.JsonValueKind JsonValueKindNull = System.Text.Json.JsonValueKind.Null;
+
+ [TestMethod]
+ public async Task TheLibraryFolderChangesOnlyOnTheDesktopAndAccountsKeepTheirFiles()
+ {
+ await using (var docker = await Part2.StartAsync())
+ {
+ var (status, _) = await docker.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
+ new { libraryFolder = docker.Temp.Combine("altrove"), namingScheme = NamingScheme.DefaultGeneral, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
+ Assert.AreEqual(HttpStatusCode.BadRequest, status);
+ }
+
+ await using var server = await Part2.StartAsync(FebeEdition.Desktop);
+ var withFiles = await server.Db.Accounts.AddAsync(Make.Account("con.file"));
+ var empty = await server.Db.Accounts.AddAsync(Make.Account("senza.file"));
+ var oldFolder = server.Library.Layout.AccountFolder(withFiles);
+ Directory.CreateDirectory(oldFolder);
+ var newRoot = server.Temp.Combine("nuova-libreria");
+
+ var (inside, insideError) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
+ new { libraryFolder = server.Temp.Combine("dati", "libreria"), namingScheme = NamingScheme.DefaultGeneral, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
+ Assert.AreEqual(HttpStatusCode.BadRequest, inside);
+ StringAssert.Contains(insideError.Str("message"), "cartella dei dati");
+
+ var (status2, general) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/general",
+ new { libraryFolder = newRoot, namingScheme = NamingScheme.DefaultGeneral, highlightScheme = NamingScheme.DefaultHighlight, setFileTime = true });
+ Assert.AreEqual(HttpStatusCode.OK, status2);
+ Assert.AreEqual(newRoot, general.GetProperty("library").Str("path"));
+ Assert.AreEqual(newRoot, server.Library.Layout.Root);
+ Assert.IsTrue(Directory.Exists(newRoot));
+ var kept = (await server.Db.Accounts.GetAsync(withFiles.Id))!;
+ Assert.AreEqual(oldFolder, server.Library.Layout.AccountFolder(kept), "an account with files keeps its folder");
+ var moved = (await server.Db.Accounts.GetAsync(empty.Id))!;
+ Assert.AreEqual(Path.Combine(newRoot, "senza.file"), server.Library.Layout.AccountFolder(moved), "an account without files goes in the new library");
+ }
+
+ [TestMethod]
+ public async Task LimitsKeepTheBoundsOfTheSpecWithItalianMessages()
+ {
+ await using var server = await Part2.StartAsync();
+ var limits = await server.GetJsonAsync("/api/settings/limits");
+ Assert.AreEqual("prudent", limits.Str("profile"));
+ Assert.AreEqual(3, limits.GetProperty("presets").GetArrayLength());
+ var rules = limits.GetProperty("rules");
+ Assert.AreEqual(5, rules.Int("minPauseMinutes"));
+ Assert.AreEqual(30, rules.Int("maxSessionMinutes"));
+ Assert.AreEqual(20, rules.Int("maxWindowHours"));
+ var current = limits.GetProperty("current");
+ var kinds = current.Items("budgets").Select(b => b.Str("kind")).ToList();
+ CollectionAssert.AreEqual(new[] { "Home", "ProfileOpen", "StoryView", "BackfillPage", "SinglePost", "FollowingListPage" }, kinds, "every row of the table of §7.5");
+ CollectionAssert.AreEqual(new[] { "1 ora", "6 ore", "24 ore" }, limits.Items("stops").Select(s => s.GetString()).ToArray());
+
+ object Body(Func, Dictionary> edit, string profile = "custom")
+ {
+ var values = System.Text.Json.JsonSerializer.Deserialize>(current.GetRawText(), WebTestServer.Json)!;
+ return new { profile, values = edit(values), pace = "natural", gradualStart = true, activeDays = new[] { 0, 1, 2, 3, 4, 5, 6 } };
+ }
+
+ async Task RefusedAsync(object body)
+ {
+ var (status, error) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", body);
+ Assert.AreEqual(HttpStatusCode.BadRequest, status);
+ return error.Str("message");
+ }
+
+ StringAssert.Contains(await RefusedAsync(Body(v => { v["sessionMaxMinutes"] = 45; return v; })), "Una sessione non può durare più di 30 minuti");
+ StringAssert.Contains(await RefusedAsync(Body(v => { v["pauseMinMinutes"] = 3; return v; })), "La pausa minima non può scendere sotto i 5 minuti");
+ StringAssert.Contains(await RefusedAsync(Body(v => { v["windowStart"] = "02:00"; v["windowEnd"] = "23:30"; return v; })), "20 ore");
+ StringAssert.Contains(await RefusedAsync(Body(v => { v["windowStart"] = "sette"; return v; })), "07:30");
+ StringAssert.Contains(await RefusedAsync(new { profile = "prudent", pace = "natural", gradualStart = true, activeDays = Array.Empty() }), "almeno un giorno");
+ var tooMany = Body(v =>
+ {
+ var budgets = System.Text.Json.JsonSerializer.Deserialize>>(System.Text.Json.JsonSerializer.Serialize(v["budgets"]), WebTestServer.Json)!;
+ budgets[1]["perDay"] = 601;
+ v["budgets"] = budgets;
+ return v;
+ });
+ StringAssert.Contains(await RefusedAsync(tooMany), "doppio di «Rapido»");
+
+ var (okStatus, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", Body(v => { v["sessionMaxMinutes"] = 12; v["pauseMinMinutes"] = 25; return v; }));
+ Assert.AreEqual(HttpStatusCode.OK, okStatus);
+ Assert.AreEqual("custom", saved.Str("profile"));
+ var settings = await EngineSettingsStore.LoadAsync(server.Db.Settings);
+ Assert.AreEqual(Febe.Core.Domain.CautionProfileKind.Custom, settings.ProfileKind);
+ Assert.AreEqual(TimeSpan.FromMinutes(12), settings.EffectiveProfile.SessionMax);
+ Assert.AreEqual(TimeSpan.FromMinutes(25), settings.EffectiveProfile.PauseMin);
+
+ var (fastStatus, fast) = await server.SendJsonAsync(HttpMethod.Put, "/api/settings/limits", new { profile = "fast", pace = "brisk", gradualStart = false, activeDays = new[] { 1, 2, 3, 4, 5 } });
+ Assert.AreEqual(HttpStatusCode.OK, fastStatus);
+ Assert.AreEqual("fast", fast.Str("profile"));
+ Assert.AreEqual("brisk", fast.Str("pace"));
+ Assert.IsFalse(fast.Bool("gradualStart"));
+ CollectionAssert.AreEqual(new[] { 1, 2, 3, 4, 5 }, fast.Items("activeDays").Select(d => d.GetInt32()).ToArray());
+ Assert.IsNotNull((await EngineSettingsStore.LoadAsync(server.Db.Settings)).Custom, "the «Su misura» values stay stored for later");
+ }
+
+ [TestMethod]
+ public async Task NotificationsNeverSendTheBotTokenBack()
+ {
+ await using var server = await Part2.StartAsync();
+ var initial = await server.GetJsonAsync("/api/settings/notifications");
+ Assert.IsTrue(initial.GetProperty("events").Bool("verification"));
+ Assert.IsFalse(initial.Bool("telegramTokenSet"));
+ Assert.IsFalse(initial.Bool("windowsAvailable"), "Docker has no Windows notifications");
+
+ const string token = "123456789:AAEsegretissimoNonDaMostrare_xyz";
+ var events = new { verification = true, disconnection = true, throttle = false, backfillDone = true, diskLow = true, unknownFormat = false };
+ var (status, text) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
+ new { events, windows = false, telegramChatId = "987654", telegramToken = token, removeTelegramToken = false });
+ Assert.AreEqual(HttpStatusCode.OK, status);
+ Assert.DoesNotContain(token, text, "the token is not echoed back");
+ Assert.DoesNotContain("segretissimo", text);
+ var (_, getText, saved) = await server.GetAsync("/api/settings/notifications");
+ Assert.DoesNotContain(token, getText);
+ Assert.IsTrue(saved.Bool("telegramTokenSet"));
+ Assert.AreEqual("987654", saved.Str("telegramChatId"));
+ Assert.IsFalse(saved.GetProperty("events").Bool("throttle"));
+ Assert.AreEqual(token, (await AlertSettingsStore.LoadAsync(server.Db.Settings)).TelegramToken, "stored in the settings of the Data folder");
+
+ // An empty token keeps the stored one; «Togli il gettone» removes it.
+ await server.SendJsonAsync(HttpMethod.Put, "/api/settings/notifications", new { events, windows = false, telegramChatId = "987654", telegramToken = "", removeTelegramToken = false });
+ Assert.AreEqual(token, (await AlertSettingsStore.LoadAsync(server.Db.Settings)).TelegramToken);
+
+ var (testStatus, test) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "telegram" });
+ Assert.AreEqual(HttpStatusCode.OK, testStatus);
+ Assert.IsFalse(test.Bool("sent"), "the Telegram sender arrives with M8");
+ Assert.AreEqual(TelegramNotAvailableYet.Text, test.Str("message"));
+ var (windowsStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "windows" });
+ Assert.AreEqual(HttpStatusCode.BadRequest, windowsStatus);
+
+ var (badStatus, badText) = await server.SendTextAsync(HttpMethod.Put, "/api/settings/notifications",
+ new { events, windows = false, telegramChatId = "987654", telegramToken = "con spazi dentro", removeTelegramToken = false });
+ Assert.AreEqual(HttpStatusCode.BadRequest, badStatus);
+ Assert.DoesNotContain("con spazi", badText, "a refused token is not echoed either");
+
+ await server.SendJsonAsync(HttpMethod.Put, "/api/settings/notifications", new { events, windows = false, telegramChatId = "987654", telegramToken = (string?)null, removeTelegramToken = true });
+ Assert.IsNull((await AlertSettingsStore.LoadAsync(server.Db.Settings)).TelegramToken);
+ Assert.IsFalse((await server.GetJsonAsync("/api/settings/notifications")).Bool("telegramTokenSet"));
+ }
+
+ [TestMethod]
+ public async Task WindowsNotificationsUseTheNativeShell()
+ {
+ var shell = new NotifyingShell();
+ await using var server = await Part2.StartAsync(FebeEdition.Desktop, s => s.AddSingleton(shell));
+ Assert.IsTrue((await server.GetJsonAsync("/api/settings/notifications")).Bool("windowsAvailable"));
+ var (status, result) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/notifications/test", new { channel = "windows" });
+ Assert.AreEqual(HttpStatusCode.OK, status);
+ Assert.IsTrue(result.Bool("sent"));
+ Assert.AreEqual(1, shell.Notifications);
+ }
+
+ [TestMethod]
+ public async Task BackupsAndTheRebuildOfTheDatabase()
+ {
+ await using var server = await Part2.StartAsync();
+ var data = await server.GetJsonAsync("/api/settings/data");
+ Assert.AreEqual(0, data.GetProperty("backups").GetArrayLength());
+ Assert.AreEqual(7, data.Int("keepDays"));
+ Assert.IsFalse(data.GetProperty("rebuild").Bool("running"));
+
+ var (status, message) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/backups");
+ Assert.AreEqual(HttpStatusCode.OK, status);
+ StringAssert.Contains(message.Str("message"), "febe-2026-10-13.sqlite");
+ await server.SendJsonAsync(HttpMethod.Post, "/api/settings/backups");
+ var backups = (await server.GetJsonAsync("/api/settings/data")).Items("backups").ToList();
+ Assert.HasCount(1, backups, "one copy per day: a new copy replaces today's");
+ Assert.AreEqual("2026-10-13", backups[0].Str("day"));
+
+ var (wrong, wrongError) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "sì" });
+ Assert.AreEqual(HttpStatusCode.BadRequest, wrong);
+ StringAssert.Contains(wrongError.Str("message"), "ricostruisci");
+
+ var account = await server.Db.Accounts.AddAsync(Make.Account("giornale.prova"));
+ var folder = server.Library.Layout.AccountFolder(account);
+ Part2.WritePhoto(Path.Combine(folder, "post", "foto.jpg"), 3);
+ var (started, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "Ricostruisci" });
+ Assert.AreEqual(HttpStatusCode.OK, started);
+ await Part2.WaitUntilAsync(async () => !(await server.GetJsonAsync("/api/settings/rebuild")).Bool("running"), "rebuild");
+ var rebuild = await server.GetJsonAsync("/api/settings/rebuild");
+ Assert.AreEqual(System.Text.Json.JsonValueKind.Null, rebuild.GetProperty("error").ValueKind);
+ Assert.IsTrue(rebuild.Items("lines").Any(l => l.GetString()!.StartsWith("Cartelle di account lette", StringComparison.Ordinal)));
+ Assert.IsTrue(File.Exists(Path.Combine(folder, "post", "foto.jpg")), "the rebuild never touches files");
+ }
+
+ [TestMethod]
+ public async Task AboutSaysVersionShellAndFolders()
+ {
+ await using var server = await Part2.StartAsync();
+ var about = await server.GetJsonAsync("/api/about");
+ Assert.AreEqual("Docker", about.Str("edition"));
+ Assert.AreEqual(server.Library.Layout.Root, about.Str("libraryFolder"));
+ Assert.AreEqual(server.Library.Data.Root, about.Str("dataFolder"));
+ StringAssert.Contains(about.Str("guide"), "/wiki");
+ }
+
+ private sealed class NotifyingShell : INativeShell
+ {
+ public int Notifications { get; private set; }
+
+ public bool CanPickFolder => false;
+
+ public bool CanShowInFolder => false;
+
+ public bool CanOpenUrl => false;
+
+ public bool CanNotify => true;
+
+ public bool SupportsAutostart => true;
+
+ public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(null);
+
+ public Task ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false);
+
+ public Task OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
+
+ public Task NotifyAsync(string title, string message, CancellationToken ct)
+ {
+ Notifications++;
+ return Task.CompletedTask;
+ }
+
+ public Task GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
+
+ public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
+ }
+}
diff --git a/tools/schermate/passi/benvenuto.js b/tools/schermate/passi/benvenuto.js
new file mode 100644
index 0000000..e11ff98
--- /dev/null
+++ b/tools/schermate/passi/benvenuto.js
@@ -0,0 +1,11 @@
+// The first start (spec §10.3): not connected and an empty library. The demo always has a library, so the screen is
+// drawn here into the page body, as the library draws it when it finds nothing, with the header count of an empty one.
+const { welcome } = await import('/js/pages/welcome.js');
+const { t } = await import('/js/core/text.js');
+const body = document.querySelector('.corpo');
+body.replaceChildren(welcome());
+document.querySelector('.strumenti')?.setAttribute('hidden', '');
+const count = document.querySelector('.testa .quanti');
+if (count) count.textContent = t('libreria.quanti', { elementi: t('comune.elementi', { n: 0 }), account: t('comune.account', { n: 0 }) });
+await new Promise((r) => setTimeout(r, 300));
+return [document.querySelectorAll('.benvenuto .btn').length, count?.textContent];
diff --git a/tools/schermate/passi/doppione-scelto.js b/tools/schermate/passi/doppione-scelto.js
new file mode 100644
index 0000000..9da32ca
--- /dev/null
+++ b/tools/schermate/passi/doppione-scelto.js
@@ -0,0 +1,8 @@
+// Chooses «Tieni il più grande» on the first probable duplicate of the import review, then goes back to it: mockup 09
+// shows a case with its decision (the panel moves on to the next case after each choice).
+await new Promise((r) => setTimeout(r, 800));
+document.querySelector('.scelte-doppione input[value="keepLarger"]')?.click();
+await new Promise((r) => setTimeout(r, 900));
+document.querySelector('.confronto .navigazione .btn.solo')?.click();
+await new Promise((r) => setTimeout(r, 900));
+return [document.querySelector('.confronto .navigazione .muto')?.textContent, document.querySelector('.scelte-doppione input:checked')?.value];
diff --git a/tools/schermate/passi/misure.js b/tools/schermate/passi/misure.js
new file mode 100644
index 0000000..e08886c
--- /dev/null
+++ b/tools/schermate/passi/misure.js
@@ -0,0 +1,8 @@
+// Prints the boxes of the elements named in window.FEBE_MISURE (CSS selectors), for checking a layout against a mockup.
+await new Promise((r) => setTimeout(r, 300));
+const selectors = (window.FEBE_MISURE || new URLSearchParams(location.hash.slice(1)).get('m') || '.testa-blocco .destra').split('|');
+return selectors.map((s) => [...document.querySelectorAll(s)].slice(0, 4).map((el) => {
+ const r = el.getBoundingClientRect();
+ const cs = getComputedStyle(el);
+ return `${s}: x=${Math.round(r.left)} y=${Math.round(r.top)} w=${Math.round(r.width)} h=${Math.round(r.height)} ml=${cs.marginLeft} d=${cs.display}`;
+}).join('\n')).join('\n');
diff --git a/tools/schermate/passi/su-misura.js b/tools/schermate/passi/su-misura.js
new file mode 100644
index 0000000..d99d01d
--- /dev/null
+++ b/tools/schermate/passi/su-misura.js
@@ -0,0 +1,7 @@
+// Changes a value on «Limiti e comportamento»: the profile becomes «Su misura» and the save bar wakes up (spec §7.5).
+await new Promise((r) => setTimeout(r, 500));
+const input = document.querySelector('.tabella-tetti tbody tr:nth-child(2) td:nth-child(3) input');
+input.value = '90';
+input.dispatchEvent(new Event('input', { bubbles: true }));
+await new Promise((r) => setTimeout(r, 300));
+return [document.querySelector('.su-misura b')?.textContent, document.querySelector('.salva .nota')?.textContent, document.querySelector('.salva .btn.primo')?.disabled];
diff --git a/tools/schermate/passi/tutti-tetti.js b/tools/schermate/passi/tutti-tetti.js
new file mode 100644
index 0000000..fc9c20c
--- /dev/null
+++ b/tools/schermate/passi/tutti-tetti.js
@@ -0,0 +1,5 @@
+// Opens «Tutti i tetti» on the Attività page (spec §7.4: every category, hourly and daily).
+await new Promise((r) => setTimeout(r, 500));
+[...document.querySelectorAll('.testa-blocco .btn.collegamento')].find((b) => b.textContent.includes('tetti'))?.click();
+await new Promise((r) => setTimeout(r, 600));
+return document.querySelectorAll('.tutti-tetti tbody tr').length;
diff --git a/tools/schermate/tutte.sh b/tools/schermate/tutte.sh
index a7f2283..89f8ddf 100644
--- a/tools/schermate/tutte.sh
+++ b/tools/schermate/tutte.sh
@@ -21,3 +21,28 @@ shot "$b/account/2?tema=scuro&tipo=storie" 12-account-storie-tema-scuro.png
shot "$b/libreria?tema=chiaro" 14-finestra-stretta.png 860 900
shot "$b/libreria?tema=chiaro" 14-telefono.png 390 844
shot "$b/account/2/cronologia?tema=chiaro" account-cronologia.png
+# Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione.
+# The stopped scene first: «Riprendi» stays off until the browser has been used (spec §7.6).
+shot "$b/attivita?scena=fermo&tema=scuro" 11-attivita-fermo-tema-scuro.png
+shot "$b/attivita?scena=sessione&tema=chiaro" 06-attivita.png
+shot "$b/attivita?scena=sessione&tema=chiaro" 06-attivita-tutti-i-tetti.png 1440 900 3000 "$here/passi/tutti-tetti.js"
+shot "$b/attivita?scena=sessione&tema=chiaro" 14-attivita-finestra-stretta.png 860 900
+shot "$b/attivita?scena=sessione&tema=chiaro" 14-attivita-telefono.png 390 844
+shot "$b/attivita?scena=normale&tema=chiaro" 14-attivita-finestra-stretta-normale.png 860 900
+shot "$b/attivita?scena=normale&tema=chiaro" 14-attivita-telefono-normale.png 390 844
+shot "$b/impostazioni/limiti?tema=chiaro" 07-limiti-e-comportamento.png 1440 1470
+shot "$b/impostazioni/limiti?tema=chiaro" 07-limiti-su-misura.png 1440 900 3000 "$here/passi/su-misura.js"
+shot "$b/impostazioni/generali?tema=chiaro" 08-impostazioni-generali.png
+shot "$b/impostazioni/notifiche?tema=chiaro" impostazioni-notifiche.png
+shot "$b/impostazioni/dati?tema=chiaro" impostazioni-dati.png
+shot "$b/impostazioni/informazioni?tema=chiaro" impostazioni-informazioni.png
+shot "$b/importa?passo=1&tema=chiaro&veste=docker" 09-importa-sorgente.png
+shot "$b/importa?passo=3&tema=chiaro" 09-importa-revisione.png 1440 900 3000 "$here/passi/doppione-scelto.js"
+shot "$b/importa?passo=3&tema=chiaro" 09-importa-telefono.png 390 844
+shot "$b/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=docker" 10-collegamento-instagram.png
+shot "$b/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=windows" 10-collegamento-windows.png
+shot "$b/impostazioni/collegamento?scena=normale&tema=chiaro&veste=docker" 10-collegamento-collegato.png
+shot "$b/browser?scena=fermo&tema=chiaro&veste=docker" 10-browser.png
+shot "$b/doppioni?tema=chiaro" doppioni-download.png
+shot "$b/libreria?scena=scollegato&tema=chiaro" primo-avvio.png 1440 900 3000 "$here/passi/benvenuto.js"
+shot "$b/libreria?scena=errore&tema=chiaro" errore-configurazione.png