72 lines
2.1 KiB
C#
72 lines
2.1 KiB
C#
using Amazon.Runtime;
|
|
using Amazon.S3;
|
|
using Amazon.S3.Model;
|
|
|
|
namespace Messenger.Api.Services;
|
|
|
|
public sealed class S3AttachmentStorage : IAttachmentStorage, IDisposable
|
|
{
|
|
private readonly AmazonS3Client _client;
|
|
private readonly string _bucket;
|
|
|
|
public S3AttachmentStorage(S3Settings settings)
|
|
{
|
|
var config = new AmazonS3Config
|
|
{
|
|
ServiceURL = settings.Endpoint,
|
|
ForcePathStyle = true,
|
|
AuthenticationRegion = settings.Region,
|
|
Timeout = TimeSpan.FromSeconds(15),
|
|
MaxErrorRetry = 1
|
|
};
|
|
|
|
var credentials = new BasicAWSCredentials(settings.AccessKey, settings.SecretKey);
|
|
_client = new AmazonS3Client(credentials, config);
|
|
|
|
_bucket = settings.Bucket;
|
|
}
|
|
|
|
public async Task PutAsync(string objectKey, Stream content, string contentType, CancellationToken ct)
|
|
{
|
|
var request = new PutObjectRequest
|
|
{
|
|
BucketName = _bucket,
|
|
Key = objectKey,
|
|
InputStream = content,
|
|
ContentType = contentType,
|
|
// Поток принадлежит вызывающему коду, а не SDK.
|
|
AutoCloseStream = false
|
|
};
|
|
|
|
await _client.PutObjectAsync(request, ct);
|
|
}
|
|
|
|
public async Task CopyToAsync(string objectKey, Stream destination, CancellationToken ct)
|
|
{
|
|
var request = new GetObjectRequest
|
|
{
|
|
BucketName = _bucket,
|
|
Key = objectKey
|
|
};
|
|
|
|
using var response = await _client.GetObjectAsync(request, ct);
|
|
await response.ResponseStream.CopyToAsync(destination, ct);
|
|
}
|
|
|
|
public async Task DeleteAsync(string objectKey, CancellationToken ct)
|
|
{
|
|
var request = new DeleteObjectRequest
|
|
{
|
|
BucketName = _bucket,
|
|
Key = objectKey
|
|
};
|
|
|
|
await _client.DeleteObjectAsync(request, ct);
|
|
}
|
|
|
|
public void Dispose() => _client.Dispose();
|
|
|
|
public async Task CheckAsync(CancellationToken ct) =>
|
|
await _client.GetBucketLocationAsync(new GetBucketLocationRequest { BucketName = _bucket }, ct);
|
|
}
|