diff --git a/src/Febe.Core/Export/ExportCopier.cs b/src/Febe.Core/Export/ExportCopier.cs index 5099b4e..c46e862 100644 --- a/src/Febe.Core/Export/ExportCopier.cs +++ b/src/Febe.Core/Export/ExportCopier.cs @@ -576,9 +576,23 @@ public sealed class ExportCopier(ExportEnvironment env) } var sha = library.Sha256; + var (mode, count) = x.Frames ?? (FrameMode.At, 1); + TimeSpan? chosen = null; + if (mode == FrameMode.Still && !string.Equals(batch[0].SourceSha256, sha, StringComparison.Ordinal)) + { + // The file changed since the frame was chosen (a job that waited): the instant is the one of the analysis of + // the new file, or there is none (the item keeps the one it was recorded with, the copy says the true one). + if (await _env.Storage.VideoAnalyses.GetAsync(sha, ct).ConfigureAwait(false) is not { Outcome: VideoAnalysisOutcome.Still, FrameAt: { } at }) + { + await EndAllAsync(batch, ExportItemState.Skipped, ExportText.Notes.NotStill, null).ConfigureAwait(false); + return null; + } + + chosen = at; + } + batch = batch.Select(i => string.Equals(i.SourceSha256, sha, StringComparison.Ordinal) ? i : i with { SourceSha256 = sha }).ToList(); var format = batch[0].Format; - var (mode, count) = x.Frames ?? (FrameMode.At, 1); var firstId = mode == FrameMode.Count ? await exports.FirstItemIdAsync(x.Run.Id, library.Media.Id, ExportVariant.Frame, format, ct).ConfigureAwait(false) ?? batch[0].Id : 0; @@ -625,7 +639,7 @@ public sealed class ExportCopier(ExportEnvironment env) : []; using (reader) { - var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : []; + var targets = info.Available ? reader.Locate([.. batch.Select(i => chosen ?? i.FrameAt ?? TimeSpan.Zero)]) : []; if (targets.Count != batch.Count) { await EndAllAsync(batch, ExportItemState.Skipped, ExportText.Notes.FrameNotAvailable, null).ConfigureAwait(false); diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index b72911e..b6ff08d 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -54,7 +54,8 @@ public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video /// «Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity. /// The instant of a frame row; null otherwise. -public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt); +/// The frame row is one of «Salva il fotogramma»: the new file is named …_fotogramma again. +public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt, bool Still = false); /// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked. /// The formats of this request («Copia in…» → «Cambia»); null: those of the destination. diff --git a/src/Febe.Core/Export/ExportService.cs b/src/Febe.Core/Export/ExportService.cs index ba63aef..1309938 100644 --- a/src/Febe.Core/Export/ExportService.cs +++ b/src/Febe.Core/Export/ExportService.cs @@ -303,9 +303,9 @@ public sealed class ExportService : IAsyncDisposable { await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false); } - else if (request.Exact is { Variant: ExportVariant.Frame }) + else if (request.Exact is { Variant: ExportVariant.Frame } exact) { - await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false); + await ExportRunSettings.SetFramesAsync(store, runId, exact.Still ? FrameMode.Still : FrameMode.At, 1, none).ConfigureAwait(false); } if (request.Exact is not null) diff --git a/src/Febe.Core/Export/ExportText.cs b/src/Febe.Core/Export/ExportText.cs index ed1edd8..7d4e183 100644 --- a/src/Febe.Core/Export/ExportText.cs +++ b/src/Febe.Core/Export/ExportText.cs @@ -39,6 +39,9 @@ public static class ExportText public const string AsIsTooLarge = ImageConversionLosses.AsIsTooLarge; public const string AsIsNotRemuxable = MediaConversionResult.AsIsNotRemuxable; public const string FrameNotAvailable = "FrameNotAvailable"; + + // Tappa E4: «Salva il fotogramma» of a file that changed meanwhile, and is not a still video as far as Febe knows. + public const string NotStill = "NotStill"; public const string TransparencyWhite = ImageConversionLosses.TransparencyWhite; public const string CopiedInAnotherFormat = "CopiedInAnotherFormat"; public const string LostTracks = Mp4Remuxer.LostTracks; @@ -142,6 +145,7 @@ public static class ExportText Notes.AsIsCmyk => "Copiato com'è: immagine CMYK", Notes.AsIsTooLarge => "Copiato com'è: troppo grande per il formato scelto", Notes.FrameNotAvailable => "Fotogramma non disponibile per questo video", + Notes.NotStill => "Il video è cambiato: il file di adesso non è un video fermo, o non è stato analizzato", Notes.TransparencyWhite => "La trasparenza è diventata bianco", Notes.CopiedInAnotherFormat => "Già copiato in un altro formato", ImageConversionLosses.LostTexts => "Non tenuti: testi", diff --git a/src/Febe.Web/Api/EngineApi.cs b/src/Febe.Web/Api/EngineApi.cs index 89eab65..efe7eaa 100644 --- a/src/Febe.Web/Api/EngineApi.cs +++ b/src/Febe.Web/Api/EngineApi.cs @@ -131,8 +131,8 @@ public static class EngineApi /// /// /api/eventi: server-sent events. motore carries the engine (at once, at every change, at least every - /// minute); libreria says the library changed (at most every second and a half); a comment line keeps the - /// stream open. Never contains captions, bodies or addresses. + /// minute); libreria says the library changed (at most every second and a half, one event for each reason + /// there was); a comment line keeps the stream open. Never contains captions, bodies or addresses. /// public static async Task StreamAsync( HttpContext context, @@ -151,6 +151,7 @@ public static class EngineApi var ct = context.RequestAborted; var signals = Channel.CreateBounded(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest }); + var changes = new PendingLibraryChanges(); using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct); var engineTask = Task.Run( async () => @@ -166,7 +167,8 @@ public static class EngineApi { await foreach (var change in library.SubscribeAsync(stop.Token).ConfigureAwait(false)) { - signals.Writer.TryWrite("libreria:" + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange)); + changes.Add(change); + signals.Writer.TryWrite("libreria"); } }, CancellationToken.None); @@ -178,7 +180,6 @@ public static class EngineApi var libraryGap = TimeSpan.FromMilliseconds(1500); var lastEngine = DateTimeOffset.UtcNow; var lastLibrary = DateTimeOffset.MinValue; - string? pendingLibrary = null; var enginePending = false; while (!ct.IsCancellationRequested) @@ -190,7 +191,7 @@ public static class EngineApi wait = lastEngine + Refresh - now; } - if (pendingLibrary is not null && lastLibrary + libraryGap - now < wait) + if (changes.Any && lastLibrary + libraryGap - now < wait) { wait = lastLibrary + libraryGap - now; } @@ -202,14 +203,7 @@ public static class EngineApi await Task.Delay(TimeSpan.FromMilliseconds(300), ct).ConfigureAwait(false); while (signals.Reader.TryRead(out var signal)) { - if (signal == "motore") - { - enginePending = true; - } - else - { - pendingLibrary = signal["libreria:".Length..]; - } + enginePending |= signal == "motore"; } } @@ -223,10 +217,13 @@ public static class EngineApi sent = true; } - if (pendingLibrary is not null && now - lastLibrary >= libraryGap) + if (changes.Any && now - lastLibrary >= libraryGap) { - await WriteAsync(response, "event: libreria\ndata: " + pendingLibrary + "\n\n", ct).ConfigureAwait(false); - pendingLibrary = null; + foreach (var change in changes.Take()) + { + await WriteAsync(response, "event: libreria\ndata: " + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange) + "\n\n", ct).ConfigureAwait(false); + } + lastLibrary = now; sent = true; } diff --git a/src/Febe.Web/Api/ExportApi.cs b/src/Febe.Web/Api/ExportApi.cs index 66f0048..ae3047b 100644 --- a/src/Febe.Web/Api/ExportApi.cs +++ b/src/Febe.Web/Api/ExportApi.cs @@ -310,7 +310,8 @@ public static class ExportApi .OrderBy(l => l.Media.Id == copy.MediaId ? 0 : l.Media.Kind == kind ? 1 : 2) .FirstOrDefault() ?? present[0]; var service = await hub.GetAsync(ct).ConfigureAwait(false); - var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt); + var still = copy.Variant == ExportVariant.Frame && sha == copy.SourceSha256 && ExportFrames.IsSingleName(copy.RelativePath); + var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt, still); var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true, Exact: exact), ct)).ConfigureAwait(false); return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto); }); diff --git a/src/Febe.Web/Library/FebeLibrary.cs b/src/Febe.Web/Library/FebeLibrary.cs index 7898b4d..6556df4 100644 --- a/src/Febe.Web/Library/FebeLibrary.cs +++ b/src/Febe.Web/Library/FebeLibrary.cs @@ -120,9 +120,50 @@ public sealed class LibraryConversionFileResolver(FebeLibrary library) : IConver /// Something changed in the library: the open pages reload what they show. /// When. /// The account concerned, when there is only one. -/// Short machine reason: "stored", "deleted", "account", "import". +/// Short machine reason: "stored", "deleted", "account", "import", "export", "fermi". public sealed record LibraryChange(DateTimeOffset At, long? AccountId, string Reason); +/// +/// The changes a page has not been told yet, one per reason: pages skip some reasons («fermi»), so one must not take the +/// place of another. Two of one reason are told together, with the account only if it is the same. +/// +internal sealed class PendingLibraryChanges +{ + private readonly Dictionary _pending = new(StringComparer.Ordinal); + + public bool Any + { + get + { + lock (_pending) + { + return _pending.Count > 0; + } + } + } + + public void Add(LibraryChange change) + { + lock (_pending) + { + _pending[change.Reason] = _pending.TryGetValue(change.Reason, out var before) && before.AccountId != change.AccountId + ? change with { AccountId = null } + : change; + } + } + + /// The changes to tell, in the order they came in; none is left. + public IReadOnlyList Take() + { + lock (_pending) + { + LibraryChange[] taken = [.. _pending.Values.OrderBy(c => c.At)]; + _pending.Clear(); + return taken; + } + } +} + /// /// Library notifications for the server-sent events (/api/eventi, event libreria). Publishers: the web /// layer itself (deletions, account changes), the download queue () and the import (M7). diff --git a/src/Febe.Web/wwwroot/js/core/shell.js b/src/Febe.Web/wwwroot/js/core/shell.js index 7f5c357..4bbed4e 100644 --- a/src/Febe.Web/wwwroot/js/core/shell.js +++ b/src/Febe.Web/wwwroot/js/core/shell.js @@ -356,6 +356,7 @@ async function render() { if (current) { current.frame.destroy(); current = null; + document.dispatchEvent(new Event('febe:pagina')); // what lies over the page (the viewer) goes with it } for (const [key, link] of Object.entries(navLinks)) { const here = route && route.nav === key; diff --git a/src/Febe.Web/wwwroot/js/pages/accounts.js b/src/Febe.Web/wwwroot/js/pages/accounts.js index 39859aa..c34cee7 100644 --- a/src/Febe.Web/wwwroot/js/pages/accounts.js +++ b/src/Febe.Web/wwwroot/js/pages/accounts.js @@ -325,7 +325,9 @@ export default { }, 150); search.addEventListener('input', onSearch); const onChange = later(reload, 600); - page.onLibrary(onChange); + page.onLibrary((change) => { + if (change.reason !== 'fermi') onChange(); // an analysis («Cerca i video fermi») changes nothing here + }); page.onLeave(() => { onSearch.cancel(); onChange.cancel(); diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js index 0ba77d1..ec212bd 100644 --- a/src/Febe.Web/wwwroot/js/pages/dashboard-export.js +++ b/src/Febe.Web/wwwroot/js/pages/dashboard-export.js @@ -37,6 +37,7 @@ export async function mountExport(page) { let runs = []; let progress = null; let stillJob = null; + let drawnStills = ''; let wasRunning = null; let timer = 0; let ticks = 0; @@ -233,6 +234,10 @@ export async function mountExport(page) { function drawStills() { const job = stillJob; stills.hidden = !job || !(job.running || job.total); + // A job that is over stays as it is drawn: read again every few seconds, its link keeps the focus of the keyboard. + const drawn = stills.hidden || job.running ? '' : JSON.stringify(job); + if (drawn && drawn === drawnStills) return; + drawnStills = drawn; if (stills.hidden) { stills.replaceChildren(); return; diff --git a/src/Febe.Web/wwwroot/js/pages/dashboard.js b/src/Febe.Web/wwwroot/js/pages/dashboard.js index 5e333e7..0be5ec6 100644 --- a/src/Febe.Web/wwwroot/js/pages/dashboard.js +++ b/src/Febe.Web/wwwroot/js/pages/dashboard.js @@ -90,7 +90,9 @@ export default { } await loadSide(); if (page.signal.aborted) return; - page.onLibrary(() => loadSide()); + page.onLibrary((change) => { + if (change.reason !== 'fermi') loadSide(); // an analysis («Cerca i video fermi») changes nothing here + }); const timer = setInterval(() => { if (latest && document.visibilityState === 'visible') loadSide(); }, 60000); diff --git a/src/Febe.Web/wwwroot/js/pages/still-videos.js b/src/Febe.Web/wwwroot/js/pages/still-videos.js index 1b4b8d4..f837515 100644 --- a/src/Febe.Web/wwwroot/js/pages/still-videos.js +++ b/src/Febe.Web/wwwroot/js/pages/still-videos.js @@ -115,7 +115,9 @@ export function stillVideosDialog(selection) { draw(); try { const job = await api('/api/still-videos/start', { method: 'POST', body: selection }); - if (job.running) toast(t('esportazione.fermi.avviata', { n: plan.toAnalyse }), '', { label: t('esportazione.copia.vediAvanzamento'), href: PROGRESS_PAGE }); + const follow = { label: t('esportazione.copia.vediAvanzamento'), href: PROGRESS_PAGE }; + if (job.added) toast(t('esportazione.fermi.avviata', { n: job.added }), '', follow); + else if (job.running) toast(t('esportazione.fermi.giaInCoda'), '', follow); // all of them were queued already else toast(t('esportazione.fermi.niente')); noteJob(job); close(job); diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js index 9ad44c1..dbdc2fc 100644 --- a/src/Febe.Web/wwwroot/js/pages/viewer.js +++ b/src/Febe.Web/wwwroot/js/pages/viewer.js @@ -37,6 +37,8 @@ export function openViewer({ tile, source, origin, onDeleted }) { const copying = new Set(); // The videos being analysed («È un video fermo?», tappa E4): the answer may come once another file is on screen. const analysing = new Set(); + // Only the last reading of the analyses counts. + let analysesToken = 0; let closed = false; const where = h('span.dove'); @@ -88,8 +90,19 @@ export function openViewer({ tile, source, origin, onDeleted }) { } function close() { + dismiss(); + if (entry && source && source.reveal) { + const key = keyAt(0); + if (key != null) source.reveal(key); + } + if (opener && document.contains(opener)) opener.focus(); + } + + /** Takes the viewer away, also when the page under it changes (a link of a toast, Back): nothing under it is left. */ + function dismiss() { closed = true; document.removeEventListener('keydown', onKey, true); + document.removeEventListener('febe:pagina', dismiss); stopWatching(); onCopiesChanged.cancel(); onAnalysed.cancel(); @@ -97,11 +110,6 @@ export function openViewer({ tile, source, origin, onDeleted }) { if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); box.remove(); document.body.style.overflow = ''; - if (entry && source && source.reveal) { - const key = keyAt(0); - if (key != null) source.reveal(key); - } - if (opener && document.contains(opener)) opener.focus(); } function setZoom(on) { @@ -403,7 +411,10 @@ export function openViewer({ tile, source, origin, onDeleted }) { } analysing.delete(media.id); if (closed) return; - if (still) setStill(media.id, still); + if (still) { + analysesToken++; + setStill(media.id, still); + } const current = entry.media[fileIndex]; if (!current || current.id !== media.id) return; const lostFocus = document.activeElement === document.body; @@ -431,13 +442,15 @@ export function openViewer({ tile, source, origin, onDeleted }) { async function readAnalyses() { if (!entry) return; const id = entry.id; + const mine = ++analysesToken; let fresh; try { fresh = await api(`/api/entries/${id}`); } catch { return; } - if (closed || !entry || entry.id !== id) return; + // Asked again since, or answered by «È un video fermo?»: an older answer must not bring back what was before. + if (closed || !entry || entry.id !== id || mine !== analysesToken) return; const stills = (media) => JSON.stringify(media.map((m) => [m.id, m.still || null])); if (stills(fresh.media) === stills(entry.media)) return; for (const m of fresh.media) setStill(m.id, m.still || null); @@ -501,10 +514,12 @@ export function openViewer({ tile, source, origin, onDeleted }) { const onAnalysed = later(readAnalyses, 400); const stopWatching = onLibrary((change) => { if (change.reason === 'export') onCopiesChanged(); - if (change.reason === 'fermi' && (!entry || !change.accountId || change.accountId === entry.account.id)) onAnalysed(); + // An outcome belongs to the file: the same video may be here under another account than the one analysed. + if (change.reason === 'fermi' && entry && entry.media.some((m) => m.kind === 'video')) onAnalysed(); }); document.addEventListener('keydown', onKey, true); + document.addEventListener('febe:pagina', dismiss); document.body.append(box); closeButton.focus(); load(tile.id, 0, files && tile.cover ? tile.cover.mediaId : null); diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index fd96281..4c71a84 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -1333,6 +1333,7 @@ "niente": "Niente da analizzare: i video scelti sono già analizzati o non sono in libreria.", "nienteVideo": "Niente da analizzare: fra gli elementi scelti non ci sono video.", "avviata": "Ricerca dei video fermi avviata: 1 video da analizzare.|Ricerca dei video fermi avviata: {n} video da analizzare.", + "giaInCoda": "I video scelti sono già in coda.", "mostra": "Mostra i video fermi", "interrotta": "Ricerca interrotta. {riepilogo}.", "interrottaSubito": "Ricerca interrotta: nessun video analizzato.", diff --git a/tests/Febe.Tests/Export/ExportFrameNamesTests.cs b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs index 4c4d3ca..ea9e51c 100644 --- a/tests/Febe.Tests/Export/ExportFrameNamesTests.cs +++ b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs @@ -122,4 +122,17 @@ public sealed class ExportFrameNamesTests Assert.HasCount(1, asIs.Notes); StringAssert.StartsWith(asIs.Notes[0], MediaConversionResult.AsIsNotRemuxable + ":"); } + + [TestMethod] + [DataRow("marta/post/a_fotogramma.png", true)] + [DataRow("a_fotogramma (2).webp", true)] + [DataRow("a_fotogramma (12).jpg", true)] + [DataRow("a_t0m01s125.png", false)] + [DataRow("a_fotogramma_t0m01s125.png", false)] + [DataRow("a_fotogramma_f001.png", false)] + [DataRow("a fotogramma.png", false)] + [DataRow("a_fotogramma (x).png", false)] + [DataRow(null, false)] + public void TheNameOfSalvaIlFotogrammaIsKnownAgain(string? path, bool single) => + Assert.AreEqual(single, ExportFrames.IsSingleName(path)); } diff --git a/tests/Febe.Tests/Export/ExportFramesTests.cs b/tests/Febe.Tests/Export/ExportFramesTests.cs index 948eda7..ba2cb94 100644 --- a/tests/Febe.Tests/Export/ExportFramesTests.cs +++ b/tests/Febe.Tests/Export/ExportFramesTests.cs @@ -345,6 +345,53 @@ public sealed class ExportFramesTests Assert.HasCount(1, Fingerprint.Of(bed.Usb)); } + [TestMethod] + [DataRow(null)] + [DataRow(VideoAnalysisOutcome.Moving)] + [DataRow(VideoAnalysisOutcome.Still)] + public async Task AFrameWaitingForAFileThatChangedIsTheOneOfTheNewAnalysisOrNone(VideoAnalysisOutcome? now) + { + // The job waited (disk full) while the file was replaced: the instant was chosen on the old one, so it would save + // any frame of the new one, whatever it is. + var ct = TestContext.CancellationToken; + await using var bed = await ExportTestBed.CreateAsync(); + var video = (await SaveVideoAsync(bed, bed.Marta, "984", Mp4, ".mp4")).Media[0]; + var usb = await bed.GeneralAsync(ct: ct); + await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, 1, VideoAnalysisOutcome.Still, Make.T0, TimeSpan.FromMilliseconds(400)), ct); + bed.Disk.Free = 0; + var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Still, null, null, null, ExportFormat.Png)), ct); + + byte[] other = [.. Mp4, 0, 0, 0, 8, (byte)'f', (byte)'r', (byte)'e', (byte)'e']; + var sha = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(other)); + await File.WriteAllBytesAsync(bed.Library.Layout.FullPath(bed.Marta, video.RelativePath!), other, ct); + await bed.Db.Media.UpdateAsync((await bed.Db.Media.GetAsync(video.Id, ct))! with { Sha256 = sha, Bytes = other.Length }, ct); + var at = TimeSpan.FromMilliseconds(100); + if (now is { } outcome) + { + await bed.Db.VideoAnalyses.SetAsync(new VideoAnalysis(sha, 1, outcome, Make.T0, outcome == VideoAnalysisOutcome.Still ? at : null), ct); + } + + bed.Disk.Free = null; + await bed.Service.ResumeAsync([start.Runs.Single().Id], ct); + await bed.Service.WaitAsync(ct); + var run = await bed.RunAsync(start.Runs.Single().Id, ct); + Assert.AreEqual(ExportRunState.Completed, run.State, run.LastError); + var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single(); + if (now == VideoAnalysisOutcome.Still) + { + var copy = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single(); + Assert.AreEqual((ExportItemState.Copied, sha), (item.State, copy.SourceSha256), item.LastError); + Assert.AreEqual(TimeSpan.FromMilliseconds(ExportFrames.ActualMs(Locate(other, [at]).Single().Actual)), copy.FrameAt); + StringAssert.EndsWith(copy.RelativePath, "_fotogramma.png"); + } + else + { + Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotStill), (item.State, item.Note)); + StringAssert.Contains(ExportText.Note(item.Note), "Il video è cambiato"); + Assert.IsEmpty(Fingerprint.Of(bed.Usb)); + } + } + [TestMethod] public async Task OnlyAStillVideoGivesItsFrameAndACopyIsAlwaysTheWholeVideo() { diff --git a/tests/Febe.Tests/Web/StillVideosApiTests.cs b/tests/Febe.Tests/Web/StillVideosApiTests.cs index 7b60b5e..46471ed 100644 --- a/tests/Febe.Tests/Web/StillVideosApiTests.cs +++ b/tests/Febe.Tests/Web/StillVideosApiTests.cs @@ -113,6 +113,12 @@ public sealed class StillVideosApiTests var (slowStatus, slowBody) = await slow.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still"); Assert.AreEqual((HttpStatusCode.ServiceUnavailable, StillVideoText.TooSlow), (slowStatus, slowBody.Str("message"))); Assert.IsNull(await slow.Db.VideoAnalyses.GetAsync(video.Sha256!, ct)); + + // Analysed before: the selection would skip it, so the answer does not send there. + await slow.Db.VideoAnalyses.SetAsync(new VideoAnalysis(video.Sha256!, StillVideoAnalyzer.Algorithm, VideoAnalysisOutcome.Moving, slow.Clock.Now), ct); + var (keptStatus, keptBody) = await slow.SendJsonAsync(HttpMethod.Post, $"/api/media/{video.Id}/still"); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, keptStatus); + StringAssert.StartsWith(keptBody.Str("message"), StillVideoText.TooSlowKept); } [TestMethod] @@ -241,6 +247,49 @@ public sealed class StillVideosApiTests Assert.HasCount(2, Directory.GetFiles(usb, "*_fotogramma*.png", SearchOption.AllDirectories)); } + [TestMethod] + [Timeout(180_000, CooperativeCancellation = true)] + public async Task CopiaDiNuovoKeepsTheNameFotogramma() + { + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + var marta = await AccountAsync(server); + var still = (await WebLibrary.AddPostAsync(server, marta, "fermo", Make.T0.AddDays(-1), WebLibrary.Video(FadeInStill(10)))).Media[0]; + var usb = server.Temp.Combine("usb"); + Directory.CreateDirectory(usb); + var destinationId = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", WebLibrary.Destination(usb))).Body.GetProperty("destination").Long("id"); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/media/{still.Id}/still")).Status); + await WebLibrary.StartAndWaitAsync(server, new { mediaIds = new[] { still.Id }, frames = new { mode = "fermo", format = "png" } }); + + async Task AgainAsync() + { + var copy = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Copied, 0, 10, ct)).Single(); + File.Delete(Path.Combine(usb, LibraryLayout.ToPlatform(copy.RelativePath!))); + await server.Db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Removed, StateChangedAt = server.Clock.Now }, ct); + var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = copy.Id }); + Assert.AreEqual(HttpStatusCode.OK, status, job.ToString()); + await WebLibrary.WaitIdleAsync(server); + var again = (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Copied, 0, 10, ct)).Single(); + Assert.AreEqual((copy.FrameAt, copy.Format), (again.FrameAt, again.Format)); + Assert.IsTrue(File.Exists(Path.Combine(usb, LibraryLayout.ToPlatform(again.RelativePath!))), again.RelativePath); + return again; + } + + var first = await AgainAsync(); + StringAssert.EndsWith(first.RelativePath, "_fotogramma.png", "not the name of «Questo istante»"); + + // A file of that name that Febe did not write: the number, and «Copia di nuovo» of the numbered one too. + var taken = Path.Combine(usb, LibraryLayout.ToPlatform(first.RelativePath!)); + File.Delete(taken); + await server.Db.Exports.UpdateCopyAsync(first with { State = ExportCopyState.Removed, StateChangedAt = server.Clock.Now }, ct); + await File.WriteAllBytesAsync(taken, [1, 2, 3], ct); + Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = first.Id })).Status); + await WebLibrary.WaitIdleAsync(server); + StringAssert.EndsWith((await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Copied, 0, 10, ct)).Single().RelativePath, "_fotogramma (2).png"); + StringAssert.EndsWith((await AgainAsync()).RelativePath, "_fotogramma (2).png"); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, await File.ReadAllBytesAsync(taken, ct), "never overwritten"); + } + [TestMethod] [Timeout(180_000, CooperativeCancellation = true)] public async Task CercaIVideoFermiCountsWaitsStopsAndEnds() @@ -266,7 +315,9 @@ public sealed class StillVideosApiTests session.InSession = true; Assert.AreEqual(StillVideoText.InSession, (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/plan", selection)).Body.Str("waiting")); var started = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", selection)).Body; - Assert.AreEqual((true, 2), (started.Bool("running"), started.Int("total")), started.ToString()); + Assert.AreEqual((true, 2, 2), (started.Bool("running"), started.Int("total"), started.Int("added")), started.ToString()); + var twice = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/start", selection)).Body; + Assert.AreEqual((true, 2, 0), (twice.Bool("running"), twice.Int("total"), twice.Int("added")), "queued already: nothing added"); await WebLibrary.WaitAsync(async () => (await server.GetJsonAsync("/api/still-videos/progress")).Str("waiting") == StillVideoText.InSession, "the job waits for the session"); var stopped = (await server.SendJsonAsync(HttpMethod.Post, "/api/still-videos/stop")).Body; Assert.IsTrue(stopped.Bool("stopped")); @@ -448,6 +499,75 @@ public sealed class StillVideosApiTests await changes.DisposeAsync(); } + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task AChangeFollowedAtOnceByAnAnalysisIsNotLost() + { + // The Dashboard and the accounts skip «fermi»: during «Cerca i video fermi» a copy that ends must still reach them. + var ct = TestContext.CancellationToken; + await using var server = await StartAsync(); + using var request = new HttpRequestMessage(HttpMethod.Get, "/api/eventi"); + request.Headers.TryAddWithoutValidation("Sec-Fetch-Site", "same-origin"); + using var response = await server.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct); + using var reader = new StreamReader(await response.Content.ReadAsStreamAsync(ct)); + using var done = CancellationTokenSource.CreateLinkedTokenSource(ct); + + // Again and again: the stream may not be listening to the library yet when its first line comes. + var publishing = Task.Run( + async () => + { + while (!done.IsCancellationRequested) + { + server.Changes.Publish(new LibraryChange(server.Clock.Now, null, "export")); + for (var i = 1; i <= 40; i++) + { + server.Changes.Publish(new LibraryChange(server.Clock.Now, i, "fermi")); + } + + await Task.Delay(3000, done.Token).ContinueWith(_ => { }, TaskScheduler.Default); + } + }, + CancellationToken.None); + + var reasons = new HashSet(); + var library = false; + while (reasons.Count < 2 && await reader.ReadLineAsync(ct) is { } line) + { + if (line.StartsWith("event: ", StringComparison.Ordinal)) + { + library = line == "event: libreria"; + } + else if (library && line.StartsWith("data: ", StringComparison.Ordinal)) + { + using var json = JsonDocument.Parse(line[6..]); + reasons.Add(json.RootElement.Str("reason")); + } + } + + await done.CancelAsync(); + await publishing; + CollectionAssert.AreEquivalent(new[] { "export", "fermi" }, reasons.ToArray()); + } + + [TestMethod] + public void PendingChangesKeepOneForEachReason() + { + var pending = new PendingLibraryChanges(); + Assert.IsFalse(pending.Any); + pending.Add(new LibraryChange(Make.T0, 1, "stored")); + pending.Add(new LibraryChange(Make.T0.AddSeconds(1), 2, "export")); + pending.Add(new LibraryChange(Make.T0.AddSeconds(2), 1, "fermi")); + pending.Add(new LibraryChange(Make.T0.AddSeconds(3), 1, "stored")); + pending.Add(new LibraryChange(Make.T0.AddSeconds(4), 3, "fermi")); + Assert.IsTrue(pending.Any); + CollectionAssert.AreEqual( + new[] { ("export", (long?)2), ("stored", 1), ("fermi", null) }, + pending.Take().Select(c => (c.Reason, c.AccountId)).ToArray(), + "the account only if it is the same"); + Assert.IsFalse(pending.Any); + Assert.IsEmpty(pending.Take()); + } + // ------------------------------------------------------------------------------------------------- support private static readonly FebeWebOptions Options = new() { Edition = FebeEdition.Desktop, Access = AccessMode.None };