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;
///
/// /api/v1/videos (owner review 1, R9; capability ): 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 /archive/trash/{name}/restore;
/// and copying them, hash-verified, into the server's videos folder as one video-copy job (Edit). The files
/// themselves are GET /api/v1/renders/{id}/file. Deletes and copies are audited (videos_deleted,
/// videos_copied). The panel manages and never edits (owner review 2, R6): nothing here changes a project or starts a render.
///
public static class VideoEndpoints
{
/// The most renders one delete or copy names.
public const int MaxIds = VideoQuery.MaxLimit;
/// Renders an audit entry names by file, the rest counted.
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);
}
/// 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).
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);
}
///
/// One page of videos: q (sequence title, preset or file name), kind (video, still,
/// sequence), codec, year, sequence, sort (), cursor,
/// limit (1–500). 400 invalid_filter (details: the filter).
///
private static async Task 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 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");
///
/// With dryRun the plan of moving ids 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 (busy, not_found) and the plan's
/// fingerprint; nothing moves. Otherwise the request carries that fingerprint and the renders move as planned, each
/// into a trash entry (); copies in the videos folder are never touched.
/// 400 bad_request (ids, fingerprint); 409 plan_changed (nothing moved), video_busy,
/// sequence_busy, folder_in_use; 503 archive_offline. Publishes sequenceChanged
/// (renders) for every sequence that lost a render.
///
private static async Task 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");
}
}
///
/// Queues one video-copy job copying ids into the server's videos folder (),
/// 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 bad_request (ids); 404 not_found (render, details); 409
/// videos_folder_unset, job_unavailable; 422 videos_folder_invalid (inside the archive or the data
/// folder); 507 videos_no_space (the folder's volume cannot take the renders' bytes).
///
private static async Task 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(ids.Count);
foreach (var id in ids)
{
if (await ServedItems.RenderAsync(db, context.RequestServices.GetRequiredService(), 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);
}
/// The answer of a library refusal: its code with its status.
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);
/// This server's archive engine has no videos library (a build before it): nothing can be deleted or copied.
private static IResult Unavailable(HttpContext context) => ApiErrors.Conflict(context, "job_unavailable", JobWire.Kind(JobKind.VideoCopy));
/// The ids of a request, each once in order; null when there are none, too many, or an empty one.
///
/// 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.
///
private static async Task> ServedAsync(HttpContext context, ChronosDatabase db, List ids)
{
var archive = context.RequestServices.GetRequiredService();
var served = new List(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? Ids(IReadOnlyList? 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);
/// An audit entry's details: how many, their bytes, and the first file names.
private static string Summary(int count, long bytes, IEnumerable names) =>
string.Create(CultureInfo.InvariantCulture, $"{count} · {bytes} · {string.Join(", ", names.Take(AuditNames))}");
private static string? Blank(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}