79 lines
3.0 KiB
C#
79 lines
3.0 KiB
C#
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Routing;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using SlpModularCms.Core.Availability;
|
|
|
|
namespace SlpModularCms.Core.Media;
|
|
|
|
public static class MediaEndpoint
|
|
{
|
|
public const string RateLimiterName = "media-public";
|
|
|
|
/// <summary>
|
|
/// <c>GET|HEAD /media/{area}/{setHash}/{name}</c>: anonymous, same origin, immutable. Only addresses of the exact
|
|
/// scheme in a registered area are served; everything else (a bad path, an unknown area, a missing file) is the same
|
|
/// plain 404. No directory is ever listed and no processing happens on this path.
|
|
/// </summary>
|
|
public static IEndpointRouteBuilder MapCmsMedia(this IEndpointRouteBuilder endpoints)
|
|
{
|
|
// The areas are known from the modules' registrations at the time the routes are mapped (before the hosted
|
|
// services run), so they are copied into the registry here.
|
|
var registrations = endpoints.ServiceProvider.GetServices<MediaAreaRegistration>().ToList();
|
|
if (registrations.Count == 0 || endpoints.ServiceProvider.GetService<MediaAreaRegistry>() is not { } registry)
|
|
{
|
|
return endpoints;
|
|
}
|
|
|
|
foreach (var registration in registrations)
|
|
{
|
|
registry.Add(registration.Area);
|
|
}
|
|
|
|
endpoints.MapMethods("/media/{**path}", ["GET", "HEAD"], ServeAsync)
|
|
.WithMetadata(new PublicSiteEndpointAttribute())
|
|
.RequireRateLimiting(RateLimiterName)
|
|
.ExcludeFromDescription();
|
|
return endpoints;
|
|
}
|
|
|
|
private static async Task<IResult> ServeAsync(string? path, HttpContext context, IMediaStore store, MediaAreaRegistry areas)
|
|
{
|
|
if (!MediaPaths.TryParse(path, out var address)
|
|
|| !areas.Contains(address.Area)
|
|
|| !MediaPaths.TryParseName(address.Name, out _, out _, out var format))
|
|
{
|
|
return Results.NotFound();
|
|
}
|
|
|
|
var file = await store.OpenReadAsync(address.Key, context.RequestAborted);
|
|
if (file is null)
|
|
{
|
|
return Results.NotFound();
|
|
}
|
|
|
|
var response = context.Response;
|
|
var etag = $"\"{address.SetHash}-{address.Name}\"";
|
|
response.Headers.CacheControl = "public, max-age=31536000, immutable";
|
|
response.Headers.ETag = etag;
|
|
response.Headers["X-Content-Type-Options"] = "nosniff";
|
|
|
|
var ifNoneMatch = context.Request.Headers.IfNoneMatch.ToString();
|
|
if (ifNoneMatch.Split(',').Select(t => t.Trim()).Contains(etag))
|
|
{
|
|
await file.Content.DisposeAsync();
|
|
return Results.StatusCode(StatusCodes.Status304NotModified);
|
|
}
|
|
|
|
response.ContentType = format.MimeType();
|
|
response.ContentLength = file.Length;
|
|
if (HttpMethods.IsHead(context.Request.Method))
|
|
{
|
|
await file.Content.DisposeAsync();
|
|
return Results.Empty;
|
|
}
|
|
|
|
return Results.Stream(file.Content, format.MimeType(), enableRangeProcessing: false);
|
|
}
|
|
}
|