Files
Febe/src/Febe.Core/Import/ImportEnvironment.cs
T
Alby96andClaude Opus 5.5 2068dd28f3 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>
2026-11-25 14:21:36 +01:00

235 lines
9.4 KiB
C#

using System.Globalization;
using System.Security.Cryptography;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Core.Import;
/// <summary>
/// What the import needs from the rest of Febe. Built once by the composition root (Server, Desktop) with the same
/// library objects the collection uses, so thumbnails, hashes and <c>_febe.jsonl</c> lines are made the same way.
/// </summary>
public sealed record ImportEnvironment
{
public required IFebeStorage Storage { get; init; }
/// <summary>Library folder and account folders.</summary>
public required LibraryLayout Layout { get; init; }
/// <summary>The two naming schemes of the library settings.</summary>
public LibraryNaming Naming { get; init; } = LibraryNaming.Default;
public required AccountJournal Journal { get; init; }
public required IClock Clock { get; init; }
public ThumbnailStore? Thumbnails { get; init; }
/// <summary>
/// The in-memory index of the library's perceptual hashes, shared with the collection. When null the analysis loads
/// its own copy from the database (and imported photos are not added to any shared index).
/// </summary>
public PerceptualHashIndex? HashIndex { get; init; }
/// <summary>The in-house frame decoder, for thumbnails of imported videos (spec §8.4). Null: the neutral tile.</summary>
public VideoFrameDecoder? Frames { get; init; }
/// <summary>
/// Reader of the metadata of videos the MP4 header reader does not cover (WebM/Matroska, AVI, WMV/ASF, FLV and MPEG
/// program streams: see <see cref="IVideoMetadataProbe"/>). Null: the in-house <see cref="ContainerVideoMetadataProbe"/>
/// on the clock of this environment.
/// </summary>
public IVideoMetadataProbe? VideoProbe { get; init; }
/// <summary>«Imposta la data del file a quella di pubblicazione» (library setting).</summary>
public bool SetFileTimeToPublication { get; init; } = true;
/// <summary>Where sources may be chosen (Docker: <c>/importa</c>).</summary>
public ImportSourceOptions Sources { get; init; } = ImportSourceOptions.AnyFolder;
/// <summary>The Data folder: a source may not overlap it.</summary>
public string? DataFolder { get; init; }
/// <summary>Read-only detection of sources.</summary>
public ISourceAccessProbe? AccessProbe { get; init; }
/// <summary>Reading, hashing and deleting source files.</summary>
public IImportFileSystem FileSystem { get; init; } = ImportFileSystem.Instance;
/// <summary>Files analysed at the same time (hashing and decoding).</summary>
public int Parallelism { get; init; } = Math.Clamp(Environment.ProcessorCount, 1, 4);
/// <summary>The checker of sources for this environment.</summary>
public ImportSources CreateSources() => new(Sources, Layout.Root, DataFolder, AccessProbe);
}
/// <summary>
/// File operations of the import on the source and on the copies. A separate seam so that the safety rule of «Sposta»
/// (the original goes only after the copy has been verified with SHA-256) can be tested with a corrupted copy.
/// </summary>
public interface IImportFileSystem
{
/// <summary>Opens a source file for reading only.</summary>
Stream OpenRead(string fullPath);
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
Task<string> ComputeSha256Async(string fullPath, CancellationToken ct);
/// <summary>Deletes an original of «Sposta», after its copy was verified.</summary>
void DeleteOriginal(string fullPath);
}
/// <summary>The real file system.</summary>
public sealed class ImportFileSystem : IImportFileSystem
{
private const int BufferSize = 128 * 1024;
private ImportFileSystem()
{
}
public static ImportFileSystem Instance { get; } = new();
public Stream OpenRead(string fullPath) =>
new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
public async Task<string> ComputeSha256Async(string fullPath, CancellationToken ct)
{
await using var stream = OpenRead(fullPath);
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
}
public void DeleteOriginal(string fullPath) => File.Delete(fullPath);
}
/// <summary>
/// Choices of an import that have no column in <c>import_run</c>, kept in the <c>setting</c> table under
/// <c>importazione.{id}.*</c>: whether the 4K Stogram hypothesis is on, and the folders that go to a new «Solo archivio»
/// account (created only when the copy starts, so an abandoned import leaves no empty account behind).
/// </summary>
internal static class ImportRunSettings
{
public static string StogramKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.ipotesi-stogram");
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);
public static Task SetStogramAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
store.SetAsync(StogramKey(runId), value ? "true" : null, ct);
/// <summary>Folder → user name of the new «Solo archivio» account it goes to.</summary>
public static async Task<IReadOnlyDictionary<string, string>> GetNewAccountsAsync(ISettingsStore store, long runId, CancellationToken ct)
{
var text = await store.GetAsync(NewAccountsKey(runId), ct).ConfigureAwait(false);
var result = new Dictionary<string, string>(StringComparer.Ordinal);
if (string.IsNullOrWhiteSpace(text))
{
return result;
}
try
{
if (JsonNode.Parse(text) is JsonObject json)
{
foreach (var (folder, value) in json)
{
if (value?.GetValue<string>() is { Length: > 0 } username)
{
result[folder] = username;
}
}
}
}
catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{
// An unreadable value: as if no new account had been chosen.
}
return result;
}
public static Task SetNewAccountsAsync(ISettingsStore store, long runId, IReadOnlyDictionary<string, string> folders, CancellationToken ct)
{
if (folders.Count == 0)
{
return store.SetAsync(NewAccountsKey(runId), null, ct);
}
var json = new JsonObject();
foreach (var (folder, username) in folders.OrderBy(f => f.Key, StringComparer.Ordinal))
{
json[folder] = username;
}
return store.SetAsync(NewAccountsKey(runId), json.ToJsonString(), ct);
}
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
store.SetManyAsync(new Dictionary<string, string?> { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null, [DamagedKey(runId)] = null }, ct);
}