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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user