using System.Globalization; using System.Text.Json; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Library; using Febe.Core.Library.StillVideos; using Febe.Core.Storage; using Febe.Tests.Support; using Febe.Tests.Web.Support; using Febe.Web.Demo; using Microsoft.Extensions.DependencyInjection; namespace Febe.Tests.Web; /// /// Tappa E4 in a real browser, on the demo (spec §4.10 «Video fermi», §10.3): the chip, the row and the buttons of a still /// video in the viewer, «Salva il fotogramma» («Scarica» and «Nella cartella delle copie»), «È un video fermo?» and /// «Analizza di nuovo», the filter «Video fermi», the confirmation of «Cerca i video fermi» with its counts, its end, its /// card in the Dashboard with the reason it waits and «Interrompi», what a change of the page takes away, the «fermi» events /// of the stream (which the demo does not have: the tests open one of their own). Analyses are only ever on request: what each video is /// before the test asks is read from the database and the API, never assumed from how the demo is built (it places its /// entries by the hour, #72). /// public sealed partial class ExportInterfaceTests { [TestMethod] public async Task TheViewerShowsAStillVideoAndSavesItsFrame() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-visualizzatore-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await RecordNoticesAsync(ui); await ui.AddInitScriptAsync(UiBrowser.Requests); // The name of every file the page gives to the browser to download. await ui.AddInitScriptAsync("(() => { window.__downloads = []; const click = HTMLAnchorElement.prototype.click; HTMLAnchorElement.prototype.click = function () { if (this.hasAttribute('download')) window.__downloads.push(this.download); return click.call(this); }; })();"); var (still, analysis) = await DemoVideoAsync(demo, a => a?.Outcome == VideoAnalysisOutcome.Still); await OpenInViewerAsync(ui, demo, still.Id, "docker"); await ui.WaitAsync("document.querySelector('.vis .azione-salva-fotogramma') !== null", "«Salva il fotogramma» nel visualizzatore " + ui.Report()); var entry = await ui.EvalAsync(Get($"/api/entries/{still.EntryId}")); var said = entry.GetProperty("media").EnumerateArray().Single(m => m.GetProperty("id").GetInt64() == still.Id).GetProperty("still"); var label = said.GetProperty("frameLabel").GetString()!; Assert.AreEqual((long)analysis!.FrameAt!.Value.TotalMilliseconds, said.GetProperty("frameAtMs").GetInt64()); // The chip, the row with the instant chosen, and no question: it was analysed. Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.vis .etichette .et.accento')].some((e) => e.textContent.trim() === 'Video fermo')")).GetBoolean(), "l'etichetta «Video fermo»"); Assert.AreEqual($"Un'immagine sola per tutto il video: basta un fotogramma · fotogramma a {label}", (await ui.EvalAsync("document.querySelector('.vis .riga-fermo span').textContent")).GetString()); Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis .azione-video-fermo') === null && document.querySelector('.vis .analizza-di-nuovo') === null")).GetBoolean()); Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis .azione-fotogramma') !== null")).GetBoolean(), "«Fotogramma» di E3 resta"); // «Salva il fotogramma»: the frame alone, with its preview; no instant, no number to choose. const string Dialog = "document.querySelector('.dialogo.fotogrammi')"; const string Start = $"{Dialog}.querySelector('footer .btn.primo')"; await ui.EvalAsync("document.querySelector('.vis .azione-salva-fotogramma').click()"); await ui.WaitAsync($"{Dialog}?.querySelector('.istante-mostrato') != null", "il dialogo «Salva il fotogramma»"); Assert.AreEqual("Salva il fotogramma", (await ui.EvalAsync($"{Dialog}.querySelector('h2').textContent")).GetString()); Assert.AreEqual($"Il fotogramma più nitido fra quelli guardati dall'analisi, a {label}.", (await ui.EvalAsync($"{Dialog}.querySelector('.istante-mostrato').textContent")).GetString()); await ui.WaitAsync($"(() => {{ const i = {Dialog}.querySelector('.anteprima-fotogramma img'); return i && i.complete && i.naturalWidth > 0 && new URL(i.src).pathname === '/api/media/{still.Id}/still/frame'; }})()", "l'anteprima " + ui.Report()); Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.campo-tempo, input[type=number], [data-value=istante], [data-value=numero]') === null")).GetBoolean(), "nothing to choose but the format"); Assert.AreEqual("Il fotogramma non ha l'audio.", (await ui.EvalAsync($"{Dialog}.querySelector('.nota-audio').textContent.trim()")).GetString()); Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis video').paused")).GetBoolean(), "the video waits while the dialog is open"); // PNG first, without loss; JPG says it loses. Assert.AreEqual("png", (await ui.EvalAsync($"{Dialog}.querySelector('[role=radio][aria-checked=true][data-value]').dataset.value")).GetString()); Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').hidden")).GetBoolean()); await ui.EvalAsync($"{Dialog}.querySelector('[role=radio][data-value=jpg]').click()"); Assert.IsFalse((await ui.EvalAsync($"{Dialog}.querySelector('.nota-perdita').hidden")).GetBoolean()); await ui.EvalAsync($"{Dialog}.querySelector('[role=radio][data-value=png]').click()"); // «Scarica»: one file, its name says «_fotogramma». await ui.WaitAsync($"{Start}.textContent.trim() === 'Scarica 1 fotogramma' && !{Start}.disabled", "«Scarica 1 fotogramma»"); Assert.AreEqual("1 fotogramma", (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-fotogrammi .riepilogo-copia').textContent")).GetString()); await ui.EvalAsync($"{Start}.click()"); await ui.WaitAsync($"{Dialog} === null && {Shown("Scaricamento del fotogramma avviato.")}", "il fotogramma si scarica " + ui.Report()); Assert.HasCount(1, await ui.AskedAsync($"GET /api/media/{still.Id}/still/frame?format=png&download=1")); var downloads = await ui.EvalAsync("window.__downloads"); Assert.AreEqual(Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(still.RelativePath!)) + "_fotogramma.png", downloads.Single()); // «Nella cartella delle copie»: the plan of the copies, then a copy of one frame at the instant of the analysis. await ui.EvalAsync("document.querySelector('.vis .azione-salva-fotogramma').click()"); await ui.WaitAsync($"{Dialog}?.querySelector('input[type=radio][value=cartella]') != null", "il dialogo, di nuovo"); await ui.EvalAsync($"{Dialog}.querySelector('input[type=radio][value=cartella]').click()"); await ui.WaitAsync($"{Start}.textContent.trim() === 'Copia 1 fotogramma' && !{Start}.disabled", "«Copia 1 fotogramma» " + ui.Report()); await ui.EvalAsync($"{Start}.click()"); await ui.WaitAsync($"{Dialog} === null && window.__notices.some((n) => n.href === '/dashboard/esportazione' && !n.kind.includes('errore'))", "la copia parte " + ui.Report()); await ui.WaitAsync($"{Get("/api/export/progress")}.then((j) => !j.running)", "la copia finisce"); var copy = (await demo.Storage.Exports.ListCopiesBySha256Async(still.Sha256!)).Single(c => c.MediaId == still.Id); Assert.AreEqual((ExportCopyState.Copied, ExportVariant.Frame, ExportFormat.Png, analysis.FrameAt), (copy.State, copy.Variant, copy.Format, copy.FrameAt)); StringAssert.EndsWith(copy.RelativePath, "_fotogramma.png"); Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); await CloseViewerAsync(ui); // The viewer opened again has the copy row, as for any frame (looked up by its words: the demo has others). await OpenInViewerAsync(ui, demo, still.Id, "docker"); await ui.WaitAsync($"[...document.querySelectorAll('.vis .riga-copia')].some((r) => r.textContent.includes('Copiato in Disco USB') && r.textContent.includes({Js($"fotogramma a {label} · PNG")}))", "la riga «Copia» del fotogramma " + ui.Report()); await CloseViewerAsync(ui); } [TestMethod] public async Task AVideoIsAnalysedFromTheViewerOnlyWhenAsked() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-domanda-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await RecordNoticesAsync(ui); await ui.AddInitScriptAsync(UiBrowser.Requests); // Never analysed: no chip, no row, «È un video fermo?». Opening the viewer asks for nothing. var (video, _) = await DemoVideoAsync(demo, a => a is null); const string Ask = "document.querySelector('.vis .azione-video-fermo')"; await OpenInViewerAsync(ui, demo, video.Id, "docker"); await ui.WaitAsync($"{Ask} !== null && !{Ask}.disabled", "«È un video fermo?» " + ui.Report()); Assert.AreEqual("È un video fermo?", (await ui.EvalAsync($"{Ask}.textContent.trim()")).GetString()); Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis .riga-fermo') === null && document.querySelector('.vis .azione-salva-fotogramma') === null && document.querySelector('.vis .azione-fotogramma') !== null")).GetBoolean()); Assert.IsEmpty(await ui.AskedAsync("/still")); // An answer that is not one (an analysis past its 30 seconds): the notice says why, the question stays. await ui.EvalAsync($"(() => {{ const real = window.fetch; window.__real = real; window.fetch = (input, init) => (String(input).endsWith('/api/media/{video.Id}/still') ? Promise.resolve(new Response(JSON.stringify({{ message: {Js(StillVideoText.TooSlow)} }}), {{ status: 503, headers: {{ 'Content-Type': 'application/json' }} }})) : real(input, init)); return true; }})()"); await ui.EvalAsync($"{Ask}.click()"); await ui.WaitAsync($"window.__notices.some((n) => n.kind.includes('errore') && n.text.includes({Js(StillVideoText.TooSlow)}))", "l'avviso dell'analisi troppo lunga " + ui.Report()); await ui.WaitAsync($"{Ask} !== null && !{Ask}.disabled && {Ask}.textContent.trim() === 'È un video fermo?'", "la domanda resta"); Assert.IsNull(await demo.Storage.VideoAnalyses.GetAsync(video.Sha256!)); await ui.EvalAsync("(() => { window.fetch = window.__real; window.__notices.length = 0; return true; })()"); // Asked: «Analisi in corso…» until the answer comes, then the row; the button is gone. await ui.EvalAsync($"window.__hold('/api/media/{video.Id}/still')"); await ui.EvalAsync($"{Ask}.click()"); await ui.WaitAsync($"(window.__started['/api/media/{video.Id}/still'] || 0) === 1 && {Ask}.disabled && {Ask}.textContent.trim() === 'Analisi in corso…'", "«Analisi in corso…»"); await ui.EvalAsync($"window.__release('/api/media/{video.Id}/still')"); await ui.WaitAsync("document.querySelector('.vis .riga-fermo') !== null", "la riga «Video fermo» " + ui.Report()); Assert.AreEqual("No: l'immagine cambia", (await ui.EvalAsync("document.querySelector('.vis .riga-fermo span').textContent")).GetString()); await ui.WaitAsync(Shown("Non è un video fermo: l'immagine cambia."), "l'avviso dell'esito"); Assert.IsTrue((await ui.EvalAsync($"{Ask} === null && document.querySelector('.vis .azione-salva-fotogramma') === null")).GetBoolean(), "nothing more to ask"); Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); Assert.AreEqual(VideoAnalysisOutcome.Moving, (await demo.Storage.VideoAnalyses.GetAsync(video.Sha256!))!.Outcome); await CloseViewerAsync(ui); // «Non analizzabile» because it took too long: «Analizza di nuovo» gives the answer. var (slow, _) = await DemoVideoAsync(demo, a => a?.Note == VideoAnalysisNotes.TooSlow); await OpenInViewerAsync(ui, demo, slow.Id, "docker"); await ui.WaitAsync("document.querySelector('.vis .analizza-di-nuovo') !== null", "«Analizza di nuovo» " + ui.Report()); Assert.AreEqual("Non analizzabile: l'analisi richiedeva troppo tempo", (await ui.EvalAsync("document.querySelector('.vis .riga-fermo span').textContent")).GetString()); Assert.AreEqual("Analizza di nuovo", (await ui.EvalAsync("document.querySelector('.vis .analizza-di-nuovo').textContent.trim()")).GetString()); Assert.IsTrue((await ui.EvalAsync($"{Ask} === null")).GetBoolean()); await ui.EvalAsync("document.querySelector('.vis .analizza-di-nuovo').click()"); await ui.WaitAsync("document.querySelector('.vis .riga-fermo span')?.textContent === \"No: l'immagine cambia\" && document.querySelector('.vis .analizza-di-nuovo') === null", "l'esito nuovo " + ui.Report()); Assert.AreEqual(VideoAnalysisOutcome.Moving, (await demo.Storage.VideoAnalyses.GetAsync(slow.Sha256!))!.Outcome); await CloseViewerAsync(ui); // A photo has nothing of this. var photo = await DemoCopyAsync(demo, ExportVariant.Whole); await OpenInViewerAsync(ui, demo, photo.MediaId!.Value, "docker"); await ui.WaitAsync("document.querySelector('.vis .riga-copia') !== null", "una foto nel visualizzatore"); Assert.IsTrue((await ui.EvalAsync("document.querySelector('.vis .riga-fermo, .vis .azione-video-fermo, .vis .azione-salva-fotogramma') === null")).GetBoolean()); await CloseViewerAsync(ui); } [TestMethod] public async Task TheFilterVideoFermiIsInTheLibraryAfterVideo() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-filtro-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); const string Chips = "[...document.querySelectorAll('.strumenti .filtri button')]"; const string Active = "document.querySelector('.strumenti .filtri button.qui')?.textContent.trim()"; const string Tiles = "[...document.querySelectorAll('.mosaico .tess')].map((t) => Number(t.dataset.id))"; await ui.OpenAsync(new Uri(demo.Address, "/libreria")); await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null", "il mosaico"); var names = await ui.EvalAsync($"{Chips}.map((b) => b.textContent.trim())"); Assert.AreEqual(Array.IndexOf(names, "Video") + 1, Array.IndexOf(names, "Video fermi"), string.Join(" · ", names)); Assert.IsGreaterThan(0, Array.IndexOf(names, "Video"), string.Join(" · ", names)); // Chosen: the address says it, the tiles are those of the API, and the page read again keeps it. var expected = await ui.EvalAsync($"{Get("/api/library?kind=stillvideos&limit=100")}.then((j) => j.tiles.map((t) => t.id).sort((a, b) => a - b))"); Assert.IsNotEmpty(expected); var same = $"JSON.stringify(({Tiles}).sort((a, b) => a - b)) === {Js(JsonSerializer.Serialize(expected))}"; await ui.EvalAsync($"{Chips}.find((b) => b.textContent.trim() === 'Video fermi').click()"); await ui.WaitAsync($"new URLSearchParams(location.search).get('tipo') === 'fermi' && {Active} === 'Video fermi'", "il filtro nell'indirizzo"); await ui.WaitAsync(same, "le tessere dei video fermi " + ui.Report()); await ui.OpenAsync(new Uri(demo.Address, "/libreria?tipo=fermi")); await ui.WaitAsync($"{Active} === 'Video fermi' && {same}", "il filtro riletto dall'indirizzo " + ui.Report()); // «Tutte le foto»: the still files, one tile each. var files = await ui.EvalAsync($"{Get("/api/library?kind=stillvideos&mode=files&limit=100")}.then((j) => j.tiles.map((t) => t.cover.mediaId).sort((a, b) => a - b))"); await ui.EvalAsync("document.querySelector('.strumenti .modo-mosaico [data-value=files]').click()"); await ui.WaitAsync($"JSON.stringify(({Tiles}).sort((a, b) => a - b)) === {Js(JsonSerializer.Serialize(files))}", "i file dei video fermi " + ui.Report()); // The account tab has «Cerca i video fermi» but not the filter (answer 40: Libreria only). var (still, _) = await DemoVideoAsync(demo, a => a?.Outcome == VideoAnalysisOutcome.Still); var account = (await demo.Storage.Entries.GetAsync(still.EntryId))!.AccountId; await ui.OpenAsync(new Uri(demo.Address, $"/account/{account}")); await ui.WaitAsync("document.querySelector('.mosaico .tess') !== null && document.querySelector('.filtri button') !== null && [...document.querySelectorAll('.btn')].some((b) => b.textContent.includes('Seleziona'))", "i contenuti dell'account"); Assert.IsFalse((await ui.EvalAsync("[...document.querySelectorAll('.filtri button')].some((b) => b.textContent.includes('Video fermi'))")).GetBoolean()); await ui.EvalAsync("[...document.querySelectorAll('.btn')].find((b) => b.textContent.includes('Seleziona')).click()"); await ui.EvalAsync("document.querySelector('.mosaico .tess').click()"); await ui.WaitAsync("document.querySelector('.salva .fermi-selezione') !== null && !document.querySelector('.salva .fermi-selezione').disabled", "«Cerca i video fermi» nella scheda dell'account"); } [TestMethod] public async Task CercaIVideoFermiCountsStartsAndSaysItsEnd() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-cerca-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await RecordNoticesAsync(ui); await ui.AddInitScriptAsync(UiBrowser.Requests); var chosen = await ChooseVideosAsync(ui, demo); var body = $"{{ \"entryIds\": {JsonSerializer.Serialize(chosen)} }}"; var fresh = (await UnanalysedAsync(demo, chosen))[0]; // One of the chosen videos is still when it is analysed (the file of the demo's still video is served for it). Assert.IsTrue(demo.World.StillVideoFiles.TryAdd(fresh.Sha256!, demo.World.StillVideoFiles.First().Value)); var plan = await ui.EvalAsync(Post("/api/still-videos/plan", body)); var toAnalyse = plan.GetProperty("toAnalyse").GetInt32(); Assert.IsGreaterThan(0, toAnalyse, plan.ToString()); Assert.IsGreaterThan(0, plan.GetProperty("photosSkipped").GetInt32(), plan.ToString()); // The confirmation says what the API says. const string Dialog = "document.querySelector('.dialogo.cerca-fermi')"; await OpenSearchAsync(ui); Assert.AreEqual("Cerca i video fermi", (await ui.EvalAsync($"{Dialog}.querySelector('h2').textContent")).GetString()); Assert.AreEqual(plan.GetProperty("summary").GetString(), (await ui.EvalAsync($"{Dialog}.querySelector('.riepilogo-copia').textContent")).GetString()); Assert.AreEqual($"Analizza {toAnalyse} video", (await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').textContent.trim()")).GetString()); Assert.IsTrue((await ui.EvalAsync($"{Dialog}.querySelector('.avviso.ambra') === null")).GetBoolean(), "nothing makes it wait"); // «Annulla» analyses nothing. await ui.EvalAsync($"[...{Dialog}.querySelectorAll('footer button')].find((b) => b.textContent === 'Annulla').click()"); await ui.WaitAsync($"{Dialog} === null", "il dialogo si chiude"); Assert.IsNull(await demo.Storage.VideoAnalyses.GetAsync(fresh.Sha256!)); Assert.AreEqual(0, (await ui.EvalAsync(Get("/api/still-videos/progress"))).GetProperty("total").GetInt32()); // Started: the notice leads to the Dashboard; the end is said on the page, with the link to what was found. await OpenSearchAsync(ui); await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); await ui.WaitAsync($"{Dialog} === null && {Shown($"Ricerca dei video fermi avviata: {toAnalyse} video da analizzare.")}", "la ricerca parte " + ui.Report()); Assert.AreEqual("/dashboard/esportazione", (await ui.EvalAsync("window.__notices.find((n) => n.text.includes('Ricerca dei video fermi avviata')).href")).GetString()); await ui.WaitAsync("window.__notices.some((n) => n.text.startsWith('Analizzat'))", "l'avviso della fine " + ui.Report()); var done = await ui.EvalAsync(Get("/api/still-videos/progress")); Assert.AreEqual((false, toAnalyse, toAnalyse, 1), (done.GetProperty("running").GetBoolean(), done.GetProperty("total").GetInt32(), done.GetProperty("done").GetInt32(), done.GetProperty("still").GetInt32()), done.ToString()); Assert.IsTrue((await ui.EvalAsync(Shown(done.GetProperty("summary").GetString() + "."))).GetBoolean(), "the notice is the summary of the API"); Assert.AreEqual("/libreria", (await ui.EvalAsync("window.__notices.find((n) => n.text.startsWith('Analizzat')).href")).GetString()); Assert.AreEqual("?tipo=fermi", (await ui.EvalAsync("new URL(window.__noticeLinks.at(-1).href).search")).GetString()); Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); Assert.AreEqual(VideoAnalysisOutcome.Still, (await demo.Storage.VideoAnalyses.GetAsync(fresh.Sha256!))!.Outcome); // «Mostra i video fermi»: the filter, with the entry just found (the link of the last notice: the one of the start, // which leads to the Dashboard, can still be on screen). await ui.EvalAsync("(() => { const link = window.__noticeLinks.at(-1); if (link.isConnected) link.click(); else location.assign(link.href); return true; })()"); await ui.WaitAsync("location.pathname === '/libreria' && new URLSearchParams(location.search).get('tipo') === 'fermi' && document.querySelector('.strumenti .filtri button.qui')?.textContent.trim() === 'Video fermi' && document.querySelector('.mosaico .tess') !== null", "la Libreria dei video fermi " + ui.Report()); var found = await ui.EvalAsync($"{Get("/api/library?kind=stillvideos&limit=1000")}.then((j) => j.tiles.map((t) => t.id))"); CollectionAssert.Contains(found, fresh.EntryId); // The Dashboard keeps the end of the last search, with the same link; a second search has nothing left. await ui.OpenAsync(new Uri(demo.Address, "/dashboard/esportazione")); await ui.WaitAsync($"document.querySelector('.ricerca-fermi .riga-conteggi span')?.textContent === {Js(done.GetProperty("summary").GetString() + ".")}", "la fine nella Dashboard " + ui.Report()); Assert.AreEqual("/libreria?tipo=fermi", (await ui.EvalAsync("(() => { const u = new URL(document.querySelector('.ricerca-fermi .riga-conteggi a').href); return u.pathname + u.search; })()")).GetString()); var left = await ui.EvalAsync(Post("/api/still-videos/plan", body)); Assert.AreEqual(0, left.GetProperty("toAnalyse").GetInt32(), left.ToString()); // The card is read again every few seconds: its link keeps the focus of the keyboard. const string Asked = "window.__asked.filter((r) => r.includes('/api/still-videos/progress')).length"; await ui.EvalAsync("(() => { window.__link = document.querySelector('.ricerca-fermi .riga-conteggi a'); window.__link.focus(); return true; })()"); var polls = (await ui.EvalAsync(Asked)).GetInt32(); await ui.WaitAsync($"{Asked} >= {polls + 3}", "l'avanzamento riletto"); Assert.IsTrue((await ui.EvalAsync("window.__link.isConnected && document.activeElement === window.__link")).GetBoolean(), "the focus stays on «Mostra i video fermi»"); } [TestMethod] public async Task TheDashboardSaysWhyTheSearchWaitsAndInterrompiEndsIt() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-dashboard-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await RecordNoticesAsync(ui); var chosen = await ChooseVideosAsync(ui, demo); var fresh = await UnanalysedAsync(demo, chosen); Assert.IsTrue(demo.App.Services.GetRequiredService().TryEnter(LongWorkKind.Import, out var lease, out _)); using (lease) { // An import at work: the confirmation says the search will wait, and lets it start. const string Dialog = "document.querySelector('.dialogo.cerca-fermi')"; await OpenSearchAsync(ui); Assert.AreEqual(StillVideoText.LongWork, (await ui.EvalAsync($"{Dialog}.querySelector('.avviso.ambra').textContent.trim()")).GetString()); await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); await ui.WaitAsync($"{Dialog} === null && {Shown("Ricerca dei video fermi avviata")}", "la ricerca parte " + ui.Report()); // The same videos again, while they wait: they are queued already, and nothing says that others were started. await OpenSearchAsync(ui); await ui.EvalAsync($"{Dialog}.querySelector('footer .btn.primo').click()"); await ui.WaitAsync($"{Dialog} === null && {Shown("I video scelti sono già in coda.")}", "i video già in coda " + ui.Report()); Assert.AreEqual(1, (await ui.EvalAsync("window.__notices.filter((n) => n.text.includes('Ricerca dei video fermi avviata')).length")).GetInt32()); await ui.EvalAsync(FollowNoticeLink); // Dashboard → Esportazione: nothing done yet, the reason, «Interrompi». const string Card = "document.querySelector('.ricerca-fermi .avanzamento-fermi')"; await ui.WaitAsync($"location.pathname === '/dashboard/esportazione' && {Card}?.querySelector('.fase-copia') != null", "la ricerca nella Dashboard " + ui.Report()); var job = await ui.EvalAsync(Get("/api/still-videos/progress")); var total = job.GetProperty("total").GetInt32(); Assert.AreEqual((true, 0), (job.GetProperty("running").GetBoolean(), job.GetProperty("done").GetInt32()), job.ToString()); Assert.AreEqual(StillVideoText.LongWork, (await ui.EvalAsync($"{Card}.querySelector('.fase-copia').textContent.trim()")).GetString()); Assert.AreEqual(total == 1 ? "0 di 1 video analizzato" : $"0 di {total} video analizzati", (await ui.EvalAsync($"{Card}.querySelector('.conteggio').textContent")).GetString()); Assert.IsTrue((await ui.EvalAsync("(() => { const b = [...document.querySelectorAll('.avanzamento-fermi button')].find((x) => x.textContent.trim() === 'Interrompi'); if (!b || b.disabled) return false; b.click(); return true; })()")).GetBoolean()); await ui.WaitAsync("document.querySelector('.ricerca-fermi .riga-conteggi span')?.textContent === 'Ricerca interrotta: nessun video analizzato.'", "la ricerca interrotta " + ui.Report()); } var ended = await ui.EvalAsync(Get("/api/still-videos/progress")); Assert.AreEqual((false, true, 0), (ended.GetProperty("running").GetBoolean(), ended.GetProperty("stopped").GetBoolean(), ended.GetProperty("done").GetInt32()), ended.ToString()); foreach (var media in fresh) { Assert.IsNull(await demo.Storage.VideoAnalyses.GetAsync(media.Sha256!), "nothing was analysed"); } Assert.IsTrue((await ui.EvalAsync("document.querySelector('.ricerca-fermi .riga-conteggi a') === null")).GetBoolean(), "nothing found, nothing to show"); Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); } [TestMethod] public async Task AChangeOfThePageTakesAwayTheViewerAndTheDialogsOverIt() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-pagina-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await RecordNoticesAsync(ui); var (still, _) = await DemoVideoAsync(demo, a => a?.Outcome == VideoAnalysisOutcome.Still); // The notice of the end of a search lies above everything, wherever it comes from. const string FollowNotice = "import('/js/core/ui.js').then((m) => { m.toast('Analizzati 2 video: 1 fermo, 1 in movimento.', '', { label: 'Mostra i video fermi', href: '/libreria?tipo=fermi' }); const links = document.querySelectorAll('.brevi .breve a.breve-link'); links[links.length - 1].click(); return true; })"; const string Arrived = "location.pathname === '/libreria' && new URLSearchParams(location.search).get('tipo') === 'fermi' && document.querySelector('.strumenti .filtri button.qui')?.textContent.trim() === 'Video fermi' && document.querySelector('.mosaico .tess') !== null"; const string Nothing = "document.querySelector('.vis') === null && document.querySelector('.velo.finestra') === null"; // A dialog of the page itself with Back: the one of the selection, which counts as dismissed. await ui.OpenAsync(new Uri(demo.Address, "/dashboard")); await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .attivita') !== null", "la Dashboard"); await ChooseVideosInPageAsync(ui, demo); await OpenSearchAsync(ui); await ui.EvalAsync("(() => { history.back(); return true; })()"); await ui.WaitAsync("location.pathname === '/dashboard' && document.querySelector('main .attivita') !== null", "Indietro " + ui.Report()); Assert.IsTrue((await ui.EvalAsync(Nothing)).GetBoolean(), "the dialog goes with its page"); Assert.AreEqual(0, (await ui.EvalAsync(Get("/api/still-videos/progress"))).GetProperty("total").GetInt32(), "nothing was started"); await OpenInViewerAsync(ui, demo, still.Id, "docker"); await ui.EvalAsync(FollowNotice); await ui.WaitAsync(Arrived, "la Libreria dei video fermi " + ui.Report()); Assert.IsTrue((await ui.EvalAsync(Nothing)).GetBoolean(), "the viewer goes with its page"); // Also what was opened from it: «Salva il fotogramma» of a video that is no longer shown. await OpenInViewerAsync(ui, demo, still.Id, "docker"); await ui.WaitAsync("document.querySelector('.vis .azione-salva-fotogramma') !== null", "«Salva il fotogramma»"); await ui.EvalAsync("document.querySelector('.vis .azione-salva-fotogramma').click()"); await ui.WaitAsync("document.querySelector('.dialogo.fotogrammi .istante-mostrato') !== null", "il dialogo «Salva il fotogramma»"); await ui.EvalAsync(FollowNotice); await ui.WaitAsync(Arrived, "la Libreria dei video fermi, di nuovo " + ui.Report()); Assert.IsTrue((await ui.EvalAsync(Nothing)).GetBoolean(), "the dialog goes with the viewer"); Assert.IsTrue((await ui.EvalAsync(NoErrorNotice)).GetBoolean(), ui.Report()); } [TestMethod] public async Task TheViewerFollowsTheAnalysesMadeElsewhereAndOnlyTheLastReadingCounts() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-eventi-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await ui.AddInitScriptAsync(UiBrowser.Requests); var (video, _) = await DemoVideoAsync(demo, a => a is null); var entry = (await demo.Storage.Entries.GetAsync(video.EntryId))!; await OpenInViewerAsync(ui, demo, video.Id, "docker"); await ui.WaitAsync("document.querySelector('.vis .azione-video-fermo') !== null", "«È un video fermo?» " + ui.Report()); await OpenStreamAsync(ui); // From here the answers for the entry come when the test says, with what the test says. await ui.EvalAsync($$""" (() => { const real = window.fetch; window.__answers = []; window.fetch = (input, init) => (new URL(String(input), location.href).pathname === '/api/entries/{{video.EntryId}}' ? new Promise((resolve) => window.__answers.push((json) => resolve(new Response(JSON.stringify(json), { status: 200, headers: { 'Content-Type': 'application/json' } })))) : real(input, init)); window.__real = real; return true; })() """); // An analysis made under another account: the outcome belongs to the file, which may be here too. var change = $"{{ reason: 'fermi', accountId: {entry.AccountId + 1000}, at: 0 }}"; await ui.EvalAsync($"window.__stream('libreria', {change})"); await ui.WaitAsync("window.__answers.length === 1", "l'elemento riletto"); await ui.EvalAsync($"window.__stream('libreria', {change})"); await ui.WaitAsync("window.__answers.length === 2", "l'elemento riletto ancora"); // The second answer comes first; the first, older, must not bring back what was before. await ui.EvalAsync($"window.__real('/api/entries/{video.EntryId}', {{ headers: {{ Accept: 'application/json' }} }}).then((r) => r.json()).then((j) => {{ window.__older = j; window.__newer = structuredClone(j); window.__newer.media.find((m) => m.id === {video.Id}).still = {{ outcome: 'moving', note: null, frameAtMs: null, frameLabel: null, current: true }}; return true; }})"); await ui.EvalAsync("(() => { window.__answers[1](window.__newer); return true; })()"); await ui.WaitAsync("document.querySelector('.vis .riga-fermo span')?.textContent === \"No: l'immagine cambia\"", "l'esito nella scheda " + ui.Report()); await ui.EvalAsync("(() => { window.__answers[0](window.__older); return new Promise((resolve) => setTimeout(resolve, 100)); })()"); Assert.AreEqual("No: l'immagine cambia", (await ui.EvalAsync("document.querySelector('.vis .riga-fermo span')?.textContent ?? ''")).GetString(), "an older answer does not count"); await CloseViewerAsync(ui); } [TestMethod] public async Task AnAnalysisReloadsNeitherTheAccountsNorTheDashboard() { await using var ui = await UiBrowser.StartAsync(1440, 900); using var temp = new TempFolder("fermi-ricariche-ui"); await using var demo = await DemoHost.StartAsync(new DemoOptions(0, TestZones.Rome, temp.Path)); await ui.AddInitScriptAsync(UiBrowser.Requests); foreach (var (path, request, ready) in new[] { ("/account", "GET /api/accounts", "document.querySelector('a[href^=\"/account/\"]') !== null"), ("/dashboard", "GET /api/alerts", "document.querySelector('main .attivita') !== null"), }) { var asked = $"window.__asked.filter((r) => r.split('?')[0] === {Js(request)}).length"; await ui.OpenAsync(new Uri(demo.Address, path)); await ui.WaitAsync($"{ready} && {asked} > 0", path + " " + ui.Report()); await ui.WaitForQuietAsync("richieste della pagina finite"); await OpenStreamAsync(ui); await ui.WaitForQuietAsync("richieste della pagina finite"); var before = (await ui.EvalAsync(asked)).GetInt32(); // The pages wait at most 600 ms before they read again: past a second and a half what had to be asked was. await ui.EvalAsync("(() => { window.__stream('libreria', { reason: 'fermi', accountId: 1, at: 0 }); return new Promise((resolve) => setTimeout(resolve, 1500)); })()"); Assert.AreEqual(before, (await ui.EvalAsync(asked)).GetInt32(), $"{path}: an analysis changes nothing here"); // Any other change of the library does. await ui.EvalAsync("(() => { window.__stream('libreria', { reason: 'import', accountId: 1, at: 0 }); return true; })()"); await ui.WaitAsync($"{asked} > {before}", $"{path}: riletta dopo un altro cambio"); } } // ------------------------------------------------------------------------------------------------- support /// /// Opens the event stream of the interface (the demo has none) on one the test writes: window.__stream(name, data) /// brings an event. /// private static async Task OpenStreamAsync(UiBrowser ui) => await ui.EvalAsync(""" (async () => { const streams = []; window.EventSource = class extends EventTarget { constructor() { super(); this.readyState = 1; streams.push(this); } }; window.__stream = (name, data) => { for (const stream of streams) stream.dispatchEvent(new MessageEvent(name, { data: JSON.stringify(data) })); return true; }; const context = await import('/js/core/context.js'); const engine = await import('/js/core/engine.js'); context.setCapabilities({ demo: false }); engine.startEvents(); context.setCapabilities({ demo: true }); if (streams.length !== 1) throw new Error('il flusso degli eventi non è stato aperto'); return true; })() """); /// /// The newest video of @marta.demo whose analysis (null: never analysed) is the one looked for. Read from the database: /// which of the demo's videos they are depends on the hour it is built. /// private static async Task<(Media Media, VideoAnalysis? Analysis)> DemoVideoAsync(DemoHost demo, Func wanted) { var marta = (await demo.Storage.Accounts.ListAsync()).Single(a => a.Username == DemoStillVideos.StillAccount).Id; LibraryCursor? cursor = null; do { var page = await demo.Storage.Entries.QueryLibraryAsync( new LibraryQuery { Filter = new LibraryFilter { AccountIds = [marta] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 }); foreach (var tile in page.Tiles.Where(t => t.CoverKind == MediaKind.Video && t.CoverMediaId is not null)) { if (await demo.Storage.Media.GetAsync(tile.CoverMediaId!.Value) is { Sha256: { } sha, RelativePath: not null } media && EntryStateRules.IsPresent(media.State) && await demo.Storage.VideoAnalyses.GetAsync(sha) is var analysis && wanted(analysis)) { return (media, analysis); } } cursor = page.Older; } while (cursor is not null); Assert.Fail("the demo has no such video"); return default; } /// /// Selects, in the Libreria of @marta.demo, up to two entries with a video never analysed and one of photos only among /// the tiles on screen (what they are is asked of the API). Returns the entries. /// private static async Task ChooseVideosAsync(UiBrowser ui, DemoHost demo) { var marta = (await demo.Storage.Accounts.ListAsync()).Single(a => a.Username == DemoStillVideos.StillAccount).Id; await ui.OpenAsync(new Uri(demo.Address, string.Create(CultureInfo.InvariantCulture, $"/libreria?account={marta}"))); return await ChooseAsync(ui); } /// As , going to the Libreria inside the page that is open. private static async Task ChooseVideosInPageAsync(UiBrowser ui, DemoHost demo) { var marta = (await demo.Storage.Accounts.ListAsync()).Single(a => a.Username == DemoStillVideos.StillAccount).Id; await ui.NavigateAsync(string.Create(CultureInfo.InvariantCulture, $"/libreria?account={marta}")); await ui.WaitAsync("location.pathname === '/libreria'", "la Libreria"); await ChooseAsync(ui); } private static async Task ChooseAsync(UiBrowser ui) { 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()); return await ui.EvalAsync( "(async () => { const fresh = []; const photos = []; " + "for (const id of [...document.querySelectorAll('.mosaico .tess')].map((t) => Number(t.dataset.id))) { " + "if (fresh.length === 2 && photos.length === 1) break; " + "const e = await fetch(`/api/entries/${id}`, { headers: { Accept: 'application/json' } }).then((r) => r.json()); " + "if (e.media.some((m) => m.kind === 'video' && m.available && !m.still)) { if (fresh.length < 2) fresh.push(id); } " + "else if (e.media.every((m) => m.kind === 'photo') && !photos.length) photos.push(id); } " + "const chosen = [...fresh, ...photos]; " + "chosen.forEach((id) => document.querySelector(`.mosaico .tess[data-id=\"${id}\"]`).click()); return chosen; })()"); } /// The videos never analysed of the entries. private static async Task> UnanalysedAsync(DemoHost demo, long[] entries) { var found = new List(); foreach (var id in entries) { foreach (var media in (await demo.Storage.Entries.GetWithMediaAsync(id))!.Media.Where(m => m.Kind == MediaKind.Video && m.Sha256 is not null)) { if (await demo.Storage.VideoAnalyses.GetAsync(media.Sha256!) is null) { found.Add(media); } } } Assert.IsNotEmpty(found, "a video never analysed among the tiles on screen"); return found; } /// «Cerca i video fermi» of the selection bar, until its counts are there and the button can be pressed. private static async Task OpenSearchAsync(UiBrowser ui) { const string Search = "document.querySelector('.salva .fermi-selezione')"; const string Start = "document.querySelector('.dialogo.cerca-fermi footer .btn.primo')"; await ui.WaitAsync($"{Search} && !{Search}.disabled", "«Cerca i video fermi» nella barra della scelta " + ui.Report()); Assert.AreEqual("Cerca i video fermi", (await ui.EvalAsync($"{Search}.textContent.trim()")).GetString()); await ui.EvalAsync($"{Search}.click()"); await ui.WaitAsync($"document.querySelector('.dialogo.cerca-fermi .riepilogo-copia') !== null && !{Start}.disabled", "i conti della ricerca " + ui.Report()); } }