[FA-misc] Mass transit overhaul, needs testing and review
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using FictionArchive.Common.Enums;
|
||||
using FictionArchive.Service.FileService.Models;
|
||||
using FictionArchive.Service.Shared.MassTransit.Contracts.Commands;
|
||||
using FictionArchive.Service.Shared.MassTransit.Contracts.Events;
|
||||
using MassTransit;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace FictionArchive.Service.FileService.Services.EventHandlers;
|
||||
|
||||
public class UploadFileCommandConsumer : IConsumer<UploadFileCommand>
|
||||
{
|
||||
private readonly ILogger<UploadFileCommandConsumer> _logger;
|
||||
private readonly AmazonS3Client _amazonS3Client;
|
||||
private readonly S3Configuration _s3Configuration;
|
||||
private readonly ProxyConfiguration _proxyConfiguration;
|
||||
|
||||
public UploadFileCommandConsumer(
|
||||
ILogger<UploadFileCommandConsumer> logger,
|
||||
AmazonS3Client amazonS3Client,
|
||||
IOptions<S3Configuration> s3Configuration,
|
||||
IOptions<ProxyConfiguration> proxyConfiguration)
|
||||
{
|
||||
_logger = logger;
|
||||
_amazonS3Client = amazonS3Client;
|
||||
_proxyConfiguration = proxyConfiguration.Value;
|
||||
_s3Configuration = s3Configuration.Value;
|
||||
}
|
||||
|
||||
public async Task Consume(ConsumeContext<UploadFileCommand> context)
|
||||
{
|
||||
var command = context.Message;
|
||||
|
||||
var putObjectRequest = new PutObjectRequest();
|
||||
putObjectRequest.BucketName = _s3Configuration.Bucket;
|
||||
putObjectRequest.Key = command.FilePath;
|
||||
putObjectRequest.UseChunkEncoding = false; // Needed to avoid an error with Garage
|
||||
|
||||
using MemoryStream memoryStream = new MemoryStream(command.FileData);
|
||||
putObjectRequest.InputStream = memoryStream;
|
||||
|
||||
var s3Response = await _amazonS3Client.PutObjectAsync(putObjectRequest);
|
||||
if (s3Response.HttpStatusCode != System.Net.HttpStatusCode.OK)
|
||||
{
|
||||
_logger.LogError("An error occurred while uploading file to S3. Response code: {responsecode}", s3Response.HttpStatusCode);
|
||||
await context.Publish(new FileUploadCompletedEvent
|
||||
{
|
||||
RequestId = command.RequestId,
|
||||
Status = RequestStatus.Failed,
|
||||
ErrorMessage = "An error occurred while uploading file to S3."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await context.Publish(new FileUploadCompletedEvent
|
||||
{
|
||||
Status = RequestStatus.Success,
|
||||
RequestId = command.RequestId,
|
||||
FileAccessUrl = _proxyConfiguration.BaseUrl + "/" + command.FilePath
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user