Importazione: plurali nei messaggi, elenco dei file con avanzamento corretto, lettura di ffprobe più robusta, prove su file cambiato dopo l'analisi e su serie completata
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
6 files changed
+74
-15
No files matched your search
@@ -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<string>();
|
||||
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<ImportOutcome, int>(), 0, env.Clock.Now));
|
||||
progress?.Report(new ImportProgress(run.Id, ImportPhase.Listing, 0, seen, 0, 0, relative, new Dictionary<ImportOutcome, int>(), 0, env.Clock.Now));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,9 +215,14 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
|
||||
/// <summary>Files that could not be read last time go back to «da analizzare».</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 + ".";
|
||||
|
||||
@@ -122,6 +122,10 @@ public static class ImportText
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>«1 file importato», «7.682 file importati»: the number with the right ending.</summary>
|
||||
public static string Count(int count, string one, string many) =>
|
||||
count == 1 ? "1 " + one : ItalianText.Number(count) + " " + many;
|
||||
|
||||
/// <summary>«1 file», «1.438 file».</summary>
|
||||
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.";
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user