using Amazon.S3; using Amazon.S3.Model; using Microsoft.Extensions.Options; using OnlineAssessment.Models; using System; using System.IO; using System.Threading.Tasks; using System.Collections.Specialized; using System.Net; namespace OnlineAssessment.Helpers { public interface IAWSS3BucketHelper { Task UploadFile(System.IO.Stream inputStream, string fileName); Task UploadFileWithMeta(System.IO.Stream inputStream, string fileName, string meta); Task FilesList(); Task GetFile(string key); Task MetaDetail(string fileName); Task DeleteFile(string key); } public class AWSS3BucketHelper : IAWSS3BucketHelper { private readonly IAmazonS3 _amazonS3; private readonly ServiceConfiguration _settings; public AWSS3BucketHelper(IAmazonS3 s3Client, IOptions settings) { this._amazonS3 = s3Client; this._settings = settings.Value; } public async Task UploadFile(System.IO.Stream inputStream, string fileName) { try { PutObjectRequest request = new PutObjectRequest() { InputStream = inputStream, BucketName = _settings.AWSS3.BucketName, Key = fileName }; PutObjectResponse response = await _amazonS3.PutObjectAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) return true; else return false; } catch (Exception ex) { throw ex; } } public async Task UploadFileWithMeta(System.IO.Stream inputStream, string fileName, string meta) { try { PutObjectRequest request = new PutObjectRequest() { InputStream = inputStream, BucketName = _settings.AWSS3.BucketName, Key = fileName }; //request.Metadata.Add("meta-title", "someTitle"); PutObjectResponse response = await _amazonS3.PutObjectAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) return true; else return false; } catch (Exception ex) { throw ex; } } public async Task FilesList() { return await _amazonS3.ListVersionsAsync(_settings.AWSS3.BucketName); } public async Task MetaDetail(string fileName) { GetObjectMetadataRequest request = new GetObjectMetadataRequest() { BucketName = _settings.AWSS3.BucketName, Key = fileName }; return await _amazonS3.GetObjectMetadataAsync(request); } public async Task GetFile(string key) { try { string file = key.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ? key : key + ".png"; string filename_print = _settings.AWSS3.BucketName + file; var response = await _amazonS3.GetObjectAsync(_settings.AWSS3.BucketName, file); if (response.HttpStatusCode == HttpStatusCode.OK) return response.ResponseStream; return null; } catch (AmazonS3Exception ex) { Console.WriteLine($"AWS S3 Error: {ex.Message} ({ex.ErrorCode})"); throw; } catch (Exception ex) { Console.WriteLine($"General Error: {ex.Message}"); throw; } } public async Task DeleteFile(string key) { try { DeleteObjectResponse response = await _amazonS3.DeleteObjectAsync(_settings.AWSS3.BucketName, key); if (response.HttpStatusCode == System.Net.HttpStatusCode.NoContent) return true; else return false; } catch (Exception ex) { throw ex; } } } }