Files
yes.blog/Yes.Application/Admins/Themes/DeleteThemeCommandHandler.cs
2025-05-16 23:14:52 +08:00

60 lines
2.0 KiB
C#

namespace Yes.Application.Admins.Themes
{
public record DeleteThemeCommand(string ThemeName) : IRequest<DeleteThemeCommandResponse>;
public record DeleteThemeCommandResponse();
public class DeleteThemeCommandHandler(
IWebHostEnvironment env,
BlogDbContext db,
IIdentityContext identity,
IOptionsMonitor<BlogSettings> options) : IRequestHandler<DeleteThemeCommand, DeleteThemeCommandResponse>
{
private readonly IWebHostEnvironment _env = env;
private readonly BlogSettings _settings = options.CurrentValue;
private readonly BlogDbContext _db = db;
private readonly IIdentityContext _identity = identity;
public async Task<DeleteThemeCommandResponse> Handle(DeleteThemeCommand request, CancellationToken cancellationToken)
{
var identityUser = await _db.Users.FindAsync(_identity.Id);
if (identityUser == null)
{
throw new UserNotExistsException(_identity.Id);
}
if (!identityUser.IsSystemUser())
{
throw new AccessDeniedException();
}
try
{
var themeName = request.ThemeName;
if (_settings.Theme == themeName)
{
throw new ThemeInUseException();
}
var targetDirectory = Path.Combine(_env.ContentRootPath, "files", "themes", themeName);
if (Directory.Exists(targetDirectory))
Directory.Delete(targetDirectory, recursive: true);
return new DeleteThemeCommandResponse();
}
catch (Exception ex) when (ex is OverflowException)
{
throw new FileOverflowException();
}
catch (Exception ex) when (ex is InvalidDataException)
{
throw new FileNotSupportedException(ex.Message);
}
}
}
}