Adds library saved domnain event and its handler

This commit is contained in:
BinaryAlley committed 2025-01-09 18:47:47 +02:00
1 parent 846edac83f
commit 104106d2ec
26 files changed
+475 -28

No files matched your search

@@ -3,16 +3,23 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
@@ -24,16 +31,30 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
public AddLibraryCommandHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService)
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public AddLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_authorizationService = authorizationService;
}
/// <summary>
@@ -46,6 +67,20 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
{
// make sure the file is an actual supported image
if (request.CoverImage is not null)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
ErrorOr<ImageType> imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false);
if (imageCheckResult.IsError)
return imageCheckResult.Errors;
if (imageCheckResult.Value == ImageType.None)
return DomainErrors.Library.CoverFileMustBeAnImage;
}
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
_currentUserService.UserId!.Value,
@@ -55,8 +90,13 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
request.CoverImage
);
// if the user that made the request is not an Admin, they do not have the right to create it
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
if (createLibraryResult.IsError)
return createLibraryResult.Errors;
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
// convert the domain library entity to a repository library entity
@@ -66,12 +106,24 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
if (insertLibraryResult.IsError)
return insertLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// retrieve the newly saved media library from the persistence medium and return it
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
if (getLibraryResult.Value is null)
return Errors.Persistence.ErrorPersistingMediaLibrary;
return getLibraryResult.Value.ToResponse();
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
// queue any domain events
foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
// retrieve the updated media library from the persistence medium and return it
ErrorOr<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (getCreatedLibraryResult.IsError)
return getCreatedLibraryResult.Errors;
if (getCreatedLibraryResult.Value is null)
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
return getCreatedLibraryResult.Value.ToResponse();
}
}
@@ -3,11 +3,16 @@ using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Mediator;
@@ -28,18 +33,29 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public UpdateLibraryCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
public UpdateLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
}
/// <summary>
@@ -52,6 +68,20 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
{
// make sure the file is an actual supported image
if (request.CoverImage is not null)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
ErrorOr<ImageType> imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false);
if (imageCheckResult.IsError)
return imageCheckResult.Errors;
if (imageCheckResult.Value == ImageType.None)
return DomainErrors.Library.CoverFileMustBeAnImage;
}
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
@@ -60,7 +90,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
else if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it
if (getLibraryResult.Value.UserId != _currentUserService.UserId || !await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken))
if (getLibraryResult.Value.UserId != _currentUserService.UserId || !await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
@@ -83,6 +113,10 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
return updateLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// queue any domain events
foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
// retrieve the updated media library from the persistence medium and return it
ErrorOr<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (getCreatedLibraryResult.IsError)
@@ -0,0 +1,225 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Models.Configuration;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.PhotoLibrary;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Mediator;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library is created or updated.
/// </summary>
public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedDomainEvent>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
private readonly MediaSettingsModel _mediaSettingsModel;
/// <summary>
///
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsModel"/>.</param>
public LibrarySavedDomainEventHandler(
IUnitOfWork unitOfWork,
IEnvironmentContext environmentContext,
IPathService pathService,
IOptions<MediaSettingsModel> mediaSettingsModelOptions)
{
_unitOfWork = unitOfWork;
_environmentContext = environmentContext;
_pathService = pathService;
_mediaSettingsModel = mediaSettingsModelOptions.Value;
}
/// <summary>
/// Handles the event raised when a media library is created or updated.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public async ValueTask Handle(LibrarySavedDomainEvent domainEvent, CancellationToken cancellationToken)
{
if (domainEvent.Library.CoverImage is not null)
{
// attempt to copy the image from the original location provided by the user to the internal location for media library files
ErrorOr<string> saveCoverImageResult = await SaveCoverImageToMediaDirectoryAsync(domainEvent.Library.Id.Value, domainEvent.Library.CoverImage, cancellationToken).ConfigureAwait(false);
if (saveCoverImageResult.IsError)
throw new EventualConsistencyException(saveCoverImageResult.FirstError, saveCoverImageResult.Errors);
domainEvent.Library.SetInternalLibraryCoverImagePath(saveCoverImageResult.Value);
// update the media library with the new cover location
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(domainEvent.Library.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
if (updateLibraryResult.IsError)
throw new EventualConsistencyException(updateLibraryResult.FirstError, updateLibraryResult.Errors);
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
}
else // no cover image is provided, delete any cover image that might exist in the internal location for media library files
{
ErrorOr<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
if (libraryPathResult.IsError)
throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors);
DeleteCoverImageFromMediaDirectory(libraryPathResult.Value);
}
}
/// <summary>
/// Gets the file system path of a media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The id of the media library for which to regtrieve the file system path.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either the file system path of the media library, or an error message.
/// </returns>
private ErrorOr<string> GetLibraryPath(Guid libraryId)
{
// root directory for media
ErrorOr<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory);
if (rootPathResult.IsError)
return rootPathResult.Errors;
// libraries directory
ErrorOr<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory);
if (librariesPathResult.IsError)
return librariesPathResult.Errors;
// this new particular library' directory
ErrorOr<string> libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString());
if (libraryPathResult.IsError)
return libraryPathResult.Errors;
return libraryPathResult.Value;
}
/// <summary>
/// Saves the cover image of a media library to the internal media directory.
/// </summary>
/// <param name="libraryId">The Id of the library for which to save the cover image.</param>
/// <param name="imagePath">The file path of the image file that will be copied to the media directory.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either the location of the new cover image, or an error message.
/// </returns>
private async Task<ErrorOr<string>> SaveCoverImageToMediaDirectoryAsync(Guid libraryId, string imagePath, CancellationToken cancellationToken)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(imagePath);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
ErrorOr<bool> fileExistsResult = _environmentContext.FileProviderService.FileExists(fileSystemPathIdResult.Value);
if (fileExistsResult.IsError)
return fileExistsResult.Errors;
if (!fileExistsResult.Value)
return Errors.FileSystemManagement.FileNotFound;
// make sure the file is an actual supported image
ErrorOr<ImageType> imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false);
if (imageCheckResult.IsError)
return imageCheckResult.Errors;
if (imageCheckResult.Value == ImageType.None)
return Errors.Library.CoverFileMustBeAnImage;
// the provided cover image path exists and is a valid image, store it in the media directory
ErrorOr<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media
if (rootPathResult.IsError)
return rootPathResult.Errors;
ErrorOr<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory
if (librariesPathResult.IsError)
return librariesPathResult.Errors;
ErrorOr<FileSystemPathId> rootPathIdResult = FileSystemPathId.Create(rootPathResult.Value);
if (rootPathIdResult.IsError)
return rootPathIdResult.Errors;
ErrorOr<FileSystemPathId> librariesPathIdResult = FileSystemPathId.Create(librariesPathResult.Value);
if (librariesPathIdResult.IsError)
return librariesPathIdResult.Errors;
// create the path of the new library
ErrorOr<string> libraryPathResult = GetLibraryPath(libraryId);
if (libraryPathResult.IsError)
return libraryPathResult.Errors;
ErrorOr<FileSystemPathId> newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value);
if (newLibraryPathIdResult.IsError)
return newLibraryPathIdResult.Errors;
// check if it doesn't already exist, and if so, create it
ErrorOr<bool> directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value);
if (directoryExistsResult.IsError)
return directoryExistsResult.Errors;
if (!directoryExistsResult.Value)
{
ErrorOr<FileSystemPathId> createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(librariesPathIdResult.Value, libraryId.ToString());
if (createDirectoryResult.IsError)
return createDirectoryResult.Errors;
}
else
{
// delete previous library covers that might exist
DeleteCoverImageFromMediaDirectory(libraryPathResult.Value);
ErrorOr<Deleted> deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value);
if (deleteExistingCoverImageResult.IsError)
return deleteExistingCoverImageResult.Errors;
}
// copy the new cover file from the location provided by the user
ErrorOr<FileSystemPathId> copyFileResult = _environmentContext.FileProviderService.CopyFile(fileSystemPathIdResult.Value, newLibraryPathIdResult.Value, true);
if (copyFileResult.IsError)
return copyFileResult.Errors;
// rename the new cover file to the standard naming
ErrorOr<FileSystemPathId> renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}");
if (renameFileResult.IsError)
return renameFileResult.Errors;
return renameFileResult.Value.Path;
}
/// <summary>
/// Saves the cover image of a media library to the internal media directory.
/// </summary>
/// <param name="libraryId">The Id of the library for which to save the cover image.</param>
/// <param name="imagePath">The file path of the image file that will be copied to the media directory.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either the location of the new cover image, or an error message.
/// </returns>
private ErrorOr<Deleted> DeleteCoverImageFromMediaDirectory(string libraryPath)
{
ErrorOr<FileSystemPathId> newLibraryPathIdResult = FileSystemPathId.Create(libraryPath);
if (newLibraryPathIdResult.IsError)
return newLibraryPathIdResult.Errors;
// get existing files of this media library's directory, and delete previous cover files, if they are found
ErrorOr<IEnumerable<FileSystemPathId>> getExistingLibraryFilesResult = _environmentContext.FileProviderService.GetFilePaths(newLibraryPathIdResult.Value, true);
if (getExistingLibraryFilesResult.IsError)
return getExistingLibraryFilesResult.Errors;
foreach (FileSystemPathId filePathId in getExistingLibraryFilesResult.Value)
if (Regex.IsMatch(filePathId.Path, @"[\\/]cover\.[^.\\/]+$", RegexOptions.IgnoreCase))
_environmentContext.FileProviderService.DeleteFile(filePathId);
return Result.Deleted;
}
}