M7 Importazione: sorgenti con sola lettura riconosciuta, analisi in sola lettura interrompibile e ripristinabile (tipo dal contenuto, SHA-256, impronta, date da nome, EXIF scritto a mano, mvhd e ffprobe facoltativo), riconoscitori Febe, generico e 4K Stogram come ipotesi spenta, confronto con la libreria e dentro la sorgente, associazione cartelle-account, decisioni sui doppioni, copia o spostamento verificati con sostituzione sicura, resoconto e CSV; prove

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 18:32:01 +00:00
1 parent 6ff11ac8e3
commit 5e77bdefe0
32 files changed
+7707 -3

No files matched your search

@@ -0,0 +1,224 @@
using System.Security.Cryptography;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Import.Support;
/// <summary>Read-only detection decided by the test.</summary>
internal sealed class FixedAccessProbe(bool readOnly) : ISourceAccessProbe
{
public bool IsReadOnly(string fullPath) => readOnly;
}
/// <summary>
/// The real file system, except that copies in the library can be damaged right before «Sposta» verifies them, and
/// deletions of originals are counted.
/// </summary>
internal sealed class CorruptingFileSystem(string libraryRoot) : IImportFileSystem
{
private readonly string _libraryRoot = Path.GetFullPath(libraryRoot);
private readonly HashSet<string> _damaged = new(StringComparer.Ordinal);
/// <summary>Damage every library file (once: the damage stays) before it is hashed.</summary>
public bool CorruptCopies { get; set; }
public List<string> Deleted { get; } = [];
public Stream OpenRead(string fullPath) => ImportFileSystem.Instance.OpenRead(fullPath);
public Task<string> ComputeSha256Async(string fullPath, CancellationToken ct)
{
var full = Path.GetFullPath(fullPath);
if (CorruptCopies && full.StartsWith(_libraryRoot, StringComparison.Ordinal) && _damaged.Add(full))
{
var bytes = File.ReadAllBytes(full);
bytes[^1] ^= 0xFF;
File.WriteAllBytes(full, bytes);
}
return ImportFileSystem.Instance.ComputeSha256Async(fullPath, ct);
}
/// <summary>Deleting an original fails, as for a file open in another program.</summary>
public bool FailDeletes { get; set; }
public void DeleteOriginal(string fullPath)
{
if (FailDeletes)
{
throw new IOException("File in uso.");
}
Deleted.Add(fullPath);
ImportFileSystem.Instance.DeleteOriginal(fullPath);
}
}
/// <summary>A library with database and services plus a source folder to import from.</summary>
internal sealed class ImportTestBed : IAsyncDisposable
{
private ImportTestBed(TestLibrary library, TempFolder temp, bool readOnlySource)
{
Library = library;
Temp = temp;
Source = temp.Combine("sorgente");
Directory.CreateDirectory(Source);
FileSystem = new CorruptingFileSystem(library.Layout.Root);
Environment = new ImportEnvironment
{
Storage = library.Db,
Layout = library.Layout,
Journal = library.Journal,
Clock = library.Clock,
Thumbnails = library.Thumbnails,
HashIndex = library.Index,
DataFolder = library.Data.Root,
AccessProbe = new FixedAccessProbe(readOnlySource),
FileSystem = FileSystem,
Parallelism = 2,
};
}
public TestLibrary Library { get; }
public TempFolder Temp { get; }
/// <summary>Full path of the source folder.</summary>
public string Source { get; }
public CorruptingFileSystem FileSystem { get; }
public ImportEnvironment Environment { get; private set; }
public ImportAnalyzer Analyzer => new(Environment);
public ImportCopier Copier => new(Environment);
public ImportReview Review => new(Environment);
public ImportReports Reports => new(Environment);
public static async Task<ImportTestBed> CreateAsync(TempFolder temp, bool readOnlySource = false) =>
new(await TestLibrary.CreateAsync(temp), temp, readOnlySource);
/// <summary>Uses another environment (e.g. with the Docker root).</summary>
public void Use(ImportEnvironment environment) => Environment = environment;
/// <summary>Writes a file in the source; the modification time is set when given.</summary>
public string Write(string relativePath, byte[] bytes, DateTime? modifiedUtc = null)
{
var full = Path.Combine(Source, relativePath.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(full)!);
File.WriteAllBytes(full, bytes);
File.SetLastWriteTimeUtc(full, modifiedUtc ?? new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc));
return full;
}
/// <summary>Path, size, modification time and SHA-256 of every file of the source: compares «before» and «after».</summary>
public IReadOnlyList<string> Fingerprint() =>
Directory.EnumerateFiles(Source, "*", SearchOption.AllDirectories)
.Order(StringComparer.Ordinal)
.Select(f =>
{
var info = new FileInfo(f);
return $"{Path.GetRelativePath(Source, f)}|{info.Length}|{info.LastWriteTimeUtc:O}|{Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(f)))}";
})
.ToList();
/// <summary>Checks the source, records the import and runs the analysis to the end.</summary>
public async Task<ImportRun> AnalyzeAsync(ImportAnalysisOptions? options = null)
{
var info = Environment.CreateSources().Inspect(Source);
var run = await Analyzer.CreateRunAsync(info, options);
return await Analyzer.AnalyzeAsync(run.Id);
}
public async Task<IReadOnlyList<ImportFile>> FilesAsync(long runId) =>
await Library.Db.Imports.ListFilesAsync(new Core.Storage.ImportFileQuery { RunId = runId, Limit = 10_000 });
public async Task<ImportFile> FileAsync(long runId, string relativePath) =>
await Library.Db.Imports.FindFileAsync(runId, relativePath) ?? throw new AssertFailedException($"{relativePath} non è nell'importazione.");
/// <summary>An account with a photo already in the library (stored as the collection would).</summary>
public async Task<(Account Account, EntryWithMedia Saved)> AccountWithPhotoAsync(string username, string instagramId, byte[] photo, string? code = null, DateTimeOffset? publishedAt = null)
{
var account = await Library.Db.Accounts.FindByUsernameAsync(username) ?? await Library.Db.Accounts.AddAsync(Make.Account(username));
var entry = Make.Entry(account.Id, instagramId, publishedAt ?? Make.T0.AddDays(-30)) with { Code = code ?? "C" + instagramId };
var saved = await Library.SaveAsync(account, entry, [new TestFile(Make.Photo(1), photo, ".jpg")]);
return (account, saved);
}
public ValueTask DisposeAsync() => Library.DisposeAsync();
}
/// <summary>
/// Reading a source file whose path matches <paramref name="blocks"/> waits until the job is cancelled: an import can
/// be interrupted at a known point.
/// </summary>
internal sealed class GatedFileSystem(IImportFileSystem inner, Func<string, bool> blocks) : IImportFileSystem
{
/// <summary>Set when the first blocked file is opened.</summary>
public TaskCompletionSource Reached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public Stream OpenRead(string fullPath)
{
var stream = inner.OpenRead(fullPath);
if (!blocks(fullPath))
{
return stream;
}
Reached.TrySetResult();
return new BlockedStream(stream);
}
public Task<string> ComputeSha256Async(string fullPath, CancellationToken ct) => inner.ComputeSha256Async(fullPath, ct);
public void DeleteOriginal(string fullPath) => inner.DeleteOriginal(fullPath);
private sealed class BlockedStream(Stream inner) : Stream
{
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => throw new NotSupportedException(); }
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await Task.Delay(Timeout.Infinite, cancellationToken);
return 0;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush()
{
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
inner.Dispose();
}
base.Dispose(disposing);
}
}
}
@@ -0,0 +1,259 @@
using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using Febe.Tests.Support;
using SkiaSharp;
namespace Febe.Tests.Import.Support;
/// <summary>Bytes of test media written by hand: JPEGs with an EXIF date, PNGs with eXIf, MP4/MOV headers.</summary>
internal static class ImportTestFiles
{
private static readonly DateTimeOffset Epoch1904 = new(1904, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>A generated photo as JPEG.</summary>
public static byte[] Photo(int scene, int width = 800, int height = 600, int quality = 88)
{
using var bitmap = TestImages.Scene(scene, width, height);
return TestImages.Jpeg(bitmap, quality);
}
/// <summary>
/// A TIFF structure (big or little endian) with IFD0 → Exif IFD holding DateTimeOriginal and/or CreateDate and an
/// optional OffsetTimeOriginal: the content of an EXIF block after «Exif\0\0».
/// </summary>
public static byte[] Tiff(string? dateTimeOriginal, string? createDate = null, string? offsetOriginal = null, bool littleEndian = false)
{
var tags = new List<(ushort Tag, string Value)>();
if (dateTimeOriginal is not null)
{
tags.Add((0x9003, dateTimeOriginal));
}
if (createDate is not null)
{
tags.Add((0x9004, createDate));
}
if (offsetOriginal is not null)
{
tags.Add((0x9011, offsetOriginal));
}
tags.Sort((a, b) => a.Tag.CompareTo(b.Tag));
var buffer = new byte[1024];
var span = buffer.AsSpan();
void U16(int at, ushort v)
{
if (littleEndian)
{
BinaryPrimitives.WriteUInt16LittleEndian(buffer.AsSpan(at), v);
}
else
{
BinaryPrimitives.WriteUInt16BigEndian(buffer.AsSpan(at), v);
}
}
void U32(int at, uint v)
{
if (littleEndian)
{
BinaryPrimitives.WriteUInt32LittleEndian(buffer.AsSpan(at), v);
}
else
{
BinaryPrimitives.WriteUInt32BigEndian(buffer.AsSpan(at), v);
}
}
(littleEndian ? "II"u8 : "MM"u8).CopyTo(span);
U16(2, 42);
U32(4, 8);
// IFD0 at 8: one entry, the Exif IFD pointer.
U16(8, 1);
U16(10, 0x8769);
U16(12, 4); // LONG
U32(14, 1);
const int exifIfd = 26;
U32(18, exifIfd);
U32(22, 0); // no next IFD
// Exif IFD at 26: the ASCII tags, values after the IFD.
U16(exifIfd, (ushort)tags.Count);
var valueAt = exifIfd + 2 + (tags.Count * 12) + 4;
for (var i = 0; i < tags.Count; i++)
{
var at = exifIfd + 2 + (i * 12);
var bytes = Encoding.ASCII.GetBytes(tags[i].Value + "\0");
U16(at, tags[i].Tag);
U16(at + 2, 2); // ASCII
U32(at + 4, (uint)bytes.Length);
if (bytes.Length <= 4)
{
bytes.CopyTo(span[(at + 8)..]);
}
else
{
U32(at + 8, (uint)valueAt);
bytes.CopyTo(span[valueAt..]);
valueAt += bytes.Length;
}
}
U32(exifIfd + 2 + (tags.Count * 12), 0);
return buffer[..valueAt];
}
/// <summary>Inserts an APP1 «Exif» segment with the given TIFF block right after the SOI marker of a JPEG.</summary>
public static byte[] JpegWithExif(byte[] jpeg, byte[] tiff)
{
var length = 2 + 6 + tiff.Length;
var app1 = new byte[2 + length];
app1[0] = 0xFF;
app1[1] = 0xE1;
BinaryPrimitives.WriteUInt16BigEndian(app1.AsSpan(2), (ushort)length);
"Exif\0\0"u8.CopyTo(app1.AsSpan(4));
tiff.CopyTo(app1.AsSpan(10));
return [.. jpeg.AsSpan(0, 2), .. app1, .. jpeg.AsSpan(2)];
}
/// <summary>A generated JPEG photo with DateTimeOriginal «yyyy:MM:dd HH:mm:ss» written by hand.</summary>
public static byte[] PhotoWithExifDate(int scene, DateTime local, string? offset = null, int width = 800, int height = 600) =>
JpegWithExif(Photo(scene, width, height), Tiff(local.ToString("yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture), offsetOriginal: offset));
/// <summary>A PNG with an eXIf chunk inserted before the image data.</summary>
public static byte[] PngWithExif(byte[] png, byte[] tiff)
{
// After the signature (8) comes IHDR (8 + 13 + 4 = 25 bytes).
var chunk = new byte[12 + tiff.Length];
BinaryPrimitives.WriteUInt32BigEndian(chunk, (uint)tiff.Length);
"eXIf"u8.CopyTo(chunk.AsSpan(4));
tiff.CopyTo(chunk.AsSpan(8));
// CRC left at zero: readers of dates do not check it.
return [.. png.AsSpan(0, 33), .. chunk, .. png.AsSpan(33)];
}
/// <summary>
/// A minimal ISO media file: ftyp, then (or after the media data) a moov with mvhd and a video tkhd. The payload
/// makes each file different.
/// </summary>
public static byte[] Mp4(
DateTimeOffset? createdAt,
int width = 1080,
int height = 1920,
int durationMs = 15_000,
int payloadSeed = 1,
string brand = "isom",
bool moovAtEnd = false,
bool rotated = false,
bool withFtyp = true)
{
using var output = new MemoryStream();
if (withFtyp)
{
WriteBox(output, "ftyp", [.. Encoding.ASCII.GetBytes(brand), 0, 0, 2, 0, .. Encoding.ASCII.GetBytes("isommp41")]);
}
var payload = new byte[4096];
new Random(payloadSeed).NextBytes(payload);
var mvhd = new byte[100];
var creation = createdAt is { } c ? (uint)(c - Epoch1904).TotalSeconds : 0u;
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(4), creation);
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(8), creation);
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(12), 1000);
BinaryPrimitives.WriteUInt32BigEndian(mvhd.AsSpan(16), (uint)durationMs);
var tkhd = new byte[84];
tkhd[3] = 3; // enabled, in movie
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(4), creation);
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(12), 1);
var matrix = tkhd.AsSpan(40, 36);
int[] values = rotated ? [0, 0x10000, 0, -0x10000, 0, 0, 0, 0, 0x40000000] : [0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000];
for (var i = 0; i < 9; i++)
{
BinaryPrimitives.WriteInt32BigEndian(matrix[(i * 4)..], values[i]);
}
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(76), (uint)width << 16);
BinaryPrimitives.WriteUInt32BigEndian(tkhd.AsSpan(80), (uint)height << 16);
using var trak = new MemoryStream();
WriteBox(trak, "tkhd", tkhd);
using var moov = new MemoryStream();
WriteBox(moov, "mvhd", mvhd);
WriteBox(moov, "trak", trak.ToArray());
if (moovAtEnd)
{
WriteBox(output, "mdat", payload);
WriteBox(output, "moov", moov.ToArray());
}
else
{
WriteBox(output, "moov", moov.ToArray());
WriteBox(output, "mdat", payload);
}
return output.ToArray();
}
/// <summary>Makes a real one-second MP4 with ffmpeg and the given creation time; false when ffmpeg is missing.</summary>
public static bool TryMakeMp4WithFfmpeg(string path, DateTimeOffset createdAt)
{
var ffmpeg = new[] { "/usr/bin/ffmpeg", "/usr/local/bin/ffmpeg" }.FirstOrDefault(File.Exists);
if (ffmpeg is null)
{
return false;
}
var start = new ProcessStartInfo(ffmpeg) { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false };
foreach (var argument in new[]
{
"-hide_banner", "-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=0x3366aa:s=64x48:d=1:r=10",
"-metadata", "creation_time=" + createdAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) + "Z",
"-c:v", "mpeg4", "-f", "mp4", path,
})
{
start.ArgumentList.Add(argument);
}
using var process = Process.Start(start)!;
process.StandardError.ReadToEnd();
process.WaitForExit(30_000);
return process.ExitCode == 0 && File.Exists(path);
}
/// <summary>The PNG encoding of a generated scene.</summary>
public static byte[] Png(int scene, int width = 400, int height = 300)
{
using var bitmap = TestImages.Scene(scene, width, height);
return TestImages.Png(bitmap);
}
/// <summary>A resized and recompressed copy of a scene (a probable duplicate).</summary>
public static byte[] Resized(int scene, int width, int height, int targetWidth, int targetHeight, int quality = 60)
{
using var bitmap = TestImages.Scene(scene, width, height);
using var smaller = TestImages.Resize(bitmap, targetWidth, targetHeight);
return TestImages.Jpeg(smaller, quality);
}
/// <summary>A crop of a scene: the top-left quarter (not a duplicate).</summary>
public static byte[] Cropped(int scene, int width, int height)
{
using var bitmap = TestImages.Scene(scene, width, height);
using var crop = TestImages.Crop(bitmap, new SKRectI(0, 0, width / 2, height / 2));
return TestImages.Jpeg(crop, 88);
}
private static void WriteBox(Stream output, string type, byte[] body)
{
Span<byte> header = stackalloc byte[8];
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(body.Length + 8));
Encoding.ASCII.GetBytes(type).CopyTo(header[4..]);
output.Write(header);
output.Write(body);
}
}