Files
Chronos/src/Chronos.Server/Api/VideoEndpoints.cs
T
Alby96andClaude Opus 5.5 8d41992d84 feat: Chronos Desktop shares its library on the LAN (owner review 5 P4)
Chronos Server for Windows is replaced by Settings > Server > Share this
library: Chronos Desktop hosts the server engine in its own process over its
own index, archive and processing services, job engine and scheduler, so a
second PC, the Uploader and render nodes use this PC's library without a
Windows service or a second index.

- Chronos.Server is a library; Chronos.Server.Host is the console exe that
  Docker and development runs start. The App references the library and the
  ASP.NET Core shared framework (no package).
- ServerHost.BuildHosted/HostedServer: reuses the desktop's engines and
  never creates, starts or disposes them; no static log sink, no console
  lifetime; server.json plus desktop-owned values locked "Set in Chronos
  Desktop"; only upload-cleanup and audit-cleanup schedules are added.
- Both modes: by-id endpoints scoped to the served archive, a client's
  render export folder dropped; hosted mode exposes server job kinds only.
- Desktop: LibraryShare (start after the schedules, stop first, port in
  use named), Settings > Server sharing rows, Server > This library panel
  (state, addresses with Copy, ports, fingerprint, temporary admin
  password, clients, admin panel), own library refused by ConnectFlow and
  dropped from LAN discovery, the uploads sweep step, thumbnails after scans
  while sharing, capture scenes server-share and server-share-failed.
- Removed: the Windows service hosting of Chronos.Server, its switches and
  its tests.

Refs #67

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:55:50 +01:00

239 lines
14 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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");
ids = await ServedAsync(context, db, 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 ServedItems.RenderAsync(db, context.RequestServices.GetRequiredService<ServerArchive>(), 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>
/// <summary>
/// <paramref name="ids"/> without the renders of another archive of the index (owner review 5, #67): they are left out as
/// ids the server does not know. Unknown ids stay, for the library to report.
/// </summary>
private static async Task<List<Guid>> ServedAsync(HttpContext context, ChronosDatabase db, List<Guid> ids)
{
var archive = context.RequestServices.GetRequiredService<ServerArchive>();
var served = new List<Guid>(ids.Count);
foreach (var id in ids)
{
if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render
|| archive.Owns(await db.Sequences.GetAsync(render.SequenceId, context.RequestAborted)))
served.Add(id);
}
return served;
}
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();
}