From 104106d2ec3ce6ddc9552cd080a2bba4f79dabef Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 9 Jan 2025 18:47:47 +0200 Subject: [PATCH] Adds library saved domnain event and its handler --- .../Configuration/MediaSettingsModel.cs | 7 +- .../AddLibrary/AddLibraryCommandHandler.cs | 62 ++++- .../UpdateLibraryCommandHandler.cs | 38 ++- .../Events/LibrarySavedDomainEventHandler.cs | 225 ++++++++++++++++++ .../Lumina.Application.csproj | 3 +- .../Common/Errors/Errors.Library.cs | 1 + .../Services/ThumbnailService.cs | 2 +- .../Events/LibrarySavedDomainEvent.cs | 20 ++ .../LibraryAggregate/Library.cs | 29 ++- .../SharedConfiguration.cs | 1 + .../Common/Errors/Errors.Configuration.cs | 1 + .../Validators/MediaSettingsModelValidator.cs | 3 +- .../appsettings.shared.json | 3 +- .../Management/LibraryManagementController.cs | 22 +- .../ExceptionHandlingMiddleware.de-DE.resx | 3 + .../ExceptionHandlingMiddleware.en-US.resx | 3 + .../ExceptionHandlingMiddleware.es-ES.resx | 3 + .../ExceptionHandlingMiddleware.fr-FR.resx | 3 + .../ExceptionHandlingMiddleware.it-IT.resx | 3 + .../ExceptionHandlingMiddleware.ja-JP.resx | 3 + .../ExceptionHandlingMiddleware.resx | 3 + .../ExceptionHandlingMiddleware.ro-RO.resx | 3 + .../ExceptionHandlingMiddleware.ru-RU.resx | 3 + .../ExceptionHandlingMiddleware.zh-CN.resx | 3 + .../Views/Shared/_NavMenu.cshtml | 4 +- .../MediaSettingsModelValidatorTests.cs | 52 +++- 26 files changed, 475 insertions(+), 28 deletions(-) rename src/{Lumina.Infrastructure/Common => Lumina.Application/Common/Infrastructure}/Models/Configuration/MediaSettingsModel.cs (70%) create mode 100644 src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs create mode 100644 src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/MediaSettingsModel.cs b/src/Lumina.Application/Common/Infrastructure/Models/Configuration/MediaSettingsModel.cs similarity index 70% rename from src/Lumina.Infrastructure/Common/Models/Configuration/MediaSettingsModel.cs rename to src/Lumina.Application/Common/Infrastructure/Models/Configuration/MediaSettingsModel.cs index f00b484b..c851eb97 100644 --- a/src/Lumina.Infrastructure/Common/Models/Configuration/MediaSettingsModel.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/Configuration/MediaSettingsModel.cs @@ -2,7 +2,7 @@ using System.Diagnostics; #endregion -namespace Lumina.Infrastructure.Common.Models.Configuration; +namespace Lumina.Application.Common.Infrastructure.Models.Configuration; /// /// Model for deserializing media settings. @@ -16,4 +16,9 @@ public class MediaSettingsModel /// Gets or sets the root directory where media files are stored. /// public required string RootDirectory { get; init; } + + /// + /// Gets or sets the directory where media library files are stored. + /// + public required string LibrariesDirectory { get; init; } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 961e2db2..17c5fa05 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -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 /// Initializes a new instance of the class. /// - /// Injected unit of work for interacting with the data access layer repositories. + /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. - public AddLibraryCommandHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService) + /// Injected service for the queue of domain events. + /// Injected facade service for environment contextual services. + /// Injected unit of work for interacting with the data access layer repositories. + public AddLibraryCommandHandler( + IAuthorizationService authorizationService, + ICurrentUserService currentUserService, + IDomainEventsQueue domainEventsQueue, + IEnvironmentContext environmentContext, + IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; _currentUserService = currentUserService; + _domainEventsQueue = domainEventsQueue; + _environmentContext = environmentContext; + _authorizationService = authorizationService; } /// @@ -46,6 +67,20 @@ public class AddLibraryCommandHandler : IRequestHandler public async ValueTask> Handle(AddLibraryCommand request, CancellationToken cancellationToken) { + // make sure the file is an actual supported image + if (request.CoverImage is not null) + { + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + + ErrorOr 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 createLibraryResult = Library.Create( _currentUserService.UserId!.Value, @@ -55,8 +90,13 @@ public class AddLibraryCommandHandler : IRequestHandler(); // convert the domain library entity to a repository library entity @@ -66,12 +106,24 @@ public class AddLibraryCommandHandler : IRequestHandler 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 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(); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 9d96ad7e..ff8c32b4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -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 /// Initializes a new instance of the class. /// /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. + /// Injected service for the queue of domain events. + /// Injected facade service for environment contextual services. /// Injected unit of work for interacting with the data access layer repositories. - 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; } /// @@ -52,6 +68,20 @@ public class UpdateLibraryCommandHandler : IRequestHandler public async ValueTask> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken) { + // make sure the file is an actual supported image + if (request.CoverImage is not null) + { + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + + ErrorOr 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(); ErrorOr getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false); @@ -60,7 +90,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false); if (getCreatedLibraryResult.IsError) diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs new file mode 100644 index 00000000..3aa16913 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -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; + +/// +/// Handler for the event raised when a media library is created or updated. +/// +public class LibrarySavedDomainEventHandler : INotificationHandler +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IEnvironmentContext _environmentContext; + private readonly IPathService _pathService; + private readonly MediaSettingsModel _mediaSettingsModel; + + /// + /// + /// + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected facade service for environment contextual services. + /// Injected service for handling file system paths. + /// Injected service for retrieving . + public LibrarySavedDomainEventHandler( + IUnitOfWork unitOfWork, + IEnvironmentContext environmentContext, + IPathService pathService, + IOptions mediaSettingsModelOptions) + { + _unitOfWork = unitOfWork; + _environmentContext = environmentContext; + _pathService = pathService; + _mediaSettingsModel = mediaSettingsModelOptions.Value; + } + + /// + /// Handles the event raised when a media library is created or updated. + /// + /// The domain event to be handled. + /// Cancellation token that can be used to stop the execution. + 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 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(); + ErrorOr 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 libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value); + if (libraryPathResult.IsError) + throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors); + DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); + } + } + + /// + /// Gets the file system path of a media library identified by . + /// + /// The id of the media library for which to regtrieve the file system path. + /// + /// An containing either the file system path of the media library, or an error message. + /// + private ErrorOr GetLibraryPath(Guid libraryId) + { + // root directory for media + ErrorOr rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); + if (rootPathResult.IsError) + return rootPathResult.Errors; + + // libraries directory + ErrorOr librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); + if (librariesPathResult.IsError) + return librariesPathResult.Errors; + + // this new particular library' directory + ErrorOr libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString()); + if (libraryPathResult.IsError) + return libraryPathResult.Errors; + return libraryPathResult.Value; + } + + /// + /// Saves the cover image of a media library to the internal media directory. + /// + /// The Id of the library for which to save the cover image. + /// The file path of the image file that will be copied to the media directory. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the location of the new cover image, or an error message. + /// + private async Task> SaveCoverImageToMediaDirectoryAsync(Guid libraryId, string imagePath, CancellationToken cancellationToken) + { + ErrorOr fileSystemPathIdResult = FileSystemPathId.Create(imagePath); + if (fileSystemPathIdResult.IsError) + return fileSystemPathIdResult.Errors; + + ErrorOr 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 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 rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory); // root directory for media + if (rootPathResult.IsError) + return rootPathResult.Errors; + + ErrorOr librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory); // libraries directory + if (librariesPathResult.IsError) + return librariesPathResult.Errors; + + ErrorOr rootPathIdResult = FileSystemPathId.Create(rootPathResult.Value); + if (rootPathIdResult.IsError) + return rootPathIdResult.Errors; + + ErrorOr librariesPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); + if (librariesPathIdResult.IsError) + return librariesPathIdResult.Errors; + + // create the path of the new library + ErrorOr libraryPathResult = GetLibraryPath(libraryId); + if (libraryPathResult.IsError) + return libraryPathResult.Errors; + + ErrorOr newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value); + if (newLibraryPathIdResult.IsError) + return newLibraryPathIdResult.Errors; + + // check if it doesn't already exist, and if so, create it + ErrorOr directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(newLibraryPathIdResult.Value); + if (directoryExistsResult.IsError) + return directoryExistsResult.Errors; + + if (!directoryExistsResult.Value) + { + ErrorOr 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 deleteExistingCoverImageResult = DeleteCoverImageFromMediaDirectory(libraryPathResult.Value); + if (deleteExistingCoverImageResult.IsError) + return deleteExistingCoverImageResult.Errors; + } + // copy the new cover file from the location provided by the user + ErrorOr 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 renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageCheckResult.Value.ToString().ToLower()}"); + if (renameFileResult.IsError) + return renameFileResult.Errors; + + return renameFileResult.Value.Path; + } + + /// + /// Saves the cover image of a media library to the internal media directory. + /// + /// The Id of the library for which to save the cover image. + /// The file path of the image file that will be copied to the media directory. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either the location of the new cover image, or an error message. + /// + private ErrorOr DeleteCoverImageFromMediaDirectory(string libraryPath) + { + + ErrorOr 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> 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; + } +} diff --git a/src/Lumina.Application/Lumina.Application.csproj b/src/Lumina.Application/Lumina.Application.csproj index e4b4642a..56ecccde 100644 --- a/src/Lumina.Application/Lumina.Application.csproj +++ b/src/Lumina.Application/Lumina.Application.csproj @@ -1,4 +1,4 @@ - + net9.0 disable @@ -28,5 +28,6 @@ + diff --git a/src/Lumina.Domain/Common/Errors/Errors.Library.cs b/src/Lumina.Domain/Common/Errors/Errors.Library.cs index a941299f..43802d9d 100644 --- a/src/Lumina.Domain/Common/Errors/Errors.Library.cs +++ b/src/Lumina.Domain/Common/Errors/Errors.Library.cs @@ -15,6 +15,7 @@ public static partial class Errors public static Error LibraryAlreadyExists => Error.Conflict(description: nameof(LibraryAlreadyExists)); public static Error LibraryNotFound => Error.NotFound(description: nameof(LibraryNotFound)); public static Error LibraryTypeCannotBeNull => Error.Validation(description: nameof(LibraryTypeCannotBeNull)); + public static Error CoverFileMustBeAnImage => Error.Validation(description: nameof(CoverFileMustBeAnImage)); public static Error UnknownLibraryType => Error.Unexpected(description: nameof(UnknownLibraryType)); public static Error PathsListCannotBeNull => Error.Validation(description: nameof(PathsListCannotBeNull)); public static Error PathsListCannotBeEmpty => Error.Validation(description: nameof(PathsListCannotBeEmpty)); diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs index 816e63ac..11501e7c 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/ThumbnailService.cs @@ -26,7 +26,7 @@ public class ThumbnailService : IThumbnailService /// /// Initializes a new instance of the class. /// - /// Injected environment context. + /// Injected facade service for environment contextual services. public ThumbnailService(IEnvironmentContext environmentContext) { _environmentContext = environmentContext; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs new file mode 100644 index 00000000..50a034c1 --- /dev/null +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Events/LibrarySavedDomainEvent.cs @@ -0,0 +1,20 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; + +/// +/// Domain event raised when a libary is created or updated. +/// +/// The Id of the domain event. +/// The library that was created or updated. +/// The date and time when the domain event occurred. +[DebuggerDisplay("Id: {Library.Id} Title: {Library.Title}")] +public record LibrarySavedDomainEvent( + Guid Id, + Library Library, + DateTime OccurredOnUtc +) : IDomainEvent; diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 7446081b..9fdadc05 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -3,6 +3,7 @@ using ErrorOr; using Lumina.Domain.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using System; @@ -40,6 +41,11 @@ public class Library : AggregateRoot /// public string? CoverImage { get; private set; } + /// + /// Gets the path of the image file chosen by the user to be used as the cover for the library. + /// + public string? CoverImageSourcePath { get; private set; } + /// /// Gets the list of file system paths that make up the media library. /// @@ -67,6 +73,8 @@ public class Library : AggregateRoot LibraryType = libraryType; _contentLocations = contentLocations; CoverImage = coverImage; + + _domainEvents.Add(new LibrarySavedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow)); } /// @@ -76,7 +84,7 @@ public class Library : AggregateRoot /// The title of the media library. /// The type of the media library (e.g., Book, TvShow). /// The list of file system paths that make up the media library. - /// The path of the image file used as the cover for the library. + /// The path of the image file chosen by the user to be used as the cover for the library. /// /// An containing either a successfully created , or an error message. /// @@ -85,7 +93,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, IEnumerable contentLocations, - string? coverImage) + string? coverImageSourcePath) { List tempContentLocations = []; // go through all the file system paths that make up the media library and create domain objects from them @@ -102,7 +110,7 @@ public class Library : AggregateRoot title, libraryType, tempContentLocations, - coverImage + coverImageSourcePath ); } @@ -114,7 +122,7 @@ public class Library : AggregateRoot /// The title of the media library. /// The type of the media library (e.g., Book, TvShow). /// The list of file system paths that make up the media library. - /// The path of the image file used as the cover for the library. + /// The path of the image file chosen by the user to be used as the cover for the library. /// /// An containing either a successfully created , or an error message. /// @@ -124,7 +132,7 @@ public class Library : AggregateRoot string title, LibraryType libraryType, IEnumerable contentLocations, - string? coverImage) + string? coverImageSourcePath) { List tempContentLocations = []; // go through all the file system paths that make up the media library and create domain objects from them @@ -141,7 +149,16 @@ public class Library : AggregateRoot title, libraryType, tempContentLocations, - coverImage + coverImageSourcePath ); } + + /// + /// Sets the file system path where the cover image was copied to from where it was located when the user selected it, to the internal library. + /// + /// The internal libray path location of the cover image file. + public void SetInternalLibraryCoverImagePath(string path) + { + CoverImage = path; + } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs index 430d8cfe..ebd28609 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.Configuration; using Lumina.Infrastructure.Common.Models.Configuration; using Lumina.Infrastructure.Common.Utilities; using Microsoft.Extensions.Configuration; diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index 94fb3220..2ef61c98 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -14,6 +14,7 @@ public static partial class Errors public static Error ApplicationThemeCannotBeEmpty => Error.Validation(description: nameof(ApplicationThemeCannotBeEmpty)); public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty)); public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty)); + public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty)); public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty)); public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String)); public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty)); diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs index caf6d52e..0d23296f 100644 --- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs @@ -1,6 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FluentValidation; -using Lumina.Infrastructure.Common.Models.Configuration; +using Lumina.Application.Common.Infrastructure.Models.Configuration; #endregion namespace Lumina.Infrastructure.Common.Validators; @@ -16,5 +16,6 @@ public class MediaSettingsModelValidator : AbstractValidator public MediaSettingsModelValidator() { RuleFor(x => x.RootDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); + RuleFor(x => x.LibrariesDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description); } } diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 215c4274..6145e0ae 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -1,6 +1,7 @@ { "MediaSettings": { - "RootDirectory": "media" + "RootDirectory": "media", + "LibrariesDirectory": "libraries" }, "CommonSettings": { "Theme": "LuminaDark" diff --git a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs index 4c5b71b1..958c89e2 100644 --- a/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs +++ b/src/Lumina.Presentation.Web/Controllers/Library/Management/LibraryManagementController.cs @@ -35,16 +35,24 @@ public class LibraryManagementController : Controller } /// - /// Displays the view for adding or editing a media library. + /// Displays the view for adding a media library. /// - /// The optional id of the media library to edit. - /// Cancellation token that can be used to stop the execution. - [HttpGet("item/{id?}")] - public async Task EditLibrary(Guid? id = null, CancellationToken cancellationToken = default) + [HttpGet("item")] + public IActionResult AddLibrary() { LibraryModel libraryModel = new(); - if (id is not null) - libraryModel = await _apiHttpClient.GetAsync($"libraries/{id}", cancellationToken).ConfigureAwait(false); + return View("/Views/Library/Management/Item.cshtml", libraryModel); + } + + /// + /// Displays the view for editing a media library. + /// + /// The id of the media library to edit. + /// Cancellation token that can be used to stop the execution. + [HttpGet("item/{id}")] + public async Task EditLibrary(Guid id, CancellationToken cancellationToken = default) + { + LibraryModel libraryModel = await _apiHttpClient.GetAsync($"libraries/{id}", cancellationToken).ConfigureAwait(false); return View("/Views/Library/Management/Item.cshtml", libraryModel); } diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx index b62e24c8..01ad9aef 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.de-DE.resx @@ -540,4 +540,7 @@ Bandnummer muss größer als null sein! + + Die Coverdatei muss ein Bild sein! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx index f949be0c..d9489262 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.en-US.resx @@ -540,4 +540,7 @@ Volume number must be greater than zero! + + Cover file must be an image! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx index da624ff0..93ffbcf6 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.es-ES.resx @@ -540,4 +540,7 @@ ¡El número de volumen debe ser mayor que cero! + + ¡El archivo de portada debe ser una imagen! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx index 5c0d6138..0f7aa647 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.fr-FR.resx @@ -540,4 +540,7 @@ Le numéro de volume doit être supérieur à zéro ! + + Le fichier de couverture doit être une image! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx index c8b8d4c9..311bba59 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.it-IT.resx @@ -540,4 +540,7 @@ Il numero del volume deve essere maggiore di zero! + + Il file di copertina deve essere un'immagine! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx index 539f4afc..e593ace3 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ja-JP.resx @@ -540,4 +540,7 @@ 巻数は0より大きくなければなりません! + + カバーファイルは画像である必要があります! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx index 3d70ef17..fcd32e32 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.resx @@ -540,4 +540,7 @@ Volume number must be greater than zero! + + Cover file must be an image! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx index b698683c..0edd4874 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ro-RO.resx @@ -540,4 +540,7 @@ Numărul volumului trebuie să fie mai mare decât zero! + + Fișierul copertă trebuie să fie o imagine! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx index 24a1ccb7..ca4c8f8f 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.ru-RU.resx @@ -540,4 +540,7 @@ Номер тома должен быть больше нуля! + + Файл обложки должен быть изображением! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx index dad89403..448253f9 100644 --- a/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Resources/Common/Middlewares/ExceptionHandlingMiddleware.zh-CN.resx @@ -540,4 +540,7 @@ 卷号必须大于零! + + 封面文件必须是图片! + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml index 17058e8d..b88205c7 100644 --- a/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml +++ b/src/Lumina.Presentation.Web/Views/Shared/_NavMenu.cshtml @@ -52,7 +52,7 @@
@_localizer["WrittenContent"] @@ -147,7 +147,7 @@
  • @_localizer["ManageLibraries"]
  • -
  • @_localizer["AddNewLibrary"]
  • +
  • @_localizer["AddNewLibrary"]
    • diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs index d44b6a43..7aa47d01 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Validators/MediaSettingsModelValidatorTests.cs @@ -2,8 +2,8 @@ using AutoFixture; using AutoFixture.AutoNSubstitute; using FluentAssertions; +using Lumina.Application.Common.Infrastructure.Models.Configuration; using Lumina.Infrastructure.Common.Errors; -using Lumina.Infrastructure.Common.Models.Configuration; using Lumina.Infrastructure.Common.Validators; using System.Diagnostics.CodeAnalysis; #endregion @@ -77,4 +77,54 @@ public class MediaSettingsModelValidatorTests result.Errors.Should().ContainSingle() .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description); } + + [Fact] + public void MediaSettingsModelValidator_WhenMediaLibrariesDirectoryIsEmpty_ShouldHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.LibrariesDirectory, string.Empty) + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description); + } + + [Fact] + public void MediaSettingsModelValidator_WhenMediaLibrariesDirectoryProvided_ShouldNotHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.LibrariesDirectory, "/path/to/media") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeTrue(); + result.Errors.Should().BeEmpty(); + } + + [Fact] + public void MediaSettingsModelValidator_WhenMediaLibrariesDirectoryIsWhitespace_ShouldHaveValidationError() + { + // Arrange + MediaSettingsModel model = _fixture.Build() + .With(x => x.LibrariesDirectory, " ") + .Create(); + + // Act + FluentValidation.Results.ValidationResult result = _validator.Validate(model); + + // Assert + result.IsValid.Should().BeFalse(); + result.Errors.Should().ContainSingle() + .Which.ErrorMessage.Should().Be(Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description); + } }