Correzioni della revisione della catena 0.3.0, ognuna con la sua prova

- Collegamento: corretta la SyntaxError di connection.js (una «let saved» dichiarata due
  volte nello stesso blocco fermava tutta la pagina). Nuova prova ScriptSyntaxTests con un
  controllo scritto in casa che legge ogni modulo di wwwroot: parentesi, dichiarazioni
  doppie nello stesso blocco, importazioni che il modulo di arrivo non esporta.
- HEIF: il riconoscimento dei formati prende ogni marchio che HeifDecoder accetta (mif2,
  MiHE, marchi solo compatibili), così rilevazione, decodifica, misure, miniatura e
  impronta concordano.
- Docker, lasciare la pagina del browser: un nuovo contratto del browser cancella l'uscita
  annotata (_leftAt) anche prima che la vista si riapra, e la copia della sessione aspetta
  un altro comando del collegamento al più LetGoWait invece che senza limite.
- JPEG e PNG: senza EOI o IEND la decodifica fallisce («File danneggiato o incompleto»),
  la sola lettura delle misure resta tollerante.
- Visualizzatore: IsDamaged legge prima l'intestazione e il file intero solo quando può
  servire, in modo asincrono e con una piccola memoria per file, così una scheda con
  molti file non blocca il server.
- Importazione (§9.3): le immagini danneggiate si importano come le altre ma si segnano
  nella revisione, nel resoconto e nel CSV.
- Pulizia: le prove con il limite di 5 minuti non corrono più in parallelo fra loro.
- Pila dei caratteri come l'appendice B, senza Liberation; testo di Informazioni sulle
  immagini fatte in casa; guida (Problemi comuni, Sicurezza) allineata all'uscita in
  Docker dalla pagina del browser.
- docs/decisioni.md: le righe del 25 novembre 2026 con i motivi, compresa l'unione 537517b
  tenuta così com'è.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 14:21:36 +01:00
1 parent 3d234f8791
commit 2068dd28f3
35 files changed
+1366 -75

No files matched your search

