Files
admin/Azaion.Services/ResourcesService.cs
T
2024-12-24 12:48:02 +02:00

50 lines
2.1 KiB
C#

using Azaion.Common;
using Azaion.Common.Configs;
using Azaion.Common.Database;
using Azaion.Common.Entities;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Azaion.Services;
public interface IResourcesService
{
Task<Stream> GetEncryptedResource(string? dataFolder, string fileName, string key, CancellationToken cancellationToken = default);
Task SaveResource(string? dataFolder, IFormFile data, CancellationToken cancellationToken = default);
}
public class ResourcesService(IOptions<ResourcesConfig> resourcesConfig, ILogger<ResourcesService> logger) : IResourcesService
{
public async Task<Stream> 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");
}
}