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"); } }