Files
TelegramMemeVault/src/MemeVault.Infrastructure/Services/S3FileStorage.cs
T

67 lines
1.9 KiB
C#
Raw Normal View History

2026-10-07 02:17:30 +04:00
using Amazon.S3;
using Amazon.S3.Model;
using MemeVault.Application.Common;
using MemeVault.Domain.ValueObjects;
using MemeVault.Infrastructure.Options;
using Microsoft.Extensions.Options;
namespace MemeVault.Infrastructure.Services;
/// <summary>
/// S3/MinIO-backed implementation of <see cref="IFileStorage"/>.
/// </summary>
public sealed class S3FileStorage : IFileStorage
{
private readonly IAmazonS3 _s3;
private readonly S3Options _opts;
public S3FileStorage(IAmazonS3 s3, IOptions<S3Options> opts)
{
_s3 = s3;
_opts = opts.Value;
}
public async Task<MediaSource> UploadAsync(
Stream content,
string objectKey,
string contentType,
long ownerTelegramId,
CancellationToken ct = default)
{
var request = new PutObjectRequest
{
BucketName = _opts.BucketName,
Key = objectKey,
InputStream = content,
ContentType = contentType,
// CalcMD5 + autoCloseStream defaults are fine
};
await _s3.PutObjectAsync(request, ct);
return MediaSource.FromS3(objectKey);
}
public async Task<string> GetDownloadUrlAsync(
string objectKey,
TimeSpan expiry,
CancellationToken ct = default)
{
var request = new GetPreSignedUrlRequest
{
BucketName = _opts.BucketName,
Key = objectKey,
Expires = DateTime.UtcNow.Add(expiry),
Protocol = _opts.ServiceUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
? Protocol.HTTPS
: Protocol.HTTP,
};
return await _s3.GetPreSignedURLAsync(request);
}
public async Task DeleteAsync(string objectKey, CancellationToken ct = default)
{
await _s3.DeleteObjectAsync(_opts.BucketName, objectKey, ct);
}
}