feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
CI / Build and test (push) Successful in 9m41s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 14m49s
CI / PostgreSQL 16 integration (push) Successful in 8m51s
CI / PostgreSQL 17 integration (push) Successful in 9m48s
CI / Docker image (push) Successful in 54s
Release / Server image (push) Successful in 1m39s
Owner review 1 R3, R8, R9. A grouped Export step and Render menu; encoding, playback (reverse, boomerang, loops, fades, hold) and still frames; one videos library on the desktop and the server with a verified trash and copies to a videos folder. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #27.
This commit is contained in:
1 parent
188b2c2e55
commit
728ffa35cb
729 files changed
+26954
-1652
No files matched your search
@@ -508,7 +508,7 @@ public sealed class ProjectTests(TestContext context)
|
||||
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
|
||||
using (var anonymous = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests"))
|
||||
Assert.Equal(ProjectSettings.CurrentVersion, (await anonymous.GetInfoAsync(context.Cancellation)).SettingsFormat);
|
||||
Assert.Equal(2, ProjectSettings.CurrentVersion);
|
||||
Assert.Equal(3, ProjectSettings.CurrentVersion);
|
||||
|
||||
var (http, _, token) = await server.UserAsync("alberto", "editor");
|
||||
using var alberto = Client(server, token);
|
||||
@@ -527,8 +527,8 @@ public sealed class ProjectTests(TestContext context)
|
||||
var mirrored = ProjectSettings.FromJson(Assert.NotNull((await server.Database.Sequences.GetAsync(sid))!.SettingsJson));
|
||||
Assert.Equal((90, true, "sepia"), (mirrored.Camera.Rotate, mirrored.Camera.Mirror, mirrored.Look?.Filter), "Main's head is the sequence's settings");
|
||||
|
||||
const string future = """{"version":3,"camera":{"rotate":90}}""";
|
||||
var newer = Version(v3, new ProjectSettings(), home) with { SettingsJson = future, ContentHash = ProjectContent.Hash(future), SettingsFormat = 3 };
|
||||
const string future = """{"version":4,"camera":{"rotate":90}}""";
|
||||
var newer = Version(v3, new ProjectSettings(), home) with { SettingsJson = future, ContentHash = ProjectContent.Hash(future), SettingsFormat = 4 };
|
||||
using (var raw = await http.PostAsJsonAsync($"/api/v1/sequences/{sid}/projects/{main.Id}/versions", newer, ProtocolJson.Default.ProjectVersionDto))
|
||||
await raw.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, ProjectErrors.NewerFormat);
|
||||
Assert.Equal(3, (await alberto.GetProjectAsync(sid, main.Id)).HeadNumber);
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// The wire shapes of the videos library (owner review 1, phase 5): camelCase members, nulls left out, and the members
|
||||
/// added to existing DTOs trailing and optional, so a client or server of before reads and writes them as it did.
|
||||
/// </summary>
|
||||
public sealed class VideoContractTests
|
||||
{
|
||||
private static readonly Guid RenderId = Guid.Parse("01890000-0000-7000-8000-000000000001");
|
||||
private static readonly Guid SequenceId = Guid.Parse("01890000-0000-7000-8000-000000000002");
|
||||
private static readonly DateTimeOffset Created = new(2026, 11, 5, 18, 30, 0, TimeSpan.Zero);
|
||||
|
||||
[Test]
|
||||
public void AVideoTravelsWithItsSequenceStateAndCopies()
|
||||
{
|
||||
var video = new VideoDto(RenderId, SequenceId, "Web 1080p", "h264", 1920, 1080, 25, 12.5, 4_000_000, Created, "PC-A", null, null,
|
||||
new string('a', 64), RenderKind.Video, "Harbour sunset", new DateTime(2026, 10, 1, 18, 0, 0), "Main", 3, VideoStates.Ok,
|
||||
[new VideoCopyDto("/videos/Harbour sunset.mp4", Created)], "Harbour sunset.mp4");
|
||||
var json = JsonNode.Parse(JsonSerializer.Serialize(video, ProtocolJson.Default.VideoDto))!.AsObject();
|
||||
Assert.SequenceEqual(
|
||||
["id", "sequenceId", "presetName", "codec", "width", "height", "fps", "durationSeconds", "bytes", "created", "producedBy", "sha256",
|
||||
"kind", "sequenceTitle", "sequenceFirstCapture", "projectName", "projectVersionNumber", "state", "copies", "fileName"],
|
||||
json.Select(p => p.Key));
|
||||
Assert.Equal("video", json["kind"]!.GetValue<string>());
|
||||
Assert.Equal("/videos/Harbour sunset.mp4", json["copies"]![0]!["path"]!.GetValue<string>());
|
||||
var back = JsonSerializer.Deserialize(json.ToJsonString(), ProtocolJson.Default.VideoDto)!;
|
||||
Assert.Equal(video with { Copies = back.Copies }, back);
|
||||
Assert.Equal(video.Copies[0], back.Copies[0]);
|
||||
|
||||
var page = new VideoPageDto([video], "cursor-2");
|
||||
var pageJson = JsonNode.Parse(JsonSerializer.Serialize(page, ProtocolJson.Default.VideoPageDto))!.AsObject();
|
||||
Assert.SequenceEqual(["items", "next"], pageJson.Select(p => p.Key));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DeletingIsADryRunThenTheSameFingerprint()
|
||||
{
|
||||
var request = JsonSerializer.Serialize(new VideoDeleteRequest([RenderId], DryRun: true), ProtocolJson.Default.VideoDeleteRequest);
|
||||
Assert.Equal($$"""{"ids":["{{RenderId}}"],"dryRun":true}""", request);
|
||||
var real = JsonSerializer.Deserialize("""{ "ids": [], "dryRun": false, "fingerprint": "abc" }""", ProtocolJson.Default.VideoDeleteRequest)!;
|
||||
Assert.Equal((false, "abc"), (real.DryRun, real.Fingerprint));
|
||||
|
||||
var plan = new VideoDeletePlanDto([new VideoDeleteItemDto(RenderId, SequenceId, "Harbour sunset", "a.mp4", 10, Missing: false)], 10,
|
||||
[new VideoBlockedDto(Guid.Empty, VideoBlockReasons.Busy)], "f1", DryRun: true);
|
||||
var json = JsonNode.Parse(JsonSerializer.Serialize(plan, ProtocolJson.Default.VideoDeletePlanDto))!.AsObject();
|
||||
Assert.SequenceEqual(["items", "bytes", "blocked", "fingerprint", "dryRun"], json.Select(p => p.Key));
|
||||
Assert.Equal("busy", json["blocked"]![0]!["reason"]!.GetValue<string>());
|
||||
|
||||
var copy = JsonSerializer.Serialize(new VideoCopyRequest([RenderId]), ProtocolJson.Default.VideoCopyRequest);
|
||||
Assert.Equal($$"""{"ids":["{{RenderId}}"]}""", copy);
|
||||
Assert.Equal(RenderId, JsonSerializer.Deserialize($$"""{"jobId":"{{RenderId}}"}""", ProtocolJson.Default.VideoCopyResultDto)!.JobId);
|
||||
Assert.Equal("videos", ServerCapabilities.Videos);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheMembersAddedToOlderDtosAreLeftOutUntilSet()
|
||||
{
|
||||
var render = new RenderDto(RenderId, "MJPEG", "mjpeg", 96, 64, 25, 1, 10, Created, null);
|
||||
var renderJson = JsonSerializer.Serialize(render, ProtocolJson.Default.RenderDto);
|
||||
Assert.False(renderJson.Contains("sha256", StringComparison.Ordinal) || renderJson.Contains("kind", StringComparison.Ordinal), renderJson);
|
||||
var hashed = JsonNode.Parse(JsonSerializer.Serialize(render with { Sha256 = "ab", Kind = RenderKind.Still }, ProtocolJson.Default.RenderDto))!;
|
||||
Assert.Equal(("ab", "still"), (hashed["sha256"]!.GetValue<string>(), hashed["kind"]!.GetValue<string>()));
|
||||
|
||||
var parameters = new RenderJobParameters("MJPEG", "{}", "mjpeg", 96, 64, false, null);
|
||||
var parametersJson = JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters);
|
||||
Assert.False(parametersJson.Contains("still", StringComparison.OrdinalIgnoreCase), parametersJson);
|
||||
Assert.False(parameters.IsStill);
|
||||
var still = JsonSerializer.Deserialize(
|
||||
JsonSerializer.Serialize(parameters with { StillFrame = 41, StillPhoto = "cd", RequiredSettingsFormat = 3 }, ProtocolJson.Default.RenderJobParameters),
|
||||
ProtocolJson.Default.RenderJobParameters)!;
|
||||
Assert.Equal(((int?)41, "cd", 3, true), (still.StillFrame, still.StillPhoto, still.RequiredSettingsFormat, still.IsStill));
|
||||
|
||||
var result = JsonSerializer.Deserialize("""{ "fileName": "a.png", "size": 1, "sha256": "ab", "presetName": "PNG", "width": 1, "height": 1, "fps": 0, "durationSeconds": 0 }""",
|
||||
ProtocolJson.Default.RenderResultRequest)!;
|
||||
Assert.Null(result.Kind);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheLibraryStubAnswersEmptyUntilTheLibraryLands()
|
||||
{
|
||||
var stub = NotImplementedVideoLibrary.Instance;
|
||||
Assert.False(stub.IsAvailable);
|
||||
Assert.Equal(VideoErrors.FolderUnset, stub.FolderProblem(" "));
|
||||
Assert.Null(stub.FolderProblem("/videos"));
|
||||
Assert.Empty(stub.ListAsync(new VideoQuery()).GetAwaiter().GetResult().Items);
|
||||
Assert.Null(stub.GetAsync(RenderId).GetAwaiter().GetResult());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TrashEntriesAndCopyParametersReadBack()
|
||||
{
|
||||
var name = VideoTrashNames.EntryName(RenderId, Created);
|
||||
Assert.True(name.StartsWith(VideoTrashNames.Prefix, StringComparison.Ordinal));
|
||||
Assert.True(VideoTrashNames.TryParse(name, out var id, out var ticks));
|
||||
Assert.Equal((RenderId, Created.UtcTicks), (id, ticks));
|
||||
Assert.False(VideoTrashNames.IsEntryName($"sequence-{RenderId}"));
|
||||
Assert.False(VideoTrashNames.IsEntryName(null));
|
||||
Assert.Equal("videos", TrashKind.Videos.ToString().ToLowerInvariant());
|
||||
|
||||
var parameters = new VideoCopyParameters([RenderId], "/videos", FromServer: true, RequestedBy: "alberto");
|
||||
var back = Assert.NotNull(VideoCopyParameters.Read(parameters.ToJson()));
|
||||
Assert.Equal((parameters.Folder, parameters.FromServer, parameters.RequestedBy), (back.Folder, back.FromServer, back.RequestedBy));
|
||||
Assert.SequenceEqual(parameters.RenderIds, back.RenderIds);
|
||||
Assert.Null(VideoCopyParameters.Read("not json"));
|
||||
Assert.Equal(24, (int)JobKind.VideoCopy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Videos;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Storage;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Api;
|
||||
|
||||
/// <summary>
|
||||
/// <c>/api/v1/videos</c> (owner review 1, phase 5, R9) against a library that answers what each test sets: who may read,
|
||||
/// delete and copy, the dry run and its fingerprint, the videos folder, the audit entries, a video restored through the
|
||||
/// trash routes, and the protocol client's calls.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed class VideoEndpointTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task ReadersListAndPlayEditorsCopyAndDeleters()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library);
|
||||
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
|
||||
var (uploader, _, _) = await server.UserAsync("ugo", "uploader");
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var render = await RenderAsync(server, editor, library);
|
||||
|
||||
using (var anonymous = await server.Client.GetAsync("/api/v1/videos")) await anonymous.ExpectAsync(HttpStatusCode.Unauthorized);
|
||||
using (var refused = await uploader.GetAsync("/api/v1/videos")) await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
using (var listed = await viewer.GetAsync("/api/v1/videos"))
|
||||
{
|
||||
var page = await listed.ReadAsync(ProtocolJson.Default.VideoPageDto);
|
||||
var video = page.Items.Single();
|
||||
Assert.Equal((render.Id, "Harbour sunset", RenderKind.Video, VideoStates.Ok, "Harbour sunset - 4K.mp4"),
|
||||
(video.Id, video.SequenceTitle, video.Kind, video.State, video.FileName));
|
||||
Assert.Equal("/videos/Harbour sunset - 4K.mp4", video.Copies.Single().Path);
|
||||
}
|
||||
using (var one = await viewer.GetAsync($"/api/v1/videos/{render.Id}"))
|
||||
Assert.Equal(render.Sha256, (await one.ReadAsync(ProtocolJson.Default.VideoDto)).Sha256);
|
||||
using (var unknown = await viewer.GetAsync($"/api/v1/videos/{Guid.CreateVersion7()}"))
|
||||
Assert.Equal("render", (await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
|
||||
// A reader plays the file: a <video> seeks with Range requests.
|
||||
using var range = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/renders/{render.Id}/file");
|
||||
range.Headers.Range = new RangeHeaderValue(10, 19);
|
||||
using (var partial = await viewer.SendAsync(range))
|
||||
{
|
||||
await partial.ExpectAsync(HttpStatusCode.PartialContent);
|
||||
Assert.Equal(("video/mp4", 10L), (partial.Content.Headers.ContentType!.MediaType, partial.Content.Headers.ContentLength!.Value));
|
||||
}
|
||||
|
||||
// Deleting needs Delete, copying Edit: a viewer has neither.
|
||||
var plan = new VideoDeleteRequest([render.Id], DryRun: true);
|
||||
using (var refused = await viewer.PostAsJsonAsync("/api/v1/videos/delete", plan, ProtocolJson.Default.VideoDeleteRequest))
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
using (var refused = await viewer.PostAsJsonAsync("/api/v1/videos/copy", new VideoCopyRequest([render.Id]), ProtocolJson.Default.VideoCopyRequest))
|
||||
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
using (var planned = await editor.PostAsJsonAsync("/api/v1/videos/delete", plan, ProtocolJson.Default.VideoDeleteRequest))
|
||||
await planned.ExpectAsync(HttpStatusCode.OK);
|
||||
Assert.Empty(library.Deleted);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheListPassesItsFiltersAndRefusesUnknownOnes()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library);
|
||||
var (viewer, _, _) = await server.UserAsync("marco", "viewer");
|
||||
var sequence = Guid.CreateVersion7();
|
||||
using (var listed = await viewer.GetAsync($"/api/v1/videos?q=+harbour+&kind=Still&codec=png&year=2026&sequence={sequence}&sort=largest&limit=900"))
|
||||
await listed.ExpectAsync(HttpStatusCode.OK);
|
||||
var query = library.Queries.Single();
|
||||
Assert.Equal(("harbour", RenderKind.Still, "png", (int?)2026, (Guid?)sequence, VideoSorts.Largest, VideoQuery.MaxLimit),
|
||||
(query.Text, query.Kind, query.Codec, query.Year, query.SequenceId, query.Sort, query.Limit));
|
||||
|
||||
foreach (var (filter, details) in new[] { ("kind=film", "kind"), ("sort=random", "sort"), ("year=0", "year") })
|
||||
{
|
||||
using var refused = await viewer.GetAsync("/api/v1/videos?" + filter);
|
||||
Assert.Equal(details, (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_filter")).Details);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ADeleteIsTheDryRunThenItsFingerprintAndIsAudited()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var render = await RenderAsync(server, editor, library);
|
||||
var gone = Guid.CreateVersion7();
|
||||
var ids = new[] { render.Id, gone, render.Id };
|
||||
|
||||
using (var planned = await editor.PostAsJsonAsync("/api/v1/videos/delete", new VideoDeleteRequest(ids, DryRun: true), ProtocolJson.Default.VideoDeleteRequest))
|
||||
{
|
||||
var plan = await planned.ReadAsync(ProtocolJson.Default.VideoDeletePlanDto);
|
||||
Assert.Equal((true, FakeVideoLibrary.Fingerprint, render.Bytes), (plan.DryRun, plan.Fingerprint, plan.Bytes));
|
||||
Assert.Equal((render.Id, "Harbour sunset", false), (plan.Items.Single().Id, plan.Items.Single().SequenceTitle, plan.Items.Single().Missing));
|
||||
Assert.Equal((gone, VideoBlockReasons.NotFound), (plan.Blocked.Single().Id, plan.Blocked.Single().Reason));
|
||||
Assert.Null(plan.TrashEntries);
|
||||
}
|
||||
// Each id once, in order.
|
||||
Assert.SequenceEqual([render.Id, gone], library.Planned.Single());
|
||||
|
||||
using (var unsigned = await editor.PostAsJsonAsync("/api/v1/videos/delete", new VideoDeleteRequest(ids, DryRun: false), ProtocolJson.Default.VideoDeleteRequest))
|
||||
Assert.Equal("fingerprint", (await unsigned.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
||||
using (var changed = await editor.PostAsJsonAsync("/api/v1/videos/delete", new VideoDeleteRequest(ids, false, "older"), ProtocolJson.Default.VideoDeleteRequest))
|
||||
await changed.ExpectErrorAsync(HttpStatusCode.Conflict, VideoErrors.PlanChanged);
|
||||
Assert.Empty(library.Deleted);
|
||||
foreach (var bad in new[] { Array.Empty<Guid>(), [Guid.Empty], [.. Enumerable.Range(0, VideoEndpoints.MaxIds + 1).Select(_ => Guid.CreateVersion7())] })
|
||||
{
|
||||
using var refused = await editor.PostAsJsonAsync("/api/v1/videos/delete", new VideoDeleteRequest(bad, DryRun: true), ProtocolJson.Default.VideoDeleteRequest);
|
||||
Assert.Equal("ids", (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "bad_request")).Details);
|
||||
}
|
||||
|
||||
using (var deleted = await editor.PostAsJsonAsync("/api/v1/videos/delete", new VideoDeleteRequest(ids, false, FakeVideoLibrary.Fingerprint),
|
||||
ProtocolJson.Default.VideoDeleteRequest))
|
||||
{
|
||||
var result = await deleted.ReadAsync(ProtocolJson.Default.VideoDeletePlanDto);
|
||||
Assert.Equal((false, render.Id, 1), (result.DryRun, result.Items.Single().Id, result.Blocked.Count));
|
||||
Assert.True(VideoTrashNames.IsEntryName(Assert.NotNull(result.TrashEntries).Single()));
|
||||
}
|
||||
Assert.Equal("alberto", library.Deleted.Single().By);
|
||||
var audit = Assert.Contains((await server.Database.Audit.ListByActionsAsync(null, ["videos_deleted"], 10, null)).Items, a => a.Action == "videos_deleted");
|
||||
Assert.Equal(("videos", render.Id.ToString(), "alberto"), (audit.TargetKind, audit.TargetId, audit.Username));
|
||||
Assert.Contains("Harbour sunset - 4K.mp4", audit.Details);
|
||||
|
||||
// A library that refuses tells why.
|
||||
library.Refusal = VideoErrors.Busy;
|
||||
using var busy = await editor.PostAsJsonAsync("/api/v1/videos/delete", new VideoDeleteRequest(ids, false, FakeVideoLibrary.Fingerprint),
|
||||
ProtocolJson.Default.VideoDeleteRequest);
|
||||
await busy.ExpectErrorAsync(HttpStatusCode.Conflict, VideoErrors.Busy);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACopyNeedsAVideosFolderOutsideTheArchiveAndIsOneAuditedJob()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library, s =>
|
||||
{
|
||||
s.AddSingleton<IJobHandler>(new CopyHandler());
|
||||
s.AddSingleton<FakeVolumeSpace>();
|
||||
s.AddSingleton<VolumeSpace>(sp => sp.GetRequiredService<FakeVolumeSpace>());
|
||||
});
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var render = await RenderAsync(server, editor, library);
|
||||
var request = new VideoCopyRequest([render.Id]);
|
||||
|
||||
using (var unset = await editor.PostAsJsonAsync("/api/v1/videos/copy", request, ProtocolJson.Default.VideoCopyRequest))
|
||||
await unset.ExpectErrorAsync(HttpStatusCode.Conflict, VideoErrors.FolderUnset);
|
||||
foreach (var inside in new[] { server.Options.ArchivePath, Path.Combine(server.Options.ArchivePath, "videos"), Path.Combine(server.Options.DataPath, "videos") })
|
||||
{
|
||||
server.Options.VideosPath = inside;
|
||||
using var invalid = await editor.PostAsJsonAsync("/api/v1/videos/copy", request, ProtocolJson.Default.VideoCopyRequest);
|
||||
await invalid.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, VideoErrors.FolderInvalid);
|
||||
}
|
||||
var folder = context.CreateTempDirectory("videos");
|
||||
server.Options.VideosPath = folder;
|
||||
using (var unknown = await editor.PostAsJsonAsync("/api/v1/videos/copy", new VideoCopyRequest([render.Id, Guid.CreateVersion7()]), ProtocolJson.Default.VideoCopyRequest))
|
||||
Assert.Equal("render", (await unknown.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
var volumes = server.Services.GetRequiredService<FakeVolumeSpace>();
|
||||
volumes.Set(folder, new VolumeFigures(render.Bytes - 1, 1L << 40));
|
||||
using (var full = await editor.PostAsJsonAsync("/api/v1/videos/copy", request, ProtocolJson.Default.VideoCopyRequest))
|
||||
await full.ExpectErrorAsync(HttpStatusCode.InsufficientStorage, VideoErrors.NoSpace);
|
||||
volumes.Set(folder, null);
|
||||
Assert.Empty(library.Copies);
|
||||
|
||||
Guid jobId;
|
||||
using (var queued = await editor.PostAsJsonAsync("/api/v1/videos/copy", request, ProtocolJson.Default.VideoCopyRequest))
|
||||
{
|
||||
await queued.ExpectAsync(HttpStatusCode.Accepted);
|
||||
jobId = (await queued.ReadAsync(ProtocolJson.Default.VideoCopyResultDto)).JobId;
|
||||
}
|
||||
var parameters = library.Copies.Single();
|
||||
Assert.Equal((folder, false, "alberto"), (parameters.Folder, parameters.FromServer, parameters.RequestedBy));
|
||||
Assert.SequenceEqual([render.Id], parameters.RenderIds);
|
||||
var job = Assert.NotNull(await server.Database.Jobs.GetAsync(jobId));
|
||||
Assert.Equal(JobKind.VideoCopy, job.Kind);
|
||||
Assert.Equal(parameters.Folder, Assert.NotNull(VideoCopyParameters.Read(job.ParametersJson)).Folder);
|
||||
var audit = Assert.Contains((await server.Database.Audit.ListByActionsAsync(null, ["videos_copied"], 10, null)).Items, a => a.Action == "videos_copied");
|
||||
Assert.Equal(("job", jobId.ToString()), (audit.TargetKind, audit.TargetId));
|
||||
Assert.Contains("Harbour sunset - 4K.mp4", audit.Details);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WithoutACopyHandlerTheCopyIsRefusedAsUnavailable()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var render = await RenderAsync(server, editor, library);
|
||||
server.Options.VideosPath = context.CreateTempDirectory("videos");
|
||||
using var refused = await editor.PostAsJsonAsync("/api/v1/videos/copy", new VideoCopyRequest([render.Id]), ProtocolJson.Default.VideoCopyRequest);
|
||||
Assert.Equal("video-copy", (await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "job_unavailable")).Details);
|
||||
Assert.Empty(library.Copies);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheServerAnnouncesVideosAndFormatThreeAndKeepsItsVideosFolder()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
using (var info = await server.Client.GetAsync("/api/v1/server/info"))
|
||||
{
|
||||
var announced = await info.ReadAsync(ProtocolJson.Default.ServerInfo);
|
||||
Assert.Contains(ServerCapabilities.Videos, announced.Capabilities);
|
||||
Assert.Equal(3, ProjectSettings.CurrentVersion);
|
||||
Assert.Equal(ProjectSettings.CurrentVersion, announced.SettingsFormat);
|
||||
}
|
||||
|
||||
var admin = await server.AdminAsync();
|
||||
ServerSettingsDto settings;
|
||||
using (var read = await admin.GetAsync("/api/v1/server/settings")) settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
Assert.Null(settings.VideosPath);
|
||||
Assert.Contains("video-copy", settings.JobPriorities.Select(p => p.Kind));
|
||||
|
||||
var folder = context.CreateTempDirectory("videos");
|
||||
using (var saved = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { VideosPath = " " + folder + " " }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Equal(folder, (await saved.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).VideosPath);
|
||||
Assert.Equal(folder, server.Options.VideosPath);
|
||||
Assert.Equal(folder, JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!["VideosPath"]!.GetValue<string>());
|
||||
|
||||
// A client of before sends none: the folder stays. An empty text clears it.
|
||||
using (var kept = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { VideosPath = null, ServerName = "Rooftop" }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Equal(folder, (await kept.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).VideosPath);
|
||||
foreach (var refusedPath in new[] { "videos", Path.Combine(server.Options.ArchivePath, "videos"), server.Options.DataPath })
|
||||
{
|
||||
using var refused = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { VideosPath = refusedPath }, ProtocolJson.Default.ServerSettingsDto);
|
||||
Assert.Equal("VideosPath", (await refused.ExpectErrorAsync(HttpStatusCode.BadRequest, "invalid_setting")).Details);
|
||||
}
|
||||
using (var cleared = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { VideosPath = "" }, ProtocolJson.Default.ServerSettingsDto))
|
||||
Assert.Null((await cleared.ReadAsync(ProtocolJson.Default.ServerSettingsDto)).VideosPath);
|
||||
Assert.Null(server.Options.VideosPath);
|
||||
Assert.Null(JsonNode.Parse(await File.ReadAllTextAsync(server.Options.SettingsFile))!["VideosPath"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVideosFolderSetByTheEnvironmentIsLocked()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context, o =>
|
||||
{
|
||||
o.VideosPath = "/videos";
|
||||
o.Locked = [nameof(ServerOptions.VideosPath)];
|
||||
o.LockedBy = new Dictionary<string, string> { [nameof(ServerOptions.VideosPath)] = "CHRONOS_VIDEOS_PATH" };
|
||||
});
|
||||
var admin = await server.AdminAsync();
|
||||
ServerSettingsDto settings;
|
||||
using (var read = await admin.GetAsync("/api/v1/server/settings")) settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
|
||||
Assert.Equal(("/videos", "CHRONOS_VIDEOS_PATH"), (settings.VideosPath, settings.LockedBy["VideosPath"]));
|
||||
using (var same = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { ServerName = "Rooftop" }, ProtocolJson.Default.ServerSettingsDto))
|
||||
await same.ExpectAsync(HttpStatusCode.OK);
|
||||
using var locked = await admin.PutAsJsonAsync("/api/v1/server/settings", settings with { VideosPath = "" }, ProtocolJson.Default.ServerSettingsDto);
|
||||
Assert.Equal("VideosPath", (await locked.ExpectErrorAsync(HttpStatusCode.Conflict, "setting_locked")).Details);
|
||||
|
||||
// The variable locks the folder; it must be absolute.
|
||||
var absolute = OperatingSystem.IsWindows() ? @"D:\Videos" : "/videos";
|
||||
Dictionary<string, string?> Environment(string videos) => new()
|
||||
{
|
||||
["CHRONOS_DATA_PATH"] = context.CreateTempDirectory("data"),
|
||||
["CHRONOS_VIDEOS_PATH"] = videos,
|
||||
};
|
||||
var options = ServerOptions.Load(Environment(absolute));
|
||||
Assert.Equal((absolute, "CHRONOS_VIDEOS_PATH"), (options.VideosPath, options.LockedBy[nameof(ServerOptions.VideosPath)]));
|
||||
Assert.Throws<InvalidOperationException>(() => ServerOptions.Load(Environment("videos")));
|
||||
Assert.Contains("CHRONOS_VIDEOS_PATH", ServerOptions.EnvironmentVariables);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AVideoComesBackThroughTheTrashRoutes()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var render = await RenderAsync(server, editor, library);
|
||||
var admin = await server.AdminAsync();
|
||||
var entry = VideoTrashNames.EntryName(render.Id, DateTimeOffset.UtcNow);
|
||||
Assert.True(TrashEndpoints.IsEntryName(entry));
|
||||
Assert.False(TrashEndpoints.IsEntryName("videos-" + render.Id + "-../1"));
|
||||
|
||||
using (var refused = await editor.PostAsync($"/api/v1/archive/trash/{entry}/restore", null)) await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
|
||||
foreach (var (code, status) in new[] { (VideoErrors.HashMismatch, HttpStatusCode.UnprocessableEntity), (VideoErrors.SequenceGone, HttpStatusCode.Conflict) })
|
||||
{
|
||||
library.Refusal = code;
|
||||
using var refused = await admin.PostAsync($"/api/v1/archive/trash/{entry}/restore", null);
|
||||
await refused.ExpectErrorAsync(status, code);
|
||||
}
|
||||
library.Refusal = null;
|
||||
using (var missing = await admin.PostAsync($"/api/v1/archive/trash/{VideoTrashNames.EntryName(Guid.CreateVersion7(), DateTimeOffset.UtcNow)}/restore", null))
|
||||
Assert.Equal("trash_entry", (await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
|
||||
|
||||
using (var restored = await admin.PostAsync($"/api/v1/archive/trash/{entry}/restore", null))
|
||||
{
|
||||
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
|
||||
Assert.Equal((entry, "videos", render.SequenceId, 1), (result.Name, result.Kind, result.SequenceId, result.Photos));
|
||||
}
|
||||
Assert.Equal(entry, library.Restored.Single());
|
||||
var audit = Assert.Contains((await server.Database.Audit.ListByActionsAsync(null, ["trash_restored"], 10, null)).Items, a => a.TargetKind == "render");
|
||||
Assert.Equal(render.Id.ToString(), audit.TargetId);
|
||||
|
||||
// Emptying names a video entry like any other.
|
||||
using var plan = await admin.PostAsJsonAsync("/api/v1/archive/trash/empty", new TrashEmptyRequest([entry], DryRun: true, Fingerprint: null), ProtocolJson.Default.TrashEmptyRequest);
|
||||
await plan.ExpectAsync(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheProtocolClientCallsEveryVideoEndpoint()
|
||||
{
|
||||
var library = new FakeVideoLibrary();
|
||||
await using var server = await StartAsync(library, s => s.AddSingleton<IJobHandler>(new CopyHandler()));
|
||||
var (editor, _, token) = await server.UserAsync("alberto", "editor");
|
||||
var render = await RenderAsync(server, editor, library);
|
||||
using var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), "tests") { Token = token };
|
||||
|
||||
var page = await client.ListVideosAsync(new VideoQueryDto(Kind: RenderKind.Video, Sequence: render.SequenceId, Limit: 10), context.Cancellation);
|
||||
Assert.Equal(render.Id, page.Items.Single().Id);
|
||||
Assert.Equal((RenderKind.Video, (Guid?)render.SequenceId, 10), (library.Queries.Single().Kind, library.Queries.Single().SequenceId, library.Queries.Single().Limit));
|
||||
Assert.Equal("Harbour sunset", (await client.GetVideoAsync(render.Id, context.Cancellation)).SequenceTitle);
|
||||
var missing = await Assert.ThrowsAsync<ChronosApiException>(() => client.GetVideoAsync(Guid.CreateVersion7(), context.Cancellation));
|
||||
Assert.Equal(HttpStatusCode.NotFound, missing.Status);
|
||||
|
||||
var plan = await client.PlanDeleteVideosAsync([render.Id], context.Cancellation);
|
||||
var changed = await Assert.ThrowsAsync<ChronosApiException>(() => client.DeleteVideosAsync([render.Id], "older", context.Cancellation));
|
||||
Assert.Equal((HttpStatusCode.Conflict, VideoErrors.PlanChanged), (changed.Status, changed.Error.Code));
|
||||
var deleted = await client.DeleteVideosAsync([render.Id], plan.Fingerprint, context.Cancellation);
|
||||
Assert.Equal(render.Id, deleted.Items.Single().Id);
|
||||
|
||||
var unset = await Assert.ThrowsAsync<ChronosApiException>(() => client.CopyVideosAsync([render.Id], context.Cancellation));
|
||||
Assert.Equal(VideoErrors.FolderUnset, unset.Error.Code);
|
||||
server.Options.VideosPath = context.CreateTempDirectory("videos");
|
||||
var copy = await client.CopyVideosAsync([render.Id], context.Cancellation);
|
||||
Assert.NotEqual(Guid.Empty, copy.JobId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASentRenderKeepsItsHashAndKind()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var (editor, _, _) = await server.UserAsync("alberto", "editor");
|
||||
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(1000, 91));
|
||||
var output = Uploads.Photo(3000, 92);
|
||||
var request = new RenderUploadRequest(Guid.CreateVersion7(), "Roof - 0042.png", output.Length, Uploads.Sha(output).ToUpperInvariant(), "PNG", "png",
|
||||
1920, 1080, 0, 0, null, Kind: RenderKind.Still);
|
||||
using var started = await editor.PostAsJsonAsync($"/api/v1/sequences/{frame.SequenceId}/renders", request, ProtocolJson.Default.RenderUploadRequest);
|
||||
var upload = Assert.NotNull((await started.ReadAsync(ProtocolJson.Default.StartUploadResponse)).UploadId);
|
||||
using (var put = await Uploads.PutChunkAsync(editor, upload, 0, output)) await put.ExpectAsync(HttpStatusCode.OK);
|
||||
using var complete = await editor.PostAsync($"/api/v1/sequences/{frame.SequenceId}/renders/{upload}/complete", null);
|
||||
var render = await complete.ReadAsync(ProtocolJson.Default.RenderDto);
|
||||
Assert.Equal((Uploads.Sha(output), RenderKind.Still), (render.Sha256, render.Kind));
|
||||
|
||||
Assert.Equal(RenderKind.Still, RenderStore.KindOf(" Still "));
|
||||
foreach (var plain in new[] { null, "", "video", "sequence", "../x", new string('a', 33) }) Assert.Null(RenderStore.KindOf(plain));
|
||||
Assert.Equal("timelapse-loop", RenderStore.KindOf("timelapse-loop"));
|
||||
var listed = Dto.Render(new Render { Id = render.Id, SequenceId = frame.SequenceId, PresetName = "PNG", OutputPath = "a.png", Sha256 = "ab", Kind = RenderKind.Still });
|
||||
Assert.Equal(("ab", RenderKind.Still), (listed.Sha256, listed.Kind));
|
||||
}
|
||||
|
||||
private Task<TestServer> StartAsync(FakeVideoLibrary library, Action<IServiceCollection>? services = null) =>
|
||||
TestServer.StartAsync(context, null, s =>
|
||||
{
|
||||
s.AddSingleton<IVideoLibrary>(library);
|
||||
services?.Invoke(s);
|
||||
});
|
||||
|
||||
/// <summary>A sequence with one render file in its exports, the render indexed and known to <paramref name="library"/>.</summary>
|
||||
private static async Task<Render> RenderAsync(TestServer server, HttpClient editor, FakeVideoLibrary library)
|
||||
{
|
||||
var frame = await Uploads.UploadAsync(editor, Uploads.Photo(1000, 93));
|
||||
var sequence = (await server.Database.Sequences.GetAsync(frame.SequenceId))!;
|
||||
var bytes = Uploads.Photo(4096, 94);
|
||||
var relative = $"{sequence.Folder}/exports/Harbour sunset - 4K.mp4";
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(server.Options.ArchivePath, relative))!);
|
||||
await File.WriteAllBytesAsync(Path.Combine(server.Options.ArchivePath, relative), bytes);
|
||||
var render = new Render
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = sequence.Id,
|
||||
PresetName = "4K HEVC",
|
||||
OutputPath = relative,
|
||||
Codec = "hevc",
|
||||
Width = 3840,
|
||||
Height = 2160,
|
||||
Fps = 30,
|
||||
DurationSeconds = 4,
|
||||
Bytes = bytes.Length,
|
||||
Created = DateTimeOffset.UtcNow,
|
||||
Sha256 = Uploads.Sha(bytes),
|
||||
};
|
||||
await server.Database.Renders.InsertAsync(render);
|
||||
library.Add(new VideoItem
|
||||
{
|
||||
Render = render,
|
||||
SequenceTitle = "Harbour sunset",
|
||||
FullPath = Path.Combine(server.Options.ArchivePath, relative),
|
||||
Copies = [new RenderCopy { Id = Guid.CreateVersion7(), RenderId = render.Id, Path = "/videos/Harbour sunset - 4K.mp4", CopiedAt = DateTimeOffset.UtcNow }],
|
||||
});
|
||||
return render;
|
||||
}
|
||||
|
||||
/// <summary>Copies nothing: the job just finishes.</summary>
|
||||
private sealed class CopyHandler : IJobHandler
|
||||
{
|
||||
public JobKind Kind => JobKind.VideoCopy;
|
||||
|
||||
public Task RunAsync(JobContext context) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>A videos library of the items a test adds, whose plans have one fingerprint and which refuses with <see cref="Refusal"/>.</summary>
|
||||
private sealed class FakeVideoLibrary : IVideoLibrary
|
||||
{
|
||||
public const string Fingerprint = "plan-1";
|
||||
|
||||
private readonly ConcurrentDictionary<Guid, VideoItem> _items = new();
|
||||
|
||||
public ConcurrentQueue<VideoQuery> Queries { get; } = new();
|
||||
public ConcurrentQueue<IReadOnlyList<Guid>> Planned { get; } = new();
|
||||
public ConcurrentQueue<(IReadOnlyList<Guid> Ids, string? By)> Deleted { get; } = new();
|
||||
public ConcurrentQueue<string> Restored { get; } = new();
|
||||
public ConcurrentQueue<VideoCopyParameters> Copies { get; } = new();
|
||||
|
||||
/// <summary>When set, deletes and restores are refused with this code.</summary>
|
||||
public string? Refusal { get; set; }
|
||||
|
||||
public bool IsAvailable => true;
|
||||
|
||||
public void Add(VideoItem item) => _items[item.Render.Id] = item;
|
||||
|
||||
public Task<VideoPage> ListAsync(VideoQuery query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Queries.Enqueue(query);
|
||||
return Task.FromResult(new VideoPage([.. _items.Values.Where(i => query.SequenceId is null || i.Render.SequenceId == query.SequenceId)], null, _items.Count));
|
||||
}
|
||||
|
||||
public Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(_items.TryGetValue(renderId, out var item) ? item : null);
|
||||
|
||||
public Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Planned.Enqueue(renderIds);
|
||||
return Task.FromResult(Plan(renderIds));
|
||||
}
|
||||
|
||||
public Task<VideoDeleteResult> DeleteAsync(IReadOnlyList<Guid> renderIds, string fingerprint, string? deletedBy, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Refusal is { } code) throw new VideoLibraryException(code, code);
|
||||
if (fingerprint != Fingerprint) throw new VideoLibraryException(VideoErrors.PlanChanged, "changed");
|
||||
var plan = Plan(renderIds);
|
||||
Deleted.Enqueue((renderIds, deletedBy));
|
||||
return Task.FromResult(new VideoDeleteResult(plan.Items, plan.Blocked, [.. plan.Items.Select(i => VideoTrashNames.EntryName(i.Render.Id, DateTimeOffset.UtcNow))]));
|
||||
}
|
||||
|
||||
public Task<Render> RestoreAsync(Guid archiveId, string entryName, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Refusal is { } code) throw new VideoLibraryException(code, code);
|
||||
if (!VideoTrashNames.TryParse(entryName, out var id, out _) || !_items.TryGetValue(id, out var item)) throw new DirectoryNotFoundException(entryName);
|
||||
Restored.Enqueue(entryName);
|
||||
return Task.FromResult(item.Render);
|
||||
}
|
||||
|
||||
public string? FolderProblem(string? folder) => string.IsNullOrWhiteSpace(folder) ? VideoErrors.FolderUnset : null;
|
||||
|
||||
public ArchiveJobRequest CopyJob(VideoCopyParameters parameters)
|
||||
{
|
||||
Copies.Enqueue(parameters);
|
||||
return new ArchiveJobRequest(JobKind.VideoCopy, parameters.RenderIds, "videos", parameters.ToJson(), JobPriority.Normal);
|
||||
}
|
||||
|
||||
private VideoDeletePlan Plan(IReadOnlyList<Guid> ids) => new(
|
||||
[.. ids.Where(_items.ContainsKey).Select(id => _items[id])],
|
||||
[.. ids.Where(id => !_items.ContainsKey(id)).Select(id => new VideoBlocked(id, VideoBlockReasons.NotFound))],
|
||||
Fingerprint);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// The Videos page of the admin panel (owner review 1, R9, decision 22; <c>Admin/web/pages/videos.js</c>): in the menu after
|
||||
/// the Library, what it imports and calls (the videos API, never an edit or a render: owner review 2, R6), the delete's dry
|
||||
/// run before the move with the plan's fingerprint, Copy's reasons when it is off, the player, and its strings; and what the
|
||||
/// Trash, a sequence and Settings show of the videos library.
|
||||
/// </summary>
|
||||
[Category("server")]
|
||||
public sealed partial class AdminVideosTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task TheVideosPageIsInTheMenuAfterTheLibraryAndLoads()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var app = await server.Client.GetStringAsync("/admin/app.js");
|
||||
var top = Regex.Match(app, @"const topPages = \[([^\]]*)\]").Groups[1].Value.Split(',').Select(p => p.Trim().Trim('"')).ToList();
|
||||
Assert.Equal(top.IndexOf("library") + 1, top.IndexOf("videos"));
|
||||
Assert.Contains(" videos: `<svg", await server.Client.GetStringAsync("/admin/icons.js"));
|
||||
|
||||
using var response = await server.Client.GetAsync("/admin/pages/videos.js");
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType);
|
||||
var page = await response.Content.ReadAsStringAsync();
|
||||
Assert.Contains("export async function render(root, { api, setMeta, actions, onEvent })", page);
|
||||
var imports = StaticImport().Matches(page).Select(m => m.Groups[1].Value).ToList();
|
||||
Assert.SequenceEqual(["../i18n.js", "../ui.js", "../icons.js", "./library/shared.js"], imports);
|
||||
// The panel runs under a strict CSP: no inline handlers or styles.
|
||||
Assert.True(!Regex.IsMatch(page, @"\son[a-z]+="""), "inline handler");
|
||||
Assert.True(!page.Contains(" style=", StringComparison.Ordinal), "inline style");
|
||||
// A sequence's renders name their kind and hash as the Videos page does.
|
||||
foreach (var helper in new[] { "videoKind(v)", "kindText(kind)", "codecLabel(codec)", "shortHash(sha256)" })
|
||||
Assert.Contains($"export function {helper}", page);
|
||||
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
Assert.Contains(@"import { videoKind, kindText, shortHash } from ""../videos.js"";", sequence);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheVideosPageManagesAndNeverEdits()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
|
||||
var calls = ApiCall().Matches(page).Select(m => (Method: m.Groups[1].Value, Target: m.Groups[2].Value)).ToList();
|
||||
Assert.True(calls.Count >= 4, string.Join(", ", calls));
|
||||
// Reads the list, the server's videos folder and a filtered sequence's title; writes only the videos' delete and copy:
|
||||
// no settings, no project, no render, no job of its own.
|
||||
foreach (var (method, target) in calls)
|
||||
{
|
||||
Assert.True(method is "get" or "post", $"api.{method}({target}");
|
||||
if (method == "get") Assert.True(target is "listQuery(" or @"""/api/v1/server/settings""" or "`/api/v1/sequences/${encodeURIComponent(id)}`", target);
|
||||
else Assert.True(target is @"""/api/v1/videos/copy""" or @"""/api/v1/videos/delete""", target);
|
||||
}
|
||||
Assert.Contains("return `/api/v1/videos?${p}`;", page);
|
||||
foreach (var never in new[] { "settingsJson", "/projects", "/jobs\"", "api.put(", "api.patch(", "api.del(" })
|
||||
Assert.False(page.Contains(never, StringComparison.Ordinal), never);
|
||||
// A render's file is read (play, download); nothing asks for a render.
|
||||
Assert.False(Regex.IsMatch(page, "/render(?!s/)"), "a render request");
|
||||
|
||||
// Delete: the dry run, the confirmation (copies stay), then the delete with the plan's fingerprint; a changed plan reloads.
|
||||
var dryRun = page.IndexOf(@"api.post(""/api/v1/videos/delete"", { ids, dryRun: true, fingerprint: null })", StringComparison.Ordinal);
|
||||
var confirm = page.IndexOf("const confirmed = await confirmDialog({", Math.Max(0, dryRun), StringComparison.Ordinal);
|
||||
var delete = page.IndexOf(@"api.post(""/api/v1/videos/delete"", { ids, dryRun: false, fingerprint: plan.fingerprint })", StringComparison.Ordinal);
|
||||
Assert.True(dryRun > 0 && confirm > dryRun && delete > confirm, "dry run, confirmation, delete");
|
||||
Assert.Contains(@"t(""Admin.Videos.Delete.CopiesStay"")", page);
|
||||
Assert.Contains("list: listed([...blocked, ...going]),", page);
|
||||
Assert.Contains(@"if (err.code === ""plan_changed"") await load();", page);
|
||||
// Copy is off, saying why, without the right or without a videos folder; a folder unset since says so from then on.
|
||||
Assert.Contains(@"const copyWhy = !may(EDIT) ? ""Admin.Videos.Copy.NoRight.Tip"" : folder === """" ? ""Admin.Videos.Copy.NoFolder.Tip"" : null;", page);
|
||||
Assert.Contains(@"const deleteWhy = may(DELETE) ? null : ""Admin.Videos.Delete.NoRight.Tip"";", page);
|
||||
Assert.Contains(@"if (err.code === ""videos_folder_unset"") folder = """";", page);
|
||||
Assert.Contains("const EDIT = 4;", page);
|
||||
Assert.Contains("const DELETE = 8;", page);
|
||||
Assert.Equal(4L, (long)Chronos.Core.Model.Permissions.Edit);
|
||||
Assert.Equal(8L, (long)Chronos.Core.Model.Permissions.Delete);
|
||||
// The player: a <video> for the formats a browser plays, an image for stills, GIF and APNG, the file by its render.
|
||||
Assert.Contains(@"<video controls autoplay preload=""metadata"" src=""${attr(fileUrl(v))}""></video>", page);
|
||||
Assert.Contains("return `/api/v1/renders/${encodeURIComponent(v.id)}/file`;", page);
|
||||
Assert.Contains(@"shown?.addEventListener(""error"", () => {", page);
|
||||
// An image sequence (a folder, no single file) and a missing file have no download, in the bar or the player.
|
||||
Assert.Contains(@"if (videoKind(v) === ""sequence"") return ""Admin.Videos.Download.Folder.Tip"";", page);
|
||||
Assert.Contains(@"if (v.state === ""missing"") return ""Admin.Videos.Download.Missing.Tip"";", page);
|
||||
Assert.Contains(@"const downloadWhy = one ? downloadBlock(rows.find((v) => v.id === only)) : ""Admin.Videos.Download.One.Tip"";", page);
|
||||
Assert.Contains("if (!v || downloadBlock(v)) return;", page);
|
||||
Assert.Contains("${downloadBlock(v)\n", page);
|
||||
// A sequence filter whose videos are not on the page names the sequence from its own record.
|
||||
Assert.Contains("api.get(`/api/v1/sequences/${encodeURIComponent(id)}`)", page);
|
||||
// The list follows the jobs that end (a copy, a render), the sequences that change and a reconnection.
|
||||
Assert.Contains(@"if (e.type === ""jobState"" && JOB_ENDED.has(e.state)) refreshSoon(1500);", page);
|
||||
Assert.Contains(@"else if (e.type === ""reconnected"") refreshSoon(0);", page);
|
||||
// The wire values the page sends are the API's.
|
||||
Assert.Contains($"const SORTS = [{string.Join(", ", VideoSorts.All.Select(s => $@"""{s}"""))}];", page);
|
||||
Assert.Contains(@"if (reason === ""busy"")", page);
|
||||
Assert.Equal("busy", VideoBlockReasons.Busy);
|
||||
Assert.Contains(@"if (reason === ""not_found"")", page);
|
||||
Assert.Equal("not_found", VideoBlockReasons.NotFound);
|
||||
Assert.Contains(@"v.state === ""missing""", page);
|
||||
Assert.Equal("missing", VideoStates.Missing);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheVideosStringsAreInEnglishAndItalian()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
|
||||
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
|
||||
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
|
||||
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
|
||||
var keys = Regex.Matches(page, @"""(Admin\.[A-Za-z]+(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value).Distinct().ToList();
|
||||
Assert.Greater(keys.Count, 50);
|
||||
// The keys the pages build from a value.
|
||||
keys.AddRange(VideoSorts.All.Select(s => $"Admin.Videos.Sort.{char.ToUpperInvariant(s[0])}{s[1..]}"));
|
||||
keys.AddRange(["Admin.Videos.Kind.Video", "Admin.Videos.Kind.Still", "Admin.Videos.Kind.Sequence", "Admin.Trash.Kind.Videos", "Admin.Nav.Videos", "Admin.Nav.Videos.Tip",
|
||||
"Admin.Settings.VideosPath", "Admin.Settings.VideosPath.Tip", "Admin.Job.Kind.VideoCopy"]);
|
||||
keys.AddRange(Regex.Matches(trash + sequence, @"""(Admin\.(?:Trash\.[A-Za-z]*Video[A-Za-z]*|Videos\.[A-Za-z.]+)(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value));
|
||||
Assert.Contains("Admin.Trash.RestoredVideo", keys);
|
||||
Assert.Contains("Admin.Videos.AllVideos.Tip", keys);
|
||||
foreach (var key in keys.Distinct())
|
||||
{
|
||||
var name = en.ContainsKey(key) ? key : key + ".other";
|
||||
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
|
||||
}
|
||||
Assert.Equal("Video", it["Admin.Nav.Videos"]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheTrashASequenceAndSettingsKnowTheVideosLibrary()
|
||||
{
|
||||
await using var server = await TestServer.StartAsync(context);
|
||||
// The trash lists a deleted video as "videos" (TrashKind.Videos), restores it after its hash check and says where it went.
|
||||
var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
|
||||
Assert.Contains(@"kind === ""videos"" ? ""Admin.Trash.Kind.Videos""", trash);
|
||||
Assert.Contains(@"kind === ""videos"" ? ""Admin.Trash.RestoreVideos.Tip""", trash);
|
||||
Assert.Contains(@"result.kind === ""videos"" ? t(""Admin.Trash.RestoredVideo"", videoFile(entry), entry.title)", trash);
|
||||
Assert.Contains(@"e.kind === ""videos"" ? ""—"" : formatNumber(e.photos)", trash);
|
||||
Assert.True(Chronos.Data.Videos.VideoTrashNames.IsEntryName(Chronos.Data.Videos.VideoTrashNames.EntryName(Guid.NewGuid(), DateTimeOffset.UtcNow)));
|
||||
|
||||
// A sequence's renders: kind and hash, and every video of the sequence on the Videos page.
|
||||
var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
|
||||
Assert.Contains(@"href=""#/videos?sequence=${attr(encodeURIComponent(id))}"" data-i18n=""Admin.Videos.AllVideos""", sequence);
|
||||
Assert.Contains(@"data-i18n=""Admin.Videos.Column.Kind""", sequence);
|
||||
Assert.Contains(@"data-i18n=""Admin.Videos.Column.Hash""", sequence);
|
||||
Assert.Contains(@"title=""${attr(r.sha256 ?? """")}"">${escapeHtml(shortHash(r.sha256))}", sequence);
|
||||
// The Videos page reads its sequence filter from the address the link writes.
|
||||
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
|
||||
Assert.Contains(@"const FILTERS = [""q"", ""kind"", ""codec"", ""year"", ""sequence"", ""sort""];", page);
|
||||
Assert.Contains("history.replaceState(null, \"\", `#/videos${query.size ? `?${query}` : \"\"}`);", page);
|
||||
|
||||
// Settings: the videos folder, read-only when an environment variable fixes it (lock), sent only when changed.
|
||||
var settings = await server.Client.GetStringAsync("/admin/pages/settings.js");
|
||||
Assert.Contains(@"${text(""videosPath"", settings.videosPath, 'dir=""ltr"" spellcheck=""false"" autocomplete=""off""')}", settings);
|
||||
Assert.Contains("videosPath: videosPath(),", settings);
|
||||
Assert.Contains("if (!input || input.disabled) return null;", settings);
|
||||
Assert.Contains(@"return next === (settings.videosPath ?? """") ? null : next;", settings);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
|
||||
private static partial Regex StaticImport();
|
||||
|
||||
/// <summary>A call of the panel's api object: its method and the start of its first argument.</summary>
|
||||
[GeneratedRegex(@"(?<![\w$.])api\.(\w+)\((""[^""]*""|`[^`]*`|\w+\()")]
|
||||
private static partial Regex ApiCall();
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Testing;
|
||||
|
||||
namespace Chronos.Server.Tests.Jobs;
|
||||
|
||||
/// <summary>Owner review 1, phase 5: a job that plays back, or saves a still, goes only to a node that reads settings format 3.</summary>
|
||||
[Category("server")]
|
||||
public sealed class PlaybackRoutingTests
|
||||
{
|
||||
private static readonly ExportSettings Mjpeg = new()
|
||||
{
|
||||
Preset = new Auto<string>().WithManual("mjpeg-avi"),
|
||||
Overrides = new ExportOverrides { Width = 96, Height = 64 },
|
||||
};
|
||||
|
||||
[Test]
|
||||
public void APlaybackJobIsNeverGivenToAFormatTwoNode()
|
||||
{
|
||||
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Roof", Title = "Roof" };
|
||||
var playing = ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg with { Playback = new PlaybackSettings { Loops = 3 } }, 96, 64,
|
||||
new ProjectSettings()).ParametersJson).Parameters;
|
||||
var plain = ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson).Parameters;
|
||||
Assert.Equal((3, 1), (playing.RequiredSettingsFormat, plain.RequiredSettingsFormat));
|
||||
|
||||
RegisterNodeRequest Node(int format) => new("node", [new NodeEncoder("mjpeg", "managed", false, false)], 0, 0, format);
|
||||
Assert.False(RenderNodeService.Renders(Node(2), playing), "a format-2 node would render it forward once");
|
||||
Assert.True(RenderNodeService.Renders(Node(3), playing));
|
||||
Assert.True(RenderNodeService.Renders(Node(2), plain));
|
||||
|
||||
// A still needs format 3 too (and an image codec no node encodes).
|
||||
var still = ProcessingJobs.ReadRender(ProcessingJobs.Still(sequence, Mjpeg, VideoCodec.JpegSequence, 0, null, 96, 64, new ProjectSettings()).ParametersJson).Parameters;
|
||||
Assert.False(RenderNodeService.Renders(Node(2) with { Encoders = [new NodeEncoder(still.Codec, "managed", false, false)] }, still));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SettingsWrittenInFormatThreeNeverGoToAFormatTwoNodeEvenWhenTheJobDoesNotPlayBack()
|
||||
{
|
||||
// The sequence's own export plays back, so its settings text is stamped version 3; the job's preset does not.
|
||||
var stored = new ProjectSettings { Export = Mjpeg with { Playback = new PlaybackSettings { Loops = 3 } } }.ToJson();
|
||||
var read = ProcessingJobs.ReadSettings(stored)!;
|
||||
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "Roof", Title = "Roof" };
|
||||
var job = ProcessingJobs.ReadRender(ProcessingJobs.Render(sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson).Parameters;
|
||||
Assert.Equal(1, job.RequiredSettingsFormat);
|
||||
|
||||
var routed = ProcessingJobs.Routed(job, read, 96, 64);
|
||||
var split = ProcessingJobs.Split(job, 96, 64, read);
|
||||
|
||||
Assert.Equal(3, routed.RequiredSettingsFormat);
|
||||
Assert.True(split.All(p => p.RequiredSettingsFormat == 3));
|
||||
RegisterNodeRequest Node(int format) => new("node", [new NodeEncoder("mjpeg", "managed", false, false)], 0, 0, format);
|
||||
Assert.False(RenderNodeService.Renders(Node(2), routed), "a format-2 node cannot parse the settings it would be handed");
|
||||
Assert.True(RenderNodeService.Renders(Node(3), routed));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user