E5: «Riconosci le copie già presenti» per tutta una cartella
«Riconosci» parte da una cartella (ExportService.RecognizeAsync) come lavoro di Alberto: sposta una copia automatica, non gira con importazione, ricostruzione o «Copia in…», aspetta fuori dalle sessioni ed è riprendibile. Registra un lavoro di tipo «Riconosci» su ogni file dovuto alla cartella che non è «Copiato» e sui fotogrammi che hanno già una riga lì. Per ogni file la copia guarda il percorso dello schema e «nome (2)» … «nome (50)», nella forma chiesta adesso e come originale, ciascuna con la sua identità; prima i percorsi, poi lunghezza e SHA-256, con la conversione rifatta solo se un file c'è. Un file uguale diventa «Adottato»: la riga «Non riuscito» diventa la copia, l'orfana si ricollega, la «Superato» con gli stessi byte torna «Copiato». Un «Tolto» resta «Tolto» anche se il file è tornato identico (risposta 51 b). L'adozione per percorso è estratta da WriteAsync (TryAdoptAsync) e serve a entrambi. Non scrive né toglie file, neppure i .part di altri; una cartella che non risponde mette in pausa senza segnare nulla; scrive solo l'evento esportazione-riconosci. Il resoconto conta «Non c'è nella cartella» e «Nel percorso c'è un altro file», e solo il secondo è un problema. Un «Riconosci» in pausa non chiede spazio libero. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0f69a01f88
commit
0ff4a0d632
9 files changed
+1370
-63
No files matched your search
@@ -0,0 +1,654 @@
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Codecs.Containers;
|
||||
using Febe.Tests.Export.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Export;
|
||||
|
||||
/// <summary>
|
||||
/// «Riconosci le copie già presenti» (tappa E5, D13; answer 51 of 4 December 2026) on real folders: a file already in the
|
||||
/// destination at the path of the naming scheme or at «nome (2)», in the form asked now or as the original, is recorded
|
||||
/// «Adottato» by length and SHA-256, never by size alone; a «Non riuscito» row becomes the copy, an orphan row is linked
|
||||
/// again, a «Superato» row of these very bytes is revived; a frame already recorded is recognised; a «Tolto» stays
|
||||
/// «Tolto» even when its file came back identical; nothing is written or deleted; an unreachable folder pauses and marks
|
||||
/// nothing; the run is resumable, Alberto's work (it displaces an automatic copy), and writes only its own event.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ExportRecognizeTests
|
||||
{
|
||||
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(30);
|
||||
|
||||
public TestContext TestContext { get; set; } = null!;
|
||||
|
||||
[TestMethod]
|
||||
public async Task AByteCopyAtThePlannedPathIsAdopted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r01", 1);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var copy = PutCopy(bed, bed.Marta, media);
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.AreEqual((ExportRunKind.Recognize, ExportRunOrigin.Manual, ExportRunState.Completed), (run.Kind, run.Origin, run.State));
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, "marta.demo/" + media.RelativePath), (item.State, item.RelativePath));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
Assert.AreEqual(
|
||||
(ExportCopyState.Copied, ExportCopyOrigin.Adopted, ExportVariant.Whole, ExportFormat.Original, media.Sha256, media.Sha256, bed.Marta.Id),
|
||||
(row.State, row.Origin, row.Variant, row.Format, row.SourceSha256, row.CopySha256, row.AccountId));
|
||||
Assert.AreEqual(new FileInfo(copy).Length, row.Bytes);
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "recognised, not written");
|
||||
|
||||
// Now it is «Copiato»: «Copia in…» has nothing to write.
|
||||
Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).Files);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ANumberedSiblingIsAdopted()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r02", 2);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var planned = "marta.demo/" + media.RelativePath;
|
||||
|
||||
// The planned name holds another file; ours went to «(3)» after «(2)» was taken too.
|
||||
var taken = Full(bed, planned);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(taken)!);
|
||||
await File.WriteAllBytesAsync(taken, [1, 2, 3], ct);
|
||||
await File.WriteAllBytesAsync(Full(bed, ExportPaths.NumberedName(bed.Usb, planned, 2)), [4, 5, 6], ct);
|
||||
var third = ExportPaths.NumberedName(bed.Usb, planned, 3);
|
||||
File.Copy(bed.LibraryFile(bed.Marta, media), Full(bed, third));
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, third), (item.State, item.RelativePath));
|
||||
Assert.AreEqual(third, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.RelativePath);
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written or renamed");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AConvertedCopyIsRecognisedByConvertingAgain()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r03", 3);
|
||||
var media = post.Media[0];
|
||||
var usb = await GeneralInPngAsync(bed, ct);
|
||||
|
||||
// A PNG copy made earlier, at the name the scheme gives a converted file.
|
||||
var path = "marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".png");
|
||||
string converted;
|
||||
using (var conversion = await MediaConverter.PrepareAsync(() => File.OpenRead(bed.LibraryFile(bed.Marta, media)), media.RelativePath!, media.Kind, ExportFormat.Png, media.Sha256!, new ConversionThrottle(), ct))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Full(bed, path))!);
|
||||
await using (var file = File.Create(Full(bed, path)))
|
||||
{
|
||||
await conversion.Produce(file, ct);
|
||||
}
|
||||
|
||||
converted = conversion.Sha256!;
|
||||
}
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, ExportVariant.Converted, ExportFormat.Png, path), (item.State, item.Variant, item.Format, item.RelativePath));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, converted, ExportCopyOrigin.Adopted), (row.Variant, row.Format, row.CopySha256, row.Origin));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOriginalCopyIsRecordedAsWholeOriginalWhenTheDestinationNowConverts()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r04", 4);
|
||||
var media = post.Media[0];
|
||||
var usb = await GeneralInPngAsync(bed, ct);
|
||||
PutCopy(bed, bed.Marta, media); // copied as it was, before the folder asked PNG
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, ExportVariant.Converted, ExportFormat.Png), (item.State, item.Variant, item.Format), "the item keeps the form asked");
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (row.Variant, row.Format, row.CopySha256), "the bytes say Whole/Original");
|
||||
Assert.AreEqual("marta.demo/" + media.RelativePath, row.RelativePath);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADifferentFileAtThePathIsNotAdopted_NoteDifferent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r05", 5);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var copy = PutCopy(bed, bed.Marta, media);
|
||||
var bytes = await File.ReadAllBytesAsync(copy, ct);
|
||||
bytes[^3] ^= 0x01; // same size, other bytes
|
||||
await File.WriteAllBytesAsync(copy, bytes, ct);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Different, (long?)null), (item.State, item.Note, item.CopyId));
|
||||
Assert.AreEqual("Nel percorso c'è un altro file", ExportText.Note(item.Note));
|
||||
Assert.HasCount(0, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NothingThereGivesNotFoundWithoutConverting()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var counting = new CountingExportFileSystem();
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = counting });
|
||||
var photo = await bed.PostAsync(bed.Marta, "r06", 6);
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r07", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]);
|
||||
var usb = await GeneralInPngAsync(bed, ct);
|
||||
counting.Reads = 0;
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.HasCount(2, items);
|
||||
Assert.IsTrue(items.All(i => i.State == ExportItemState.Skipped && i.Note == ExportText.Notes.NotFound), string.Join(", ", items.Select(i => $"{i.State} {i.Note}")));
|
||||
Assert.AreEqual(0, counting.Reads, "no file read, hashed or converted when nothing is there");
|
||||
Assert.AreEqual(ExportVariant.Converted, items.Single(i => i.MediaId == photo.Media[0].Id).Variant);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognitionNeverWritesOrDeletesAFile()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r08", 7, 8, 9);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
var different = PutCopy(bed, bed.Marta, post.Media[1]);
|
||||
await File.WriteAllBytesAsync(different, [9, 9, 9], ct);
|
||||
|
||||
// A frame whose row says «Superato»: its item gets the folder of the row (where a copy job cleans its .part).
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r08v", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")])).Media[0];
|
||||
var frame = await FrameAsync(bed, video, TimeSpan.Zero, ct);
|
||||
await bed.Db.Exports.UpdateCopyAsync(frame with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(778), StateChangedAt = bed.Clock.Now }, ct);
|
||||
|
||||
// Temporary files left by someone in the items' folders: a copy job cleans its own, «Riconosci» touches nothing.
|
||||
var strays = new[] { different, Full(bed, frame.RelativePath!) }
|
||||
.Select(f => Path.Combine(Path.GetDirectoryName(f)!, SafeFileWriter.TempPrefix + "stray.part"))
|
||||
.ToList();
|
||||
foreach (var stray in strays)
|
||||
{
|
||||
await File.WriteAllBytesAsync(stray, [1], ct);
|
||||
}
|
||||
|
||||
File.SetLastWriteTimeUtc(different, new DateTime(2021, 3, 4, 5, 6, 7, DateTimeKind.Utc));
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
var times = Times(bed.Usb);
|
||||
var library = Fingerprint.Of(bed.Library.Layout.Root, "febe.db");
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.AreEqual(ExportItemState.Adopted, items.Single(i => i.Variant == ExportVariant.Frame).State, "the frame revived");
|
||||
var states = items.Where(i => i.Variant != ExportVariant.Frame).Select(i => i.State).Order().ToList();
|
||||
CollectionAssert.AreEqual(new[] { ExportItemState.Adopted, ExportItemState.Skipped, ExportItemState.Skipped, ExportItemState.Skipped }, states);
|
||||
Assert.IsTrue(strays.All(File.Exists));
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "the destination");
|
||||
CollectionAssert.AreEqual(times, Times(bed.Usb), "names, lengths and times");
|
||||
Fingerprint.AreEqual(library, Fingerprint.Of(bed.Library.Layout.Root, "febe.db"), "the library");
|
||||
}
|
||||
|
||||
/// <summary>Answer 51: a «Tolto» stays «Tolto» even when its file came back identical; only «Copia di nuovo» copies it.</summary>
|
||||
[TestMethod]
|
||||
public async Task ARemovedCopyWhoseFileCameBackIdenticalStaysRemoved()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r09", 10);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
var file = bed.GeneralCopy(bed.Marta, media);
|
||||
File.Move(file, file + ".away");
|
||||
await bed.Service.CheckCopiesAsync(usb.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(copyId, ct))!.State);
|
||||
File.Move(file + ".away", file); // back, byte for byte
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.HasCount(0, await bed.ItemsAsync(run.Id, ct), "not even looked for");
|
||||
var rows = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||
Assert.AreEqual((copyId, ExportCopyState.Removed), (rows.Single().Id, rows.Single().State));
|
||||
|
||||
// A Recognize run planned before the «Tolto» (resumed later) leaves it «Tolto» too.
|
||||
var planned = await bed.Db.Exports.CreateRunAsync(new ExportRun { DestinationId = usb.Id, Kind = ExportRunKind.Recognize, State = ExportRunState.Interrupted, StartedAt = bed.Clock.Now }, ct);
|
||||
await bed.Db.Exports.AddItemsAsync([new ExportItem { RunId = planned.Id, MediaId = media.Id, AccountId = bed.Marta.Id, SourceSha256 = media.Sha256 }], ct);
|
||||
await bed.Service.ResumeAsync([planned.Id], ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
var item = (await bed.ItemsAsync(planned.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Removed, (long?)copyId), (item.State, item.Note, item.CopyId));
|
||||
rows = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||
Assert.AreEqual((copyId, ExportCopyState.Removed), (rows.Single().Id, rows.Single().State));
|
||||
|
||||
// «Copia di nuovo» still copies it.
|
||||
Assert.AreEqual(1, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id), CopyAgain: true), ct)).Files);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailedIdentityBecomesCopiedNotDuplicated()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r10", 11);
|
||||
var media = post.Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var failed = await bed.Db.Exports.AddCopyAsync(
|
||||
new ExportCopy
|
||||
{
|
||||
DestinationId = usb.Id,
|
||||
AccountId = bed.Marta.Id,
|
||||
MediaId = media.Id,
|
||||
SourceSha256 = media.Sha256!,
|
||||
Variant = ExportVariant.Whole,
|
||||
State = ExportCopyState.Failed,
|
||||
CopiedAt = bed.Clock.Now,
|
||||
LastError = "Errore di lettura o scrittura",
|
||||
},
|
||||
ct);
|
||||
PutCopy(bed, bed.Marta, media);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)failed.Id), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
|
||||
Assert.AreEqual((failed.Id, ExportCopyState.Copied, ExportCopyOrigin.Adopted, (string?)null), (row.Id, row.State, row.Origin, row.LastError));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOrphanRowIsRelinked()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.PostAsync(bed.Marta, "r11", 12);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
|
||||
// marta.demo is removed (her copy stays without an account); an account with that name but another id comes back
|
||||
// with the same post: the copy does not come back by itself.
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
|
||||
var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
|
||||
await bed.PostAsync(again, "r11", 12);
|
||||
Assert.IsNull((await bed.Db.Exports.GetCopyAsync(copyId, ct))!.AccountId);
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)copyId), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
Assert.AreEqual((again.Id, ExportCopyState.Copied), (row.AccountId, row.State));
|
||||
Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASupersededRowWithMatchingBytesIsRevived()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r12", 13);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyId = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
|
||||
|
||||
// Recorded «Superato» although the library still has (again) these very bytes: «Superato» is not «Tolto».
|
||||
var copy = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
await bed.Db.Exports.UpdateCopyAsync(copy with { State = ExportCopyState.Superseded, SupersededBySha256 = Make.Sha(777), StateChangedAt = bed.Clock.Now }, ct);
|
||||
Assert.AreEqual(0, (await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct)).Files, "a copy job leaves it");
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)copyId), (item.State, item.CopyId));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(copyId, ct))!;
|
||||
Assert.AreEqual((ExportCopyState.Copied, (string?)null, post.Media[0].Id), (row.State, row.SupersededBySha256, row.MediaId));
|
||||
Assert.HasCount(1, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFrameWithAFailedRowIsRecognised_RemovedFramesStayRemoved_FramesWithoutRowsAreNotCandidates()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r13", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")])).Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var at0 = await FrameAsync(bed, video, TimeSpan.Zero, ct);
|
||||
var at1 = await FrameAsync(bed, video, TimeSpan.FromMilliseconds(100), ct);
|
||||
var at2 = await FrameAsync(bed, video, TimeSpan.FromMilliseconds(200), ct);
|
||||
|
||||
// At 0 s the copy said «Non riuscito» (the file was written all the same, by an earlier Febe or by hand); at 0,1 s
|
||||
// the frame is «Tolto» although its file is there; at 0,2 s the frame was never recorded (its row is gone).
|
||||
await bed.Db.Exports.UpdateCopyAsync(at0 with { State = ExportCopyState.Failed, RelativePath = null, Bytes = null, CopySha256 = null, LastError = "x" }, ct);
|
||||
await bed.Db.Exports.UpdateCopyAsync(at1 with { State = ExportCopyState.Removed, StateChangedAt = bed.Clock.Now }, ct);
|
||||
await DeleteCopyAsync(bed, at2.Id, ct);
|
||||
var files = Fingerprint.Of(bed.Usb);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
var frame = items.Single(i => i.Variant == ExportVariant.Frame);
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)at0.Id, at0.FrameAt), (frame.State, frame.CopyId, frame.FrameAt));
|
||||
var row = (await bed.Db.Exports.GetCopyAsync(at0.Id, ct))!;
|
||||
Assert.AreEqual((ExportCopyState.Copied, at0.RelativePath, at0.CopySha256), (row.State, row.RelativePath, row.CopySha256));
|
||||
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(at1.Id, ct))!.State, "a «Tolto» frame stays «Tolto»");
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotFound), (items.Single(i => i.Variant != ExportVariant.Frame).State, items.Single(i => i.Variant != ExportVariant.Frame).Note), "the video itself");
|
||||
Assert.HasCount(2, items, "no item for the frame never recorded, nor for the «Tolto» one");
|
||||
Assert.HasCount(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Where(c => c.State != ExportCopyState.Failed));
|
||||
Fingerprint.AreEqual(files, Fingerprint.Of(bed.Usb), "nothing written");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnOrphanFrameIsRelinkedByTheBytesItsRowRecorded()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
|
||||
var video = (await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "r14", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")])).Media[0];
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var frame = await FrameAsync(bed, video, TimeSpan.Zero, ct);
|
||||
await bed.Db.Accounts.DeleteAsync(bed.Marta.Id, ct);
|
||||
Directory.Delete(bed.Library.Layout.AccountFolder(bed.Marta), recursive: true);
|
||||
var again = await bed.Db.Accounts.AddAsync(Make.Account("marta.demo", "999"), ct);
|
||||
await bed.Library.SaveAsync(again, Make.Entry(again.Id, "r14", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var item = (await bed.ItemsAsync(run.Id, ct)).Single(i => i.Variant == ExportVariant.Frame);
|
||||
Assert.AreEqual((ExportItemState.Adopted, (long?)frame.Id), (item.State, item.CopyId));
|
||||
Assert.AreEqual((again.Id, ExportCopyState.Copied), ((await bed.Db.Exports.GetCopyAsync(frame.Id, ct))!.AccountId, (await bed.Db.Exports.GetCopyAsync(frame.Id, ct))!.State));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OneOnlyIsRespected()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
await bed.SetSamePostAsync(SamePostCopies.OneOnly, ct);
|
||||
var marta = await bed.PostAsync(bed.Marta, "r15", 14);
|
||||
var luca = await bed.PostAsync(bed.Luca, "r15", 14); // the same bytes for another account
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, marta.Media[0]);
|
||||
var lucasCopy = PutCopy(bed, bed.Luca, luca.Media[0]); // an identical file at luca's path too
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
Assert.AreEqual(ExportItemState.Adopted, items.Single(i => i.AccountId == bed.Marta.Id).State);
|
||||
var rows = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
|
||||
Assert.AreEqual(bed.Marta.Id, rows.Single().AccountId, "one copy only: luca's file is not recorded");
|
||||
Assert.IsTrue(File.Exists(lucasCopy));
|
||||
|
||||
// Planned before marta's copy was recognised (two pages, or a resume): the item ends «già copiato per un altro account».
|
||||
var lucasItem = items.SingleOrDefault(i => i.AccountId == bed.Luca.Id);
|
||||
Assert.IsTrue(lucasItem is null || (lucasItem.State == ExportItemState.AlreadyCopied && lucasItem.Note == ExportText.Notes.CopiedForAnotherAccount), $"{lucasItem?.State} {lucasItem?.Note}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUnreachableRootPausesAndMarksNothing()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r16", 15, 16);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
Directory.Move(bed.Usb, bed.Usb + "-staccata");
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
Assert.AreEqual(ExportRunState.Paused, run.State);
|
||||
Assert.IsTrue((await bed.ItemsAsync(run.Id, ct)).All(i => i.State == ExportItemState.Pending), "nothing marked «Non c'è»");
|
||||
Assert.IsNotNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
|
||||
Assert.HasCount(0, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
|
||||
Assert.IsFalse(Directory.Exists(bed.Usb), "the root is never created");
|
||||
|
||||
// Back: «Riprova» resumes it, and it ends.
|
||||
Directory.Move(bed.Usb + "-staccata", bed.Usb);
|
||||
var retry = await bed.Service.RetryDestinationAsync(usb.Id, ct);
|
||||
Assert.AreEqual(run.Id, retry.Resumed.Single().Id);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
var states = (await bed.ItemsAsync(run.Id, ct)).ToDictionary(i => i.MediaId!.Value, i => (i.State, i.Note));
|
||||
Assert.AreEqual((ExportItemState.Adopted, (string?)null), states[post.Media[0].Id]);
|
||||
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.NotFound), states[post.Media[1].Id]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARecognizeRunIsResumable()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r17", 17, 18);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
PutCopy(bed, bed.Marta, post.Media[1]);
|
||||
|
||||
// Febe stopped in the middle of a Recognize run: the first file was recognised, the second still waits.
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
var items = await bed.ItemsAsync(run.Id, ct);
|
||||
var second = items.Single(i => i.MediaId == post.Media[1].Id);
|
||||
var copyId = second.CopyId!.Value;
|
||||
await bed.Db.Exports.UpdateItemsAsync([second with { State = ExportItemState.Pending, CopyId = null, RelativePath = null }], ct);
|
||||
await DeleteCopyAsync(bed, copyId, ct);
|
||||
await bed.Db.Exports.UpdateRunAsync(run with { State = ExportRunState.Running, CompletedAt = null }, ct);
|
||||
|
||||
Assert.AreEqual(1, await bed.Service.RecoverAsync(ct));
|
||||
Assert.AreEqual(ExportRunState.Interrupted, (await bed.RunAsync(run.Id, ct)).State);
|
||||
await bed.Service.ResumeAsync(null, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
Assert.IsTrue((await bed.ItemsAsync(run.Id, ct)).All(i => i.State == ExportItemState.Adopted));
|
||||
Assert.HasCount(2, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Where(c => c.State == ExportCopyState.Copied));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARecognizeRunWritesOnlyItsOwnEvent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r18", 19, 20);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
|
||||
await RecognizeAsync(bed, usb, ct);
|
||||
|
||||
var events = await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct);
|
||||
Assert.IsFalse(events.Any(e => e.Code == "esportazione-completata"));
|
||||
var recognized = events.Single(e => e.Code == ExportText.RecognizeEventCode);
|
||||
Assert.AreEqual(("Riconosciuta 1 copia già presente in Disco USB.", EventSeverity.Success), (recognized.Message, recognized.Severity));
|
||||
|
||||
// Nothing more to recognise: information, not success.
|
||||
await RecognizeAsync(bed, usb, ct);
|
||||
var second = (await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Where(e => e.Code == ExportText.RecognizeEventCode).OrderBy(e => e.Id).Last();
|
||||
Assert.AreEqual(("Nessuna copia già presente da riconoscere in Disco USB.", EventSeverity.Info), (second.Message, second.Severity));
|
||||
Assert.IsFalse((await bed.Db.Events.ListAsync(new() { Limit = 50 }, ct)).Any(e => e.Code == "esportazione-completata"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognizeReportCountsNotFoundAndDifferentAndListsOnlyDifferent()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
await using var bed = await ExportTestBed.CreateAsync();
|
||||
var post = await bed.PostAsync(bed.Marta, "r19", 21, 22, 23, 24);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, post.Media[0]);
|
||||
await File.WriteAllBytesAsync(PutCopy(bed, bed.Marta, post.Media[1]), [1, 2], ct);
|
||||
|
||||
var run = await RecognizeAsync(bed, usb, ct);
|
||||
var report = await bed.Service.Reports.BuildAsync(run.Id, ct);
|
||||
|
||||
Assert.AreEqual((2, 1), (report.NotFound, report.Different));
|
||||
Assert.AreEqual(1, report.ByState[ExportItemState.Adopted]);
|
||||
var problem = report.Problems.Single();
|
||||
Assert.AreEqual(("Nel percorso c'è un altro file", "marta.demo/" + post.Media[1].RelativePath), (problem.Text, problem.RelativePath));
|
||||
|
||||
// In a copy job nothing changes: a skipped file with a note is a problem line, and nothing is counted by note.
|
||||
var copy = await bed.CopyAccountAsync(bed.Marta, ct: ct);
|
||||
var copyReport = await bed.Service.Reports.BuildAsync(copy.Runs.Single().Id, ct);
|
||||
Assert.AreEqual((0, 0), (copyReport.NotFound, copyReport.Different));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognitionPreemptsAnAutomaticJob()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_2.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||
var post = await bed.PostAsync(bed.Luca, "r20", 25, 26, 27);
|
||||
var other = await bed.PostAsync(bed.Marta, "r21", 28);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
PutCopy(bed, bed.Marta, other.Media[0]);
|
||||
var spec = new DestinationSpec(usb.Scope, usb.AccountId, usb.RootPath, usb.Label, usb.ContentTypes, usb.NamingScheme, usb.HighlightNamingScheme, usb.ProfileNamingScheme, Automatic: true, OnlyNew: false);
|
||||
var auto = (await bed.Service.Destinations.UpdateAsync(usb.Id, spec, ct)).Destination;
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, false, ct);
|
||||
|
||||
var start = await bed.Service.TryStartAutomaticAsync(new ExportSelection.Automatic([new ExportSelection.AutomaticScope(auto.Id, auto.AutomaticSince)], [], true), ct);
|
||||
Assert.AreEqual(AutoExportStartOutcome.Started, start.Outcome);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
Assert.IsTrue(bed.Service.AutomaticRunning);
|
||||
|
||||
await bed.Service.Destinations.SetAccountEnabledAsync(bed.Marta.Id, true, ct);
|
||||
var run = await bed.Service.RecognizeAsync(usb.Id, ct);
|
||||
Assert.AreEqual((ExportRunState.Interrupted, (string?)null), ((await bed.RunAsync(start.Runs.Single().Id, ct)).State, (await bed.RunAsync(start.Runs.Single().Id, ct)).LastError), "displaced, not failed");
|
||||
Assert.IsFalse(bed.Service.AutomaticRunning);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
|
||||
Assert.AreEqual(ExportItemState.Adopted, (await bed.ItemsAsync(run.Id, ct)).Single(i => i.MediaId == other.Media[0].Id).State);
|
||||
held.Release();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task RecognizeRefusesARetiredOrUnknownDestinationAndWhileAJobRuns()
|
||||
{
|
||||
var ct = TestContext.CancellationToken;
|
||||
var held = new HeldExportFileSystem(p => p.EndsWith("_1.jpg", StringComparison.Ordinal));
|
||||
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = held });
|
||||
await bed.PostAsync(bed.Marta, "r22", 29);
|
||||
var usb = await bed.GeneralAsync(ct: ct);
|
||||
var own = await bed.OwnAsync(bed.Luca, "luca-own", ct: ct);
|
||||
await bed.Service.Destinations.RetireAsync(own.Id, ct);
|
||||
|
||||
await Assert.ThrowsExactlyAsync<KeyNotFoundException>(() => bed.Service.RecognizeAsync(9999, ct));
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.RecognizeAsync(own.Id, ct));
|
||||
|
||||
// A «Copia in…» of Alberto's runs: «Riconosci» waits for it, it does not displace it.
|
||||
await bed.Service.StartAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
|
||||
await held.Reached.Task.WaitAsync(Patience, ct);
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => bed.Service.RecognizeAsync(usb.Id, ct));
|
||||
held.Release();
|
||||
await bed.Service.WaitAsync(ct);
|
||||
Assert.IsFalse((await bed.Db.Exports.ListRunsAsync(ct)).Any(r => r.Kind == ExportRunKind.Recognize), "a refused start records nothing");
|
||||
}
|
||||
|
||||
// Helpers -------------------------------------------------------------------------------------------------------
|
||||
|
||||
/// <summary>«Riconosci» and waits for its job.</summary>
|
||||
private static async Task<ExportRun> RecognizeAsync(ExportTestBed bed, ExportDestination destination, CancellationToken ct)
|
||||
{
|
||||
var run = await bed.Service.RecognizeAsync(destination.Id, ct);
|
||||
await bed.Service.WaitAsync(ct);
|
||||
return await bed.RunAsync(run.Id, ct);
|
||||
}
|
||||
|
||||
/// <summary>The general folder at <see cref="ExportTestBed.Usb"/> asking PNG for photos.</summary>
|
||||
private static async Task<ExportDestination> GeneralInPngAsync(ExportTestBed bed, CancellationToken ct) =>
|
||||
(await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Png), ct)).Destination;
|
||||
|
||||
/// <summary>A byte copy of the library file at the path of the general folder «Come la libreria» (by hand, or an older Febe).</summary>
|
||||
private static string PutCopy(ExportTestBed bed, Account account, Media media)
|
||||
{
|
||||
var path = bed.GeneralCopy(account, media);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
File.Copy(bed.LibraryFile(account, media), path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>A PNG frame of «Questo istante» written by Febe; its copy row.</summary>
|
||||
private static async Task<ExportCopy> FrameAsync(ExportTestBed bed, Media video, TimeSpan at, CancellationToken ct)
|
||||
{
|
||||
var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: new ExportFramesRequest(FrameMode.At, at, null, null, ExportFormat.Png)), ct);
|
||||
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
|
||||
Assert.AreEqual(ExportItemState.Copied, item.State);
|
||||
return (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
|
||||
}
|
||||
|
||||
/// <summary>A copy row gone from the database (its items keep no link to it).</summary>
|
||||
private static Task DeleteCopyAsync(ExportTestBed bed, long copyId, CancellationToken ct) =>
|
||||
bed.Db.WriteAsync(x => x.Command("DELETE FROM export_copy WHERE id = @id").With("@id", copyId).ExecuteNonQuery(), ct);
|
||||
|
||||
private static string Full(ExportTestBed bed, string relativePath) => Path.Combine(bed.Usb, LibraryLayout.ToPlatform(relativePath));
|
||||
|
||||
/// <summary>Every file of a folder tree with its length and last write time.</summary>
|
||||
private static List<string> Times(string folder) =>
|
||||
[.. Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)
|
||||
.Select(f => $"{Path.GetRelativePath(folder, f)}:{new FileInfo(f).Length}:{File.GetLastWriteTimeUtc(f).Ticks}")
|
||||
.Order(StringComparer.Ordinal)];
|
||||
|
||||
/// <summary>The real file system, counting every read of a file (opened, or hashed).</summary>
|
||||
private sealed class CountingExportFileSystem : IExportFileSystem
|
||||
{
|
||||
private readonly IExportFileSystem _inner = ExportFileSystem.Instance;
|
||||
private int _reads;
|
||||
|
||||
public int Reads
|
||||
{
|
||||
get => Volatile.Read(ref _reads);
|
||||
set => Volatile.Write(ref _reads, value);
|
||||
}
|
||||
|
||||
public Stream OpenRead(string path)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return _inner.OpenRead(path);
|
||||
}
|
||||
|
||||
public Stream OpenRandomAccess(string path)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return _inner.OpenRandomAccess(path);
|
||||
}
|
||||
|
||||
public Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _reads);
|
||||
return _inner.ComputeSha256Async(path, ct);
|
||||
}
|
||||
|
||||
public bool FileExists(string path) => _inner.FileExists(path);
|
||||
|
||||
public long? FileLength(string path) => _inner.FileLength(path);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user