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:
1 parent
3d234f8791
commit
2068dd28f3
35 files changed
+1366
-75
No files matched your search
@@ -533,3 +533,12 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-11-18 | Schermate dell'interfaccia con `tools/Febe.Schermate`, un programma C# (`ClientWebSocket` e `System.Text.Json`, nessun pacchetto) che sostituisce `tools/schermate` (sostituisce la riga del 2026-10-13); resta il Chromium senza finestra, come le prove dell'interfaccia (`UiBrowser`), solo verso 127.0.0.1, localhost o [::1] | Lo strumento di prima voleva Node; la regola «Chromium mai headless» riguarda il browser di Febe verso il sito, non le schermate dell'interfaccia di Febe stessa |
|
||||
| 2026-11-25 | Unione della catena della 0.3.0 in `funzione/senza-terzi`: la CI, l'immagine e le guide di C6 restano (solo comandi, niente Node, installatore `src/Febe.Installer`, carattere del sistema e icone di Febe, Febe processo 1) senza più ffmpeg e con la categoria «da fare» di `riepilogo-prove.sh`; la guida (`docs/guida/Sviluppo.md`) dice che Node, il programma di installazione, il carattere e le icone di terzi sono usciti con la tappa C6 senza nominare gli ultimi tre, e `SpecificationConsistencyTests` lo ammette solo per la guida; `InstallerTests` ammette NSIS solo nella regola 12 di `CLAUDE.md`, copia dell'appendice A della specifica | Le prove di C6 vietano NSIS, Archivo e Lucide in `docs/guida` e in `CLAUDE.md`, quelle dei documenti chiedevano che la regola li nominasse con la loro tappa: con C6 fatta i nomi possono uscire dalla guida, mentre la regola 12 di `CLAUDE.md` e la specifica sono del lavoro sui documenti |
|
||||
| 2026-11-25 | Immagine Docker e contenitore delle prove: `fonts-noto-color-emoji` torna accanto a `fonts-dejavu-core`, con il suo motivo nel `Dockerfile` e nella tabella di `docs/docker.md`; `fonts-liberation` resta fuori. `ImageContentsTests` lo ammette e chiede gli stessi due caratteri in `ambiente-prove.sh` (sostituisce, per le emoji, la riga del 18 novembre che toglieva i due caratteri) | Risposta di Alberto del 25 novembre 2026: a Chromium le emoji servono per mostrare le pagine (senza, quadratini nella vista remota); Liberation non serve |
|
||||
| 2026-11-25 | Revisione della catena su `funzione/senza-terzi`: `ImageFormatSniffer.Detect` dice HEIF per ogni file che `HeifDecoder.Looks` accetta (mif2, MiHE, o una marca HEIF solo fra le compatibili), dopo il controllo di AVIF | La facciata delle immagini sceglie il decodificatore con `Detect`: con un elenco più stretto un HEIC di quelle marche restava senza miniatura, impronta e dimensioni, mentre `MediaSniffer` lo archiviava come foto HEIC |
|
||||
| 2026-11-25 | Docker, lasciare la pagina del browser: una vista che si riapre cancella un abbandono annunciato prima (il `pageLeft` tardivo di una pagina ricaricata, la vecchia vista chiusa da «Riprova»), e l'attesa di un altro comando del collegamento prima della copia dura al più `LetGoWait` (30 s), come alla chiusura della finestra su Windows; poi il permesso finisce senza copia | §6.0: il browser spento non vale come abbandono, quindi una vista chiusa dal server deve aspettare `DrivingGrace`; e il motore non deve restare trattenuto da un comando lungo |
|
||||
| 2026-11-25 | JPEG e PNG che finiscono prima del loro marcatore di fine (EOI, IEND) non si decodificano più, anche con le scansioni o i dati completi: sono «File danneggiato o incompleto»; `Identify` ne legge ancora le dimensioni | §3 lo chiede alla lettera; un JPEG progressivo tagliato fra due scansioni dava un'immagine di qualità minore, con miniatura e impronta, senza dirlo |
|
||||
| 2026-11-25 | Visualizzatore: il controllo «danneggiato» guarda prima l'intestazione (formati che Febe non decodifica, HEIC, PNG/GIF/BMP/WebP oltre i 100 megapixel dall'intestazione: mai danneggiati, senza leggere il resto), legge con I/O asincrono e tiene la risposta per percorso, lunghezza e data di modifica (al più 512) | Ogni apertura del visualizzatore rileggeva tutto il file, fino a 512 MB, per arrivare al limite già scritto nell'intestazione |
|
||||
| 2026-11-25 | Importazione (§9.3): l'analisi segna le immagini danneggiate o troncate; la revisione lo dice in un avviso, il resoconto le elenca sotto «File danneggiato o incompleto» e l'elenco CSV lo scrive nella colonna «Nota». Gli identificativi stanno nell'impostazione `importazione.<n>.danneggiati` della singola importazione, come le altre sue impostazioni, senza una colonna nuova in `import_file` | La migrazione `0002` è riservata alla tappa E1 (§8.3): un'impostazione dell'importazione evita una migrazione fuori piano; i file danneggiati sono pochi |
|
||||
| 2026-11-25 | Moduli dell'interfaccia: una prova senza browser (`ScriptSyntaxTests`, lettore di simboli in casa) cerca le parentesi che non tornano, `let`/`const`/`class` dichiarati due volte nello stesso blocco o col nome di un parametro o di un'importazione, e le importazioni statiche di nomi che l'altro modulo non esporta | `let saved` in `savedSessionBox(saved, …)` era un errore di sintassi che fermava `connection.js` e con lui le pagine Browser e Collegamento; le prove con Chromium girano solo nella CI. Niente Node (regola 12) |
|
||||
| 2026-11-25 | Le sei prove di `PipelineTests.Pulizia` con il limite di 5 minuti girano una per volta, dopo le altre (`[DoNotParallelize]`), senza alzare il limite | In un giro completo in locale, accanto alle suite di conformità H.264/H.265, superavano i 5 minuti; da sole ne prendono circa uno |
|
||||
| 2026-11-25 | Carattere: il token `--carattere` è esattamente la pila dell'appendice B (`system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`), che `InHouseAssetsTests` confronta con la specifica; sostituisce la pila del 18 novembre con Cantarell, "Noto Sans" e "Liberation Sans" | La specifica fissa la pila; Liberation è fuori anche dall'immagine. Resta per i documenti: l'appendice B non elenca il token `--carattere` |
|
||||
| 2026-11-25 | Il commit di unione 537517b ha nel messaggio, dopo `Co-Authored-By`, le righe `# Conflicts:` lasciate da git: si accetta così, sapendolo | Rifarlo vorrebbe dire riscrivere la storia di cinque rami locali costruiti sopra; `git interpret-trailers` legge lo stesso il `Co-Authored-By` |
|
||||
@@ -32,7 +32,7 @@ dati.
|
||||
| La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso |
|
||||
| Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) |
|
||||
| «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» |
|
||||
| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era. Se invece il messaggio dice che la sessione «era già stata copiata quando il browser è tornato al motore», Febe l'ha copiata quando hai lasciato il browser (su Windows chiudendo la finestra, o alla fine della guida) e il browser era già tornato al motore: se il messaggio non dice che mancano valori, non serve fare nulla. In Docker lasciare la pagina senza «Ho finito» non copia: premi «Ho finito» prima di uscire |
|
||||
| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era. Se invece il messaggio dice che la sessione «era già stata copiata quando il browser è tornato al motore», Febe l'ha copiata quando hai lasciato il browser (su Windows chiudendo la finestra, in Docker lasciando la pagina del browser, o alla fine della guida) e il browser era già tornato al motore: se il messaggio non dice che mancano valori, non serve fare nulla. In Docker, se lasci la pagina del browser (o ne chiudi la scheda) senza «Ho finito», Febe aspetta 5 secondi: se nessuna vista del browser si riapre copia la sessione e restituisce il browser al motore; solo «Annulla» lo restituisce senza copiare |
|
||||
| «Serve «Ho finito»» (barra laterale o pagina Collegamento) | Solo con la raccolta «richieste»: il browser ha la sessione, ma Febe non ha una copia leggibile per le richieste (dopo «Annulla», o con un file che non si legge più). Il motore aspetta: dalla pagina Collegamento apri la tua pagina iniziale nel browser e premi «Ho finito» |
|
||||
| «Alla pagina mancavano … Febe tiene la copia completa salvata prima e non usa quella nuova» | Hai scelto «Tieni la copia completa» nella pagina Collegamento e alla pagina mancava un valore che le richieste usano. Se hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque» e premi di nuovo «Ho finito» |
|
||||
| «Sessione copiata…, ma non ancora scritta su disco» | Il disco ha rifiutato la scrittura (spazio, permessi di `/dati/sessione`): Febe usa la copia in memoria e riprova alla prossima scrittura. Controlla lo spazio e i permessi; il registro dice il tipo d'errore |
|
||||
|
||||
@@ -18,7 +18,8 @@ copia altrove.
|
||||
|
||||
Con la raccolta «richieste» (`FEBE_RACCOLTA`, `--raccolta`) «Ho finito» copia la sessione del browser in
|
||||
`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe; la copia si fa anche quando chiudi
|
||||
la finestra del browser su Windows e quando la guida del browser finisce da sola (vedi
|
||||
la finestra del browser su Windows, in Docker quando lasci la pagina del browser senza «Ho finito», e quando la guida
|
||||
del browser finisce da sola (vedi
|
||||
[Primo collegamento](Primo-collegamento)). Con Instagram, per ora, non succede: la copia si accende solo quando ci sono
|
||||
richieste configurate.
|
||||
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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++;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -369,6 +369,104 @@ public sealed class SessionCopyOnLetGoTests
|
||||
Assert.IsNull(bed.App.SavedSession!.Read());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task ABeginOfAReloadedPageCancelsTheLeaveEvenBeforeItsViewOpens()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await StartAsync();
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
|
||||
var view = await DockerBeginAsync(bed);
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
browser.FakeCdp.Navigated(Site + "/");
|
||||
|
||||
// A reload where the new page's «begin» arrives but its view does not open within the moment: «begin» alone says
|
||||
// Alberto is back. Waited past PageLeaveGrace and well below DrivingGrace.
|
||||
await connection.LeavePageAsync(ct);
|
||||
view.Dispose();
|
||||
connection.RemoteViewClosed();
|
||||
await BeginAsync(bed, openLogin: false);
|
||||
await browser.HideFromUserAsync(ct);
|
||||
await Task.Delay(TimeSpan.FromSeconds(2.5), ct);
|
||||
Assert.IsTrue(browser.UserIsDriving, "begin cancels the leave");
|
||||
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
|
||||
Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
[DataRow(false, DisplayName = "«pageLeft» tardivo della pagina ricaricata")]
|
||||
[DataRow(true, DisplayName = "vecchia vista chiusa da «Riprova»")]
|
||||
public async Task ALeaveFollowedByAViewOpenAgainIsForgottenWhenThatViewEndsFromTheServer(bool oldViewClosed)
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await StartAsync();
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
|
||||
var view = await DockerBeginAsync(bed);
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
browser.FakeCdp.Navigated(Site + "/");
|
||||
|
||||
// The leave arrives while a view is open: the keepalive «pageLeft» of a reloaded page after the new page's
|
||||
// «begin», or the old socket closed by «Riprova» while the new view opens without «begin».
|
||||
if (oldViewClosed)
|
||||
{
|
||||
connection.RemoteViewClosed();
|
||||
}
|
||||
else
|
||||
{
|
||||
await connection.LeavePageAsync(ct);
|
||||
}
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(600), ct);
|
||||
|
||||
// That view then ends from the server (the browser stopped): it is not told to the connection. A browser that is
|
||||
// down is not leaving it, so the lease waits for DrivingGrace, not for PageLeaveGrace.
|
||||
view.Dispose();
|
||||
await Task.Delay(TimeSpan.FromSeconds(2.5), ct);
|
||||
Assert.IsTrue(browser.UserIsDriving, "the earlier leave was forgotten once a view was open again");
|
||||
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
|
||||
Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task LeavingTheBrowserPageWaitsForAnotherCommandOnlyForLetGoWait()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await StartAsync();
|
||||
var browser = bed.Browser!;
|
||||
var connection = bed.App.Connection!;
|
||||
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300);
|
||||
connection.LetGoWait = TimeSpan.FromMilliseconds(500);
|
||||
connection.PageTurnWait = TimeSpan.FromSeconds(30);
|
||||
var view = await DockerBeginAsync(bed);
|
||||
browser.FakeCdp.LoggedIn = true;
|
||||
browser.FakeCdp.Navigated(Site + "/");
|
||||
|
||||
// «Pagina iniziale» holds the commands of the connection while it waits for the page's turn, which a step of the
|
||||
// profile search keeps for longer than leaving the page may wait.
|
||||
using var press = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
Task startPage;
|
||||
using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct))
|
||||
{
|
||||
startPage = connection.OpenStartPageAsync(press.Token);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(200), ct);
|
||||
view.Dispose();
|
||||
connection.RemoteViewClosed();
|
||||
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo l'attesa massima");
|
||||
press.Cancel();
|
||||
}
|
||||
|
||||
await startPage;
|
||||
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
|
||||
StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione non copiata, un altro comando del collegamento era ancora in corso.");
|
||||
Assert.IsNull(bed.App.SavedSession!.Read());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(60_000, CooperativeCancellation = true)]
|
||||
public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack()
|
||||
|
||||
@@ -3,7 +3,7 @@ using Febe.Core.Codecs.Images;
|
||||
namespace Febe.Tests.Imaging;
|
||||
|
||||
/// <summary>
|
||||
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (no EOI, bytes after EOI,
|
||||
/// Damaged and unusual JPEG files: the decoder reads what T.81 and common practice allow (bytes after EOI,
|
||||
/// no DHT as in Motion JPEG), refuses what it cannot read with the right exception, and never fails in any other way.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
@@ -34,9 +34,11 @@ public sealed class JpegMalformedTests
|
||||
}
|
||||
}
|
||||
|
||||
// Only the EOI missing: complete scans are accepted.
|
||||
using var withoutEoi = JpegDecoder.Decode(file[..^2]);
|
||||
ImageAssert.AreEqual(whole, withoutEoi, $"senza EOI, ripristino {restart}");
|
||||
// Only the EOI missing: incomplete all the same (spec §3), though its size is still read.
|
||||
var withoutEoi = file[..^2];
|
||||
var error = Assert.Throws<ImageDecodeException>(() => JpegDecoder.Decode(withoutEoi), $"senza EOI, ripristino {restart}");
|
||||
StringAssert.Contains(error.Message, "EOI");
|
||||
Assert.AreEqual((whole.Width, whole.Height), (JpegDecoder.Identify(withoutEoi).Width, JpegDecoder.Identify(withoutEoi).Height));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -290,7 +290,7 @@ public sealed class PngCodecTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryTruncationEitherFailsOrGivesTheWholeImage()
|
||||
public void EveryTruncationFailsEvenAfterTheLastImageData()
|
||||
{
|
||||
var reference = ReferenceImages.Get("png-tav-4-adam7");
|
||||
var full = reference.ReadInput();
|
||||
@@ -310,23 +310,10 @@ public sealed class PngCodecTests
|
||||
}
|
||||
}
|
||||
|
||||
// Only cuts at a chunk boundary after the last IDAT keep everything (a missing IEND is accepted).
|
||||
var lastIdatEnd = 8;
|
||||
var boundaries = new List<int>();
|
||||
for (var pos = 8; pos < full.Length;)
|
||||
{
|
||||
var length = (int)BinaryPrimitives.ReadUInt32BigEndian(full.AsSpan(pos));
|
||||
var type = Encoding.ASCII.GetString(full, pos + 4, 4);
|
||||
pos += length + 12;
|
||||
boundaries.Add(pos);
|
||||
if (type == "IDAT")
|
||||
{
|
||||
lastIdatEnd = pos;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.AreEqual(boundaries.Count(b => b >= lastIdatEnd && b < full.Length), whole);
|
||||
Assert.IsGreaterThanOrEqualTo(1, whole);
|
||||
// Spec §3: a PNG that ends before IEND is incomplete, also when the cut falls after the last IDAT.
|
||||
Assert.AreEqual(0, whole);
|
||||
var error = Assert.Throws<ImageDecodeException>(() => PngDecoder.Decode(full[..^12]), "solo IEND mancante");
|
||||
StringAssert.Contains(error.Message, "IEND");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -513,6 +513,46 @@ public sealed class ImportCopyTests
|
||||
CollectionAssert.AreEqual(new[] { "marta.demo/documento.pdf" }, report.Unrecognized.ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheReviewTheReportAndTheCsvMarkADamagedImageImportedLikeTheOthers()
|
||||
{
|
||||
// Spec §9.3: a truncated image has its type and SHA-256 but no fingerprint; it is imported like the others and
|
||||
// the review and the report mark it «File danneggiato o incompleto».
|
||||
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 whole = ImportTestFiles.Photo(130);
|
||||
var cut = whole[..(whole.Length * 2 / 3)];
|
||||
bed.Write("marta.demo/tagliata.jpg", cut);
|
||||
bed.Write("marta.demo/intera.jpg", ImportTestFiles.Photo(131));
|
||||
bed.Write("marta.demo/nota.txt", "testo"u8.ToArray());
|
||||
var run = await bed.AnalyzeAsync();
|
||||
|
||||
var summary = await bed.Review.GetSummaryAsync(run.Id);
|
||||
Assert.AreEqual(1, summary.Damaged);
|
||||
var files = await bed.FilesAsync(run.Id);
|
||||
var damaged = files.Single(f => f.RelativePath == "marta.demo/tagliata.jpg");
|
||||
Assert.AreEqual(ImportOutcome.New, damaged.Outcome, "si importa come le altre");
|
||||
Assert.IsNull(damaged.PerceptualHash, "nessuna impronta visiva");
|
||||
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(cut)), damaged.Sha256);
|
||||
|
||||
await bed.Copier.CopyAsync(run.Id);
|
||||
Assert.AreEqual(ImportFileState.Copied, (await bed.FilesAsync(run.Id)).Single(f => f.Id == damaged.Id).State);
|
||||
var report = await bed.Reports.GetReportAsync(run.Id);
|
||||
Assert.AreEqual(1, report.DamagedCount);
|
||||
CollectionAssert.AreEqual(new[] { "marta.demo/tagliata.jpg" }, report.Damaged!.ToArray());
|
||||
|
||||
using var output = new MemoryStream();
|
||||
await bed.Reports.WriteCsvAsync(run.Id, output);
|
||||
var lines = System.Text.Encoding.UTF8.GetString(output.ToArray()).Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
|
||||
StringAssert.EndsWith(lines.Single(l => l.StartsWith("marta.demo/tagliata.jpg;", StringComparison.Ordinal)), ";File danneggiato o incompleto");
|
||||
Assert.DoesNotContain("danneggiato", lines.Single(l => l.StartsWith("marta.demo/intera.jpg;", StringComparison.Ordinal)));
|
||||
|
||||
// An analysis that starts again marks it once.
|
||||
await ImportRunSettings.AddDamagedAsync(bed.Library.Db.Settings, run.Id, [damaged.Id], CancellationToken.None);
|
||||
Assert.AreEqual(1, (await bed.Review.GetSummaryAsync(run.Id)).Damaged);
|
||||
}
|
||||
|
||||
private sealed class SyncProgress(Action<ImportProgress> report) : IProgress<ImportProgress>
|
||||
{
|
||||
public void Report(ImportProgress value) => report(value);
|
||||
|
||||
@@ -48,6 +48,60 @@ public sealed class DamagedImageTests
|
||||
Assert.IsFalse(DamagedImage.IsFileDamaged(temp.Combine("non-c-e.jpg")), "un file che non c'è non è danneggiato");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ThePictureOverTheLimitOrAFormatFebeDoesNotDecodeIsToldFromItsFirstBytes()
|
||||
{
|
||||
// 20,000 × 20,000 = 400 megapixels: over the limit, never damaged, so never read whole for nothing.
|
||||
var ihdr = Febe.Tests.Imaging.TestImages.Ihdr(20_000, 20_000, 8, 6);
|
||||
var hugePng = Febe.Tests.Imaging.TestImages.Png(("IHDR", ihdr), ("IDAT", new byte[64]), ("IEND", []));
|
||||
Assert.AreEqual(400_000_000L, ImageDecoding.HeaderPixels(Febe.Core.Codecs.Images.ImageFormat.Png, hugePng));
|
||||
Assert.IsFalse(ImageDecoding.MayBeDamaged(hugePng));
|
||||
|
||||
byte[] gif = [.. "GIF89a"u8, 0x10, 0x27, 0x10, 0x27, 0, 0, 0];
|
||||
Assert.AreEqual(100_000_000L, ImageDecoding.HeaderPixels(Febe.Core.Codecs.Images.ImageFormat.Gif, gif));
|
||||
byte[] vp8x = [.. "RIFF"u8, 0, 0, 0, 0, .. "WEBPVP8X"u8, 10, 0, 0, 0, 0, 0, 0, 0, 0x0F, 0x27, 0, 0x0F, 0x27, 0];
|
||||
Assert.AreEqual(100_000_000L, ImageDecoding.HeaderPixels(Febe.Core.Codecs.Images.ImageFormat.WebP, vp8x), "VP8X: 10,000 × 10,000");
|
||||
byte[] heic = [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8];
|
||||
Assert.IsFalse(ImageDecoding.MayBeDamaged(heic));
|
||||
Assert.IsFalse(ImageDecoding.MayBeDamaged(new byte[64]), "un formato sconosciuto");
|
||||
|
||||
using var scene = TestImages.Scene(7, 120, 90);
|
||||
var png = TestImages.Png(scene);
|
||||
Assert.IsTrue(ImageDecoding.MayBeDamaged(png), "un PNG piccolo va guardato tutto");
|
||||
Assert.IsTrue(ImageDecoding.MayBeDamaged(TestImages.Jpeg(scene)), "un JPEG si decodifica ridotto: va guardato tutto");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheViewerAsksAsynchronouslyAndTheSameFileIsAnsweredOnce()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
using var temp = new TempFolder();
|
||||
using var scene = TestImages.Scene(8, 200, 150);
|
||||
var whole = TestImages.Jpeg(scene);
|
||||
var cutPath = temp.Combine("tagliata.jpg");
|
||||
var wholePath = temp.Combine("intera.jpg");
|
||||
var hugePath = temp.Combine("enorme.png");
|
||||
File.WriteAllBytes(cutPath, whole[..(whole.Length / 2)]);
|
||||
File.WriteAllBytes(wholePath, whole);
|
||||
var ihdr = Febe.Tests.Imaging.TestImages.Ihdr(20_000, 20_000, 8, 6);
|
||||
File.WriteAllBytes(hugePath, [.. Febe.Tests.Imaging.TestImages.Png(("IHDR", ihdr)), .. new byte[600_000]]);
|
||||
|
||||
Assert.IsTrue(await DamagedImage.IsFileDamagedAsync(cutPath, ct));
|
||||
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(wholePath, ct));
|
||||
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(hugePath, ct), "oltre il limite: non danneggiato");
|
||||
Assert.IsFalse(DamagedImage.IsFileDamaged(hugePath));
|
||||
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(temp.Combine("non-c-e.jpg"), ct));
|
||||
|
||||
// The answer is kept for the same file: a file locked for reading still gets it. A changed file is looked at again.
|
||||
using (new FileStream(cutPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
Assert.IsTrue(await DamagedImage.IsFileDamagedAsync(cutPath, ct), "la risposta di prima, senza rileggere");
|
||||
}
|
||||
|
||||
File.WriteAllBytes(cutPath, whole);
|
||||
Assert.IsFalse(await DamagedImage.IsFileDamagedAsync(cutPath, ct), "il file cambiato si guarda di nuovo");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADamagedPhotoIsStoredWithItsShaButNoThumbnailOrHashAndStays()
|
||||
{
|
||||
|
||||
@@ -179,6 +179,43 @@ public sealed class HeifDecoderTests
|
||||
Assert.AreEqual((picture.Frame.Height, picture.Frame.Width), ImageDecoding.ReadSize(stream));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("mif2", null, DisplayName = "marca principale mif2")]
|
||||
[DataRow("MiHE", null, DisplayName = "marca principale MiHE")]
|
||||
[DataRow("isom", "heic", DisplayName = "heic solo fra le marche compatibili")]
|
||||
public void TheImageFacadeTakesEveryBrandTheHeifDecoderTakes(string major, string? compatibleOnly)
|
||||
{
|
||||
// The facade picks the decoder from the first bytes: it must take every file HeifDecoder.Looks takes,
|
||||
// or such a HEIC would lose its thumbnail, its fingerprint and its size.
|
||||
var picture = CodedPicture.First(Tiles[0]);
|
||||
var builder = new HeifBuilder { Brand = major };
|
||||
if (compatibleOnly is not null)
|
||||
{
|
||||
builder.CompatibleBrands = ["isom", compatibleOnly];
|
||||
}
|
||||
|
||||
var hvcC = builder.Property(HeifBuilder.HvcCProperty(picture.HvcC));
|
||||
var ispe = builder.Property(HeifBuilder.Ispe(picture.Frame.Width, picture.Frame.Height));
|
||||
builder.Item(1, "hvc1", picture.Data, -hvcC, ispe);
|
||||
var file = builder.Build();
|
||||
Assert.IsTrue(HeifDecoder.Looks(file));
|
||||
Assert.AreEqual(ImageFormat.Heif, ImageFormatSniffer.Detect(file));
|
||||
using (var image = ImageDecoder.Decode(file, out _))
|
||||
{
|
||||
CollectionAssert.AreEqual(Rgba(picture.Frame), image.ToArray());
|
||||
}
|
||||
|
||||
using (var stream = new MemoryStream(file))
|
||||
{
|
||||
Assert.AreEqual((picture.Frame.Width, picture.Frame.Height), ImageDecoding.ReadSize(stream));
|
||||
}
|
||||
|
||||
using var temp = new TempFolder("marca-heic");
|
||||
var store = new ThumbnailStore(temp.Combine("miniature"));
|
||||
Assert.IsTrue(store.Create(new string('b', 64), new MemoryStream(file)), "miniatura");
|
||||
Assert.IsNotNull(PerceptualHash.Compute(new MemoryStream(file)), "impronta visiva");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCleanApertureCutsThePicture()
|
||||
{
|
||||
|
||||
@@ -95,6 +95,9 @@ internal sealed class HeifBuilder
|
||||
/// <summary>Major brand of the ftyp box.</summary>
|
||||
public string Brand { get; set; } = "heic";
|
||||
|
||||
/// <summary>Compatible brands of the ftyp box; null means «mif1» and the major brand.</summary>
|
||||
public string[]? CompatibleBrands { get; set; }
|
||||
|
||||
/// <summary>The item data goes into idat instead of mdat.</summary>
|
||||
public bool InIdat { get; set; }
|
||||
|
||||
@@ -157,7 +160,8 @@ internal sealed class HeifBuilder
|
||||
|
||||
public byte[] Build()
|
||||
{
|
||||
var ftyp = Box("ftyp", [.. Encoding.ASCII.GetBytes(Brand), 0, 0, 0, 0, .. "mif1"u8, .. Encoding.ASCII.GetBytes(Brand)]);
|
||||
var compatible = CompatibleBrands ?? ["mif1", Brand];
|
||||
var ftyp = Box("ftyp", [.. Encoding.ASCII.GetBytes(Brand), 0, 0, 0, 0, .. compatible.SelectMany(Encoding.ASCII.GetBytes)]);
|
||||
|
||||
// The meta box is built twice: the first time only to learn its size, so that the offsets into mdat are known.
|
||||
var meta = Meta(0);
|
||||
|
||||
@@ -17,6 +17,9 @@ namespace Febe.Tests.Packaging;
|
||||
/// </summary>
|
||||
public sealed partial class PipelineTests
|
||||
{
|
||||
// The tests that run the cleanup script on the fake daemon take about a minute each on Windows (Git Bash): they run
|
||||
// one at a time after the parallel ones ([DoNotParallelize]), or next to the conformance suites of the video
|
||||
// decoders they went past their limit of five minutes in a full local run.
|
||||
private const string RegistryApi = "http://gitea.invalid/api/v1";
|
||||
|
||||
private const string WeeklyStep = "Pulizia completa del demone Docker e del registro";
|
||||
@@ -212,6 +215,7 @@ public sealed partial class PipelineTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade()
|
||||
{
|
||||
@@ -250,6 +254,7 @@ public sealed partial class PipelineTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task AfterEveryRunOnlyWhatNobodyUsesGoesAndADaemonThatRefusesIsOnlyAWarning()
|
||||
{
|
||||
@@ -275,6 +280,7 @@ public sealed partial class PipelineTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task TheCompleteCleanupTakesWhatNobodyUsesAndNeverAContainerVolumeOrNetworkOfAnotherProject()
|
||||
{
|
||||
@@ -328,6 +334,7 @@ public sealed partial class PipelineTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
|
||||
{
|
||||
@@ -394,6 +401,7 @@ public sealed partial class PipelineTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task OnTheContainerdStoreTheCleanupSaysSoAndTheAgesOfTheDryRunAreOnlyIndicative()
|
||||
{
|
||||
@@ -529,6 +537,7 @@ public sealed partial class PipelineTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
[Timeout(300_000, CooperativeCancellation = true)]
|
||||
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
|
||||
{
|
||||
|
||||
@@ -45,10 +45,14 @@ public sealed partial class InHouseAssetsTests
|
||||
var families = stack.Groups[1].Value.Split(',', StringSplitOptions.TrimEntries);
|
||||
Assert.AreEqual("system-ui", families[0], "prima il carattere del sistema");
|
||||
Assert.AreEqual("sans-serif", families[^1], "e in fondo il generico");
|
||||
CollectionAssert.Contains(families, "\"Segoe UI\"");
|
||||
CollectionAssert.Contains(families, "Roboto");
|
||||
CollectionAssert.Contains(families, "Cantarell");
|
||||
CollectionAssert.Contains(families, "\"Noto Sans\"");
|
||||
|
||||
// Exactly the stack of the specification (appendix B, «pila dei caratteri di sistema»), nothing more: no name of a
|
||||
// font the Docker image leaves out (Liberation).
|
||||
var specification = File.ReadAllText(Febe.Tests.Desktop.Support.Repository.PathOf("docs", "SPECIFICA.md"));
|
||||
var stated = SpecificationStack().Match(specification);
|
||||
Assert.IsTrue(stated.Success, "la pila dell'appendice B");
|
||||
Assert.AreEqual(stated.Groups[1].Value, stack.Groups[1].Value.Trim());
|
||||
Assert.DoesNotContain("Liberation", css);
|
||||
|
||||
foreach (var page in new[] { "index.html", "accesso.html" })
|
||||
{
|
||||
@@ -621,6 +625,9 @@ public sealed partial class InHouseAssetsTests
|
||||
Assert.IsGreaterThan(100, looked, "i file del programma sono stati letti");
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"pila dei caratteri di sistema `([^`]+)`")]
|
||||
private static partial Regex SpecificationStack();
|
||||
|
||||
[GeneratedRegex(@"--carattere:([^;]+);")]
|
||||
private static partial Regex CharacterToken();
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The modules of the interface load: a mistake that stops one module from parsing breaks every page importing it, and
|
||||
/// the Chromium tests that would see it run only in the CI. <see cref="ScriptCheck"/> reads them without a browser.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ScriptSyntaxTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void EveryModuleOfTheInterfaceReadsWithoutTheMistakesThatStopItLoading()
|
||||
{
|
||||
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
|
||||
var files = Directory.GetFiles(root, "*.js", SearchOption.AllDirectories);
|
||||
Assert.IsGreaterThan(30, files.Length, "the modules of the interface");
|
||||
var problems = new List<string>();
|
||||
foreach (var file in files)
|
||||
{
|
||||
var name = Path.GetRelativePath(root, file);
|
||||
problems.AddRange(ScriptCheck.Problems(File.ReadAllText(file)).Select(p => $"{name}, {p}"));
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryStaticImportNamesSomethingTheOtherModuleExports()
|
||||
{
|
||||
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
|
||||
var problems = new List<string>();
|
||||
var checkedNames = 0;
|
||||
foreach (var file in Directory.GetFiles(root, "*.js", SearchOption.AllDirectories))
|
||||
{
|
||||
foreach (var (from, names, line) in ScriptCheck.Imports(File.ReadAllText(file)))
|
||||
{
|
||||
if (!from.StartsWith('.'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, from));
|
||||
var where = $"{Path.GetRelativePath(root, file)}, riga {line}";
|
||||
if (!File.Exists(target))
|
||||
{
|
||||
problems.Add($"{where}: «{from}» non esiste");
|
||||
continue;
|
||||
}
|
||||
|
||||
var exports = ScriptCheck.Exports(File.ReadAllText(target));
|
||||
foreach (var name in names)
|
||||
{
|
||||
checkedNames++;
|
||||
if (!exports.Contains(name))
|
||||
{
|
||||
problems.Add($"{where}: «{from}» non esporta «{name}»");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(50, checkedNames);
|
||||
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("export function box(saved, page) {\n if (!saved) return null;\n let saved = null;\n}", "«saved» dichiarato di nuovo con let (già parametro", DisplayName = "parametro ridichiarato (connection.js, b29b35a)")]
|
||||
[DataRow("const show = (value) => { const value = 1; };", "«value» dichiarato di nuovo", DisplayName = "parametro di una freccia")]
|
||||
[DataRow("items.map(x => { let x = 2; return x; });", "«x» dichiarato di nuovo", DisplayName = "parametro senza parentesi")]
|
||||
[DataRow("function f() { let a = 1; if (a) { let b; } const a = 2; }", "«a» dichiarato di nuovo con const", DisplayName = "due volte nello stesso blocco")]
|
||||
[DataRow("import { h } from './dom.js';\nconst h = 1;", "«h» dichiarato di nuovo con const (già import", DisplayName = "nome già importato")]
|
||||
[DataRow("class A { m(p) { class p {} } }", "«p» dichiarato di nuovo con class", DisplayName = "classe con il nome di un parametro")]
|
||||
[DataRow("function f() { if (x) { return 1; }", "mai chiusa", DisplayName = "parentesi graffa mai chiusa")]
|
||||
[DataRow("const a = [1, 2);", "chiude «[»", DisplayName = "parentesi che non corrispondono")]
|
||||
[DataRow("const s = 'non chiusa;\n", "stringa non chiusa", DisplayName = "stringa non chiusa")]
|
||||
[DataRow("const s = `a ${b} c;\n", "modello fra apici inversi non chiuso", DisplayName = "modello non chiuso")]
|
||||
public void TheCheckFindsTheMistakesThatStopAModuleLoading(string source, string expected)
|
||||
{
|
||||
var problems = ScriptCheck.Problems(source);
|
||||
Assert.IsTrue(problems.Any(p => p.Contains(expected, StringComparison.Ordinal)), string.Join(" | ", problems.DefaultIfEmpty("(nessuno)")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("export function box(saved, page) {\n let stored = null;\n const show = (value) => { stored = value; };\n}", DisplayName = "la correzione di connection.js")]
|
||||
[DataRow("for (let i = 0; i < 3; i++) { let i2 = i; }\nfor (let i = 0; i < 3; i++) { const j = i; }", DisplayName = "variabili dei cicli")]
|
||||
[DataRow("const re = /a{2}[/}]\\//g; const half = 4 / 2; const t = `x ${ { a: 1 }.a } ${`y ${1}`}`;", DisplayName = "espressioni regolari, divisioni e modelli annidati")]
|
||||
[DataRow("function f(a) { { let a = 1; } if (a) { const a = 2; } }", DisplayName = "lo stesso nome in un blocco interno")]
|
||||
[DataRow("const o = { let: 1, const: 2 }; o.let = o.const;", DisplayName = "proprietà con nomi di parole chiave")]
|
||||
[DataRow("try { x(); } catch (error) { console.log(error); }\nconst error = 1;", DisplayName = "parametro di catch e nome fuori")]
|
||||
[DataRow("// a comment with ' and ` and {\n/* and } */ const a = \"}\";", DisplayName = "commenti e stringhe con parentesi")]
|
||||
public void TheCheckLeavesValidCodeAlone(string source)
|
||||
{
|
||||
var problems = ScriptCheck.Problems(source);
|
||||
Assert.IsEmpty(problems, string.Join(" | ", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ImportsAndExportsAreReadByTheirNames()
|
||||
{
|
||||
var exports = ScriptCheck.Exports("export function a() {}\nexport async function b() {}\nexport const c = 1;\nexport class D {}\nconst e = 1, f = 2;\nexport { e, f as g };\nexport default a;");
|
||||
CollectionAssert.AreEquivalent(new[] { "a", "b", "c", "D", "e", "g", "default" }, exports.ToArray());
|
||||
var imports = ScriptCheck.Imports("import { a, b as c } from './x.js';\nimport * as y from './y.js';\nconst z = await import('./z.js');");
|
||||
Assert.HasCount(2, imports);
|
||||
Assert.AreEqual("./x.js", imports[0].From);
|
||||
CollectionAssert.AreEqual(new[] { "a", "b" }, imports[0].Names);
|
||||
Assert.IsEmpty(imports[1].Names);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Febe.Tests.Web.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A small check of the interface's ES modules that runs without a browser (the Chromium tests run only in the CI): it
|
||||
/// reads the tokens of a module — comments, strings, template literals, regular expressions — and finds the mistakes
|
||||
/// that stop a whole module from loading, so that every page importing it breaks: brackets that do not match, a
|
||||
/// <c>let</c>, <c>const</c> or <c>class</c> declared twice in one block or with the name of a parameter of its function,
|
||||
/// or of an import, and a static import of a name the other module does not export. Not a JavaScript parser: what it
|
||||
/// does not understand (destructured bindings, <c>var</c>) it leaves alone rather than guess.
|
||||
/// </summary>
|
||||
internal static class ScriptCheck
|
||||
{
|
||||
private static readonly HashSet<string> RegexAfterWords = new(StringComparer.Ordinal)
|
||||
{
|
||||
"return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> NotFunctionBefore = new(StringComparer.Ordinal)
|
||||
{
|
||||
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> Reserved = new(StringComparer.Ordinal)
|
||||
{
|
||||
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
|
||||
"function", "class", "const", "let", "var", "this", "super", "null", "true", "false", "else", "do", "try", "catch",
|
||||
"finally", "throw", "case", "default", "break", "continue", "import", "export", "async", "instanceof",
|
||||
};
|
||||
|
||||
internal enum Kind
|
||||
{
|
||||
Word,
|
||||
Punct,
|
||||
Text,
|
||||
Number,
|
||||
Regex,
|
||||
}
|
||||
|
||||
internal readonly record struct Token(Kind Kind, string Value, int Line);
|
||||
|
||||
/// <summary>The problems found in the source of one module, each with its line; empty when it reads cleanly.</summary>
|
||||
public static List<string> Problems(string source)
|
||||
{
|
||||
var problems = new List<string>();
|
||||
List<Token> tokens;
|
||||
try
|
||||
{
|
||||
tokens = Tokens(source);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
problems.Add(ex.Message);
|
||||
return problems;
|
||||
}
|
||||
|
||||
CheckScopes(tokens, problems);
|
||||
return problems;
|
||||
}
|
||||
|
||||
/// <summary>The names a module exports (<c>export function</c>, <c>const</c>, <c>let</c>, <c>class</c>, <c>{ a as b }</c>, default).</summary>
|
||||
public static HashSet<string> Exports(string source)
|
||||
{
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
var tokens = Tokens(source);
|
||||
for (var i = 0; i < tokens.Count - 1; i++)
|
||||
{
|
||||
if (!IsWord(tokens[i], "export"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var j = i + 1;
|
||||
if (IsWord(tokens[j], "default"))
|
||||
{
|
||||
names.Add("default");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (IsWord(tokens[j], "async"))
|
||||
{
|
||||
j++;
|
||||
}
|
||||
|
||||
if (j < tokens.Count && tokens[j].Kind == Kind.Word && tokens[j].Value is "function" or "const" or "let" or "var" or "class")
|
||||
{
|
||||
j++;
|
||||
if (j < tokens.Count && IsPunct(tokens[j], "*"))
|
||||
{
|
||||
j++;
|
||||
}
|
||||
|
||||
if (j < tokens.Count && tokens[j].Kind == Kind.Word)
|
||||
{
|
||||
names.Add(tokens[j].Value);
|
||||
}
|
||||
}
|
||||
else if (j < tokens.Count && IsPunct(tokens[j], "{"))
|
||||
{
|
||||
for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++)
|
||||
{
|
||||
if (tokens[j].Kind == Kind.Word && (j + 1 >= tokens.Count || IsPunct(tokens[j + 1], ",") || IsPunct(tokens[j + 1], "}")))
|
||||
{
|
||||
names.Add(tokens[j].Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
/// <summary>The static imports of a module: the module named and the names taken from it (not «* as» nor default).</summary>
|
||||
public static List<(string From, List<string> Names, int Line)> Imports(string source)
|
||||
{
|
||||
var imports = new List<(string, List<string>, int)>();
|
||||
var tokens = Tokens(source);
|
||||
for (var i = 0; i < tokens.Count - 1; i++)
|
||||
{
|
||||
if (!IsWord(tokens[i], "import") || IsPunct(tokens[i + 1], "(") || IsPunct(tokens[i + 1], "."))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var names = new List<string>();
|
||||
var j = i + 1;
|
||||
for (; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++)
|
||||
{
|
||||
if (IsPunct(tokens[j], "{"))
|
||||
{
|
||||
for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++)
|
||||
{
|
||||
if (tokens[j].Kind == Kind.Word && !IsWord(tokens[j], "as") && (j == 0 || !IsWord(tokens[j - 1], "as")))
|
||||
{
|
||||
names.Add(tokens[j].Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (j < tokens.Count && IsWord(tokens[j], "from"))
|
||||
{
|
||||
j++;
|
||||
}
|
||||
|
||||
if (j < tokens.Count && tokens[j].Kind == Kind.Text)
|
||||
{
|
||||
imports.Add((tokens[j].Value, names, tokens[i].Line));
|
||||
}
|
||||
}
|
||||
|
||||
return imports;
|
||||
}
|
||||
|
||||
private static bool IsWord(Token token, string value) => token.Kind == Kind.Word && token.Value == value;
|
||||
|
||||
private static bool IsPunct(Token token, string value) => token.Kind == Kind.Punct && token.Value == value;
|
||||
|
||||
/// <summary>The tokens of the source; throws <see cref="FormatException"/> for an unfinished string, comment or regex.</summary>
|
||||
internal static List<Token> Tokens(string s)
|
||||
{
|
||||
var tokens = new List<Token>();
|
||||
|
||||
// Braces opened in code: '{' an ordinary one, 'E' the «${» of a template literal.
|
||||
var braces = new Stack<char>();
|
||||
var line = 1;
|
||||
var i = 0;
|
||||
var inTemplate = false;
|
||||
|
||||
bool RegexMayStart()
|
||||
{
|
||||
if (tokens.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var last = tokens[^1];
|
||||
return last.Kind switch
|
||||
{
|
||||
Kind.Punct => last.Value is not (")" or "]" or "}"),
|
||||
Kind.Word => RegexAfterWords.Contains(last.Value),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
|
||||
void ScanTemplate()
|
||||
{
|
||||
// From just after a backtick or the «}» of an expression, up to the closing backtick or the next «${».
|
||||
var start = line;
|
||||
var text = new StringBuilder();
|
||||
while (true)
|
||||
{
|
||||
if (i >= s.Length)
|
||||
{
|
||||
throw new FormatException($"riga {start}: modello fra apici inversi non chiuso");
|
||||
}
|
||||
|
||||
var c = s[i];
|
||||
if (c == '\\')
|
||||
{
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '\n')
|
||||
{
|
||||
line++;
|
||||
}
|
||||
|
||||
if (c == '`')
|
||||
{
|
||||
i++;
|
||||
inTemplate = false;
|
||||
tokens.Add(new Token(Kind.Text, text.ToString(), start));
|
||||
return;
|
||||
}
|
||||
|
||||
if (c == '$' && i + 1 < s.Length && s[i + 1] == '{')
|
||||
{
|
||||
i += 2;
|
||||
braces.Push('E');
|
||||
inTemplate = false;
|
||||
tokens.Add(new Token(Kind.Text, text.ToString(), start));
|
||||
tokens.Add(new Token(Kind.Punct, "${", line));
|
||||
return;
|
||||
}
|
||||
|
||||
text.Append(c);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
while (i < s.Length || inTemplate)
|
||||
{
|
||||
if (inTemplate)
|
||||
{
|
||||
ScanTemplate();
|
||||
continue;
|
||||
}
|
||||
|
||||
var c = s[i];
|
||||
if (c == '\n')
|
||||
{
|
||||
line++;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char.IsWhiteSpace(c))
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '/' && i + 1 < s.Length && s[i + 1] == '/')
|
||||
{
|
||||
while (i < s.Length && s[i] != '\n')
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '/' && i + 1 < s.Length && s[i + 1] == '*')
|
||||
{
|
||||
var end = s.IndexOf("*/", i + 2, StringComparison.Ordinal);
|
||||
if (end < 0)
|
||||
{
|
||||
throw new FormatException($"riga {line}: commento non chiuso");
|
||||
}
|
||||
|
||||
line += s.AsSpan(i, end - i).Count('\n');
|
||||
i = end + 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c is '\'' or '"')
|
||||
{
|
||||
i++;
|
||||
var text = new StringBuilder();
|
||||
while (true)
|
||||
{
|
||||
if (i >= s.Length || s[i] == '\n')
|
||||
{
|
||||
throw new FormatException($"riga {line}: stringa non chiusa");
|
||||
}
|
||||
|
||||
if (s[i] == '\\')
|
||||
{
|
||||
text.Append(s[i + 1]);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (s[i] == c)
|
||||
{
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
|
||||
text.Append(s[i++]);
|
||||
}
|
||||
|
||||
tokens.Add(new Token(Kind.Text, text.ToString(), line));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '`')
|
||||
{
|
||||
i++;
|
||||
inTemplate = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '/' && RegexMayStart())
|
||||
{
|
||||
var start = i++;
|
||||
var inClass = false;
|
||||
while (true)
|
||||
{
|
||||
if (i >= s.Length || s[i] == '\n')
|
||||
{
|
||||
throw new FormatException($"riga {line}: espressione regolare non chiusa");
|
||||
}
|
||||
|
||||
if (s[i] == '\\')
|
||||
{
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (s[i] == '[')
|
||||
{
|
||||
inClass = true;
|
||||
}
|
||||
else if (s[i] == ']')
|
||||
{
|
||||
inClass = false;
|
||||
}
|
||||
else if (s[i] == '/' && !inClass)
|
||||
{
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
while (i < s.Length && char.IsAsciiLetter(s[i]))
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
tokens.Add(new Token(Kind.Regex, s[start..i], line));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char.IsLetter(c) || c is '_' or '$' or '#')
|
||||
{
|
||||
var start = i++;
|
||||
while (i < s.Length && (char.IsLetterOrDigit(s[i]) || s[i] is '_' or '$'))
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
tokens.Add(new Token(Kind.Word, s[start..i], line));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char.IsAsciiDigit(c) || (c == '.' && i + 1 < s.Length && char.IsAsciiDigit(s[i + 1])))
|
||||
{
|
||||
var start = i++;
|
||||
while (i < s.Length && (char.IsAsciiLetterOrDigit(s[i]) || s[i] is '.' or '_'))
|
||||
{
|
||||
i++;
|
||||
}
|
||||
|
||||
tokens.Add(new Token(Kind.Number, s[start..i], line));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '{')
|
||||
{
|
||||
braces.Push('{');
|
||||
}
|
||||
else if (c == '}')
|
||||
{
|
||||
if (braces.Count > 0 && braces.Peek() == 'E')
|
||||
{
|
||||
braces.Pop();
|
||||
i++;
|
||||
tokens.Add(new Token(Kind.Punct, "}$", line));
|
||||
inTemplate = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (braces.Count > 0)
|
||||
{
|
||||
braces.Pop();
|
||||
}
|
||||
}
|
||||
|
||||
// The punctuators that matter here; any other is one character.
|
||||
string[] longest = ["...", "=>", "?.", "??", "===", "!==", "==", "!=", "&&", "||", "**", "<=", ">=", "++", "--"];
|
||||
var punct = longest.FirstOrDefault(p => string.CompareOrdinal(s, i, p, 0, p.Length) == 0) ?? c.ToString();
|
||||
tokens.Add(new Token(Kind.Punct, punct, line));
|
||||
i += punct.Length;
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private sealed class Frame(char open, int line, int start)
|
||||
{
|
||||
public char Open { get; } = open;
|
||||
|
||||
public int Line { get; } = line;
|
||||
|
||||
/// <summary>Index of the opening token.</summary>
|
||||
public int Start { get; } = start;
|
||||
|
||||
/// <summary>Names declared in this block with let, const or class, or as parameters (for a function body).</summary>
|
||||
public Dictionary<string, string> Names { get; } = new(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
private static void CheckScopes(List<Token> tokens, List<string> problems)
|
||||
{
|
||||
var frames = new Stack<Frame>();
|
||||
frames.Push(new Frame('m', 1, -1));
|
||||
List<string>? pendingParams = null;
|
||||
var pendingAt = -1;
|
||||
|
||||
void Declare(string name, string how, int line)
|
||||
{
|
||||
var scope = frames.Peek();
|
||||
if (scope.Names.TryGetValue(name, out var before))
|
||||
{
|
||||
problems.Add($"riga {line}: «{name}» dichiarato di nuovo con {how} (già {before} nello stesso blocco)");
|
||||
return;
|
||||
}
|
||||
|
||||
scope.Names[name] = how;
|
||||
}
|
||||
|
||||
for (var i = 0; i < tokens.Count; i++)
|
||||
{
|
||||
var token = tokens[i];
|
||||
var prev = i > 0 ? tokens[i - 1] : default;
|
||||
if (token.Kind == Kind.Punct)
|
||||
{
|
||||
switch (token.Value)
|
||||
{
|
||||
case "{":
|
||||
{
|
||||
var frame = new Frame('{', token.Line, i);
|
||||
if (pendingParams is not null && pendingAt == i)
|
||||
{
|
||||
foreach (var name in pendingParams)
|
||||
{
|
||||
frame.Names.TryAdd(name, "parametro");
|
||||
}
|
||||
}
|
||||
|
||||
frames.Push(frame);
|
||||
pendingParams = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
case "(" or "[" or "${":
|
||||
frames.Push(new Frame(token.Value[0], token.Line, i));
|
||||
continue;
|
||||
case "}" or ")" or "]" or "}$":
|
||||
{
|
||||
var open = token.Value switch { "}" => '{', ")" => '(', "]" => '[', _ => '$' };
|
||||
if (frames.Count <= 1 || frames.Peek().Open != open)
|
||||
{
|
||||
var top = frames.Peek();
|
||||
problems.Add(top.Open == 'm'
|
||||
? $"riga {token.Line}: «{token.Value[0]}» senza apertura"
|
||||
: $"riga {token.Line}: «{token.Value[0]}» chiude «{top.Open}» aperta alla riga {top.Line}");
|
||||
return;
|
||||
}
|
||||
|
||||
var closed = frames.Pop();
|
||||
if (open == '(')
|
||||
{
|
||||
OnParenClosed(tokens, closed.Start, i, ref pendingParams, ref pendingAt);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
case "=>":
|
||||
if (prev.Kind == Kind.Word && !Reserved.Contains(prev.Value))
|
||||
{
|
||||
pendingParams = [prev.Value];
|
||||
pendingAt = i + 1;
|
||||
}
|
||||
else if (pendingParams is not null && pendingAt == i)
|
||||
{
|
||||
pendingAt = i + 1; // «(a, b) => {»
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (token.Kind != Kind.Word || i + 1 >= tokens.Count || (prev.Kind == Kind.Punct && prev.Value is "." or "?."))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var next = tokens[i + 1];
|
||||
if (token.Value is "let" or "const" && next.Kind == Kind.Word && !Reserved.Contains(next.Value))
|
||||
{
|
||||
Declare(next.Value, token.Value, next.Line);
|
||||
}
|
||||
else if (token.Value == "class" && next.Kind == Kind.Word && !Reserved.Contains(next.Value) && StatementStart(tokens, i))
|
||||
{
|
||||
Declare(next.Value, "class", next.Line);
|
||||
}
|
||||
else if (token.Value == "import" && frames.Count == 1 && !IsPunct(next, "(") && !IsPunct(next, "."))
|
||||
{
|
||||
for (var j = i + 1; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++)
|
||||
{
|
||||
var t = tokens[j];
|
||||
var after = j + 1 < tokens.Count ? tokens[j + 1] : default;
|
||||
if (t.Kind == Kind.Word && !IsWord(t, "as") && !IsWord(after, "as") && !Reserved.Contains(t.Value))
|
||||
{
|
||||
Declare(t.Value, "import", t.Line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (frames.Count > 1)
|
||||
{
|
||||
var open = frames.Peek();
|
||||
problems.Add($"riga {open.Line}: «{open.Open}» mai chiusa");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A «)» just closed: when a function body follows, the simple names of its parameters are kept for it.</summary>
|
||||
private static void OnParenClosed(List<Token> tokens, int open, int close, ref List<string>? pending, ref int pendingAt)
|
||||
{
|
||||
var next = close + 1 < tokens.Count ? tokens[close + 1] : default;
|
||||
var before = open > 0 ? tokens[open - 1] : default;
|
||||
var arrow = IsPunct(next, "=>");
|
||||
var body = IsPunct(next, "{") && before.Kind == Kind.Word && (!NotFunctionBefore.Contains(before.Value) || before.Value == "function");
|
||||
if (!arrow && !body)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var names = new List<string>();
|
||||
var depth = 0;
|
||||
var pieceStart = true;
|
||||
for (var j = open + 1; j < close; j++)
|
||||
{
|
||||
var t = tokens[j];
|
||||
if (t.Kind == Kind.Punct && t.Value is "(" or "[" or "{" or "${")
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (t.Kind == Kind.Punct && t.Value is ")" or "]" or "}" or "}$")
|
||||
{
|
||||
depth--;
|
||||
}
|
||||
|
||||
if (depth == 0 && IsPunct(t, ","))
|
||||
{
|
||||
pieceStart = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (pieceStart && depth == 0)
|
||||
{
|
||||
pieceStart = false;
|
||||
var name = IsPunct(t, "...") && j + 1 < close ? tokens[j + 1] : t;
|
||||
if (name.Kind == Kind.Word && !Reserved.Contains(name.Value))
|
||||
{
|
||||
names.Add(name.Value);
|
||||
}
|
||||
}
|
||||
else if (pieceStart)
|
||||
{
|
||||
pieceStart = false; // a destructured parameter: left alone
|
||||
}
|
||||
}
|
||||
|
||||
pending = names;
|
||||
pendingAt = close + 1;
|
||||
}
|
||||
|
||||
/// <summary>True when the word at <paramref name="i"/> starts a statement (a declaration, not an expression).</summary>
|
||||
private static bool StatementStart(List<Token> tokens, int i)
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var prev = tokens[i - 1];
|
||||
return (prev.Kind == Kind.Punct && prev.Value is ";" or "{" or "}") || IsWord(prev, "export") || IsWord(prev, "default");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user