Files
slp-modular-cms/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs
T
SluijsensandClaude Sonnet 5.5 6999f5b2ba Hero-admin: schakelaar Actief, destructieve knoppen rood, slide-kopjes, juiste voorvertoning in het focusvenster, status per foto
- Schakelaar (role=switch) Actief / Niet actief bij de knoppen, gedimde rij; 'Verberg voor schermlezers'; veld 'Beschrijving' binnen een groep 'Slide N'
- Alle foto's zonder complete set tonen 'Wordt verwerkt' (voortgang bij de foto die bezig is, 'in de wachtrij' bij de rest); totaal bovenaan telt ook nog niet opgeslagen foto's
- Per foto 'Verwerking afgerond' (zelfde weergave voor een hergebruikte foto), foto direct bruikbaar; niet-opgeslagen foto's worden zelf ververst (GET /hero/images/{id}), ook in een achtergrondtab
- Focusvenster toont de hele foto (full-preview in elke set, achtergrond-aanvulling voor oude sets) in plaats van de uitgesneden wide-variant (vervorming)
- Prullenbak en 'Wijzigingen weggooien' in de destructieve stijl
- upload-respons: reused (intern)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:26:47 +01:00

177 lines
7.3 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Availability;
using SlpModularCms.Core.Media;
using SlpModularCms.Core.Texts;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
namespace SlpModularCms.Modules.Hero.Controllers;
/// <summary>
/// The hero of the site. <c>GET /hero</c> is what websites read (200 with the hero, 204 when there is none to show);
/// management (<c>GET /hero/all</c>, <c>PUT /hero</c>) is for administrators.
/// </summary>
[ApiController]
[Route("hero")]
public class HeroController(IHeroService service, IPublicHeroService publicService) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting("hero-public")]
[ProducesResponseType<PublicHeroDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> Get(CancellationToken cancellationToken)
{
Response.Headers.CacheControl = "public, max-age=60";
var hero = await publicService.GetActiveAsync(cancellationToken);
return hero is null ? NoContent() : Ok(hero);
}
[HttpGet("all")]
[Authorize(Policy = "AdminOnly")]
[ProducesResponseType<HeroAdminDto>(StatusCodes.Status200OK)]
public async Task<IActionResult> GetForAdmin(CancellationToken cancellationToken)
=> Ok(await service.GetAsync(cancellationToken));
[HttpPut]
[Authorize(Policy = "AdminOnly")]
[ProducesResponseType<HeroAdminDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Save([FromBody] HeroSaveRequest request, CancellationToken cancellationToken)
{
try
{
return Ok(await service.SaveAsync(request, HeroCaller.Id(User), cancellationToken));
}
catch (HeroSaveRejectedException exception)
{
ModelState.AddModelError(exception.Field, exception.Message);
return ValidationProblem(ModelState);
}
catch (ImageRejectedException rejection)
{
// Cutting the variants for a changed focus needs the stored original and a free processing slot.
var status = rejection.Reason == ImageRejection.Busy ? StatusCodes.Status429TooManyRequests : StatusCodes.Status503ServiceUnavailable;
return StatusCode(status, new { error = rejection.Code, message = HttpTexts.From(HttpContext).Get(HeroTexts.Image.For(rejection.Reason)) });
}
}
}
/// <summary>Images of the hero: upload, focus and delete. Administrators only.</summary>
[ApiController]
[Route("hero/images")]
[Authorize(Policy = "AdminOnly")]
public class HeroImagesController(IHeroImageService service, IOptions<MediaOptions> media, MediaStatus mediaStatus) : ControllerBase
{
/// <summary>The body limit leaves room for the multipart envelope around the file limit of <see cref="MediaOptions.MaxUploadBytes"/>.</summary>
private const long RequestLimit = 12 * 1024 * 1024;
[HttpPost]
[RequestSizeLimit(RequestLimit)]
[EnableRateLimiting("hero-upload")]
[Consumes("multipart/form-data")]
[ProducesResponseType<HeroImageDto>(StatusCodes.Status201Created)]
public async Task<IActionResult> Upload(IFormFile file, CancellationToken cancellationToken)
{
try
{
await using var stream = file.OpenReadStream();
var image = await service.UploadAsync(stream, file.Length, HeroCaller.Id(User), cancellationToken);
return Created($"/api/v1/hero/images/{image.Id}", image);
}
catch (ImageRejectedException rejection)
{
return Rejected(rejection);
}
catch (MediaStorageFullException)
{
return StatusCode(StatusCodes.Status503ServiceUnavailable, new { error = "storage_full", message = Texts().Get(HeroTexts.Image.StorageFull) });
}
}
/// <summary>One image as the admin sees it now; the page asks for the images it uploaded but has not saved yet.</summary>
[HttpGet("{id:guid}")]
[ProducesResponseType<HeroImageDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Get(Guid id, CancellationToken cancellationToken)
{
var image = await service.GetImageAsync(id, cancellationToken);
return image is null ? NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) }) : Ok(image);
}
/// <summary>The formats and limits an upload has to meet on this host (what the validation uses).</summary>
[HttpGet("limits")]
[ProducesResponseType<HeroUploadLimitsDto>(StatusCodes.Status200OK)]
public ActionResult<HeroUploadLimitsDto> Limits() => HeroMapping.UploadLimits(mediaStatus, media.Value);
/// <summary>Lets the background renderer try an image it gave up on again.</summary>
[HttpPost("{id:guid}/retry")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Retry(Guid id, CancellationToken cancellationToken)
{
try
{
await service.RetryRenderAsync(id, cancellationToken);
return NoContent();
}
catch (HeroImageNotFoundException)
{
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
}
}
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
{
try
{
await service.DeleteAsync(id, HeroCaller.Id(User), cancellationToken);
return NoContent();
}
catch (HeroImageNotFoundException)
{
return NotFound(new { error = "not_found", message = Texts().Get(HeroTexts.Image.NotFound) });
}
catch (HeroImageInUseException)
{
return Conflict(new { error = "in_use", message = Texts().Get(HeroTexts.Image.InUse) });
}
}
private ITextCatalog Texts() => HttpTexts.From(HttpContext);
private IActionResult Rejected(ImageRejectedException rejection)
{
var status = rejection.Reason switch
{
ImageRejection.TooLarge => StatusCodes.Status413PayloadTooLarge,
ImageRejection.Busy => StatusCodes.Status429TooManyRequests,
ImageRejection.Unavailable => StatusCodes.Status503ServiceUnavailable,
_ => StatusCodes.Status400BadRequest,
};
var key = HeroTexts.Image.For(rejection.Reason);
var message = rejection.Reason == ImageRejection.TooLarge
? Texts().Get(key, args: ("max", media.Value.MaxUploadBytes / (1024 * 1024)))
: Texts().Get(key);
return StatusCode(status, new { error = rejection.Code, message });
}
}
internal static class HeroCaller
{
public static Guid Id(ClaimsPrincipal user)
{
var claim = user.FindFirstValue(ClaimTypes.NameIdentifier) ?? user.FindFirstValue("sub");
return Guid.TryParse(claim, out var id) ? id : Guid.Empty;
}
}