Files
FictionArchive/FictionArchive.Service.FileService/Controllers/S3ProxyController.cs
gamer147 6fd76f6787
All checks were successful
CI / build-backend (pull_request) Successful in 1m4s
CI / build-frontend (pull_request) Successful in 41s
[FA-misc] Fixes file caching
2025-12-10 16:09:41 -05:00

60 lines
1.8 KiB
C#

using System.Web;
using Amazon.S3;
using Amazon.S3.Model;
using FictionArchive.Service.FileService.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace FictionArchive.Service.FileService.Controllers
{
[Route("api/{*path}")]
[ApiController]
[Authorize]
public class S3ProxyController : ControllerBase
{
private readonly AmazonS3Client _amazonS3Client;
private readonly S3Configuration _s3Configuration;
public S3ProxyController(AmazonS3Client amazonS3Client, IOptions<S3Configuration> s3Configuration)
{
_amazonS3Client = amazonS3Client;
_s3Configuration = s3Configuration.Value;
}
[HttpGet]
public async Task<IActionResult> Get(string path)
{
var decodedPath = HttpUtility.UrlDecode(path);
try
{
var s3Response = await _amazonS3Client.GetObjectAsync(new GetObjectRequest()
{
BucketName = _s3Configuration.Bucket,
Key = decodedPath
});
Response.Headers.CacheControl = "public, max-age=604800"; // 7 days
Response.Headers.LastModified = s3Response.LastModified?.ToString("R");
if (!string.IsNullOrEmpty(s3Response.ETag))
{
Response.Headers.ETag = s3Response.ETag;
}
return File(s3Response.ResponseStream, s3Response.Headers.ContentType);
}
catch (AmazonS3Exception e)
{
if (e.Message == "Key not found")
{
return NotFound();
}
throw;
}
}
}
}