Files
Chronos/tests/Chronos.Server.Tests/Api/VideoEndpointTests.cs
T
Alby96andClaude Opus 5.5 728ffa35cb
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
feat: export panel and Render menu, playback options, videos library (owner review 1 phase 5) (#27)
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>
2026-11-05 09:18:40 +01:00

482 lines
29 KiB
C#

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);
}
}