using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using CoviDok.Api; using CoviDok.Api.Request; using CoviDok.BLL; using CoviDok.BLL.Sessions; using CoviDok.BLL.Storage; using CoviDok.Data.SessionProviders; using CoviDok.Data.StorageProviders; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using NCuid; namespace CoviDok.Controllers { [Route("api/[controller]")] [ApiController] public class ImagesController : ControllerBase { private StorageHandler MinioHandler = new StorageHandler(new MinioProvider()); private readonly string BucketName = "test1"; private readonly SessionHandler Handler = new SessionHandler(); private static Stream MakeStream(string s) { var stream = new MemoryStream(); var writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } [HttpPost("Upload")] public async Task> OnPostImage(ImagePost post) { GenericResponse response = new GenericResponse(); try { Session s = await Handler.GetSession(post.SessionId); Console.WriteLine("ImagesController:OnPostImage - Incoming request, ID: " + post.SessionId + ", payload: " + post.File.Length); string id = Cuid.Generate(); StorageResult Result = await MinioHandler.UploadImage(BucketName, MakeStream(post.File), post.File.Length, id); Console.WriteLine("ImagesController:OnPostImage - Request successful, uploaded " + id); if (!Result.Success) response.Status = Status.Error; response.Body["reason"] = Result.Data; return response; } catch (UnauthorizedAccessException) { response.Status = Status.Error; response.Body["reason"] = "unauthorized"; return response; } } [HttpPost("Download")] public async Task OnGetImage(ImageGet imageGet) { GenericResponse response = new GenericResponse(); try { Session s = await Handler.GetSession(imageGet.SessionId); string res = null; await MinioHandler.GetImage(BucketName, imageGet.ImageId, (stream) => { StreamReader reader = new StreamReader(stream); res = reader.ReadToEnd(); }); response.Body["image"] = res; return response; } catch (UnauthorizedAccessException) { response.Status = Status.Error; response.Body["reason"] = "unauthorized"; return response; } catch (KeyNotFoundException) { response.Status = Status.Error; response.Body["reason"] = "Image not found!"; return response; } } } }