From d197715fc73d972f2bf7c27568cc7e71ba522ff0 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Sat, 28 Nov 2026 11:48:27 +0100 Subject: [PATCH] E3: prove web, interfaccia, demo e scala di formati e fotogrammi MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le prove dell'API dei fotogrammi (anteprime, istanti, «Scarica» di un'immagine o di uno zip con nomi e date, limiti, il permesso dei lavori lunghi, i fotogrammi nella cartella delle copie, i controlli dell'Origin) e dei formati («Copia in…» con il suo formato, la conversione della libreria dalla domanda alla cancellazione). Le prove dell'interfaccia con Chromium: formati delle impostazioni e della cartella, la domanda «Solo i nuovi», «Cambia» in «Copia in…», «Fotogrammi…» dal visualizzatore e da una scelta, le righe delle copie e del file convertito. Ciò che le pagine devono dire si chiede all'API, perché la demo dispone i suoi elementi secondo l'ora. La prova di scala riempie anche copie convertite e fotogrammi, che il filtro «Copie» deve contare o ignorare come prima, entro i suoi tempi. Co-Authored-By: Claude Opus 5.5 --- tests/Febe.Tests/Data/LibraryScaleTests.cs | 60 +- tests/Febe.Tests/Web/DemoExportTests.cs | 76 +++ tests/Febe.Tests/Web/ExportFormatsApiTests.cs | 216 ++++++++ tests/Febe.Tests/Web/ExportFramesApiTests.cs | 521 ++++++++++++++++++ .../Web/ExportInterfaceTests.Formats.cs | 433 +++++++++++++++ tests/Febe.Tests/Web/ExportInterfaceTests.cs | 5 +- 6 files changed, 1292 insertions(+), 19 deletions(-) create mode 100644 tests/Febe.Tests/Web/ExportFramesApiTests.cs create mode 100644 tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs diff --git a/tests/Febe.Tests/Data/LibraryScaleTests.cs b/tests/Febe.Tests/Data/LibraryScaleTests.cs index 688b495..621b7e7 100644 --- a/tests/Febe.Tests/Data/LibraryScaleTests.cs +++ b/tests/Febe.Tests/Data/LibraryScaleTests.cs @@ -83,6 +83,9 @@ public sealed class LibraryScaleTests var copies = await FillCopiesAsync(db, temp, accountIds, ct); fill.Stop(); TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s"); + TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare"); + Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill"); + Assert.IsGreaterThan(0, copies.Frames, "frames in the fill"); // Plans differ with and without ANALYZE statistics: both must be fast. // The fill stays outside the timings. @@ -111,26 +114,46 @@ public sealed class LibraryScaleTests 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(); + int Insert(WriteContext w, string state, string source, string supersededBy, string which, Form? form = null) + { + var f = form ?? Form.Whole; + return w.Command( + $""" + INSERT INTO export_copy (destination_id, account_id, media_id, source_sha256, variant, format, frame_at_ms, state, superseded_by_sha256, + origin, relative_path, bytes, copy_sha256, copied_at) + SELECT {destination}, e.account_id, m.id, {source}, '{f.Variant}', {f.Format}, {f.FrameAt}, '{state}', {supersededBy}, + 'Written', 'p/' || m.id || '{f.Suffix}', 1000, {f.CopySha ?? source}, 1767225600000 + FROM media m JOIN entry e ON e.id = m.entry_id + WHERE {due} AND {which} + """).ExecuteNonQuery(); + } + + // Tappa E3: three in ten of the copied files are converted copies (PNG, or MP4 for a video), which count as + // copied; one video in fifty has a frame in its folder, copied or not, and one in a hundred a frame «Tolto»: + // frames never count in the «Copie» filter (D4), so the counts asserted stay those of the whole copies. + var converted = new Form("Converted", "(CASE m.kind WHEN 'Video' THEN 'Mp4' ELSE 'Png' END)", "NULL", ".c", "'c' || substr(m.sha256, 2)"); + var frame = new Form("Frame", "'Png'", "1000", "_t0m01s000.png", "'f' || substr(m.sha256, 2)"); 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"), + w => + { + var whole = Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0 AND {Spread} % 10 >= 3"); + var convertedCopies = Insert(w, "Copied", "m.sha256", "NULL", $"{Spread} % 3 = 0 AND {Spread} % 10 < 3", converted); + var removed = 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]), + var superseded = Insert(w, "Superseded", "'e' || substr(m.sha256, 2)", "m.sha256", $"{Spread} % 3 <> 0 AND {Spread} % 100 = 2"); + var frames = Insert(w, "Copied", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 50 = 7", frame) + + Insert(w, "Removed", "m.sha256", "NULL", $"m.kind = 'Video' AND {Spread} % 100 = 9", frame); + return new CopiesWorld(whole + convertedCopies, removed, superseded, DueFiles(), accountIds[OwnAccount], convertedCopies, frames); + }, ct); } + /// The form of the copies an insert writes: variant, format and instant (SQL), name suffix, copy SHA (SQL). + private sealed record Form(string Variant, string Format, string FrameAt, string Suffix, string? CopySha) + { + public static readonly Form Whole = new("Whole", "'Original'", "NULL", ".jpg", null); + } + /// 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 { @@ -285,6 +308,9 @@ public sealed class LibraryScaleTests 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); + /// + /// What the export fill wrote: copies by state ( with the converted ones), the due files, the + /// account with its own folder, and of tappa E3 the converted copies and the frames (copied and «Tolto»). + /// + private sealed record CopiesWorld(int Copied, int Removed, int Superseded, int Due, long OwnAccountId, int Converted, int Frames); } diff --git a/tests/Febe.Tests/Web/DemoExportTests.cs b/tests/Febe.Tests/Web/DemoExportTests.cs index 6575887..bde03e3 100644 --- a/tests/Febe.Tests/Web/DemoExportTests.cs +++ b/tests/Febe.Tests/Web/DemoExportTests.cs @@ -1,6 +1,9 @@ +using System.IO.Compression; using System.Net; using System.Security.Cryptography; +using System.Text; using System.Text.Json; +using System.Text.RegularExpressions; using Febe.Core.Domain; using Febe.Core.Library; using Febe.Tests.Support; @@ -211,4 +214,77 @@ public sealed class DemoExportTests Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(rowId, ct))!.State, "the demo never converts"); Assert.IsTrue(File.Exists(file)); } + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task TheDemoGivesFramesAndPlansTheFormats() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("demo-export-formati"); + 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) }; + var origin = demo.Address.GetLeftPart(UriPartial.Authority); + + async Task SendAsync(HttpMethod method, string path, string? json = null) + { + using var request = new HttpRequestMessage(method, path); + request.Headers.TryAddWithoutValidation("Origin", origin); + if (json is not null) + { + request.Content = new StringContent(json, Encoding.UTF8, "application/json"); + } + + using var response = await client.SendAsync(request, ct); + var text = await response.Content.ReadAsStringAsync(ct); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}"); + return JsonDocument.Parse(text).RootElement.Clone(); + } + + // Entries of @marta.demo with a video cover and with a photo cover (the demo places them by the hour: asked). + var marta = (await SendAsync(HttpMethod.Get, "/api/accounts")).Items("accounts").Single(a => a.Str("username") == "marta.demo").Long("id"); + var tiles = (await SendAsync(HttpMethod.Get, $"/api/library?accounts={marta}&limit=1000")).Items("tiles").ToList(); + var videos = tiles.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "video").Take(2).Select(t => t.Long("id")).ToList(); + var photos = tiles.Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "photo").Take(3).Select(t => t.Long("id")).ToList(); + Assert.HasCount(2, videos, "the demo has videos of marta.demo"); + Assert.IsNotEmpty(photos, "the demo has photos of marta.demo"); + + // «Fotogrammi…» of a selection: two in all of each video, the photos skipped, a zip named as the copies. + var selection = $"{{ \"entryIds\": [{string.Join(", ", videos.Concat(photos))}], \"frames\": {{ \"mode\": \"numero\", \"count\": 2, \"format\": \"png\" }} }}"; + var plan = await SendAsync(HttpMethod.Post, "/api/frames/plan", selection); + Assert.IsGreaterThanOrEqualTo(2, plan.Int("videos"), plan.ToString()); + Assert.IsGreaterThan(0, plan.Int("photosSkipped"), plan.ToString()); + Assert.AreEqual(0, plan.Int("notAvailable"), "every video of the demo gives frames"); + Assert.AreEqual(2 * plan.Int("videos"), plan.Int("frames")); + StringAssert.Contains(plan.Str("summary"), " si salt", plan.Str("summary")); + var token = await SendAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(plan.Int("frames"), token.Int("frames")); + using (var zip = await client.GetAsync(token.Str("url"), ct)) + { + Assert.AreEqual(HttpStatusCode.OK, zip.StatusCode); + using var archive = new ZipArchive(new MemoryStream(await zip.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read); + Assert.HasCount(plan.Int("frames"), archive.Entries); + foreach (var entry in archive.Entries) + { + StringAssert.StartsWith(entry.FullName, "marta.demo/", entry.FullName); + Assert.IsTrue(Regex.IsMatch(entry.FullName, @"_f00[12]\.png$"), entry.FullName); + using var read = entry.Open(); + var head = new byte[8]; + read.ReadExactly(head); + CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, head, entry.FullName); + } + } + + // «Copia in…» of photos not copied yet (a new format is for those): PNG converts the JPG photos of the demo, + // without loss; JPG copies them byte for byte. + var notCopied = (await SendAsync(HttpMethod.Get, $"/api/library?accounts={marta}&copies=notCopied&limit=1000")).Items("tiles") + .Where(t => t.GetProperty("cover").ValueKind == JsonValueKind.Object && t.GetProperty("cover").Str("kind") == "photo").Take(3).Select(t => t.Long("id")).ToList(); + Assert.IsNotEmpty(notCopied, "the demo has photos of marta.demo not copied yet"); + var photoIds = string.Join(", ", notCopied); + var png = await SendAsync(HttpMethod.Post, "/api/export/plan", $"{{ \"entryIds\": [{photoIds}], \"copyAgain\": false, \"photoFormat\": \"png\" }}"); + Assert.IsGreaterThan(0, png.Int("converted"), png.ToString()); + Assert.IsFalse(png.Bool("lossy"), png.ToString()); + var jpg = await SendAsync(HttpMethod.Post, "/api/export/plan", $"{{ \"entryIds\": [{photoIds}], \"copyAgain\": false, \"photoFormat\": \"jpg\" }}"); + Assert.AreEqual(0, jpg.Int("converted"), jpg.ToString()); + Assert.IsFalse(jpg.Bool("lossy"), "a JPG already JPG is copied as it is, never encoded again"); + } } diff --git a/tests/Febe.Tests/Web/ExportFormatsApiTests.cs b/tests/Febe.Tests/Web/ExportFormatsApiTests.cs index 47eeb19..7ec0bb0 100644 --- a/tests/Febe.Tests/Web/ExportFormatsApiTests.cs +++ b/tests/Febe.Tests/Web/ExportFormatsApiTests.cs @@ -1,14 +1,19 @@ using System.IO.Compression; using System.Net; using System.Text.Json; +using Febe.Core.Abstractions; using Febe.Core.Codecs.H264; using Febe.Core.Domain; using Febe.Core.Export; using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Core.Storage; +using Febe.Tests.Alerts.Support; using Febe.Tests.Export.Support; using Febe.Tests.Support; using Febe.Tests.Web.Support; using Febe.Web; +using Febe.Web.Library; using Microsoft.Extensions.DependencyInjection; namespace Febe.Tests.Web; @@ -161,8 +166,219 @@ public sealed class ExportFormatsApiTests Assert.AreEqual(HttpStatusCode.BadRequest, photoStatus); } + [TestMethod] + public async Task AFormatLeftToTheSettingsIsStoredAsNone() + { + await using var server = await StartAsync(); + var root = server.Temp.Combine("usb"); + Directory.CreateDirectory(root); + var (_, saved) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(root, photoFormat: "jpg", videoFormat: "mp4")); + var id = saved.GetProperty("destination").Long("id"); + Assert.AreEqual((ExportFormat?)ExportFormat.Mp4, (await server.Db.Exports.GetDestinationAsync(id))!.VideoFormat); + + // «Come le impostazioni generali» is no format of its own: it follows the settings when they change. + var (status, changed) = await server.SendJsonAsync(HttpMethod.Put, $"/api/export/destinations/{id}", Destination(root, photoFormat: "general", videoFormat: "general")); + Assert.AreEqual(HttpStatusCode.OK, status, changed.ToString()); + Assert.AreEqual(id, changed.GetProperty("destination").Long("id"), "the same folder: the same destination"); + var stored = await server.Db.Exports.GetDestinationAsync(id); + Assert.AreEqual(((ExportFormat?)null, (ExportFormat?)null), (stored!.PhotoFormat, stored.VideoFormat)); + Assert.AreEqual(JsonValueKind.Null, changed.GetProperty("destination").GetProperty("photoFormat").ValueKind); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task CopyInConvertsAsTheRequestAsksAndSaysWhatStaysAsItIs() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var jpg = await WebLibrary.AddPostAsync(server, marta, "foto-1", Make.T0.AddDays(-1), WebLibrary.Photo(1)); + await WebLibrary.AddPostAsync(server, marta, "foto-2", Make.T0.AddDays(-2), WebLibrary.Photo(2)); + var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-3), WebLibrary.Image(PngBytes(3), ".png")); + var heic = await WebLibrary.AddPostAsync(server, marta, "heic", Make.T0.AddDays(-4), WebLibrary.Image(Heic, ".heic")); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", Destination(usb)); + Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString()); + var destinationId = destination.GetProperty("destination").Long("id"); + + // The plan of each choice: JPG converts the PNG with loss and leaves the HEIC as it is; PNG converts the two JPGs + // without loss; «Originale» (the settings) copies everything as it is and says nothing about it. + async Task PlanAsync(string? photoFormat) => + (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Id, photoFormat })).Body; + var toJpg = await PlanAsync("jpg"); + Assert.AreEqual((4, 1, true), (toJpg.Int("files"), toJpg.Int("converted"), toJpg.Bool("lossy")), toJpg.ToString()); + Assert.AreEqual(("HEIC", 1), toJpg.Items("asIs").Select(a => (a.Str("label"), a.Int("files"))).Single()); + StringAssert.StartsWith(toJpg.Str("summary"), "4 file · circa 1 HEIC copiato com'è · circa "); + StringAssert.EndsWith(toJpg.Str("summary"), " · con perdita"); + var toPng = await PlanAsync("png"); + Assert.AreEqual((4, 2, false), (toPng.Int("files"), toPng.Int("converted"), toPng.Bool("lossy")), toPng.ToString()); + Assert.IsFalse(toPng.Str("summary").Contains("con perdita", StringComparison.Ordinal)); + var asTheyAre = await PlanAsync(null); + Assert.AreEqual((4, 0, false), (asTheyAre.Int("files"), asTheyAre.Int("converted"), asTheyAre.Bool("lossy")), asTheyAre.ToString()); + Assert.IsEmpty(asTheyAre.Items("asIs").ToList()); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { accountId = marta.Id, photoFormat = "mp4" })).Status); + + // Copied as PNG: the JPGs converted, the PNG and the HEIC byte for byte, the library untouched. + var library = Fingerprint.Of(server.Library.Layout.AccountFolder(marta)); + var (started, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", new { accountId = marta.Id, photoFormat = "png" }); + Assert.AreEqual(HttpStatusCode.OK, started, job.ToString()); + await WebLibrary.WaitIdleAsync(server); + Fingerprint.AreEqual(library, Fingerprint.Of(server.Library.Layout.AccountFolder(marta)), "the library is never touched"); + var written = Directory.GetFiles(usb, "*", SearchOption.AllDirectories).Select(f => Path.GetExtension(f)).Order(StringComparer.Ordinal).ToArray(); + CollectionAssert.AreEqual(new[] { ".heic", ".png", ".png", ".png" }, written); + CollectionAssert.AreEqual(PngBytes(3), await File.ReadAllBytesAsync(CopyPath(usb, png.Media[0], ".png"), ct), "PNG to PNG is a byte copy"); + CollectionAssert.AreEqual(Heic, await File.ReadAllBytesAsync(CopyPath(usb, heic.Media[0], ".heic"), ct), "HEIC is copied as it is"); + var converted = await File.ReadAllBytesAsync(CopyPath(usb, jpg.Media[0], ".png"), ct); + CollectionAssert.AreEqual(new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G' }, converted[..4]); + + // The report says what was copied as it is; the viewer says the form of each copy. + var report = await server.GetJsonAsync($"/api/export/runs/{job.Items("runIds").Single().GetInt64()}/report"); + Assert.AreEqual(1, report.Items("accounts").Single().GetProperty("asIs").Int("HEIC"), report.ToString()); + Assert.IsTrue(report.Items("notes").Any(n => n.Str("path")?.EndsWith(".heic", StringComparison.Ordinal) == true && n.Str("text").Length > 0), report.ToString()); + async Task FormAsync(EntryWithMedia post) => + (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single().Items("copies").Select(c => $"{c.Str("state")} {c.Str("variant")} {c.GetProperty("format")}").Single(); + Assert.AreEqual("copied converted png", await FormAsync(jpg)); + Assert.AreEqual("copied whole ", await FormAsync(png)); + Assert.AreEqual("copied whole ", await FormAsync(heic)); + + // Already copied in another form: a new format applies to the files not yet copied (D3, §16 domanda 28). + var again = await PlanAsync("jpg"); + Assert.AreEqual((0, 4, false), (again.Int("files"), again.Int("alreadyCopied"), again.Bool("lossy")), again.ToString()); + + // A converted copy removed from the folder: «Copia di nuovo» writes that same form, whatever the settings say. + File.Delete(CopyPath(usb, jpg.Media[0], ".png")); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{destinationId}/check")).Status); + await WebLibrary.WaitAsync(async () => (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Count == 1, "the copy «Tolto»"); + await WebLibrary.WaitIdleAsync(server); + var removed = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Single(); + Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png), (removed.Variant, removed.Format)); + var (copiedAgain, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = removed.Id }); + Assert.AreEqual(HttpStatusCode.OK, copiedAgain); + await WebLibrary.WaitIdleAsync(server); + CollectionAssert.AreEqual(converted, await File.ReadAllBytesAsync(CopyPath(usb, jpg.Media[0], ".png"), ct), "the same conversion at its place"); + Assert.IsFalse(File.Exists(CopyPath(usb, jpg.Media[0], ".jpg")), "not the whole file"); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task TheConversionOfTheLibraryAsksConvertsAndGoesWithTheFiles() + { + var ct = TestContext.CancellationToken; + await using var server = await WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => + { + s.AddSingleton(new FakeExportDisk(500_000_000_000)); + // The worker of the composition, with a disk far above the threshold; the test runs its passes. + s.AddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment + { + Storage = sp.GetRequiredService(), + Layout = () => sp.GetRequiredService().Layout, + Clock = sp.GetRequiredService(), + Gate = sp.GetRequiredService(), + Session = sp.GetRequiredService(), + FreeSpace = new FakeFreeSpaceProbe(), + })); + }); + var worker = server.App.Services.GetRequiredService(); + var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(5), ".png")); + var jpg = await WebLibrary.AddPostAsync(server, marta, "jpg", Make.T0.AddDays(-2), WebLibrary.Photo(6)); + + // The question: only the PNG would convert to JPG (a JPG is already one). + var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?photo=jpg"); + Assert.AreEqual((1, (long)PngBytes(5).Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString()); + Assert.IsNotEmpty(preview.Str("text")); + + // «Solo i nuovi»: nothing already in the library is queued; a new file is, after its line of the journal. + var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg" }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.AreEqual(0, saved.Int("queued")); + var conversion = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual((true, 0), (conversion.Bool("on"), conversion.Int("pending"))); + var later = await WebLibrary.AddPostAsync(server, marta, "nuova", Make.T0, WebLibrary.Image(PngBytes(7), ".png")); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion")).Int("pending"), "the new file waits for its conversion"); + + // Off: the queue empties; on with «Anche i N già in libreria»: both PNGs. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "original" })).Status); + conversion = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual((false, 0), (conversion.Bool("on"), conversion.Int("pending"))); + (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = true }); + Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString()); + Assert.AreEqual(2, saved.Int("queued")); + Assert.AreEqual(2, saved.GetProperty("overview").GetProperty("libraryConversion").Int("pending")); + + // «Interrompi» holds the queue; «Riprendi» lets it go. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/library-conversion/pause", new { })).Status); + Assert.IsTrue((await server.GetJsonAsync("/api/export/library-conversion")).Bool("paused")); + Assert.AreEqual(0, (await worker.RunOnceAsync(ct)).Converted, "paused: nothing converts"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/library-conversion/resume", new { })).Status); + Assert.IsFalse((await server.GetJsonAsync("/api/export/library-conversion")).Bool("paused")); + var library = Fingerprint.Of(server.Library.Layout.AccountFolder(marta)); + Assert.AreEqual(2, (await worker.RunOnceAsync(ct)).Converted); + conversion = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.AreEqual((0, 2, 0), (conversion.Int("pending"), conversion.Int("converted"), conversion.Int("failed")), conversion.ToString()); + Assert.AreEqual("Convertiti 2", conversion.Str("text")); + + // The converted file is added next to its original, which stays as it was (rule 11). + var original = WebLibrary.PathOf(server, marta, png.Media[0]); + var added = Path.ChangeExtension(original, ".jpg"); + Assert.IsTrue(File.Exists(added)); + var after = Fingerprint.Of(server.Library.Layout.AccountFolder(marta)); + Assert.AreEqual(library.Count + 2, after.Count, "two files added, none changed or taken away"); + foreach (var (path, sha) in library) + { + Assert.AreEqual(sha, after[path], path); + } + + // The viewer row, the file over the API, and «Mostra nella cartella» where there is no desktop. + var row = (await server.GetJsonAsync($"/api/entries/{png.Entry.Id}")).Items("media").Single().Items("conversions").Single(); + Assert.AreEqual(("jpg", "converted", true, Path.GetFileName(added)), (row.Str("format"), row.Str("state"), row.Bool("available"), row.Str("fileName"))); + Assert.AreEqual(new FileInfo(added).Length, row.Long("bytes")); + Assert.IsEmpty((await server.GetJsonAsync($"/api/entries/{jpg.Entry.Id}")).Items("media").Single().Items("conversions").ToList(), "a JPG has nothing to convert"); + using (var file = await server.Client.GetAsync($"/api/conversions/{row.Long("id")}/file?download=1", ct)) + { + Assert.AreEqual(HttpStatusCode.OK, file.StatusCode); + Assert.AreEqual("image/jpeg", file.Content.Headers.ContentType?.MediaType); + Assert.AreEqual(Path.GetFileName(added), file.Content.Headers.ContentDisposition?.FileNameStar ?? file.Content.Headers.ContentDisposition?.FileName?.Trim('"')); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(added, ct), await file.Content.ReadAsByteArrayAsync(ct)); + } + + Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/conversions/999999/file")).Status); + var (shown, shownBody) = await server.SendJsonAsync(HttpMethod.Post, "/api/conversions/show-in-folder", new { conversionId = row.Long("id") }); + Assert.AreEqual(HttpStatusCode.BadRequest, shown); + StringAssert.Contains(shownBody.Str("message"), "Scarica"); + + // «Elimina dalla libreria» counts the converted files that go with the entries. + var (previewStatus, deletion) = await server.SendJsonAsync(HttpMethod.Post, "/api/entries/delete-preview", new { ids = new[] { png.Entry.Id, jpg.Entry.Id } }); + Assert.AreEqual(HttpStatusCode.OK, previewStatus, deletion.ToString()); + Assert.AreEqual((2, 2, 1), (deletion.Int("entries"), deletion.Int("files"), deletion.Int("convertedFiles"))); + + // «Rimuovi» with the files: the converted files go too, and the message says how many. + var (removed, removal) = await server.SendJsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/remove", new { deleteFiles = true }); + Assert.AreEqual(HttpStatusCode.OK, removed, removal.ToString()); + Assert.AreEqual(2, removal.Int("convertedFiles")); + StringAssert.Contains(removal.Str("message"), "e 2 file convertiti"); + Assert.IsFalse(File.Exists(added)); + Assert.IsFalse(File.Exists(Path.ChangeExtension(WebLibrary.PathOf(server, marta, later.Media[0]), ".jpg"))); + } + // ------------------------------------------------------------------------------------------------- support + /// A HEIC as far as its name and brand go: Febe copies it as it is, it never decodes it. + private static readonly byte[] Heic = [0, 0, 0, 0x18, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, 0, 0, 0, 8, .. "free"u8, .. new byte[64]]; + + private static byte[] PngBytes(int scene) + { + using var image = TestImages.Scene(scene, 64, 48); + return TestImages.Png(image); + } + + /// Where the general folder «usb» has the copy of a file of marta.demo, with the extension of its form. + private static string CopyPath(string usb, Media media, string extension) => + Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(media.RelativePath!, extension))); + private static Task StartAsync() => WebTestServer.StartAsync( new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, diff --git a/tests/Febe.Tests/Web/ExportFramesApiTests.cs b/tests/Febe.Tests/Web/ExportFramesApiTests.cs new file mode 100644 index 0000000..4e76c57 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportFramesApiTests.cs @@ -0,0 +1,521 @@ +using System.IO.Compression; +using System.Net; +using System.Text.Json; +using Febe.Core.Abstractions; +using Febe.Core.Codecs.H264; +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 Febe.Web.Export; +using Microsoft.Extensions.DependencyInjection; + +namespace Febe.Tests.Web; + +/// +/// Frames over the API of a real web host (spec §4.10 «Fotogrammi», tappa E3, D12-D14), with videos built by the test: +/// the instants of each mode are the pictures shown, a video without frames says so everywhere, a preview past its +/// budget answers 503, «Scarica» gives one image or a zip (names, account folders, dates per the setting), the limits of +/// «Scarica» (20 at any time, 21-500 only outside engine sessions and other long work, more than 500 never), the lease of +/// a large zip held until it ends or the page goes away, and frames to the folder of the copies with their viewer rows, +/// mark and «Copia di nuovo». +/// +[TestClass] +public sealed class ExportFramesApiTests +{ + public TestContext TestContext { get; set; } = null!; + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheInstantsOfEachModeAreThePicturesShown() + { + await using var server = await StartAsync(); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo())); + var video = post.Media[0].Id; + + // The demo video shows a picture every 125 ms: «Questo istante» gives the one shown, past the end the last one. + var at = (await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=istante&at=1234")).Items("instants").Single(); + Assert.AreEqual((1234L, 1125L, "0:01,125", "_t0m01s125"), (at.Long("requestedMs"), at.Long("actualMs"), at.Str("label"), at.Str("suffix"))); + var past = (await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=istante&at=60000")).Items("instants").Single(); + Assert.AreEqual(1875L, past.Long("actualMs"), "past the end: the last picture"); + + // «Uno ogni k secondi» from 0:00; «N in tutto» centred in N equal parts (§16 domanda 33). + var every = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=ogni&every=500"); + Assert.AreEqual(4, every.Int("total")); + CollectionAssert.AreEqual(new long[] { 0, 500, 1000, 1500 }, every.Items("instants").Select(i => i.Long("actualMs")).ToArray()); + CollectionAssert.AreEqual(new[] { "_t0m00s000", "_t0m00s500", "_t0m01s000", "_t0m01s500" }, every.Items("instants").Select(i => i.Str("suffix")).ToArray()); + var count = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=numero&count=4"); + CollectionAssert.AreEqual(new long[] { 250, 750, 1250, 1750 }, count.Items("instants").Select(i => i.Long("requestedMs")).ToArray()); + CollectionAssert.AreEqual(new long[] { 250, 750, 1250, 1750 }, count.Items("instants").Select(i => i.Long("actualMs")).ToArray()); + CollectionAssert.AreEqual(new[] { "0:00,25", "0:00,75", "0:01,25", "0:01,75" }, count.Items("instants").Select(i => i.Str("label")).ToArray()); + + // A re-request at the actual instant gives the same picture (D12: ceil ms). + using (var first = await server.Client.GetAsync($"/api/media/{video}/frame?at=1234&format=png", TestContext.CancellationToken)) + using (var again = await server.Client.GetAsync($"/api/media/{video}/frame?at=1125&format=png", TestContext.CancellationToken)) + { + CollectionAssert.AreEqual(await first.Content.ReadAsByteArrayAsync(TestContext.CancellationToken), await again.Content.ReadAsByteArrayAsync(TestContext.CancellationToken)); + } + + // The limits (§16 domanda 38) and the words of the modes. + foreach (var wrong in new[] { "mode=ogni&every=50", "mode=numero&count=0", "mode=numero&count=1001", "mode=sempre", "mode=numero&count=3&format=gif" }) + { + var path = $"/api/media/{video}/frames/instants?{wrong}"; + if (wrong.Contains("format", StringComparison.Ordinal)) + { + path = $"/api/media/{video}/frame?at=0&format=gif"; + } + + var (status, body) = await server.SendJsonAsync(HttpMethod.Get, path); + Assert.AreEqual(HttpStatusCode.BadRequest, status, wrong); + Assert.IsNotEmpty(body.Str("message"), wrong); + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task AVideoWithoutFramesSaysSoEverywhere() + { + await using var server = await StartAsync(); + var noise = new byte[40_000]; + new Random(5).NextBytes(noise); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "rumore", Make.T0.AddDays(-1), WebLibrary.Video(noise)); + var video = post.Media[0].Id; + + var info = await server.GetJsonAsync($"/api/media/{video}/frames/info"); + Assert.IsFalse(info.Bool("available")); + Assert.IsNotEmpty(info.Str("unavailable")); + + var (frameStatus, frame) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video}/frame?at=0&max=160"); + Assert.AreEqual(HttpStatusCode.NotFound, frameStatus); + Assert.IsNotEmpty(frame.Str("message")); + var instants = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=numero&count=3"); + Assert.AreEqual(0, instants.Int("total")); + Assert.IsNotEmpty(instants.Str("problem")); + + // The viewer says «Fotogramma non disponibile» (WP4) from this flag. + var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single(); + Assert.IsFalse(shown.Bool("framesAvailable")); + + var selection = new { mediaIds = new[] { video }, frames = new { mode = "istante", atMs = 0, format = "png" } }; + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection)).Body; + Assert.AreEqual((1, 1, 0), (plan.Int("videos"), plan.Int("notAvailable"), plan.Int("frames")), plan.ToString()); + Assert.AreEqual(FrameService.NothingText, plan.Str("problem")); + StringAssert.Contains(plan.Str("summary"), "1 video senza fotogrammi"); + var (tokenStatus, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.BadRequest, tokenStatus); + Assert.AreEqual(FrameService.NothingText, token.Str("message")); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task APreviewPastItsBudgetSaysToUseTheFolderOfTheCopies() + { + await using var server = await WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => s.AddSingleton(sp => new FrameService(sp.GetRequiredService()) { Budget = TimeSpan.Zero })); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo())); + + var (status, body) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{post.Media[0].Id}/frame?at=0&max=160"); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, status); + Assert.AreEqual(FrameService.TimeoutText, body.Str("message")); + + // What the video allows is known without decoding a frame. + Assert.IsTrue((await server.GetJsonAsync($"/api/media/{post.Media[0].Id}/frames/info")).Bool("available")); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task ScaricaGivesOneImageOrAZipNamedAndDatedAsTheCopies() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var first = await WebLibrary.AddPostAsync(server, marta, "primo", Make.T0.AddDays(-3), WebLibrary.DemoVideo(2)); + var second = await WebLibrary.AddPostAsync(server, marta, "secondo", Make.T0.AddDays(-5), WebLibrary.DemoVideo(3), WebLibrary.Photo(4)); + + // One frame: the image itself, named by its actual instant, in the format chosen. + var one = new { mediaIds = new[] { first.Media[0].Id }, frames = new { mode = "istante", atMs = 1234, format = "jpg" } }; + var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", one); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + Assert.AreEqual(1, token.Int("frames")); + using (var image = await server.Client.GetAsync(token.Str("url"), ct)) + { + Assert.AreEqual(HttpStatusCode.OK, image.StatusCode); + Assert.AreEqual("image/jpeg", image.Content.Headers.ContentType?.MediaType); + Assert.AreEqual(Stem(first.Media[0]) + "_t0m01s125.jpg", FileName(image)); + var bytes = await image.Content.ReadAsByteArrayAsync(ct); + Assert.AreEqual((0xFF, 0xD8), (bytes[0], bytes[1])); + } + + // Two entries, grouped: their videos (the photo is skipped and said), three frames each, in one zip. + var both = new { entryIds = new[] { first.Entry.Id, second.Entry.Id }, frames = new { mode = "numero", count = 3, format = "png" } }; + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", both)).Body; + Assert.AreEqual((2, 1, 0, 6), (plan.Int("videos"), plan.Int("photosSkipped"), plan.Int("notAvailable"), plan.Int("frames")), plan.ToString()); + Assert.AreEqual("6 fotogrammi da 2 video · la foto si salta", plan.Str("summary")); + Assert.IsFalse(plan.Bool("needsQuiet")); + Assert.AreEqual(JsonValueKind.Null, plan.GetProperty("problem").ValueKind); + + var published = await ZipAsync(server, both); + Assert.AreEqual($"febe-fotogrammi-{LocalCalendar.Today(server.Clock.Now, server.Clock.LocalZone):yyyy-MM-dd}.zip", published.Name); + var expected = new[] { first, second } + .SelectMany(p => new[] { "_f001", "_f002", "_f003" }.Select(s => $"marta.demo/{Stem(p.Media[0])}{s}.png")) + .ToArray(); + CollectionAssert.AreEquivalent(expected, published.Entries.Keys.ToArray()); + // The time of publication of each entry, where Febe runs (D18; the zip keeps 2 s steps). + AssertNear(first.Entry.PublishedAt, published.Entries[expected[0]], server.Clock.LocalZone); + AssertNear(second.Entry.PublishedAt, published.Entries[expected[3]], server.Clock.LocalZone); + + // «Data del file = pubblicazione» off: the time of the download. + await server.Db.Settings.SetAsync(SettingKeys.SetFileTimeToPublication, "false", ct); + var now = await ZipAsync(server, both); + Assert.IsTrue(now.Entries.Values.All(time => Math.Abs((time - TimeZoneInfo.ConvertTime(server.Clock.Now, server.Clock.LocalZone).DateTime).TotalSeconds) <= 2), string.Join(", ", now.Entries.Values)); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task TheLimitsOfScaricaAreKept() + { + var session = new FakeSessionState(); + await using var server = await StartAsync(session); + var gate = server.App.Services.GetRequiredService(); + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo())); + object Selection(int n) => new { mediaIds = new[] { post.Media[0].Id }, frames = new { mode = "numero", count = n, format = "png" } }; + + // More than 500: never «Scarica» (the folder of the copies takes them); more than 1.000 a video: refused. + var many = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(501))).Body; + Assert.IsTrue(many.Bool("tooManyToDownload")); + Assert.AreEqual(FrameService.TooManyText, many.Str("problem")); + Assert.AreEqual((HttpStatusCode.BadRequest, FrameService.TooManyText), await TokenAsync(server, Selection(501))); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(1001))).Status); + + // From 21: only when it is quiet; up to 20 at any time. + var quiet = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body; + Assert.IsTrue(quiet.Bool("needsQuiet")); + Assert.AreEqual(JsonValueKind.Null, quiet.GetProperty("problem").ValueKind); + + session.InSession = true; + Assert.AreEqual(FrameService.SessionText, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.Str("problem")); + Assert.AreEqual(((HttpStatusCode)409, FrameService.SessionText), await TokenAsync(server, Selection(21))); + Assert.HasCount(16, (await ZipAsync(server, Selection(20))).Entries, "20 frames during a session: a zip of the 16 pictures of the video"); + + // A download asked outside a session and opened during one waits for it to end. + session.InSession = false; + var (_, ready) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", Selection(21)); + session.InSession = true; + var (late, lateBody) = await server.SendJsonAsync(HttpMethod.Get, ready.Str("url")); + Assert.AreEqual((HttpStatusCode)409, late); + Assert.AreEqual(FrameService.SessionText, lateBody.Str("message")); + session.InSession = false; + + // Another long work: 21 and more wait for it with its message, 20 do not. + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _)); + using (export) + { + var busy = LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Export); + Assert.AreEqual(busy, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.Str("problem")); + Assert.AreEqual(((HttpStatusCode)409, busy), await TokenAsync(server, Selection(21))); + Assert.HasCount(16, (await ZipAsync(server, Selection(20))).Entries); + } + + Assert.IsNull(gate.Busy, "no lease is left behind"); + } + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task AZipOfMoreThanTwentyHoldsItsLeaseUntilItEndsOrThePageGoes() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var gate = server.App.Services.GetRequiredService(); + // Big pictures of noise, so the zip (about 60 MB of PNG) cannot sit whole in the buffers of the connection: the + // server is still writing while the test looks. + var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "rumore", Make.T0.AddDays(-1), WebLibrary.Video(NoiseVideo(1280, 720, 24))); + var selection = new { mediaIds = new[] { post.Media[0].Id }, frames = new { mode = "numero", count = 22, format = "png" } }; + + // Read to the end: the lease is held while it is written, then let go. + var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + using (var response = await server.Client.GetAsync(token.Str("url"), HttpCompletionOption.ResponseHeadersRead, ct)) + { + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, gate.Busy); + Assert.IsFalse(gate.TryEnter(LongWorkKind.Import, out _, out var busyWith)); + Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, busyWith); + Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.FrameDownload), (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection)).Body.Str("problem")); + using var archive = new ZipArchive(new MemoryStream(await response.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read); + Assert.HasCount(22, archive.Entries); + } + + await WaitFreeAsync(gate, "after the whole zip"); + + // The page goes away halfway: the lease goes with it. + (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + var abandoned = await server.Client.GetAsync(token.Str("url"), HttpCompletionOption.ResponseHeadersRead, ct); + Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, gate.Busy); + var part = new byte[64 * 1024]; + await (await abandoned.Content.ReadAsStreamAsync(ct)).ReadAtLeastAsync(part, part.Length, throwOnEndOfStream: false, ct); + abandoned.Dispose(); + await WaitFreeAsync(gate, "after the page went away"); + Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _), "another long work can start"); + lease.Dispose(); + } + + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task FramesGoToTheFolderOfTheCopiesAndAreCopiedAgainOnRequest() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var post = await WebLibrary.AddPostAsync(server, marta, "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo()), WebLibrary.Photo(4)); + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", WebLibrary.Destination(usb)); + Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString()); + var destinationId = destination.GetProperty("destination").Long("id"); + + // Formats and frames are two different requests. + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { entryIds = new[] { post.Entry.Id }, photoFormat = "png", frames = new { mode = "istante", atMs = 1234 } })).Status); + + var request = new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "istante", atMs = 1234, format = "png" } }; + var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", request)).Body; + Assert.AreEqual((1, 1, 1), (plan.Int("videos"), plan.Int("photosSkipped"), plan.Int("frames")), plan.ToString()); + Assert.AreEqual("1 fotogramma da 1 video · la foto si salta", plan.Str("summary")); + Assert.IsFalse(plan.Bool("lossy")); + Assert.IsTrue((await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "istante", atMs = 1234, format = "jpg" } })).Body.Bool("lossy"), "a JPG frame is «con perdita»"); + + await WebLibrary.StartAndWaitAsync(server, request); + var frame = Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(post.Media[0].RelativePath!, null) + "_t0m01s125.png")); + Assert.IsTrue(File.Exists(frame), string.Join(", ", Directory.GetFiles(usb, "*", SearchOption.AllDirectories))); + Assert.HasCount(1, Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "only the frame: the video and the photo are not copied"); + + // The viewer row of the frame, and the mark of the entry: a frame does not make the file «Copiato». + var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").ToDictionary(m => m.Long("id")); + var row = shown[post.Media[0].Id].Items("copies").Single(); + Assert.AreEqual(("copied", "frame", "png", 1125L, "0:01,125"), (row.Str("state"), row.Str("variant"), row.Str("format"), row.Long("frameAtMs"), row.Str("frameLabel"))); + Assert.IsFalse(row.Bool("canCopyAgain")); + var tile = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").Single(t => t.Long("id") == post.Entry.Id); + Assert.AreEqual("frameOnly", tile.Str("copies"), tile.ToString()); + Assert.HasCount(1, (await server.GetJsonAsync("/api/library?copies=notCopied")).Items("tiles").ToList(), "still «Non ancora copiati»"); + + // Removed from the folder: «Controlla le copie» says «Tolto», «Copia di nuovo» writes the same frame again. + File.Delete(frame); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{destinationId}/check")).Status); + await WebLibrary.WaitAsync(async () => (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Count == 1, "the frame «Tolto»"); + await WebLibrary.WaitIdleAsync(server); + row = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single(m => m.Long("id") == post.Media[0].Id).Items("copies").Single(); + Assert.AreEqual("removed", row.Str("state")); + Assert.IsTrue(row.Bool("canCopyAgain")); + var (again, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = row.Long("copyId") }); + Assert.AreEqual(HttpStatusCode.OK, again, job.ToString()); + await WebLibrary.WaitIdleAsync(server); + Assert.IsTrue(File.Exists(frame), "the frame written again at its place"); + var copies = await server.Db.Exports.ListCopiesAsync(destinationId, null, 0, 10, ct); + Assert.AreEqual( + (ExportVariant.Frame, ExportFormat.Png, TimeSpan.FromMilliseconds(1125)), + copies.Where(c => c.State == ExportCopyState.Copied).Select(c => (c.Variant, c.Format, c.FrameAt!.Value)).Single(), + "the same form, not the whole video"); + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = row.Long("copyId") })).Status, "already copied again"); + } + + [TestMethod] + public async Task CommandsOfFramesAndConversionsComeOnlyFromFebesPages() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var frames = new { mediaIds = new[] { 1L }, frames = new { mode = "istante", atMs = 0 } }; + foreach (var (method, path, body) in new (HttpMethod, string, object)[] + { + (HttpMethod.Post, "/api/frames/plan", frames), + (HttpMethod.Post, "/api/frames/download-token", frames), + (HttpMethod.Post, "/api/conversions/show-in-folder", new { conversionId = 1 }), + (HttpMethod.Post, "/api/entries/delete-preview", new { ids = new[] { 1L } }), + (HttpMethod.Post, "/api/export/library-conversion/pause", new { }), + (HttpMethod.Post, "/api/export/library-conversion/resume", new { }), + (HttpMethod.Post, "/api/export/library-conversion/retry", new { }), + (HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = true }), + }) + { + using var request = server.Request(method, path, body, "http://altro.example"); + using var response = await server.Client.SendAsync(request, ct); + Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path); + } + + var status = await server.GetJsonAsync("/api/export/library-conversion"); + Assert.IsFalse(status.Bool("paused"), "nothing was done"); + Assert.IsFalse(status.Bool("on")); + } + + // ------------------------------------------------------------------------------------------------- support + + private static Task StartAsync(IEngineSessionState? session = null) => + WebTestServer.StartAsync( + new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None }, + s => + { + s.AddSingleton(new FakeExportDisk(500_000_000_000)); + if (session is not null) + { + s.AddSingleton(session); + } + }); + + private static Task AccountAsync(WebTestServer server) => server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + + private static string Stem(Media media) => Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(media.RelativePath!)); + + private static string? FileName(HttpResponseMessage response) => + response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName?.Trim('"'); + + private static void AssertNear(DateTimeOffset expected, DateTime actual, TimeZoneInfo zone) + { + var local = TimeZoneInfo.ConvertTime(expected, zone).DateTime; + Assert.IsLessThanOrEqualTo(2.0, Math.Abs((actual - local).TotalSeconds), $"{actual} vs {local}"); + } + + private static async Task<(HttpStatusCode Status, string Message)> TokenAsync(WebTestServer server, object selection) + { + var (status, body) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + return (status, body.ValueKind == JsonValueKind.Object && body.TryGetProperty("message", out var message) ? message.GetString() ?? string.Empty : string.Empty); + } + + /// «Scarica» of a selection that gives a zip: its name and its entries with their times. + private async Task<(string? Name, Dictionary Entries)> ZipAsync(WebTestServer server, object selection) + { + var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection); + Assert.AreEqual(HttpStatusCode.OK, status, token.ToString()); + using var response = await server.Client.GetAsync(token.Str("url"), TestContext.CancellationToken); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual("application/zip", response.Content.Headers.ContentType?.MediaType); + using var archive = new ZipArchive(new MemoryStream(await response.Content.ReadAsByteArrayAsync(TestContext.CancellationToken)), ZipArchiveMode.Read); + foreach (var entry in archive.Entries) + { + Assert.AreEqual(entry.Length, entry.CompressedLength, $"{entry.FullName}: stored, not compressed"); + } + + return (FileName(response), archive.Entries.ToDictionary(e => e.FullName, e => e.LastWriteTime.DateTime, StringComparer.Ordinal)); + } + + private static async Task WaitFreeAsync(LongWorkGate gate, string what) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + while (gate.Busy is not null) + { + if (watch.Elapsed > TimeSpan.FromSeconds(90)) + { + Assert.Fail($"the lease of the zip is still held {what}"); + } + + await Task.Delay(50); + } + } + + /// An I_PCM video of noise (it does not compress), 8 pictures per second. + private static byte[] NoiseVideo(int width, int height, int pictures) + { + var random = new Random(11); + using var output = new MemoryStream(); + H264PcmWriter.WriteMp4(output, width, height, pictures, 8, _ => + { + var p = new H264PcmPicture(width, height); + foreach (var plane in new[] { p.Y, p.Cb, p.Cr }) + { + random.NextBytes(plane); + for (var i = 0; i < plane.Length; i++) + { + plane[i] = (byte)(16 + (plane[i] % 220)); // no zero byte, as in the demo video + } + } + + return p; + }); + return output.ToArray(); + } +} + +/// Library files and folders of the copies for the web tests of tappa E3, saved as the collection does. +internal static class WebLibrary +{ + public sealed record Item(byte[] Bytes, string Extension, MediaKind Kind); + + public static Item Video(byte[] bytes) => new(bytes, ".mp4", MediaKind.Video); + + /// + /// The demo's video with its own creation date, so two of them are two files (the same bytes would be one file of the + /// library in two entries). + /// + public static Item DemoVideo(int day) + { + using var output = new MemoryStream(); + H264PcmWriter.WriteMp4(output, H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight, H264PcmWriter.DemoPictures, H264PcmWriter.DemoFps, H264PcmWriter.DemoPicture, new DateTimeOffset(2026, 1, day, 12, 0, 0, TimeSpan.Zero)); + return Video(output.ToArray()); + } + + public static Item Photo(int scene) => new(TestFile.PhotoBytes(scene, 96, 120), ".jpg", MediaKind.Photo); + + public static Item Image(byte[] bytes, string extension) => new(bytes, extension, MediaKind.Photo); + + /// A post of with its files on disk and its journal line. + public static async Task AddPostAsync(WebTestServer server, Account account, string code, DateTimeOffset published, params Item[] files) + { + 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, published), + [.. files.Select((f, i) => f.Kind == MediaKind.Video ? Make.Video(i + 1) : Make.Photo(i + 1))]); + foreach (var (media, file) in added.Stored.Media.Zip(files)) + { + await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension }); + } + + await ingest.AppendJournalAsync(added.Stored.Entry.Id); + return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + } + + /// The library file of a media of . + public static string PathOf(WebTestServer server, Account account, Media media) => + Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(media.RelativePath!)); + + public static object Destination(string path, string scope = "general", long? accountId = null, string? photoFormat = null, string? videoFormat = null) => new + { + scope, + accountId, + path, + label = (string?)null, + types = new[] { "postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo" }, + namingScheme = (string?)null, + highlightNamingScheme = (string?)null, + profileNamingScheme = (string?)null, + photoFormat, + videoFormat, + }; + + public 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); + } + + public static Task WaitIdleAsync(WebTestServer server) => + WaitAsync(async () => !(await server.GetJsonAsync("/api/export/progress")).Bool("running"), "the copy ends"); + + public static async Task WaitAsync(Func> condition, string what) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + while (!await condition()) + { + if (watch.Elapsed > TimeSpan.FromSeconds(60)) + { + Assert.Fail($"not reached: {what}"); + } + + await Task.Delay(50); + } + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs new file mode 100644 index 0000000..a2f95d7 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.Formats.cs @@ -0,0 +1,433 @@ +using System.Globalization; +using Febe.Core.Domain; +using Febe.Tests.Support; +using Febe.Tests.Web.Support; +using Febe.Web.Demo; + +namespace Febe.Tests.Web; + +/// +/// Tappa E3 in a real browser, on the demo (spec §4.10, §10.3): the formats of Impostazioni → Esportazione and of the +/// dialog of a folder («con perdita» under JPG), the question of the conversion of the library with «Solo i nuovi» first, +/// «Copia in…» with «Formato: come la destinazione · Cambia», «Fotogrammi…» from the viewer (opened at the player's +/// time, with its previews) and from a selection (the photos are skipped and the dialog says so), the copy rows of the +/// viewer with their form, the converted file of the library and the deletion that counts it. What the pages should say +/// is asked of the API, never assumed from how the demo is built (it places its entries by the hour, #72). +/// +public sealed partial class ExportInterfaceTests +{ + /// A GET of the API from the page, as JSON. + private static string Get(string path) => $"fetch({Js(path)}, {{ headers: {{ Accept: 'application/json' }} }}).then((r) => r.json())"; + + /// A POST of the API from the page (a command of Febe's own page), as JSON. + private static string Post(string path, string json) => + $"fetch({Js(path)}, {{ method: 'POST', headers: {{ 'Content-Type': 'application/json', Accept: 'application/json' }}, body: {Js(json)} }}).then((r) => r.json())"; + + /// The choice of one format (photo or video) inside a scope. + private static string FormatChoice(string scope, string kind) => $"document.querySelector({Js(scope + " .scelta-formato[data-tipo=" + kind + "]")})"; + + /// The value checked in a choice of format. + private static string Checked(string choice) => $"{choice}.querySelector('[role=radio][aria-checked=true]').dataset.value"; + + [TestMethod] + public async Task FormatsAreChosenInTheSettingsAndJpgSaysItLoses() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-formati-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await RecordNoticesAsync(ui); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + var photo = FormatChoice(".sezione-formati", "photo"); + var video = FormatChoice(".sezione-formati", "video"); + await ui.WaitAsync($"{photo} !== null && {video} !== null", "i formati delle copie " + ui.Report()); + CollectionAssert.AreEqual(new[] { "Originale", "JPG", "PNG", "WEBP senza perdita" }, await ui.EvalAsync($"[...{photo}.querySelectorAll('[role=radio]')].map((b) => b.textContent.trim())")); + CollectionAssert.AreEqual(new[] { "Originale", "MP4" }, await ui.EvalAsync($"[...{video}.querySelectorAll('[role=radio]')].map((b) => b.textContent.trim())")); + Assert.AreEqual("original", (await ui.EvalAsync(Checked(photo))).GetString()); + Assert.IsTrue((await ui.EvalAsync($"{photo}.querySelector('.nota-formato').hidden")).GetBoolean(), "«Originale» needs no note"); + + // JPG: saved at once, with the note of the loss; MP4 says it only remuxes. + await ui.EvalAsync($"{photo}.querySelector('[data-value=jpg]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.photoFormat === 'jpg')", "JPG sul server"); + Assert.IsFalse((await ui.EvalAsync($"{photo}.querySelector('.nota-formato').hidden")).GetBoolean()); + Assert.AreEqual("con perdita: qualità 92", (await ui.EvalAsync($"{photo}.querySelector('.nota-formato').textContent")).GetString()); + await ui.EvalAsync($"{video}.querySelector('[data-value=mp4]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.videoFormat === 'mp4')", "MP4 sul server"); + Assert.AreEqual("solo rimuxaggio, mai ricodifica", (await ui.EvalAsync($"{video}.querySelector('.nota-formato').textContent")).GetString()); + await ui.WaitAsync("window.__notices.length >= 2", "gli avvisi brevi del salvataggio"); + Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), (await ui.EvalAsync("JSON.stringify(window.__notices)")).GetString()); + + // The page drawn again shows what is saved; «Originale» again takes the note away. + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + await ui.WaitAsync($"{photo} !== null && {Checked(photo)} === 'jpg' && {Checked(video)} === 'mp4'", "i formati salvati dopo il ricaricamento"); + await ui.EvalAsync($"{photo}.querySelector('[data-value=original]').click()"); + await ui.EvalAsync($"{video}.querySelector('[data-value=original]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.photoFormat === 'original' && j.videoFormat === 'original')", "di nuovo «Originale»"); + Assert.IsTrue((await ui.EvalAsync($"{photo}.querySelector('.nota-formato').hidden && {video}.querySelector('.nota-formato').hidden")).GetBoolean()); + } + + [TestMethod] + public async Task TurningOnTheLibraryConversionAsksAboutTheFilesAlreadyThere() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-conversione-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + await RecordNoticesAsync(ui); + + await ui.OpenAsync(new Uri(demo.Address, "/impostazioni/esportazione?veste=desktop")); + var photo = FormatChoice(".sezione-conversione", "photo"); + await ui.WaitAsync($"{photo} !== null && document.querySelector('.stato-conversione .riga-conteggi') !== null", "la conversione della libreria " + ui.Report()); + var before = await ui.EvalAsync(Get("/api/export/library-conversion")); + Assert.IsFalse(before.GetProperty("on").GetBoolean()); + // The demo has its two rows («Convertito», «Non si converte») and never converts: the line says so. + StringAssert.Contains((await ui.EvalAsync("document.querySelector('.stato-conversione').textContent")).GetString(), before.GetProperty("text").GetString()); + + // PNG: the question, with the count and the space of the files already there, «Solo i nuovi» first and focused. + var preview = await ui.EvalAsync(Get("/api/export/library-conversion/preview?photo=png")); + var files = preview.GetProperty("files").GetInt32(); + Assert.IsGreaterThan(1, files, "the demo has photos that would convert to PNG"); + const string Question = "[...document.querySelectorAll('.dialogo.piccolo')].find((d) => d.querySelector('.spazio-conversione'))"; + await ui.EvalAsync($"{photo}.querySelector('[data-value=png]').click()"); + await ui.WaitAsync($"({Question}) !== undefined", "la domanda"); + Assert.AreEqual( + $"Convertire anche i {files.ToString("N0", CultureInfo.GetCultureInfo("it-IT"))} file già in libreria?", + (await ui.EvalAsync($"({Question}).querySelector('h2').textContent")).GetString()); + StringAssert.StartsWith((await ui.EvalAsync($"({Question}).querySelector('.spazio-conversione').textContent")).GetString(), "Gli originali occupano circa"); + CollectionAssert.AreEqual( + new[] { $"Anche i {files.ToString("N0", CultureInfo.GetCultureInfo("it-IT"))} già in libreria", "Solo i nuovi" }, + await ui.EvalAsync($"[...({Question}).querySelectorAll('footer button')].map((b) => b.textContent.trim())")); + Assert.IsTrue((await ui.EvalAsync($"({Question}).querySelector('footer .btn.primo').textContent === 'Solo i nuovi'")).GetBoolean(), "«Solo i nuovi» is the primary answer"); + + // Closed without an answer: nothing changes, and the control goes back. + await ui.EvalAsync($"({Question}).querySelector('header button').click()"); + await ui.WaitAsync($"({Question}) === undefined && {Checked(photo)} === 'original'", "la domanda chiusa, il controllo com'era"); + Assert.AreEqual("original", (await ui.EvalAsync(Get("/api/export"))).GetProperty("libraryPhotoFormat").GetString()); + + // «Solo i nuovi»: on, and nothing already in the library is queued. + await ui.EvalAsync($"{photo}.querySelector('[data-value=png]').click()"); + await ui.WaitAsync($"({Question}) !== undefined", "la domanda di nuovo"); + await ui.EvalAsync($"({Question}).querySelector('footer .btn.primo').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.libraryPhotoFormat === 'png' && j.libraryConversion.on)", "PNG sul server"); + var on = await ui.EvalAsync(Get("/api/export/library-conversion")); + Assert.AreEqual(before.GetProperty("pending").GetInt32(), on.GetProperty("pending").GetInt32(), "«Solo i nuovi» queues none of the files already there"); + await ui.WaitAsync($"document.querySelector('.stato-conversione').textContent.includes({Js(on.GetProperty("text").GetString()!)})", "la riga dello stato"); + + // «Interrompi» and «Riprendi». + Assert.IsTrue((await ui.EvalAsync(ClickText(".stato-conversione", "button", "Interrompi"))).GetBoolean(), "«Interrompi» while it is on"); + await ui.WaitAsync($"{Get("/api/export/library-conversion")}.then((j) => j.paused)", "interrotta sul server"); + await ui.WaitAsync("[...document.querySelectorAll('.stato-conversione button')].some((b) => b.textContent.includes('Riprendi'))", "«Riprendi»"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".stato-conversione", "button", "Riprendi"))).GetBoolean()); + await ui.WaitAsync($"{Get("/api/export/library-conversion")}.then((j) => !j.paused)", "ripresa sul server"); + + // Back to «Originale»: no question. + await ui.EvalAsync($"{photo}.querySelector('[data-value=original]').click()"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.libraryPhotoFormat === 'original' && !j.libraryConversion.on)", "spenta sul server"); + Assert.IsTrue((await ui.EvalAsync($"({Question}) === undefined")).GetBoolean(), "turning it off asks nothing"); + Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), (await ui.EvalAsync("JSON.stringify(window.__notices)")).GetString()); + } + + [TestMethod] + public async Task TheDestinationDialogHasItsFormats() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-dialogo-formati-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')"; + var photo = FormatChoice(".dialogo.destinazione .parte-formati", "photo"); + var video = FormatChoice(".dialogo.destinazione .parte-formati", "video"); + await ui.WaitAsync($"{photo} !== null && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "il dialogo con i formati"); + Assert.AreEqual("Formati", (await ui.EvalAsync($"{Dialog}.querySelector('.parte-formati h3').textContent")).GetString()); + CollectionAssert.AreEqual( + new[] { "Come le impostazioni generali", "Originale", "JPG", "PNG", "WEBP senza perdita" }, + await ui.EvalAsync($"[...{photo}.querySelectorAll('[role=radio]')].map((b) => b.textContent.trim())")); + Assert.AreEqual("general", (await ui.EvalAsync(Checked(photo))).GetString(), "a folder without formats of its own follows the settings"); + Assert.AreEqual("general", (await ui.EvalAsync(Checked(video))).GetString()); + + // JPG for the photos of this folder: the note, then «Salva» stores it. + await ui.EvalAsync($"{photo}.querySelector('[data-value=jpg]').click()"); + Assert.AreEqual("con perdita: qualità 92", (await ui.EvalAsync($"{photo}.querySelector('.nota-formato').textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync(ClickText(".dialogo.destinazione", "footer button", "Salva"))).GetBoolean()); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude " + ui.Report()); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.general.photoFormat === 'jpg' && j.general.videoFormat === null)", "il formato della cartella sul server"); + + // Open again: JPG is chosen; back to «Come le impostazioni generali». + Assert.IsTrue((await ui.EvalAsync(ClickText(".cartella-impostazioni", "button", "Modifica"))).GetBoolean()); + await ui.WaitAsync($"{photo} !== null && {Checked(photo)} === 'jpg' && /liberi/.test({Dialog}.querySelector('.controllo-cartella').textContent)", "JPG scelto alla riapertura"); + await ui.EvalAsync($"{photo}.querySelector('[data-value=general]').click()"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".dialogo.destinazione", "footer button", "Salva"))).GetBoolean()); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + await ui.WaitAsync($"{Get("/api/export")}.then((j) => j.general.photoFormat === null)", "di nuovo come le impostazioni generali"); + } + + [TestMethod] + public async Task CopyInChangesTheFormatAndTheSummaryFollowsThePlan() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-copia-formati-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico"); + var marta = (await ui.EvalAsync($"{Get("/api/accounts")}.then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?copie=non-copiati&account={marta}")); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 1 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico dei non ancora copiati"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); + var ids = (await ui.EvalAsync("(() => { const tiles = [...document.querySelectorAll('.mosaico .tess')].slice(0, 4); tiles.forEach((t) => t.click()); return JSON.stringify(tiles.map((t) => Number(t.dataset.id))); })()")).GetString()!; + const string CopyIn = "[...document.querySelectorAll('.salva button')].find((b) => b.textContent.includes('Copia in'))"; + await ui.WaitAsync($"({CopyIn}) && !({CopyIn}).disabled", "«Copia in…»"); + await ui.EvalAsync($"({CopyIn}).click()"); + + const string Dialog = "document.querySelector('.dialogo.copia-in')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-copia') != null", "il riepilogo"); + Assert.AreEqual("Formato: come la destinazione", (await ui.EvalAsync($"{Dialog}.querySelector('.riga-formato .testo-formato').textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.riga-formato .formati-copie').hidden")).GetBoolean(), "the controls open with «Cambia»"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".dialogo.copia-in .riga-formato", "button", "Cambia"))).GetBoolean()); + await ui.WaitAsync($"!{Dialog}.querySelector('.riga-formato .formati-copie').hidden", "i formati di questa copia"); + var photo = FormatChoice(".dialogo.copia-in .riga-formato", "photo"); + Assert.AreEqual("Come la destinazione", (await ui.EvalAsync($"{photo}.querySelector('[role=radio]').textContent.trim()")).GetString()); + Assert.AreEqual("destination", (await ui.EvalAsync(Checked(photo))).GetString()); + + // Each format asks the plan again: the summary and the button say what the plan of that format says. + foreach (var format in new[] { "png", "jpg" }) + { + await ui.EvalAsync($"{photo}.querySelector('[data-value={format}]').click()"); + var label = format == "png" ? "PNG" : "JPG"; + Assert.AreEqual($"Formato: foto {label} · video come la destinazione", (await ui.EvalAsync($"{Dialog}.querySelector('.riga-formato .testo-formato').textContent")).GetString()); + var plan = await ui.EvalAsync(Post("/api/export/plan", $"{{ \"entryIds\": {ids}, \"copyAgain\": false, \"photoFormat\": \"{format}\" }}")); + var files = plan.GetProperty("files").GetInt32(); + var lossy = plan.GetProperty("lossy").GetBoolean(); + await ui.WaitAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim() === {Js($"Copia {files} file")} && !{Dialog}.querySelector('footer .btn.primo').disabled", $"il pulsante del piano in {label}"); + var summary = (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()!; + StringAssert.StartsWith(summary, $"{files} file", summary); + Assert.AreEqual(lossy, summary.Contains("con perdita", StringComparison.Ordinal), $"{label}: {summary}"); + foreach (var asIs in plan.GetProperty("asIs").EnumerateArray().Where(a => a.GetProperty("files").GetInt32() > 0)) + { + StringAssert.Contains(summary, asIs.GetProperty("label").GetString(), summary); + } + } + + // JPG has its note of the loss here too; «Annulla» leaves nothing behind. + Assert.AreEqual("con perdita: qualità 92", (await ui.EvalAsync($"{photo}.querySelector('.nota-formato').textContent")).GetString()); + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + } + + [TestMethod] + public async Task TheFrameDialogOfTheViewerOpensAtThePlayerTimeAndPreviews() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-fotogramma-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + var video = (await DemoCopyAsync(demo, ExportVariant.Frame)).MediaId!.Value; + await OpenInViewerAsync(ui, demo, video, "docker"); + await ui.WaitAsync("document.querySelector('.vis .azione-fotogramma') !== null && document.querySelector('.vis video') !== null", "«Fotogramma» nel visualizzatore " + ui.Report()); + + // The player is at 1,3 s: the dialog opens there, the video waits. + await ui.EvalAsync("Object.defineProperty(document.querySelector('.vis video'), 'currentTime', { configurable: true, get: () => 1.3, set: () => {} })"); + await ui.EvalAsync("document.querySelector('.vis .azione-fotogramma').click()"); + const string Dialog = "document.querySelector('.dialogo.fotogrammi')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.dati-video') != null", "il dialogo «Fotogrammi»"); + Assert.AreEqual("Fotogrammi", (await ui.EvalAsync($"{Dialog}.querySelector('h2').textContent")).GetString()); + var info = await ui.EvalAsync(Get($"/api/media/{video}/frames/info")); + var data = (await ui.EvalAsync($"{Dialog}.querySelector('.dati-video').textContent")).GetString()!; + StringAssert.StartsWith(data, "Video di 0:0", data); + StringAssert.EndsWith(data, $", {info.GetProperty("width").GetInt32()} × {info.GetProperty("height").GetInt32()} pixel.", data); + Assert.AreEqual("0:01,3", (await ui.EvalAsync($"{Dialog}.querySelector('.campo-tempo input').value")).GetString()); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis video').paused")).GetBoolean(), "the video waits while the dialog is open"); + + // The preview of that instant, and the instant really shown (asked of the API). + var shown = (await ui.EvalAsync(Get($"/api/media/{video}/frames/instants?mode=istante&at=1300"))).GetProperty("instants")[0].GetProperty("label").GetString(); + await ui.WaitAsync($"{Dialog}.querySelector('.istante-mostrato').textContent === {Js($"Fotogramma a {shown}")}", "l'istante mostrato"); + await ui.WaitAsync($"(() => {{ const i = {Dialog}.querySelector('.anteprima-fotogramma img'); return i && i.complete && i.naturalWidth > 0; }})()", "l'anteprima " + ui.Report()); + Assert.IsTrue((await ui.EvalAsync($"Math.max({Dialog}.querySelector('.anteprima-fotogramma img').naturalWidth, {Dialog}.querySelector('.anteprima-fotogramma img').naturalHeight) <= 480")).GetBoolean(), "a preview is at most 480 pixels"); + Assert.AreEqual("Il fotogramma non ha l'audio.", (await ui.EvalAsync($"{Dialog}.querySelector('.nota-audio').textContent.trim()")).GetString()); + + // Above the viewer (its own layer): the middle of the dialog is the dialog. + Assert.IsTrue((await ui.EvalAsync($"(() => {{ const r = {Dialog}.getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return e !== null && e.closest('.dialogo.fotogrammi') !== null; }})()")).GetBoolean(), "the dialog is above the viewer"); + + // «N in tutto» with 8: the strip shows the first 6 at the instants of the API, and «e altri 2». + await ui.EvalAsync($"{Dialog}.querySelector('.modo-fotogrammi').previousElementSibling.querySelector('[data-value=numero]').click()"); + await ui.EvalAsync($"(() => {{ const i = {Dialog}.querySelector('input[type=number]'); i.value = '8'; i.dispatchEvent(new Event('input', {{ bubbles: true }})); }})()"); + var labels = (await ui.EvalAsync(Get($"/api/media/{video}/frames/instants?mode=numero&count=8"))).GetProperty("instants").EnumerateArray().Take(6).Select(i => i.GetProperty("label").GetString()!).ToArray(); + await ui.WaitAsync($"{Dialog}.querySelector('.altri-fotogrammi')?.textContent === 'e altri 2'", "la striscia con «e altri 2»"); + CollectionAssert.AreEqual(labels, await ui.EvalAsync($"[...{Dialog}.querySelectorAll('.striscia-fotogrammi figcaption')].map((c) => c.textContent)")); + + // JPG says it loses; the summary of «Scarica» is the one of the API. + Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').hidden")).GetBoolean(), "PNG is the default, without loss"); + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('[role=radio][data-value=jpg]')].pop().click()"); + Assert.IsFalse((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').hidden")).GetBoolean()); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').textContent")).GetString(), "con perdita: qualità 92"); + var plan = await ui.EvalAsync(Post("/api/frames/plan", $"{{ \"mediaIds\": [{video}], \"frames\": {{ \"mode\": \"numero\", \"count\": 8, \"format\": \"jpg\" }} }}")); + var frames = plan.GetProperty("frames").GetInt32(); + await ui.WaitAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia')?.textContent === {Js(plan.GetProperty("summary").GetString()!)}", "il riepilogo di «Scarica»"); + await ui.WaitAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim() === {Js($"Scarica {frames} fotogrammi")} && !{Dialog}.querySelector('footer .btn.primo').disabled", "il pulsante «Scarica»"); + + // «Nella cartella delle copie»: the plan of the copies, and the button says «Copia». + await ui.EvalAsync($"{Dialog}.querySelector('input[type=radio][value=cartella]').click()"); + var copies = await ui.EvalAsync(Post("/api/export/plan", $"{{ \"mediaIds\": [{video}], \"frames\": {{ \"mode\": \"numero\", \"count\": 8, \"format\": \"jpg\" }} }}")); + await ui.WaitAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia')?.textContent.startsWith({Js(copies.GetProperty("summary").GetString()!)})", "il riepilogo della cartella delle copie"); + await ui.WaitAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim() === {Js($"Copia {copies.GetProperty("frames").GetInt32()} fotogrammi")}", "il pulsante «Copia»"); + + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null && document.querySelector('.vis') !== null", "il dialogo si chiude, il visualizzatore resta"); + } + + [TestMethod] + public async Task TheFrameDialogOfASelectionSkipsThePhotos() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-fotogrammi-scelta-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + await ui.OpenAsync(new Uri(demo.Address, "/libreria")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico"); + var marta = (await ui.EvalAsync($"{Get("/api/accounts")}.then((j) => j.accounts.find((a) => a.username === 'marta.demo').id)")).GetInt64(); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?account={marta}")); + await ui.WaitAsync("document.querySelectorAll('.mosaico .tess').length >= 4 && [...document.querySelectorAll('.mosaico .tess')].every((t) => t.dataset.id)", "il mosaico di marta.demo"); + Assert.IsTrue((await ui.EvalAsync(ClickText(".strumenti", ".btn", "Seleziona"))).GetBoolean()); + + // Two entries with a video and two with photos only, among the tiles on screen (their kinds asked of the API). + var ids = (await ui.EvalAsync( + $"(async () => {{ const j = await ({Get($"/api/library?accounts={marta}&limit=1000")}); const kinds = new Map(j.tiles.map((t) => [t.id, t.cover && t.cover.kind])); " + + "const tiles = [...document.querySelectorAll('.mosaico .tess')]; const videos = tiles.filter((t) => kinds.get(Number(t.dataset.id)) === 'video').slice(0, 2); " + + "const photos = tiles.filter((t) => kinds.get(Number(t.dataset.id)) === 'photo').slice(0, 2); const chosen = [...videos, ...photos]; " + + "chosen.forEach((t) => t.click()); return JSON.stringify(chosen.map((t) => Number(t.dataset.id))); })()")).GetString()!; + var plan = await ui.EvalAsync(Post("/api/frames/plan", $"{{ \"entryIds\": {ids}, \"frames\": {{ \"mode\": \"istante\", \"atMs\": 0, \"format\": \"png\" }} }}")); + Assert.IsGreaterThan(0, plan.GetProperty("photosSkipped").GetInt32(), $"{ids}: {plan}"); + Assert.IsGreaterThan(0, plan.GetProperty("videos").GetInt32(), $"{ids}: {plan}"); + + const string Frames = "document.querySelector('.salva .fotogrammi-selezione')"; + await ui.WaitAsync($"{Frames} && !{Frames}.disabled", "«Fotogrammi…» nella barra della scelta"); + Assert.AreEqual("Fotogrammi…", (await ui.EvalAsync($"{Frames}.textContent.trim()")).GetString()); + await ui.EvalAsync($"{Frames}.click()"); + const string Dialog = "document.querySelector('.dialogo.fotogrammi')"; + await ui.WaitAsync($"{Dialog}?.querySelector('.riepilogo-fotogrammi .riepilogo-copia') != null", "il dialogo della scelta " + ui.Report()); + Assert.AreEqual("Fotogrammi dei video scelti", (await ui.EvalAsync($"{Dialog}.querySelector('h2').textContent")).GetString()); + Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.anteprima-fotogramma') === null")).GetBoolean(), "no preview: there is no single video"); + StringAssert.Contains((await ui.EvalAsync($"{Dialog}.querySelector('.modo-fotogrammi').textContent")).GetString(), "Lo stesso istante in ogni video"); + await ui.WaitAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia').textContent === {Js(plan.GetProperty("summary").GetString()!)}", "il riepilogo dell'API"); + StringAssert.Contains(plan.GetProperty("summary").GetString(), "si salt", "the summary says the photos are skipped"); + await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); + + // The account tab has «Fotogrammi…» in its selection bar too. + await ui.OpenAsync(new Uri(demo.Address, $"/account/{marta}")); + await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null && [...document.querySelectorAll('.btn')].some((b) => b.textContent.includes('Seleziona'))", "i contenuti dell'account"); + await ui.EvalAsync("[...document.querySelectorAll('.btn')].find((b) => b.textContent.includes('Seleziona')).click()"); + await ui.EvalAsync("document.querySelector('.mosaico .tess').click()"); + await ui.WaitAsync($"{Frames} && !{Frames}.disabled", "«Fotogrammi…» nella scheda dell'account"); + } + + [TestMethod] + public async Task TheViewerSaysTheFormOfEachCopyAndShowsTheConvertedFile() + { + await using var ui = await UiBrowser.StartAsync(1440, 900); + using var temp = new TempFolder("esporta-righe-ui"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); + + // The frame of a video: «· fotogramma a 0:01,125 · PNG». + var frame = await DemoCopyAsync(demo, ExportVariant.Frame); + await OpenInViewerAsync(ui, demo, frame.MediaId!.Value, "docker"); + await ui.WaitAsync("[...document.querySelectorAll('.vis .riga-copia')].some((r) => r.textContent.includes('fotogramma'))", "la riga del fotogramma " + ui.Report()); + var rows = await ui.EvalAsync("[...document.querySelectorAll('.vis .riga-copia')].map((r) => r.querySelector('span').textContent)"); + Assert.IsTrue(rows.Any(r => r.StartsWith("Copiato in Disco USB il ", StringComparison.Ordinal) && r.EndsWith(" · fotogramma a 0:01,125 · PNG", StringComparison.Ordinal)), string.Join(" | ", rows)); + await CloseViewerAsync(ui); + + // A copy converted to PNG: «· PNG»; a whole one: «· intero». + var converted = await DemoCopyAsync(demo, ExportVariant.Converted); + await OpenInViewerAsync(ui, demo, converted.MediaId!.Value, "docker"); + await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "la riga della copia convertita"); + rows = await ui.EvalAsync("[...document.querySelectorAll('.vis .riga-copia')].map((r) => r.querySelector('span').textContent)"); + Assert.IsTrue(rows.Any(r => r.StartsWith("Copiato in Disco USB il ", StringComparison.Ordinal) && r.EndsWith(" · PNG", StringComparison.Ordinal)), string.Join(" | ", rows)); + await CloseViewerAsync(ui); + var whole = await DemoCopyAsync(demo, ExportVariant.Whole); + await OpenInViewerAsync(ui, demo, whole.MediaId!.Value, "docker"); + await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "la riga della copia intera"); + rows = await ui.EvalAsync("[...document.querySelectorAll('.vis .riga-copia')].map((r) => r.querySelector('span').textContent)"); + Assert.IsTrue(rows.Any(r => r.StartsWith("Copiato in Disco USB il ", StringComparison.Ordinal) && r.EndsWith(" · intero", StringComparison.Ordinal)), string.Join(" | ", rows)); + await CloseViewerAsync(ui); + + // The converted file of the library next to its original, with «Scarica» in Docker; the deletion counts it. + var conversionId = demo.World.ConversionFiles.Single().Key; + var conversion = await demo.Storage.Conversions.GetAsync(conversionId); + await OpenInViewerAsync(ui, demo, conversion!.MediaId, "docker"); + await ui.WaitAsync("document.querySelector('.vis .riga-conversione') !== null", "la riga del file convertito " + ui.Report()); + StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.vis .riga-conversione span').textContent")).GetString(), "Convertito in PNG · "); + Assert.AreEqual($"/api/conversions/{conversionId}/file", (await ui.EvalAsync("new URL(document.querySelector('.vis .riga-conversione a').href).pathname")).GetString()); + Assert.AreEqual("Scarica", (await ui.EvalAsync("document.querySelector('.vis .riga-conversione a').textContent.trim()")).GetString()); + Assert.AreEqual("Convertito", (await ui.EvalAsync("document.querySelector('.vis .riga-conversione').previousElementSibling.textContent")).GetString()); + + Assert.IsTrue((await ui.EvalAsync("(() => { const b = [...document.querySelectorAll('.vis button')].find((x) => x.textContent.includes('Elimina dalla libreria')); if (!b) return false; b.click(); return true; })()")).GetBoolean()); + const string Confirm = "[...document.querySelectorAll('.dialogo.piccolo')].pop()"; + // One file of an entry of several says the whole entry goes, converted file included; otherwise its own line. + await ui.WaitAsync($"({Confirm})?.querySelector('.contenuto').textContent.includes('1 file convertito')", "la conferma conta il file convertito " + ui.Report()); + if ((await ui.EvalAsync($"({Confirm}).querySelector('.conta-convertiti') !== null")).GetBoolean()) + { + Assert.AreEqual( + "Si cancella anche 1 file convertito della libreria, fatto da questi file.", + (await ui.EvalAsync($"({Confirm}).querySelector('.conta-convertiti').textContent")).GetString()); + } + else + { + StringAssert.Contains((await ui.EvalAsync($"({Confirm}).querySelector('.contenuto').textContent")).GetString(), "e 1 file convertito."); + } + await ui.EvalAsync($"[...({Confirm}).querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); + await ui.WaitAsync("document.querySelector('.dialogo.piccolo') === null && document.querySelector('.vis') !== null", "annullato: nulla si cancella"); + Assert.AreEqual(MediaConversionState.Converted, (await demo.Storage.Conversions.GetAsync(conversionId))!.State); + } + + // ------------------------------------------------------------------------------------------------- support + + /// A copy «Copiato» of the demo of a form (of @marta.demo, in its general folder). + private static async Task DemoCopyAsync(DemoHost demo, ExportVariant variant) + { + foreach (var destination in await demo.Storage.Exports.ListDestinationsAsync(includeRetired: false)) + { + var found = (await demo.Storage.Exports.ListCopiesAsync(destination.Id, ExportCopyState.Copied, 0, 100_000)) + .Where(c => c.Variant == variant && c.MediaId is not null) + .OrderBy(c => c.Id) + .ToList(); + foreach (var copy in found) + { + // A file on disk, whose kind is the one of the form (the demo shares a picture's bytes with a video). + var media = await demo.Storage.Media.GetAsync(copy.MediaId!.Value); + if (media is { RelativePath: not null } && EntryStateRules.IsPresent(media.State) && (variant != ExportVariant.Whole || media.Kind == MediaKind.Photo)) + { + return copy; + } + } + } + + Assert.Fail($"the demo has no copy {variant}"); + return null!; + } + + /// + /// Opens the viewer on one file: the Libreria of its account on its day, «Tutte le foto», its tile (the mosaic shows a + /// window of tiles, so a file far down would not be on screen in the whole library). + /// + private static async Task OpenInViewerAsync(UiBrowser ui, DemoHost demo, long mediaId, string look) + { + var media = await demo.Storage.Media.GetAsync(mediaId); + var entry = await demo.Storage.Entries.GetAsync(media!.EntryId); + var day = LocalCalendar.Today(entry!.PublishedAt, demo.World.Zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + await ui.OpenAsync(new Uri(demo.Address, $"/libreria?account={entry.AccountId}&dal={day}&al={day}&veste={look}")); + await ui.WaitAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]') !== null && document.querySelector('.mosaico .tess') !== null", "la Libreria del giorno " + ui.Report()); + await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()"); + var tile = $"document.querySelector('.mosaico .tess[data-id=\"{mediaId}\"]')"; + await ui.WaitAsync($"document.querySelector('.strumenti .modo-mosaico [aria-checked=true]').dataset.value === 'files' && {tile} !== null", "la tessera del file " + ui.Report()); + await ui.EvalAsync($"{tile}.click()"); + await ui.WaitAsync("document.querySelector('.vis .scheda') !== null", "il visualizzatore"); + } + + private static async Task CloseViewerAsync(UiBrowser ui) + { + await ui.EvalAsync("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))"); + await ui.WaitAsync("document.querySelector('.vis') === null", "Esc chiude il visualizzatore"); + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.cs index 210356c..275c659 100644 --- a/tests/Febe.Tests/Web/ExportInterfaceTests.cs +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.cs @@ -10,10 +10,11 @@ namespace Febe.Tests.Web; /// 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. +/// Dashboard tab «Esportazione». Chromium only (CI); the selectors follow the pages of WP3, checked on the demo. Tappa +/// E3 (formats, frames, the conversion of the library) is in ExportInterfaceTests.Formats.cs. /// [TestClass] -public sealed class ExportInterfaceTests +public sealed partial 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 || ''";