using System.Globalization;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Titano.Core.Archiving;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Server.Jobs;
using Titano.Server.Security;
using Titano.Server.Storage;
namespace Titano.Server.Api;
///
/// Streamed archive files with Range support (BRIEF §14.3): originals, proxies, thumbnails and exports. Paths come
/// from the database by id and are resolved under the archive root only. Proxies of frames the server cannot decode
/// arrive from clients and render nodes (PUT /frames/{id}/proxy, BRIEF §2.3).
///
public static class FileEndpoints
{
private const string Immutable = "private, max-age=31536000, immutable";
private const string Regenerable = "private, max-age=3600";
public static void Map(RouteGroupBuilder api)
{
// Originals feed editing clients and render nodes; viewers browse proxies, thumbnails and exports.
api.MapGet("/frames/{id:guid}/original", OriginalAsync).Requires(Permissions.Edit | Permissions.RenderNode);
api.MapGet("/frames/{id:guid}/proxy", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Proxy, db, a, l))
.Requires(Permissions.Read | Permissions.RenderNode);
// Made by clients that edit and by render nodes, which decode what the server cannot.
api.MapPut("/frames/{id:guid}/proxy", StoreProxyAsync).Requires(Permissions.Edit | Permissions.RenderNode);
api.MapGet("/frames/{id:guid}/thumb", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Thumbnail, db, a, l))
.Requires(Permissions.Read);
api.MapGet("/renders/{id:guid}/file", RenderAsync).Requires(Permissions.Read);
}
private static async Task OriginalAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive)
{
if (await db.Frames.GetAsync(id, context.RequestAborted) is not { } frame) return ApiErrors.NotFound(context, "frame");
if (ArchivePathGuard.ExistingFile(archive.Root, frame.RelativePath) is not { } file) return ApiErrors.NotFound(context, "file_missing");
return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(frame.FileName), Immutable, frame.Sha256, frame.FileName)
?? ApiErrors.NotFound(context, "file_missing");
}
private static async Task AssetAsync(HttpContext context, Guid id, FrameAsset kind, TitanoDatabase db, ServerArchive archive, IFrameAssetLocator locator)
{
var ct = context.RequestAborted;
if (await db.Frames.GetAsync(id, ct) is not { } frame || await db.Sequences.GetAsync(frame.SequenceId, ct) is not { } sequence)
return ApiErrors.NotFound(context, "frame");
var location = await locator.LocateAsync(archive.Current, sequence, frame, kind, ct);
if (location is null || !ArchivePathGuard.IsInside(archive.Root, location.Path)) return ApiErrors.NotFound(context, "asset_missing");
var file = new FileInfo(location.Path);
if (!file.Exists || file.LinkTarget is not null) return ApiErrors.NotFound(context, "asset_missing");
var etag = string.Create(CultureInfo.InvariantCulture, $"{kind}-{frame.Id:N}-{file.LastWriteTimeUtc.Ticks}-{location.Offset}");
return FileResponses.Serve(context, file, location.Offset, location.Length, location.ContentType, Regenerable, etag)
?? ApiErrors.NotFound(context, "asset_missing");
}
///
/// Files the body (a JPEG made from the original, its Exif capture time the frame's, as large as the archive's proxies,
/// at most ) as the proxy of a frame the server cannot decode
/// (); the sequence's thumbnails, proxy state and light analysis follow as background jobs.
/// 204; 413 too_large; 422 proxy_not_wanted (the server decodes that original itself, or it is missing or
/// damaged), invalid_proxy, proxy_mismatch or proxy_too_small, which concern that proxy only; 409
/// proxies_disabled, which concerns them all; 503 archive_offline.
///
private static async Task StoreProxyAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, SequenceJobs follow)
{
var ct = context.RequestAborted;
if (await db.Frames.GetAsync(id, ct) is not { } frame || await db.Sequences.GetAsync(frame.SequenceId, ct) is not { } sequence)
return ApiErrors.NotFound(context, "frame");
// A proxy replaces the server's own of an original it decodes, which renders and remote views would then show.
if (!ServerProxies.CannotDecode(frame.Format) || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0)
return ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "proxy_not_wanted");
if (context.Request.ContentLength is > ArchiveImages.MaxProxyBytes) return ApiErrors.Result(context, StatusCodes.Status413PayloadTooLarge, "too_large");
// Proxies are larger than the JSON bodies Kestrel is limited to; reading past this answers 413.
if (context.Features.Get() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = ArchiveImages.MaxProxyBytes;
using var body = new MemoryStream();
await context.Request.Body.CopyToAsync(body, ct);
var images = (archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner })).Images;
ProxyStoreResult result;
try
{
result = images.StoreProxy(archive.Current, sequence, frame, body.ToArray());
}
catch (ArchiveOfflineException)
{
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
switch (result)
{
case ProxyStoreResult.Disabled:
return ApiErrors.Conflict(context, "proxies_disabled");
case ProxyStoreResult.Invalid:
return ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "invalid_proxy");
case ProxyStoreResult.WrongFrame:
return ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "proxy_mismatch");
case ProxyStoreResult.TooSmall:
return ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "proxy_too_small");
}
// The proxy is filed: its follow-up is queued even when the sender is gone by now.
await follow.ProxyArrivedAsync(sequence, CancellationToken.None);
return Results.NoContent();
}
private static async Task RenderAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive)
{
if (await db.Renders.GetAsync(id, context.RequestAborted) is not { } render) return ApiErrors.NotFound(context, "render");
if (ArchivePathGuard.ExistingFile(archive.Root, render.OutputPath) is not { } file) return ApiErrors.NotFound(context, "file_missing");
var etag = string.Create(CultureInfo.InvariantCulture, $"r-{render.Id:N}-{file.Length}-{file.LastWriteTimeUtc.Ticks}");
return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(file.Name), Immutable, etag, file.Name)
?? ApiErrors.NotFound(context, "file_missing");
}
}