From 83ad105d401a6eaf954d9b1bd8e569c6d5016c54 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 18:43:53 +0000 Subject: [PATCH] =?UTF-8?q?Importazione:=20plurali=20nei=20messaggi,=20ele?= =?UTF-8?q?nco=20dei=20file=20con=20avanzamento=20corretto,=20lettura=20di?= =?UTF-8?q?=20ffprobe=20pi=C3=B9=20robusta,=20prove=20su=20file=20cambiato?= =?UTF-8?q?=20dopo=20l'analisi=20e=20su=20serie=20completata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA --- src/Febe.Core/Import/ImportAnalyzer.cs | 16 +++++--- src/Febe.Core/Import/ImportCopier.cs | 8 ++-- src/Febe.Core/Import/ImportText.cs | 6 ++- src/Febe.Core/Import/VideoMetadataProbe.cs | 13 +++--- tests/Febe.Tests/Import/ImportCopyTests.cs | 45 +++++++++++++++++++++ tests/Febe.Tests/Import/MediaReaderTests.cs | 1 + 6 files changed, 74 insertions(+), 15 deletions(-) diff --git a/src/Febe.Core/Import/ImportAnalyzer.cs b/src/Febe.Core/Import/ImportAnalyzer.cs index 5d81c8e..322f87c 100644 --- a/src/Febe.Core/Import/ImportAnalyzer.cs +++ b/src/Febe.Core/Import/ImportAnalyzer.cs @@ -82,7 +82,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env) var summary = await env.Storage.Imports.GetSummaryAsync(runId, CancellationToken.None).ConfigureAwait(false); await WriteEventAsync( "importazione-analizzata", - $"Analisi della cartella «{layout.RootName}» finita: {ImportText.Files(summary.Total)}, {ItalianText.Number(summary.ByOutcome[ImportOutcome.New])} nuovi.", + $"Analisi della cartella «{layout.RootName}» finita: {ImportText.Files(summary.Total)}, {ImportText.Count(summary.ByOutcome[ImportOutcome.New], "nuovo", "nuovi")}.", EventSeverity.Info).ConfigureAwait(false); progress?.Report(await SnapshotAsync(runId, ImportPhase.Finished, null).ConfigureAwait(false)); return run; @@ -156,6 +156,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env) } var found = new List(); + var seen = 0; foreach (var path in Directory.EnumerateFiles(layout.Root, "*", ImportSources.Enumeration(recursive: true))) { ct.ThrowIfCancellationRequested(); @@ -170,9 +171,9 @@ public sealed class ImportAnalyzer(ImportEnvironment env) found.Add(relative); } - if (found.Count % 1000 == 0 && found.Count > 0) + if (++seen % 1000 == 0) { - progress?.Report(new ImportProgress(run.Id, ImportPhase.Listing, 0, known.Count + found.Count, 0, 0, relative, new Dictionary(), 0, env.Clock.Now)); + progress?.Report(new ImportProgress(run.Id, ImportPhase.Listing, 0, seen, 0, 0, relative, new Dictionary(), 0, env.Clock.Now)); } } @@ -214,9 +215,14 @@ public sealed class ImportAnalyzer(ImportEnvironment env) /// Files that could not be read last time go back to «da analizzare». private async Task RetryUnreadableAsync(long runId, CancellationToken ct) { - var failed = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, State = ImportFileState.Failed, Outcome = ImportOutcome.Pending, Limit = 10_000 }, ct).ConfigureAwait(false); - if (failed.Count > 0) + while (true) { + var failed = await env.Storage.Imports.ListFilesAsync(new ImportFileQuery { RunId = runId, State = ImportFileState.Failed, Outcome = ImportOutcome.Pending, Limit = 5000 }, ct).ConfigureAwait(false); + if (failed.Count == 0) + { + return; + } + await env.Storage.Imports.UpdateFilesAsync(failed.Select(f => f with { State = ImportFileState.Pending, LastError = null }).ToList(), ct).ConfigureAwait(false); } } diff --git a/src/Febe.Core/Import/ImportCopier.cs b/src/Febe.Core/Import/ImportCopier.cs index 193205f..f039f06 100644 --- a/src/Febe.Core/Import/ImportCopier.cs +++ b/src/Febe.Core/Import/ImportCopier.cs @@ -124,20 +124,20 @@ public sealed class ImportCopier(ImportEnvironment env) private static string CompletionMessage(string source, Tally tally) { - var text = $"Importazione dalla cartella «{source}» finita: {ImportText.Files(tally.Copied)} importati"; + var text = $"Importazione dalla cartella «{source}» finita: {ImportText.Count(tally.Copied, "file importato", "file importati")}"; if (tally.Replaced > 0) { - text += $" ({ItalianText.Number(tally.Replaced)} al posto di file più piccoli)"; + text += $" ({ImportText.Count(tally.Replaced, "al posto di un file più piccolo", "al posto di file più piccoli")})"; } if (tally.LeftOut > 0) { - text += $", {ImportText.Files(tally.LeftOut)} restano fuori"; + text += ", " + ImportText.Count(tally.LeftOut, "file resta fuori", "file restano fuori"); } if (tally.Failed > 0) { - text += $", {ImportText.Files(tally.Failed)} non riusciti"; + text += ", " + ImportText.Count(tally.Failed, "file non riuscito", "file non riusciti"); } return text + "."; diff --git a/src/Febe.Core/Import/ImportText.cs b/src/Febe.Core/Import/ImportText.cs index 3f789f4..3dab244 100644 --- a/src/Febe.Core/Import/ImportText.cs +++ b/src/Febe.Core/Import/ImportText.cs @@ -122,6 +122,10 @@ public static class ImportText return text; } + /// «1 file importato», «7.682 file importati»: the number with the right ending. + public static string Count(int count, string one, string many) => + count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many; + /// «1 file», «1.438 file». public static string Files(int count) => ItalianText.Number(count) + " file"; @@ -135,7 +139,7 @@ public static class ImportText internal const string NoteNotRecognized = "Né foto né video: ignorato."; internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato."; internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto."; - internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Rifai l'analisi di questa cartella."; + internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella."; internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria."; internal const string NoteOriginalKept = "Copiato; l'originale non si è potuto eliminare e resta al suo posto."; internal const string NoteMovePending = "Copiato; l'originale si elimina dopo la verifica della copia."; diff --git a/src/Febe.Core/Import/VideoMetadataProbe.cs b/src/Febe.Core/Import/VideoMetadataProbe.cs index 51b3afa..eef40f1 100644 --- a/src/Febe.Core/Import/VideoMetadataProbe.cs +++ b/src/Febe.Core/Import/VideoMetadataProbe.cs @@ -144,12 +144,14 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe { foreach (var stream in streams.EnumerateArray()) { - if (stream.TryGetProperty("codec_type", out var type) && type.GetString() == "video" + if (stream.TryGetProperty("codec_type", out var type) && type.ValueKind == JsonValueKind.String && type.GetString() == "video" && stream.TryGetProperty("width", out var w) && w.TryGetInt32(out var wv) && wv > 0 && stream.TryGetProperty("height", out var h) && h.TryGetInt32(out var hv) && hv > 0) { var rotate = stream.TryGetProperty("tags", out var tags) && tags.TryGetProperty("rotate", out var r) - && int.TryParse(r.GetString(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var degrees) ? Math.Abs(degrees) % 180 : 0; + && int.TryParse(r.ValueKind == JsonValueKind.String ? r.GetString() : r.GetRawText(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var degrees) + ? Math.Abs(degrees) % 180 + : 0; (width, height) = rotate == 90 ? (hv, wv) : (wv, hv); created ??= CreationTime(stream); break; @@ -159,15 +161,16 @@ public sealed class FfprobeVideoMetadataProbe : IVideoMetadataProbe return new VideoMetadata(created, duration, width, height); } - catch (JsonException) + catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException) { - return null; + return null; // an unexpected shape: as if ffprobe had nothing to say } } private static DateTimeOffset? CreationTime(JsonElement element) { - if (element.TryGetProperty("tags", out var tags) && tags.TryGetProperty("creation_time", out var value) + if (element.TryGetProperty("tags", out var tags) && tags.ValueKind == JsonValueKind.Object + && tags.TryGetProperty("creation_time", out var value) && value.ValueKind == JsonValueKind.String && DateTimeOffset.TryParse(value.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var instant) && instant.Year >= 1995) { diff --git a/tests/Febe.Tests/Import/ImportCopyTests.cs b/tests/Febe.Tests/Import/ImportCopyTests.cs index 9e74e3a..4c4f0e9 100644 --- a/tests/Febe.Tests/Import/ImportCopyTests.cs +++ b/tests/Febe.Tests/Import/ImportCopyTests.cs @@ -224,6 +224,51 @@ public sealed class ImportCopyTests Assert.AreEqual(ImportFileState.Copied, (await bed.FileAsync(run.Id, "marta.demo/copiata-prima.jpg")).State); } + [TestMethod] + public async Task AFileChangedAfterTheAnalysisIsNotCopied() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var path = bed.Write("marta.demo/cambiata.jpg", ImportTestFiles.Photo(47)); + var run = await bed.AnalyzeAsync(); + File.WriteAllBytes(path, ImportTestFiles.Photo(48)); + + await bed.Copier.CopyAsync(run.Id); + + var file = (await bed.FilesAsync(run.Id)).Single(); + Assert.AreEqual(ImportFileState.Failed, file.State); + Assert.AreEqual(ImportText.NoteChanged, file.LastError); + var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!; + Assert.IsEmpty(await bed.Library.Db.Entries.ListByAccountAsync(account.Id), "Nessun elemento vuoto resta in libreria."); + Assert.IsFalse(Directory.Exists(bed.Library.Layout.AccountFolder(account)) && Directory.EnumerateFiles(bed.Library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories).Any()); + } + + [TestMethod] + public async Task AnImportCompletesASeriesAlreadyInTheLibrary() + { + using var temp = new TempFolder("importa"); + await using var bed = await ImportTestBed.CreateAsync(temp); + var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var first = ImportTestFiles.Photo(130); + var entry = Make.Entry(marta.Id, "555", new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero)) with { Code = "SER1234" }; + var added = await bed.Library.Db.Entries.AddAsync(entry, [Make.Photo(1), Make.Photo(2)]); + await bed.Library.Ingest.SaveMediaAsync(marta, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = new MemoryStream(first), Extension = ".jpg" }); + bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_SER1234_1.jpg", first); + bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_SER1234_2.jpg", ImportTestFiles.Photo(131)); + + var run = await bed.AnalyzeAsync(); + Assert.AreEqual(ImportOutcome.AlreadyInLibrary, (await bed.FileAsync(run.Id, "marta.demo/post/2026/2026-10-10_18-22-05_SER1234_1.jpg")).Outcome); + Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/post/2026/2026-10-10_18-22-05_SER1234_2.jpg")).Outcome, "Il secondo file manca: non è un doppione."); + await bed.Copier.CopyAsync(run.Id); + + var stored = (await bed.Library.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!; + Assert.AreEqual(EntryState.Downloaded, stored.Entry.State, "L'elemento ora ha tutti i suoi file."); + Assert.AreEqual("post/2026/2026-10-10_18-22-05_SER1234_2.jpg", stored.Media[1].RelativePath); + Assert.IsTrue(EntryStateRules.IsPresent(stored.Media[1].State)); + Assert.HasCount(1, await bed.Library.Db.Entries.ListByAccountAsync(marta.Id), "Nessun elemento nuovo: il file completa quello che c'era."); + } + [TestMethod] public async Task AReadOnlySourceDoesNotOfferMove() { diff --git a/tests/Febe.Tests/Import/MediaReaderTests.cs b/tests/Febe.Tests/Import/MediaReaderTests.cs index e5371fb..c660bde 100644 --- a/tests/Febe.Tests/Import/MediaReaderTests.cs +++ b/tests/Febe.Tests/Import/MediaReaderTests.cs @@ -119,6 +119,7 @@ public sealed class MediaReaderTests Assert.AreEqual(TimeSpan.FromSeconds(12.5), parsed?.Duration); Assert.AreEqual((1080, 1920), (parsed?.Width, parsed?.Height)); Assert.IsNull(FfprobeVideoMetadataProbe.Parse("non json")); + Assert.AreEqual(640, FfprobeVideoMetadataProbe.Parse("""{"streams":[{"codec_type":"video","width":640,"height":480,"tags":{"rotate":0}}],"format":{"tags":{"creation_time":5}}}""")?.Width, "Valori di tipo inatteso non fanno fallire la lettura."); var probe = FfprobeVideoMetadataProbe.TryCreate(); if (probe is null)