+11 -7
View File
@@ -14,7 +14,8 @@ internal sealed record ContentFacts(
TimeSpan? Duration,
ulong? PerceptualHash,
DateTimeOffset? MetadataDate,
string? Error);
string? Error,
bool Damaged = false);
/// <summary>
/// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for
@@ -58,6 +59,7 @@ internal static class ContentAnalysis
string sha;
int? width = null, height = null;
ulong? hash = null;
var damaged = false;
if (length <= InMemoryLimit)
{
var bytes = new byte[length];
@@ -69,16 +71,18 @@ internal static class ContentAnalysis
sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
ct.ThrowIfCancellationRequested();
(width, height, hash) = Decode(bytes);
damaged = hash is null && ImageDecoding.IsDamaged(bytes);
}
else
{
sha = await env.FileSystem.ComputeSha256Async(fullPath, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
(width, height, hash) = Decode(() => env.FileSystem.OpenRead(fullPath));
(width, height, hash, damaged) = Decode(() => env.FileSystem.OpenRead(fullPath));
}
// Spec §9.3: a truncated or damaged image is imported like the others, and the review and the report say so.
var date = ExifDateReader.Read(head, env.Clock.LocalZone);
return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
return new ContentFacts(type, length, sha, width, height, null, hash, date, null, damaged);
}
/// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. AVIF).</summary>
@@ -101,7 +105,7 @@ internal static class ContentAnalysis
/// more, whole (up to <see cref="ImageDecoding.MaxFileBytes"/>; the codecs need the bytes in memory), and decoded
/// once for both hash and size.
/// </summary>
private static (int? Width, int? Height, ulong? Hash) Decode(Func<Stream> open)
private static (int? Width, int? Height, ulong? Hash, bool Damaged) Decode(Func<Stream> open)
{
try
{
@@ -113,15 +117,15 @@ internal static class ContentAnalysis
if (data is null)
{
return (null, null, null);
return (null, null, null, false);
}
var (hash, size) = PerceptualHash.ComputeWithSize(data);
return (size?.Width, size?.Height, hash);
return (size?.Width, size?.Height, hash, hash is null && ImageDecoding.IsDamaged(data));
}
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
{
return (null, null, null); // a format no decoder reads (e.g. AVIF): no size, no hash
return (null, null, null, false); // a format no decoder reads (e.g. AVIF): no size, no hash
}
}
+7
View File
@@ -265,6 +265,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
.ConfigureAwait(false);
var updates = new List<ImportFile>(batch.Count);
var damaged = new List<long>();
for (var i = 0; i < batch.Count; i++)
{
var file = batch[i];
@@ -275,6 +276,11 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
continue;
}
if (fact.Damaged)
{
damaged.Add(file.Id);
}
var hints = recognizers.Recognize(new ImportFileContext(layout, file.RelativePath));
var (takenAt, source) = ResolveDate(hints, fact.MetadataDate, file.ModifiedAt);
var analysed = file with
@@ -318,6 +324,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env)
}
await env.Storage.Imports.UpdateFilesAsync(updates, ct).ConfigureAwait(false);
await ImportRunSettings.AddDamagedAsync(env.Storage.Settings, run.Id, damaged, ct).ConfigureAwait(false);
foreach (var update in updates)
{
done++;
+62 -1
View File
@@ -115,6 +115,67 @@ internal static class ImportRunSettings
public static string NewAccountsKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.nuovi-account");
/// <summary>
/// The files of the run the analysis found «File danneggiato o incompleto» (spec §9.3), as a JSON array of their ids:
/// a setting of the run like the others, so that the schema (and the numbering of its migrations) stays as it is.
/// </summary>
public static string DamagedKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.danneggiati");
/// <summary>The ids of the files of the run that the analysis found damaged or truncated (spec §9.3).</summary>
public static async Task<HashSet<long>> GetDamagedAsync(ISettingsStore store, long runId, CancellationToken ct)
{
var text = await store.GetAsync(DamagedKey(runId), ct).ConfigureAwait(false);
var result = new HashSet<long>();
if (string.IsNullOrWhiteSpace(text))
{
return result;
}
try
{
if (JsonNode.Parse(text) is JsonArray ids)
{
foreach (var id in ids)
{
if (id is JsonValue value && value.TryGetValue<long>(out var fileId))
{
result.Add(fileId);
}
}
}
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{
// An unreadable value: no file is marked.
}
return result;
}
/// <summary>Adds <paramref name="fileIds"/> to the damaged files of the run (an analysis that starts again adds nothing twice).</summary>
public static async Task AddDamagedAsync(ISettingsStore store, long runId, IReadOnlyCollection<long> fileIds, CancellationToken ct)
{
if (fileIds.Count == 0)
{
return;
}
var all = await GetDamagedAsync(store, runId, ct).ConfigureAwait(false);
if (all.IsSupersetOf(fileIds))
{
return;
}
all.UnionWith(fileIds);
var json = new JsonArray();
foreach (var id in all.Order())
{
json.Add(id);
}
await store.SetAsync(DamagedKey(runId), json.ToJsonString(), ct).ConfigureAwait(false);
}
public static Task<bool> GetStogramAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.GetBoolAsync(StogramKey(runId), false, ct);
@@ -169,5 +230,5 @@ internal static class ImportRunSettings
}
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.SetManyAsync(new Dictionary<string, string?> { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null }, ct);
store.SetManyAsync(new Dictionary<string, string?> { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null, [DamagedKey(runId)] = null }, ct);
}
+3 -1
View File
@@ -124,6 +124,7 @@ public sealed record ImportFolderReview(
/// <param name="AnalysisDuration">From the start of the import to the end of the analysis.</param>
/// <param name="StogramHypothesis">The 4K Stogram hypothesis recognizer was used.</param>
/// <param name="Copied">Files already copied or moved by this import.</param>
/// <param name="Damaged">Images the analysis found «File danneggiato o incompleto» (spec §9.3): imported like the others.</param>
public sealed record ImportReviewSummary(
ImportRun Run,
string DisplayPath,
@@ -135,7 +136,8 @@ public sealed record ImportReviewSummary(
IReadOnlyList<ImportFolderReview> Folders,
TimeSpan? AnalysisDuration,
bool StogramHypothesis,
int Copied)
int Copied,
int Damaged = 0)
{
/// <summary>«Sposta» is offered only for writable sources.</summary>
public bool CanMove => !Run.SourceReadOnly;
+20 -3
View File
@@ -29,6 +29,8 @@ public sealed record ReportNote(string Path, string Note);
/// <param name="AlreadyInLibraryByAccount">Where the «Già in libreria» files already are.</param>
/// <param name="Unrecognized">The files that are neither photos nor videos (at most <see cref="ImportReports.MaxListed"/>).</param>
/// <param name="Problems">Files that failed or need attention, with the reason (at most <see cref="ImportReports.MaxListed"/>).</param>
/// <param name="DamagedCount">Images found «File danneggiato o incompleto» by the analysis (spec §9.3).</param>
/// <param name="Damaged">Their paths (at most <see cref="ImportReports.MaxListed"/>).</param>
public sealed record ImportReport(
ImportRun Run,
string DisplayPath,
@@ -46,7 +48,9 @@ public sealed record ImportReport(
IReadOnlyList<AccountCount> ImportedByAccount,
IReadOnlyList<AccountCount> AlreadyInLibraryByAccount,
IReadOnlyList<string> Unrecognized,
IReadOnlyList<ReportNote> Problems);
IReadOnlyList<ReportNote> Problems,
int DamagedCount = 0,
IReadOnlyList<string>? Damaged = null);
/// <summary>
/// The report of an import and its CSV export (spec §9.4, §4.8): one row per file, ';' as separator, UTF-8 with BOM, so
@@ -74,9 +78,16 @@ public sealed class ImportReports(ImportEnvironment env)
var already = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
var unrecognized = new List<string>();
var problems = new List<ReportNote>();
var damagedIds = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
var damaged = new List<string>();
await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false))
{
var file = row.File;
if (damagedIds.Contains(file.Id) && damaged.Count < MaxListed)
{
damaged.Add(file.RelativePath);
}
if (file.State is ImportFileState.Copied or ImportFileState.Moved)
{
bytesCopied += file.Bytes;
@@ -120,7 +131,9 @@ public sealed class ImportReports(ImportEnvironment env)
Sorted(imported),
Sorted(already),
unrecognized,
problems);
problems,
damagedIds.Count,
damaged);
}
/// <summary>Suggested name of the CSV file: «importazione-2026-10-13-12.csv».</summary>
@@ -138,9 +151,13 @@ public sealed class ImportReports(ImportEnvironment env)
var zone = env.Clock.LocalZone;
await using var writer = new StreamWriter(destination, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), 64 * 1024, leaveOpen: true) { NewLine = "\r\n" };
await writer.WriteLineAsync(Line(Header)).ConfigureAwait(false);
var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false))
{
var f = row.File;
var note = damaged.Contains(f.Id)
? f.LastError is { Length: > 0 } other ? $"{ImportText.NoteDamaged}. {other}" : ImportText.NoteDamaged
: f.LastError ?? string.Empty;
var replaced = f.LastError?.StartsWith(ImportText.NoteReplaced, StringComparison.Ordinal) == true;
var destinationUser = replaced ? row.MatchedUsername : row.TargetUsername;
await writer.WriteLineAsync(Line(
@@ -163,7 +180,7 @@ public sealed class ImportReports(ImportEnvironment env)
f.InstagramId ?? string.Empty,
row.MatchedUsername is { } user ? $"{user}/{row.MatchedPath}" : string.Empty,
f.DestinationPath is { } path && destinationUser is { } to ? $"{to}/{path}" : f.DestinationPath ?? string.Empty,
f.LastError ?? string.Empty,
note,
])).ConfigureAwait(false);
}
+3 -1
View File
@@ -20,6 +20,7 @@ public sealed class ImportReview(ImportEnvironment env)
var folders = await ListFoldersAsync(run, ct).ConfigureAwait(false);
var pending = await env.Storage.Imports.CountPairsAsync(runId, pendingOnly: true, ct).ConfigureAwait(false);
var stogram = await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false);
return new ImportReviewSummary(
run,
env.CreateSources().DisplayPath(run.SourcePath),
@@ -31,7 +32,8 @@ public sealed class ImportReview(ImportEnvironment env)
folders,
run.AnalyzedAt is { } analyzed ? analyzed - run.StartedAt : null,
stogram,
summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved]);
summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved],
damaged.Count);
}
/// <summary>The rows of «Cartelle e account».</summary>
+3
View File
@@ -145,4 +145,7 @@ public static class ImportText
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.";
internal const string NoteOldNotDeleted = "Il file sostituito non si è potuto eliminare dalla libreria: resta accanto al nuovo.";
/// <summary>Spec §9.3, §8.4: an image truncated or damaged, imported like the others, without visual fingerprint.</summary>
internal const string NoteDamaged = "File danneggiato o incompleto";
}