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

+21 -3
View File
@@ -794,10 +794,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return;
}
// Besides this lease: the remote view, the browser window in front, «Scollega» in progress.
// Besides this lease: the remote view, the browser window in front, «Scollega» in progress. A view open
// again also cancels an earlier leave (a late «pageLeft» of a reloaded page, the old view that
// «Riprova» closed): only a view closing after this counts as leaving, so that a view ended later by
// the server (the browser stopped) waits for DrivingGrace, as a browser that is down is not leaving.
if (_browser.UserDriving.Leases > 1)
{
_lastDrivingSign = _clock.Now;
_leftAt = null;
}
lastSign = _lastDrivingSign;
@@ -867,10 +871,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide.
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide. Leaving the page
// in Docker waits at most LetGoWait for another command of the connection, as closing the window does (§6.0), so
// that the engine is not held still: then the lease ends without the copy.
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
if (what == PageLeftText)
{
limit.CancelAfter(LetGoWait);
}
try
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested && limit.IsCancellationRequested)
{
ForgetLetGoCopy();
_log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
return true;
}
catch (ObjectDisposedException)
{
+11 -1
View File
@@ -23,7 +23,10 @@ public enum ImageFormat
/// <summary>Recognises an image format from the first bytes of a file.</summary>
public static class ImageFormatSniffer
{
/// <summary>Bytes <see cref="Detect"/> needs to tell every format apart; fewer are fine for most formats.</summary>
/// <summary>
/// Bytes <see cref="Detect"/> needs to tell every format apart; fewer are fine for most formats. A HEIF whose brand
/// is only among the compatible brands needs the whole <c>ftyp</c> box.
/// </summary>
public const int HeaderLength = 32;
/// <summary>The format the bytes start with, or <see cref="ImageFormat.Unknown"/>.</summary>
@@ -72,6 +75,13 @@ public static class ImageFormatSniffer
{
return ImageFormat.Heif;
}
// Every file the HEIF decoder takes (mif2, MiHE, or a HEIF brand among the compatible ones) is a HEIF:
// the decoder is chosen from this answer, so a narrower list would leave such a HEIC without a picture.
if (Heif.HeifDecoder.Looks(header))
{
return ImageFormat.Heif;
}
}
return ImageFormat.Unknown;
+4 -2
View File
@@ -10,8 +10,10 @@ namespace Febe.Core.Codecs.Images;
/// </summary>
/// <remarks>
/// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged
/// (<see cref="ImageDecodeException"/>), as is a Huffman code the table does not have; a missing EOI after complete
/// scans, bytes after EOI and stray restart markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused
/// (<see cref="ImageDecodeException"/>), as is a Huffman code the table does not have, and a file that ends before its
/// EOI is incomplete even after complete scans (spec §3: a progressive file cut between two scans is refused, not shown
/// at a lower quality); <see cref="Identify"/> still reads the size of such a file. Bytes after EOI and stray restart
/// markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused
/// with <see cref="ImageFormatNotSupportedException"/>.
/// </remarks>
public static class JpegDecoder
+7
View File
@@ -288,6 +288,13 @@ internal sealed partial class JpegFile : IDisposable
return;
}
// Spec §3, §8.4: a JPEG that ends before its end marker is incomplete, even when its scans so far are complete
// (a progressive file cut between two scans would otherwise give a picture of lower quality).
if (!sawEoi)
{
throw new ImageDecodeException("JPEG troncato: manca il marcatore di fine (EOI).");
}
if (_scanCount == 0)
{
throw new ImageDecodeException("JPEG senza dati d'immagine.");
+18
View File
@@ -48,6 +48,7 @@ public static class PngDecoder
{
limits ??= ImageLimits.Default;
var file = Parse(data, limits, readMetadata: false);
RequireEnd(file);
return DecodePixels(data, file, limits, pooled);
}
@@ -56,13 +57,27 @@ public static class PngDecoder
{
limits ??= ImageLimits.Default;
var file = Parse(data, limits, readMetadata: true);
RequireEnd(file);
var image = DecodePixels(data, file, limits, pooled);
info = file.ToInfo();
return image;
}
/// <summary>
/// Spec §3, §8.4: a PNG that ends before its end marker is incomplete, even when its image data is complete, and is
/// not decoded; <see cref="Identify"/> still reads its size.
/// </summary>
private static void RequireEnd(PngFile file)
{
if (!file.SeenEnd)
{
throw new ImageDecodeException("PNG troncato: manca il blocco di fine (IEND).");
}
}
private sealed class PngFile
{
public bool SeenEnd;
public int Width;
public int Height;
public int BitDepth;
@@ -129,6 +144,7 @@ public static class PngDecoder
var seenPalette = false;
var seenTransparency = false;
var idatState = 0; // 0 none yet, 1 inside the IDAT run, 2 after it
var seenEnd = false;
var metadataBudget = limits.MaxMetadataBytes;
var pos = 8;
while (pos < data.Length)
@@ -227,6 +243,7 @@ public static class PngDecoder
break;
case "IEND":
seenEnd = true;
pos = data.Length;
break;
@@ -275,6 +292,7 @@ public static class PngDecoder
throw new ImageDecodeException("PNG senza dati dell'immagine (IDAT).");
}
file.SeenEnd = seenEnd;
return file;
}
+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";
}
+113 -7
View File
@@ -1,3 +1,5 @@
using System.Collections.Concurrent;
namespace Febe.Core.Library;
/// <summary>
@@ -7,11 +9,18 @@ namespace Febe.Core.Library;
/// class only looks, it never deletes, replaces or downloads again.
/// </summary>
/// <remarks>
/// The check decodes the picture, so it is meant for a single file at a time (the viewer) and only for photos that
/// have no thumbnail: a photo with a thumbnail was decoded when it was stored.
/// The check decodes the picture, so it is meant for a single file at a time (the viewer, the import of one file) and
/// only for photos that have no thumbnail: a photo with a thumbnail was decoded when it was stored. The first bytes are
/// looked at before the rest is read: a format Febe does not decode, a HEIC and a picture over the decoding limit are
/// never damaged, so their file is not read whole for nothing.
/// </remarks>
public static class DamagedImage
{
/// <summary>How many answers <see cref="IsFileDamagedAsync"/> keeps; the whole memory is dropped when it is full.</summary>
private const int RememberedAnswers = 512;
private static readonly ConcurrentDictionary<(string Path, long Length, DateTime Written), bool> Answers = new();
/// <summary>
/// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or
/// truncated; false for a photo that decodes, for a format Febe does not read (AVIF, an unknown one), for HEIC (see ImageDecoding.IsDamaged) and for a
@@ -20,23 +29,120 @@ public static class DamagedImage
public static bool IsDamaged(ReadOnlyMemory<byte> data) => ImageDecoding.IsDamaged(data);
/// <summary>
/// <see cref="IsDamaged(ReadOnlyMemory{byte})"/> for a file on disk, read once; false when it cannot be read or is
/// larger than <see cref="ImageDecoding.MaxFileBytes"/>.
/// <see cref="IsDamaged(ReadOnlyMemory{byte})"/> for a file on disk; false when it cannot be read or is larger than
/// <see cref="ImageDecoding.MaxFileBytes"/>. Reads the first bytes and, only when the picture may be damaged, the rest.
/// </summary>
public static bool IsFileDamaged(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
byte[]? data;
try
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
data = ImageDecoding.ReadAll(stream);
var length = stream.Length;
if (length <= 0 || length > ImageDecoding.MaxFileBytes)
{
return false;
}
var head = (int)Math.Min(length, ImageDecoding.HeaderBytes);
var data = new byte[head];
stream.ReadExactly(data);
if (!ImageDecoding.MayBeDamaged(data))
{
return false;
}
if (length > head)
{
var whole = new byte[length];
data.CopyTo(whole, 0);
stream.ReadExactly(whole.AsSpan(head));
data = whole;
}
return ImageDecoding.IsDamaged(data);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>
/// <see cref="IsFileDamaged"/> with asynchronous reads, for a request: the answer is kept for the same file (path,
/// length and time of the last write), so stepping back and forth in the viewer does not read and decode it again.
/// </summary>
public static async Task<bool> IsFileDamagedAsync(string path, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrEmpty(path);
(string, long, DateTime) key;
try
{
var info = new FileInfo(path);
if (!info.Exists)
{
return false;
}
key = (info.FullName, info.Length, info.LastWriteTimeUtc);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
return data is not null && ImageDecoding.IsDamaged(data);
if (Answers.TryGetValue(key, out var known))
{
return known;
}
var answer = await ReadAndCheckAsync(path, ct).ConfigureAwait(false);
if (answer is not { } damaged)
{
return false; // not readable now: not remembered
}
if (Answers.Count >= RememberedAnswers)
{
Answers.Clear();
}
Answers[key] = damaged;
return damaged;
}
private static async Task<bool?> ReadAndCheckAsync(string path, CancellationToken ct)
{
try
{
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan);
var length = stream.Length;
if (length <= 0 || length > ImageDecoding.MaxFileBytes)
{
return false;
}
var head = (int)Math.Min(length, ImageDecoding.HeaderBytes);
var data = new byte[head];
await stream.ReadExactlyAsync(data, ct).ConfigureAwait(false);
if (!ImageDecoding.MayBeDamaged(data))
{
return false;
}
if (length > head)
{
var whole = new byte[length];
data.CopyTo(whole, 0);
await stream.ReadExactlyAsync(whole.AsMemory(head), ct).ConfigureAwait(false);
data = whole;
}
return ImageDecoding.IsDamaged(data);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return null;
}
}
}
+49
View File
@@ -1,3 +1,4 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Heif;
using Febe.Core.Codecs.Images;
@@ -112,6 +113,54 @@ internal static class ImageDecoding
}
}
/// <summary>
/// From the first bytes of a file (at least the header of its format): false when <see cref="IsDamaged"/> would
/// say false whatever follows — a format Febe does not decode, a HEIC, a PNG, GIF, BMP or WebP whose header gives
/// more pixels than <see cref="MaxDecodedPixels"/> — so that such a file is not read whole only to be refused.
/// JPEG decodes at a reduced size, so its header alone never rules it out.
/// </summary>
internal static bool MayBeDamaged(ReadOnlySpan<byte> head)
{
var format = head.IsEmpty ? ImageFormat.Unknown : ImageFormatSniffer.Detect(head);
if (format == ImageFormat.Heif || !ImageDecoder.CanDecode(format))
{
return false;
}
return HeaderPixels(format, head) is not { } pixels || pixels <= MaxDecodedPixels;
}
/// <summary>
/// Width × height as the header of a PNG (IHDR), GIF (logical screen), BMP (information header) or WebP (VP8X,
/// VP8L or VP8 frame header) states it, from their public specifications; null when it is not there.
/// </summary>
internal static long? HeaderPixels(ImageFormat format, ReadOnlySpan<byte> h)
{
switch (format)
{
case ImageFormat.Png when h.Length >= 24 && h[12..16].SequenceEqual("IHDR"u8):
return (long)BinaryPrimitives.ReadUInt32BigEndian(h[16..]) * BinaryPrimitives.ReadUInt32BigEndian(h[20..]);
case ImageFormat.Gif when h.Length >= 10:
return (long)BinaryPrimitives.ReadUInt16LittleEndian(h[6..]) * BinaryPrimitives.ReadUInt16LittleEndian(h[8..]);
case ImageFormat.Bmp when h.Length >= 22 && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) == 12:
return (long)BinaryPrimitives.ReadUInt16LittleEndian(h[18..]) * BinaryPrimitives.ReadUInt16LittleEndian(h[20..]);
case ImageFormat.Bmp when h.Length >= 26:
return Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(h[18..])) * Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(h[22..]));
case ImageFormat.WebP when h.Length >= 30 && h[12..16].SequenceEqual("VP8X"u8):
return (1L + (h[24] | (h[25] << 8) | (h[26] << 16))) * (1L + (h[27] | (h[28] << 8) | (h[29] << 16)));
case ImageFormat.WebP when h.Length >= 25 && h[12..16].SequenceEqual("VP8L"u8) && h[20] == 0x2F:
{
var bits = BinaryPrimitives.ReadUInt32LittleEndian(h[21..]);
return (1L + (bits & 0x3FFF)) * (1L + ((bits >> 14) & 0x3FFF));
}
case ImageFormat.WebP when h.Length >= 30 && h[12..16].SequenceEqual("VP8 "u8) && h[23] == 0x9D && h[24] == 0x01 && h[25] == 0x2A:
return (long)(BinaryPrimitives.ReadUInt16LittleEndian(h[26..]) & 0x3FFF) * (BinaryPrimitives.ReadUInt16LittleEndian(h[28..]) & 0x3FFF);
default:
return null;
}
}
/// <summary>The smallest long side <see cref="IsDamaged"/> lets a JPEG be decoded at: the cheapest reduction.</summary>
private const int DamageCheckSide = 1;
+5 -2
View File
@@ -322,7 +322,8 @@ public static class ImportApi
review.CanMove,
review.StogramHypothesis,
review.Copied,
[.. accounts.OrderBy(a => a.Username, StringComparer.Ordinal).Select(a => new AccountChoiceDto(a.Id, a.Username, ApiMapping.State(a.State)))]);
[.. accounts.OrderBy(a => a.Username, StringComparer.Ordinal).Select(a => new AccountChoiceDto(a.Id, a.Username, ApiMapping.State(a.State)))],
review.Damaged);
}
public static DuplicateCaseDto Case(DuplicateCase item, IClock clock)
@@ -373,7 +374,9 @@ public static class ImportApi
[.. report.ImportedByAccount.Select(a => new ImportCountDto(a.Username, a.Files))],
[.. report.AlreadyInLibraryByAccount.Select(a => new ImportCountDto(a.Username, a.Files))],
report.Unrecognized,
[.. report.Problems.Select(p => new ImportNoteDto(p.Path, p.Note))]);
[.. report.Problems.Select(p => new ImportNoteDto(p.Path, p.Note))],
report.DamagedCount,
report.Damaged ?? []);
}
private static ImportMode ParseMode(string? text) => text?.ToLowerInvariant() switch
+11 -7
View File
@@ -227,7 +227,8 @@ public static class LibraryApi
var local = LocalCalendar.ToLocal(entry.PublishedAt, zone);
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
var media = stored.Media.Select(m =>
var media = new List<MediaDto>(stored.Media.Count);
foreach (var m in stored.Media)
{
var relative = m.RelativePath;
string? folder = null;
@@ -238,7 +239,8 @@ public static class LibraryApi
}
var path = files.Resolve(account, m);
return new MediaDto(
var damaged = await IsDamagedAsync(m, path, ct).ConfigureAwait(false);
media.Add(new MediaDto(
m.Id,
m.Position,
ApiMapping.Media(m.Kind),
@@ -251,8 +253,8 @@ public static class LibraryApi
m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null,
path is not null,
ApiMapping.State(m.State),
IsDamaged(m, path));
}).ToList();
damaged));
}
return new EntryDto(
entry.Id,
@@ -277,10 +279,12 @@ public static class LibraryApi
/// <summary>
/// «File danneggiato o incompleto» (spec §4.6, §8.4): a photo on disk with no thumbnail whose bytes are damaged or
/// truncated. A photo with a thumbnail was decoded when it was stored, so only those without one are looked at,
/// one file each time the viewer opens it; the file is only read, never touched (rule 12).
/// one file each time the viewer opens it, with asynchronous reads and the answer kept for the same file; a format
/// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole.
/// The file is only read, never touched (rule 12).
/// </summary>
private static bool IsDamaged(Media media, string? path) =>
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && DamagedImage.IsFileDamaged(path);
private static async Task<bool> IsDamagedAsync(Media media, string? path, CancellationToken ct) =>
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false);
private static async Task<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct)
{
+5 -2
View File
@@ -311,7 +311,8 @@ public sealed record ImportReviewDto(
bool CanMove,
bool StogramHypothesis,
int Copied,
IReadOnlyList<AccountChoiceDto> Accounts);
IReadOnlyList<AccountChoiceDto> Accounts,
int Damaged);
/// <summary>Sets where a folder goes. <see cref="Kind"/>: none, existing (with <see cref="AccountId"/>), newArchiveAccount (with <see cref="Username"/>).</summary>
public sealed record FolderTargetRequest(string Folder, string Kind, long? AccountId, string? Username);
@@ -340,4 +341,6 @@ public sealed record ImportReportDto(
IReadOnlyList<ImportCountDto> ImportedByAccount,
IReadOnlyList<ImportCountDto> AlreadyInLibraryByAccount,
IReadOnlyList<string> Unrecognized,
IReadOnlyList<ImportNoteDto> Problems);
IReadOnlyList<ImportNoteDto> Problems,
int DamagedCount,
IReadOnlyList<string> Damaged);
+1 -1
View File
@@ -31,7 +31,7 @@
--r-pannello:10px;
--r-dialogo:14px;
--tratteggio:rgba(0,0,0,.075);
--carattere:system-ui,"Segoe UI",Roboto,Cantarell,"Noto Sans","Liberation Sans",sans-serif;
--carattere:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
}
[data-tema="scuro"]{
--fondo:#1B1B1B;
+5 -5
View File
@@ -328,7 +328,7 @@ export function savedSessionBox(saved, page) {
// Neither choice is shown as chosen, and neither can be picked, until the server says which one is stored: the page
// never claims a choice the next copy will not follow. Once Alberto picks one, a late answer no longer changes it;
// a choice the server did not save goes back to the one before.
let saved = null;
let stored = null;
let chosen = false;
const show = (value) => {
keep.input.checked = value === 'tieni-completa';
@@ -336,10 +336,10 @@ export function savedSessionBox(saved, page) {
};
const choose = async (value) => {
chosen = true;
const before = saved;
const before = stored;
try {
const settings = await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } });
saved = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
stored = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
unknown.hidden = true;
toast(k('salvato'));
} catch (error) {
@@ -353,8 +353,8 @@ export function savedSessionBox(saved, page) {
for (const choice of [replace, keep]) choice.input.disabled = true;
api('/api/connection/settings', { signal: page && page.signal }).then((settings) => {
if (chosen) return;
saved = settings.incompleteCopy;
show(saved);
stored = settings.incompleteCopy;
show(stored);
}).catch(() => {
if (page && page.signal && page.signal.aborted) return; // the page was left
if (!chosen) unknown.hidden = false;
+5 -1
View File
@@ -351,7 +351,8 @@ async function reviewStep(ctx, run) {
function drawNotes() {
fill(notes,
review.recognized > 0 ? h('div.avviso', icon('info', 's'), h('span', t('importa.revisione.riconosciuti', { n: number(review.recognized) }))) : null,
review.stogramHypothesis ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.stogram'))) : null);
review.stogramHypothesis ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.stogram'))) : null,
review.damaged > 0 ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.danneggiati', { n: number(review.damaged) }))) : null);
}
// The fixed bar: Copia/Sposta, what stays out, CSV, «Importa N file».
@@ -482,6 +483,9 @@ async function reportStep(ctx, run) {
h('section', h('h2', t('importa.resoconto.giaPerAccount')), h('div.pannello', accounts(report.alreadyInLibraryByAccount)))),
report.unrecognized.length ? h('section.blocco', h('h2', t('importa.resoconto.nonRiconosciuti')),
h('div.pannello', h('ul.elenco-semplice', report.unrecognized.map((u) => h('li.dati', u))))) : null,
report.damaged.length ? h('section.blocco', h('h2', t('importa.resoconto.danneggiati')),
h('div.pannello', h('ul.elenco-semplice', report.damaged.map((u) => h('li.dati', u))),
report.damagedCount > report.damaged.length ? h('p.aiuto', t('importa.resoconto.danneggiatiAltri', { n: number(report.damagedCount - report.damaged.length) })) : null)) : null,
report.problems.length ? h('section.blocco', h('h2', t('importa.resoconto.problemi')),
h('div.pannello', h('ul.elenco-semplice', report.problems.map((p) => h('li', h('span.dati', p.path), h('span.muto', p.note)))))) : null,
h('div.riga-azione',
+5 -2
View File
@@ -845,7 +845,7 @@
{ "nome": "WebView2", "testo": "solo versione Windows, licenza Microsoft" }
],
"leggiLicenza": "Leggi la licenza",
"fattoInCasa": "Il carattere è quello del tuo sistema e le icone sono disegnate per Febe: nessun carattere né icona di terzi."
"fattoInCasa": "Il carattere è quello del tuo sistema e le icone sono disegnate per Febe; le immagini (miniature, impronte visive, fotogrammi dei video) le legge e le disegna il codice di Febe: nessun carattere, icona o componente di terzi."
}
},
"browser": {
@@ -936,7 +936,8 @@
"nessunNome": "Nessun nome di account riconosciuto",
"esistenti": "Account in Febe",
"riconosciuti": "Dai nomi dei file Febe ha ricavato data e codice di {n} elementi: quando terrà aggiornati questi account non li riscaricherà.",
"stogram": "I nomi sono stati letti con l'ipotesi su 4K Stogram, non ancora verificata: controlla date e codici prima di importare."
"stogram": "I nomi sono stati letti con l'ipotesi su 4K Stogram, non ancora verificata: controlla date e codici prima di importare.",
"danneggiati": "File danneggiato o incompleto: 1 immagine troncata o rovinata. Si importa come le altre, ma senza miniatura né impronta visiva.|File danneggiato o incompleto: {n} immagini troncate o rovinate. Si importano come le altre, ma senza miniatura né impronta visiva."
},
"doppioni": {
"titolo": "Doppioni probabili",
@@ -997,6 +998,8 @@
"perAccount": "Importati per account",
"giaPerAccount": "Già in libreria, per account",
"nonRiconosciuti": "Non riconosciuti",
"danneggiati": "File danneggiato o incompleto",
"danneggiatiAltri": "e altri {n}: sono tutti nell'elenco CSV.",
"problemi": "Da guardare",
"nessuno": "Nessuno",
"nuova": "Nuova importazione",