using System.Security.Cryptography;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Export;
using Febe.Core.Library;
using Febe.Core.Library.Conversion;
using Febe.Core.Storage;
using Febe.Tests.Codecs.Containers;
using Febe.Tests.Export.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Export;
///
/// The copy job of tappa E3 on real folders (WP1.7): converted copies, byte copies of the same format, files copied as
/// they are with a note, the format chosen by the request, the destination or the settings (D1), «già copiato» in any
/// form (D3), adoption of a converted file (D10), «Copia di nuovo» of a form (D11), the space of the converted size
/// (D17) and the file time (D18). The media are built by the tests; more frames are in .
///
[TestClass]
public sealed class ExportConversionTests
{
private static readonly byte[] PngSignature = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task APhotoIsConvertedAndThenCountsAsCopiedInAnyForm()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "960", 31);
var media = post.Media[0];
await bed.GeneralAsync(ct: ct);
var start = await bed.CopyAsync(
new ExportJobRequest(new ExportSelection.Media([media.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)), ct);
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportVariant.Converted, ExportFormat.Png), (item.State, item.Variant, item.Format));
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Converted, ExportFormat.Png, media.Sha256), (copy.Variant, copy.Format, copy.SourceSha256));
Assert.AreEqual("marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".png"), copy.RelativePath);
var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!));
var bytes = await File.ReadAllBytesAsync(file, ct);
CollectionAssert.AreEqual(PngSignature, bytes[..8]);
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), copy.CopySha256);
Assert.AreNotEqual(media.Sha256, copy.CopySha256);
Assert.AreEqual(bytes.Length, copy.Bytes);
Assert.IsFalse(File.Exists(bed.GeneralCopy(bed.Marta, media)), "no byte copy next to it");
// «Già copiato» is any form but a frame (D3): a copy of the account in Originale writes nothing more.
var again = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var second = (await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id, ExportText.Notes.CopiedInAnotherFormat), (second.State, second.CopyId, second.Note));
Assert.AreEqual("Già copiato in un altro formato", ExportText.Note(second.Note));
Assert.HasCount(1, Fingerprint.Of(bed.Usb));
}
[TestMethod]
public async Task AFrameIsWrittenWithItsInstantAndLeavesTheVideoToCopy()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var mp4 = TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D"));
var post = await bed.Library.SaveAsync(bed.Marta, Make.Entry(bed.Marta.Id, "961", Make.T0.AddDays(-2)), [new TestFile(Make.Video(1), mp4, ".mp4")]);
var video = post.Media[0];
await bed.GeneralAsync(ct: ct);
var frames = new ExportFramesRequest(FrameMode.At, TimeSpan.Zero, null, null, ExportFormat.Png);
var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: frames), ct);
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual(ExportRunState.Completed, run.State);
var item = (await bed.ItemsAsync(run.Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportVariant.Frame, ExportFormat.Png, (TimeSpan?)TimeSpan.Zero), (item.State, item.Variant, item.Format, item.FrameAt));
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Frame, ExportFormat.Png, video.Sha256), (copy.Variant, copy.Format, copy.SourceSha256));
Assert.IsNotNull(copy.FrameAt);
StringAssert.Contains(copy.RelativePath, "_t0m00s");
StringAssert.EndsWith(copy.RelativePath, ".png");
var bytes = await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct);
CollectionAssert.AreEqual(PngSignature, bytes[..8]);
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(bytes)), copy.CopySha256);
// A frame never makes the file copied (D4): the mark says so, and «Copia in…» copies the video itself.
Assert.AreEqual(ExportMark.FrameOnly, (await bed.Db.Exports.GetFileMarksAsync([video.Id], ct))[video.Id]);
var whole = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var copied = (await bed.ItemsAsync(whole.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportVariant.Whole), (copied.State, copied.Variant));
Assert.AreEqual(ExportMark.Copied, (await bed.Db.Exports.GetFileMarksAsync([video.Id], ct))[video.Id]);
// The same instant asked again is «Già copiato» (its exact identity, D12).
var repeat = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([video.Id]), Frames: frames), ct);
var same = (await bed.ItemsAsync(repeat.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.AlreadyCopied, copy.Id), (same.State, same.CopyId));
Assert.HasCount(2, Fingerprint.Of(bed.Usb));
}
[TestMethod]
public async Task JpgToJpgIsAByteCopyAndTheLibraryIsUntouched()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await FormatsAsync(bed, ExportFormat.Jpg, ct);
var post = await bed.PostAsync(bed.Marta, "962", 33);
var media = post.Media[0];
await bed.GeneralAsync(ct: ct);
var library = Fingerprint.Of(bed.Temp.Combine("libreria"));
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.AreEqual((1, 0, false), (start.Plan.Files, start.Plan.Converted, start.Plan.Lossy), "a JPEG to JPG is not a conversion, nor «con perdita»");
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, (string?)null), (item.State, item.Note));
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (copy.Variant, copy.Format, copy.CopySha256));
CollectionAssert.AreEqual(await File.ReadAllBytesAsync(bed.LibraryFile(bed.Marta, media), ct), await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, media), ct));
Fingerprint.AreEqual(library, Fingerprint.Of(bed.Temp.Combine("libreria")), "the library is never touched");
}
[TestMethod]
public async Task APngIsConvertedToTheDestinationFormatWithItsNoteAndTime()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await FormatsAsync(bed, ExportFormat.Png, ct); // the destination's format wins over this one
using var picture = Imaging.TestImages.Gradient(40, 30, seed: 6); // with transparent pixels
var post = await SaveAsync(bed, bed.Marta, "963", ImageConverter.Encode(picture, ImageFormat.Png, null), ".png");
var media = post.Media[0];
await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Jpg), ct);
var library = Fingerprint.Of(bed.Temp.Combine("libreria"));
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.AreEqual((1, 1, true), (start.Plan.Files, start.Plan.Converted, start.Plan.Lossy));
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.TransparencyWhite), (item.State, item.Note));
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Converted, ExportFormat.Jpg, media.Sha256), (copy.Variant, copy.Format, copy.SourceSha256));
Assert.AreEqual("marta.demo/" + Path.ChangeExtension(media.RelativePath!, ".jpg"), copy.RelativePath);
var file = Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!));
var bytes = await File.ReadAllBytesAsync(file, ct);
CollectionAssert.AreEqual(new byte[] { 0xFF, 0xD8, 0xFF }, bytes[..3]);
Assert.AreEqual((Convert.ToHexStringLower(SHA256.HashData(bytes)), (long?)bytes.Length), (copy.CopySha256, copy.Bytes));
Assert.AreEqual(post.Entry.PublishedAt.UtcDateTime, File.GetLastWriteTimeUtc(file), "«libreria.data-file-pubblicazione» is on");
Fingerprint.AreEqual(library, Fingerprint.Of(bed.Temp.Combine("libreria")), "the original stays as it is");
// The report lists the note, in Italian.
var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct);
var line = report.Notes.Single();
Assert.AreEqual((item.Id, ExportItemState.Copied), (line.ItemId, line.State));
Assert.AreEqual(ExportText.Note(ExportText.Notes.TransparencyWhite), line.Text);
Assert.IsEmpty(report.Accounts.Single().AsIs);
}
[TestMethod]
public void TheFormatIsTheRequestsThenTheDestinationsThenTheSettings()
{
var settings = ExportSettings.Default with { PhotoFormat = ExportFormat.Png, VideoFormat = ExportFormat.Mp4 };
var destination = new ExportDestination { Id = 1, Scope = ExportScope.General, RootPath = "/copie", ContentTypes = ContentTypes.All, CreatedAt = Make.T0 };
var jpgHere = destination with { PhotoFormat = ExportFormat.Jpg, VideoFormat = ExportFormat.Original };
Assert.AreEqual(ExportFormat.Png, ExportConversions.Resolve(MediaKind.Photo, null, destination, settings));
Assert.AreEqual(ExportFormat.Mp4, ExportConversions.Resolve(MediaKind.Video, null, destination, settings));
Assert.AreEqual(ExportFormat.Jpg, ExportConversions.Resolve(MediaKind.Photo, null, jpgHere, settings));
Assert.AreEqual(ExportFormat.Original, ExportConversions.Resolve(MediaKind.Video, null, jpgHere, settings));
Assert.AreEqual(ExportFormat.WebpLossless, ExportConversions.Resolve(MediaKind.Photo, new ExportFormatChoice(ExportFormat.WebpLossless, null), jpgHere, settings));
Assert.AreEqual(ExportFormat.Mp4, ExportConversions.Resolve(MediaKind.Video, new ExportFormatChoice(null, ExportFormat.Mp4), jpgHere, settings));
Assert.AreEqual(ExportFormat.Jpg, ExportConversions.Resolve(MediaKind.Photo, new ExportFormatChoice(ExportFormat.Mp4, null), jpgHere, settings), "a video format is not a photo's");
}
[TestMethod]
public async Task TheRequestOverridesTheDestination()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await bed.PostAsync(bed.Marta, "964", 34);
await bed.Service.Destinations.CreateAsync(new DestinationSpec(ExportScope.General, null, bed.Usb, "Disco USB", ContentTypes.All, null, null, null, PhotoFormat: ExportFormat.Png), ct);
var start = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([post.Media[0].Id]), Formats: new ExportFormatChoice(ExportFormat.WebpLossless, null)), ct);
var copy = (await bed.Db.Exports.GetCopyAsync((await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single().CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Converted, ExportFormat.WebpLossless), (copy.Variant, copy.Format));
StringAssert.EndsWith(copy.RelativePath, ".webp");
Assert.AreEqual(ImageFormat.WebP, ImageFormatSniffer.Detect(await File.ReadAllBytesAsync(Path.Combine(bed.Usb, LibraryLayout.ToPlatform(copy.RelativePath!)), ct)));
}
[TestMethod]
public async Task HeicIsCopiedAsItIsWithANoteAndTheReportCountsIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await FormatsAsync(bed, ExportFormat.Jpg, ct);
byte[] heic = [0, 0, 0, 0x18, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, 0, 0, 0, 8, .. "free"u8, .. new byte[64]];
var post = await SaveAsync(bed, bed.Marta, "965", heic, ".heic");
var media = post.Media[0];
await bed.GeneralAsync(ct: ct);
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.AreEqual(new ExportPlanAsIs("HEIC", 1), start.Plan.AsIs.Single(), "predicted from the name");
var item = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Copied, ExportText.Notes.AsIsHeif), (item.State, item.Note));
var copy = (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, media.Sha256), (copy.Variant, copy.Format, copy.CopySha256));
CollectionAssert.AreEqual(heic, await File.ReadAllBytesAsync(bed.GeneralCopy(bed.Marta, media), ct));
var report = await bed.Service.Reports.BuildAsync(start.Runs.Single().Id, ct);
Assert.AreEqual(1, report.Accounts.Single().AsIs["HEIC"]);
Assert.AreEqual(ExportText.Note(ExportText.Notes.AsIsHeif), report.Notes.Single().Text);
}
[TestMethod]
public async Task AConvertedFileAtThePathIsAdoptedAndASameSizeDifferentFileIsNot()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await FormatsAsync(bed, ExportFormat.Jpg, ct);
var same = await SavePngAsync(bed, "966", 35);
var other = await SavePngAsync(bed, "967", 36);
await bed.GeneralAsync(ct: ct);
// An earlier conversion of the same file (the bytes Febe makes), and one of the other file with a byte changed.
var adopted = ConvertedPath(bed, same.Media[0], ".jpg");
var foreign = ConvertedPath(bed, other.Media[0], ".jpg");
Directory.CreateDirectory(Path.GetDirectoryName(adopted)!);
Directory.CreateDirectory(Path.GetDirectoryName(foreign)!);
var conversion = await ConvertAsync(bed, same.Media[0], ExportFormat.Jpg, ct);
await File.WriteAllBytesAsync(adopted, conversion, ct);
var handDate = new DateTime(2020, 5, 1, 12, 0, 0, DateTimeKind.Utc);
File.SetLastWriteTimeUtc(adopted, handDate);
var changed = await ConvertAsync(bed, other.Media[0], ExportFormat.Jpg, ct);
changed[^10] ^= 0x01;
await File.WriteAllBytesAsync(foreign, changed, ct);
var before = Fingerprint.Of(bed.Usb);
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var items = (await bed.ItemsAsync(start.Runs.Single().Id, ct)).ToDictionary(i => i.MediaId!.Value);
var adoption = items[same.Media[0].Id];
Assert.AreEqual(ExportItemState.Adopted, adoption.State);
var copy = (await bed.Db.Exports.GetCopyAsync(adoption.CopyId!.Value, ct))!;
Assert.AreEqual((ExportCopyOrigin.Adopted, ExportVariant.Converted, ExportFormat.Jpg), (copy.Origin, copy.Variant, copy.Format));
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(conversion)), copy.CopySha256);
Assert.AreEqual(handDate, File.GetLastWriteTimeUtc(adopted), "adopted, not written again");
var written = items[other.Media[0].Id];
Assert.AreEqual(ExportItemState.Copied, written.State);
StringAssert.Contains(written.Note, ExportText.Notes.NameTaken);
StringAssert.EndsWith(written.RelativePath, " (2).jpg");
var after = Fingerprint.Of(bed.Usb);
foreach (var (path, print) in before)
{
Assert.AreEqual(print, after[path], path);
}
Assert.AreEqual(before.Count + 1, after.Count);
}
[TestMethod]
public async Task SpaceIsCheckedOnTheConvertedSize()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await FormatsAsync(bed, ExportFormat.Png, ct);
var post = await bed.PostAsync(bed.Marta, "968", 37);
var media = post.Media[0];
var usb = await bed.GeneralAsync(ct: ct);
long png = (await ConvertAsync(bed, media, ExportFormat.Png, ct)).Length;
Assert.IsGreaterThan(media.Bytes!.Value, png, "the PNG of a small JPEG is bigger");
bed.Disk.Free = media.Bytes!.Value + ExportSpace.Margin; // enough for the original, not for its PNG
var start = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var run = await bed.RunAsync(start.Runs.Single().Id, ct);
Assert.AreEqual(ExportRunState.Paused, run.State);
StringAssert.Contains(run.LastError, "margine di 64 MB");
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
bed.Disk.Free = png + ExportSpace.Margin;
await bed.Service.ResumeAsync([run.Id], ct);
await bed.Service.WaitAsync(ct);
Assert.AreEqual(ExportRunState.Completed, (await bed.RunAsync(run.Id, ct)).State);
Assert.IsNull((await bed.Db.Exports.GetDestinationAsync(usb.Id, ct))!.PausedAt);
Assert.AreEqual(png, (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single().Bytes);
}
[TestMethod]
public async Task ARemovedWholeCopyIsNotCopiedAgainInTheNewFormatUntilAskedAndExactIgnoresOtherForms()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var post = await SavePngAsync(bed, "969", 38);
var media = post.Media[0];
var usb = await bed.GeneralAsync(ct: ct);
var first = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var whole = (await bed.ItemsAsync(first.Runs.Single().Id, ct)).Single().CopyId!.Value;
File.Delete(bed.GeneralCopy(bed.Marta, media));
// The format changes to JPG: the file was copied («Tolto» now), so it is not copied again by itself (D3).
await FormatsAsync(bed, ExportFormat.Jpg, ct);
var skipped = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var item = (await bed.ItemsAsync(skipped.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Skipped, ExportText.Notes.Removed, (long?)whole), (item.State, item.Note, item.CopyId));
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
var plan = await bed.Service.PlanAsync(new ExportJobRequest(new ExportSelection.Account(bed.Marta.Id)), ct);
Assert.AreEqual((0, 1), (plan.Files, plan.RemovedOrSuperseded));
// «Copia di nuovo» from the dialog writes the current form: a JPG.
var again = await bed.CopyAccountAsync(bed.Marta, copyAgain: true, ct: ct);
var converted = (await bed.Db.Exports.GetCopyAsync((await bed.ItemsAsync(again.Runs.Single().Id, ct)).Single().CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Converted, ExportFormat.Jpg, ExportCopyState.Copied), (converted.Variant, converted.Format, converted.State));
Assert.AreEqual(ExportCopyState.Removed, (await bed.Db.Exports.GetCopyAsync(whole, ct))!.State);
// «Copia di nuovo» of the removed row from the viewer: its own form, whatever else is copied (D11).
var exact = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([media.Id]), CopyAgain: true, Exact: new ExportCopyRequest(ExportVariant.Whole, ExportFormat.Original, null)), ct);
var back = (await bed.ItemsAsync(exact.Runs.Single().Id, ct)).Single();
Assert.AreEqual(ExportItemState.Copied, back.State);
var restored = (await bed.Db.Exports.GetCopyAsync(back.CopyId!.Value, ct))!;
Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original), (restored.Variant, restored.Format));
Assert.AreNotEqual(whole, restored.Id);
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, media)));
Assert.HasCount(2, Fingerprint.Of(bed.Usb), "the JPG and the PNG");
Assert.AreEqual(ExportCopyState.Copied, (await bed.Db.Exports.GetCopyAsync(converted.Id, ct))!.State);
// The JPG asked again exactly: «Già copiato».
var twice = await bed.CopyAsync(new ExportJobRequest(new ExportSelection.Media([media.Id]), CopyAgain: true, Exact: new ExportCopyRequest(ExportVariant.Converted, ExportFormat.Jpg, null)), ct);
var same = (await bed.ItemsAsync(twice.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.AlreadyCopied, (long?)converted.Id), (same.State, same.CopyId));
Assert.HasCount(3, await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct));
}
[TestMethod]
public async Task OneCopyOnlyIgnoresTheFormat()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await (ExportSettings.Default with { SamePost = SamePostCopies.OneOnly, PhotoFormat = ExportFormat.Jpg }).SaveAsync(bed.Db.Settings, ct);
using var image = TestImages.Scene(39, 64, 48);
var png = TestImages.Png(image);
await SaveAsync(bed, bed.Marta, "970", png, ".png");
await SaveAsync(bed, bed.Luca, "970", png, ".png");
await bed.GeneralAsync(ct: ct);
await bed.CopyAccountAsync(bed.Marta, ct: ct);
var luca = await bed.CopyAccountAsync(bed.Luca, ct: ct);
var item = (await bed.ItemsAsync(luca.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.AlreadyCopied, ExportText.Notes.CopiedForAnotherAccount), (item.State, item.Note));
Assert.AreEqual(ExportVariant.Converted, (await bed.Db.Exports.GetCopyAsync(item.CopyId!.Value, ct))!.Variant);
Assert.HasCount(1, Fingerprint.Of(bed.Usb));
}
[TestMethod]
public async Task AChangedSourceFailsTheConversionAndAStaleFailedRowIsClearedLater()
{
var ct = TestContext.CancellationToken;
var corrupt = true;
await using var bed = await ExportTestBed.CreateAsync(env => env with { FileSystem = new CorruptingExportFileSystem(path => corrupt && path.EndsWith(".jpg", StringComparison.Ordinal)) });
await FormatsAsync(bed, ExportFormat.Png, ct);
var post = await bed.PostAsync(bed.Marta, "971", 40);
var usb = await bed.GeneralAsync(ct: ct);
var failed = await bed.CopyAccountAsync(bed.Marta, ct: ct);
var item = (await bed.ItemsAsync(failed.Runs.Single().Id, ct)).Single();
Assert.AreEqual((ExportItemState.Failed, ExportText.Notes.SourceChanged), (item.State, item.Note));
var row = (await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct)).Single();
Assert.AreEqual((ExportCopyState.Failed, ExportVariant.Converted, ExportFormat.Png), (row.State, row.Variant, row.Format));
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
// The disk reads well again and the format is back to Originale: the copy is written, the old failure goes.
corrupt = false;
await FormatsAsync(bed, ExportFormat.Original, ct);
var copied = await bed.CopyAccountAsync(bed.Marta, ct: ct);
Assert.AreEqual(ExportItemState.Copied, (await bed.ItemsAsync(copied.Runs.Single().Id, ct)).Single().State);
var copies = await bed.Db.Exports.ListCopiesAsync(usb.Id, ct: ct);
Assert.AreEqual((ExportCopyState.Copied, ExportVariant.Whole), (copies.Single().State, copies.Single().Variant), "the «Non riuscito» row of the other form has no use");
Assert.IsTrue(File.Exists(bed.GeneralCopy(bed.Marta, post.Media[0])));
}
private static Task FormatsAsync(ExportTestBed bed, ExportFormat photo, CancellationToken ct) =>
(ExportSettings.Default with { PhotoFormat = photo }).SaveAsync(bed.Db.Settings, ct);
private static Task SaveAsync(ExportTestBed bed, Account account, string code, byte[] bytes, string extension) =>
bed.Library.SaveAsync(account, Make.Entry(account.Id, code, Make.T0.AddDays(-1)), [new TestFile(Make.Photo(1), bytes, extension)]);
private static Task SavePngAsync(ExportTestBed bed, string code, int scene)
{
using var image = TestImages.Scene(scene, 64, 48);
return SaveAsync(bed, bed.Marta, code, TestImages.Png(image), ".png");
}
/// Where the general folder gets the converted copy of a file of marta.demo.
private static string ConvertedPath(ExportTestBed bed, Media media, string extension) =>
Path.Combine(bed.Usb, bed.Marta.Username, LibraryLayout.ToPlatform(Path.ChangeExtension(media.RelativePath!, extension)));
/// The bytes Febe makes of a library file in a format.
private static async Task ConvertAsync(ExportTestBed bed, Media media, ExportFormat format, CancellationToken ct)
{
var path = bed.LibraryFile(bed.Marta, media);
using var conversion = await MediaConverter.PrepareAsync(() => File.OpenRead(path), media.RelativePath!, media.Kind, format, media.Sha256!, new ConversionThrottle(), ct);
Assert.AreEqual(ExportVariant.Converted, conversion.Variant);
using var output = new MemoryStream();
await conversion.Produce!(output, ct);
return output.ToArray();
}
}