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,279 @@
using System.Security.Cryptography;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class ImportAnalysisTests
{
[TestMethod]
public async Task AGeneratedSourceTreeIsAnalysedWithoutTouchingIt()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var named = bed.Write("marta.demo/IMG_20210506_070809.jpg", ImportTestFiles.Photo(1));
bed.Write("marta.demo/storie/foto-exif.jpg", ImportTestFiles.PhotoWithExifDate(2, new DateTime(2020, 2, 3, 10, 0, 0)));
bed.Write("marta.demo/storie/video.mp4", ImportTestFiles.Mp4(new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero), 1080, 1920, 15_000, payloadSeed: 7));
bed.Write("marta.demo/vecchia.jpg", ImportTestFiles.Photo(3), new DateTime(2019, 1, 2, 3, 4, 5, DateTimeKind.Utc));
bed.Write("marta.demo/note.txt", "Appunti, non una foto."u8.ToArray());
bed.Write("marta.demo/travestita.png", ImportTestFiles.Photo(4, 320, 240));
bed.Write("Foto sparse/a.jpg", ImportTestFiles.Photo(5));
bed.Write("marta.demo/Thumbs.db", [1, 2, 3]);
var realVideo = Path.Combine(bed.Source, "marta.demo", "storie", "ffmpeg.mp4");
var withFfmpeg = ImportTestFiles.TryMakeMp4WithFfmpeg(realVideo, new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero));
var before = bed.Fingerprint();
var run = await bed.AnalyzeAsync();
Assert.AreEqual(ImportRunState.Reviewing, run.State);
Assert.IsNotNull(run.AnalyzedAt);
CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "L'analisi è in sola lettura: nessun file della sorgente cambia.");
var files = (await bed.FilesAsync(run.Id)).Where(f => !f.RelativePath.EndsWith("ffmpeg.mp4", StringComparison.Ordinal)).ToList();
Assert.HasCount(7, files, "Thumbs.db non è un contenuto e non si elenca.");
if (withFfmpeg)
{
var real = await bed.FileAsync(run.Id, "marta.demo/storie/ffmpeg.mp4");
Assert.AreEqual("video/mp4", real.ContentType);
Assert.AreEqual(new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero), real.TakenAt, "Data di creazione del video, dal suo mvhd.");
Assert.AreEqual(ImportDateSource.Metadata, real.DateSource);
Assert.AreEqual((64, 48), (real.Width, real.Height));
}
Assert.IsTrue(files.All(f => f.State == ImportFileState.Analyzed));
var byName = await bed.FileAsync(run.Id, "marta.demo/IMG_20210506_070809.jpg");
Assert.AreEqual(ImportOutcome.New, byName.Outcome);
Assert.AreEqual(MediaKind.Photo, byName.MediaKind);
Assert.AreEqual("image/jpeg", byName.ContentType);
Assert.AreEqual((800, 600), (byName.Width, byName.Height));
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(named))), byName.Sha256);
Assert.AreEqual(new FileInfo(named).Length, byName.Bytes);
Assert.IsNotNull(byName.PerceptualHash);
Assert.AreEqual(ImportDateSource.FileName, byName.DateSource);
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), byName.TakenAt);
Assert.AreEqual("marta.demo", byName.Folder);
Assert.AreEqual("marta.demo", byName.ProbableAccount);
Assert.IsNull(byName.ProbableKind);
var exif = await bed.FileAsync(run.Id, "marta.demo/storie/foto-exif.jpg");
Assert.AreEqual(ImportDateSource.Metadata, exif.DateSource);
Assert.AreEqual(new DateTimeOffset(2020, 2, 3, 9, 0, 0, TimeSpan.Zero), exif.TakenAt);
Assert.AreEqual(EntryKind.Story, exif.ProbableKind);
var video = await bed.FileAsync(run.Id, "marta.demo/storie/video.mp4");
Assert.AreEqual(MediaKind.Video, video.MediaKind);
Assert.AreEqual(ImportDateSource.Metadata, video.DateSource);
Assert.AreEqual(new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero), video.TakenAt);
Assert.AreEqual(TimeSpan.FromSeconds(15), video.Duration);
Assert.AreEqual((1080, 1920), (video.Width, video.Height));
Assert.IsNull(video.PerceptualHash, "I video non hanno impronta visiva.");
var old = await bed.FileAsync(run.Id, "marta.demo/vecchia.jpg");
Assert.AreEqual(ImportDateSource.ModifiedTime, old.DateSource);
Assert.AreEqual(new DateTimeOffset(2019, 1, 2, 3, 4, 5, TimeSpan.Zero), old.TakenAt);
Assert.AreEqual(ImportOutcome.Unrecognized, (await bed.FileAsync(run.Id, "marta.demo/note.txt")).Outcome);
Assert.AreEqual("image/jpeg", (await bed.FileAsync(run.Id, "marta.demo/travestita.png")).ContentType, "Il tipo viene dal contenuto.");
var loose = await bed.FileAsync(run.Id, "Foto sparse/a.jpg");
Assert.AreEqual("Foto sparse", loose.Folder);
Assert.IsNull(loose.ProbableAccount, "«Foto sparse» non può essere un nome utente.");
var summary = await bed.Review.GetSummaryAsync(run.Id);
Assert.AreEqual(withFfmpeg ? 8 : 7, summary.Files);
Assert.AreEqual(withFfmpeg ? 7 : 6, summary.ByOutcome[ImportOutcome.New]);
Assert.AreEqual(1, summary.ByOutcome[ImportOutcome.Unrecognized]);
var marta = summary.Folders.Single(f => f.Folder == "marta.demo");
Assert.AreEqual(FolderTargetKind.NewArchiveAccount, marta.Target.Kind, "Un nome valido senza account: nuovo account, solo archivio.");
Assert.AreEqual("marta.demo", marta.Target.Username);
Assert.AreEqual(FolderTargetKind.None, summary.Folders.Single(f => f.Folder == "Foto sparse").Target.Kind, "Nessun nome riconosciuto: nessuna scelta fatta.");
Assert.IsTrue(summary.CanMove);
StringAssert.StartsWith(summary.Headline, withFfmpeg ? "8 file, " : "7 file, ");
StringAssert.EndsWith(summary.Headline, "Nessun file è stato ancora copiato.");
}
[TestMethod]
public async Task AnInterruptedAnalysisResumesWhereItStopped()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var twin = ImportTestFiles.Png(1000, 48, 36);
for (var i = 0; i < 100; i++)
{
bed.Write($"luca.demo/f{i:000}.png", i == 90 ? twin : ImportTestFiles.Png(1000 + i, 48, 36));
}
var info = bed.Environment.CreateSources().Inspect(bed.Source);
var run = await bed.Analyzer.CreateRunAsync(info);
using var stop = new CancellationTokenSource();
var progress = new SyncProgress(p =>
{
if (p.Phase == ImportPhase.Analyzing && p.FilesDone >= 64)
{
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => bed.Analyzer.AnalyzeAsync(run.Id, progress, stop.Token));
var interrupted = await bed.Library.Db.Imports.GetRunAsync(run.Id);
Assert.AreEqual(ImportRunState.AnalysisInterrupted, interrupted!.State);
Assert.IsNull(interrupted.LastError, "Un'interruzione non è un errore.");
var halfway = await bed.FilesAsync(run.Id);
var analysed = halfway.Count(f => f.State == ImportFileState.Analyzed);
Assert.AreEqual(64, analysed, "Il primo gruppo di file è salvato con il suo esito.");
Assert.AreEqual(36, halfway.Count(f => f.State == ImportFileState.Pending));
var resumed = await bed.Analyzer.AnalyzeAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, resumed.State);
var files = await bed.FilesAsync(run.Id);
Assert.HasCount(100, files, "Nessun file elencato due volte.");
Assert.IsTrue(files.All(f => f.State == ImportFileState.Analyzed && f.Outcome != ImportOutcome.Pending), "Un esito per ogni file.");
Assert.AreEqual(ImportOutcome.IdenticalInSource, files.Single(f => f.RelativePath == "luca.demo/f090.png").Outcome, "La copia identica è riconosciuta anche dopo la ripresa.");
Assert.AreEqual(99, files.Count(f => f.Outcome == ImportOutcome.New));
}
[TestMethod]
public async Task SameBytesAreAlreadyInTheLibraryAndTheReportSaysWhere()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var photo = ImportTestFiles.Photo(20);
var (luca, saved) = await bed.AccountWithPhotoAsync("luca.demo", "500", photo);
var (marta, savedMarta) = await bed.AccountWithPhotoAsync("marta.demo", "600", ImportTestFiles.Photo(21));
bed.Write("marta.demo/copia.jpg", photo);
bed.Write("marta.demo/anche-questa.jpg", ImportTestFiles.Photo(21));
var run = await bed.AnalyzeAsync();
var copy = await bed.FileAsync(run.Id, "marta.demo/copia.jpg");
Assert.AreEqual(ImportOutcome.AlreadyInLibrary, copy.Outcome);
Assert.AreEqual(saved.Media[0].Id, copy.MatchedMediaId);
var rows = await bed.Library.Db.Imports.ListReportRowsAsync(run.Id);
Assert.AreEqual("luca.demo", rows.Single(r => r.File.Id == copy.Id).MatchedUsername, "Il resoconto dice in quale account si trova.");
Assert.AreEqual(savedMarta.Media[0].Id, (await bed.FileAsync(run.Id, "marta.demo/anche-questa.jpg")).MatchedMediaId);
Assert.AreEqual(marta.Id, (await bed.Review.ListFoldersAsync(run.Id)).Single().Target.AccountId, "La cartella va all'account con lo stesso nome.");
Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import));
_ = luca;
}
[TestMethod]
public async Task TheDestinationAccountIsSearchedFirst()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var photo = ImportTestFiles.Photo(22);
await bed.AccountWithPhotoAsync("luca.demo", "700", photo);
var (_, inMarta) = await bed.AccountWithPhotoAsync("marta.demo", "701", photo);
bed.Write("marta.demo/x.jpg", photo);
var run = await bed.AnalyzeAsync();
Assert.AreEqual(inMarta.Media[0].Id, (await bed.FileAsync(run.Id, "marta.demo/x.jpg")).MatchedMediaId);
}
[TestMethod]
public async Task SameIdentifierWithADifferentFileIsAProbableDuplicate()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var account = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var story = Make.Entry(account.Id, "3742118", new DateTimeOffset(2026, 10, 13, 7, 41, 7, TimeSpan.Zero), EntryKind.Story);
var saved = await bed.Library.SaveAsync(account, story, [new TestFile(Make.Photo(1), ImportTestFiles.Photo(30), ".jpg")]);
bed.Write("marta.demo/storie/2026/2026-10-13_09-41-07_3742118_1.jpg", ImportTestFiles.Photo(31));
var run = await bed.AnalyzeAsync();
var file = (await bed.FilesAsync(run.Id)).Single();
Assert.AreEqual(ImportOutcome.ProbableDuplicate, file.Outcome);
Assert.AreEqual("3742118", file.InstagramId);
var pair = (await bed.Library.Db.Duplicates.ListPendingAsync(DuplicateOrigin.Import)).Single();
Assert.AreEqual(DuplicateReason.SameInstagramId, pair.Reason);
Assert.AreEqual(saved.Media[0].Id, pair.ExistingMediaId);
Assert.AreEqual(file.Id, pair.CandidateImportFileId);
Assert.AreEqual(DuplicateDecision.Pending, pair.Decision, "Nessuna scelta è fatta in partenza.");
}
[TestMethod]
public async Task AResizedCopyIsAProbableDuplicateAndACropIsNot()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var (_, saved) = await bed.AccountWithPhotoAsync("marta.demo", "800", ImportTestFiles.Photo(40, 800, 600, 92));
bed.Write("marta.demo/piccola.jpg", ImportTestFiles.Resized(40, 800, 600, 400, 300, 55));
bed.Write("marta.demo/ritaglio.jpg", ImportTestFiles.Cropped(40, 800, 600));
bed.Write("marta.demo/altra.jpg", ImportTestFiles.Photo(41));
var run = await bed.AnalyzeAsync();
var resized = await bed.FileAsync(run.Id, "marta.demo/piccola.jpg");
Assert.AreEqual(ImportOutcome.ProbableDuplicate, resized.Outcome);
var pair = (await bed.Review.ListDuplicatesAsync(run.Id)).Single();
Assert.AreEqual(DuplicateReason.VisuallySimilar, pair.Pair.Reason);
Assert.AreEqual(saved.Media[0].Id, pair.Existing.MediaId);
Assert.IsTrue(pair.Existing.InLibrary);
Assert.AreEqual("marta.demo", pair.Existing.Username);
Assert.AreEqual(resized.Id, pair.Candidate.ImportFileId);
Assert.IsFalse(pair.CandidateIsLarger, "Quella in libreria ha più pixel.");
Assert.IsTrue(pair.Pair.Distance <= PerceptualHash.DuplicateThreshold);
Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/ritaglio.jpg")).Outcome, "Un ritaglio non è un doppione.");
Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/altra.jpg")).Outcome);
}
[TestMethod]
public async Task DuplicatesAreLookedForInsideTheSourceToo()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var photo = ImportTestFiles.Photo(50, 800, 600, 92);
bed.Write("marta.demo/a.jpg", photo);
bed.Write("marta.demo/backup/a.jpg", photo);
bed.Write("marta.demo/b-grande.jpg", ImportTestFiles.Photo(51, 800, 600, 92));
bed.Write("marta.demo/c-piccola.jpg", ImportTestFiles.Resized(51, 800, 600, 400, 300, 55));
bed.Write("marta.demo/d-video.mp4", ImportTestFiles.Mp4(null, payloadSeed: 3));
bed.Write("marta.demo/e-video.mp4", ImportTestFiles.Mp4(null, payloadSeed: 4));
var run = await bed.AnalyzeAsync();
Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/a.jpg")).Outcome);
var copy = await bed.FileAsync(run.Id, "marta.demo/backup/a.jpg");
Assert.AreEqual(ImportOutcome.IdenticalInSource, copy.Outcome);
StringAssert.Contains(copy.LastError, "marta.demo/a.jpg");
var large = await bed.FileAsync(run.Id, "marta.demo/b-grande.jpg");
var small = await bed.FileAsync(run.Id, "marta.demo/c-piccola.jpg");
Assert.AreEqual(ImportOutcome.New, large.Outcome);
Assert.AreEqual(ImportOutcome.ProbableDuplicate, small.Outcome);
var pair = (await bed.Review.ListDuplicatesAsync(run.Id)).Single();
Assert.IsTrue(pair.InsideSource);
Assert.AreEqual(large.Id, pair.Existing.ImportFileId);
Assert.AreEqual(small.Id, pair.Candidate.ImportFileId);
Assert.AreEqual(ImportOutcome.New, (await bed.FileAsync(run.Id, "marta.demo/e-video.mp4")).Outcome, "Per i video vale solo lo SHA-256.");
}
[TestMethod]
public async Task AFileAlbertoDeletedIsNotBroughtBack()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var photo = ImportTestFiles.Photo(60);
var (_, saved) = await bed.AccountWithPhotoAsync("marta.demo", "900", photo);
await new LibraryDeletion(bed.Library.Db, bed.Library.Layout, bed.Library.Journal, bed.Library.Clock).DeleteAsync(saved.Entry.Id);
bed.Write("marta.demo/eliminata.jpg", photo);
var run = await bed.AnalyzeAsync();
var file = (await bed.FilesAsync(run.Id)).Single();
Assert.AreEqual(ImportOutcome.AlreadyInLibrary, file.Outcome);
StringAssert.Contains(file.LastError, "eliminato");
}
private sealed class SyncProgress(Action<ImportProgress> report) : IProgress<ImportProgress>
{
public void Report(ImportProgress value) => report(value);
}
}
+475
View File
@@ -0,0 +1,475 @@
using System.Security.Cryptography;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class ImportCopyTests
{
[TestMethod]
public async Task KnownFilesTakeTheLibraryNameAndTheOthersGoToImportati()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_DBx3kQ2_1.jpg", ImportTestFiles.Photo(1));
bed.Write("marta.demo/post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg", ImportTestFiles.Photo(2));
bed.Write("marta.demo/storie/2026/2026-10-13_09-41-07_3742118_1.mp4", ImportTestFiles.Mp4(null, payloadSeed: 11));
bed.Write("marta.demo/IMG_20210506_070809.jpg", ImportTestFiles.Photo(3));
bed.Write("marta.demo/senza data.jpg", ImportTestFiles.Photo(4), new DateTime(2018, 3, 4, 5, 6, 7, DateTimeKind.Utc));
var folder = bed.Library.Layout.AccountFolder(marta);
Directory.CreateDirectory(Path.Combine(folder, "importati"));
var squatter = Path.Combine(folder, "importati", "IMG_20210506_070809.jpg");
File.WriteAllBytes(squatter, [9, 9, 9]);
var before = bed.Fingerprint();
var run = await bed.AnalyzeAsync();
await bed.Copier.CopyAsync(run.Id);
CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList(), "Con «Copia» gli originali restano come sono.");
var files = await bed.FilesAsync(run.Id);
Assert.IsTrue(files.All(f => f.State == ImportFileState.Copied), string.Join("; ", files.Select(f => f.RelativePath + ": " + f.State + " " + f.LastError)));
Assert.AreEqual(ImportRunState.Completed, (await bed.Library.Db.Imports.GetRunAsync(run.Id))!.State);
var carousel = await bed.Library.Db.Imports.FindEntryByCodeAsync(marta.Id, EntryKind.Post, "DBx3kQ2");
var post = (await bed.Library.Db.Entries.GetWithMediaAsync(carousel!.Id))!;
Assert.AreEqual(Provenance.Imported, post.Entry.Provenance);
Assert.AreEqual(EntryState.Imported, post.Entry.State);
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero), post.Entry.PublishedAt);
CollectionAssert.AreEqual(
new[] { "post/2026/2026-10-10_18-22-05_DBx3kQ2_1.jpg", "post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg" },
post.Media.Select(m => m.RelativePath).ToArray(),
"Un post con più file diventa un elemento solo, con i nomi dello schema.");
Assert.IsTrue(post.Media.All(m => m.State == MediaState.Imported && m.HasThumbnail && m.PerceptualHash is not null));
Assert.IsTrue(bed.Library.Index.Count >= 2, "Le impronte delle foto importate entrano nell'indice.");
Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(bed.Library.Layout.FullPath(marta, post.Media[0].RelativePath!)));
var story = (await bed.Library.Db.Entries.FindAsync(marta.Id, EntryKind.Story, "3742118"))!;
Assert.AreEqual("storie/2026/2026-10-13_09-41-07_3742118_1.mp4", (await bed.Library.Db.Media.ListByEntryAsync(story.Id)).Single().RelativePath);
var byDate = files.Single(f => f.RelativePath.EndsWith("IMG_20210506_070809.jpg", StringComparison.Ordinal));
Assert.AreEqual("importati/IMG_20210506_070809 (2).jpg", byDate.DestinationPath, "Senza codice: in importati con il nome originale, e mai sopra un file che c'è già.");
CollectionAssert.AreEqual(new byte[] { 9, 9, 9 }, File.ReadAllBytes(squatter));
Assert.AreEqual("importati/senza data.jpg", files.Single(f => f.RelativePath.EndsWith("senza data.jpg", StringComparison.Ordinal)).DestinationPath);
var journal = await AccountJournal.ReadAsync(folder);
Assert.IsTrue(journal.Lines.All(l => l.Entry.Provenance == "imported"));
Assert.AreEqual(4, journal.Lines.Select(l => l.Entry.Id ?? l.Entry.Code ?? l.Files![0].Path).Distinct().Count(), "Una riga di _febe.jsonl per ogni elemento importato.");
}
[TestMethod]
public async Task AFolderWithoutAccountBlocksOnlyItsOwnFiles()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(10));
bed.Write("marta.demo/b.jpg", ImportTestFiles.Photo(11));
bed.Write("Foto sparse/c.jpg", ImportTestFiles.Photo(12));
bed.Write("Foto sparse/d.jpg", ImportTestFiles.Photo(13));
bed.Write("Foto sparse/e.jpg", ImportTestFiles.Photo(14));
var run = await bed.AnalyzeAsync();
var plan = await bed.Review.GetPlanAsync(run.Id);
Assert.AreEqual(2, plan.ToImport);
Assert.AreEqual(3, plan.LeftOutNoAccount);
Assert.AreEqual(1, plan.FoldersWithoutAccount);
Assert.AreEqual("Importa 2 file", plan.ButtonLabel);
Assert.AreEqual("1 cartella senza account: 3 file restano fuori", plan.LeftOutLabel);
await bed.Copier.CopyAsync(run.Id);
var created = await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo");
Assert.IsNotNull(created, "L'account nuovo nasce quando parte la copia.");
Assert.AreEqual(AccountState.ArchiveOnly, created.State);
Assert.IsFalse(created.KeepUpdated);
var files = await bed.FilesAsync(run.Id);
Assert.AreEqual(2, files.Count(f => f.State == ImportFileState.Copied));
var left = files.Where(f => f.Folder == "Foto sparse").ToList();
Assert.IsTrue(left.All(f => f.State == ImportFileState.Analyzed && f.LastError == ImportText.NoteNoAccount));
var report = await bed.Reports.GetReportAsync(run.Id);
Assert.AreEqual(2, report.Copied);
Assert.AreEqual(3, report.LeftOut);
// «Importa i rimasti»: the folder gets an account and the copy runs again on the same import.
await bed.Review.SetFolderTargetAsync(run.Id, "Foto sparse", FolderTarget.Existing(created.Id));
Assert.AreEqual(3, (await bed.Review.GetPlanAsync(run.Id)).ToImport);
await bed.Copier.CopyAsync(run.Id);
Assert.AreEqual(5, (await bed.FilesAsync(run.Id)).Count(f => f.State == ImportFileState.Copied));
Assert.AreEqual(0, (await bed.Review.GetPlanAsync(run.Id)).ToImport);
Assert.IsNull((await bed.Review.GetPlanAsync(run.Id)).LeftOutLabel);
}
[TestMethod]
public async Task AnInterruptedCopyResumesWithoutDuplicates()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
for (var i = 0; i < 20; i++)
{
bed.Write($"luca.demo/foto-{i:00}.png", ImportTestFiles.Png(200 + i, 48, 36));
}
var run = await bed.AnalyzeAsync();
using var stop = new CancellationTokenSource();
var progress = new SyncProgress(p =>
{
if (p.Phase == ImportPhase.Copying && p.FilesDone >= 7)
{
stop.Cancel();
}
});
await Assert.ThrowsAsync<OperationCanceledException>(() => bed.Copier.CopyAsync(run.Id, progress, stop.Token));
Assert.AreEqual(ImportRunState.CopyInterrupted, (await bed.Library.Db.Imports.GetRunAsync(run.Id))!.State);
var halfway = (await bed.FilesAsync(run.Id)).Count(f => f.State == ImportFileState.Copied);
Assert.IsTrue(halfway is >= 7 and < 20, $"Copiati prima dell'interruzione: {halfway}.");
await bed.Copier.CopyAsync(run.Id);
var files = await bed.FilesAsync(run.Id);
Assert.IsTrue(files.All(f => f.State == ImportFileState.Copied));
var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("luca.demo"))!;
var onDisk = Directory.GetFiles(bed.Library.Layout.AccountFolder(account), "*.png", SearchOption.AllDirectories);
Assert.HasCount(20, onDisk, "Nessun file copiato due volte.");
Assert.IsFalse(onDisk.Any(f => f.Contains(" (2)", StringComparison.Ordinal)));
Assert.HasCount(20, await bed.Library.Db.Entries.ListByAccountAsync(account.Id));
}
[TestMethod]
public async Task MoveDeletesAnOriginalOnlyAfterItsCopyIsVerified()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var already = ImportTestFiles.Photo(30);
await bed.AccountWithPhotoAsync("marta.demo", "300", already);
var moved = bed.Write("marta.demo/nuova.jpg", ImportTestFiles.Photo(31));
var skipped = bed.Write("marta.demo/gia-presente.jpg", already);
var run = await bed.AnalyzeAsync();
await bed.Review.SetModeAsync(run.Id, ImportMode.Move);
await bed.Copier.CopyAsync(run.Id);
var file = await bed.FileAsync(run.Id, "marta.demo/nuova.jpg");
Assert.AreEqual(ImportFileState.Moved, file.State);
Assert.IsFalse(File.Exists(moved), "Copia verificata: l'originale si elimina.");
var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!;
var copy = bed.Library.Layout.FullPath(account, file.DestinationPath!);
Assert.AreEqual(file.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(copy))));
Assert.IsTrue(File.Exists(skipped), "Un file saltato non si tocca, nemmeno con «Sposta».");
CollectionAssert.AreEqual(new[] { moved }, bed.FileSystem.Deleted);
}
[TestMethod]
public async Task MoveNeverDeletesAnUnverifiedOriginal()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var original = bed.Write("marta.demo/preziosa.jpg", ImportTestFiles.Photo(40));
var originalBytes = File.ReadAllBytes(original);
var run = await bed.AnalyzeAsync();
await bed.Review.SetModeAsync(run.Id, ImportMode.Move);
bed.FileSystem.CorruptCopies = true; // the copy on disk is damaged before it is checked
await bed.Copier.CopyAsync(run.Id);
var file = await bed.FileAsync(run.Id, "marta.demo/preziosa.jpg");
Assert.AreEqual(ImportFileState.Failed, file.State);
Assert.AreEqual(ImportText.NoteNotVerified, file.LastError);
Assert.IsTrue(File.Exists(original), "Copia non verificata: l'originale resta.");
CollectionAssert.AreEqual(originalBytes, File.ReadAllBytes(original));
Assert.IsEmpty(bed.FileSystem.Deleted);
// Trying again checks the copy again: still damaged, still kept.
await bed.Copier.CopyAsync(run.Id);
Assert.IsTrue(File.Exists(original));
Assert.IsEmpty(bed.FileSystem.Deleted);
}
[TestMethod]
public async Task AMoveLeftHalfwayIsFinishedAndCopiesMadeBeforeAreNeverMoved()
{
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 copiedFirst = bed.Write("marta.demo/copiata-prima.jpg", ImportTestFiles.Photo(45));
var locked = bed.Write("Foto sparse/in-uso.jpg", ImportTestFiles.Photo(46));
var run = await bed.AnalyzeAsync();
// First «Copia» for marta.demo only (Foto sparse has no account yet).
await bed.Copier.CopyAsync(run.Id);
Assert.AreEqual(ImportFileState.Copied, (await bed.FileAsync(run.Id, "marta.demo/copiata-prima.jpg")).State);
// Then «Sposta» for the rest, with the original open in another program.
var marta = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!;
await bed.Review.SetFolderTargetAsync(run.Id, "Foto sparse", FolderTarget.Existing(marta.Id));
await bed.Review.SetModeAsync(run.Id, ImportMode.Move);
bed.FileSystem.FailDeletes = true;
await bed.Copier.CopyAsync(run.Id);
var stuck = await bed.FileAsync(run.Id, "Foto sparse/in-uso.jpg");
Assert.AreEqual(ImportFileState.Copied, stuck.State);
StringAssert.EndsWith(stuck.LastError, ImportText.NoteOriginalKept);
Assert.IsTrue(File.Exists(locked));
bed.FileSystem.FailDeletes = false;
await bed.Copier.CopyAsync(run.Id);
Assert.AreEqual(ImportFileState.Moved, (await bed.FileAsync(run.Id, "Foto sparse/in-uso.jpg")).State);
Assert.IsNull((await bed.FileAsync(run.Id, "Foto sparse/in-uso.jpg")).LastError);
Assert.IsFalse(File.Exists(locked), "La copia è verificata di nuovo, poi l'originale si elimina.");
Assert.IsTrue(File.Exists(copiedFirst), "Un file copiato con «Copia» non si elimina passando a «Sposta».");
Assert.AreEqual(ImportFileState.Copied, (await bed.FileAsync(run.Id, "marta.demo/copiata-prima.jpg")).State);
}
[TestMethod]
public async Task AReadOnlySourceDoesNotOfferMove()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp, readOnlySource: true);
bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(50));
var info = bed.Environment.CreateSources().Inspect(bed.Source);
Assert.IsTrue(info.ReadOnly);
Assert.IsFalse(info.CanMove);
var run = await bed.AnalyzeAsync();
Assert.IsTrue(run.SourceReadOnly);
Assert.IsFalse((await bed.Review.GetSummaryAsync(run.Id)).CanMove, "«Sposta» non compare.");
await Assert.ThrowsAsync<InvalidOperationException>(() => bed.Review.SetModeAsync(run.Id, ImportMode.Move));
await bed.Copier.CopyAsync(run.Id);
Assert.AreEqual(ImportFileState.Copied, (await bed.FilesAsync(run.Id)).Single().State);
Assert.IsTrue(File.Exists(Path.Combine(bed.Source, "marta.demo", "a.jpg")));
// In Docker the /importa volume is read-only by configuration, whatever the probe says.
var docker = new ImportSources(ImportSourceOptions.Docker(bed.Temp.Path), probe: new FixedAccessProbe(false));
Assert.IsTrue(docker.Inspect(bed.Source).ReadOnly);
}
[TestMethod]
public async Task DecisionsOnProbableDuplicatesAreAppliedByTheCopyOnly()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var (marta, a) = await bed.AccountWithPhotoAsync("marta.demo", "70", ImportTestFiles.Photo(70, 800, 600, 92));
var (_, b) = await bed.AccountWithPhotoAsync("marta.demo", "71", ImportTestFiles.Resized(71, 800, 600, 400, 300, 70));
var (_, c) = await bed.AccountWithPhotoAsync("marta.demo", "72", ImportTestFiles.Photo(72, 800, 600, 92));
var (_, d) = await bed.AccountWithPhotoAsync("marta.demo", "73", ImportTestFiles.Photo(73, 800, 600, 92));
bed.Write("marta.demo/a-piccola.jpg", ImportTestFiles.Resized(70, 800, 600, 400, 300, 60));
var bigger = bed.Write("marta.demo/b-grande.jpg", ImportTestFiles.Photo(71, 800, 600, 92));
bed.Write("marta.demo/c-piccola.jpg", ImportTestFiles.Resized(72, 800, 600, 400, 300, 60));
bed.Write("marta.demo/d-piccola.jpg", ImportTestFiles.Resized(73, 800, 600, 400, 300, 60));
var run = await bed.AnalyzeAsync();
var oldB = bed.Library.Layout.FullPath(marta, b.Media[0].RelativePath!);
var undecided = await bed.Review.GetPlanAsync(run.Id);
Assert.AreEqual(4, undecided.LeftOutUndecided);
StringAssert.Contains(undecided.LeftOutLabel, "4 file aspettano la tua decisione");
await bed.Copier.CopyAsync(run.Id);
Assert.IsTrue(File.Exists(oldB), "Senza una scelta di Alberto non si sostituisce nulla (regola 12).");
Assert.IsTrue((await bed.FilesAsync(run.Id)).All(f => f.State == ImportFileState.Analyzed));
var cases = await bed.Review.ListDuplicatesAsync(run.Id);
Assert.HasCount(4, cases);
Assert.IsTrue(cases.All(x => x.Pair.Decision == DuplicateDecision.Pending), "Nessuna scelta fatta in partenza.");
DuplicateCase Case(EntryWithMedia library) => cases.Single(x => x.Existing.MediaId == library.Media[0].Id);
Assert.IsTrue(Case(b).CandidateIsLarger);
Assert.IsFalse(Case(a).CandidateIsLarger);
await bed.Review.DecideAsync(run.Id, Case(a).Pair.Id, DuplicateDecision.KeepLarger);
await bed.Review.DecideAsync(run.Id, Case(b).Pair.Id, DuplicateDecision.KeepLarger);
await bed.Review.DecideAsync(run.Id, Case(c).Pair.Id, DuplicateDecision.KeepBoth);
await bed.Review.DecideAsync(run.Id, Case(d).Pair.Id, DuplicateDecision.KeepExisting);
var plan = await bed.Review.GetPlanAsync(run.Id);
Assert.AreEqual(2, plan.ToImport);
Assert.AreEqual(1, plan.ToReplace);
await bed.Copier.CopyAsync(run.Id);
var files = await bed.FilesAsync(run.Id);
ImportFile File_(string name) => files.Single(f => f.RelativePath == "marta.demo/" + name);
Assert.AreEqual(ImportFileState.Skipped, File_("a-piccola.jpg").State);
Assert.AreEqual(ImportText.NoteLibraryLarger, File_("a-piccola.jpg").LastError);
Assert.AreEqual(ImportFileState.Skipped, File_("d-piccola.jpg").State);
Assert.AreEqual(ImportFileState.Copied, File_("c-piccola.jpg").State, "«Tienili entrambi».");
Assert.AreEqual(1, (await bed.Library.Db.Entries.ListByAccountAsync(marta.Id)).Count(e => e.Provenance == Provenance.Imported), "Solo «Tienili entrambi» crea un elemento nuovo.");
// «Tieni il più grande» with the imported file larger: the library file is replaced, safely.
var replaced = File_("b-grande.jpg");
Assert.AreEqual(ImportFileState.Copied, replaced.State);
StringAssert.StartsWith(replaced.LastError, ImportText.NoteReplaced);
var media = (await bed.Library.Db.Media.GetAsync(b.Media[0].Id))!;
Assert.AreEqual(replaced.Sha256, media.Sha256, "Il record della libreria punta al file nuovo.");
Assert.AreEqual((800, 600), (media.Width, media.Height));
Assert.AreEqual(MediaState.Downloaded, media.State, "Il file resta quello dell'elemento scaricato.");
var newPath = bed.Library.Layout.FullPath(marta, media.RelativePath!);
Assert.AreEqual(replaced.Sha256, Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(newPath))));
Assert.IsFalse(File.Exists(oldB), "Il file più piccolo si elimina solo dopo che il nuovo è stato scritto e verificato.");
Assert.IsTrue(File.Exists(bigger), "Con «Copia» l'originale resta.");
Assert.IsTrue(bed.Library.Thumbnails.Exists(media.Sha256!));
Assert.IsFalse(bed.Library.Thumbnails.Exists(b.Media[0].Sha256!), "La miniatura del file sostituito non serve più.");
var journal = await AccountJournal.ReadAsync(bed.Library.Layout.AccountFolder(marta));
Assert.AreEqual(media.RelativePath, journal.Lines.Last(l => l.Entry.Id == "71").Files!.Single().Path, "L'ultima riga di _febe.jsonl porta il file nuovo.");
Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import));
}
[TestMethod]
public async Task ADecisionCanBeAppliedToTheOtherCases()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
for (var i = 0; i < 3; i++)
{
await bed.AccountWithPhotoAsync("marta.demo", (80 + i).ToString(System.Globalization.CultureInfo.InvariantCulture), ImportTestFiles.Photo(80 + i, 800, 600, 92));
bed.Write($"marta.demo/copia-{i}.jpg", ImportTestFiles.Resized(80 + i, 800, 600, 400, 300, 60));
}
var account = (await bed.Library.Db.Accounts.FindByUsernameAsync("marta.demo"))!;
var story = Make.Entry(account.Id, "3742119", Make.T0, EntryKind.Story);
await bed.Library.SaveAsync(account, story, [new TestFile(Make.Photo(1), ImportTestFiles.Photo(90), ".jpg")]);
bed.Write("marta.demo/storie/2026/2026-10-13_10-00-00_3742119_1.jpg", ImportTestFiles.Photo(91));
var run = await bed.AnalyzeAsync();
var cases = await bed.Review.ListDuplicatesAsync(run.Id);
Assert.HasCount(4, cases);
var visual = cases.First(c => c.Pair.Reason == DuplicateReason.VisuallySimilar);
Assert.AreEqual(3, await bed.Review.DecideAsync(run.Id, visual.Pair.Id, DuplicateDecision.KeepExisting, DecisionScope.SameReason));
Assert.HasCount(1, await bed.Review.ListDuplicatesAsync(run.Id), "Resta il caso con un'altra ragione.");
var last = (await bed.Review.ListDuplicatesAsync(run.Id)).Single();
Assert.AreEqual(1, await bed.Review.DecideAsync(run.Id, last.Pair.Id, DuplicateDecision.KeepBoth, DecisionScope.AllPending));
Assert.IsEmpty(await bed.Review.ListDuplicatesAsync(run.Id));
Assert.AreEqual(ImportDecision.KeepExisting, (await bed.FileAsync(run.Id, "marta.demo/copia-1.jpg")).Decision);
await Assert.ThrowsAsync<ArgumentException>(() => bed.Review.DecideAsync(run.Id, last.Pair.Id, DuplicateDecision.Pending));
}
[TestMethod]
public async Task InsideTheSourceKeepLargerImportsOnlyTheLargest()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
bed.Write("marta.demo/1-media.jpg", ImportTestFiles.Resized(95, 800, 600, 600, 450, 80));
bed.Write("marta.demo/2-grande.jpg", ImportTestFiles.Photo(95, 800, 600, 92));
bed.Write("marta.demo/3-piccola.jpg", ImportTestFiles.Resized(95, 800, 600, 400, 300, 60));
var run = await bed.AnalyzeAsync();
var cases = await bed.Review.ListDuplicatesAsync(run.Id);
Assert.HasCount(2, cases);
Assert.IsTrue(cases.All(c => c.InsideSource));
await bed.Review.DecideAsync(run.Id, cases[0].Pair.Id, DuplicateDecision.KeepLarger, DecisionScope.AllPending);
await bed.Copier.CopyAsync(run.Id);
var files = await bed.FilesAsync(run.Id);
Assert.AreEqual("marta.demo/2-grande.jpg", files.Single(f => f.State == ImportFileState.Copied).RelativePath);
Assert.AreEqual(2, files.Count(f => f.State == ImportFileState.Skipped));
}
[TestMethod]
public async Task AFebeLibraryIsImportedWithItsIdentifiersAndCaptions()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var folder = Path.Combine(bed.Source, "marta.demo");
bed.Write("marta.demo/post/2025/2025-03-01_10-30-15_CxYz123_1.jpg", ImportTestFiles.Photo(100));
bed.Write("marta.demo/evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg", ImportTestFiles.Photo(101));
await AccountJournal.AppendAsync(folder, new JournalLine
{
Op = JournalOps.Save,
At = Make.T0,
Account = new JournalAccount("4242", "marta.demo"),
Entry = new JournalEntry { Kind = "post", Id = "3100000000000000001", Code = "CxYz123", PublishedAt = new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), Caption = "Al mare" },
Files = [new JournalFile { N = 1, Type = "photo", Path = "post/2025/2025-03-01_10-30-15_CxYz123_1.jpg", Id = "3100000000000000002" }],
});
await AccountJournal.AppendAsync(folder, new JournalLine
{
Op = JournalOps.Save,
At = Make.T0,
Account = new JournalAccount("4242", "marta.demo"),
Entry = new JournalEntry { Kind = "evidenza", Id = "3391207", PublishedAt = new DateTimeOffset(2025, 8, 2, 8, 11, 12, TimeSpan.Zero), Highlights = [new JournalHighlight("99", "Estate 2025")] },
Files = [new JournalFile { N = 1, Type = "photo", Path = "evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg" }],
});
var marta = await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo", "4242"));
var info = bed.Environment.CreateSources().Inspect(bed.Source);
Assert.IsTrue(info.LooksLikeFebeLibrary);
var run = await bed.AnalyzeAsync();
var summary = await bed.Review.GetSummaryAsync(run.Id);
Assert.AreEqual(2, summary.Recognized, "Elementi di cui si conosce codice o identificativo: Febe non li riscaricherà.");
Assert.AreEqual(marta.Id, summary.Folders.Single().Target.AccountId, "Riconosciuto dall'identificativo Instagram dell'account.");
await bed.Copier.CopyAsync(run.Id);
var post = (await bed.Library.Db.Entries.FindAsync(marta.Id, EntryKind.Post, "3100000000000000001"))!;
Assert.AreEqual("CxYz123", post.Code);
Assert.AreEqual("Al mare", post.Caption);
Assert.AreEqual(new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), post.PublishedAt, "Data esatta dal giornale di Febe.");
Assert.AreEqual("3100000000000000002", (await bed.Library.Db.Media.ListByEntryAsync(post.Id)).Single().InstagramId);
Assert.IsTrue(await bed.Library.Db.Entries.IsKnownAsync(marta.Id, EntryKind.Post, "3100000000000000001"), "Quando terrà aggiornato l'account non lo riscaricherà.");
var highlight = (await bed.Library.Db.Entries.FindAsync(marta.Id, EntryKind.Highlight, "3391207"))!;
var collections = await bed.Library.Db.Highlights.ListForEntryAsync(highlight.Id);
Assert.AreEqual("Estate 2025", collections.Single().Title);
Assert.AreEqual("evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1.jpg", (await bed.Library.Db.Media.ListByEntryAsync(highlight.Id)).Single().RelativePath);
}
[TestMethod]
public async Task TheCsvHasOneRowPerFileSemicolonsAndABom()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
bed.Write("marta.demo/uno;due.jpg", ImportTestFiles.Photo(110));
bed.Write("marta.demo/=SOMMA(1).jpg", ImportTestFiles.Photo(111));
bed.Write("marta.demo/nota.txt", "testo"u8.ToArray());
var run = await bed.AnalyzeAsync();
await bed.Copier.CopyAsync(run.Id);
using var output = new MemoryStream();
await bed.Reports.WriteCsvAsync(run.Id, output);
var bytes = output.ToArray();
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "UTF-8 con BOM, per Excel in italiano.");
var text = System.Text.Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
var lines = text.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
Assert.HasCount(4, lines, "Intestazione e una riga per file.");
Assert.AreEqual("File;Cartella;Esito;Stato;Account di destinazione;Tipo;Data;Origine della data;Formato;Byte;Larghezza;Altezza;Durata (s);SHA-256;Codice;Identificativo Instagram;Già in libreria;Destinazione;Nota", lines[0]);
Assert.IsTrue(lines.Any(l => l.StartsWith("\"marta.demo/uno;due.jpg\";marta.demo;Nuovo;Copiato;marta.demo;", StringComparison.Ordinal)), "Un campo con «;» va tra virgolette.");
Assert.IsTrue(lines.Any(l => l.StartsWith("marta.demo/=SOMMA(1).jpg;", StringComparison.Ordinal)), "Il percorso comincia con la cartella: nessuna formula.");
Assert.IsTrue(lines.Any(l => l.Contains(";Non riconosciuto;Saltato;", StringComparison.Ordinal)));
Assert.AreEqual("'=SOMMA(1)", ImportReports.Field("=SOMMA(1)"), "Un testo che Excel prenderebbe per una formula.");
Assert.AreEqual("\"a \"\"b\"\"\"", ImportReports.Field("a \"b\""));
Assert.AreEqual($"importazione-2026-10-13-{run.Id}.csv", bed.Reports.CsvFileName(run));
}
[TestMethod]
public async Task TheReportCountsEveryOutcome()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
var photo = ImportTestFiles.Photo(120);
await bed.AccountWithPhotoAsync("luca.demo", "120", photo);
await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
bed.Write("marta.demo/gia.jpg", photo);
bed.Write("marta.demo/nuova.jpg", ImportTestFiles.Photo(121));
bed.Write("marta.demo/copia/nuova.jpg", ImportTestFiles.Photo(121));
bed.Write("marta.demo/documento.pdf", "%PDF-1.7\n"u8.ToArray());
var run = await bed.AnalyzeAsync();
await bed.Copier.CopyAsync(run.Id);
var report = await bed.Reports.GetReportAsync(run.Id);
Assert.AreEqual(4, report.Files);
Assert.AreEqual(1, report.ByOutcome[ImportOutcome.AlreadyInLibrary]);
Assert.AreEqual(1, report.ByOutcome[ImportOutcome.IdenticalInSource]);
Assert.AreEqual(1, report.Copied);
Assert.AreEqual(3, report.Skipped, "Già in libreria, copia identica e non riconosciuto.");
Assert.AreEqual("luca.demo", report.AlreadyInLibraryByAccount.Single().Username);
Assert.AreEqual("marta.demo", report.ImportedByAccount.Single().Username);
CollectionAssert.AreEqual(new[] { "marta.demo/documento.pdf" }, report.Unrecognized.ToArray());
}
private sealed class SyncProgress(Action<ImportProgress> report) : IProgress<ImportProgress>
{
public void Report(ImportProgress value) => report(value);
}
}
@@ -0,0 +1,123 @@
using System.Collections.Concurrent;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class ImportServiceTests
{
[TestMethod]
public async Task TheFourStepsRunInTheBackground()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
await bed.Library.Db.Accounts.AddAsync(Make.Account("marta.demo"));
for (var i = 0; i < 5; i++)
{
bed.Write($"marta.demo/foto-{i}.jpg", ImportTestFiles.Photo(300 + i, 200, 150));
}
await using var service = new ImportService(bed.Environment);
var events = new ConcurrentQueue<ImportProgress>();
service.ProgressChanged += (_, p) => events.Enqueue(p);
var source = service.InspectSource(bed.Source);
Assert.IsTrue(source.CanMove);
var run = await service.StartAsync(bed.Source);
Assert.AreEqual(ImportRunState.Analyzing, run.State);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.StartAsync(bed.Source), "Un lavoro alla volta.");
var analysed = await service.WaitAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, analysed!.State);
Assert.IsNull(service.ActiveRunId);
Assert.IsTrue(events.Any(e => e.Phase == ImportPhase.Finished && e.RunId == run.Id && e.FilesDone == 5));
var review = await service.GetReviewAsync(run.Id);
Assert.AreEqual(5, review.ByOutcome[ImportOutcome.New]);
var plan = await service.GetPlanAsync(run.Id);
Assert.AreEqual("Importa 5 file", plan.ButtonLabel);
await service.StartCopyAsync(run.Id, ImportMode.Copy);
var copied = await service.WaitAsync(run.Id);
Assert.AreEqual(ImportRunState.Completed, copied!.State);
var progress = await service.GetProgressAsync(run.Id);
Assert.AreEqual(ImportPhase.Finished, progress.Phase);
Assert.AreEqual(5, progress.Copied);
Assert.AreEqual(5, (await service.GetReportAsync(run.Id)).Copied);
}
[TestMethod]
public async Task AJobLeftRunningByAStopIsResumed()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
bed.Write("marta.demo/a.jpg", ImportTestFiles.Photo(310, 200, 150));
var run = await bed.Analyzer.CreateRunAsync(bed.Environment.CreateSources().Inspect(bed.Source));
// Febe stopped while the analysis was running: the state says «in corso» but nothing runs.
await using var service = new ImportService(bed.Environment);
Assert.AreEqual(1, await service.RecoverAsync());
Assert.AreEqual(ImportRunState.AnalysisInterrupted, (await service.GetRunAsync(run.Id))!.State);
await service.ResumeAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, (await service.WaitAsync(run.Id))!.State);
await Assert.ThrowsAsync<InvalidOperationException>(() => service.ResumeAsync(run.Id), "Niente da riprendere.");
}
[TestMethod]
public async Task InterruptStopsTheJobAndKeepsWhatIsDone()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
for (var i = 0; i < 100; i++)
{
bed.Write($"marta.demo/f{i:000}.png", ImportTestFiles.Png(400 + i, 40, 30));
}
// Files from f080 on cannot be read until the job is stopped: the first group of 64 is done by then.
var gated = new GatedFileSystem(bed.FileSystem, path => string.CompareOrdinal(Path.GetFileName(path), "f080.png") >= 0);
await using var service = new ImportService(bed.Environment with { FileSystem = gated });
var run = await service.StartAsync(bed.Source);
await gated.Reached.Task.WaitAsync(TimeSpan.FromSeconds(60));
await service.InterruptAsync(run.Id);
var stopped = (await service.GetRunAsync(run.Id))!;
Assert.AreEqual(ImportRunState.AnalysisInterrupted, stopped.State);
Assert.IsNull(stopped.LastError);
var summary = await bed.Library.Db.Imports.GetSummaryAsync(run.Id);
Assert.AreEqual(64, summary.ByState[ImportFileState.Analyzed]);
Assert.AreEqual(36, summary.ByState[ImportFileState.Pending]);
var progress = await service.GetProgressAsync(run.Id);
Assert.AreEqual((64, 100), (progress.FilesDone, progress.FilesTotal));
await using var again = new ImportService(bed.Environment);
await again.ResumeAsync(run.Id);
Assert.AreEqual(ImportRunState.Reviewing, (await again.WaitAsync(run.Id))!.State);
Assert.AreEqual(100, (await bed.Library.Db.Imports.GetSummaryAsync(run.Id)).ByState[ImportFileState.Analyzed]);
}
[TestMethod]
public async Task DiscardingAnImportLeavesFilesAlone()
{
using var temp = new TempFolder("importa");
await using var bed = await ImportTestBed.CreateAsync(temp);
await bed.AccountWithPhotoAsync("marta.demo", "1", ImportTestFiles.Photo(320, 800, 600, 92));
bed.Write("marta.demo/simile.jpg", ImportTestFiles.Resized(320, 800, 600, 400, 300, 60));
var before = bed.Fingerprint();
await using var service = new ImportService(bed.Environment);
var run = await service.StartAsync(bed.Source, new ImportAnalysisOptions { StogramHypothesis = true });
await service.WaitAsync(run.Id);
Assert.AreEqual(1, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import));
Assert.IsTrue((await service.GetReviewAsync(run.Id)).StogramHypothesis);
await service.DiscardAsync(run.Id);
Assert.IsNull(await service.GetRunAsync(run.Id), "Nulla era stato copiato: l'importazione sparisce.");
Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import));
Assert.IsNull(await bed.Library.Db.Settings.GetAsync($"importazione.{run.Id}.ipotesi-stogram"));
CollectionAssert.AreEqual(before.ToList(), bed.Fingerprint().ToList());
}
}
@@ -0,0 +1,81 @@
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class ImportSourcesTests
{
[TestMethod]
public void InDockerOnlyTheImportVolumeIsOffered()
{
using var temp = new TempFolder("sorgenti");
var root = temp.Combine("importa");
Directory.CreateDirectory(Path.Combine(root, "4K Stogram", "marta.demo"));
Directory.CreateDirectory(Path.Combine(root, "Telefono"));
Directory.CreateDirectory(temp.Combine("fuori"));
var sources = new ImportSources(ImportSourceOptions.Docker(root), probe: new FixedAccessProbe(false));
var choices = sources.Browse();
CollectionAssert.AreEqual(new[] { "4K Stogram", "Telefono" }, choices.Select(c => c.Name).ToArray());
Assert.IsTrue(choices[0].HasSubfolders);
Assert.AreEqual("4K Stogram/marta.demo", sources.Browse("4K Stogram").Single().Path);
var info = sources.Inspect("4K Stogram");
Assert.AreEqual(Path.Combine(root, "4K Stogram"), info.FullPath);
Assert.IsTrue(info.ReadOnly, "Il volume /importa è in sola lettura.");
Assert.IsFalse(info.CanMove);
Assert.AreEqual(root + "/4K Stogram", info.DisplayPath);
var outside = Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(temp.Combine("fuori")));
StringAssert.Contains(outside.Message, "sottocartella");
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect("../fuori"));
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect("non-esiste"));
Assert.ThrowsExactly<ImportSourceException>(() => sources.Browse(".."));
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(" "));
}
[TestMethod]
public void TheLibraryAndTheDataFolderAreNotSources()
{
using var temp = new TempFolder("sorgenti");
var library = temp.Combine("libreria");
var data = temp.Combine("dati");
Directory.CreateDirectory(Path.Combine(library, "marta.demo"));
File.WriteAllText(Path.Combine(library, "marta.demo", AccountJournal.FileName), string.Empty);
Directory.CreateDirectory(Path.Combine(library, "vecchie foto"));
Directory.CreateDirectory(data);
var sources = new ImportSources(ImportSourceOptions.AnyFolder, library, data, new FixedAccessProbe(false));
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(temp.Path), "Contiene la libreria.");
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(library));
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(Path.Combine(library, "marta.demo")), "Cartella di un account.");
Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(data));
Assert.AreEqual("vecchie foto", sources.Inspect(Path.Combine(library, "vecchie foto")).Name, "Una cartella della libreria senza _febe.jsonl si può importare.");
}
[TestMethod]
public void AReadOnlyMountIsSeenInTheMountTable()
{
const string mounts = """
overlay / overlay rw,relatime,lowerdir=/x 0 0
/dev/sdb1 /importa ext4 ro,relatime 0 0
/dev/sdc1 /importa/scrivibile ext4 rw,relatime 0 0
/dev/sdd1 /mnt/foto\040di\040casa xfs ro 0 0
""";
Assert.IsTrue(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importa/4K Stogram"));
Assert.IsTrue(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importa"));
Assert.IsFalse(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importa/scrivibile/a"), "Vince il punto di montaggio più lungo.");
Assert.IsFalse(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/home/alberto/Immagini"));
Assert.IsFalse(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/importazione"), "/importa non contiene /importazione.");
Assert.IsTrue(SystemSourceAccessProbe.MountIsReadOnly(mounts, "/mnt/foto di casa/2019"));
if (OperatingSystem.IsLinux())
{
using var temp = new TempFolder("sorgenti");
Assert.IsFalse(new SystemSourceAccessProbe().IsReadOnly(temp.Path), "Una cartella temporanea si può scrivere.");
}
}
}
+176
View File
@@ -0,0 +1,176 @@
using System.Text;
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Tests.Import.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class MediaReaderTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero);
[TestMethod]
public void TheTypeComesFromTheContentNotFromTheExtension()
{
var jpeg = ImportTestFiles.Photo(1, 64, 48);
var png = ImportTestFiles.Png(2, 64, 48);
Assert.AreEqual("image/jpeg", MediaSniffer.Detect(jpeg, ".png")?.ContentType, "Un JPEG chiamato .png resta un JPEG.");
Assert.AreEqual(".jpg", MediaSniffer.Detect(jpeg, ".jpeg")?.Extension);
Assert.AreEqual("image/png", MediaSniffer.Detect(png, ".jpg")?.ContentType);
Assert.AreEqual(MediaKind.Photo, MediaSniffer.Detect("GIF89a\x01\0\x01\0"u8.ToArray())?.Kind);
Assert.AreEqual("image/webp", MediaSniffer.Detect("RIFF\0\0\0\0WEBPVP8 "u8.ToArray())?.ContentType);
Assert.AreEqual("video/x-msvideo", MediaSniffer.Detect("RIFF\0\0\0\0AVI LIST"u8.ToArray())?.ContentType);
Assert.AreEqual("image/heic", MediaSniffer.Detect(Ftyp("heic", "mif1", "heic"))?.ContentType);
Assert.AreEqual("image/heif", MediaSniffer.Detect(Ftyp("mif1", "mif1"))?.ContentType);
Assert.AreEqual("image/avif", MediaSniffer.Detect(Ftyp("avif", "mif1", "avif"))?.ContentType);
Assert.AreEqual("video/mp4", MediaSniffer.Detect(Ftyp("isom", "isom", "mp41"))?.ContentType);
Assert.AreEqual("video/mp4", MediaSniffer.Detect(Ftyp("mp42", "mp42"))?.ContentType);
Assert.AreEqual("video/quicktime", MediaSniffer.Detect(Ftyp("qt ", "qt "))?.ContentType);
Assert.AreEqual("video/quicktime", MediaSniffer.Detect(ImportTestFiles.Mp4(Now, withFtyp: false))?.ContentType, "MOV senza ftyp, che comincia con moov.");
Assert.AreEqual("video/webm", MediaSniffer.Detect([0x1A, 0x45, 0xDF, 0xA3, 0x9F, 0x42, 0x86, 0x81, 0x01, 0x42, 0x82, 0x84, .. "webm"u8])?.ContentType);
Assert.AreEqual(MediaKind.Photo, MediaSniffer.Detect("II*\0\x08\0\0\0"u8.ToArray(), ".DNG")?.Kind);
Assert.AreEqual(".dng", MediaSniffer.Detect("II*\0\x08\0\0\0"u8.ToArray(), ".DNG")?.Extension, "I formati raw tengono la loro estensione.");
Assert.IsNull(MediaSniffer.Detect(Ftyp("M4A ", "M4A ", "mp42")), "Solo audio: né foto né video.");
Assert.IsNull(MediaSniffer.Detect(Encoding.UTF8.GetBytes("Appunti del viaggio, non una foto.")));
Assert.IsNull(MediaSniffer.Detect("%PDF-1.7\n"u8.ToArray()));
Assert.IsNull(MediaSniffer.Detect([]));
}
[TestMethod]
public void TheShootingDateIsReadFromExifWrittenByHand()
{
var zone = TestZones.Rome;
var jpeg = ImportTestFiles.PhotoWithExifDate(3, new DateTime(2021, 5, 6, 7, 8, 9), width: 64, height: 48);
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), ExifDateReader.Read(jpeg, zone), "Ora locale di Roma (estate, +2).");
var withOffset = ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff("2021:05:06 07:08:09", offsetOriginal: "-05:00", littleEndian: true));
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 12, 8, 9, TimeSpan.Zero), ExifDateReader.Read(withOffset, zone)?.ToUniversalTime(), "Il fuso scritto dalla fotocamera vince.");
var onlyCreate = ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff(null, createDate: "2019:12:31 23:59:58"));
Assert.AreEqual(new DateTimeOffset(2019, 12, 31, 22, 59, 58, TimeSpan.Zero), ExifDateReader.Read(onlyCreate, zone), "Senza DateTimeOriginal si usa CreateDate.");
var png = ImportTestFiles.PngWithExif(ImportTestFiles.Png(4, 32, 24), ImportTestFiles.Tiff("2018:02:03 10:00:00"));
Assert.AreEqual(new DateTimeOffset(2018, 2, 3, 9, 0, 0, TimeSpan.Zero), ExifDateReader.Read(png, zone), "PNG con il blocco eXIf.");
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.Photo(3, 64, 48), zone), "Nessun EXIF: nessuna data.");
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), ImportTestFiles.Tiff("0000:00:00 00:00:00")), zone));
// A damaged block (offsets beyond the end) gives no date, never an exception.
var damaged = ImportTestFiles.Tiff("2021:05:06 07:08:09");
damaged.AsSpan(36, 4).Fill(0xFF); // the offset of the date value points far beyond the block
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), damaged), zone));
Assert.IsNull(ExifDateReader.Read(ImportTestFiles.JpegWithExif(ImportTestFiles.Photo(3, 64, 48), damaged.AsSpan(0, 20).ToArray()), zone));
}
[TestMethod]
public void CreationTimeDurationAndSizeComeFromTheMp4Header()
{
var created = new DateTimeOffset(2022, 7, 1, 18, 30, 0, TimeSpan.Zero);
var info = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, 1080, 1920, 15_500)), Now);
Assert.IsNotNull(info);
Assert.AreEqual(created, info.CreatedAt);
Assert.AreEqual(TimeSpan.FromMilliseconds(15_500), info.Duration);
Assert.AreEqual(1080, info.Width);
Assert.AreEqual(1920, info.Height);
var atEnd = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, moovAtEnd: true)), Now);
Assert.AreEqual(created, atEnd?.CreatedAt, "Il moov dopo i dati si trova saltando mdat.");
var rotated = Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(created, 1920, 1080, rotated: true)), Now);
Assert.AreEqual((1080, 1920), (rotated?.Width, rotated?.Height), "Un video ruotato di 90° si mostra in verticale.");
Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(null)), Now)?.CreatedAt, "Zero: data non scritta.");
Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(new DateTimeOffset(1904, 1, 2, 0, 0, 0, TimeSpan.Zero))), Now)?.CreatedAt, "Una data del 1904 non è plausibile.");
Assert.IsNull(Mp4Reader.Read(new MemoryStream(ImportTestFiles.Mp4(Now.AddDays(10))), Now)?.CreatedAt, "Una data nel futuro non è plausibile.");
Assert.IsNull(Mp4Reader.Read(new MemoryStream("not a movie at all"u8.ToArray()), Now));
}
[TestMethod]
public void AnMp4MadeByFfmpegCarriesItsCreationTime()
{
using var temp = new TempFolder("mp4");
var path = temp.Combine("prova.mp4");
var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero);
if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created))
{
Assert.Inconclusive("ffmpeg non è installato: la prova sulle intestazioni sintetiche copre il lettore.");
}
Assert.AreEqual("video/mp4", MediaSniffer.DetectFile(path)?.ContentType);
var info = Mp4Reader.ReadFile(path, Now);
Assert.AreEqual(created, info?.CreatedAt);
Assert.AreEqual(64, info?.Width);
Assert.AreEqual(48, info?.Height);
Assert.IsTrue(info?.Duration > TimeSpan.FromMilliseconds(500));
}
[TestMethod]
public async Task FfprobeIsAnOptionalExtra()
{
var parsed = FfprobeVideoMetadataProbe.Parse("""
{"streams":[{"codec_type":"audio"},{"codec_type":"video","width":1920,"height":1080,"tags":{"rotate":"90"}}],
"format":{"duration":"12.500000","tags":{"creation_time":"2020-08-09T10:11:12.000000Z"}}}
""");
Assert.AreEqual(new DateTimeOffset(2020, 8, 9, 10, 11, 12, TimeSpan.Zero), parsed?.CreatedAt);
Assert.AreEqual(TimeSpan.FromSeconds(12.5), parsed?.Duration);
Assert.AreEqual((1080, 1920), (parsed?.Width, parsed?.Height));
Assert.IsNull(FfprobeVideoMetadataProbe.Parse("non json"));
var probe = FfprobeVideoMetadataProbe.TryCreate();
if (probe is null)
{
Assert.Inconclusive("ffprobe non è installato.");
return;
}
using var temp = new TempFolder("ffprobe");
var path = temp.Combine("prova.mp4");
var created = new DateTimeOffset(2021, 3, 4, 5, 6, 7, TimeSpan.Zero);
if (!ImportTestFiles.TryMakeMp4WithFfmpeg(path, created))
{
Assert.Inconclusive("ffmpeg non è installato.");
}
var metadata = await probe.ProbeAsync(path);
Assert.AreEqual(created, metadata?.CreatedAt);
Assert.AreEqual(64, metadata?.Width);
}
[TestMethod]
public void DatesAreFoundInCommonFileNames()
{
var zone = TestZones.Rome;
static DateTimeOffset Rome(int y, int mo, int d, int h, int mi, int s) => new DateTimeOffset(y, mo, d, h, mi, s, TimeSpan.Zero).AddHours(mo is >= 4 and <= 10 ? -2 : -1);
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("IMG_20210506_070809", zone, Now)?.Instant);
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("VID_20210506_070809", zone, Now)?.Instant);
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("PXL_20210506_070809123", zone, Now)?.Instant);
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("2021-05-06 07.08.09", zone, Now)?.Instant);
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("WhatsApp Image 2021-05-06 at 07.08.09", zone, Now)?.Instant);
Assert.AreEqual(Rome(2021, 5, 6, 7, 8, 9), FileNameDates.Find("Screenshot_2021-05-06-07-08-09", zone, Now)?.Instant);
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 7, 8, 9, TimeSpan.Zero), FileNameDates.Find("2021-05-06_07-08-09_UTC", zone, Now)?.Instant, "«_UTC» dice che l'ora è universale.");
var dayOnly = FileNameDates.Find("IMG-20210506-WA0001", zone, Now);
Assert.IsTrue(dayOnly?.DayOnly);
Assert.AreEqual(Rome(2021, 5, 6, 12, 0, 0), dayOnly?.Instant);
Assert.IsNull(FileNameDates.Find("2567890123456789012_123456", zone, Now), "Le cifre di un identificativo non sono una data.");
Assert.IsNull(FileNameDates.Find("IMG_20211306_070809", zone, Now), "Mese 13: non è una data.");
Assert.IsNull(FileNameDates.Find("IMG_20300506_070809", zone, Now), "Una data nel futuro non è plausibile.");
Assert.IsNull(FileNameDates.Find("vacanze al mare", zone, Now));
}
private static byte[] Ftyp(string major, params string[] compatible)
{
var body = Encoding.ASCII.GetBytes(major).Concat(new byte[] { 0, 0, 0, 0 }).Concat(compatible.SelectMany(Encoding.ASCII.GetBytes)).ToArray();
var box = new byte[8 + body.Length + 16];
System.Buffers.Binary.BinaryPrimitives.WriteUInt32BigEndian(box, (uint)(8 + body.Length));
"ftyp"u8.CopyTo(box.AsSpan(4));
body.CopyTo(box.AsSpan(8));
return box;
}
}
+166
View File
@@ -0,0 +1,166 @@
using Febe.Core.Domain;
using Febe.Core.Import;
using Febe.Core.Library;
using Febe.Tests.Support;
namespace Febe.Tests.Import;
[TestClass]
public sealed class RecognizerTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 13, 8, 0, 0, TimeSpan.Zero);
private static ImportRecognizers Recognizers(bool stogram = false) => ImportRecognizers.Create(TestZones.Rome, () => Now, stogram);
[TestMethod]
public void AFolderOfAccountsAndAFolderThatIsOneAccountAreTold()
{
using var temp = new TempFolder("layout");
var many = temp.Combine("archivio");
Directory.CreateDirectory(Path.Combine(many, "marta.demo", "storie"));
Directory.CreateDirectory(Path.Combine(many, "Foto sparse"));
var layout = SourceLayout.Inspect(many);
Assert.IsFalse(layout.RootIsAccount);
Assert.AreEqual(("marta.demo", "storie/2021/a.jpg"), layout.Split("marta.demo/storie/2021/a.jpg"));
Assert.AreEqual((string.Empty, "sciolto.jpg"), layout.Split("sciolto.jpg"));
Assert.IsNull(layout.AccountFolderName(string.Empty), "I file sciolti in cima non hanno un account probabile.");
var one = temp.Combine("luca.viaggi.demo");
Directory.CreateDirectory(Path.Combine(one, "post", "2024"));
Directory.CreateDirectory(Path.Combine(one, "Stories"));
Directory.CreateDirectory(Path.Combine(one, "In evidenza"));
var single = SourceLayout.Inspect(one);
Assert.IsTrue(single.RootIsAccount, "Solo cartelle di tipo: la cartella scelta è un account.");
Assert.AreEqual((string.Empty, "post/2024/a.jpg"), single.Split("post/2024/a.jpg"));
Assert.AreEqual("luca.viaggi.demo", single.AccountFolderName(string.Empty));
Assert.AreEqual("marta.demo", SourceLayout.UsernameFrom("Marta.Demo"));
Assert.AreEqual("marta.demo", SourceLayout.UsernameFrom("@marta.demo"));
Assert.IsNull(SourceLayout.UsernameFrom("Foto sparse"), "Uno spazio non sta in un nome utente.");
Assert.IsNull(SourceLayout.UsernameFrom("2019"), "Un anno non è un account.");
Assert.IsNull(SourceLayout.UsernameFrom("storie"));
Assert.IsNull(SourceLayout.UsernameFrom(".nascosta"));
Assert.IsNull(SourceLayout.UsernameFrom("un.nome.decisamente.troppo.lungo.per.instagram"));
}
[TestMethod]
public void TheGenericRecognizerReadsAccountKindAndDate()
{
var layout = SourceLayout.Create("/importa/archivio", rootIsAccount: false, ["marta.demo"]);
var recognizers = Recognizers();
var story = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/Storie/IMG_20210506_070809.jpg"));
Assert.AreEqual("marta.demo", story.AccountUsername);
Assert.AreEqual(EntryKind.Story, story.Kind);
Assert.AreEqual(ImportDateSource.FileName, story.DateSource);
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 5, 8, 9, TimeSpan.Zero), story.Date);
Assert.IsNull(story.InstagramId, "Il riconoscitore generico non indovina identificativi.");
var highlight = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/highlights/Estate 2025/foto.jpg"));
Assert.AreEqual(EntryKind.Highlight, highlight.Kind);
Assert.AreEqual("Estate 2025", highlight.HighlightTitle);
var tagged = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/tagged/foto (2).jpg"));
Assert.AreEqual(EntryKind.Tagged, tagged.Kind);
Assert.IsNull(tagged.Date);
}
[TestMethod]
public void FebeNamesGiveDateCodeAndPosition()
{
var layout = SourceLayout.Create("/importa/marta.demo", rootIsAccount: true);
var recognizers = Recognizers();
var post = recognizers.Recognize(new ImportFileContext(layout, "post/2026/2026-10-10_18-22-05_DBx3kQ2_2.jpg"));
Assert.AreEqual("febe", post.Recognizer);
Assert.AreEqual("DBx3kQ2", post.Code);
Assert.IsNull(post.InstagramId);
Assert.AreEqual(2, post.Position);
Assert.AreEqual(EntryKind.Post, post.Kind);
Assert.AreEqual(new DateTimeOffset(2026, 10, 10, 16, 22, 5, TimeSpan.Zero), post.Date, "Le ore nei nomi sono quelle di Alberto.");
Assert.AreEqual("marta.demo", post.AccountUsername);
var story = recognizers.Recognize(new ImportFileContext(layout, "storie/2026/2026-10-13_09-41-07_3742118_1.mp4"));
Assert.AreEqual("3742118", story.InstagramId, "Per storie ed evidenza il codice è l'identificativo.");
Assert.AreEqual(EntryKind.Story, story.Kind);
var highlight = recognizers.Recognize(new ImportFileContext(layout, "evidenza/Estate 2025/2025-08-02_10-11-12_3391207_1 (2).jpg"));
Assert.AreEqual(EntryKind.Highlight, highlight.Kind);
Assert.AreEqual("Estate 2025", highlight.HighlightTitle);
Assert.AreEqual("3391207", highlight.InstagramId);
var instaloader = recognizers.Recognize(new ImportFileContext(layout, "2021-05-06_07-08-09_UTC_1.jpg"));
Assert.IsNull(instaloader.Code, "«UTC» non è un codice.");
Assert.AreEqual(new DateTimeOffset(2021, 5, 6, 7, 8, 9, TimeSpan.Zero), instaloader.Date);
}
[TestMethod]
public async Task FebeJournalGivesIdentifiersCaptionsAndExactTimes()
{
using var temp = new TempFolder("febe-sorgente");
var account = temp.Combine("marta.demo");
Directory.CreateDirectory(Path.Combine(account, "post", "2025"));
await AccountJournal.AppendAsync(account, new JournalLine
{
Op = JournalOps.Save,
At = Now,
Account = new JournalAccount("4242", "marta.demo"),
Entry = new JournalEntry { Kind = "post", Id = "3100000000000000001", Code = "CxYz123", PublishedAt = new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), Caption = "Una didascalia" },
Files =
[
new JournalFile { N = 1, Type = "photo", Path = "post/2025/scelto-da-me.jpg", Id = "3100000000000000002" },
new JournalFile { N = 2, Type = "photo", Path = "post/2025/altro.jpg" },
],
});
var layout = SourceLayout.Create(temp.Path, rootIsAccount: false, ["marta.demo"]);
var recognizers = Recognizers();
await recognizers.PrepareAsync(layout, CancellationToken.None);
var hints = recognizers.Recognize(new ImportFileContext(layout, "marta.demo/post/2025/scelto-da-me.jpg"));
Assert.AreEqual(ImportDateSource.Journal, hints.DateSource);
Assert.AreEqual(new DateTimeOffset(2025, 3, 1, 9, 30, 15, 250, TimeSpan.Zero), hints.Date);
Assert.AreEqual("3100000000000000001", hints.InstagramId);
Assert.AreEqual("3100000000000000002", hints.MediaInstagramId);
Assert.AreEqual("CxYz123", hints.Code);
Assert.AreEqual(1, hints.Position);
Assert.AreEqual("Una didascalia", hints.Caption);
Assert.AreEqual("4242", hints.AccountInstagramId);
Assert.IsFalse(hints.ToString().Contains("didascalia", StringComparison.Ordinal), "La didascalia non finisce mai in ToString.");
Assert.AreEqual(2, recognizers.Recognize(new ImportFileContext(layout, "marta.demo/post/2025/altro.jpg")).Position);
}
[TestMethod]
public void TheStogramHypothesisReadsSyntheticNamesOnlyWhenAskedFor()
{
var layout = SourceLayout.Create("/importa/4K Stogram", rootIsAccount: false, ["vecchio.profilo.demo"]);
const string name = "vecchio.profilo.demo/stories/2019-06-01 21.15.30 2071234567890123456_1234567890.jpg";
var off = Recognizers().Recognize(new ImportFileContext(layout, name));
Assert.IsNull(off.InstagramId, "Spenta per impostazione predefinita: nessun identificativo dall'ipotesi.");
Assert.IsFalse(off.Hypothesis);
Assert.AreEqual(new DateTimeOffset(2019, 6, 1, 19, 15, 30, TimeSpan.Zero), off.Date, "La data la legge comunque il riconoscitore generico.");
var on = Recognizers(stogram: true).Recognize(new ImportFileContext(layout, name));
Assert.IsTrue(on.Hypothesis);
Assert.AreEqual("4k-stogram-ipotesi", on.Recognizer);
Assert.AreEqual("2071234567890123456", on.InstagramId);
Assert.AreEqual("1234567890", on.AccountInstagramId);
Assert.AreEqual(EntryKind.Story, on.Kind);
Assert.AreEqual("vecchio.profilo.demo", on.AccountUsername);
var copy = Recognizers(stogram: true).Recognize(new ImportFileContext(layout, "vecchio.profilo.demo/2019-06-01 21.15.30 2071234567890123456_1234567890 (2).jpg"));
Assert.AreEqual("2071234567890123456", copy.InstagramId);
Assert.IsNull(Recognizers(stogram: true).Recognize(new ImportFileContext(layout, "vecchio.profilo.demo/IMG_0001.jpg")).InstagramId);
}
[TestMethod]
public void A4KStogramFolderIsRecognizedWithoutOpeningItsDatabase()
{
using var temp = new TempFolder("stogram");
Assert.IsFalse(StogramHypothesisRecognizer.LooksLikeStogramFolder(temp.Path));
File.WriteAllText(temp.Combine("stogram.sqlite"), "non è un database: Febe non lo apre");
Assert.IsTrue(StogramHypothesisRecognizer.LooksLikeStogramFolder(temp.Path));
Assert.IsTrue(ImportSources.IsIgnoredFile("stogram.sqlite"), "I database di 4K Stogram non si importano né si leggono.");
}
}
@@ -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);
}
}