diff --git a/docs/decisioni.md b/docs/decisioni.md index aea492f..e852776 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -482,3 +482,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Impronta percettiva e misure di una foto da una sola lettura e una sola decodifica (`PerceptualHash.ComputeWithSize`, usata da importazione, ricostruzione, copia dell'importazione e analisi); `ImageDecoding.ReadSize(Stream)` legge prima 256 KiB per JPEG, GIF e BMP e il resto solo se le intestazioni non ci stanno; PNG e WebP sempre interi | Senza SkiaSharp `ReadSize` leggeva tutto il file solo per le misure, subito dopo l'impronta che lo leggeva di nuovo: ogni foto entrava in memoria due volte, e i file oltre 64 MiB dell'analisi («troppo grandi da tenere in memoria») due volte interi. Se la foto non si decodifica le misure vengono ancora dalle intestazioni, come prima | | 2026-11-18 | Correzione della riga sulle immagini di riferimento: l'insieme è di 116 file per 2.003.752 byte (circa 2,0 MB), non «circa 2,2 MB» | Somma di `git ls-tree -l` sul ramo `funzione/codec-immagini`; la riga resta com'era perché le righe si aggiungono soltanto | | 2026-11-18 | `Febe.exe` pubblicato senza SkiaSharp (`dotnet publish` come `installer/costruisci.sh`, un file solo e compresso): 85.583.840 byte, circa 86 MB come prima | Misurato di nuovo per `docs/windows.md`; la libreria nativa di Skia, compressa nel file solo, pesava poco | +| 2026-11-25 | **«File danneggiato o incompleto» nel visualizzatore** (risposta 3 di Alberto del 25 novembre; §4.6, §8.4): `MediaDto` ha `damaged`, vero per una foto sul disco senza miniatura che i codec di casa riconoscono ma non riescono a decodificare (`DamagedImage` in `Febe.Core.Library`: un errore di decodifica che non sia «formato non letto» né «troppo grande»). Il visualizzatore mostra «File danneggiato o incompleto» al posto dell'immagine, con le azioni sul file che restano; il mosaico ha già la tessera neutra (nessuna miniatura). Il controllo si fa quando il visualizzatore apre l'elemento, solo per le sue foto senza miniatura, decodificando un JPEG alla riduzione più piccola; nulla nel database. HEIC, i formati sconosciuti e le immagini oltre i limiti non sono «danneggiati». Il file si legge soltanto (§2 regola 12) | Il ramo dei codec rifiutava già le immagini troncate (niente miniatura, niente impronta, file tenuto con il suo SHA-256), ma il visualizzatore mostrava il file a metà come lo disegna il browser. Calcolarlo al volo evita una colonna e una migrazione e vale anche per le librerie già scaricate; con 200.000 elementi non pesa, perché riguarda solo le poche foto senza miniatura e solo quando si aprono. Restano da fare la revisione e il resoconto dell'importazione (§9.3) e l'anteprima della Dashboard (D1) | diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 22d82d4..6f032a5 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -78,6 +78,7 @@ Controlla in quest'ordine, guardando [Attività](Attivita-e-arresti): | File «da scaricare» che non arrivano | Gli scaricamenti hanno un loro tetto giornaliero di dati; durante un fermo continuano solo quelli già in coda. Un indirizzo scaduto torna «da scaricare» e si recupera rileggendo il post; per le storie scadute non c'è recupero | | Elementi «falliti» | Dopo cinque tentativi non riusciti un file resta «fallito»; anche una storia scaduta prima dello scaricamento finisce così | | Nel visualizzatore: «Il file non è sul disco» | Il file è stato spostato o cancellato fuori da Febe. Rimettilo dov'era o elimina l'elemento | +| Nel visualizzatore: «File danneggiato o incompleto», nel mosaico una tessera neutra | La foto è troncata o rovinata (uno scaricamento o una copia interrotti): Febe non la mostra a metà e non ne calcola l'impronta, quindi non la propone mai come doppione. Il file resta in libreria così com'è: Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Se non ti serve, elimina l'elemento | | «N doppioni da decidere» | Foto che sembrano la stessa immagine salvata due volte: decidi tu in «Doppioni da decidere» (vedi [Libreria](Libreria)) | | Un elemento eliminato torna | Hai usato «Eliminalo e lascia che torni»: elimina di nuovo con «Elimina dalla libreria» | | Il CSV si apre male in Excel | Aprilo con doppio clic (non con «Importa testo» impostando un altro separatore): è fatto per Excel in italiano, con `;` e UTF-8 con BOM | diff --git a/src/Febe.Core/Library/DamagedImage.cs b/src/Febe.Core/Library/DamagedImage.cs new file mode 100644 index 0000000..af2ac28 --- /dev/null +++ b/src/Febe.Core/Library/DamagedImage.cs @@ -0,0 +1,42 @@ +namespace Febe.Core.Library; + +/// +/// «File danneggiato o incompleto» (spec §4.6, §8.4; Alberto's answer of 25 November 2026): a photo truncated or +/// damaged, downloaded or imported, is refused and said so. It has no thumbnail (the neutral tile) and no perceptual +/// hash, so it is never a probable duplicate; its SHA-256 still counts. The file stays in the library (rule 12): this +/// class only looks, it never deletes, replaces or downloads again. +/// +/// +/// 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. +/// +public static class DamagedImage +{ + /// + /// 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 (HEIC, an unknown one) and for a + /// picture too large to decode. + /// + public static bool IsDamaged(ReadOnlyMemory data) => ImageDecoding.IsDamaged(data); + + /// + /// for a file on disk, read once; false when it cannot be read or is + /// larger than . + /// + 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); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + + return data is not null && ImageDecoding.IsDamaged(data); + } +} diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs index 8453f19..45f9c9e 100644 --- a/src/Febe.Core/Library/ImageDecoding.cs +++ b/src/Febe.Core/Library/ImageDecoding.cs @@ -75,6 +75,42 @@ internal static class ImageDecoding } } + /// + /// True when is in a format Febe decodes but cannot be decoded because it is damaged or + /// truncated (spec §8.4, «File danneggiato o incompleto»). False for a picture that decodes, for what Febe does not + /// read (unknown formats, HEIC, the JPEG processes it leaves out) and for a picture over the limits: those are not + /// damaged, Febe just has no picture of them. + /// + internal static bool IsDamaged(ReadOnlyMemory data) + { + if (data.IsEmpty || !ImageDecoder.CanDecode(ImageFormatSniffer.Detect(data.Span))) + { + return false; + } + + try + { + // A reduced JPEG decode still reads every scan to its end, so it finds a cut as the full decode does. + using var image = ImageDecoder.DecodeAtLeast(data, DamageCheckSide, out _, Limits, pooled: true); + return false; + } + catch (ImageLimitException) + { + return false; + } + catch (ImageFormatNotSupportedException) + { + return false; + } + catch (ImageDecodeException) + { + return true; + } + } + + /// The smallest long side lets a JPEG be decoded at: the cheapest reduction. + private const int DamageCheckSide = 1; + /// /// Bytes read first by for JPEG, GIF and BMP, whose headers (a JPEG EXIF block is /// at most 64 KiB) fit; when they do not (large ICC profiles) the rest of the file is read as well. PNG and WebP diff --git a/src/Febe.Web/Api/Dtos.cs b/src/Febe.Web/Api/Dtos.cs index 3edbc74..71faf7d 100644 --- a/src/Febe.Web/Api/Dtos.cs +++ b/src/Febe.Web/Api/Dtos.cs @@ -77,7 +77,8 @@ public sealed record MediaDto( string? Folder, string? Thumb, bool Available, - string State); + string State, + bool Damaged = false); /// Everything the viewer shows of an entry. public sealed record EntryDto( diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 39fb041..6b73f75 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -237,6 +237,7 @@ public static class LibraryApi folder = string.IsNullOrEmpty(directory) ? accountFolder : Path.Combine(accountFolder, directory); } + var path = files.Resolve(account, m); return new MediaDto( m.Id, m.Position, @@ -248,8 +249,9 @@ public static class LibraryApi relative is null ? null : Path.GetFileName(LibraryLayout.ToPlatform(relative)), folder, m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null, - files.Resolve(account, m) is not null, - ApiMapping.State(m.State)); + path is not null, + ApiMapping.State(m.State), + IsDamaged(m, path)); }).ToList(); return new EntryDto( @@ -272,6 +274,14 @@ public static class LibraryApi media); } + /// + /// «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). + /// + 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<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct) { var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato."); diff --git a/src/Febe.Web/wwwroot/js/pages/viewer.js b/src/Febe.Web/wwwroot/js/pages/viewer.js index da6e2c7..a3b302c 100644 --- a/src/Febe.Web/wwwroot/js/pages/viewer.js +++ b/src/Febe.Web/wwwroot/js/pages/viewer.js @@ -143,6 +143,11 @@ export function openViewer({ tile, source, origin, onDeleted }) { h('p', t(media.kind === 'video' ? 'vis.videoMancante' : 'vis.mancante')))); return; } + if (media.damaged) { + // Spec §4.6, §8.4: a truncated or damaged photo is never shown half; the file stays, its actions too. + fill(stage, h('div.mancante', icon('image', 'l'), h('p', h('b', t('vis.danneggiato'))), h('p', t('vis.danneggiatoTesto')))); + return; + } const src = `/api/media/${media.id}/file`; if (media.kind === 'video') { fill(stage, h('video', { src, poster: thumb, controls: true, autoplay: true, muted: true, playsinline: true, preload: 'metadata', 'aria-label': t('libreria.tipiTessera.' + entry.kind) })); diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index 65a5d93..1727851 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -202,6 +202,8 @@ "elimina": "Elimina dalla libreria", "mancante": "Il file non è sul disco: forse è stato spostato o cancellato fuori da Febe.", "videoMancante": "Il video non è sul disco: qui si vede solo la sua copertina.", + "danneggiato": "File danneggiato o incompleto", + "danneggiatoTesto": "Febe non riesce a leggere questa foto: forse lo scaricamento o la copia si sono interrotti. Il file resta nella libreria così com'è.", "tipoFile": "{tipo}, {media} {n} di {totale}", "tipoSingolo": "{tipo}, {media}", "seguito": "Seguito", diff --git a/tests/Febe.Tests/Library/DamagedImageTests.cs b/tests/Febe.Tests/Library/DamagedImageTests.cs new file mode 100644 index 0000000..78fda9e --- /dev/null +++ b/tests/Febe.Tests/Library/DamagedImageTests.cs @@ -0,0 +1,81 @@ +using System.Security.Cryptography; +using Febe.Core.Domain; +using Febe.Core.Library; +using Febe.Tests.Support; + +namespace Febe.Tests.Library; + +/// +/// «File danneggiato o incompleto» (spec §4.6, §8.4; Alberto's answer of 25 November 2026): a truncated PNG or JPEG +/// is refused and said so, with no thumbnail and no perceptual hash, and the file stays in the library as it came. +/// +[TestClass] +public sealed class DamagedImageTests +{ + [TestMethod] + public void ATruncatedPngOrJpegIsDamagedAndWhatFebeDoesNotReadIsNot() + { + using var scene = TestImages.Scene(4, 320, 240); + var jpeg = TestImages.Jpeg(scene, 85); + var png = TestImages.Png(scene); + + Assert.IsFalse(DamagedImage.IsDamaged(jpeg), "un JPEG intero"); + Assert.IsFalse(DamagedImage.IsDamaged(png), "un PNG intero"); + Assert.IsTrue(DamagedImage.IsDamaged(jpeg[..(jpeg.Length / 2)]), "un JPEG che finisce a metà della scansione"); + Assert.IsTrue(DamagedImage.IsDamaged(png[..(png.Length / 2)]), "un PNG che finisce a metà dei dati"); + Assert.IsTrue(DamagedImage.IsDamaged(png[..40]), "un PNG che finisce dentro l'intestazione"); + + // Not damaged: Febe just has no picture of them. + Assert.IsFalse(DamagedImage.IsDamaged(ReadOnlyMemory.Empty)); + Assert.IsFalse(DamagedImage.IsDamaged(new byte[100]), "un formato sconosciuto"); + byte[] heic = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. new byte[64]]; + Assert.IsFalse(DamagedImage.IsDamaged(heic), "HEIC: Febe non lo legge, ma non è rovinato"); + } + + [TestMethod] + public void AFileOnDiskIsReadOnceAndLeftAsItIs() + { + using var temp = new TempFolder(); + using var scene = TestImages.Scene(5, 200, 150); + var cut = TestImages.Jpeg(scene)[..900]; + var path = temp.Combine("foto.jpg"); + File.WriteAllBytes(path, cut); + var written = File.GetLastWriteTimeUtc(path); + + Assert.IsTrue(DamagedImage.IsFileDamaged(path)); + CollectionAssert.AreEqual(cut, File.ReadAllBytes(path), "il file resta com'è"); + Assert.AreEqual(written, File.GetLastWriteTimeUtc(path)); + Assert.IsFalse(DamagedImage.IsFileDamaged(temp.Combine("non-c-e.jpg")), "un file che non c'è non è danneggiato"); + } + + [TestMethod] + public async Task ADamagedPhotoIsStoredWithItsShaButNoThumbnailOrHashAndStays() + { + using var temp = new TempFolder(); + await using var library = await TestLibrary.CreateAsync(temp); + var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100")); + using var scene = TestImages.Scene(6, 640, 480); + var whole = TestImages.Jpeg(scene, 88); + var cutJpeg = whole[..(whole.Length * 2 / 3)]; + var png = TestImages.Png(scene); + var cutPng = png[..(png.Length / 2)]; + + var saved = await library.SaveAsync(account, Make.Entry(account.Id, "701", Make.T0), [new TestFile(Make.Photo(1), cutJpeg, ".jpg"), new TestFile(Make.Photo(2), cutPng, ".png")]); + var intact = await library.SaveAsync(account, Make.Entry(account.Id, "702", Make.T0 + TimeSpan.FromHours(1)), [new TestFile(Make.Photo(1), whole, ".jpg")]); + + Assert.AreEqual(EntryState.Downloaded, saved.Entry.State, "scaricato come gli altri: niente si riscarica da sé"); + foreach (var (media, bytes) in saved.Media.Zip([cutJpeg, cutPng])) + { + Assert.AreEqual(MediaState.Downloaded, media.State); + Assert.IsNull(media.PerceptualHash, "nessuna impronta visiva: mai doppione probabile per impronta"); + Assert.IsFalse(media.HasThumbnail, "la tessera neutra"); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), media.Sha256, "lo SHA-256 sì"); + var path = library.Layout.FullPath(account, media.RelativePath!); + CollectionAssert.AreEqual(bytes, await File.ReadAllBytesAsync(path), "il file resta in libreria com'è arrivato"); + Assert.IsTrue(DamagedImage.IsFileDamaged(path)); + } + + Assert.IsNotNull(intact.Media[0].PerceptualHash, "la stessa foto intera ha la sua impronta"); + Assert.IsTrue(intact.Media[0].HasThumbnail); + } +} diff --git a/tests/Febe.Tests/Web/LibraryApiTests.cs b/tests/Febe.Tests/Web/LibraryApiTests.cs index 934f6f7..74ebec4 100644 --- a/tests/Febe.Tests/Web/LibraryApiTests.cs +++ b/tests/Febe.Tests/Web/LibraryApiTests.cs @@ -111,6 +111,8 @@ public sealed class LibraryApiTests Assert.AreEqual("foto_1.jpg", media[0].Str("fileName")); Assert.AreEqual(Path.Combine("marta.demo", "post"), media[0].Str("folder")); Assert.IsFalse(media[1].Bool("available"), "a file missing from disk is said, not hidden"); + Assert.IsFalse(media[0].Bool("damaged"), "a whole photo without a thumbnail yet is not damaged"); + Assert.IsFalse(media[1].Bool("damaged")); using (var file = await server.Client.GetAsync($"/api/media/{media[0].Long("id")}/file?download=1")) { @@ -149,6 +151,49 @@ public sealed class LibraryApiTests Assert.AreEqual(JsonValueKind.Null, after.GetProperty("instagramUrl").ValueKind); } + [TestMethod] + public async Task ADamagedPhotoHasTheNeutralTileTheViewerSaysSoAndItsFileStays() + { + await using var server = await WebTestServer.StartAsync(); + var account = await server.Db.Accounts.AddAsync(Make.Account("marta.demo")); + var folder = server.Library.Layout.AccountFolder(account); + Directory.CreateDirectory(Path.Combine(folder, "post")); + var whole = TestImages.Jpeg(TestImages.Scene(7, 240, 180)); + var cut = whole[..(whole.Length / 2)]; + var png = TestImages.Png(TestImages.Scene(8, 120, 90)); + var cutPng = png[..(png.Length / 2)]; + await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_1.jpg"), cut); + await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_2.png"), cutPng); + await File.WriteAllBytesAsync(Path.Combine(folder, "post", "foto_3.jpg"), whole); + var added = await server.Db.Entries.AddAsync( + Make.Entry(account.Id, "1", Make.T0) with { State = EntryState.Downloaded }, + [ + Make.Stored(Make.Photo(1), Make.Sha(1), "post/foto_1.jpg") with { Bytes = cut.Length }, + Make.Stored(Make.Photo(2), Make.Sha(2), "post/foto_2.png") with { Bytes = cutPng.Length }, + Make.Stored(Make.Photo(3), Make.Sha(3), "post/foto_3.jpg") with { Bytes = whole.Length }, + ]); + var id = added.Stored.Entry.Id; + + var tile = (await server.GetJsonAsync("/api/library")).Items("tiles").Single(); + Assert.AreEqual(JsonValueKind.Null, tile.GetProperty("cover").GetProperty("thumb").ValueKind, "the neutral tile in the mosaic"); + + var media = (await server.GetJsonAsync($"/api/entries/{id}")).Items("media").ToList(); + Assert.IsTrue(media[0].Bool("damaged"), "a JPEG cut in its scan: «File danneggiato o incompleto»"); + Assert.IsTrue(media[1].Bool("damaged"), "a PNG cut in its data"); + Assert.IsFalse(media[2].Bool("damaged")); + Assert.IsTrue(media.All(m => m.Bool("available")), "the file is in the library: its actions stay"); + + // The file stays as it came, and can still be downloaded (rule 12: Febe never deletes or replaces it). + using (var file = await server.Client.GetAsync($"/api/media/{media[0].Long("id")}/file?download=1")) + { + Assert.AreEqual(HttpStatusCode.OK, file.StatusCode); + CollectionAssert.AreEqual(cut, await file.Content.ReadAsByteArrayAsync()); + } + + CollectionAssert.AreEqual(cut, await File.ReadAllBytesAsync(Path.Combine(folder, "post", "foto_1.jpg"))); + Assert.AreEqual(MediaState.Downloaded, (await server.Db.Media.GetAsync(media[0].Long("id")))!.State); + } + [TestMethod] public async Task DeletionCanLetTheEntryComeBack() {