Le prove dell'API dei fotogrammi (anteprime, istanti, «Scarica» di un'immagine o di uno zip con nomi e date, limiti, il permesso dei lavori lunghi, i fotogrammi nella cartella delle copie, i controlli dell'Origin) e dei formati («Copia in…» con il suo formato, la conversione della libreria dalla domanda alla cancellazione). Le prove dell'interfaccia con Chromium: formati delle impostazioni e della cartella, la domanda «Solo i nuovi», «Cambia» in «Copia in…», «Fotogrammi…» dal visualizzatore e da una scelta, le righe delle copie e del file convertito. Ciò che le pagine devono dire si chiede all'API, perché la demo dispone i suoi elementi secondo l'ora. La prova di scala riempie anche copie convertite e fotogrammi, che il filtro «Copie» deve contare o ignorare come prima, entro i suoi tempi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
522 lines
31 KiB
C#
522 lines
31 KiB
C#
using System.IO.Compression;
|
|
using System.Net;
|
|
using System.Text.Json;
|
|
using Febe.Core.Abstractions;
|
|
using Febe.Core.Codecs.H264;
|
|
using Febe.Core.Domain;
|
|
using Febe.Core.Export;
|
|
using Febe.Core.Library;
|
|
using Febe.Core.Storage;
|
|
using Febe.Tests.Export.Support;
|
|
using Febe.Tests.Support;
|
|
using Febe.Tests.Web.Support;
|
|
using Febe.Web;
|
|
using Febe.Web.Export;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace Febe.Tests.Web;
|
|
|
|
/// <summary>
|
|
/// Frames over the API of a real web host (spec §4.10 «Fotogrammi», tappa E3, D12-D14), with videos built by the test:
|
|
/// the instants of each mode are the pictures shown, a video without frames says so everywhere, a preview past its
|
|
/// budget answers 503, «Scarica» gives one image or a zip (names, account folders, dates per the setting), the limits of
|
|
/// «Scarica» (20 at any time, 21-500 only outside engine sessions and other long work, more than 500 never), the lease of
|
|
/// a large zip held until it ends or the page goes away, and frames to the folder of the copies with their viewer rows,
|
|
/// mark and «Copia di nuovo».
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class ExportFramesApiTests
|
|
{
|
|
public TestContext TestContext { get; set; } = null!;
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task TheInstantsOfEachModeAreThePicturesShown()
|
|
{
|
|
await using var server = await StartAsync();
|
|
var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo()));
|
|
var video = post.Media[0].Id;
|
|
|
|
// The demo video shows a picture every 125 ms: «Questo istante» gives the one shown, past the end the last one.
|
|
var at = (await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=istante&at=1234")).Items("instants").Single();
|
|
Assert.AreEqual((1234L, 1125L, "0:01,125", "_t0m01s125"), (at.Long("requestedMs"), at.Long("actualMs"), at.Str("label"), at.Str("suffix")));
|
|
var past = (await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=istante&at=60000")).Items("instants").Single();
|
|
Assert.AreEqual(1875L, past.Long("actualMs"), "past the end: the last picture");
|
|
|
|
// «Uno ogni k secondi» from 0:00; «N in tutto» centred in N equal parts (§16 domanda 33).
|
|
var every = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=ogni&every=500");
|
|
Assert.AreEqual(4, every.Int("total"));
|
|
CollectionAssert.AreEqual(new long[] { 0, 500, 1000, 1500 }, every.Items("instants").Select(i => i.Long("actualMs")).ToArray());
|
|
CollectionAssert.AreEqual(new[] { "_t0m00s000", "_t0m00s500", "_t0m01s000", "_t0m01s500" }, every.Items("instants").Select(i => i.Str("suffix")).ToArray());
|
|
var count = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=numero&count=4");
|
|
CollectionAssert.AreEqual(new long[] { 250, 750, 1250, 1750 }, count.Items("instants").Select(i => i.Long("requestedMs")).ToArray());
|
|
CollectionAssert.AreEqual(new long[] { 250, 750, 1250, 1750 }, count.Items("instants").Select(i => i.Long("actualMs")).ToArray());
|
|
CollectionAssert.AreEqual(new[] { "0:00,25", "0:00,75", "0:01,25", "0:01,75" }, count.Items("instants").Select(i => i.Str("label")).ToArray());
|
|
|
|
// A re-request at the actual instant gives the same picture (D12: ceil ms).
|
|
using (var first = await server.Client.GetAsync($"/api/media/{video}/frame?at=1234&format=png", TestContext.CancellationToken))
|
|
using (var again = await server.Client.GetAsync($"/api/media/{video}/frame?at=1125&format=png", TestContext.CancellationToken))
|
|
{
|
|
CollectionAssert.AreEqual(await first.Content.ReadAsByteArrayAsync(TestContext.CancellationToken), await again.Content.ReadAsByteArrayAsync(TestContext.CancellationToken));
|
|
}
|
|
|
|
// The limits (§16 domanda 38) and the words of the modes.
|
|
foreach (var wrong in new[] { "mode=ogni&every=50", "mode=numero&count=0", "mode=numero&count=1001", "mode=sempre", "mode=numero&count=3&format=gif" })
|
|
{
|
|
var path = $"/api/media/{video}/frames/instants?{wrong}";
|
|
if (wrong.Contains("format", StringComparison.Ordinal))
|
|
{
|
|
path = $"/api/media/{video}/frame?at=0&format=gif";
|
|
}
|
|
|
|
var (status, body) = await server.SendJsonAsync(HttpMethod.Get, path);
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, status, wrong);
|
|
Assert.IsNotEmpty(body.Str("message"), wrong);
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task AVideoWithoutFramesSaysSoEverywhere()
|
|
{
|
|
await using var server = await StartAsync();
|
|
var noise = new byte[40_000];
|
|
new Random(5).NextBytes(noise);
|
|
var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "rumore", Make.T0.AddDays(-1), WebLibrary.Video(noise));
|
|
var video = post.Media[0].Id;
|
|
|
|
var info = await server.GetJsonAsync($"/api/media/{video}/frames/info");
|
|
Assert.IsFalse(info.Bool("available"));
|
|
Assert.IsNotEmpty(info.Str("unavailable"));
|
|
|
|
var (frameStatus, frame) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{video}/frame?at=0&max=160");
|
|
Assert.AreEqual(HttpStatusCode.NotFound, frameStatus);
|
|
Assert.IsNotEmpty(frame.Str("message"));
|
|
var instants = await server.GetJsonAsync($"/api/media/{video}/frames/instants?mode=numero&count=3");
|
|
Assert.AreEqual(0, instants.Int("total"));
|
|
Assert.IsNotEmpty(instants.Str("problem"));
|
|
|
|
// The viewer says «Fotogramma non disponibile» (WP4) from this flag.
|
|
var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single();
|
|
Assert.IsFalse(shown.Bool("framesAvailable"));
|
|
|
|
var selection = new { mediaIds = new[] { video }, frames = new { mode = "istante", atMs = 0, format = "png" } };
|
|
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection)).Body;
|
|
Assert.AreEqual((1, 1, 0), (plan.Int("videos"), plan.Int("notAvailable"), plan.Int("frames")), plan.ToString());
|
|
Assert.AreEqual(FrameService.NothingText, plan.Str("problem"));
|
|
StringAssert.Contains(plan.Str("summary"), "1 video senza fotogrammi");
|
|
var (tokenStatus, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, tokenStatus);
|
|
Assert.AreEqual(FrameService.NothingText, token.Str("message"));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(120_000, CooperativeCancellation = true)]
|
|
public async Task APreviewPastItsBudgetSaysToUseTheFolderOfTheCopies()
|
|
{
|
|
await using var server = await WebTestServer.StartAsync(
|
|
new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None },
|
|
s => s.AddSingleton(sp => new FrameService(sp.GetRequiredService<IClock>()) { Budget = TimeSpan.Zero }));
|
|
var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo()));
|
|
|
|
var (status, body) = await server.SendJsonAsync(HttpMethod.Get, $"/api/media/{post.Media[0].Id}/frame?at=0&max=160");
|
|
Assert.AreEqual(HttpStatusCode.ServiceUnavailable, status);
|
|
Assert.AreEqual(FrameService.TimeoutText, body.Str("message"));
|
|
|
|
// What the video allows is known without decoding a frame.
|
|
Assert.IsTrue((await server.GetJsonAsync($"/api/media/{post.Media[0].Id}/frames/info")).Bool("available"));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(180_000, CooperativeCancellation = true)]
|
|
public async Task ScaricaGivesOneImageOrAZipNamedAndDatedAsTheCopies()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var first = await WebLibrary.AddPostAsync(server, marta, "primo", Make.T0.AddDays(-3), WebLibrary.DemoVideo(2));
|
|
var second = await WebLibrary.AddPostAsync(server, marta, "secondo", Make.T0.AddDays(-5), WebLibrary.DemoVideo(3), WebLibrary.Photo(4));
|
|
|
|
// One frame: the image itself, named by its actual instant, in the format chosen.
|
|
var one = new { mediaIds = new[] { first.Media[0].Id }, frames = new { mode = "istante", atMs = 1234, format = "jpg" } };
|
|
var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", one);
|
|
Assert.AreEqual(HttpStatusCode.OK, status, token.ToString());
|
|
Assert.AreEqual(1, token.Int("frames"));
|
|
using (var image = await server.Client.GetAsync(token.Str("url"), ct))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, image.StatusCode);
|
|
Assert.AreEqual("image/jpeg", image.Content.Headers.ContentType?.MediaType);
|
|
Assert.AreEqual(Stem(first.Media[0]) + "_t0m01s125.jpg", FileName(image));
|
|
var bytes = await image.Content.ReadAsByteArrayAsync(ct);
|
|
Assert.AreEqual((0xFF, 0xD8), (bytes[0], bytes[1]));
|
|
}
|
|
|
|
// Two entries, grouped: their videos (the photo is skipped and said), three frames each, in one zip.
|
|
var both = new { entryIds = new[] { first.Entry.Id, second.Entry.Id }, frames = new { mode = "numero", count = 3, format = "png" } };
|
|
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", both)).Body;
|
|
Assert.AreEqual((2, 1, 0, 6), (plan.Int("videos"), plan.Int("photosSkipped"), plan.Int("notAvailable"), plan.Int("frames")), plan.ToString());
|
|
Assert.AreEqual("6 fotogrammi da 2 video · la foto si salta", plan.Str("summary"));
|
|
Assert.IsFalse(plan.Bool("needsQuiet"));
|
|
Assert.AreEqual(JsonValueKind.Null, plan.GetProperty("problem").ValueKind);
|
|
|
|
var published = await ZipAsync(server, both);
|
|
Assert.AreEqual($"febe-fotogrammi-{LocalCalendar.Today(server.Clock.Now, server.Clock.LocalZone):yyyy-MM-dd}.zip", published.Name);
|
|
var expected = new[] { first, second }
|
|
.SelectMany(p => new[] { "_f001", "_f002", "_f003" }.Select(s => $"marta.demo/{Stem(p.Media[0])}{s}.png"))
|
|
.ToArray();
|
|
CollectionAssert.AreEquivalent(expected, published.Entries.Keys.ToArray());
|
|
// The time of publication of each entry, where Febe runs (D18; the zip keeps 2 s steps).
|
|
AssertNear(first.Entry.PublishedAt, published.Entries[expected[0]], server.Clock.LocalZone);
|
|
AssertNear(second.Entry.PublishedAt, published.Entries[expected[3]], server.Clock.LocalZone);
|
|
|
|
// «Data del file = pubblicazione» off: the time of the download.
|
|
await server.Db.Settings.SetAsync(SettingKeys.SetFileTimeToPublication, "false", ct);
|
|
var now = await ZipAsync(server, both);
|
|
Assert.IsTrue(now.Entries.Values.All(time => Math.Abs((time - TimeZoneInfo.ConvertTime(server.Clock.Now, server.Clock.LocalZone).DateTime).TotalSeconds) <= 2), string.Join(", ", now.Entries.Values));
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(180_000, CooperativeCancellation = true)]
|
|
public async Task TheLimitsOfScaricaAreKept()
|
|
{
|
|
var session = new FakeSessionState();
|
|
await using var server = await StartAsync(session);
|
|
var gate = server.App.Services.GetRequiredService<LongWorkGate>();
|
|
var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo()));
|
|
object Selection(int n) => new { mediaIds = new[] { post.Media[0].Id }, frames = new { mode = "numero", count = n, format = "png" } };
|
|
|
|
// More than 500: never «Scarica» (the folder of the copies takes them); more than 1.000 a video: refused.
|
|
var many = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(501))).Body;
|
|
Assert.IsTrue(many.Bool("tooManyToDownload"));
|
|
Assert.AreEqual(FrameService.TooManyText, many.Str("problem"));
|
|
Assert.AreEqual((HttpStatusCode.BadRequest, FrameService.TooManyText), await TokenAsync(server, Selection(501)));
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(1001))).Status);
|
|
|
|
// From 21: only when it is quiet; up to 20 at any time.
|
|
var quiet = (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body;
|
|
Assert.IsTrue(quiet.Bool("needsQuiet"));
|
|
Assert.AreEqual(JsonValueKind.Null, quiet.GetProperty("problem").ValueKind);
|
|
|
|
session.InSession = true;
|
|
Assert.AreEqual(FrameService.SessionText, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.Str("problem"));
|
|
Assert.AreEqual(((HttpStatusCode)409, FrameService.SessionText), await TokenAsync(server, Selection(21)));
|
|
Assert.HasCount(16, (await ZipAsync(server, Selection(20))).Entries, "20 frames during a session: a zip of the 16 pictures of the video");
|
|
|
|
// A download asked outside a session and opened during one waits for it to end.
|
|
session.InSession = false;
|
|
var (_, ready) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", Selection(21));
|
|
session.InSession = true;
|
|
var (late, lateBody) = await server.SendJsonAsync(HttpMethod.Get, ready.Str("url"));
|
|
Assert.AreEqual((HttpStatusCode)409, late);
|
|
Assert.AreEqual(FrameService.SessionText, lateBody.Str("message"));
|
|
session.InSession = false;
|
|
|
|
// Another long work: 21 and more wait for it with its message, 20 do not.
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var export, out _));
|
|
using (export)
|
|
{
|
|
var busy = LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.Export);
|
|
Assert.AreEqual(busy, (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", Selection(21))).Body.Str("problem"));
|
|
Assert.AreEqual(((HttpStatusCode)409, busy), await TokenAsync(server, Selection(21)));
|
|
Assert.HasCount(16, (await ZipAsync(server, Selection(20))).Entries);
|
|
}
|
|
|
|
Assert.IsNull(gate.Busy, "no lease is left behind");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task AZipOfMoreThanTwentyHoldsItsLeaseUntilItEndsOrThePageGoes()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var gate = server.App.Services.GetRequiredService<LongWorkGate>();
|
|
// Big pictures of noise, so the zip (about 60 MB of PNG) cannot sit whole in the buffers of the connection: the
|
|
// server is still writing while the test looks.
|
|
var post = await WebLibrary.AddPostAsync(server, await AccountAsync(server), "rumore", Make.T0.AddDays(-1), WebLibrary.Video(NoiseVideo(1280, 720, 24)));
|
|
var selection = new { mediaIds = new[] { post.Media[0].Id }, frames = new { mode = "numero", count = 22, format = "png" } };
|
|
|
|
// Read to the end: the lease is held while it is written, then let go.
|
|
var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
|
|
Assert.AreEqual(HttpStatusCode.OK, status, token.ToString());
|
|
using (var response = await server.Client.GetAsync(token.Str("url"), HttpCompletionOption.ResponseHeadersRead, ct))
|
|
{
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, gate.Busy);
|
|
Assert.IsFalse(gate.TryEnter(LongWorkKind.Import, out _, out var busyWith));
|
|
Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, busyWith);
|
|
Assert.AreEqual(LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, LongWorkKind.FrameDownload), (await server.SendJsonAsync(HttpMethod.Post, "/api/frames/plan", selection)).Body.Str("problem"));
|
|
using var archive = new ZipArchive(new MemoryStream(await response.Content.ReadAsByteArrayAsync(ct)), ZipArchiveMode.Read);
|
|
Assert.HasCount(22, archive.Entries);
|
|
}
|
|
|
|
await WaitFreeAsync(gate, "after the whole zip");
|
|
|
|
// The page goes away halfway: the lease goes with it.
|
|
(status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
|
|
Assert.AreEqual(HttpStatusCode.OK, status, token.ToString());
|
|
var abandoned = await server.Client.GetAsync(token.Str("url"), HttpCompletionOption.ResponseHeadersRead, ct);
|
|
Assert.AreEqual((LongWorkKind?)LongWorkKind.FrameDownload, gate.Busy);
|
|
var part = new byte[64 * 1024];
|
|
await (await abandoned.Content.ReadAsStreamAsync(ct)).ReadAtLeastAsync(part, part.Length, throwOnEndOfStream: false, ct);
|
|
abandoned.Dispose();
|
|
await WaitFreeAsync(gate, "after the page went away");
|
|
Assert.IsTrue(gate.TryEnter(LongWorkKind.Export, out var lease, out _), "another long work can start");
|
|
lease.Dispose();
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(180_000, CooperativeCancellation = true)]
|
|
public async Task FramesGoToTheFolderOfTheCopiesAndAreCopiedAgainOnRequest()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var marta = await AccountAsync(server);
|
|
var post = await WebLibrary.AddPostAsync(server, marta, "video", Make.T0.AddDays(-1), WebLibrary.Video(H264PcmWriter.DemoVideo()), WebLibrary.Photo(4));
|
|
var usb = server.Temp.Combine("usb");
|
|
Directory.CreateDirectory(usb);
|
|
var (created, destination) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/destinations", WebLibrary.Destination(usb));
|
|
Assert.AreEqual(HttpStatusCode.OK, created, destination.ToString());
|
|
var destinationId = destination.GetProperty("destination").Long("id");
|
|
|
|
// Formats and frames are two different requests.
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { entryIds = new[] { post.Entry.Id }, photoFormat = "png", frames = new { mode = "istante", atMs = 1234 } })).Status);
|
|
|
|
var request = new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "istante", atMs = 1234, format = "png" } };
|
|
var plan = (await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", request)).Body;
|
|
Assert.AreEqual((1, 1, 1), (plan.Int("videos"), plan.Int("photosSkipped"), plan.Int("frames")), plan.ToString());
|
|
Assert.AreEqual("1 fotogramma da 1 video · la foto si salta", plan.Str("summary"));
|
|
Assert.IsFalse(plan.Bool("lossy"));
|
|
Assert.IsTrue((await server.SendJsonAsync(HttpMethod.Post, "/api/export/plan", new { entryIds = new[] { post.Entry.Id }, frames = new { mode = "istante", atMs = 1234, format = "jpg" } })).Body.Bool("lossy"), "a JPG frame is «con perdita»");
|
|
|
|
await WebLibrary.StartAndWaitAsync(server, request);
|
|
var frame = Path.Combine(usb, "marta.demo", LibraryLayout.ToPlatform(Path.ChangeExtension(post.Media[0].RelativePath!, null) + "_t0m01s125.png"));
|
|
Assert.IsTrue(File.Exists(frame), string.Join(", ", Directory.GetFiles(usb, "*", SearchOption.AllDirectories)));
|
|
Assert.HasCount(1, Directory.GetFiles(usb, "*", SearchOption.AllDirectories), "only the frame: the video and the photo are not copied");
|
|
|
|
// The viewer row of the frame, and the mark of the entry: a frame does not make the file «Copiato».
|
|
var shown = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").ToDictionary(m => m.Long("id"));
|
|
var row = shown[post.Media[0].Id].Items("copies").Single();
|
|
Assert.AreEqual(("copied", "frame", "png", 1125L, "0:01,125"), (row.Str("state"), row.Str("variant"), row.Str("format"), row.Long("frameAtMs"), row.Str("frameLabel")));
|
|
Assert.IsFalse(row.Bool("canCopyAgain"));
|
|
var tile = (await server.GetJsonAsync("/api/library?limit=50")).Items("tiles").Single(t => t.Long("id") == post.Entry.Id);
|
|
Assert.AreEqual("frameOnly", tile.Str("copies"), tile.ToString());
|
|
Assert.HasCount(1, (await server.GetJsonAsync("/api/library?copies=notCopied")).Items("tiles").ToList(), "still «Non ancora copiati»");
|
|
|
|
// Removed from the folder: «Controlla le copie» says «Tolto», «Copia di nuovo» writes the same frame again.
|
|
File.Delete(frame);
|
|
Assert.AreEqual(HttpStatusCode.OK, (await server.SendJsonAsync(HttpMethod.Post, $"/api/export/destinations/{destinationId}/check")).Status);
|
|
await WebLibrary.WaitAsync(async () => (await server.Db.Exports.ListCopiesAsync(destinationId, ExportCopyState.Removed, 0, 10, ct)).Count == 1, "the frame «Tolto»");
|
|
await WebLibrary.WaitIdleAsync(server);
|
|
row = (await server.GetJsonAsync($"/api/entries/{post.Entry.Id}")).Items("media").Single(m => m.Long("id") == post.Media[0].Id).Items("copies").Single();
|
|
Assert.AreEqual("removed", row.Str("state"));
|
|
Assert.IsTrue(row.Bool("canCopyAgain"));
|
|
var (again, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = row.Long("copyId") });
|
|
Assert.AreEqual(HttpStatusCode.OK, again, job.ToString());
|
|
await WebLibrary.WaitIdleAsync(server);
|
|
Assert.IsTrue(File.Exists(frame), "the frame written again at its place");
|
|
var copies = await server.Db.Exports.ListCopiesAsync(destinationId, null, 0, 10, ct);
|
|
Assert.AreEqual(
|
|
(ExportVariant.Frame, ExportFormat.Png, TimeSpan.FromMilliseconds(1125)),
|
|
copies.Where(c => c.State == ExportCopyState.Copied).Select(c => (c.Variant, c.Format, c.FrameAt!.Value)).Single(),
|
|
"the same form, not the whole video");
|
|
Assert.AreEqual(HttpStatusCode.BadRequest, (await server.SendJsonAsync(HttpMethod.Post, "/api/export/copy-again", new { copyId = row.Long("copyId") })).Status, "already copied again");
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task CommandsOfFramesAndConversionsComeOnlyFromFebesPages()
|
|
{
|
|
var ct = TestContext.CancellationToken;
|
|
await using var server = await StartAsync();
|
|
var frames = new { mediaIds = new[] { 1L }, frames = new { mode = "istante", atMs = 0 } };
|
|
foreach (var (method, path, body) in new (HttpMethod, string, object)[]
|
|
{
|
|
(HttpMethod.Post, "/api/frames/plan", frames),
|
|
(HttpMethod.Post, "/api/frames/download-token", frames),
|
|
(HttpMethod.Post, "/api/conversions/show-in-folder", new { conversionId = 1 }),
|
|
(HttpMethod.Post, "/api/entries/delete-preview", new { ids = new[] { 1L } }),
|
|
(HttpMethod.Post, "/api/export/library-conversion/pause", new { }),
|
|
(HttpMethod.Post, "/api/export/library-conversion/resume", new { }),
|
|
(HttpMethod.Post, "/api/export/library-conversion/retry", new { }),
|
|
(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = true }),
|
|
})
|
|
{
|
|
using var request = server.Request(method, path, body, "http://altro.example");
|
|
using var response = await server.Client.SendAsync(request, ct);
|
|
Assert.AreEqual(HttpStatusCode.Forbidden, response.StatusCode, path);
|
|
}
|
|
|
|
var status = await server.GetJsonAsync("/api/export/library-conversion");
|
|
Assert.IsFalse(status.Bool("paused"), "nothing was done");
|
|
Assert.IsFalse(status.Bool("on"));
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------- support
|
|
|
|
private static Task<WebTestServer> StartAsync(IEngineSessionState? session = null) =>
|
|
WebTestServer.StartAsync(
|
|
new FebeWebOptions { Edition = FebeEdition.Desktop, Access = AccessMode.None },
|
|
s =>
|
|
{
|
|
s.AddSingleton<IExportDisk>(new FakeExportDisk(500_000_000_000));
|
|
if (session is not null)
|
|
{
|
|
s.AddSingleton(session);
|
|
}
|
|
});
|
|
|
|
private static Task<Account> AccountAsync(WebTestServer server) => server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
|
|
|
|
private static string Stem(Media media) => Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(media.RelativePath!));
|
|
|
|
private static string? FileName(HttpResponseMessage response) =>
|
|
response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName?.Trim('"');
|
|
|
|
private static void AssertNear(DateTimeOffset expected, DateTime actual, TimeZoneInfo zone)
|
|
{
|
|
var local = TimeZoneInfo.ConvertTime(expected, zone).DateTime;
|
|
Assert.IsLessThanOrEqualTo(2.0, Math.Abs((actual - local).TotalSeconds), $"{actual} vs {local}");
|
|
}
|
|
|
|
private static async Task<(HttpStatusCode Status, string Message)> TokenAsync(WebTestServer server, object selection)
|
|
{
|
|
var (status, body) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
|
|
return (status, body.ValueKind == JsonValueKind.Object && body.TryGetProperty("message", out var message) ? message.GetString() ?? string.Empty : string.Empty);
|
|
}
|
|
|
|
/// <summary>«Scarica» of a selection that gives a zip: its name and its entries with their times.</summary>
|
|
private async Task<(string? Name, Dictionary<string, DateTime> Entries)> ZipAsync(WebTestServer server, object selection)
|
|
{
|
|
var (status, token) = await server.SendJsonAsync(HttpMethod.Post, "/api/frames/download-token", selection);
|
|
Assert.AreEqual(HttpStatusCode.OK, status, token.ToString());
|
|
using var response = await server.Client.GetAsync(token.Str("url"), TestContext.CancellationToken);
|
|
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
|
Assert.AreEqual("application/zip", response.Content.Headers.ContentType?.MediaType);
|
|
using var archive = new ZipArchive(new MemoryStream(await response.Content.ReadAsByteArrayAsync(TestContext.CancellationToken)), ZipArchiveMode.Read);
|
|
foreach (var entry in archive.Entries)
|
|
{
|
|
Assert.AreEqual(entry.Length, entry.CompressedLength, $"{entry.FullName}: stored, not compressed");
|
|
}
|
|
|
|
return (FileName(response), archive.Entries.ToDictionary(e => e.FullName, e => e.LastWriteTime.DateTime, StringComparer.Ordinal));
|
|
}
|
|
|
|
private static async Task WaitFreeAsync(LongWorkGate gate, string what)
|
|
{
|
|
var watch = System.Diagnostics.Stopwatch.StartNew();
|
|
while (gate.Busy is not null)
|
|
{
|
|
if (watch.Elapsed > TimeSpan.FromSeconds(90))
|
|
{
|
|
Assert.Fail($"the lease of the zip is still held {what}");
|
|
}
|
|
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
|
|
/// <summary>An I_PCM video of noise (it does not compress), 8 pictures per second.</summary>
|
|
private static byte[] NoiseVideo(int width, int height, int pictures)
|
|
{
|
|
var random = new Random(11);
|
|
using var output = new MemoryStream();
|
|
H264PcmWriter.WriteMp4(output, width, height, pictures, 8, _ =>
|
|
{
|
|
var p = new H264PcmPicture(width, height);
|
|
foreach (var plane in new[] { p.Y, p.Cb, p.Cr })
|
|
{
|
|
random.NextBytes(plane);
|
|
for (var i = 0; i < plane.Length; i++)
|
|
{
|
|
plane[i] = (byte)(16 + (plane[i] % 220)); // no zero byte, as in the demo video
|
|
}
|
|
}
|
|
|
|
return p;
|
|
});
|
|
return output.ToArray();
|
|
}
|
|
}
|
|
|
|
/// <summary>Library files and folders of the copies for the web tests of tappa E3, saved as the collection does.</summary>
|
|
internal static class WebLibrary
|
|
{
|
|
public sealed record Item(byte[] Bytes, string Extension, MediaKind Kind);
|
|
|
|
public static Item Video(byte[] bytes) => new(bytes, ".mp4", MediaKind.Video);
|
|
|
|
/// <summary>
|
|
/// The demo's video with its own creation date, so two of them are two files (the same bytes would be one file of the
|
|
/// library in two entries).
|
|
/// </summary>
|
|
public static Item DemoVideo(int day)
|
|
{
|
|
using var output = new MemoryStream();
|
|
H264PcmWriter.WriteMp4(output, H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight, H264PcmWriter.DemoPictures, H264PcmWriter.DemoFps, H264PcmWriter.DemoPicture, new DateTimeOffset(2026, 1, day, 12, 0, 0, TimeSpan.Zero));
|
|
return Video(output.ToArray());
|
|
}
|
|
|
|
public static Item Photo(int scene) => new(TestFile.PhotoBytes(scene, 96, 120), ".jpg", MediaKind.Photo);
|
|
|
|
public static Item Image(byte[] bytes, string extension) => new(bytes, extension, MediaKind.Photo);
|
|
|
|
/// <summary>A post of <paramref name="account"/> with its files on disk and its journal line.</summary>
|
|
public static async Task<EntryWithMedia> AddPostAsync(WebTestServer server, Account account, string code, DateTimeOffset published, params Item[] files)
|
|
{
|
|
var ingest = new LibraryIngest(server.Db, server.Library.Layout, LibraryNaming.Default, server.Library.Journal, server.Clock, server.Library.Thumbnails, new PerceptualHashIndex());
|
|
var added = await server.Db.Entries.AddAsync(
|
|
Make.Entry(account.Id, code, published),
|
|
[.. files.Select((f, i) => f.Kind == MediaKind.Video ? Make.Video(i + 1) : Make.Photo(i + 1))]);
|
|
foreach (var (media, file) in added.Stored.Media.Zip(files))
|
|
{
|
|
await ingest.SaveMediaAsync(account, added.Stored.Entry, media, new MediaContent { Content = new MemoryStream(file.Bytes), Extension = file.Extension });
|
|
}
|
|
|
|
await ingest.AppendJournalAsync(added.Stored.Entry.Id);
|
|
return (await server.Db.Entries.GetWithMediaAsync(added.Stored.Entry.Id))!;
|
|
}
|
|
|
|
/// <summary>The library file of a media of <paramref name="account"/>.</summary>
|
|
public static string PathOf(WebTestServer server, Account account, Media media) =>
|
|
Path.Combine(server.Library.Layout.AccountFolder(account), LibraryLayout.ToPlatform(media.RelativePath!));
|
|
|
|
public static object Destination(string path, string scope = "general", long? accountId = null, string? photoFormat = null, string? videoFormat = null) => new
|
|
{
|
|
scope,
|
|
accountId,
|
|
path,
|
|
label = (string?)null,
|
|
types = new[] { "postFoto", "postVideo", "storie", "evidenza", "taggati", "profilo" },
|
|
namingScheme = (string?)null,
|
|
highlightNamingScheme = (string?)null,
|
|
profileNamingScheme = (string?)null,
|
|
photoFormat,
|
|
videoFormat,
|
|
};
|
|
|
|
public static async Task StartAndWaitAsync(WebTestServer server, object request)
|
|
{
|
|
var (status, job) = await server.SendJsonAsync(HttpMethod.Post, "/api/export/start", request);
|
|
Assert.AreEqual(HttpStatusCode.OK, status, job.ToString());
|
|
Assert.IsNotEmpty(job.Items("runIds").ToList(), job.ToString());
|
|
await WaitIdleAsync(server);
|
|
}
|
|
|
|
public static Task WaitIdleAsync(WebTestServer server) =>
|
|
WaitAsync(async () => !(await server.GetJsonAsync("/api/export/progress")).Bool("running"), "the copy ends");
|
|
|
|
public static async Task WaitAsync(Func<Task<bool>> condition, string what)
|
|
{
|
|
var watch = System.Diagnostics.Stopwatch.StartNew();
|
|
while (!await condition())
|
|
{
|
|
if (watch.Elapsed > TimeSpan.FromSeconds(60))
|
|
{
|
|
Assert.Fail($"not reached: {what}");
|
|
}
|
|
|
|
await Task.Delay(50);
|
|
}
|
|
}
|
|
}
|