Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

176 linhas
6.0 KiB

  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using AutoMapper;
  7. using Azure.Core;
  8. using Domain.Identity;
  9. using Microsoft.AspNetCore.Cors;
  10. using Microsoft.AspNetCore.Hosting;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.AspNetCore.Mvc;
  13. using Microsoft.Extensions.DependencyInjection;
  14. using Microsoft.Extensions.Hosting;
  15. using Services.Identity;
  16. using SixLabors.ImageSharp;
  17. using SixLabors.ImageSharp.Formats;
  18. using SixLabors.ImageSharp.Formats.Png;
  19. using SixLabors.ImageSharp.Processing;
  20. using Image = SixLabors.ImageSharp.Image;
  21. namespace Api.Controllers
  22. {
  23. [Route("api/[controller]/[action]")]
  24. [ApiController]
  25. [EnableCors("AllowAll")]
  26. public class BaseController : ControllerBase
  27. {
  28. private readonly AutoMapper.IMapper _mapper;
  29. private readonly IWebHostEnvironment _environment;
  30. private readonly IAuthService authService;
  31. private readonly IServiceProvider serviceProvider;
  32. //response messages
  33. public BaseController(IServiceProvider serviceProvider)
  34. {
  35. _mapper = serviceProvider.GetService<IMapper>();
  36. _environment = serviceProvider.GetService<IWebHostEnvironment>();
  37. authService = serviceProvider.GetService<IAuthService>();
  38. }
  39. public IMapper Mapper => _mapper;
  40. private T GetClaim<T>(string type)
  41. {
  42. var value = User.FindFirstValue(type) ?? "";
  43. var converter = TypeDescriptor.GetConverter(typeof(T));
  44. try
  45. {
  46. return (T)converter.ConvertFromString(value);
  47. }
  48. catch
  49. {
  50. return default;
  51. }
  52. }
  53. private Account _currentAccount;
  54. public Account CurrentAccount
  55. {
  56. get
  57. {
  58. if (_currentAccount == null)
  59. _currentAccount = authService.GetByUsername(CurrentClaim.Username);
  60. return _currentAccount;
  61. }
  62. }
  63. private CustomUser GetUser()
  64. {
  65. return new CustomUser
  66. {
  67. Id = GetClaim<Guid>(ITokenIssuer.Claims.Id),
  68. Name = GetClaim<string>(ITokenIssuer.Claims.Name),
  69. Username = GetClaim<string>(ITokenIssuer.Claims.Username),
  70. Roles = GetClaim<string>(ClaimTypes.Role).Split(',')
  71. };
  72. }
  73. public CustomUser CurrentClaim => GetUser();
  74. /// <summary>
  75. /// get images as byte array and returns maximun 1000 pixle base64
  76. /// </summary>
  77. /// <param name="inStream"></param>
  78. /// <returns></returns>
  79. [ApiExplorerSettings(IgnoreApi = true)]
  80. public byte[] ResizeImage(byte[] inStream, int maxWidth = 1000)
  81. {
  82. using (var ms = new MemoryStream())
  83. {
  84. using (Image image = Image.Load(inStream))
  85. {
  86. if (image.Width < maxWidth)
  87. {
  88. image.SaveAsPng(ms);
  89. return ms.ToArray();
  90. }
  91. var ratio = (double)(maxWidth) / image.Width;
  92. int width = image.Width;
  93. int height = (int)(image.Height * ratio);
  94. image.Mutate(x => x.Resize(width, height));
  95. image.SaveAsPng(ms);
  96. return ms.ToArray();
  97. }
  98. }
  99. }
  100. [ApiExplorerSettings(IgnoreApi = true)]
  101. private string GetUniqueFileName(string fileName)
  102. {
  103. fileName = Path.GetFileName(fileName);
  104. return string.Concat(Path.GetFileNameWithoutExtension(fileName)
  105. , "_"
  106. , Guid.NewGuid().ToString().AsSpan(0, 4)
  107. , Path.GetExtension(fileName));
  108. }
  109. /// <summary>
  110. /// Saves base64 as a PNG with max 1500px width or height
  111. /// </summary>
  112. /// <param name="fileContent">base64 image</param>
  113. /// <param name="fileName">New file=empty</param>
  114. /// <returns>File Name(all of files stores in UploadedFiles folder </returns>
  115. [ApiExplorerSettings(IgnoreApi = true)]
  116. protected string SaveImageFromBase64(string fileContent, string fileName = "")
  117. {
  118. fileName = string.IsNullOrEmpty(fileName) ? Guid.NewGuid().ToString() + ".png" : fileName;
  119. string outputPath = $"{_environment.ContentRootPath}\\UploadedFiles\\";
  120. if (!System.IO.Directory.Exists(outputPath))
  121. System.IO.Directory.CreateDirectory(outputPath);
  122. // Decode Base64 string to byte array
  123. byte[] imageBytes = Convert.FromBase64String(fileContent);
  124. using (MemoryStream ms = new MemoryStream(imageBytes))
  125. using (Image image = Image.Load(ms))
  126. {
  127. // Resize if width > 1500, keeping aspect ratio
  128. if (image.Width >= image.Height)
  129. {
  130. if (image.Width > 1500)
  131. {
  132. int newWidth = 1500;
  133. int newHeight = (int)((double)newWidth / image.Width * image.Height);
  134. image.Mutate(x => x.Resize(newWidth, newHeight));
  135. }
  136. }
  137. else
  138. {
  139. if (image.Height > 1500)
  140. {
  141. int newHeight = 1500;
  142. int newWidth = (int)((double)newHeight / image.Height * image.Width);
  143. image.Mutate(x => x.Resize(newWidth, newHeight));
  144. }
  145. }
  146. // Save as PNG
  147. image.Save($"{outputPath}{fileName}", new PngEncoder());
  148. return fileName;
  149. }
  150. }
  151. }
  152. public class CustomUser
  153. {
  154. public string Name { get; set; }
  155. public string Username { get; set; }
  156. public Guid Id { get; set; }
  157. public string[] Roles { get; set; }
  158. }
  159. }