using Azaion.Common; using Azaion.Common.Configs; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Azaion.Services; public interface IResourcesService { Task GetEncryptedResource(string? dataFolder, string fileName, string key, CancellationToken cancellationToken = default); Task SaveResource(string? dataFolder, IFormFile data, CancellationToken cancellationToken = default); } public class ResourcesService(IOptions resourcesConfig, ILogger logger) : IResourcesService { public async Task GetEncryptedResource(string? dataFolder, string fileName, string key, CancellationToken cancellationToken = default) { var resourcePath = string.IsNullOrWhiteSpace(dataFolder) ? Path.Combine(resourcesConfig.Value.ResourcesFolder, fileName) : Path.Combine(resourcesConfig.Value.ResourcesFolder, dataFolder, fileName); var fileStream = new FileStream(resourcePath, FileMode.Open, FileAccess.Read); var ms = new MemoryStream(); await fileStream.EncryptTo(ms, key, cancellationToken); ms.Seek(0, SeekOrigin.Begin); return ms; } public async Task SaveResource(string? dataFolder, IFormFile data, CancellationToken cancellationToken = default) { if (data == null) throw new BusinessException(ExceptionEnum.NoFileProvided); var resourceFolder = string.IsNullOrWhiteSpace(dataFolder) ? resourcesConfig.Value.ResourcesFolder : Path.Combine(resourcesConfig.Value.ResourcesFolder, dataFolder); if (!Directory.Exists(resourceFolder)) Directory.CreateDirectory(resourceFolder); var resourcePath = Path.Combine(resourceFolder, data.FileName); await using var fileStream = new FileStream(resourcePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); await data.CopyToAsync(fileStream, cancellationToken); logger.LogInformation($"Resource {data.FileName} Saved Successfully"); } }