diff --git a/src/Febe.Web/Demo/DemoStillVideos.cs b/src/Febe.Web/Demo/DemoStillVideos.cs index f11bd59..830b904 100644 --- a/src/Febe.Web/Demo/DemoStillVideos.cs +++ b/src/Febe.Web/Demo/DemoStillVideos.cs @@ -11,8 +11,8 @@ namespace Febe.Web.Demo; /// /// The still videos of the demo (spec §4.10 «Video fermi», tappa E4): two videos (the newest of @marta.demo and the -/// newest story video of another account) become their cover picture alone for two seconds, each in its own file -/// recorded with its own SHA-256 (so «Salva il fotogramma» works both with «Scarica» and «Nella cartella delle copie»), +/// newest story video of another account, on another picture) become their cover picture alone for two seconds, each in +/// its own file recorded with its own SHA-256 (so «Salva il fotogramma» works both with «Scarica» and «Nella cartella delle copie»), /// with a «Fermo» analysis that the real analyser gave on that file. Another video of @marta.demo has an «In movimento» /// analysis (of the demo's moving file), a third «Non analizzabile» because it took too long («Analizza di nuovo»); the /// rest is never analysed, so «È un video fermo?» and «Cerca i video fermi» work live. Analyses are only on request in @@ -41,8 +41,9 @@ public static class DemoStillVideos var now = clock.Now; var folder = Path.GetDirectoryName(movingFile)!; - var own = await VideosAsync(database, world, new LibraryFilter { AccountIds = [marta.Id] }, 3, null, ct).ConfigureAwait(false); - var story = await VideosAsync(database, world, new LibraryFilter { Kind = LibraryKindFilter.Stories }, 1, marta.Id, ct).ConfigureAwait(false); + var own = await VideosAsync(database, world, new LibraryFilter { AccountIds = [marta.Id] }, 3, null, [], ct).ConfigureAwait(false); + var story = await VideosAsync( + database, world, new LibraryFilter { Kind = LibraryKindFilter.Stories }, 1, marta.Id, [.. own.Select(m => m.Sha256!)], ct).ConfigureAwait(false); var stills = own.Take(1).Concat(story).ToList(); var thumbnails = new ThumbnailStore(data.Thumbnails); var n = 0; @@ -126,13 +127,17 @@ public static class DemoStillVideos } /// - /// Up to present videos of the filter, newest first, each on its own cover picture, that no - /// copy uses (the copies of the demo keep the SHA-256 they were made from) and not of . + /// Up to present videos of the filter, newest first, each on its own cover picture, not of + /// and not on a picture of (the accounts share pictures, + /// and one picture gives one still file). First the pictures that no copy uses (the copies of the demo keep the SHA-256 + /// they were made from); how many there are depends on the day and the hour the demo is built, so when they are not + /// enough the pictures of copied photos follow, never the video of a copy. /// - private static async Task> VideosAsync(FebeDatabase database, DemoWorld world, LibraryFilter filter, int count, long? exceptAccount, CancellationToken ct) + private static async Task> VideosAsync(FebeDatabase database, DemoWorld world, LibraryFilter filter, int count, long? exceptAccount, IReadOnlyList exceptShas, CancellationToken ct) { var found = new List(); - var shas = new HashSet(StringComparer.Ordinal); + var spare = new List(); + var shas = new HashSet(exceptShas, StringComparer.Ordinal); LibraryCursor? cursor = null; do { @@ -141,12 +146,24 @@ public static class DemoStillVideos { if (tile.CoverKind != MediaKind.Video || tile.CoverMediaId is not { } id || tile.AccountId == exceptAccount || await database.Media.GetAsync(id, ct).ConfigureAwait(false) is not { Sha256: { } sha, RelativePath: not null } media - || !EntryStateRules.IsPresent(media.State) || !world.Pictures.ContainsKey(sha) || !shas.Add(sha) - || (await database.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Count > 0) + || !EntryStateRules.IsPresent(media.State) || !world.Pictures.ContainsKey(sha) || shas.Contains(sha)) { continue; } + var copies = await database.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false); + if (copies.Any(c => c.MediaId == media.Id || c.Variant == ExportVariant.Frame)) + { + continue; + } + + shas.Add(sha); + if (copies.Count > 0) + { + spare.Add(media); + continue; + } + found.Add(media); if (found.Count == count) { @@ -158,6 +175,7 @@ public static class DemoStillVideos } while (cursor is not null); + found.AddRange(spare.Take(count - found.Count)); return found; } } diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 60c7e7e..7c3d614 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -279,7 +279,7 @@ scrive mai nella libreria vera e non usa la rete. converte». La conversione della libreria non parte mai. «Nella cartella delle copie» dei fotogrammi di un video finisce in errore («non corrisponde»): i video condividono l'impronta della loro copertina, non quella del file. - Video fermi (tappa E4, `Demo/DemoStillVideos.cs`): il video più recente di @marta.demo e la storia video più recente - di un altro account sono la loro copertina ferma per 2 secondi dopo una breve dissolvenza dal nero + di un altro account (su un'altra immagine) sono la loro copertina ferma per 2 secondi dopo una breve dissolvenza dal nero (`campioni/video-fermo-dimostrativo-1.mp4` e `-2.mp4`, da `H264PcmWriter.DemoStillVideo`), ciascuno registrato con l'impronta del suo file: «Salva il fotogramma» funziona anche «Nella cartella delle copie». Hanno un'analisi «Fermo» data dall'analizzatore vero (il filtro «Video fermi» li mostra); il video dopo di @marta.demo è «In movimento», quello diff --git a/tests/Febe.Tests/Export/ExportFrameNamesTests.cs b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs index db03fcf..4c4d3ca 100644 --- a/tests/Febe.Tests/Export/ExportFrameNamesTests.cs +++ b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs @@ -48,6 +48,7 @@ public sealed class ExportFrameNamesTests Assert.AreEqual("_t1m05s000", ExportFrames.Suffix(FrameMode.Every, TimeSpan.FromSeconds(65), 3, 9)); Assert.AreEqual("_f001", ExportFrames.Suffix(FrameMode.Count, actual, 0, 12)); Assert.AreEqual("_f0042", ExportFrames.Suffix(FrameMode.Count, actual, 41, 1000)); + Assert.AreEqual("_fotogramma", ExportFrames.Suffix(FrameMode.Still, actual, 0, 1), "the same whatever the instant (tappa E4)"); Assert.AreEqual("0:01", ExportFrames.Label(TimeSpan.FromSeconds(1))); Assert.AreEqual("0:01,25", ExportFrames.Label(TimeSpan.FromMilliseconds(1250))); Assert.AreEqual("2:03,007", ExportFrames.Label(TimeSpan.FromMilliseconds(123_007))); @@ -69,6 +70,8 @@ public sealed class ExportFrameNamesTests var numbered = ExportPaths.NumberedName(root, "post/" + name, 2, keepSuffix: "_t0m12s340"); Assert.EndsWith("_t0m12s340 (2).png", numbered); + Assert.AreEqual("post/a_fotogramma (2).png", ExportPaths.NumberedName("/d", "post/a_fotogramma.png", 2, keepSuffix: ExportFrames.SingleSuffix)); + Assert.EndsWith("_fotogramma.png", WindowsFileNames.FitPath(root, ["post", new string('n', 200) + "_fotogramma.png"], keepSuffix: ExportFrames.SingleSuffix)[^1]); Assert.AreEqual("post/a_f001 (3).png", ExportPaths.NumberedName("/d", "post/a_f001.png", 3, keepSuffix: "_f001")); } diff --git a/tests/Febe.Tests/Export/ExportFramesTests.cs b/tests/Febe.Tests/Export/ExportFramesTests.cs index c451db6..948eda7 100644 --- a/tests/Febe.Tests/Export/ExportFramesTests.cs +++ b/tests/Febe.Tests/Export/ExportFramesTests.cs @@ -309,6 +309,98 @@ public sealed class ExportFramesTests Assert.HasCount(6, await bed.ItemsAsync(started.Runs.Single().Id, ct)); } + [TestMethod] + public async Task TheFrameOfAStillVideoKeepsItsNameAcrossAPause() + { + // «Salva il fotogramma» to the folder of the copies (tappa E4, D9): the run says «Fermo», so a job resumed after a + // pause (or after Febe closed) names the frame «…_fotogramma» as it would have done, at the instant recorded. + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var video = (await SaveVideoAsync(bed, bed.Marta, "981", Mp4, ".mp4")).Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + var at = TimeSpan.FromMilliseconds(400); + await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Still, Make.T0, at), ct); + var request = Frames(video, new ExportFramesRequest(FrameMode.Still, null, null, null, ExportFormat.Png)); + + bed.Disk.Free = 0; + var start = await bed.CopyAsync(request, ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Paused, run.State, run.LastError); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + + bed.Disk.Free = null; + await bed.Service.ResumeAsync([run.Id], ct); + await bed.Service.WaitAsync(ct); + Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State); + var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + Assert.AreEqual("marta.demo/" + Path.ChangeExtension(video.RelativePath!, null) + "_fotogramma.png", copy.RelativePath); + Assert.AreEqual((ExportVariant.Frame, ExportFormat.Png), (copy.Variant, copy.Format)); + Assert.AreEqual(TimeSpan.FromMilliseconds(ExportFrames.ActualMs(Locate(Mp4, [at]).Single().Actual)), copy.FrameAt); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + + // «Questo istante» at the same instant shows the same frame: «Già copiato», not another file. + var same = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.At, at, null, null, ExportFormat.Png)), ct); + var item = (await bed.ItemsAsync(same.Runs.Single().Id, ct)).Single(); + Assert.AreEqual((ExportItemState.AlreadyCopied, (long?)copy.Id), (item.State, item.CopyId)); + Assert.HasCount(1, Fingerprint.Of(bed.Usb)); + } + + [TestMethod] + public async Task OnlyAStillVideoGivesItsFrameAndACopyIsAlwaysTheWholeVideo() + { + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var video = (await SaveVideoAsync(bed, bed.Marta, "982", Mp4, ".mp4")).Media[0]; + var other = (await SaveVideoAsync(bed, bed.Marta, "983", TestVideos.Mov(Stream), ".mov")).Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + ExportFramesRequest Still(TimeSpan? at = null, TimeSpan? every = null, int? count = null) => new(FrameMode.Still, at, every, count, ExportFormat.Png); + + // No analysis, «In movimento», «Non analizzabile»: nothing is recorded. + foreach (var analysis in new[] + { + null, + new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Moving, Make.T0), + new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.NotAnalyzable, Make.T0, null, VideoAnalysisNotes.AllDark), + }) + { + if (analysis is not null) + { + await bed.Db.VideoAnalyses.SetAsync(analysis, ct); + } + + var none = await bed.Service.PlanAsync(Frames(video, Still()), ct); + Assert.AreEqual((0, 1), (none.Frames, none.NotStill), analysis?.Outcome.ToString()); + Assert.IsEmpty((await bed.CopyAsync(Frames(video, Still()), ct)).Runs); + } + + // One video, nothing but the format (answer 46). + await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.Zero), ct); + foreach (var wrong in new[] + { + Frames(video, Still(at: TimeSpan.Zero)), + Frames(video, Still(every: TimeSpan.FromSeconds(1))), + Frames(video, Still(count: 1)), + new ExportJobRequest(new ExportSelection.Media([video.Id, other.Id]), Frames: Still()), + new ExportJobRequest(new ExportSelection.Entries([video.EntryId]), Frames: Still()), + new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id), Frames: Still()), + }) + { + await Assert.ThrowsExactlyAsync(() => bed.Service.PlanAsync(wrong, ct)); + await Assert.ThrowsExactlyAsync(() => bed.Service.StartAsync(wrong, ct)); + } + + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + Assert.IsEmpty(await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)); + + // «Copia in…» of a still video copies the whole video and nothing else, byte for byte (answer 39). + await bed.CopyAccountAsync(bed.Marta, ct: ct); + var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct); + Assert.HasCount(2, copies); + Assert.IsTrue(copies.All(c => c.Variant == ExportVariant.Whole && c.FrameAt is null), string.Join(", ", copies)); + CollectionAssert.AreEqual(Mp4, await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, video), ct)); + Assert.HasCount(2, Fingerprint.Of(bed.Usb)); + } + /// A video of one still picture shown for . private static byte[] LongStill(int seconds) { diff --git a/tests/Febe.Tests/Library/StillVideoServiceTests.cs b/tests/Febe.Tests/Library/StillVideoServiceTests.cs index dce0474..2508463 100644 --- a/tests/Febe.Tests/Library/StillVideoServiceTests.cs +++ b/tests/Febe.Tests/Library/StillVideoServiceTests.cs @@ -360,8 +360,275 @@ public sealed class StillVideoServiceTests Assert.AreEqual((2, 1, 1), (service.Progress.Done, service.Progress.Still, service.Progress.Moving)); } + [TestMethod] + [DataRow(LongWorkKind.Import)] + [DataRow(LongWorkKind.Export)] + [DataRow(LongWorkKind.Rebuild)] + [DataRow(LongWorkKind.FrameDownload)] + public async Task TheJobNeverWorksTogetherWithALongWork(LongWorkKind kind) + { + // Answer 41: import, copies and rebuild (and a zip of frames); the one that starts during an analysis is never + // made to wait: the job gives its video up. + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, video) = await SaveVideoAsync(library, "1", StillVideo(20)); + var gate = new LongWorkGate(); + var blocker = new Blocker(library.Layout.FullPath(account, video.RelativePath!)); + using var service = new StillVideoService(Environment(library, gate) with { Analyser = blocker.Analyse }); + + await service.StartAsync(new ExportSelection.Account(account.Id), ct); + await blocker.Started.Task.WaitAsync(Patience, ct); + Assert.IsTrue(gate.TryEnter(kind, out var lease, out _), "the job holds no lease"); + using (lease) + { + await blocker.Cancelled.Task.WaitAsync(Patience, ct); + await UntilAsync(() => service.Progress.Waiting == StillVideoText.LongWork && service.Progress.CurrentMediaId is null, ct); + Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct)); + Assert.AreEqual((true, 0, 1), (service.Progress.Running, service.Progress.Done, blocker.Calls)); + } + + await service.Job.WaitAsync(Patience, ct); + Assert.AreEqual((1, 1, 2), (service.Progress.Done, service.Progress.Still, blocker.Calls)); + } + + [TestMethod] + public async Task AFileGoneOrChangedIsSkippedAndTheJobGoesOn() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, first) = await SaveVideoAsync(library, "1", StillVideo(21)); + var (_, gone) = await SaveVideoAsync(library, "2", StillVideo(22)); + var (_, changed) = await SaveVideoAsync(library, "3", StillVideo(23)); + var (_, replaced) = await SaveVideoAsync(library, "4", StillVideo(24)); + var (_, last) = await SaveVideoAsync(library, "5", MovingVideo()); + var calls = new ConcurrentQueue(); + var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!), cancelOnly: false); + using var service = new StillVideoService(Environment(library) with + { + Analyser = (path, budget, token) => + { + calls.Enqueue(path); + return blocker.Analyse(path, budget, token); + }, + }); + + // While the first one is analysed: a file goes, one changes on disk, one is replaced in the database («Tieni il più + // grande», a rebuild), so that its old analysis would be of another file. + await service.StartAsync(new ExportSelection.Account(account.Id), ct); + await blocker.Started.Task.WaitAsync(Patience, ct); + File.Delete(library.Layout.FullPath(account, gone.RelativePath!)); + await File.WriteAllBytesAsync(library.Layout.FullPath(account, changed.RelativePath!), StillVideo(25), ct); + await library.Db.Media.UpdateAsync((await library.Db.Media.GetAsync(replaced.Id, ct))! with { Sha256 = Make.Sha(77) }, ct); + blocker.Release(); + await service.Job.WaitAsync(Patience, ct); + + var progress = service.Progress; + Assert.AreEqual((5, 5, 1, 1, 0, 3), (progress.Total, progress.Done, progress.Still, progress.Moving, progress.NotAnalyzable, progress.Skipped)); + Assert.AreEqual("Analizzati 2 video: 1 fermo, 1 in movimento, 3 saltati", StillVideoText.Summary(progress)); + Assert.HasCount(2, calls, "only the files that are the ones recorded are analysed"); + foreach (var sha in new[] { gone.Sha256!, changed.Sha256!, replaced.Sha256!, Make.Sha(77) }) + { + Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(sha, ct), "nothing is stored for a video left out"); + } + + Assert.IsNotNull(await library.Db.VideoAnalyses.GetAsync(last.Sha256!, ct)); + + // Put back, the changed one is analysed when asked again: nothing said it was done. + Assert.AreEqual(3, (await service.PlanAsync(new ExportSelection.Account(account.Id), ct)).ToAnalyse); + } + + [TestMethod] + public async Task AnUnexpectedErrorSkipsTheVideoAndTheLogHasNoPath() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, first) = await SaveVideoAsync(library, "1", StillVideo(26)); + var (_, second) = await SaveVideoAsync(library, "2", MovingVideo()); + var firstPath = library.Layout.FullPath(account, first.RelativePath!); + var log = new ConcurrentQueue(); + using var service = new StillVideoService(Environment(library) with + { + Log = log.Enqueue, + Analyser = (path, budget, token) => path == firstPath + ? throw new InvalidOperationException("guasto in " + path) + : RealAnalysis(path, budget, token), + }); + + await service.StartAsync(new ExportSelection.Account(account.Id), ct); + await service.Job.WaitAsync(Patience, ct); + + Assert.AreEqual((2, 1, 1), (service.Progress.Done, service.Progress.Moving, service.Progress.Skipped)); + Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct)); + Assert.IsNotNull(await library.Db.VideoAnalyses.GetAsync(second.Sha256!, ct)); + var line = log.Single(); + Assert.AreEqual("Un video non si è potuto analizzare (InvalidOperationException).", line, "the type only: no path, no message (rule 10)"); + } + + [TestMethod] + public async Task AVideoAnalysedFromTheViewerMeanwhileIsCountedNotAnalysedAgain() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, video) = await SaveVideoAsync(library, "1", StillVideo(27)); + var session = new FakeSessionState { InSession = true }; + var calls = new ConcurrentQueue(); + using var service = new StillVideoService(Environment(library) with { Session = session, Analyser = Counting(calls) }); + + await service.StartAsync(new ExportSelection.Account(account.Id), ct); + await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct); + Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(video.Id, ct)).Kind, "the viewer does not wait for the session (answer 43)"); + session.InSession = false; + await service.Job.WaitAsync(Patience, ct); + + Assert.HasCount(1, calls); + Assert.AreEqual((1, 1, 1), (service.Progress.Total, service.Progress.Done, service.Progress.Still)); + } + + [TestMethod] + public async Task TheViewerAnalysesOneVideoAtATimeAndACancelledRequestStoresNothing() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, first) = await SaveVideoAsync(library, "1", StillVideo(28)); + var (_, second) = await SaveVideoAsync(library, "2", MovingVideo()); + var blocker = new Blocker(library.Layout.FullPath(account, first.RelativePath!)); + var atWork = 0; + var most = 0; + using var service = new StillVideoService(Environment(library) with + { + Analyser = (path, budget, token) => + { + var now = Interlocked.Increment(ref atWork); + InterlockedMax(ref most, now); + try + { + return blocker.Analyse(path, budget, token); + } + finally + { + Interlocked.Decrement(ref atWork); + } + }, + }); + + using var closed = CancellationTokenSource.CreateLinkedTokenSource(ct); + var one = service.AnalyseNowAsync(first.Id, closed.Token); + await blocker.Started.Task.WaitAsync(Patience, ct); + var two = service.AnalyseNowAsync(second.Id, ct); + Assert.IsFalse(two.IsCompleted, "the second waits for the first"); + + // The page that asked the first closed: its request ends, nothing is stored, and the second is answered. + await closed.CancelAsync(); + await Assert.ThrowsAsync(() => one); + Assert.AreEqual(VideoAnalysisOutcome.Moving, (await two.WaitAsync(Patience, ct)).Analysis!.Outcome); + Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(first.Sha256!, ct)); + Assert.AreEqual(1, Volatile.Read(ref most)); + Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(first.Id, ct)).Kind, "asked again, it is analysed"); + } + + [TestMethod] + public async Task AFileKeepsItsAnalysisUnderEveryEntryAndLosesItWhenItIsAnother() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, first) = await SaveVideoAsync(library, "1", StillVideo(29)); + using var service = new StillVideoService(Environment(library)); + Assert.AreEqual(StillVideoAnswerKind.Analysed, (await service.AnalyseNowAsync(first.Id, ct)).Kind); + + // The same file under an entry added later (an import): already analysed, with no work. + var again = (await library.Db.Entries.AddAsync( + Make.Entry(account.Id, "9", Make.T0.AddMinutes(9)), [Make.Stored(Make.Video(1), first.Sha256!, first.RelativePath!)], ct)).Stored; + var plan = await service.PlanAsync(new ExportSelection.Entries([again.Entry.Id]), ct); + Assert.AreEqual((0, 1), (plan.ToAnalyse, plan.AlreadyAnalysed)); + + // A row of an algorithm newer than this Febe's (a database opened by a later version first): not analysed again. + await library.Db.VideoAnalyses.SetAsync(new VideoAnalysis(first.Sha256!, StillVideoAnalyzer.Algorithm + 1, VideoAnalysisOutcome.Moving, Make.T0), ct); + Assert.AreEqual(0, (await service.PlanAsync(new ExportSelection.Account(account.Id), ct)).ToAnalyse); + + // Another file in its place: its SHA-256 has no analysis, so it is to analyse. + await library.Db.Media.UpdateAsync((await library.Db.Media.GetAsync(first.Id, ct))! with { Sha256 = Make.Sha(78) }, ct); + plan = await service.PlanAsync(new ExportSelection.Media([first.Id]), ct); + Assert.AreEqual((1, 0), (plan.ToAnalyse, plan.AlreadyAnalysed)); + } + + [TestMethod] + public async Task InterrompiWhileItWaitsEndsTheJobAndANewOneStartsFromZero() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, video) = await SaveVideoAsync(library, "1", StillVideo(30)); + var session = new FakeSessionState { InSession = true }; + using var service = new StillVideoService(Environment(library) with { Session = session }); + var selection = new ExportSelection.Account(account.Id); + + Assert.IsFalse(service.Stop().Stopped, "nothing to stop"); + await service.StartAsync(selection, ct); + await UntilAsync(() => service.Progress.Waiting == StillVideoText.InSession, ct); + service.Stop(); + await service.Job.WaitAsync(Patience, ct); + Assert.AreEqual((false, true, 1, 0), (service.Progress.Running, service.Progress.Stopped, service.Progress.Total, service.Progress.Done)); + Assert.IsNull(service.Progress.Waiting); + + session.InSession = false; + var started = await service.StartAsync(selection, ct); + Assert.AreEqual((true, false, 1, 0), (started.Running, started.Stopped, started.Total, started.Done)); + await service.Job.WaitAsync(Patience, ct); + Assert.AreEqual((1, 1, false), (service.Progress.Done, service.Progress.Still, service.Progress.Stopped)); + Assert.IsNotNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct)); + } + + [TestMethod] + public async Task ClosingFebeLeavesTheVideoAtWorkAndStoresNothing() + { + var ct = TestContext.CancellationToken; + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var (account, video) = await SaveVideoAsync(library, "1", StillVideo(31)); + var blocker = new Blocker(library.Layout.FullPath(account, video.RelativePath!)); + var service = new StillVideoService(Environment(library) with { Analyser = blocker.Analyse }); + await service.StartAsync(new ExportSelection.Account(account.Id), ct); + await blocker.Started.Task.WaitAsync(Patience, ct); + + service.Dispose(); + service.Dispose(); + await service.Job.WaitAsync(Patience, ct); + + Assert.IsFalse(service.Progress.Running); + Assert.IsNull(await library.Db.VideoAnalyses.GetAsync(video.Sha256!, ct)); + await Assert.ThrowsExactlyAsync(() => service.AnalyseNowAsync(video.Id, ct)); + await Assert.ThrowsExactlyAsync(() => service.StartAsync(new ExportSelection.Account(account.Id), ct)); + } + + [TestMethod] + public void TheTextsCountInItalian() + { + // The confirmation and the end of the job, one and many (the words of the design, questions 41 and 44). + Assert.AreEqual("28 video da analizzare · 12 già analizzati · le 5 foto si saltano", StillVideoText.PlanSummary(new StillVideoPlan(28, 12, 5, 0))); + Assert.AreEqual("1 video da analizzare · 1 già analizzato · la foto si salta · 1 video non presente in libreria", StillVideoText.PlanSummary(new StillVideoPlan(1, 1, 1, 1))); + Assert.AreEqual("1.200 video da analizzare · 3 video non presenti in libreria", StillVideoText.PlanSummary(new StillVideoPlan(1200, 0, 0, 3))); + StillVideoProgress Ended(int still, int moving, int not, int skipped) => new(false, still + moving + not + skipped, still + moving + not + skipped, still, moving, not, skipped, false, null, null); + Assert.AreEqual("Analizzati 28 video: 3 fermi, 24 in movimento, 1 non analizzabile", StillVideoText.Summary(Ended(3, 24, 1, 0))); + Assert.AreEqual("Analizzato 1 video: 1 fermo, 0 in movimento, 1 saltato", StillVideoText.Summary(Ended(1, 0, 0, 1))); + Assert.AreEqual("Analizzati 2 video: 0 fermi, 0 in movimento, 2 non analizzabili, 2 saltati", StillVideoText.Summary(Ended(0, 0, 2, 2))); + } + // ------------------------------------------------------------------------------------------------- helpers + private static void InterlockedMax(ref int target, int value) + { + int seen; + while ((seen = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, seen) != seen) + { + } + } + private static byte[] StillVideo(int seed, bool audio = false) { var photo = PcmVideos.Photo(seed); diff --git a/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs b/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs index e6c2832..3fc61ab 100644 --- a/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs +++ b/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs @@ -1,3 +1,4 @@ +using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.H264; using Febe.Core.Domain; using Febe.Core.Export; @@ -328,6 +329,154 @@ public sealed class StillVideoAnalyzerTests Assert.ThrowsExactly(() => StillVideoAnalyzer.Analyse(again, TimeSpan.FromSeconds(30), cancelled.Token)); } + [TestMethod] + [DataRow(2)] + [DataRow(3)] + public void AClipOfAFewEqualPicturesIsStill(int pictures) + { + // 0,07 and 0,1 seconds: every picture is looked at. + var photo = PcmVideos.Photo(20); + var result = Analyse(PcmVideos.Mp4(pictures, _ => photo, audio: true)); + Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); + Assert.AreEqual(pictures, result.Sampled); + Assert.AreEqual(0L, result.FrameAtMs, "the first of equally sharp ones"); + } + + [TestMethod] + public void StrongGrainAndAPulsingLightAreNotMotion() + { + var photo = PcmVideos.Photo(21); + var grain = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Noise(photo, 8, 500 + i))); + Assert.AreEqual(VideoAnalysisOutcome.Still, grain.Outcome, Describe(grain)); + Assert.IsNull(grain.Note); + + // The light goes from full to 60 % and back, twice: the frame chosen is one at (nearly) full light. + double Light(long i) => 0.8 + (0.2 * Math.Cos(i * 4 * Math.PI / 30)); + var pulsing = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Fade(photo, Light(i)))); + Assert.AreEqual(VideoAnalysisOutcome.Still, pulsing.Outcome, Describe(pulsing)); + Assert.IsGreaterThan(0.85, Light(pulsing.FrameAtMs!.Value * PcmVideos.Fps / 1000), Describe(pulsing)); + } + + [TestMethod] + public void ANightPhotoIsStillNotAllDark() + { + // Black all over but a lit sign of 16 × 16 pixels: a picture, not a black video (answer 42). + var night = PcmVideos.Sticker(PcmVideos.Black(), 60, 100, 16, 16); + var result = Analyse(PcmVideos.Mp4(30, _ => night)); + Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); + Assert.IsNull(result.Note); + } + + [TestMethod] + public void ADarkFrameIsNeverChosenEvenWhenItsGrainIsSharper() + { + // Nine nearly black pictures full of grain (a camera that starts in the dark), then a soft gradient with no + // detail: the Laplacian of the grain is larger, yet «Salva il fotogramma» must never save black (answer 45). + var soft = PcmVideos.Flat(120); + for (var y = 0; y < PcmVideos.Height; y++) + { + for (var x = 0; x < PcmVideos.Width; x++) + { + soft.Y[(y * PcmVideos.Width) + x] = (byte)(60 + ((x + y) / 4)); + } + } + + H264PcmPicture Dark(int i) => PcmVideos.Noise(PcmVideos.Black(), 12, 900 + i); + var result = Analyse(PcmVideos.Mp4(30, i => i < 9 ? Dark(i) : soft)); + Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); + Assert.IsGreaterThanOrEqualTo(Ms(9), result.FrameAtMs!.Value, Describe(result)); + + // The grain is a real trap (the same grain on a grey that is not dark is far sharper than the gradient), and a + // video of it alone is all dark: no frame to save. + var lit = Analyse(PcmVideos.Mp4(9, i => PcmVideos.Noise(PcmVideos.Sticker(PcmVideos.Flat(60), 60, 100, 16, 16), 6, 900 + i))); + Assert.AreEqual(VideoAnalysisOutcome.Still, lit.Outcome, Describe(lit)); + Assert.IsGreaterThan(result.Sharpness, lit.Sharpness); + var dark = Analyse(PcmVideos.Mp4(9, Dark)); + Assert.AreEqual(VideoAnalysisNotes.AllDark, dark.Note, Describe(dark)); + Assert.IsNull(dark.FrameAt); + } + + [TestMethod] + public void AVideoHalfTurnedIsUprightToo() + { + var photo = PcmVideos.Photo(22); + var result = Analyse(PcmVideos.Mp4(12, _ => photo, rotation: 180)); + Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result)); + Assert.AreEqual(180, result.Rotation); + } + + [TestMethod] + public void TheContainerDoesNotChangeTheOutcome() + { + var photo = PcmVideos.Photo(23); + var still = PcmVideos.Stream("pcm", 30, _ => photo); + var pan = PcmVideos.Stream("pcm", 30, i => PcmVideos.Shift(photo, 3 * i)); + foreach (var (name, build) in new (string, Func)[] + { + ("MOV", es => TestVideos.Mov(es)), + ("MP4 a frammenti", es => TestVideos.FragmentedMp4(es)), + ("Matroska", es => TestVideos.Matroska(es)), + ("AVI (i parametri in ogni fotogramma chiave, come si scrive un AVI)", es => TestVideos.Avi(es.WithParameterSetsEverywhere())), + }) + { + var fixedPicture = Analyse(build(still)); + Assert.AreEqual(VideoAnalysisOutcome.Still, fixedPicture.Outcome, $"{name}: {Describe(fixedPicture)}"); + Assert.IsNotNull(fixedPicture.FrameAt, name); + var moving = Analyse(build(pan)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, $"{name}: {Describe(moving)}"); + } + } + + [TestMethod] + public void AVideoWithNoDurationIsNotAnalysable() + { + // Two samples at the same time, and headers that say zero: nothing tells how long the video is. + var es = PcmVideos.Stream("pcm", 2, i => PcmVideos.Photo(24 + i)); + var track = new Mp4OutputTrack + { + IsVideo = true, + Timescale = TestVideos.Timescale, + Samples = [.. Enumerable.Range(0, 2).Select(i => new Mp4OutputSample(es.LengthPrefixed(i).Length, 0, 0, true))], + WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)), + Width = es.Width, + Height = es.Height, + AvcConfiguration = es.AvcC, + }; + using var output = new MemoryStream(); + Mp4Writer.Write(output, [track]); + + var result = Analyse(output.ToArray()); + Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, result.Outcome, Describe(result)); + Assert.AreEqual(VideoAnalysisNotes.DurationUnknown, result.Note); + } + + [TestMethod] + public void ADamagedStreamIsUnreadableNeverStillFromOneFrame() + { + // The headers are whole, the pictures are cut to a few bytes, all but the first: one frame alone says nothing of + // the video. + var es = PcmVideos.Stream("pcm", 30, _ => PcmVideos.Photo(26)); + for (var i = 3; i < es.Count; i++) + { + es.Units[i] = [.. es.Units[i].Select(n => n[..Math.Min(n.Length, 6)])]; + } + + var result = Analyse(TestVideos.Mp4(es)); + Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, result.Outcome, Describe(result)); + Assert.AreEqual(VideoAnalysisNotes.Unreadable, result.Note); + } + + [TestMethod] + public void EveryThresholdIsTheOneAgreed() + { + // Answer 44 of Alberto (29 November 2026) and docs/decisioni.md: a change raises Algorithm, so that the videos + // already analysed are known as of the older rule. + Assert.AreEqual( + (1, 7, 32, 32.0, 2.0, 12.0, 3.0, 0.05), + (StillVideoAnalyzer.Algorithm, StillVideoAnalyzer.Samples, StillVideoAnalyzer.GridSize, StillVideoAnalyzer.DarkLevel, + StillVideoAnalyzer.UniformSpread, StillVideoAnalyzer.BlockThreshold, StillVideoAnalyzer.MeanThreshold, StillVideoAnalyzer.AreaThreshold)); + } + private static StillVideoResult Analyse(byte[] video) { using var stream = new MemoryStream(video); diff --git a/tests/Febe.Tests/Web/DemoStillVideoTests.cs b/tests/Febe.Tests/Web/DemoStillVideoTests.cs index 59c2fcb..0de82d9 100644 --- a/tests/Febe.Tests/Web/DemoStillVideoTests.cs +++ b/tests/Febe.Tests/Web/DemoStillVideoTests.cs @@ -10,6 +10,7 @@ using Febe.Core.Library.StillVideos; using Febe.Tests.Support; using Febe.Tests.Web.Support; using Febe.Web.Demo; +using Microsoft.Extensions.DependencyInjection; namespace Febe.Tests.Web; @@ -202,6 +203,57 @@ public sealed class DemoStillVideoTests Assert.HasCount(2, (await OkAsync(HttpMethod.Get, "/api/library?kind=stillvideos&limit=100")).Items("tiles").ToList(), "the moving file is never still"); } + [TestMethod] + [DataRow(9)] + [DataRow(20)] + [Timeout(600_000, CooperativeCancellation = true)] + public async Task WhateverTheHourTheDemoHasItsStillVideos(int hour) + { + // The demo is built around its local time (posts of «oggi» are there or not yet): the still videos never depend + // on it. The hour is the zone's, so the test asks for the same thing whenever it runs. + var ct = TestContext.CancellationToken; + using var temp = new TempFolder("demo-fermi-ore"); + var offset = TimeSpan.FromMinutes(Math.Round(((hour + 0.5) * 60) - DateTimeOffset.UtcNow.TimeOfDay.TotalMinutes)); + offset = offset > TimeSpan.FromHours(12) ? offset - TimeSpan.FromHours(24) : offset < TimeSpan.FromHours(-12) ? offset + TimeSpan.FromHours(24) : offset; + var zone = TimeZoneInfo.CreateCustomTimeZone("prova", offset, "prova", "prova"); + await using var demo = await DemoHost.StartAsync(new DemoOptions(0, zone, temp.Path), ct); + + Assert.HasCount(2, demo.World.StillVideoFiles); + var tiles = (await demo.Storage.Entries.QueryLibraryAsync( + new Febe.Core.Storage.LibraryQuery { Filter = new Febe.Core.Storage.LibraryFilter { Kind = Febe.Core.Storage.LibraryKindFilter.StillVideos }, Limit = 100 }, + ct)).Tiles; + Assert.HasCount(2, tiles, "one post and one story"); + var accounts = await demo.Storage.Accounts.ListAsync(ct); + var marta = accounts.Single(a => a.Username == DemoStillVideos.StillAccount).Id; + Assert.AreEqual(1, tiles.Count(t => t.AccountId == marta)); + var entries = await Task.WhenAll(tiles.Select(async t => (await demo.Storage.Entries.GetAsync(t.EntryId, ct))!)); + Assert.AreEqual(1, entries.Count(e => e.Kind == EntryKind.Story && e.AccountId != marta)); + Assert.IsTrue(entries.All(e => e.PublishedAt <= demo.App.Services.GetRequiredService().Now), "published, not to come"); + + var outcomes = new List<(VideoAnalysisOutcome, string?)>(); + var unanalysed = 0; + foreach (var video in await VideosAsync(demo, marta, ct)) + { + if (await demo.Storage.VideoAnalyses.GetAsync(video.Sha256!, ct) is { } analysis) + { + outcomes.Add((analysis.Outcome, analysis.Note)); + } + else + { + unanalysed++; + } + } + + CollectionAssert.AreEquivalent( + new (VideoAnalysisOutcome, string?)[] + { + (VideoAnalysisOutcome.Still, null), (VideoAnalysisOutcome.Moving, null), (VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.TooSlow), + }, + outcomes.Distinct().ToArray(), + string.Join(", ", outcomes)); + Assert.IsGreaterThan(0, unanalysed, "«È un video fermo?» has a video to be tried on"); + } + private static async Task UnanalysedVideoAsync(DemoHost demo, long accountId, CancellationToken ct) { foreach (var media in await VideosAsync(demo, accountId, ct)) @@ -218,17 +270,26 @@ public sealed class DemoStillVideoTests /// The present videos of an account in the library, newest first. private static async Task> VideosAsync(DemoHost demo, long accountId, CancellationToken ct) { - var page = await demo.Storage.Entries.QueryLibraryAsync( - new Febe.Core.Storage.LibraryQuery { Filter = new Febe.Core.Storage.LibraryFilter { AccountIds = [accountId] }, Mode = Febe.Core.Storage.MosaicMode.Files, Limit = 1000 }, - ct); + // Every page: @marta.demo has more than a thousand files, and the videos the demo analysed can be among the oldest + // (the pictures that no copy uses depend on the hour). var videos = new List(); - foreach (var tile in page.Tiles.Where(t => t.CoverKind == MediaKind.Video)) + Febe.Core.Storage.LibraryCursor? cursor = null; + do { - if (await demo.Storage.Media.GetAsync(tile.CoverMediaId!.Value, ct) is { Sha256: not null } media && EntryStateRules.IsPresent(media.State)) + var page = await demo.Storage.Entries.QueryLibraryAsync( + new Febe.Core.Storage.LibraryQuery { Filter = new Febe.Core.Storage.LibraryFilter { AccountIds = [accountId] }, Mode = Febe.Core.Storage.MosaicMode.Files, Cursor = cursor, Limit = 500 }, + ct); + foreach (var tile in page.Tiles.Where(t => t.CoverKind == MediaKind.Video)) { - videos.Add(media); + if (await demo.Storage.Media.GetAsync(tile.CoverMediaId!.Value, ct) is { Sha256: not null } media && EntryStateRules.IsPresent(media.State)) + { + videos.Add(media); + } } + + cursor = page.Older; } + while (cursor is not null); return videos; } diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs new file mode 100644 index 0000000..abadd48 --- /dev/null +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.StillVideos.cs @@ -0,0 +1,386 @@ +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». 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); + + 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()); + } + + [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()); + 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()); + } + + // ------------------------------------------------------------------------------------------------- support + + /// + /// 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}"))); + 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()); + } +} diff --git a/tests/Febe.Tests/Web/ExportInterfaceTests.cs b/tests/Febe.Tests/Web/ExportInterfaceTests.cs index fdf942c..10536a3 100644 --- a/tests/Febe.Tests/Web/ExportInterfaceTests.cs +++ b/tests/Febe.Tests/Web/ExportInterfaceTests.cs @@ -11,7 +11,8 @@ namespace Febe.Tests.Web; /// 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. Tappa -/// E3 (formats, frames, the conversion of the library) is in ExportInterfaceTests.Formats.cs. +/// E3 (formats, frames, the conversion of the library) is in ExportInterfaceTests.Formats.cs, tappa E4 (still videos) in +/// ExportInterfaceTests.StillVideos.cs. /// [TestClass] public sealed partial class ExportInterfaceTests diff --git a/tests/Febe.Tests/Web/StillVideosApiTests.cs b/tests/Febe.Tests/Web/StillVideosApiTests.cs index 67aeed5..7b60b5e 100644 --- a/tests/Febe.Tests/Web/StillVideosApiTests.cs +++ b/tests/Febe.Tests/Web/StillVideosApiTests.cs @@ -343,6 +343,111 @@ public sealed class StillVideosApiTests Assert.IsFalse((await server.GetJsonAsync("/api/still-videos/progress")).Bool("running")); } + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task EverySelectionIsCountedAndTheSameFileIsAnalysedOnce() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var luca = await server.Db.Accounts.AddAsync(Make.Account("luca.demo", "200")); + var same = Still(14); + var first = await WebLibrary.AddPostAsync(server, marta, "uno", Make.T0.AddDays(-1), WebLibrary.Video(same), WebLibrary.Photo(4), WebLibrary.Photo(5)); + var twin = (await server.Db.Entries.AddAsync( + Make.Entry(marta.Id, "due", Make.T0.AddDays(-2)), + [Make.Stored(Make.Video(1), first.Media[0].Sha256!, first.Media[0].RelativePath!)], + ct)).Stored; + var other = await WebLibrary.AddPostAsync(server, luca, "tre", Make.T0.AddDays(-3), WebLibrary.Video(Moving())); + Assert.AreEqual(first.Media[0].Sha256, twin.Media[0].Sha256); + + async Task PlanAsync(object selection) + { + var (status, plan) = await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection); + Assert.AreEqual(HttpStatusCode.OK, status, plan.ToString()); + return plan; + } + + // The files, the entries, a filter in both modes, an account: one file counts once, the photos are told apart. + foreach (var (selection, toAnalyse, photos) in new (object, int, int)[] + { + (new { mediaIds = new[] { first.Media[0].Id, first.Media[1].Id } }, 1, 1), + (new { mediaIds = new[] { first.Media[1].Id, first.Media[2].Id } }, 0, 2), + (new { entryIds = new[] { first.Entry.Id, twin.Entry.Id, other.Entry.Id } }, 2, 2), + (new { query = $"accounts={marta.Id}", mode = "grouped" }, 1, 2), + (new { query = "kind=videos", mode = "files" }, 2, 0), + (new { query = "kind=stillvideos", mode = "files" }, 0, 0), + (new { accountId = luca.Id }, 1, 0), + }) + { + var plan = await PlanAsync(selection); + Assert.AreEqual((toAnalyse, photos), (plan.Int("toAnalyse"), plan.Int("photosSkipped")), $"{JsonSerializer.Serialize(selection)}: {plan}"); + } + + // Photos only: nothing to start, and the job does not. + var none = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", new { mediaIds = new[] { first.Media[1].Id } })).Body; + Assert.AreEqual((false, 0), (none.Bool("running"), none.Int("total")), none.ToString()); + + // Analysed once, under either post; the second asks nothing more. + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", new { accountId = marta.Id })).Status); + await WebLibrary.WaitAsync(async () => !(await server.GetJsonAsync("/api/still-videos/progress")).Bool("running"), "the job ends"); + Assert.AreEqual(1, (await server.GetJsonAsync("/api/still-videos/progress")).Int("still")); + var shown = (await server.GetJsonAsync($"/api/entries/{twin.Entry.Id}")).Items("media").Single().GetProperty("still"); + Assert.AreEqual("still", shown.Str("outcome"), "the same file under another post has the same analysis"); + var tiles = (await server.GetJsonAsync("/api/library?kind=stillvideos&limit=50")).Items("tiles").Select(t => t.Long("id")).ToArray(); + CollectionAssert.AreEquivalent(new[] { first.Entry.Id, twin.Entry.Id }, tiles); + Assert.AreEqual(1, (await PlanAsync(new { query = "kind=stillvideos", mode = "grouped" })).Int("alreadyAnalysed")); + + // An analysis of an algorithm newer than this Febe's is current (there is none older than 1 yet). + await server.Db.VideoAnalyses.SetAsync(new VideoAnalysis(other.Media[0].Sha256!, StillVideoAnalyzer.Algorithm + 1, VideoAnalysisOutcome.Moving, server.Clock.Now), ct); + var newer = (await server.GetJsonAsync($"/api/entries/{other.Entry.Id}")).Items("media").Single().GetProperty("still"); + Assert.AreEqual(("moving", true), (newer.Str("outcome"), newer.Bool("current")), newer.ToString()); + Assert.AreEqual(0, (await PlanAsync(new { accountId = luca.Id })).Int("toAnalyse")); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheFrameOfAPhotoAnUnknownOrAMissingFileIsRefused() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var post = await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(Still(15)), WebLibrary.Photo(4)); + var video = post.Media[0]; + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still")).Status); + + Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{post.Media[1].Id}/still/frame")).Status); + Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, "/api/media/999999/still/frame")).Status); + + // Another file in its place: the analysis was of the old one, so there is no frame to save. + var sha = video.Sha256!; + await server.Db.Media.UpdateAsync((await server.Db.Media.GetAsync(video.Id, ct))! with { Sha256 = Make.Sha(91) }, ct); + var (replaced, body) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.Id}/still/frame"); + Assert.AreEqual(HttpStatusCode.Conflict, replaced); + StringAssert.StartsWith(body.Str("message"), StillVideoText.NotStill); + await server.Db.Media.UpdateAsync((await server.Db.Media.GetAsync(video.Id, ct))! with { Sha256 = sha }, ct); + + File.Delete(WebLibrary.PathOf(server, marta, video)); + Assert.AreEqual(HttpStatusCode.NotFound, (await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video.Id}/still/frame?download=1")).Status); + Assert.AreEqual(VideoAnalysisOutcome.Still, (await server.Db.VideoAnalyses.GetAsync(sha, ct))!.Outcome, "what was found of the file stays"); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheOpenPagesHearOfAnAnalysisOnce() + { + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var video = (await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(Still(16)))).Media[0]; + var changes = server.Changes.SubscribeAsync().GetAsyncEnumerator(); + var next = changes.MoveNextAsync().AsTask(); + + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still")).Status); + + Assert.IsTrue(await next.WaitAsync(TimeSpan.FromSeconds(20)), "the library of the open pages is read again"); + Assert.AreEqual(("fermi", (long?)marta.Id), (changes.Current.Reason, changes.Current.AccountId)); + await changes.DisposeAsync(); + } + // ------------------------------------------------------------------------------------------------- support private static readonly FebeWebOptions Options = new() { Edition = FebeEdition.Desktop, Access = AccessMode.None };