Prima parte della tappa E3 (formati e fotogrammi), solo nel nucleo: il pianificatore, il copiatore e l'archivio delle esportazioni restano alla parte successiva. - Foto: ImageConverter.Check dice prima che cosa succede (copia identica, conversione, copia così com'è con il motivo: HEIC, AVIF, raw, animazioni, file danneggiati, CMYK e oltre 8 bit verso PNG/WEBP, oltre il limite di pixel); la conversione riporta come note ciò che non può portare invece di fermarsi, e la trasparenza verso JPG diventa bianco. I lettori segnalano animazioni, CMYK e segmenti non letti. VP8L usa un logaritmo in virgola fissa, così lo stesso file dà gli stessi byte su ogni sistema. - Video: i lettori ISO e Matroska leggono elenco dei montaggi, lingue, tipo di AAC, MP3 e i vecchi codici AAC di Matroska; Mp4Writer prepara la disposizione e ne conosce la lunghezza prima di scrivere; il nuovo Mp4Remuxer porta in MP4 senza ricodificare, sempre con gli stessi byte. - Fotogrammi: VideoFrameReader trova il campione mostrato a un istante come lo mostra il lettore, lo decodifica esatto a piena risoluzione e lo raddrizza; ExportFrames calcola istanti, suffissi e etichette. - Nomi: il suffisso del fotogramma non si accorcia mai e la numerazione dei nomi liberi viene dopo di lui; SafeFileWriter scrive anche contenuti prodotti mentre li scrive. - MediaConverter e ConversionThrottle preparano una conversione senza sapere dove andrà, una alla volta in tutto il processo. Nuove prove per determinismo, istanti, rotazione, rimux e nomi; tutte le prove di Febe.Tests passano. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
198 lines
9.1 KiB
C#
198 lines
9.1 KiB
C#
using System.Security.Cryptography;
|
|
using Febe.Core.Library;
|
|
using Febe.Tests.Support;
|
|
|
|
namespace Febe.Tests.Library;
|
|
|
|
[TestClass]
|
|
public sealed class SafeFileWriterTests
|
|
{
|
|
private static byte[] Content(int size, int seed = 1)
|
|
{
|
|
var bytes = new byte[size];
|
|
new Random(seed).NextBytes(bytes);
|
|
return bytes;
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ProducedContentIsHashedAndATakenNameIsNumberedAfterTheKeptSuffix()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var content = Content(3000, 7);
|
|
Directory.CreateDirectory(Path.Combine(temp.Path, "post"));
|
|
File.WriteAllBytes(Path.Combine(temp.Path, "post", "a_f001.png"), [1, 2, 3]);
|
|
var tempDirectory = Path.Combine(temp.Path, ".tmp");
|
|
Directory.CreateDirectory(tempDirectory);
|
|
FileDigest? seen = null;
|
|
|
|
var saved = await new SafeFileWriter().SaveAsync(
|
|
(output, token) => output.WriteAsync(content, token).AsTask(),
|
|
temp.Path,
|
|
tempDirectory,
|
|
(digest, _) =>
|
|
{
|
|
seen = digest;
|
|
return ValueTask.FromResult<string?>("post/a_f001.png");
|
|
},
|
|
new SafeWriteOptions { KeepSuffix = "_f001" });
|
|
|
|
Assert.IsNotNull(saved);
|
|
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), seen!.Value.Sha256);
|
|
Assert.AreEqual(3000L, seen.Value.Bytes);
|
|
Assert.AreEqual("post/a_f001 (2).png", saved.RelativePath);
|
|
CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(temp.Path, "post", "a_f001.png")), "Il file che c'era non è toccato.");
|
|
CollectionAssert.AreEqual(content, File.ReadAllBytes(saved.FullPath));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task WritesTheFileWithItsHashAndPublicationTime()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var content = Content(300_000);
|
|
var published = new DateTimeOffset(2024, 5, 6, 7, 8, 9, TimeSpan.Zero);
|
|
var saved = await new SafeFileWriter().SaveAsync(new MemoryStream(content), temp.Path, "post/2024/foto_1.jpg", new SafeWriteOptions { LastWriteTime = published });
|
|
|
|
Assert.AreEqual("post/2024/foto_1.jpg", saved.RelativePath);
|
|
Assert.AreEqual(Path.Combine(temp.Path, "post", "2024", "foto_1.jpg"), saved.FullPath);
|
|
CollectionAssert.AreEqual(content, await File.ReadAllBytesAsync(saved.FullPath));
|
|
Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), saved.Sha256);
|
|
Assert.AreEqual(content.Length, saved.Bytes);
|
|
Assert.IsTrue(saved.LastWriteTimeSet);
|
|
Assert.AreEqual(published.UtcDateTime, File.GetLastWriteTimeUtc(saved.FullPath));
|
|
Assert.IsEmpty(Directory.GetFiles(temp.Path, "*.part", SearchOption.AllDirectories));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task NeverOverwritesAnExistingFile()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var writer = new SafeFileWriter();
|
|
var first = await writer.SaveAsync(new MemoryStream(Content(10, 1)), temp.Path, "post/a.jpg");
|
|
var second = await writer.SaveAsync(new MemoryStream(Content(10, 2)), temp.Path, "post/a.jpg");
|
|
var third = await writer.SaveAsync(new MemoryStream(Content(10, 3)), temp.Path, "post/a.jpg");
|
|
|
|
Assert.AreEqual("post/a.jpg", first.RelativePath);
|
|
Assert.AreEqual("post/a (2).jpg", second.RelativePath);
|
|
Assert.AreEqual("post/a (3).jpg", third.RelativePath);
|
|
CollectionAssert.AreEqual(Content(10, 1), await File.ReadAllBytesAsync(first.FullPath), "Il primo file è rimasto com'era.");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ConcurrentWritesToTheSameNameAllSurvive()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var writer = new SafeFileWriter();
|
|
var results = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => Task.Run(() => writer.SaveAsync(new MemoryStream(Content(5000, i)), temp.Path, "storie/x.mp4"))));
|
|
Assert.AreEqual(12, results.Select(r => r.RelativePath).Distinct().Count());
|
|
foreach (var (result, i) in results.Select((r, i) => (r, i)))
|
|
{
|
|
CollectionAssert.AreEqual(Content(5000, i), await File.ReadAllBytesAsync(result.FullPath));
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task UsesATemporaryNameWhileWriting()
|
|
{
|
|
using var temp = new TempFolder();
|
|
string[]? during = null;
|
|
var stream = new ObservingStream(Content(1_000_000), 400_000, () => during = Directory.GetFiles(Path.Combine(temp.Path, "post")));
|
|
await new SafeFileWriter().SaveAsync(stream, temp.Path, "post/finale.jpg");
|
|
|
|
Assert.IsNotNull(during);
|
|
Assert.HasCount(1, during);
|
|
Assert.IsTrue(SafeFileWriter.IsTemporaryFile(during[0]), during[0]);
|
|
Assert.StartsWith(".febe-", Path.GetFileName(during[0]));
|
|
Assert.IsTrue(File.Exists(Path.Combine(temp.Path, "post", "finale.jpg")));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task AnInterruptedDownloadLeavesNoFile()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var broken = new ObservingStream(Content(1_000_000), 300_000, () => throw new IOException("Connessione interrotta"));
|
|
await Assert.ThrowsExactlyAsync<IOException>(() => new SafeFileWriter().SaveAsync(broken, temp.Path, "post/finale.jpg"));
|
|
|
|
Assert.IsFalse(File.Exists(Path.Combine(temp.Path, "post", "finale.jpg")));
|
|
Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ACancelledDownloadLeavesNoFile()
|
|
{
|
|
using var temp = new TempFolder();
|
|
using var cancel = new CancellationTokenSource();
|
|
var stream = new ObservingStream(Content(1_000_000), 300_000, cancel.Cancel);
|
|
await Assert.ThrowsAsync<OperationCanceledException>(() => new SafeFileWriter().SaveAsync(stream, temp.Path, "storie/v.mp4", ct: cancel.Token));
|
|
Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ATooLargeFileIsDropped()
|
|
{
|
|
using var temp = new TempFolder();
|
|
await Assert.ThrowsExactlyAsync<FileTooLargeException>(() => new SafeFileWriter().SaveAsync(new MemoryStream(Content(500_000)), temp.Path, "post/v.mp4", new SafeWriteOptions { MaxBytes = 200_000 }));
|
|
Assert.IsEmpty(Directory.GetFiles(temp.Path, "*", SearchOption.AllDirectories));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheNameCanDependOnTheHash()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var content = Content(2048);
|
|
var saved = await new SafeFileWriter().SaveAsync(new MemoryStream(content), temp.Path, "profilo", d => $"profilo/{d.Sha256[..8]}_{d.Bytes}.jpg");
|
|
Assert.AreEqual($"profilo/{Convert.ToHexStringLower(SHA256.HashData(content))[..8]}_2048.jpg", saved.RelativePath);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task LongNamesAreShortenedAndUnsafeNamesCleaned()
|
|
{
|
|
using var temp = new TempFolder();
|
|
var writer = new SafeFileWriter();
|
|
var name = "evidenza/" + new string('t', 200) + "/" + new string('n', 200) + "_1.jpg";
|
|
var saved = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, name);
|
|
Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, saved.FullPath.Length);
|
|
Assert.EndsWith(".jpg", saved.RelativePath);
|
|
|
|
var reserved = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, "post/CON.jpg");
|
|
Assert.AreEqual("post/CON_.jpg", reserved.RelativePath);
|
|
|
|
// «..» is not a valid name on Windows: it becomes «_», so nothing can be written outside the folder.
|
|
var escape = await writer.SaveAsync(new MemoryStream(Content(10)), temp.Path, "../fuori/a.jpg");
|
|
Assert.AreEqual("_/fuori/a.jpg", escape.RelativePath);
|
|
Assert.StartsWith(temp.Path, escape.FullPath);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void CleanupRemovesOnlyTemporaryFiles()
|
|
{
|
|
using var temp = new TempFolder();
|
|
Directory.CreateDirectory(temp.Combine("post"));
|
|
File.WriteAllText(temp.Combine("post", ".febe-abc123.part"), "x");
|
|
File.WriteAllText(temp.Combine(".febe-def456.part"), "x");
|
|
File.WriteAllText(temp.Combine("post", "foto.jpg"), "x");
|
|
File.WriteAllText(temp.Combine("post", "foto.part"), "x");
|
|
Assert.AreEqual(2, SafeFileWriter.CleanupTemporaryFiles(temp.Path));
|
|
Assert.IsTrue(File.Exists(temp.Combine("post", "foto.jpg")));
|
|
Assert.IsTrue(File.Exists(temp.Combine("post", "foto.part")));
|
|
}
|
|
|
|
/// <summary>A stream that runs an action once, after a given number of bytes has been read.</summary>
|
|
private sealed class ObservingStream(byte[] data, int triggerAt, Action action) : MemoryStream(data)
|
|
{
|
|
private bool _fired;
|
|
|
|
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
|
{
|
|
if (!_fired && Position >= triggerAt)
|
|
{
|
|
_fired = true;
|
|
action();
|
|
}
|
|
|
|
await Task.Yield();
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
return await base.ReadAsync(buffer[..Math.Min(buffer.Length, 64 * 1024)], cancellationToken);
|
|
}
|
|
}
|
|
}
|