E4: copie del fotogramma con il loro nome, eventi che non si perdono, visualizzatore che si chiude

«Copia di nuovo» di un _fotogramma lo rifaceva come _t…, e un lavoro in attesa prendeva un istante del file vecchio.
Un'analisi copriva l'evento di una copia finita; il visualizzatore restava sopra la pagina nuova e poteva mostrare un
esito superato; la scheda Esportazione perdeva il fuoco a ogni rilettura.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 18:57:58 +01:00
1 parent 6dcaf30db6
commit 2c0cfcccf2
17 files changed
+301 -35

No files matched your search

+16 -2
View File
@@ -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);
+2 -1
View File
@@ -54,7 +54,8 @@ public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video
/// <summary>«Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity.</summary>
/// <param name="FrameAt">The instant of a frame row; null otherwise.</param>
public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt);
/// <param name="Still">The frame row is one of «Salva il fotogramma»: the new file is named <c>…_fotogramma</c> again.</param>
public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt, bool Still = false);
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
/// <param name="Formats">The formats of this request («Copia in…» → «Cambia»); null: those of the destination.</param>
+2 -2
View File
@@ -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)
+4
View File
@@ -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",
+13 -16
View File
@@ -131,8 +131,8 @@ public static class EngineApi
/// <summary>
/// <c>/api/eventi</c>: server-sent events. <c>motore</c> carries the engine (at once, at every change, at least every
/// minute); <c>libreria</c> 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); <c>libreria</c> 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.
/// </summary>
public static async Task StreamAsync(
HttpContext context,
@@ -151,6 +151,7 @@ public static class EngineApi
var ct = context.RequestAborted;
var signals = Channel.CreateBounded<string>(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;
}
+2 -1
View File
@@ -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);
});
+42 -1
View File
@@ -120,9 +120,50 @@ public sealed class LibraryConversionFileResolver(FebeLibrary library) : IConver
/// <summary>Something changed in the library: the open pages reload what they show.</summary>
/// <param name="At">When.</param>
/// <param name="AccountId">The account concerned, when there is only one.</param>
/// <param name="Reason">Short machine reason: "stored", "deleted", "account", "import".</param>
/// <param name="Reason">Short machine reason: "stored", "deleted", "account", "import", "export", "fermi".</param>
public sealed record LibraryChange(DateTimeOffset At, long? AccountId, string Reason);
/// <summary>
/// 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.
/// </summary>
internal sealed class PendingLibraryChanges
{
private readonly Dictionary<string, LibraryChange> _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;
}
}
/// <summary>The changes to tell, in the order they came in; none is left.</summary>
public IReadOnlyList<LibraryChange> Take()
{
lock (_pending)
{
LibraryChange[] taken = [.. _pending.Values.OrderBy(c => c.At)];
_pending.Clear();
return taken;
}
}
}
/// <summary>
/// Library notifications for the server-sent events (<c>/api/eventi</c>, event <c>libreria</c>). Publishers: the web
/// layer itself (deletions, account changes), the download queue (<see cref="Attach"/>) and the import (M7).
+1
View File
@@ -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;
+3 -1
View File
@@ -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();
@@ -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;
+3 -1
View File
@@ -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);
@@ -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);
+23 -8
View File
@@ -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);
+1
View File
@@ -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.",