From 724db13e1b3f683368dd835bcc933f2b5475ab6a Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 27 Nov 2026 15:29:59 +0100 Subject: [PATCH] E2: misure del filtro Copie, migrazione 0004 e prove di web e Docker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Il filtro «Copie» con 200.000 elementi stava al limite dei 250 ms («Copiati» 249 ms): la migrazione 0004 aggiunge solo l'indice ix_media_sha256_entry e la finestra scende a 160 ms. Totali e giorni contano «Copiati» partendo dalle copie e gli altri valori con un solo passaggio sui file dietro gli elenchi degli SHA-256 copiati (1,5 s -> 0,7 s); hanno un limite loro di 3 s, scritto in decisioni.md con le misure. «Copia di nuovo» sceglie un file dell'account che è sul disco: prima prendeva il primo con quello SHA-256 e, nella demo, a certe ore non scriveva nulla. Nuove prove: API delle copie, coerenza della demo, interfaccia nel browser, opzioni del server, avvio del contenitore con /esporta, contenuto dell'immagine e modelli, migrazione 4 e scala. Co-Authored-By: Claude Opus 5.5 --- docs/SPECIFICA.md | 1 + docs/decisioni.md | 3 +- .../Migrations/0004_esportazione_filtro.sql | 8 + src/Febe.Data/Stores/EntryStore.cs | 16 +- src/Febe.Data/Stores/ExportFilterSql.cs | 113 +++- src/Febe.Web/Api/ExportApi.cs | 12 +- tests/Febe.Tests/Data/LibraryScaleTests.cs | 129 +++- tests/Febe.Tests/Data/MigrationTests.cs | 57 +- .../Packaging/ImageContentsTests.cs | 39 ++ tests/Febe.Tests/Packaging/PackagingTests.cs | 45 +- tests/Febe.Tests/Server/ServerOptionsTests.cs | 31 +- tests/Febe.Tests/Web/DemoExportTests.cs | 153 +++++ tests/Febe.Tests/Web/ExportApiTests.cs | 555 ++++++++++++++++++ tests/Febe.Tests/Web/ExportInterfaceTests.cs | 279 +++++++++ 14 files changed, 1403 insertions(+), 38 deletions(-) create mode 100644 src/Febe.Data/Migrations/0004_esportazione_filtro.sql create mode 100644 tests/Febe.Tests/Web/DemoExportTests.cs create mode 100644 tests/Febe.Tests/Web/ExportApiTests.cs create mode 100644 tests/Febe.Tests/Web/ExportInterfaceTests.cs diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index b051b83..6f63595 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -791,6 +791,7 @@ Vincoli che contano: - Stati di un elemento: da scaricare, scaricato, parziale, fallito, saltato, importato, eliminato. «Eliminato» resta nel database senza file, perché non venga riscaricato (§4.6). - Indici su (account, data di pubblicazione), SHA-256, impronta, stato. Dalla migrazione `0002` (tappa D1) anche `ix_entry_discovered` su `entry (discovered_at)`, per le miniature della cronologia della Dashboard (§7.9), e `ix_media_entry_files` su `media (entry_id, state, kind)`, per i conteggi di «Tutte le foto» (§4.6). - Dalla migrazione `0003` (tappa E1): l'identità di una copia è unica sulle righe correnti, «Copiato» e «Non riuscito» (`ux_export_copy_identity`); un percorso di una destinazione è tenuto al più da una copia «Copiato» o «Superato», senza distinguere le maiuscole ASCII, e un percorso «Tolto» è di nuovo libero (`ux_export_copy_path`); una copia non è mai «Superato» dal suo stesso originale (se il file della libreria torna quello di prima, la copia torna «Copiato»); una cartella senza il suo account non è mai automatica; una copia tiene identificativo e nome dell'account rimosso solo finché è senza account, e le copie orfane di un account si trovano per quelli (`ix_export_copy_orphan`); nella stessa cartella al più una conversione corrente per file e formato (`ux_media_conversion_current`); le ricerche vanno per SHA-256 (`ix_export_copy_sha256`, `ix_export_copy_superseded_by`); il filtro «Copie» su tutta la libreria legge `ix_export_copy_destination`, e le copie di una destinazione e i file di un lavoro si sfogliano per chiave senza riordinarli (`ix_export_copy_destination_id`, `ix_export_item_run`); una destinazione con copie o lavori e una riga `media` con un convertito registrato non si cancellano (`ON DELETE RESTRICT`); ogni colonna di chiave esterna delle tabelle nuove ha il suo indice. +- Dalla migrazione `0004` (tappa E2): soltanto l'indice `ix_media_sha256_entry` su `media (sha256, entry_id)` dove lo SHA-256 c'è, per il filtro «Copie» (§4.6, §4.10), che dalle copie arriva agli elementi senza leggere le righe dei file; nessuna tabella e nessuna colonna cambia. Misure in `docs/decisioni.md`. - Versione dello schema in `PRAGMA user_version`, migrazioni come file SQL numerati eseguiti all'avvio dentro una transazione. Un solo scrittore: le scritture passano da una coda. ### 8.4 Miniature e impronte diff --git a/docs/decisioni.md b/docs/decisioni.md index e11ce1b..97e384b 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -593,7 +593,8 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-27 | Tappa E2: **destinazione effettiva** = la cartella propria in uso dell'account, altrimenti la cartella generale in uso, altrimenti nessuna, calcolata al momento dal database. **File dovuto** = un file presente (`Downloaded`/`Imported` con SHA-256) di un account acceso con una destinazione effettiva e di un tipo che la destinazione copia. Segno sulla tessera, filtro «Copie», conteggio della scheda account e piano di «Copia in…» usano la stessa regola | SPECIFICA §4.10 («al più una destinazione effettiva») e proposta di §16 domanda 26: «312 su 1.204 non ancora copiati» deve essere ciò che «Copia in…» copierebbe | | 2026-11-27 | Tappa E2: le tre scelte del filtro «Copie» **dividono** i file dovuti: «Non ancora copiati» = dovuto, non «Copiato» e non «Tolto o superato»; un file la cui copia corrente è «Non riuscito» è «Non ancora copiato» (la copia lo riprova), mai «Tolto o superato». Il progetto voleva «Non ancora copiati» = non «Copiato» | «Copia in…» salta tolti e superati (§4.10): il numero di «Non ancora copiati» deve essere quello che la finestra copierebbe senza la casella «Copia di nuovo» | | 2026-11-27 | Tappa E2: nel filtro «Copie» gli identificativi (destinazioni, account, tipi di contenuto, tutti letti dal database) si scrivono **nel testo dell'SQL** come interi, invece che come parametri; `ExportFilterContext` legge prima se esistono righe «Copiato», «Non riuscito» o «Tolto/Superato» nelle destinazioni in uso, e i casi senza righe evitano gli `EXISTS` (`0`). In «Tutte le foto» la condizione sull'elemento è «esiste un suo file di quella classe» | Le condizioni compaiono più volte nella stessa istruzione, insieme ai parametri di `BuildWhere`: gli interi evitano scontri di nomi e non sono mai testo di Alberto. Con «Tutte le foto» + «Copiati» un post copiato in parte deve mostrare i suoi file copiati | -| 2026-11-27 | Tappa E2: **nessuna migrazione `0004`** nei pacchetti scritti finora: il filtro «Copie» usa gli indici della `0003`. La misura dei 250 ms con 200.000 elementi (`LibraryScaleTests`) e la decisione sulla `0004` (`ix_media_sha256_entry`) restano da fare con le prove della tappa | La sonda temporanea dei tempi ha girato ma i numeri non sono stati raccolti: una decisione senza misura non si scrive | +| 2026-11-27 | Tappa E2: **migrazione `0004`**, solo l'indice `ix_media_sha256_entry` su `media (sha256, entry_id)`, per il filtro «Copie». Misure con 200.000 elementi (`LibraryScaleTests`, senza statistiche e con ANALYZE, su questa macchina): la finestra di «Copiati» 249 ms senza l'indice, 161–164 ms con l'indice; «Non ancora copiati» 13–16 ms; «Tolti o superati» 33–67 ms; in «Tutte le foto» 19–168 ms. Totali e giorni: «Copiati» 0,65–0,71 s, «Non ancora copiati» 0,91–1,13 s, «Tolti o superati» 0,23–0,39 s. Le finestre stanno nei 250 ms di §15; totali e giorni del filtro «Copie» hanno un limite loro di 3 s invece dei 600 ms dei filtri «Foto» e «Video» | Senza l'indice la finestra di «Copiati» era al limite (249 ms su 250): l'elenco degli elementi con una copia leggeva la riga di ogni file trovato. Nei conteggi ogni file dovuto si confronta con le copie (240.000 file, circa 4 µs l'uno): «Copiati» si conta partendo dalle copie (un terzo del tempo di prima, 1,5 s → 0,67 s), gli altri valori con un solo passaggio sui file dietro gli elenchi degli SHA-256 delle copie (0,58 → 0,35 s su 40.000 elementi per «Non ancora copiati»). Scendere sotto i 600 ms vorrebbe uno stato delle copie per file, che E2 non aggiunge | +| 2026-11-27 | Tappa E2: «Copia di nuovo» sceglie, fra i file dell'account con lo SHA-256 della copia, uno che è sul disco; solo se nessuno c'è prende il primo (e il lavoro lo segna «non presente in libreria») | Lo stesso contenuto può stare in due elementi: prima si prendeva il primo trovato, che nella demo, secondo l'ora in cui nasce, era un video senza file sul disco, e la copia di nuovo non scriveva nulla (`ExportApiDemoCommandTests`) | | 2026-11-27 | Tappa E2: «Copia in…» **non sceglie la destinazione**: ogni file va nella destinazione effettiva del suo account, e la finestra dice dove («In cartella generale», «In cartella di @nome») | SPECIFICA §4.10: un account ha al più una destinazione effettiva, «già copiato» è un sì o un no | | 2026-11-27 | Tappa E2: **un `export_run` per destinazione**; un lavoro in memoria li fa in ordine (id più vecchio prima). «Interrompi» vale per il lavoro, «Riprendi» per una copia o per tutte. `StartAsync` restituisce le copie registrate **e il piano** (`ExportStart`), perché la risposta dica anche i file non esportati e quelli che mancano; mentre registra le righe il servizio è occupato (un doppio «Copia in…» non registra due volte), e se il lavoro non può partire le copie registrate diventano «Annullata» | `export_run.destination_id` è obbligatorio e `export_item` non ha la destinazione. Le note «non si esporta» e «non presente in libreria» esistono solo nel piano | | 2026-11-27 | Tappa E2: si copiano **solo gli originali** (`Variant = Whole`, `Format = Original`). I comandi di E3 ed E4 («Fotogrammi…», «Fotogramma», «È un video fermo?», i menu dei formati, la conversione della libreria) **mancano** dall'interfaccia, non sono spenti; le chiavi di `ExportSettings` restano come le ha lasciate E1 | SPECIFICA §10.4: un pulsante dice che cosa succede; un comando grigio senza niente dietro non dice nulla, e con il solo «Originale» un menu dei formati non serve | diff --git a/src/Febe.Data/Migrations/0004_esportazione_filtro.sql b/src/Febe.Data/Migrations/0004_esportazione_filtro.sql new file mode 100644 index 0000000..bac0423 --- /dev/null +++ b/src/Febe.Data/Migrations/0004_esportazione_filtro.sql @@ -0,0 +1,8 @@ +-- Febe, schema version 4: the «Copie» filter of the library (tappa E2 of 0.3.0, issue #58; spec §4.6, §4.10, §8.3). +-- Run by the migration runner inside a transaction; PRAGMA user_version is set by the runner. +-- Only an index is added: no table, column or data changes. + +-- The «Copie» filter joins the copies of the destinations in use to the files of the library by SHA-256, for the list +-- of the entries that have a copy («Copiati»): with the entry in the index the join never reads the row of the file. +-- Over 200,000 entries the window of «Copiati» took 249 ms without it, at the bound of 250 ms (docs/decisioni.md). +CREATE INDEX ix_media_sha256_entry ON media (sha256, entry_id) WHERE sha256 IS NOT NULL; diff --git a/src/Febe.Data/Stores/EntryStore.cs b/src/Febe.Data/Stores/EntryStore.cs index 1f9754a..fa2cd42 100644 --- a/src/Febe.Data/Stores/EntryStore.cs +++ b/src/Febe.Data/Stores/EntryStore.cs @@ -343,8 +343,11 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore // in SQL, no sort, and the day bounds are computed once per day rather than once per entry. var command = c.Command(string.Empty); var files = mode == MosaicMode.Files; - var where = BuildWhere(c, command, files ? EntriesOfFiles(filter) : filter, aggregate: true, files: files); var counts = files ? FileCounts(c, filter) : null; + // With the counts of every entry the «Copie» term of the entries adds nothing (an entry without files + // of the class counts 0) and would test each file a second time, once per entry. + var entries = !files ? filter : counts is null ? EntriesOfFiles(filter) : EntriesOfFiles(filter) with { Copies = null }; + var where = BuildWhere(c, command, entries, aggregate: true, files: files); var perEntry = files && counts is null; command.CommandText = !files ? $"SELECT e.published_at FROM entry e WHERE {where} ORDER BY e.published_at" @@ -422,14 +425,17 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore /// class of the «Copie» filter. With «Copie» the term reads the entry e of the file too (account and kind), so /// the caller must have it in scope (). /// - internal static string FileTerms(SqliteConnection c, LibraryFilter filter) => + /// The connection (for the export tables of «Copie»). + /// The filter. + /// The terms are read on every file of the library (the counts per entry): see ExportFilterSql.FileTerm. + internal static string FileTerms(SqliteConnection c, LibraryFilter filter, bool bulk = false) => // The unary + keeps SQLite on the key of the entry (entry_id, position) rather than on the broad state index. "+m.state IN ('Downloaded', 'Imported')" + filter.Kind switch { LibraryKindFilter.Photos => " AND m.kind = 'Photo'", LibraryKindFilter.Videos => " AND m.kind = 'Video'", _ => string.Empty, - } + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies) : string.Empty); + } + (filter.Copies is { } copies ? " AND " + ExportFilterSql.FileTerm(ExportFilterSql.Load(c), copies, bulk) : string.Empty); /// The file terms of this filter read the entry of the file (the «Copie» filter). private static bool NeedsEntry(LibraryFilter filter) => filter.Copies is not null; @@ -447,7 +453,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore } var from = NeedsEntry(filter) ? "media m JOIN entry e ON e.id = m.entry_id" : "media m"; - using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter)} GROUP BY m.entry_id"); + using var command = c.Command($"SELECT m.entry_id, COUNT(*) FROM {from} WHERE {FileTerms(c, filter, bulk: true)} GROUP BY m.entry_id"); var counts = new Dictionary(); using var r = command.ExecuteReader(); while (r.Read()) @@ -814,7 +820,7 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore if (filter.Copies is { } copies) { var export = ExportFilterSql.Load(c); - parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies)); + parts.Add(files ? ExportFilterSql.EntryOfFiles(export, copies) : ExportFilterSql.EntryTerm(export, copies, byList)); } var term = TextSearch.Normalize(filter.Search); diff --git a/src/Febe.Data/Stores/ExportFilterSql.cs b/src/Febe.Data/Stores/ExportFilterSql.cs index 0ce78c0..61a8657 100644 --- a/src/Febe.Data/Stores/ExportFilterSql.cs +++ b/src/Febe.Data/Stores/ExportFilterSql.cs @@ -137,30 +137,44 @@ internal static class ExportFilterSql /// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was /// superseded (or removed) by this file. Never copied again by itself (D9). Two EXISTS, one per index. /// - public static string Replaced(ExportFilterContext x) + /// The context of the query. + /// The term is evaluated on every file of the library (see ). + public static string Replaced(ExportFilterContext x, bool bulk = false) => !x.HasHistory + ? "0" + : $"({History(x, bulk)} AND NOT {CopiedTerm(x, bulk)} AND NOT {Failed(x)})"; + + /// + /// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). The same partition + /// as NOT Copied AND NOT Replaced, without testing the copy twice. + /// + /// The context of the query. + /// The term is evaluated on every file of the library (see ). + public static string NotCopied(ExportFilterContext x, bool bulk = false) { if (!x.HasHistory) { - return "0"; + return $"(NOT {CopiedTerm(x, bulk)})"; } - var destination = DestinationOf(x); - return $"(NOT {Copied(x)} AND NOT {Failed(x)} AND (" - + $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " - + "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL) " - + $"OR EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " - + "AND c.state IN ('Superseded', 'Removed'))))"; + return x.HasFailed + ? $"(NOT {CopiedTerm(x, bulk)} AND ({Failed(x)} OR NOT {History(x, bulk)}))" + : $"(NOT {CopiedTerm(x, bulk)} AND NOT {History(x, bulk)})"; } - /// «Non ancora copiato»: what «Copia in…» would copy (neither copied nor removed or superseded). - public static string NotCopied(ExportFilterContext x) => x.HasHistory ? $"(NOT {Copied(x)} AND NOT {Replaced(x)})" : $"(NOT {Copied(x)})"; - /// The term of «Tutte le foto» on m (with e its entry): a due file of the chosen class. - public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter) => filter switch + /// The context of the query. + /// The class. + /// + /// The term is evaluated on every file of the library (the counts of «Tutte le foto», the lists of the totals and + /// days) rather than on the few files of a window: each EXISTS then sits behind a list of the SHA-256 of the copies + /// of the destinations in use, read once from ix_export_copy_destination, so most files are settled by that list + /// without a lookup of their own (WP5b of tappa E2, measured over 200,000 entries). + /// + public static string FileTerm(ExportFilterContext x, LibraryCopiesFilter filter, bool bulk = false) => filter switch { - LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {Copied(x)})", - LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x)})", - LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x)})", + LibraryCopiesFilter.Copied => $"({DueFile(x)} AND {CopiedTerm(x, bulk)})", + LibraryCopiesFilter.NotCopied => $"({DueFile(x)} AND {NotCopied(x, bulk)})", + LibraryCopiesFilter.RemovedOrSuperseded => $"({DueFile(x)} AND {Replaced(x, bulk)})", _ => throw new ArgumentOutOfRangeException(nameof(filter), filter, null), }; @@ -169,7 +183,15 @@ internal static class ExportFilterSql /// with a copy (materialized once, a superset); «Non ancora copiati»: a due file to copy; «Tolti o superati»: a due /// file removed or superseded, behind the list of the entries with such a row. /// - public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter) + /// The context of the query. + /// The class. + /// + /// A count over the whole library (totals, days) rather than a window: «Copiati» and «Non ancora copiati» then read + /// one list of the entries of the due files of the class, in a single pass over the files with the + /// bulk terms, instead of an EXISTS per entry (about three times faster over 200,000 entries). + /// A window keeps the EXISTS: it stops after a few hundred entries in index order. + /// + public static string EntryTerm(ExportFilterContext x, LibraryCopiesFilter filter, bool aggregate = false) { if (!x.HasDestination) { @@ -177,12 +199,15 @@ internal static class ExportFilterSql } string Files(string term) => $"EXISTS (SELECT 1 FROM media m WHERE m.entry_id = e.id AND {DueFile(x)} AND {term})"; + string List(string term) => $"(SELECT m.entry_id FROM media m JOIN entry e ON e.id = m.entry_id WHERE {DueFile(x)} AND {term})"; + var withCopy = $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) " + + "AND c.state = 'Copied' AND c.variant <> 'Frame')"; return filter switch { - LibraryCopiesFilter.Copied => !x.HasCopies - ? "0" - : $"+e.id IN (SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN ({InUse(x)}) " - + $"AND c.state = 'Copied' AND c.variant <> 'Frame') AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}", + LibraryCopiesFilter.Copied when !x.HasCopies => "0", + LibraryCopiesFilter.Copied when aggregate => CopiedEntries(x), + LibraryCopiesFilter.Copied => $"{withCopy} AND {Files("1")} AND NOT {Files($"NOT {Copied(x)}")}", + LibraryCopiesFilter.NotCopied when aggregate => $"+e.id IN {List(NotCopied(x, bulk: true))}", LibraryCopiesFilter.NotCopied => Files(NotCopied(x)), LibraryCopiesFilter.RemovedOrSuperseded => !x.HasHistory ? "0" @@ -214,6 +239,54 @@ internal static class ExportFilterSql return builder.Append(CultureInfo.InvariantCulture, $" ELSE {general} END)").ToString(); } + /// + /// «Copiati» over the whole library, from the copies rather than from the files: the copied due files of each entry, + /// counted from the Copied rows of the destinations in use (CROSS JOIN keeps that order, with or without ANALYZE), + /// equal to its due files. The same rows as per file; a third of the time of a pass over every + /// file of 200,000 entries. + /// + private static string CopiedEntries(ExportFilterContext x) + { + var match = x.SamePost == SamePostCopies.OneOnly + ? string.Empty + : $" AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id"; + return "+e.id IN (SELECT m.entry_id FROM export_copy c CROSS JOIN media m CROSS JOIN entry e " + + $"WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied' AND c.variant <> 'Frame' AND m.sha256 = c.source_sha256 AND e.id = m.entry_id{match} " + + $"AND {DueFile(x)} GROUP BY m.entry_id " + + $"HAVING COUNT(DISTINCT m.id) = (SELECT COUNT(*) FROM media m WHERE m.entry_id = e.id AND {DueFile(x)}))"; + } + + /// + /// Copied (); in bulk behind the list of the SHA-256 copied in a destination in use (a superset: + /// any account, any variant), so a file never copied anywhere needs no lookup of its own. + /// + private static string CopiedTerm(ExportFilterContext x, bool bulk) => !x.HasCopies + ? "0" + : bulk + ? $"(m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({InUse(x)}) AND c.state = 'Copied') AND {Copied(x)})" + : Copied(x); + + /// + /// The removed or superseded part of : the copy of this file in the effective destination was + /// removed, or a copy was superseded (or removed) by this file. In bulk each EXISTS sits behind its list of SHA-256. + /// + private static string History(ExportFilterContext x, bool bulk) + { + var destination = DestinationOf(x); + var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " + + "AND c.state = 'Removed' AND c.superseded_by_sha256 IS NULL)"; + var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id " + + "AND c.state IN ('Superseded', 'Removed'))"; + if (!bulk) + { + return $"({removed} OR {superseded})"; + } + + var inUse = InUse(x); + return $"((m.sha256 IN (SELECT c.source_sha256 FROM export_copy c WHERE c.destination_id IN ({inUse}) AND c.state = 'Removed') AND {removed}) " + + $"OR (m.sha256 IN (SELECT c.superseded_by_sha256 FROM export_copy c WHERE c.superseded_by_sha256 IS NOT NULL AND c.destination_id IN ({inUse})) AND {superseded}))"; + } + private static string InUse(ExportFilterContext x) => string.Join(", ", x.InUse.Select(Literal)); private static string TypeTerm(ContentTypes types) => diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs index 55afea9..80f13c8 100644 --- a/src/Febe.Web/Api/ExportApi.cs +++ b/src/Febe.Web/Api/ExportApi.cs @@ -239,7 +239,7 @@ public static class ExportApi return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); }); - endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, CancellationToken ct) => + endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) => { var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CopyAgainRequest).ConfigureAwait(false); var copy = await storage.Exports.GetCopyAsync(body.CopyId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Questa copia non è più registrata."); @@ -261,8 +261,14 @@ public static class ExportApi throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella."); } - var location = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false)) - .FirstOrDefault(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State)) + // Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two + // entries, and the first one found may be a file the library lost (it would end «non presente in libreria»). + var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false); + var present = (await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false)) + .Where(l => l.Entry.AccountId == accountId && EntryStateRules.IsPresent(l.Media.State)) + .ToList(); + var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) + ?? present.FirstOrDefault() ?? throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo."); var service = await hub.GetAsync(ct).ConfigureAwait(false); var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false); diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index 3fbe074..688b495 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using Febe.Core.Domain; +using Febe.Core.Export; using Febe.Core.Storage; using Febe.Data; using Febe.Tests.Support; @@ -8,7 +9,10 @@ namespace Febe.Tests.Data; /// /// Spec §4.6: the library must stay fluid with 200,000 entries. The class runs alone, after the parallel tests, so the -/// timings do not compete with the other workers and the long fill does not load them (#46). +/// timings do not compete with the other workers and the long fill does not load them (#46). Tappa E2 adds the «Copie» +/// filter (§15: «filtro Copie con 200.000 elementi entro 250 ms»): a general folder, an own folder that takes only the +/// photos of its account, an account with «Esporta questo account» off, a third of the due files copied, 2 % removed +/// and 1 % superseded. /// [TestClass] [DoNotParallelize] @@ -17,6 +21,10 @@ public sealed class LibraryScaleTests private const int Entries = 200_000; private const int Accounts = 40; + // Tappa E2: the account with its own folder (posts, photos only) and the account with «Esporta questo account» off. + private const int OwnAccount = 4; + private const int OffAccount = 7; + // Bounds per class of query, about 5-8× the values measured on an unloaded machine (docs/decisioni.md, #46). // Index seeks and windows measure 2-30 ms; aggregates over the whole library or an account 60-220 ms. private const double IndexBoundMs = 250; @@ -25,6 +33,11 @@ public sealed class LibraryScaleTests // «Foto» and «Video» over the whole library: 60-180 ms measured; an EXISTS per post took 1.3-1.6 s and must fail. private const double FilteredAggregateBoundMs = 600; + // «Copie» over the whole library (tappa E2, WP5b): every due file is classified against the copies, 240,000 files + // at about 4 µs each; measured 0.23-1.1 s (docs/decisioni.md), «Non ancora copiati» the slowest. The design asked for + // the 600 ms of the filtered aggregates: not reachable without a column of state per file, which E2 does not add. + private const double CopiesAggregateBoundMs = 3000; + public TestContext TestContext { get; set; } = null!; [TestMethod] @@ -67,17 +80,66 @@ public sealed class LibraryScaleTests await db.Entries.AddManyAsync(items, ct); } + var copies = await FillCopiesAsync(db, temp, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); // Plans differ with and without ANALYZE statistics: both must be fast. // The fill stays outside the timings. - await MeasureAll(db, accountIds, "senza statistiche", ct); + await MeasureAll(db, accountIds, copies, "senza statistiche", ct); await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct); - await MeasureAll(db, accountIds, "con ANALYZE", ct); + await MeasureAll(db, accountIds, copies, "con ANALYZE", ct); } - private async Task MeasureAll(FebeDatabase db, List accountIds, string label, CancellationToken ct) + /// + /// The export side of the library: the general folder for every account, an own folder for account 4 (post photos + /// only, so its videos are not due), account 7 switched off. The copies are written in bulk on the due files only, + /// chosen by a hash of the media id: a third Copied, then 2 % Removed and 1 % Superseded by the file now in the + /// library. Not by the media id itself: the fill repeats every 40 entries (48 files), so «m.id % 3» (or any linear + /// hash of it) would copy all the files of some accounts and none of others; a square mixes the ids. + /// + private static async Task FillCopiesAsync(FebeDatabase db, TempFolder temp, List accountIds, CancellationToken ct) + { + const string Hash = "((m.id * 2654435761) % 1000003)"; + const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)"; + var general = await db.Exports.AddDestinationAsync( + new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct); + var own = await db.Exports.AddDestinationAsync( + new ExportDestination { Scope = ExportScope.Account, AccountId = accountIds[OwnAccount], RootPath = temp.Combine("sua"), ContentTypes = ContentTypes.PostPhotos, CreatedAt = Make.T0 }, + ct); + await db.Exports.SetAccountExportEnabledAsync(accountIds[OffAccount], false, ct); + + var destination = $"(CASE e.account_id WHEN {accountIds[OwnAccount]} THEN {own.Id} ELSE {general.Id} END)"; + var due = $"m.sha256 IS NOT NULL AND e.account_id <> {accountIds[OffAccount]} AND (e.account_id <> {accountIds[OwnAccount]} OR m.kind = 'Photo')"; + int Insert(WriteContext w, string state, string source, string supersededBy, string which) => w.Command( + $""" + INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, state, superseded_by_sha256, + origin, relative_path, bytes, copy_sha256, copied_at) + SELECT {destination}, e.account_id, m.id, {source}, 'Whole', 'Original', '{state}', {supersededBy}, + 'Written', 'p/' || m.id || '.jpg', 1000, {source}, 1767225600000 + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE {due} AND {which} + """).ExecuteNonQuery(); + return await db.WriteAsync( + w => new CopiesWorld( + Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0"), + Insert(w, "Removed", "m.sha256", "NULL", $"{Spread} % 3 <> 0 AND {Spread} % 50 = 1"), + // The old original of a file replaced in the library («Tieni il più grande», a rebuild). + Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"), + DueFiles(), + accountIds[OwnAccount]), + ct); + } + + /// The due files of the fill, from its rules: every file, but none of account 7 and only the photos of account 4. + private static int DueFiles() => Enumerable.Range(0, Entries).Sum(n => (n % Accounts) switch + { + OffAccount => 0, + OwnAccount => (n % 7 != 0 ? 1 : 0) + (n % 5 == 0 ? 1 : 0), + _ => 1 + (n % 5 == 0 ? 1 : 0), + }); + + private async Task MeasureAll(FebeDatabase db, List accountIds, CopiesWorld copies, string label, CancellationToken ct) { var times = new List<(string Name, double Bound, Timing Timing)>(); async Task Measure(string name, double bound, Func> query) @@ -155,15 +217,74 @@ public sealed class LibraryScaleTests await Measure("coda degli scaricamenti", IndexBoundMs, () => db.Media.ListPendingDownloadsAsync(50)); var hashes = await Measure("caricamento impronte", AggregateBoundMs, () => db.Media.LoadPerceptualHashesAsync()); Assert.IsGreaterThan(150_000, hashes.Count); + // The times are printed even when a result of the «Copie» filter is wrong (the measures are the point of #46). + AssertFailedException? copiesProblem = null; + try + { + await MeasureCopiesAsync(Measure, db, accountIds, copies); + } + catch (AssertFailedException e) + { + copiesProblem = e; + } foreach (var (name, bound, timing) in times) { TestContext.WriteLine($"[{label}] {name,-40} {timing.BestMs,8:F1} ms (limite {bound:F0}, {timing.Runs} prove)"); } + if (copiesProblem is not null) + { + throw copiesProblem; + } + foreach (var (name, bound, timing) in times) { Assert.IsLessThan(bound, timing.BestMs, $"[{label}] {name}"); } } + + /// + /// The «Copie» filter (tappa E2): the window of each of its three values at the bound of the windows, in the + /// grouped mosaic, in «Tutte le foto» and on one account (§15: 250 ms); totals and days at their own bound. + /// In «Tutte le foto» the three values split the due files (D3), so their days add up to the copies written. + /// + private static async Task MeasureCopiesAsync( + Func>, Task> measure, FebeDatabase db, List accountIds, CopiesWorld copies) + { + var values = new (LibraryCopiesFilter Value, string Name)[] + { + (LibraryCopiesFilter.Copied, "copiati"), + (LibraryCopiesFilter.NotCopied, "non ancora copiati"), + (LibraryCopiesFilter.RemovedOrSuperseded, "tolti o superati"), + }; + var files = new Dictionary(); + foreach (var (value, name) in values) + { + var filter = new LibraryFilter { Copies = value }; + var window = (LibraryPage)await measure($"Copie {name}", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = filter })); + Assert.HasCount(200, window.Tiles, name); + Assert.IsFalse(window.Tiles.Any(t => t.AccountId == accountIds[OffAccount]), name); + var fileWindow = (LibraryPage)await measure($"Copie {name}: tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = filter })); + Assert.HasCount(200, fileWindow.Tiles, name); + var own = new LibraryFilter { Copies = value, AccountIds = [copies.OwnAccountId] }; + var ownWindow = (LibraryPage)await measure($"Copie {name}: un account", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = own })); + Assert.IsNotEmpty(ownWindow.Tiles, name); + Assert.IsTrue(ownWindow.Tiles.All(t => t.AccountId == copies.OwnAccountId), name); + await measure($"Copie {name}: un account, tutte le foto", IndexBoundMs, async () => await db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = own })); + var totals = (LibraryTotals)await measure($"Copie {name}: totali", CopiesAggregateBoundMs, async () => await db.Entries.GetLibraryTotalsAsync(filter)); + var days = (IReadOnlyList)await measure($"Copie {name}: giorni", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome)); + Assert.AreEqual(totals.Entries, days.Sum(d => d.Count), name); + Assert.AreEqual(Accounts - 1, totals.Accounts, name); + var fileDays = (IReadOnlyList)await measure($"Copie {name}: giorni, tutte le foto", CopiesAggregateBoundMs, async () => await db.Entries.CountLibraryByDayAsync(filter, TestZones.Rome, MosaicMode.Files)); + files[value] = fileDays.Sum(d => d.Count); + } + + Assert.AreEqual(copies.Copied, files[LibraryCopiesFilter.Copied]); + Assert.AreEqual(copies.Removed + copies.Superseded, files[LibraryCopiesFilter.RemovedOrSuperseded]); + Assert.AreEqual(copies.Due - copies.Copied - copies.Removed - copies.Superseded, files[LibraryCopiesFilter.NotCopied]); + } + + /// What the export fill wrote: copies by state, the due files, and the account with its own folder. + private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId); } diff --git a/tests/Febe.Tests/Data/MigrationTests.cs b/tests/Febe.Tests/Data/MigrationTests.cs index 7e3d287..d21125f 100644 --- a/tests/Febe.Tests/Data/MigrationTests.cs +++ b/tests/Febe.Tests/Data/MigrationTests.cs @@ -164,6 +164,9 @@ public sealed class MigrationTests [TestMethod] public async Task DatabaseAtVersion2IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(2); + [TestMethod] + public async Task DatabaseAtVersion3IsUpgradedWithForeignKeysClean() => await UpgradeKeepsEverything(3); + [TestMethod] public void MigrationThreeChangesNoExistingTable() { @@ -174,12 +177,42 @@ public sealed class MigrationTests var before = SchemaOf(path, Version1Tables); var shapesBefore = TableShapes(path, Version1Tables); - Close(FebeDatabase.Open(path, all)); + // Migration 4 adds an index on media (the «Copie» filter): migration 3 alone is compared here. + Close(FebeDatabase.Open(path, all.Take(3).ToList())); CollectionAssert.AreEqual(before, SchemaOf(path, Version1Tables), "la migrazione 3 non tocca tabelle né indici esistenti"); CollectionAssert.AreEqual(shapesBefore, TableShapes(path, Version1Tables), "colonne e indici delle tabelle esistenti restano gli stessi"); } + /// + /// Migration 4 (tappa E2) adds only the index of the «Copie» filter on media (sha256, entry_id): every other table, + /// column and index stays the same, and the plan of the list of the entries with a copy reads it. + /// + [TestMethod] + public void MigrationFourOnlyAddsTheIndexOfTheCopiesFilter() + { + using var temp = new TempFolder(); + var path = temp.Combine("dati", FebeDatabase.FileName); + var all = MigrationRunner.LoadEmbedded(); + Assert.IsGreaterThanOrEqualTo(4, all.Count); + Close(FebeDatabase.Open(path, all.Take(3).ToList())); + var tables = TablesOf(path); + var before = SchemaOf(path, tables); + + Close(FebeDatabase.Open(path, all.Take(4).ToList())); + + CollectionAssert.AreEqual(tables, TablesOf(path), "nessuna tabella nuova"); + var added = SchemaOf(path, tables).Except(before).ToList(); + Assert.HasCount(1, added, string.Join(" | ", added)); + StringAssert.Contains(added[0], "ix_media_sha256_entry"); + StringAssert.Contains(added[0], "(sha256, entry_id) WHERE sha256 IS NOT NULL"); + CollectionAssert.IsSubsetOf(before, SchemaOf(path, tables), "nulla di prima cambia"); + using var connection = Connect(path); + var plan = string.Join(" | ", ReadColumn(connection, + "EXPLAIN QUERY PLAN SELECT m2.entry_id FROM export_copy c JOIN media m2 ON m2.sha256 = c.source_sha256 WHERE c.destination_id IN (1, 2) AND c.state = 'Copied'", 3)); + StringAssert.Contains(plan, "COVERING INDEX ix_media_sha256_entry", plan); + } + [TestMethod] public async Task DatabaseOneVersionNewerIsRefusedAndLeftUntouched() { @@ -218,7 +251,7 @@ public sealed class MigrationTests await using (var db = FebeDatabase.Open(path, all)) { Assert.AreEqual(all.Count, db.SchemaVersion); - Assert.AreEqual(3, db.SchemaVersion); + Assert.AreEqual(4, db.SchemaVersion); } using var connection = Connect(path); @@ -340,6 +373,26 @@ public sealed class MigrationTests return rows; } + /// Every table of the database, by name. + private static List TablesOf(string path) + { + using var connection = Connect(path); + return ReadColumn(connection, "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", 0); + } + + /// One column of every row of a query, as text. + private static List ReadColumn(SqliteConnection connection, string sql, int column) + { + using var r = connection.Command(sql).ExecuteReader(); + var values = new List(); + while (r.Read()) + { + values.Add(Convert.ToString(r.GetValue(column), System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty); + } + + return values; + } + /// The SQL of the tables and of their indexes and triggers. private static List SchemaOf(string path, IEnumerable tables) { diff --git a/tests/Febe.Tests/Packaging/ImageContentsTests.cs b/tests/Febe.Tests/Packaging/ImageContentsTests.cs index 7a8b934..0667b2e 100644 --- a/tests/Febe.Tests/Packaging/ImageContentsTests.cs +++ b/tests/Febe.Tests/Packaging/ImageContentsTests.cs @@ -154,6 +154,45 @@ public sealed partial class ImageContentsTests handovers); } + /// + /// Copie esterne (spec §4.10, §11): /esporta is never made by the image. A VOLUME or a mkdir would give an anonymous + /// volume or a folder of the image disk that looks like a mounted folder; Compose and Unraid offer it commented out + /// or empty, with FEBE_ESPORTA. + /// + [TestMethod] + public void TheImageNeverMakesTheExportFolderAndTheTemplatesOfferItOff() + { + var code = Code(Dockerfile()); + var volume = code.Split('\n').Single(line => line.StartsWith("VOLUME ", StringComparison.Ordinal)); + Assert.DoesNotContain("esporta", volume); + foreach (var line in code.Split('\n').Where(line => line.Contains("mkdir", StringComparison.Ordinal))) + { + Assert.DoesNotContain("esporta", line); + } + + Assert.DoesNotContain("FEBE_ESPORTA", code, "export is off unless the container declares it"); + StringAssert.Contains(Dockerfile(), "Niente /esporta qui", "the reason stays next to VOLUME"); + + var lines = File.ReadAllText(Repository.PathOf("docker", "compose.yml")).Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n'); + var mount = lines.Single(line => line.Contains(":/esporta", StringComparison.Ordinal) && line.Contains("FEBE_CARTELLA_ESPORTA", StringComparison.Ordinal)); + StringAssert.StartsWith(mount.TrimStart(), "# - ", "the mount of /esporta is commented out in compose.yml"); + var variable = lines.Single(line => line.TrimStart().TrimStart('#').TrimStart().StartsWith("FEBE_ESPORTA:", StringComparison.Ordinal)); + StringAssert.StartsWith(variable.TrimStart(), "# ", "FEBE_ESPORTA is commented out in compose.yml"); + var active = lines.Where(line => !line.TrimStart().StartsWith('#') && line.Contains("esporta", StringComparison.OrdinalIgnoreCase)).ToList(); + Assert.IsEmpty(active, string.Join('\n', active)); + + var template = System.Xml.Linq.XDocument.Load(Repository.PathOf("docker", "unraid", "febe.xml")).Root!; + var folder = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "/esporta"); + Assert.AreEqual("Path", (string?)folder.Attribute("Type")); + Assert.AreEqual("false", (string?)folder.Attribute("Required")); + Assert.AreEqual(string.Empty, (string?)folder.Attribute("Default")); + Assert.AreEqual(string.Empty, folder.Value.Trim(), "no folder of the server by default"); + var flag = template.Elements("Config").Single(c => (string?)c.Attribute("Target") == "FEBE_ESPORTA"); + Assert.AreEqual("Variable", (string?)flag.Attribute("Type")); + Assert.AreEqual(string.Empty, (string?)flag.Attribute("Default")); + Assert.AreEqual(string.Empty, flag.Value.Trim()); + } + [TestMethod] public void TheToolsTheStartUsesComeWithTheBaseImageAndTheBuildChecksThem() { diff --git a/tests/Febe.Tests/Packaging/PackagingTests.cs b/tests/Febe.Tests/Packaging/PackagingTests.cs index dbd3557..3baebeb 100644 --- a/tests/Febe.Tests/Packaging/PackagingTests.cs +++ b/tests/Febe.Tests/Packaging/PackagingTests.cs @@ -63,9 +63,11 @@ public sealed partial class PackagingTests Assert.Inconclusive(reason); } - // A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library. + // A first start: /dati and /libreria just created by Docker (root), a folder of photos inside the library, and + // an /esporta mounted with a folder of copies, while the copies are not declared. using var temp = new TempFolder("avvio-contenitore"); Directory.CreateDirectory(temp.Combine("libreria", "foto")); + Directory.CreateDirectory(temp.Combine("esporta", "usb")); var whoAmI = temp.Combine("dati", "home", "chi"); var (code, _, errors) = await RunEntrypointAsync(temp, "/bin/sh", "-c", $"id -u > '{whoAmI}'"); Assert.AreEqual(0, code, errors); @@ -75,12 +77,40 @@ public sealed partial class PackagingTests Assert.IsFalse(File.Exists(temp.Combine("dati", "seccomp.json")), "the profile Docker reads stays out of /dati"); Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("libreria"))).Split(' ')[0]); Assert.AreEqual("0:0", (await StatAsync(temp.Combine("libreria", "foto"))).Split(' ')[0], "the library is never changed recursively"); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "/esporta is left alone while the copies are not declared"); // A /dati/home left by a start as root (a real folder): given back to the user. await RunAsync("chown", "0:0", temp.Combine("dati", "home")); (code, _, errors) = await RunEntrypointAsync(temp, "true"); Assert.AreEqual(0, code, errors); Assert.AreEqual($"{Nobody}:{Nobody} 700", await StatAsync(temp.Combine("dati", "home"))); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]); + (code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "no")); + Assert.AreEqual(0, code, errors); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "only the values of a switch declare the copies"); + + // Copie esterne declared (FEBE_ESPORTA=1): the root of /esporta, owned by root, goes to the user; what is inside + // (files of Alberto, other copies) never changes owner. + (code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "1")); + Assert.AreEqual(0, code, errors); + Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]); + Assert.AreEqual("0:0", (await StatAsync(temp.Combine("esporta", "usb"))).Split(' ')[0], "/esporta is never changed recursively"); + + // Declared with --esporta among the arguments of the server: the same. A root of another user stays his. + await RunAsync("chown", "0:0", temp.Combine("esporta")); + (code, _, errors) = await RunEntrypointAsync(temp, "true", "--esporta"); + Assert.AreEqual(0, code, errors); + Assert.AreEqual($"{Nobody}:{Nobody}", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0]); + await RunAsync("chown", "1234:1234", temp.Combine("esporta")); + (code, _, errors) = await RunEntrypointAsync(temp, ["true"], ("FEBE_ESPORTA", "1")); + Assert.AreEqual(0, code, errors); + Assert.AreEqual("1234:1234", (await StatAsync(temp.Combine("esporta"))).Split(' ')[0], "only a root owned by root is given to the user"); + + // A missing /esporta is never created, declared or not. + Directory.Delete(temp.Combine("esporta"), recursive: true); + (code, _, errors) = await RunEntrypointAsync(temp, ["true", "--esporta"], ("FEBE_ESPORTA", "1")); + Assert.AreEqual(0, code, errors); + Assert.IsFalse(Directory.Exists(temp.Combine("esporta")), "the start never creates /esporta"); } [TestMethod] @@ -206,7 +236,12 @@ public sealed partial class PackagingTests } /// The real entrypoint, with /dati, /libreria, /esporta and the profile of the image moved into . - private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command) + private Task<(int Code, string Output, string Errors)> RunEntrypointAsync(TempFolder temp, params string[] command) => + RunEntrypointAsync(temp, command, []); + + /// The same, with variables of the container (FEBE_ESPORTA is never taken from the machine of the tests). + private async Task<(int Code, string Output, string Errors)> RunEntrypointAsync( + TempFolder temp, string[] command, params (string Name, string Value)[] variables) { var text = await File.ReadAllTextAsync(Repository.PathOf("docker", "entrypoint.sh"), TestContext.CancellationToken); var image = temp.Combine("immagine-seccomp.json"); @@ -229,6 +264,12 @@ public sealed partial class PackagingTests start.Environment["PUID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture); start.Environment["PGID"] = Nobody.ToString(System.Globalization.CultureInfo.InvariantCulture); + start.Environment.Remove("FEBE_ESPORTA"); + foreach (var (name, value) in variables) + { + start.Environment[name] = value; + } + using var process = Process.Start(start)!; var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); diff --git a/tests/Febe.Tests/Server/ServerOptionsTests.cs b/tests/Febe.Tests/Server/ServerOptionsTests.cs index 4ee4fbd..de41d3a 100644 --- a/tests/Febe.Tests/Server/ServerOptionsTests.cs +++ b/tests/Febe.Tests/Server/ServerOptionsTests.cs @@ -1,5 +1,6 @@ using System.Net; using Febe.Core.Abstractions; +using Febe.Core.Export; using Febe.Server; using Febe.Tests.Support; using Febe.Web; @@ -28,6 +29,14 @@ public sealed class ServerOptionsTests Assert.AreEqual("instagram", o.Site.Name); Assert.AreEqual("https://www.instagram.com/accounts/login/", o.LoginUrl); Assert.IsEmpty(o.AllowedHostList(), "any host name by default"); + // Copie esterne (§4.10, §11): /esporta is the only root, and it is off until declared. + Assert.IsFalse(o.ExportDeclared); + Assert.AreEqual("/esporta", o.ExportFolder); + var export = o.AppOptions().ExportRoot; + Assert.IsFalse(export.Declared); + Assert.AreEqual(ExportPaths.Trim(Path.GetFullPath("/esporta")), export.Root); + Assert.IsFalse(ExportRoots.Evaluate(export).Active); + Assert.Contains("Copie esterne = spente", o.ToString()); var web = o.WebOptions(); Assert.AreEqual(FebeEdition.Docker, web.Edition); @@ -46,13 +55,17 @@ public sealed class ServerOptionsTests ("FEBE_HOST", "tower.local, 192.168.1.10"), ("FEBE_PROXY_FIDATO", "1"), ("FEBE_SENZA_SANDBOX", "1"), - ("FEBE_PORTA_DEBUG", "9333")); + ("FEBE_PORTA_DEBUG", "9333"), + ("FEBE_ESPORTA", "1")); Assert.IsTrue(ServerOptions.TryParse(["--dati", "/tmp/d", "--sito-di-prova", "http://127.0.0.1:8481", "--accesso-di-prova", "--prima-sessione", "5"], env, out var o, out var problem), problem); Assert.AreEqual(9000, o.Port); Assert.AreEqual("Europe/London", o.ZoneId); Assert.IsTrue(o.TrustForwardedHost); Assert.IsTrue(o.NoSandbox); Assert.AreEqual(9333, o.DebugPort); + Assert.IsTrue(o.ExportDeclared); + Assert.IsTrue(o.AppOptions().ExportRoot.Declared); + Assert.Contains("Copie esterne = dichiarate", o.ToString()); Assert.AreEqual("/tmp/d", o.DataFolder); Assert.AreEqual(TimeSpan.FromSeconds(5), o.FirstSessionDelay); Assert.AreEqual("prova", o.Site.Name); @@ -62,6 +75,22 @@ public sealed class ServerOptionsTests Assert.AreEqual("http://127.0.0.1:8481/benvenuto", o.LoginUrl); CollectionAssert.IsSubsetOf(new[] { "tower.local", "tower.local:*", "192.168.1.10:*", "127.0.0.1:*", "localhost:*" }, o.AllowedHostList().ToList()); + // --esporta is a bare flag (no value), and FEBE_ESPORTA takes the values of the other switches. + Assert.IsTrue(ServerOptions.TryParse(["--esporta", "--porta", "9001"], Env(("FEBE_PASSWORD", "x")), out var flagged, out problem), problem); + Assert.IsTrue(flagged.ExportDeclared); + Assert.AreEqual(9001, flagged.Port); + foreach (var value in new[] { "true", "sì", "yes" }) + { + Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "x"), ("FEBE_ESPORTA", value)), out var on, out problem), problem); + Assert.IsTrue(on.ExportDeclared, value); + } + + foreach (var value in new[] { "0", "no", "/esporta" }) + { + Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", "x"), ("FEBE_ESPORTA", value)), out var off, out problem), problem); + Assert.IsFalse(off.ExportDeclared, value); + } + var browser = o.BrowserEnvironment("/dati/home"); Assert.AreEqual("Europe/London", browser["TZ"]); Assert.AreEqual("/dati/home", browser["HOME"]); diff --git a/tests/Febe.Tests/Web/DemoExportTests.cs b/tests/Febe.Tests/Web/DemoExportTests.cs new file mode 100644 index 0000000..7c60263 --- /dev/null +++ b/tests/Febe.Tests/Web/DemoExportTests.cs @@ -0,0 +1,153 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text.Json; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The copies of the demo (spec §10.6, tappa E2) tell one story everywhere: the block «Copie esterne» of each account +/// counts what the «Copie» filter finds and what the tiles mark; every job has its files; a copy «Copiato» is a real +/// file with its SHA-256 in its folder, a copy «Tolto» has none, the old file of a «Superato» is still there. +/// +[TestClass] +public sealed class DemoExportTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task TheDemoExportDataIsCoherent() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("demo-export-coerente"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path), ct); + using var client = new HttpClient { BaseAddress = demo.Address, Timeout = TimeSpan.FromSeconds(60) }; + + async Task GetAsync(string path) + { + using var response = await client.GetAsync(path, ct); + var text = await response.Content.ReadAsStringAsync(ct); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + // Every tile of a query, following the cursors. + async Task> AllTilesAsync(string query) + { + var tiles = new List(); + string? cursor = null; + for (var page = 0; page < 100; page++) + { + var answer = await GetAsync($"/api/library?{query}&limit=1000" + (cursor is null ? string.Empty : "&cursor=" + Uri.EscapeDataString(cursor))); + tiles.AddRange(answer.Items("tiles")); + if (answer.GetProperty("older").ValueKind == JsonValueKind.Null) + { + return tiles; + } + + cursor = answer.Str("older"); + } + + Assert.Fail($"too many pages for {query}"); + return tiles; + } + + // The copies and their files. + var destinations = await demo.Storage.Exports.ListDestinationsAsync(includeRetired: true, ct); + Assert.IsGreaterThanOrEqualTo(2, destinations.Count); + var states = new HashSet(); + foreach (var destination in destinations) + { + Assert.IsTrue(Directory.Exists(destination.RootPath), destination.RootPath); + foreach (var copy in await demo.Storage.Exports.ListCopiesAsync(destination.Id, null, 0, 100_000, ct)) + { + states.Add(copy.State); + var path = copy.RelativePath is { } relative ? Path.Combine(destination.RootPath, LibraryLayout.ToPlatform(relative)) : null; + switch (copy.State) + { + case ExportCopyState.Copied: + Assert.IsTrue(File.Exists(path), $"«Copiato» without its file: {path}"); + Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path); + Assert.AreEqual(copy.Bytes, new FileInfo(path!).Length, path); + break; + case ExportCopyState.Removed: + Assert.IsFalse(path is not null && File.Exists(path), $"«Tolto» with a file: {path}"); + break; + case ExportCopyState.Superseded: + Assert.IsTrue(File.Exists(path), $"the old file of «Superato» stays: {path}"); + Assert.AreEqual(copy.CopySha256, Convert.ToHexStringLower(SHA256.HashData(await File.ReadAllBytesAsync(path!, ct))), path); + break; + case ExportCopyState.Failed: + Assert.IsFalse(string.IsNullOrEmpty(copy.LastError), "a failure says why"); + break; + } + } + } + + CollectionAssert.AreEquivalent( + new[] { ExportCopyState.Copied, ExportCopyState.Removed, ExportCopyState.Superseded, ExportCopyState.Failed }, + states.ToArray(), + "the demo shows every state of a copy"); + Assert.IsFalse(Directory.EnumerateFiles(temp.Path, "*.part", SearchOption.AllDirectories).Any(f => f.Contains("esporta", StringComparison.Ordinal)), "no .part left"); + + // Every job has its files, and a finished one has none pending. + var runs = await demo.Storage.Exports.ListRecentRunsAsync(100, ct); + Assert.IsNotEmpty(runs); + foreach (var run in runs) + { + var summary = await demo.Storage.Exports.GetRunSummaryAsync(run.Id, ct); + Assert.IsGreaterThan(0, summary.Total, $"job {run.Id}"); + if (run.State == ExportRunState.Completed) + { + Assert.AreEqual(0, summary.ByState.GetValueOrDefault(ExportItemState.Pending), $"job {run.Id}"); + } + } + + // Each account: the card, the filter and the marks count the same files. + var accounts = (await GetAsync("/api/accounts")).Items("accounts").ToList(); + var checkedAccounts = 0; + foreach (var account in accounts) + { + var id = account.Long("id"); + var card = (await GetAsync($"/api/accounts/{id}")).GetProperty("export"); + // The card counts every due file of the account, its profile pictures too, which «Tutto» leaves out. + async Task FilesAsync(string copies) => + (await GetAsync($"/api/library/days?accounts={id}&mode=files&copies={copies}")).Int("files") + + (await GetAsync($"/api/library/days?accounts={id}&mode=files&kind=profile&copies={copies}")).Int("files"); + var copied = card.Int("due") - card.Int("notCopied") - card.Int("removedOrSuperseded"); + Assert.AreEqual(card.Int("notCopied"), await FilesAsync("notCopied"), account.Str("username")); + Assert.AreEqual(card.Int("removedOrSuperseded"), await FilesAsync("removedOrSuperseded"), account.Str("username")); + Assert.AreEqual(copied, await FilesAsync("copied"), account.Str("username")); + Assert.IsLessThanOrEqualTo(card.Int("notCopied"), card.Int("failed"), "a failed file is one still to copy"); + + var grouped = await AllTilesAsync($"accounts={id}"); + if (!card.Bool("enabled")) + { + Assert.AreEqual(0, card.Int("due"), account.Str("username")); + Assert.IsTrue(grouped.All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null), "an account that is not exported has no marks"); + continue; + } + + var marked = grouped.Where(t => t.Str("copies") == "copied").Select(t => t.Long("id")).ToHashSet(); + var filtered = (await AllTilesAsync($"accounts={id}&copies=copied")).Select(t => t.Long("id")).ToHashSet(); + Assert.IsTrue(marked.SetEquals(filtered), $"{account.Str("username")}: the mark «copiato» is the filter «Copiati»"); + foreach (var partly in grouped.Where(t => t.Str("copies") == "partly")) + { + Assert.IsGreaterThan(0, partly.Int("copiesDone")); + Assert.IsLessThan(partly.Int("copiesDue"), partly.Int("copiesDone")); + } + + var fileMarks = (await AllTilesAsync($"accounts={id}&mode=files")).Count(t => t.Str("copies") == "copied") + + (await AllTilesAsync($"accounts={id}&mode=files&kind=profile")).Count(t => t.Str("copies") == "copied"); + Assert.AreEqual(copied, fileMarks, $"{account.Str("username")}: one mark per copied file"); + checkedAccounts += card.Int("due") > 0 ? 1 : 0; + } + + Assert.IsGreaterThanOrEqualTo(2, checkedAccounts, "the demo has accounts with files to copy"); + } +} diff --git a/tests/Febe.Tests/Web/ExportApiTests.cs b/tests/Febe.Tests/Web/ExportApiTests.cs new file mode 100644 index 0000000..5061063 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportApiTests.cs @@ -0,0 +1,555 @@ +using System.Net; +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Storage; +using Febe.Tests.Export.Support; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// The copies to external folders over the API of a real web host (spec §4.10, §10.3, tappa E2), outside the demo: +/// whether export is available (Docker not declared, not mounted, mounted), the folders of /esporta, the check of a +/// candidate folder, destinations, «Copia in…» from plan to the files on disk, «Controlla le copie» and «Copia di +/// nuovo», the «Copie» filter, the marks, the viewer and the account card, and the exclusive long work. Files are +/// real (saved through ), destinations are folders of the temporary folder of the test. +/// +[TestClass] +public sealed class ExportApiTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + public async Task TheOverviewSaysWhetherExportIsAvailable() + { + // Docker, not declared (the default of the web host): off, and nothing can be chosen or saved. + await using (var server = await WebTestServer.StartAsync()) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsTrue(root.Bool("docker")); + Assert.IsFalse(root.Bool("active")); + Assert.IsFalse(root.Bool("pickFolder")); + Assert.AreEqual(ExportRoots.NotDeclaredText, root.Str("problem")); + var (folders, folderError) = await server.SendJsonAsync(HttpMethod.Get, "/api/export/folders"); + Assert.AreEqual(HttpStatusCode.BadRequest, folders); + Assert.AreEqual(ExportRoots.NotDeclaredText, folderError.Str("message")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Status); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status); + Assert.IsEmpty(await server.Db.Exports.ListDestinationsAsync(includeRetired: true)); + } + + // Declared, but nothing is mounted at or below /esporta: still off, with its own reason. + using var esporta = new TempFolder("esporta"); + Directory.CreateDirectory(esporta.Combine("usb")); + await using (var server = await StartAsync(ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts()), desktop: false)) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsTrue(root.Bool("docker")); + Assert.IsFalse(root.Bool("active")); + Assert.AreNotEqual(ExportRoots.NotDeclaredText, root.Str("problem")); + Assert.IsNotEmpty(root.Str("problem")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination("usb"))).Status); + } + + // Declared and mounted: on. + await using (var server = await StartAsync(Mounted(esporta), desktop: false)) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsTrue(root.Bool("active"), root.ToString()); + Assert.AreEqual(JsonValueKind.Null, root.GetProperty("problem").ValueKind); + } + + // Windows: any folder, through the picker of the system. + await using (var server = await StartAsync()) + { + var root = (await server.GetJsonAsync("/api/export")).GetProperty("root"); + Assert.IsFalse(root.Bool("docker")); + Assert.IsTrue(root.Bool("active")); + Assert.AreEqual(JsonValueKind.Null, root.GetProperty("root").ValueKind); + } + } + + [TestMethod] + public async Task FoldersAreListedUnderTheExportRootAndDotDotIsRefused() + { + using var esporta = new TempFolder("esporta"); + Directory.CreateDirectory(esporta.Combine("usb", "foto")); + Directory.CreateDirectory(esporta.Combine("nas")); + // Hidden as the import picker hides it: a dot folder on Linux, the attribute on Windows. + var hidden = Directory.CreateDirectory(esporta.Combine(".nascosta")); + hidden.Attributes |= FileAttributes.Hidden; + await using var server = await StartAsync(Mounted(esporta), desktop: false); + + var list = await server.GetJsonAsync("/api/export/folders"); + CollectionAssert.AreEquivalent(new[] { "nas", "usb" }, list.Items("folders").Select(f => f.Str("name")).ToArray(), "no hidden folders"); + Assert.AreEqual(string.Empty, list.Str("relative")); + Assert.AreEqual(JsonValueKind.Null, list.GetProperty("parent").ValueKind); + var usb = await server.GetJsonAsync("/api/export/folders?path=usb"); + Assert.AreEqual("foto", usb.Items("folders").Single().Str("name")); + Assert.AreEqual(string.Empty, usb.Str("parent")); + foreach (var path in new[] { "..", "usb/../..", "../fuori" }) + { + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/export/folders?path={Uri.EscapeDataString(path)}")).Status, path); + } + + var check = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path = "usb" })).Body; + Assert.IsTrue(check.Bool("accepted"), check.ToString()); + Assert.AreEqual(Free, check.Long("freeBytes")); + Assert.IsFalse(check.Bool("fat32")); + foreach (var path in new[] { string.Empty, "..", "../fuori", "usb/../.." }) + { + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path }); + Assert.IsTrue(status == HttpStatusCode.BadRequest || !answer.Bool("accepted"), $"«{path}»: {answer}"); + } + + // In Docker there is no picker of the system: the page lists the folders of /esporta. + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/pick-folder", new { })).Status); + Assert.IsFalse(Directory.Exists(esporta.Combine("fuori")), "nothing is ever created"); + } + + [TestMethod] + public async Task CheckFolderRefusesTheLibraryAndTheDataFolder() + { + await using var server = await StartAsync(); + var account = await AddPhotosAsync(server, "marta.demo", 1); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + Directory.CreateDirectory(server.Library.Layout.AccountFolder(account.Account)); + + var accepted = await CheckAsync(server, usb); + Assert.IsTrue(accepted.Bool("accepted"), accepted.ToString()); + Assert.AreEqual(Free, accepted.Long("freeBytes")); + foreach (var refused in new[] + { + server.Library.Layout.Root, + Path.Combine(server.Library.Layout.Root, "dentro"), + server.Library.Data.Root, + server.Library.Layout.AccountFolder(account.Account), + server.Temp.Path, + server.Temp.Combine("non-esiste"), + }) + { + if (refused.EndsWith("dentro", StringComparison.Ordinal)) + { + Directory.CreateDirectory(refused); + } + + var answer = await CheckAsync(server, refused); + Assert.IsFalse(answer.Bool("accepted"), refused); + Assert.IsNotEmpty(answer.Str("problem"), refused); + } + + Assert.IsFalse(Directory.Exists(server.Temp.Combine("non-esiste")), "a missing folder is never created"); + Assert.IsEmpty(Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "the probe leaves nothing behind"); + } + + [TestMethod] + public async Task DestinationsAreCreatedUpdatedAndRetired() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 1); + var usb = server.Temp.Combine("usb"); + var nas = server.Temp.Combine("nas"); + Directory.CreateDirectory(usb); + Directory.CreateDirectory(nas); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, types: []))).Status, "at least one type"); + var (status, created) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb, label: "Disco USB")); + Assert.AreEqual(HttpStatusCode.OK, status, created.ToString()); + var general = created.GetProperty("destination"); + Assert.AreEqual("general", general.Str("scope")); + Assert.AreEqual("Disco USB", general.Str("label")); + Assert.HasCount(6, general.Items("types").ToList()); + Assert.IsFalse(general.Bool("automatic")); + Assert.AreEqual(general.Long("id"), (await server.GetJsonAsync("/api/export")).GetProperty("general").Long("id")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(nas))).Status, "one general folder"); + + // The same folder: the same destination, changed in place. + var (sameStatus, same) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(usb, label: "Chiavetta", types: ["postFoto"])); + Assert.AreEqual(HttpStatusCode.OK, sameStatus, same.ToString()); + Assert.AreEqual(general.Long("id"), same.GetProperty("destination").Long("id")); + Assert.AreEqual("Chiavetta", same.GetProperty("destination").Str("label")); + CollectionAssert.AreEqual(new[] { "postFoto" }, same.GetProperty("destination").Items("types").Select(t => t.GetString()).ToArray()); + + // Another folder: the old destination is retired (it keeps its copies), a new one takes its place. + var (movedStatus, moved) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{general.Long("id")}", Destination(nas)); + Assert.AreEqual(HttpStatusCode.OK, movedStatus, moved.ToString()); + var next = moved.GetProperty("destination").Long("id"); + Assert.AreNotEqual(general.Long("id"), next); + Assert.IsNotNull((await server.Db.Exports.GetDestinationAsync(general.Long("id")))!.RemovedAt); + + // An own folder of the account, then retired: the account goes back to the general folder. + var sua = server.Temp.Combine("sua"); + Directory.CreateDirectory(sua); + var (ownStatus, own) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(sua, scope: "account", accountId: marta.Account.Id, types: ["postFoto", "postVideo"])); + Assert.AreEqual(HttpStatusCode.OK, ownStatus, own.ToString()); + Assert.AreEqual("marta.demo", own.GetProperty("destination").Str("username")); + var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsTrue(card.Bool("hasOwnFolder")); + Assert.AreEqual(own.GetProperty("destination").Long("id"), card.GetProperty("destination").Long("id")); + var overview = await server.GetJsonAsync("/api/export"); + Assert.AreEqual("marta.demo", overview.Items("own").Single().Str("username")); + + var (retiredStatus, retired) = await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{own.GetProperty("destination").Long("id")}"); + Assert.AreEqual(HttpStatusCode.OK, retiredStatus); + Assert.AreEqual(ExportDestinations.RetiredText, retired.Str("message")); + card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsFalse(card.Bool("hasOwnFolder")); + Assert.AreEqual(next, card.GetProperty("destination").Long("id")); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Delete, $"/api/export/destinations/{next}")).Status); + Assert.AreEqual(JsonValueKind.Null, (await server.GetJsonAsync("/api/export")).GetProperty("general").ValueKind); + Assert.IsTrue(Directory.Exists(usb) && Directory.Exists(nas) && Directory.Exists(sua), "retiring a destination never touches its folder"); + } + + [TestMethod] + public async Task PlanAndStartCopyTheFilesAndTheProgressFinishes() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var usb = await GeneralAsync(server); + + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(3, plan.Int("files"), plan.ToString()); + Assert.IsGreaterThan(0L, plan.Long("bytes")); + Assert.AreEqual(0, plan.Int("alreadyCopied")); + Assert.AreEqual(usb.Id, plan.Items("destinations").Single().Long("id")); + Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "a plan writes nothing"); + + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + var run = job.Items("runIds").Single().GetInt64(); + await WaitIdleAsync(server); + + var progress = await server.GetJsonAsync("/api/export/progress"); + Assert.IsFalse(progress.Bool("running")); + Assert.AreEqual(JsonValueKind.Null, progress.GetProperty("error").ValueKind, progress.ToString()); + var written = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories); + Assert.HasCount(3, written); + Assert.IsTrue(written.All(f => Path.GetRelativePath(usb.Root, f).StartsWith("marta.demo", StringComparison.Ordinal)), "the account segment comes first in the general folder"); + CollectionAssert.AreEquivalent( + marta.Files.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(), + written.Select(f => Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f)))).ToArray(), + "copies byte for byte"); + Assert.IsFalse(written.Any(f => f.EndsWith(".part", StringComparison.Ordinal))); + + var runs = (await server.GetJsonAsync("/api/export/runs")).EnumerateArray().ToList(); + var done = runs.Single(r => r.Long("id") == run); + Assert.AreEqual("completed", done.Str("state")); + Assert.AreEqual(3, done.Int("done")); + var report = await server.GetJsonAsync($"/api/export/runs/{run}/report"); + Assert.AreEqual(3, report.GetProperty("byState").Int("copied")); + Assert.AreEqual("marta.demo", report.Items("accounts").Single().Str("username")); + Assert.IsEmpty(report.Items("problems").ToList()); + + var again = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(0, again.Int("files")); + Assert.AreEqual(3, again.Int("alreadyCopied")); + var overview = await server.GetJsonAsync("/api/export"); + Assert.AreEqual(3, overview.GetProperty("general").GetProperty("counts").Int("copied")); + Assert.AreEqual(0, overview.Int("unfinishedRuns")); + } + + [TestMethod] + public async Task CheckCopiesThenCopyAgainWritesTheRemovedFileOnce() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 2); + var usb = await GeneralAsync(server); + await StartAndWaitAsync(server, new { accountId = marta.Account.Id }); + + // Alberto deletes one copy by hand; «Controlla le copie» finds it «Tolto» and touches no file. + var gone = Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).First(); + File.Delete(gone); + var kept = Fingerprint.Of(usb.Root); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{usb.Id}/check")).Status); + var removed = await WaitForAsync(async () => + { + var copies = await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Removed, 0, 10); + return copies.Count == 1 ? copies[0] : null; + }); + await WaitIdleAsync(server); + Fingerprint.AreEqual(kept, Fingerprint.Of(usb.Root), "«Controlla le copie» touches no file"); + + // The plan skips it by itself; the viewer offers «Copia di nuovo». + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(0, plan.Int("files")); + Assert.AreEqual(1, plan.Int("removedOrSuperseded")); + var entry = marta.Entries.Single(e => e.Media.Any(m => m.Id == removed.MediaId)); + var file = (await server.GetJsonAsync($"/api/entries/{entry.Entry.Id}")).Items("media").Single(m => m.Long("id") == removed.MediaId); + var copy = file.Items("copies").Single(); + Assert.AreEqual("removed", copy.Str("state")); + Assert.IsTrue(copy.Bool("canCopyAgain")); + Assert.AreEqual(removed.Id, copy.Long("copyId")); + + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + Assert.HasCount(1, job.Items("runIds").ToList()); + await WaitIdleAsync(server); + Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories)); + Assert.IsTrue(File.Exists(gone), "written again at its place"); + Assert.AreEqual(ExportCopyState.Removed, (await server.Db.Exports.GetCopyAsync(removed.Id))!.State, "the old row stays as history"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id })).Status, "already copied again"); + var notRemoved = (await server.Db.Exports.ListCopiesAsync(usb.Id, ExportCopyState.Copied, 0, 10)).First(); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = notRemoved.Id })).Status, "only a removed or superseded copy"); + } + + [TestMethod] + public async Task TheLibraryFilterTheMarksTheViewerAndTheCardAgree() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 3); + var pair = await AddPostAsync(server, marta.Account, "coppia", 40, 41); + + // No destination: no mark, no «Copie» filter offered, and every count is zero. + var days = await server.GetJsonAsync("/api/library/days"); + Assert.IsFalse(days.Bool("hasDestinations")); + Assert.IsTrue((await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").All(t => t.GetProperty("copies").ValueKind == JsonValueKind.Null)); + var card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsTrue(card.Bool("enabled"), "«Esporta questo account» is on when nothing is recorded"); + Assert.AreEqual(0, card.Int("due")); + Assert.AreEqual(JsonValueKind.Null, card.GetProperty("destination").ValueKind); + Assert.IsFalse((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Bool("canCopy")); + + // A destination and the copy of the first photos: one post copied, one in part. + var usb = await GeneralAsync(server); + await StartAndWaitAsync(server, new { mediaIds = new[] { marta.Entries[0].Media[0].Id, pair.Media[0].Id } }); + Assert.IsTrue((await server.GetJsonAsync("/api/library/days")).Bool("hasDestinations")); + var tiles = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").ToDictionary(t => t.Long("id")); + Assert.AreEqual("copied", tiles[marta.Entries[0].Entry.Id].Str("copies")); + Assert.AreEqual("partly", tiles[pair.Entry.Id].Str("copies")); + Assert.AreEqual(1, tiles[pair.Entry.Id].Int("copiesDone")); + Assert.AreEqual(2, tiles[pair.Entry.Id].Int("copiesDue")); + Assert.AreEqual(JsonValueKind.Null, tiles[marta.Entries[1].Entry.Id].GetProperty("copies").ValueKind); + + // The filter: grouped («Copiati» only when every due file is copied) and per file. + long[] Ids(JsonElement page) => [.. page.Items("tiles").Select(t => t.Long("id"))]; + CollectionAssert.AreEquivalent(new[] { marta.Entries[0].Entry.Id }, Ids(await server.GetJsonAsync("/api/library?copies=copied"))); + CollectionAssert.AreEquivalent( + new[] { marta.Entries[1].Entry.Id, marta.Entries[2].Entry.Id, pair.Entry.Id }, + Ids(await server.GetJsonAsync("/api/library?copies=notCopied"))); + Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=removedOrSuperseded"))); + Assert.HasCount(2, (await server.GetJsonAsync("/api/library?copies=copied&mode=files")).Items("tiles").ToList()); + Assert.AreEqual(3, (await server.GetJsonAsync("/api/library/days?copies=notCopied&mode=files")).Int("files")); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/library/days?copies=copied")).Int("entries")); + foreach (var bad in new[] { "tutti", "copied,notCopied", "1" }) + { + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/library?copies={bad}")).Status, bad); + } + + // The viewer: the copy of the file, and «Copia in…». + var entry = await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}"); + Assert.IsTrue(entry.Bool("canCopy")); + var media = entry.Items("media").ToDictionary(m => m.Long("id")); + var copy = media[pair.Media[0].Id].Items("copies").Single(); + Assert.AreEqual("copied", copy.Str("state")); + Assert.AreEqual("usb", copy.Str("destination")); + Assert.AreEqual("whole", copy.Str("variant")); + Assert.IsFalse(copy.Bool("canCopyAgain")); + Assert.IsFalse(copy.Bool("destinationRetired")); + Assert.IsEmpty(media[pair.Media[1].Id].Items("copies").ToList()); + + // The card counts what the filter finds; the switch off counts nothing and acts at once. + card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.AreEqual(5, card.Int("due")); + Assert.AreEqual(3, card.Int("notCopied")); + Assert.AreEqual(0, card.Int("removedOrSuperseded")); + Assert.AreEqual(usb.Id, card.GetProperty("destination").Long("id")); + var (offStatus, _) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = false }); + Assert.AreEqual(HttpStatusCode.OK, offStatus); + card = (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export"); + Assert.IsFalse(card.Bool("enabled")); + Assert.AreEqual(0, card.Int("due")); + Assert.AreEqual(0, card.Int("notCopied")); + Assert.IsEmpty(Ids(await server.GetJsonAsync("/api/library?copies=notCopied"))); + var off = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Account.Id })).Body; + Assert.AreEqual(0, off.Int("files")); + Assert.IsGreaterThan(0, off.Int("notExported"), "Q1: the switch off skips manual copies too"); + Assert.IsTrue((await server.GetJsonAsync($"/api/entries/{pair.Entry.Id}")).Items("media").Any(m => m.Items("copies").Any()), "the copies made stay visible"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Account.Id}/export-enabled", new { value = true })).Status); + Assert.AreEqual(3, (await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}")).GetProperty("export").Int("notCopied")); + } + + [TestMethod] + public async Task RebuildIsRefusedDuringAnExportAndTheCopyWaitsForTheEngineSession() + { + var session = new FakeSessionState { InSession = true }; + await using var server = await StartAsync(session: session, clock: new WaitingClock(new ManualClock(Make.T0))); + var marta = await AddPhotosAsync(server, "marta.demo", 2); + var usb = await GeneralAsync(server); + + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + var waiting = await WaitForAsync(async () => + { + var progress = await server.GetJsonAsync("/api/export/progress"); + return progress.Str("phase") == "waitingForSession" ? (JsonElement?)progress : null; + }); + Assert.IsTrue(waiting.GetValueOrDefault().Bool("running")); + Assert.IsEmpty(Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories), "no copy during an engine session"); + + var (rebuild, refusal) = await server.SendJsonAsync(HttpMethod.Post, "/api/settings/rebuild", new { confirm = "ricostruisci" }); + Assert.AreEqual(HttpStatusCode.BadRequest, rebuild); + Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.Rebuild, LongWorkKind.Export), refusal.Str("message")); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Account.Id })).Status, "one copy at a time"); + + session.InSession = false; + await WaitIdleAsync(server); + Assert.HasCount(2, Directory.GetFiles(usb.Root, "*", SearchOption.AllDirectories)); + Assert.IsNull(server.App.Services.GetRequiredService().Busy, "the long work is free again once the copy ended"); + } + + [TestMethod] + public async Task AnAccountFolderInsideADestinationIsRefused() + { + await using var server = await StartAsync(); + var marta = await AddPhotosAsync(server, "marta.demo", 1); + var usb = await GeneralAsync(server); + var detail = await server.GetJsonAsync($"/api/accounts/{marta.Account.Id}"); + var form = JsonSerializer.Deserialize>(detail.GetProperty("settings").GetRawText())! + .ToDictionary(k => k.Key, k => (object?)k.Value); + + form["folder"] = Path.Combine(usb.Root, "marta"); + var (status, error) = await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form); + Assert.AreEqual(HttpStatusCode.BadRequest, status); + StringAssert.Contains(error.Str("message"), "cartella di esportazione"); + Assert.IsNull((await server.Db.Accounts.GetAsync(marta.Account.Id))!.Folder, "nothing saved"); + + form["folder"] = server.Temp.Combine("altrove", "marta"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, $"/api/accounts/{marta.Account.Id}/settings", form)).Status); + Assert.IsNull((await server.Db.Exports.GetDestinationAsync(usb.Id))!.PausedAt); + } + + // ------------------------------------------------------------------------------------------------- support + + private const long Free = 500_000_000_000; + + private static ExportRootOptions Mounted(TempFolder esporta) => + ExportRootOptions.Docker(esporta.Path, declared: true, new FixedMounts(new ExportMount(esporta.Path, "/", "ext4", ReadOnly: false))); + + /// A web host of the Windows edition (any folder) or, with a root, the Docker one, with a disk of 500 GB. + private static Task StartAsync(ExportRootOptions? root = null, bool desktop = true, IEngineSessionState? session = null, IClock? clock = null) => + WebTestServer.StartAsync( + desktop ? new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None } : null, + s => + { + if (root is not null) + { + s.AddSingleton(root); + } + + s.AddSingleton(new FakeExportDisk(Free)); + if (session is not null) + { + s.AddSingleton(session); + } + + if (clock is not null) + { + s.AddSingleton(clock); + } + }); + + private static object Destination(string path, string scope = "general", long? accountId = null, string? label = null, string[]? types = null) => new + { + scope, + accountId, + path, + label, + types = types ?? ["postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo"], + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + }; + + /// The general folder «usb» in the temporary folder of the host. + private static async Task<(long Id, string Root)> GeneralAsync(WebTestServer server) + { + var root = server.Temp.Combine("usb"); + Directory.CreateDirectory(root); + var (status, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root)); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + return (saved.GetProperty("destination").Long("id"), root); + } + + private static async Task CheckAsync(WebTestServer server, string path) + { + var (status, answer) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/check-folder", new { path }); + Assert.AreEqual(HttpStatusCode.OK, status, $"{path}: {answer}"); + return answer; + } + + /// An account with posts of one real photo each, saved as the collection does. + private static async Task<(Account Account, List Entries, List Files)> AddPhotosAsync(WebTestServer server, string username, int count) + { + var account = await server.Db.Accounts.AddAsync(Make.Account(username)); + var entries = new List(); + for (var i = 0; i < count; i++) + { + entries.Add(await AddPostAsync(server, account, $"{username}-{i}", 10 + i)); + } + + var files = entries.SelectMany(e => e.Media).Select(m => Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(m.RelativePath!))).ToList(); + Assert.IsTrue(files.All(File.Exists)); + return (account, entries, files); + } + + private static async Task AddPostAsync(WebTestServer server, Account account, string code, params int[] scenes) + { + var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex()); + var added = await server.Db.Entries.AddAsync( + Make.Entry(account.Id, code, Make.T0.AddDays(-scenes[0])), + [.. scenes.Select((_, i) => Make.Photo(i + 1))]); + foreach (var (media, scene) in added.Stored.Media.Zip(scenes)) + { + await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(TestFile.PhotoBytes(scene, 96, 120)), Extension = ".jpg" }); + } + + await ingest.AppendJournalAsync(added.Stored.Entry.Id); + return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + } + + private static async Task StartAndWaitAsync(WebTestServer server, object request) + { + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", request); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + Assert.IsNotEmpty(job.Items("runIds").ToList(), job.ToString()); + await WaitIdleAsync(server); + } + + private static async Task WaitIdleAsync(WebTestServer server) + { + for (var i = 0; i < 600; i++) + { + if (!(await server.GetJsonAsync("/api/export/progress")).Bool("running")) + { + return; + } + + await Task.Delay(50); + } + + Assert.Fail("the copy did not end"); + } + + private static async Task WaitForAsync(Func> probe) + { + for (var i = 0; i < 600; i++) + { + if (await probe() is { } found) + { + return found; + } + + await Task.Delay(50); + } + + Assert.Fail("the expected state did not come"); + return default!; + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.cs new file mode 100644 index 0000000..fd7bc41 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.cs @@ -0,0 +1,279 @@ +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// The copies to external folders in a real browser, on the demo (spec §4.10, §10.3, tappa E2): Impostazioni → +/// Esportazione with the note of Docker, the dialog of a destination (folders of /esporta, the check of the folder, the +/// types, the preview of the names), the block «Copie esterne» of an account whose switch acts at once, «Copia in…» from +/// the selection with its summary and the toast that leads to the Dashboard, the «Copie» filter in the address with the +/// marks of the tiles and the menu of the CSV icon, the rows «Copia» of the viewer with «Copia di nuovo», and the +/// Dashboard tab «Esportazione». Chromium only (CI); the selectors follow the pages of WP3, checked on the demo. +/// +[TestClass] +public sealed class ExportInterfaceTests +{ + /// The demo copies its general folder to «Disco USB», under /esporta in the Docker look. + private const string General = "document.querySelector('.cartella-impostazioni .val')?.textContent || ''"; + + /// The «Copie» button of the tools row (the one whose label is a value of the filter). + private const string CopiesButton = "[...document.querySelectorAll('.strumenti .campo.scelta')].find((b) => /^(Copie|Copiati|Non ancora copiati|Tolti o superati)$/.test(b.textContent.trim()))"; + + /// Clicks the button (or menu item) of a scope whose text contains a given text. + private static string ClickText(string scope, string selector, string text) => + $"(() => {{ const b = [...document.querySelectorAll({Js(scope + " " + selector)})].find((x) => x.textContent.includes({Js(text)})); if (!b) return false; b.click(); return true; }})()"; + + /// The last open menu. + private const string LastMenu = "[...document.querySelectorAll('.menu[role=menu]')].pop()"; + + private static string Js(string text) => System.Text.Json.JsonSerializer.Serialize(text); + + [TestMethod] + public async Task TheExportSettingsPageShowsTheGeneralFolderAndTheDockerNote() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-impostazioni-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // Docker: the folders are under /esporta, and the page says so. + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker")); + await ui.WaitAsync($"({General}) !== ''", "la cartella generale " + ui.Report()); + Assert.AreEqual("/esporta/Disco USB", (await ui.EvalAsync(General)).GetString()); + var notes = (await ui.EvalAsync("[...document.querySelectorAll('.avviso')].map((a) => a.textContent).join(' | ')")).GetString()!; + StringAssert.Contains(notes, "sottocartelle di /esporta", "la nota di Docker"); + StringAssert.Contains(notes, "da riprendere", "il lavoro interrotto della demo"); + CollectionAssert.AreEqual( + new[] { "Esportazione", "Cartella generale", "Lo stesso post in due account", "Cartelle degli account" }, + (await ui.EvalAsync("[...document.querySelectorAll('.sezione h2')].map((x) => x.textContent)"))); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.stato-copie')?.textContent || ''")).GetString(), "copiati", "i conteggi della cartella"); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.stato-copie button')].some((b) => b.textContent.includes('Controlla le copie'))")).GetBoolean(), "«Controlla le copie»"); + StringAssert.Contains((await ui.EvalAsync("[...document.querySelectorAll('table tbody tr')].map((r) => r.textContent).join(' | ')")).GetString(), "@studio.lumen.demo", "la cartella sua di un account"); + + // Windows: the path of the folder, no note of Docker. + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + await ui.WaitAsync($"({General}).endsWith('Disco USB') && !({General}).startsWith('/esporta')", "la cartella generale in Windows"); + Assert.IsFalse((await ui.EvalAsync("[...document.querySelectorAll('.avviso')].some((a) => a.textContent.includes('sottocartelle di'))")).GetBoolean(), "nessuna nota di Docker"); + } + + [TestMethod] + public async Task TheDestinationDialogChecksTheFolderAndPreviewsNames() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-dialogo-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=docker")); + await ui.WaitAsync($"({General}) !== ''", "la cartella generale"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".cartella-impostazioni", "button", "Modifica"))).GetBoolean()); + const string Dialog = "document.querySelector('.dialogo.destinazione')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.sfoglia-voce') && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "il dialogo con le cartelle di /esporta e il controllo"); + CollectionAssert.IsSubsetOf( + new[] { "Chiavetta", "Disco USB", "Studio Lumen" }, + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.sfoglia-voce')].map((b) => b.textContent.trim())")); + Assert.AreEqual("Disco USB", (await ui.EvalAsync($"{Dialog}.querySelector('.sfoglia-voce[aria-pressed=true]').textContent.trim()")).GetString(), "la cartella di adesso è scelta"); + + // Another folder: the check follows it. + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.sfoglia-voce')].find((b) => b.textContent.trim() === 'Chiavetta').click()"); + await ui.WaitAsync($"{Dialog}.querySelector('.controllo-cartella').textContent.includes('/esporta/Chiavetta')", "il controllo della cartella scelta"); + + // «Uno schema suo»: the three schemes of the library to start from, and the tree follows what is typed. + await ui.EvalAsync($"{Dialog}.querySelector('input[value=suo]').click()"); + await ui.WaitAsync($"!{Dialog}.querySelector('.schemi-copie').hidden", "gli schemi"); + Assert.IsTrue((await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.schemi-copie input')].every((i) => i.value.includes('{{account}}'))")).GetBoolean(), "gli schemi partono da quelli della libreria"); + var before = (await ui.EvalAsync($"{Dialog}.querySelector('.albero').textContent")).GetString(); + await ui.EvalAsync($"(() => {{ const i = {Dialog}.querySelector('#schema-copie'); i.value = '{{account}}/{{anno}}/{{codice}}_{{n}}'; i.dispatchEvent(new Event('input', {{ bubbles: true }})); }})()"); + await ui.WaitAsync($"{Dialog}.querySelector('.albero').textContent !== {Js(before!)} && {Dialog}.querySelector('.albero').textContent.startsWith('Chiavetta')", "l'anteprima dei nomi nella cartella scelta"); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.albero').textContent")).GetString(), "marta.demo / 2026"); + + // No type: nothing to save. + await ui.EvalAsync($"{Dialog}.querySelectorAll('.tipi input:checked').forEach((i) => i.click())"); + await ui.WaitAsync($"!{Dialog}.querySelector('.errore-testo').hidden", "«Scegli almeno un tipo.»"); + Assert.IsTrue((await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent.includes('Salva')).disabled")).GetBoolean()); + + // «Annulla» keeps the folder of before. + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + Assert.AreEqual("/esporta/Disco USB", (await ui.EvalAsync(General)).GetString()); + } + + [TestMethod] + public async Task TheAccountBlockSwitchActsAtOnce() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-account-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/account")); + await ui.WaitAsync("document.querySelector('a[href^=\"/account/\"]') !== null", "elenco degli account"); + var id = (await ui.EvalAsync("fetch('/api/accounts').then((r) => r.json()).then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/account/{id}/impostazioni")); + const string Block = "document.querySelector('.copie-esterne')"; + await ui.WaitAsync($"{Block}?.querySelector('.conteggio-copie') != null", "il blocco «Copie esterne»"); + Assert.IsTrue((await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').checked")).GetBoolean(), "«Esporta questo account» acceso"); + StringAssert.Contains((await ui.EvalAsync($"{Block}.textContent")).GetString(), "Nella cartella generale"); + StringAssert.Contains((await ui.EvalAsync($"{Block}.querySelector('.conteggio-copie').textContent")).GetString(), "non ancora copiati"); + + // Off: at once, without «Salva», the server knows it and the block says what it means. + await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').click()"); + await ui.WaitAsync($"{Block}.textContent.includes('Questo account non si esporta')", "il blocco spento"); + await ui.WaitAsync($"fetch('/api/accounts/{id}').then((r) => r.json()).then((j) => j.export.enabled === false)", "spento sul server"); + await ui.WaitAsync("[...document.querySelectorAll('.brevi .breve')].some((b) => b.textContent.includes('non si copia più'))", "l'avviso breve"); + Assert.IsFalse((await ui.EvalAsync($"[...{Block}.querySelectorAll('button')].some((b) => b.textContent.includes('Copia in'))")).GetBoolean(), "niente «Copia in…» da spento"); + + // On again. + await ui.EvalAsync($"{Block}.querySelector('input[role=switch]').click()"); + await ui.WaitAsync($"{Block}.querySelector('.conteggio-copie')?.textContent.includes('non ancora copiati') && {Block}.querySelector('input[role=switch]').checked", "di nuovo acceso"); + await ui.WaitAsync($"fetch('/api/accounts/{id}').then((r) => r.json()).then((j) => j.export.enabled === true)", "acceso sul server"); + } + + [TestMethod] + public async Task CopyInFromTheSelectionShowsTheSummaryAndStarts() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-selezione-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // The three newest entries of the demo have four files still to copy. + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 3", "il mosaico"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); + await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].slice(0, 3).forEach((t) => t.click())"); + const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))"; + await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…» nella barra della scelta"); + await ui.EvalAsync($"({CopyIn}).click()"); + + const string Dialog = "document.querySelector('.dialogo.copia-in')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo"); + var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!; + StringAssert.StartsWith(summary, "4 file", summary); + StringAssert.Contains(summary, "circa", "lo spazio"); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.destinazioni-copia').textContent")).GetString(), "In Disco USB"); + Assert.AreEqual("Copia 4 file", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString()); + + await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + await ui.WaitAsync("document.querySelector('.brevi .breve a.breve-link') !== null", "l'avviso breve con il collegamento"); + Assert.AreEqual("/dashboard/esportazione", (await ui.EvalAsync("new URL(document.querySelector('.brevi .breve a.breve-link').href).pathname")).GetString()); + + // The job is in the Dashboard tab, finished: the demo copies at once. + await ui.EvalAsync("document.querySelector('.brevi .breve a.breve-link').click()"); + await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .elenco-attivita li') !== null", "la linguetta «Esportazione»"); + await ui.WaitAsync("document.querySelector('.esportazione-dashboard .elenco-attivita li').textContent.includes('4 di 4 file')", "il lavoro di 4 file " + ui.Report()); + } + + [TestMethod] + public async Task TheCopiesFilterIsRememberedInTheAddressAndTheTilesShowTheCopiedMark() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-filtro-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // «Copiati» from the address: the button says it, every tile has the mark. + await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=copiati")); + await ui.WaitAsync($"({CopiesButton}) && document.querySelectorAll('.mosaico .tess').length > 0", "la Libreria con «Copiati»"); + Assert.AreEqual("Copiati", (await ui.EvalAsync($"({CopiesButton}).textContent.trim()")).GetString()); + Assert.IsTrue((await ui.EvalAsync($"({CopiesButton}).classList.contains('attivo')")).GetBoolean()); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.mosaico .tess')].every((t) => t.querySelector('.segno span.copia:not(.parte)') !== null)")).GetBoolean(), "il segno «copiato» su ogni tessera " + ui.Report()); + Assert.AreEqual("copia", (await ui.EvalAsync("document.querySelector('.mosaico .tess .segno').lastElementChild.className")).GetString(), "il segno sta per ultimo"); + + // The menu of the filter: «Tolti o superati» goes to the address and stays after a reload. + await ui.EvalAsync($"({CopiesButton}).click()"); + await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitemradio]').length === 4", "il menu delle copie"); + CollectionAssert.AreEqual( + new[] { "Tutti", "Non ancora copiati", "Copiati", "Tolti o superati" }, + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].map((b) => b.textContent.trim())")); + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].find((b) => b.textContent.trim() === 'Tolti o superati').click()"); + await ui.WaitAsync("new URLSearchParams(location.search).get('copie') === 'tolti'", "«copie=tolti» nell'indirizzo"); + await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=tolti")); + await ui.WaitAsync($"({CopiesButton})?.textContent.trim() === 'Tolti o superati'", "il filtro dopo il ricaricamento"); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length > 0", "le tessere dei tolti o superati"); + + // The CSV icon is a menu: the list, and «Copia i file in…» of what the filter shows. + await ui.EvalAsync("document.querySelector('.strumenti button[aria-label=Esporta]').click()"); + await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitem]').length === 2", "il menu dell'icona CSV"); + CollectionAssert.AreEqual( + new[] { "Esporta l'elenco (CSV)", "Copia i file in…" }, + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitem]')].map((b) => b.textContent.trim())")); + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitem]')].find((b) => b.textContent.includes('Copia i file')).click()"); + await ui.WaitAsync("document.querySelector('.dialogo.copia-in .di-nuovo input') != null", "«Copia in…» del filtro, con «Copia di nuovo anche…»"); + Assert.IsFalse((await ui.EvalAsync("document.querySelector('.dialogo.copia-in .di-nuovo input').checked")).GetBoolean(), "«Copia di nuovo» spento"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.dialogo.copia-in .di-nuovo').textContent")).GetString(), "Copia di nuovo anche i"); + await ui.EvalAsync("[...document.querySelectorAll('.dialogo.copia-in footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.copia-in') === null", "il dialogo si chiude"); + + // «Tutti» takes the filter out of the address. + await ui.EvalAsync($"({CopiesButton}).click()"); + await ui.WaitAsync($"({LastMenu})?.querySelectorAll('[role=menuitemradio]').length === 4", "il menu delle copie"); + await ui.EvalAsync($"[...({LastMenu}).querySelectorAll('[role=menuitemradio]')].find((b) => b.textContent.trim() === 'Tutti').click()"); + await ui.WaitAsync("!new URLSearchParams(location.search).has('copie')", "nessun filtro nell'indirizzo"); + Assert.AreEqual("Copie", (await ui.EvalAsync($"({CopiesButton}).textContent.trim()")).GetString()); + } + + [TestMethod] + public async Task TheViewerShowsCopyRowsWithCopyAgain() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-visualizzatore-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // «Tutte le foto» with «Tolti o superati»: every tile is a file whose copy was removed or superseded. + await ui.OpenAsync(new Uri(demo.Address, "/libreria?copie=tolti")); + await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria con «Tolti o superati»"); + await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()"); + await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && document.querySelector('.mosaico .tess') !== null", "«Tutte le foto»"); + await ui.EvalAsync("document.querySelector('.mosaico .tess').click()"); + + await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "le righe «Copia» del visualizzatore " + ui.Report()); + var row = (await ui.EvalAsync("document.querySelector('.vis .riga-copia').textContent")).GetString()!; + Assert.IsTrue(row.StartsWith("Tolto da Disco USB", StringComparison.Ordinal) || row.StartsWith("Superato in Disco USB", StringComparison.Ordinal), row); + Assert.AreEqual("Copia", (await ui.EvalAsync("document.querySelector('.vis .riga-copia').previousElementSibling.textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.vis button')].some((b) => b.textContent.trim() === 'Copia in…')")).GetBoolean(), "«Copia in…» in fondo al pannello"); + + // «Copia di nuovo»: the job starts, with its toast, and the file is copied again (no longer «tolto o superato»). + const string Replaced = "fetch('/api/library?mode=files&copies=removedOrSuperseded&limit=1000').then((r) => r.json()).then((j) => j.tiles.length)"; + var before = (await ui.EvalAsync(Replaced)).GetInt32(); + Assert.IsGreaterThan(0, before); + await ui.EvalAsync("document.querySelector('.vis .riga-copia .copia-di-nuovo').click()"); + await ui.WaitAsync("document.querySelector('.brevi .breve a.breve-link') !== null", "l'avviso breve del lavoro"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.brevi .breve').textContent")).GetString(), "Copia avviata"); + await ui.WaitAsync($"({Replaced}).then((n) => n < {before})", "il file copiato di nuovo"); + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))"); + await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude"); + } + + [TestMethod] + public async Task TheDashboardExportTabShowsProgressAndResume() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-dashboard-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // The engine tab says there is a copy to resume and leads to the export tab. + await ui.OpenAsync(new Uri(demo.Address, "/dashboard")); + const string Notice = "[...document.querySelectorAll('.avviso')].find((a) => a.textContent.includes('da riprendere'))"; + await ui.WaitAsync($"({Notice}) !== undefined", "l'avviso della copia da riprendere"); + CollectionAssert.AreEqual(new[] { "Motore", "Esportazione" }, await ui.EvalAsync("[...document.querySelectorAll('.linguette-dashboard a')].map((a) => a.textContent)")); + await ui.EvalAsync($"({Notice}).querySelector('a').click()"); + + await ui.WaitAsync("location.pathname === '/dashboard/esportazione' && document.querySelector('.esportazione-dashboard .riga-riprendi') !== null", "la linguetta «Esportazione»"); + Assert.AreEqual("Esportazione", (await ui.EvalAsync("document.querySelector('.linguette-dashboard a.qui').textContent")).GetString()); + CollectionAssert.AreEqual(new[] { "In corso", "Da riprendere", "Ultimi lavori" }, await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard h2')].map((x) => x.textContent)")); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.copia-in-corso').textContent")).GetString(), "Nessuna copia al lavoro"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.riga-riprendi').textContent")).GetString(), "interrotta"); + + // «Resoconto» of the last job. + await ui.EvalAsync("[...document.querySelectorAll('.esportazione-dashboard .elenco-attivita li')][0].querySelector('button').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.resoconto-copia') !== null", "il resoconto"); + StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia h2').textContent")).GetString(), "Resoconto"); + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia').textContent")).GetString(), "Per account"); + await ui.EvalAsync("document.querySelector('.dialogo.resoconto-copia header button').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.resoconto-copia') === null", "il resoconto si chiude"); + + // «Riprendi»: the job goes on (the demo copies at once) and leaves «Da riprendere». + Assert.IsTrue((await ui.EvalAsync(ClickText(".riga-riprendi", "button", "Riprendi"))).GetBoolean()); + await ui.WaitAsync("[...document.querySelectorAll('.brevi .breve')].some((b) => b.textContent.includes('ripresa'))", "«Copia ripresa»"); + await ui.WaitAsync("document.querySelector('.esportazione-dashboard .riga-riprendi') === null", "niente più da riprendere " + ui.Report()); + } +}