fixes for s3 integration

This commit is contained in:
2023-12-04 09:51:11 -06:00
parent ddb4756f4e
commit 47a82e18a7
6 changed files with 71 additions and 62 deletions

View File

@@ -1,6 +1,5 @@
using Amazon.S3;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using Unbinder.Services;
namespace Unbinder.Controllers
@@ -11,36 +10,40 @@ namespace Unbinder.Controllers
{
try
{
var objects = await S3Service.ListObjects();
S3Service s3Service = new();
var response = await s3Service.ListObjects();
if (objects != null)
{
string keys = "";
foreach (var entry in objects.S3Objects)
{
keys += entry.Key + ", ";
}
if (keys != "") logger.Log(LogLevel.Information, $"Found keys: {keys ?? "(none)"}");
}
else
if (response == null)
{
logger.Log(LogLevel.Debug, "Did not find results in S3");
return View();
}
string keys = "";
foreach (var entry in response.S3Objects)
{
keys += entry.Key + ", ";
}
if (keys != "") logger.Log(LogLevel.Information, $"Found keys: {keys ?? "(none)"}");
return View(response.S3Objects);
}
catch (Exception ex)
{
if (ex is AmazonS3Exception s3Exception)
{
logger.Log(LogLevel.Warning, s3Exception.ErrorCode);
logger.Log(LogLevel.Warning, s3Exception.Message);
}
else
logger.Log(LogLevel.Error, ex.Message);
HandleError(ex, logger);
return View();
}
}
return View();
private static void HandleError(Exception ex, ILogger logger)
{
if (ex is AmazonS3Exception s3Exception)
{
logger.Log(LogLevel.Warning, s3Exception.ErrorCode);
logger.Log(LogLevel.Warning, s3Exception.Message);
}
else
logger.Log(LogLevel.Error, ex.Message);
}
}
}

View File

@@ -47,13 +47,14 @@ builder.Services.AddCors(options =>
builder.Services.AddScoped<IRecipeRepository, RecipeRepository>();
builder.Services.AddScoped<IIngredientRepository, IngredientRepository>();
// include aws service
builder.Services.AddTransient<S3Service>();
// configure front end features
builder.Services.AddHttpContextAccessor();
builder.Services.AddServerSideBlazor();
// include extra services
//builder.Services.AddSingleton(S3Service.Client);
// build app
var app = builder.Build();
// apply most recent migration to db

View File

@@ -9,18 +9,17 @@ namespace Unbinder.Services
{
public sealed class S3Service
{
private static AmazonS3Client CreateClient()
{
return new AmazonS3Client(Credentials, Config);
}
private static AWSCredentials Credentials
{
get
{
string? accessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY");
string? secret = Environment.GetEnvironmentVariable("AWS_SECRET_KEY");
if (accessKey == null || secret == null)
{
throw new Exception("AWS credentials not found");
}
string accessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY") ?? throw new Exception("AWS credentials not found");
string secret = Environment.GetEnvironmentVariable("AWS_SECRET_KEY") ?? throw new Exception("AWS credentials not found");
return new BasicAWSCredentials(accessKey, secret);
}
}
@@ -30,43 +29,39 @@ namespace Unbinder.Services
RegionEndpoint = RegionEndpoint.USEast2
};
private static AmazonS3Client Client => new(Credentials, Config);
private static readonly AmazonS3Client client = Client;
private static readonly string? BucketName = Environment.GetEnvironmentVariable("AWS_BUCKET_NAME");
private static readonly string BucketName = Environment.GetEnvironmentVariable("AWS_BUCKET_NAME") ?? throw new Exception("AWS_BUCKET_NAME is not defined");
public static async Task<ListObjectsResponse> ListObjects(string? prefix = "")
public async Task<ListObjectsResponse> ListObjects(string? prefix = "")
{
var bucketName = BucketName;
using var _client = CreateClient();
var request = new ListObjectsRequest
{
BucketName = bucketName,
BucketName = BucketName,
Prefix = prefix
};
return await client.ListObjectsAsync(request);
return await _client.ListObjectsAsync(request);
}
public async Task<string?> UploadFileAsync(IFormFile file)
{
if (file == null || file.Length == 0)
{
return null;
}
if (file == null || file.Length == 0) return null;
var bucketName = "unbinder-recipe-images";
var keyName = file.FileName;
using var _client = CreateClient();
using var fileTransferUtility = new TransferUtility(_client);
using var fileTransferUtility = new TransferUtility(client);
await fileTransferUtility.UploadAsync(file.OpenReadStream(), bucketName, keyName);
await fileTransferUtility.UploadAsync(
/** Stream stream, string bucketName, string key */
file.OpenReadStream(), BucketName, file.FileName);
return keyName;
return file.FileName;
}
public async Task GetFile(string path, string outFile)
{
var bucketName = "unbinder-recipe-images";
using var fileTransferUtility = new TransferUtility(client);
await fileTransferUtility.DownloadAsync(outFile, bucketName, path);
using var _client = CreateClient();
using var fileTransferUtility = new TransferUtility(_client);
await fileTransferUtility.DownloadAsync(outFile, BucketName, path);
}
}
}

View File

@@ -1,4 +1,6 @@
@{
@model IEnumerable<S3Object>?
@{
ViewData["Title"] = "UNBINDER";
}
@@ -6,4 +8,15 @@
<h1 class="display-4">UNBINDER</h1>
<p>Digitize your unruly home information stores</p>
<p>Become <span>u&nbsp;n&nbsp;b&nbsp;o&nbsp;u&nbsp;n&nbsp;d</span></p>
@if (Model != null)
{
int i = 1;
foreach (var item in Model)
{
var output = $"{i}: {item.Key.Split(".")[0]}";
<p>@output</p>
i++;
}
}
</div>

View File

@@ -1,16 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Unbinder.Views.Home
{
public class IndexModel : PageModel
public class IndexModel(ILogger<IndexModel> logger) : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
private readonly ILogger<IndexModel> _logger = logger;
public void OnGet()
{

View File

@@ -2,6 +2,7 @@
@using Unbinder.Models
@using Unbinder.ViewModels
@using Unbinder.Controllers
@using Amazon.S3.Model
@namespace Unbinder.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers