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

@@ -2,7 +2,7 @@
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.Configuration;
namespace Lumina.Application.Common.Infrastructure.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
@@ -16,4 +16,9 @@ public class MediaSettingsModel
/// Gets or sets the root directory where media files are stored.
/// </summary>
public required string RootDirectory { get; init; }
/// <summary>
/// Gets or sets the directory where media library files are stored.
/// </summary>
public required string LibrariesDirectory { get; init; }
}
@@ -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;
}
}
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
@@ -28,5 +28,6 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
</ItemGroup>
</Project>
@@ -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));
@@ -26,7 +26,7 @@ public class ThumbnailService : IThumbnailService
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailService"/> class.
/// </summary>
/// <param name="environmentContext">Injected environment context.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
public ThumbnailService(IEnvironmentContext environmentContext)
{
_environmentContext = environmentContext;
@@ -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;
/// <summary>
/// Domain event raised when a libary is created or updated.
/// </summary>
/// <param name="Id">The Id of the domain event.</param>
/// <param name="Library">The library that was created or updated.</param>
/// <param name="OccurredOnUtc">The date and time when the domain event occurred.</param>
[DebuggerDisplay("Id: {Library.Id} Title: {Library.Title}")]
public record LibrarySavedDomainEvent(
Guid Id,
Library Library,
DateTime OccurredOnUtc
) : IDomainEvent;
@@ -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<LibraryId>
/// </summary>
public string? CoverImage { get; private set; }
/// <summary>
/// Gets the path of the image file chosen by the user to be used as the cover for the library.
/// </summary>
public string? CoverImageSourcePath { get; private set; }
/// <summary>
/// Gets the list of file system paths that make up the media library.
/// </summary>
@@ -67,6 +73,8 @@ public class Library : AggregateRoot<LibraryId>
LibraryType = libraryType;
_contentLocations = contentLocations;
CoverImage = coverImage;
_domainEvents.Add(new LibrarySavedDomainEvent(Guid.NewGuid(), this, DateTime.UtcNow));
}
/// <summary>
@@ -76,7 +84,7 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="title">The title of the media library.</param>
/// <param name="libraryType">The type of the media library (e.g., Book, TvShow).</param>
/// <param name="contentLocations">The list of file system paths that make up the media library.</param>
/// <param name="coverImage">The path of the image file used as the cover for the library.</param>
/// <param name="coverImageSourcePath">The path of the image file chosen by the user to be used as the cover for the library.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
/// </returns>
@@ -85,7 +93,7 @@ public class Library : AggregateRoot<LibraryId>
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations,
string? coverImage)
string? coverImageSourcePath)
{
List<FileSystemPathId> 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<LibraryId>
title,
libraryType,
tempContentLocations,
coverImage
coverImageSourcePath
);
}
@@ -114,7 +122,7 @@ public class Library : AggregateRoot<LibraryId>
/// <param name="title">The title of the media library.</param>
/// <param name="libraryType">The type of the media library (e.g., Book, TvShow).</param>
/// <param name="contentLocations">The list of file system paths that make up the media library.</param>
/// <param name="coverImage">The path of the image file used as the cover for the library.</param>
/// <param name="coverImageSourcePath">The path of the image file chosen by the user to be used as the cover for the library.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="Library"/>, or an error message.
/// </returns>
@@ -124,7 +132,7 @@ public class Library : AggregateRoot<LibraryId>
string title,
LibraryType libraryType,
IEnumerable<string> contentLocations,
string? coverImage)
string? coverImageSourcePath)
{
List<FileSystemPathId> 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<LibraryId>
title,
libraryType,
tempContentLocations,
coverImage
coverImageSourcePath
);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="path">The internal libray path location of the cover image file.</param>
public void SetInternalLibraryCoverImagePath(string path)
{
CoverImage = path;
}
}
@@ -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;
@@ -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));
@@ -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<MediaSettingsModel>
public MediaSettingsModelValidator()
{
RuleFor(x => x.RootDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description);
RuleFor(x => x.LibrariesDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty.Description);
}
}
@@ -1,6 +1,7 @@
{
"MediaSettings": {
"RootDirectory": "media"
"RootDirectory": "media",
"LibrariesDirectory": "libraries"
},
"CommonSettings": {
"Theme": "LuminaDark"
@@ -35,16 +35,24 @@ public class LibraryManagementController : Controller
}
/// <summary>
/// Displays the view for adding or editing a media library.
/// Displays the view for adding a media library.
/// </summary>
/// <param name="id">The optional id of the media library to edit.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("item/{id?}")]
public async Task<IActionResult> EditLibrary(Guid? id = null, CancellationToken cancellationToken = default)
[HttpGet("item")]
public IActionResult AddLibrary()
{
LibraryModel libraryModel = new();
if (id is not null)
libraryModel = await _apiHttpClient.GetAsync<LibraryModel>($"libraries/{id}", cancellationToken).ConfigureAwait(false);
return View("/Views/Library/Management/Item.cshtml", libraryModel);
}
/// <summary>
/// Displays the view for editing a media library.
/// </summary>
/// <param name="id">The id of the media library to edit.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("item/{id}")]
public async Task<IActionResult> EditLibrary(Guid id, CancellationToken cancellationToken = default)
{
LibraryModel libraryModel = await _apiHttpClient.GetAsync<LibraryModel>($"libraries/{id}", cancellationToken).ConfigureAwait(false);
return View("/Views/Library/Management/Item.cshtml", libraryModel);
}
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Bandnummer muss größer als null sein!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Die Coverdatei muss ein Bild sein!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Volume number must be greater than zero!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Cover file must be an image!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>¡El número de volumen debe ser mayor que cero!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>¡El archivo de portada debe ser una imagen!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Le numéro de volume doit être supérieur à zéro !</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Le fichier de couverture doit être une image!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Il numero del volume deve essere maggiore di zero!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Il file di copertina deve essere un'immagine!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>巻数は0より大きくなければなりません!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>カバーファイルは画像である必要があります!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Volume number must be greater than zero!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Cover file must be an image!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Numărul volumului trebuie să fie mai mare decât zero!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Fișierul copertă trebuie să fie o imagine!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>Номер тома должен быть больше нуля!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>Файл обложки должен быть изображением!</value>
</data>
</root>
@@ -540,4 +540,7 @@
<data name="VolumeNumberMustBeGreaterThanZero" xml:space="preserve">
<value>卷号必须大于零!</value>
</data>
<data name="CoverFileMustBeAnImage" xml:space="preserve">
<value>封面文件必须是图片!</value>
</data>
</root>
@@ -52,7 +52,7 @@
</div>
<ul>
<li><a href="@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")" class="nav-link"><span>@_localizer["ManageLibraries"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link"><span>@_localizer["AddNewLibrary"]</span></a></li>
<li><a href="@_urlService.GetAbsoluteUrl("AddLibrary", "LibraryManagement")" class="nav-link"><span>@_localizer["AddNewLibrary"]</span></a></li>
</ul>
<div class="mobile-menu-heading">
@_localizer["WrittenContent"]
@@ -147,7 +147,7 @@
<label for="library-menu">@_localizer["Library"]</label>
<ul>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")" class="nav-link">@_localizer["ManageLibraries"]</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")" class="nav-link">@_localizer["AddNewLibrary"]</a></li>
<li tabindex="0"><a href="@_urlService.GetAbsoluteUrl("AddLibrary", "LibraryManagement")" class="nav-link">@_localizer["AddNewLibrary"]</a></li>
<li class="has-submenu" tabindex="0">
<label>@_localizer["WrittenContent"]</label>
<ul>
@@ -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<MediaSettingsModel>()
.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<MediaSettingsModel>()
.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<MediaSettingsModel>()
.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);
}
}