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

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:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 09:18:40 +01:00
1 parent 188b2c2e55
commit 728ffa35cb
729 files changed
+26954 -1652

No files matched your search

+219
View File
@@ -0,0 +1,219 @@
using System.Globalization;
using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Videos;
using Chronos.Protocol;
using Chronos.Server.Configuration;
using Chronos.Server.Events;
using Chronos.Server.Jobs;
using Chronos.Server.Security;
using Chronos.Server.Storage;
namespace Chronos.Server.Api;
/// <summary>
/// <c>/api/v1/videos</c> (owner review 1, R9; capability <see cref="ServerCapabilities.Videos"/>): every render of the
/// server in one list, read by anyone who may read; deleting renders into the archive's trash (Delete), always a dry run
/// first whose fingerprint the delete itself must give back, and restored through <c>/archive/trash/{name}/restore</c>;
/// and copying them, hash-verified, into the server's videos folder as one <c>video-copy</c> job (Edit). The files
/// themselves are <c>GET /api/v1/renders/{id}/file</c>. Deletes and copies are audited (<c>videos_deleted</c>,
/// <c>videos_copied</c>). The panel manages and never edits (owner review 2, R6): nothing here changes a project or starts a render.
/// </summary>
public static class VideoEndpoints
{
/// <summary>The most renders one delete or copy names.</summary>
public const int MaxIds = VideoQuery.MaxLimit;
/// <summary>Renders an audit entry names by file, the rest counted.</summary>
private const int AuditNames = 5;
public static void Map(RouteGroupBuilder api)
{
var videos = api.MapGroup("/videos").Requires(Permissions.Read);
videos.MapGet("", ListAsync);
videos.MapGet("/{id:guid}", GetAsync);
videos.MapPost("/delete", DeleteAsync).Requires(Permissions.Delete);
videos.MapPost("/copy", CopyAsync).Requires(Permissions.Edit);
}
/// <summary>The videos library behind these endpoints: the host's, or that of an archive engine of its own (a test host that replaces the archive module).</summary>
internal static IVideoLibrary Library(IVideoLibrary? videos, ArchiveService? archives, ChronosDatabase db) =>
videos ?? LibraryEndpoints.Engine(archives, db).Videos;
public static VideoDto Video(VideoItem item)
{
ArgumentNullException.ThrowIfNull(item);
var r = item.Render;
return new VideoDto(r.Id, r.SequenceId, r.PresetName, r.Codec, r.Width, r.Height, r.Fps, r.DurationSeconds, r.Bytes, r.Created, r.ProducedBy,
r.ProjectId, r.ProjectVersionId, r.Sha256, item.Kind, item.SequenceTitle, item.SequenceFirstCapture, item.ProjectName, item.ProjectVersionNumber,
item.State, [.. item.Copies.Select(c => new VideoCopyDto(c.Path, c.CopiedAt))], item.FileName);
}
/// <summary>
/// One page of videos: <c>q</c> (sequence title, preset or file name), <c>kind</c> (<c>video</c>, <c>still</c>,
/// <c>sequence</c>), <c>codec</c>, <c>year</c>, <c>sequence</c>, <c>sort</c> (<see cref="VideoSorts"/>), <c>cursor</c>,
/// <c>limit</c> (1–500). 400 <c>invalid_filter</c> (details: the filter).
/// </summary>
private static async Task<IResult> ListAsync(HttpContext context, string? q, string? kind, string? codec, int? year, Guid? sequence, string? sort,
string? cursor, int? limit, ChronosDatabase db, [FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos)
{
kind = Blank(kind)?.ToLowerInvariant();
sort = Blank(sort)?.ToLowerInvariant();
if (kind is not null and not (RenderKind.Video or RenderKind.Still or RenderKind.Sequence)) return ApiErrors.BadRequest(context, "invalid_filter", "kind");
if (sort is not null && !VideoSorts.All.Contains(sort)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
if (year is < 1 or > 9999) return ApiErrors.BadRequest(context, "invalid_filter", "year");
var query = VideoQuery.From(new VideoQueryDto(Blank(q), kind, Blank(codec), year, sequence, sort, Blank(cursor), limit));
VideoPage page;
try
{
page = await Library(videos, archives, db).ListAsync(query, context.RequestAborted);
}
catch (Exception ex) when (ex is ArgumentException or FormatException)
{
// A cursor of another listing, or one this server never gave.
return ApiErrors.BadRequest(context, "invalid_cursor");
}
return Results.Json(new VideoPageDto([.. page.Items.Select(Video)], page.Next, page.Total), ProtocolJson.Default.VideoPageDto);
}
private static async Task<IResult> GetAsync(HttpContext context, Guid id, ChronosDatabase db, [FromServices] ArchiveService? archives,
[FromServices] IVideoLibrary? videos) =>
await Library(videos, archives, db).GetAsync(id, context.RequestAborted) is { } item
? Results.Json(Video(item), ProtocolJson.Default.VideoDto)
: ApiErrors.NotFound(context, "render");
/// <summary>
/// With <c>dryRun</c> the plan of moving <c>ids</c> into the archive's trash: the renders that go (one whose file is
/// missing loses only its entry), their bytes, those left where they are (<c>busy</c>, <c>not_found</c>) and the plan's
/// fingerprint; nothing moves. Otherwise the request carries that fingerprint and the renders move as planned, each
/// into a trash entry (<see cref="VideoDeletePlanDto.TrashEntries"/>); copies in the videos folder are never touched.
/// 400 <c>bad_request</c> (<c>ids</c>, <c>fingerprint</c>); 409 <c>plan_changed</c> (nothing moved), <c>video_busy</c>,
/// <c>sequence_busy</c>, <c>folder_in_use</c>; 503 <c>archive_offline</c>. Publishes <c>sequenceChanged</c>
/// (<c>renders</c>) for every sequence that lost a render.
/// </summary>
private static async Task<IResult> DeleteAsync(HttpContext context, Caller caller, VideoDeleteRequest request, ChronosDatabase db,
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, AuditLog audit, EventHub events, IHostApplicationLifetime lifetime)
{
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
var library = Library(videos, archives, db);
if (!library.IsAvailable) return Unavailable(context);
try
{
if (request.DryRun)
{
var plan = await library.PlanDeleteAsync(ids, context.RequestAborted);
return Results.Json(new VideoDeletePlanDto([.. plan.Items.Select(Item)], plan.Bytes, [.. plan.Blocked.Select(Blocked)], plan.Fingerprint, DryRun: true),
ProtocolJson.Default.VideoDeletePlanDto);
}
if (string.IsNullOrWhiteSpace(request.Fingerprint)) return ApiErrors.BadRequest(context, "bad_request", "fingerprint");
// Files move into the trash: the delete runs to the end even if the client disconnects meanwhile.
var result = await library.DeleteAsync(ids, request.Fingerprint, caller.User.Username, lifetime.ApplicationStopping);
var moved = result.Deleted.Where(i => !i.Missing).Sum(i => i.Render.Bytes);
if (result.Deleted.Count > 0)
{
await audit.WriteAsync(caller, context, "videos_deleted", "videos", result.Deleted.Count == 1 ? result.Deleted[0].Render.Id.ToString() : null,
Summary(result.Deleted.Count, moved, result.Deleted.Select(i => i.FileName)));
}
foreach (var sequenceId in result.Deleted.Select(i => i.Render.SequenceId).Distinct())
{
if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } sequence)
events.Publish(new SequenceChangedEvent(sequence.Id, "renders", sequence.FramesVersion, sequence.SettingsVersion));
}
return Results.Json(new VideoDeletePlanDto([.. result.Deleted.Select(Item)], moved, [.. result.Blocked.Select(Blocked)], request.Fingerprint,
DryRun: false, result.TrashEntries), ProtocolJson.Default.VideoDeletePlanDto);
}
catch (VideoLibraryException ex)
{
return Refused(context, ex);
}
catch (ArchiveOfflineException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
catch (LeaseUnavailableException)
{
return ApiErrors.Conflict(context, "sequence_busy");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// A file is open elsewhere: nothing of it moved.
return ApiErrors.Conflict(context, "folder_in_use");
}
}
/// <summary>
/// Queues one <c>video-copy</c> job copying <c>ids</c> into the server's videos folder (<see cref="ServerOptions.VideosPath"/>),
/// each copy hash-verified before it takes its name (a free one, " (2)" on a collision); the renders are never touched.
/// 202 with the job. 400 <c>bad_request</c> (<c>ids</c>); 404 <c>not_found</c> (<c>render</c>, details); 409
/// <c>videos_folder_unset</c>, <c>job_unavailable</c>; 422 <c>videos_folder_invalid</c> (inside the archive or the data
/// folder); 507 <c>videos_no_space</c> (the folder's volume cannot take the renders' bytes).
/// </summary>
private static async Task<IResult> CopyAsync(HttpContext context, Caller caller, VideoCopyRequest request, ChronosDatabase db, ServerOptions options,
[FromServices] ArchiveService? archives, [FromServices] IVideoLibrary? videos, JobEngineHost host, VolumeSpace volumes, AuditLog audit)
{
var ct = context.RequestAborted;
if (Ids(request.Ids) is not { } ids) return ApiErrors.BadRequest(context, "bad_request", "ids");
var folder = Blank(options.VideosPath);
var library = Library(videos, archives, db);
if (folder is null) return ApiErrors.Conflict(context, VideoErrors.FolderUnset);
if (!ServerSettingsStore.IsVideosFolder(folder, options) || (library.FolderProblem(folder) is { } problem && problem != VideoErrors.FolderUnset))
return Refused(context, VideoErrors.FolderInvalid);
var renders = new List<Render>(ids.Count);
foreach (var id in ids)
{
if (await db.Renders.GetAsync(id, ct) is not { } render) return ApiErrors.NotFound(context, "render");
renders.Add(render);
}
if (!library.IsAvailable || !host.CanRun(JobKind.VideoCopy)) return Unavailable(context);
if (volumes.Measure(folder) is { } volume && volume.FreeBytes < renders.Sum(r => r.Bytes)) return Refused(context, VideoErrors.NoSpace);
ArchiveJobRequest job;
try
{
job = library.CopyJob(new VideoCopyParameters(ids, folder, FromServer: false, caller.User.Username));
}
catch (VideoLibraryException ex)
{
return Refused(context, ex);
}
var queued = await host.Engine.EnqueueAsync(job, caller.Id, ct);
await audit.WriteAsync(caller, context, "videos_copied", "job", queued.Id.ToString(),
Summary(renders.Count, renders.Sum(r => r.Bytes), renders.Select(r => Path.GetFileName(r.OutputPath.TrimEnd('/', '\\')))));
return Results.Json(new VideoCopyResultDto(queued.Id), ProtocolJson.Default.VideoCopyResultDto, statusCode: StatusCodes.Status202Accepted);
}
/// <summary>The answer of a library refusal: its code with its status.</summary>
internal static IResult Refused(HttpContext context, VideoLibraryException ex) => Refused(context, ex.Code);
private static IResult Refused(HttpContext context, string code) => ApiErrors.Result(context, code switch
{
VideoErrors.FolderInvalid or VideoErrors.HashMismatch => StatusCodes.Status422UnprocessableEntity,
VideoErrors.NoSpace => StatusCodes.Status507InsufficientStorage,
_ => StatusCodes.Status409Conflict,
}, code);
/// <summary>This server's archive engine has no videos library (a build before it): nothing can be deleted or copied.</summary>
private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy));
/// <summary>The ids of a request, each once in order; null when there are none, too many, or an empty one.</summary>
private static List<Guid>? Ids(IReadOnlyList<Guid>? ids)
{
if (ids is null || ids.Count is 0 or > MaxIds || ids.Contains(Guid.Empty)) return null;
return [.. ids.Distinct()];
}
private static VideoDeleteItemDto Item(VideoItem item) =>
new(item.Render.Id, item.Render.SequenceId, item.SequenceTitle, item.FileName, item.Missing ? 0 : item.Render.Bytes, item.Missing);
private static VideoBlockedDto Blocked(VideoBlocked blocked) => new(blocked.RenderId, blocked.Reason);
/// <summary>An audit entry's details: how many, their bytes, and the first file names.</summary>
private static string Summary(int count, long bytes, IEnumerable<string> names) =>
string.Create(CultureInfo.InvariantCulture, $"{count} · {bytes} · {string.Join(", ", names.Take(AuditNames))}");
private static string? Blank(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}