Files
Febe/src/Febe.Web/Api/ApiErrorMiddleware.cs
T
Alby96andClaude Opus 5.5 ab0d717424 E3: API di formati e fotogrammi, conversione della libreria e demo
Porta le funzioni della tappa E3 fino all'interfaccia web, così che WP4
possa costruire le schermate su indirizzi veri.

- Impostazioni, cartelle delle copie e «Copia in…» hanno i formati
  (nomi original, jpg, png, webplossless, mp4); il riepilogo dice cosa si
  converte, cosa resta com'è e se c'è perdita. «Copia di nuovo» rifà la
  copia nella sua forma esatta.
- Fotogrammi: informazioni di un video, un fotogramma (anteprima o
  scaricamento), gli istanti di una modalità, «Scarica» di uno o di uno
  zip scritto mentre parte, con il permesso dei lavori lunghi oltre 20.
  Kestrel non vede mai scritture sincrone: il piccolo descrittore che lo
  zip di .NET 10 scrive in modo sincrono parte con la scrittura seguente.
- Conversione della libreria: stato, la domanda «Converti anche i N già
  in libreria?», riprova, pausa e ripresa; il visualizzatore mostra i
  file convertiti, e le eliminazioni li contano.
- Demo: un video H.264 scritto in casa (solo macroblocchi I_PCM) per
  ogni video, una copia in PNG, un fotogramma e due conversioni; la
  conversione non parte mai.

Due prove cambiano con il comportamento: i video della demo ora si
aprono, e un file non copiato può avere il segno «solo fotogramma».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 01:02:37 +01:00

132 lines
5.5 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Febe.Core.Storage;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
namespace Febe.Web.Api;
/// <summary>
/// Turns the exceptions of the API into Italian answers: 400 for a wrong request, 404 for something missing, 409 for a
/// duplicate, 500 with a message that says what happened (never a stack trace, never a caption or a path of the request).
/// </summary>
public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMiddleware> logger)
{
public async Task InvokeAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
if (!context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
{
await next(context).ConfigureAwait(false);
return;
}
try
{
await next(context).ConfigureAwait(false);
}
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
{
// The page went away: nothing to answer.
}
catch (Exception ex) when (!context.Response.HasStarted)
{
var (status, message) = ex switch
{
BadRequestException => (StatusCodes.Status400BadRequest, ex.Message),
ArgumentException a => (StatusCodes.Status400BadRequest, CleanMessage(a)),
JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
ApiStatusException a => (a.Status, ex.Message),
DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message),
_ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."),
};
if (status == StatusCodes.Status500InternalServerError)
{
// Type and message only: no request data.
logger.LogError("Errore dell'API: {Type}: {Message}", ex.GetType().Name, ex.Message);
}
context.Response.Clear();
context.Response.StatusCode = status;
await context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto).ConfigureAwait(false);
}
}
/// <summary>The Italian message of an argument error, without the « (Parameter 'x')» that .NET appends.</summary>
public static string CleanMessage(ArgumentException exception)
{
ArgumentNullException.ThrowIfNull(exception);
return exception.ParamName is { } name ? exception.Message.Replace($" (Parameter '{name}')", string.Empty, StringComparison.Ordinal) : exception.Message;
}
}
/// <summary>Small helpers of the endpoints.</summary>
public static class ApiHttp
{
/// <summary>Reads a JSON body with its source-generated metadata; an empty or unreadable body is a 400.</summary>
public static async Task<T> BodyAsync<T>(HttpContext context, JsonTypeInfo<T> type)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(type);
if (context.Request.ContentLength == 0)
{
throw new BadRequestException("Richiesta vuota.");
}
try
{
var value = await JsonSerializer.DeserializeAsync(context.Request.Body, type, context.RequestAborted).ConfigureAwait(false);
return value ?? throw new BadRequestException("Richiesta vuota.");
}
catch (JsonException)
{
throw new BadRequestException("Richiesta non leggibile.");
}
}
/// <summary>
/// Reads an optional JSON body: <paramref name="empty"/> when there is none — no length and nothing to read, as an
/// empty POST may come chunked or over HTTP/2 — and the body otherwise (a 400 when it is not readable).
/// </summary>
public static async Task<T> OptionalBodyAsync<T>(HttpContext context, JsonTypeInfo<T> type, T empty)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.Request;
if (request.ContentLength == 0)
{
return empty;
}
if (request.ContentLength is null)
{
if (context.Features.Get<IHttpRequestBodyDetectionFeature>() is { CanHaveBody: false })
{
return empty;
}
// A body without a declared length may still be empty: one byte tells, then it is read from the start.
request.EnableBuffering();
var probe = new byte[1];
if (await request.Body.ReadAsync(probe, context.RequestAborted).ConfigureAwait(false) == 0)
{
return empty;
}
request.Body.Position = 0;
}
return await BodyAsync(context, type).ConfigureAwait(false);
}
/// <summary>A JSON answer with its source-generated metadata.</summary>
public static IResult Json<T>(T value, JsonTypeInfo<T> type, int status = StatusCodes.Status200OK) =>
Results.Json(value, type, statusCode: status);
public static IResult Message(string message, int status = StatusCodes.Status200OK) =>
Results.Json(new MessageDto(message), FebeJsonContext.Default.MessageDto, statusCode: status);
}