namespace GrossesMitainesAPI.Controllers; #region Dependencies using GrossesMitainesAPI.Data; using GrossesMitainesAPI.Models; using GrossesMitainesAPI.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; #endregion [EnableCors("_myAllowSpecificOrigins"), ApiController, Route("api/[controller]"), Authorize(AuthenticationSchemes = "Identity.Application")] public class ImageController : ControllerBase { #region DI Fields private readonly InventoryContext _context; private readonly IWebHostEnvironment _hostEnvironment; private readonly ILogger _logger; private readonly DatabaseCacheService? _cache = null; #endregion #region Ctor public ImageController(ILogger logger, InventoryContext context, IWebHostEnvironment hostEnvironment, DatabaseCacheService cache) { _context = context; _hostEnvironment = hostEnvironment; _logger = logger; if (cache.isOk()) _cache = cache; } #endregion #region API Methods [EnableCors("_myAllowSpecificOrigins"), HttpGet(Name = "Image"), AllowAnonymous] public IActionResult Get(int id, bool? thumbnail = false) { string path, filename, filetype; IQueryable query; if (_cache is not null) query = _cache.queryCache(); else query = _context.Products; try { filename = query.Where(x => x.Id == id).First().ImageName ?? throw new Exception("Unable to find product image name. Sending default.jpg instead..."); } catch (Exception e) { _logger.LogError(8, e.Message); filename = "default.jpg"; } path = Path.Combine(_hostEnvironment.ContentRootPath, "Images", Path.GetFileNameWithoutExtension(filename) + (thumbnail == true ? "_thumbnail" : "") + Path.GetExtension(filename)); if (!System.IO.File.Exists(path)) { _logger.LogError(8, "Unable to find image. Sending default image instead..."); path = Path.Combine(_hostEnvironment.ContentRootPath, "Images", "default.jpg"); } switch (Path.GetExtension(path)) { case ".png": filetype = "image/png"; break; case ".jpg": case ".jpeg": default: filetype = "image/jpeg"; break; } return File(System.IO.File.ReadAllBytes(path), filetype); } #endregion }