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;
///
/// The hero of the site. GET /hero is what websites read (200 with the hero, 204 when there is none to show);
/// management (GET /hero/all, PUT /hero) is for administrators.
///
[ApiController]
[Route("hero")]
public class HeroController(IHeroService service, IPublicHeroService publicService) : ControllerBase
{
[HttpGet]
[AllowAnonymous]
[PublicSiteEndpoint]
[EnableRateLimiting("hero-public")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task 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(StatusCodes.Status200OK)]
public async Task GetForAdmin(CancellationToken cancellationToken)
=> Ok(await service.GetAsync(cancellationToken));
[HttpPut]
[Authorize(Policy = "AdminOnly")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task 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)) });
}
}
}
/// Images of the hero: upload, focus and delete. Administrators only.
[ApiController]
[Route("hero/images")]
[Authorize(Policy = "AdminOnly")]
public class HeroImagesController(IHeroImageService service, IOptions media, MediaStatus mediaStatus) : ControllerBase
{
/// The body limit leaves room for the multipart envelope around the file limit of .
private const long RequestLimit = 12 * 1024 * 1024;
[HttpPost]
[RequestSizeLimit(RequestLimit)]
[EnableRateLimiting("hero-upload")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status201Created)]
public async Task 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) });
}
}
/// One image as the admin sees it now; the page asks for the images it uploaded but has not saved yet.
[HttpGet("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task 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);
}
/// The formats and limits an upload has to meet on this host (what the validation uses).
[HttpGet("limits")]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult Limits() => HeroMapping.UploadLimits(mediaStatus, media.Value);
/// Lets the background renderer try an image it gave up on again.
[HttpPost("{id:guid}/retry")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task 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 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;
}
}