Replaces FluentValidation and Mediator command/queries handling with custom implementations.

This commit is contained in:
BinaryAlley committed 2026-08-13 08:53:06 -07:00
1 parent 9a5c7473f9
commit 2d1c6b1ab8
297 files changed
+3619 -3045

No files matched your search

@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -31,4 +29,4 @@ public record AddLibraryCommand(
bool DownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
) : IRequest<ErrorOr<LibraryResponse>>;
) : ICommand;
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -16,8 +18,8 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -29,13 +31,14 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
/// <summary>
/// Handler for the command to add a media library.
/// </summary>
public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, ErrorOr<LibraryResponse>>
public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<AddLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddLibraryCommandHandler"/> class.
@@ -45,30 +48,36 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
/// <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>
/// <param name="validator">Injected validator for application validation rules.</param>
public AddLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<AddLibraryCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to add a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse>> HandleAsync(AddLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// if the user that made the request is not an Admin or they don't have the permission to manage media libraries, they do not have the right to create it
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
@@ -76,9 +85,9 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
return ApplicationErrors.Authorization.NotAuthorized;
// make sure the file is an actual supported image
if (request.CoverImage is not null)
if (command.CoverImage is not null)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
@@ -92,15 +101,15 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
UserId.Create(_currentUserService.UserId!.Value),
request.Title!,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!,
request.CoverImage,
request.IsEnabled,
request.IsLocked,
request.DownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan,
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
command.ContentLocations!,
command.CoverImage,
command.IsEnabled,
command.IsLocked,
command.DownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
[]
);
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
@@ -17,21 +18,28 @@ public class AddLibraryCommandValidator : AbstractValidator<AddLibraryCommand>
/// </summary>
public AddLibraryCommandValidator()
{
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(command => command.LibraryType)
.NotNull()
.WithError(Errors.Library.LibraryTypeCannotBeNull)
.Must(libraryType => Enum.TryParse<LibraryType>(libraryType, out _))
.WithError(Errors.Library.UnknownLibraryType);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description);
RuleFor(command => command.ContentLocations)
.NotNull()
.WithError(Errors.Library.PathsListCannotBeNull)
.NotEmpty()
.WithError(Errors.Library.PathsListCannotBeEmpty);
RuleForEach(x => x.ContentLocations)
.NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description)
.MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description);
RuleForEach(command => command.ContentLocations)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty)
.MaximumLength(260)
.WithError(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong);
RuleFor(x => x.Title)
.NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description);
RuleFor(command => command.Title)
.NotEmpty()
.WithError(Errors.Library.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrariesScan;
@@ -8,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari
/// <summary>
/// Command for canceling the previously started scan of all media libraries.
/// </summary>
public record CancelLibrariesScanCommand : IRequest<ErrorOr<Success>>;
public record CancelLibrariesScanCommand : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -10,7 +11,6 @@ using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrari
/// <summary>
/// Handler for the command for canceling the scan of all media libraries.
/// </summary>
public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibrariesScanCommand, ErrorOr<Success>>
{
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
@@ -51,10 +51,10 @@ public class CancelLibrariesScanCommandHandler : IRequestHandler<CancelLibraries
/// <summary>
/// Handles the command for canceling the scan of all media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(CancelLibrariesScanCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
{
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -16,4 +15,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary
public record CancelLibraryScanCommand(
Guid LibraryId,
Guid ScanId
) : IRequest<ErrorOr<Success>>;
) : ICommand;
@@ -1,15 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -21,12 +23,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.CancelLibrary
/// <summary>
/// Handler for the command for canceling the scan of a media library.
/// </summary>
public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScanCommand, ErrorOr<Success>>
public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScanCommand, ErrorOr<Success>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<CancelLibraryScanCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="CancelLibraryScanCommandHandler"/> class.
@@ -35,30 +38,37 @@ public class CancelLibraryScanCommandHandler : IRequestHandler<CancelLibraryScan
/// <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="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public CancelLibraryScanCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<CancelLibraryScanCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command for canceling the scan of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Success>> Handle(CancelLibraryScanCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Success>> HandleAsync(CancelLibraryScanCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the library scan from the repository
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(request.ScanId, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryScanEntity?> getLibraryScansResult = await libraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
if (getLibraryScansResult.IsError)
return getLibraryScansResult.Errors;
if (getLibraryScansResult.Value is null)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,11 +17,16 @@ public class CancelLibraryScanCommandValidator : AbstractValidator<CancelLibrary
/// </summary>
public CancelLibraryScanCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.ScanId)
.NotEmpty().WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.ScanIdCannotBeEmpty.Description);
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(command => command.ScanId)
.NotEmpty()
.WithError(Errors.LibraryScanning.ScanIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.LibraryScanning.ScanIdCannotBeEmpty);
}
}
@@ -1,6 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -14,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary
[DebuggerDisplay("Id: {Id}")]
public record DeleteLibraryCommand(
Guid Id
) : IRequest<ErrorOr<Deleted>>;
) : ICommand;
@@ -1,15 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -21,12 +23,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary
/// <summary>
/// Handler for the command to delete a library by its Id.
/// </summary>
public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<DeleteLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryCommandHandler"/> class.
@@ -35,29 +38,36 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
/// <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="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public DeleteLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<DeleteLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to delete a library by its Id.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<Deleted>> HandleAsync(DeleteLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -83,7 +93,7 @@ public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand,
_domainEventsQueue.Enqueue(domainEvent);
// perform the deletion
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (deletePersistenceLibraryResult.IsError)
return deletePersistenceLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class DeleteLibraryCommandValidator : AbstractValidator<DeleteLibraryComm
/// </summary>
public DeleteLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(command => command.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries
/// <summary>
/// Command for initiating the scan of all media libraries.
/// </summary>
public record ScanLibrariesCommand() : IRequest<ErrorOr<IEnumerable<MediaLibraryScanResponse>>>;
public record ScanLibrariesCommand() : ICommand;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -13,7 +14,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -25,7 +25,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibraries
/// <summary>
/// Handler for the command for initiating the scan of all media libraries.
/// </summary>
public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand, ErrorOr<IEnumerable<MediaLibraryScanResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -54,10 +54,10 @@ public class ScanLibrariesCommandHandler : IRequestHandler<ScanLibrariesCommand,
/// <summary>
/// Handles the command for initiating the scan of all media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> Handle(ScanLibrariesCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
#endregion
@@ -13,4 +11,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <param name="Id">The unique identifier of the library to scan.</param>
public record ScanLibraryCommand(
Guid Id
) : IRequest<ErrorOr<MediaLibraryScanResponse>>;
) : ICommand;
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
@@ -14,7 +16,6 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -28,12 +29,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.ScanLibrary;
/// <summary>
/// Handler for the command for initiating the scan of a media library.
/// </summary>
public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, ErrorOr<MediaLibraryScanResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IValidator<ScanLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ScanLibraryCommandHandler"/> class.
@@ -42,31 +44,38 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
/// <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="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public ScanLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<ScanLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command for initiating the scan of a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
public async ValueTask<ErrorOr<MediaLibraryScanResponse>> Handle(ScanLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<MediaLibraryScanResponse>> HandleAsync(ScanLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
// get the media library from the persistence medium
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
@@ -91,7 +100,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
return domainLibraryResult.Errors;
// get the past month's scans for this library
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<IEnumerable<LibraryScanEntity>> pastLibraryScansResult = await libraryScanRepository.GetPastMonthScansByLibraryIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (pastLibraryScansResult.IsError)
return pastLibraryScansResult.Errors;
@@ -103,7 +112,7 @@ public class ScanLibraryCommandHandler : IRequestHandler<ScanLibraryCommand, Err
// queue the media library scan
ErrorOr<LibraryScan> libraryScanResult = LibraryScan.Create(
LibraryId.Create(request.Id),
LibraryId.Create(command.Id),
UserId.Create(_currentUserService.UserId!.Value),
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
);
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class ScanLibraryCommandValidator : AbstractValidator<ScanLibraryCommand>
/// </summary>
public ScanLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(command => command.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -35,4 +33,4 @@ public record UpdateLibraryCommand(
bool DownloadMetadataFromWeb,
bool ShouldSaveMetadataInMediaDirectories,
bool ShouldSkipUnchangedDirectoriesDuringScan
) : IRequest<ErrorOr<LibraryResponse>>;
) : ICommand;
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
@@ -18,8 +20,8 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -32,13 +34,14 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary
/// <summary>
/// Handler for the command to update a media library.
/// </summary>
public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
private readonly IEnvironmentContext _environmentContext;
private readonly IValidator<UpdateLibraryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandHandler"/> class.
@@ -48,34 +51,41 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
/// <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>
/// <param name="validator">Injected validator for application validation rules.</param>
public UpdateLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IEnvironmentContext environmentContext,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<UpdateLibraryCommand> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_domainEventsQueue = domainEventsQueue;
_environmentContext = environmentContext;
_validator = validator;
}
/// <summary>
/// Handles the command to update a media library.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse>> HandleAsync(UpdateLibraryCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// make sure the file is an actual supported image
if (request.CoverImage is not null)
if (command.CoverImage is not null)
{
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(request.CoverImage);
ErrorOr<FileSystemPathId> fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage);
if (fileSystemPathIdResult.IsError)
return fileSystemPathIdResult.Errors;
@@ -88,7 +98,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
// get a library repository and retrieve the library to update
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -102,17 +112,17 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
LibraryId.Create(request.Id),
UserId.Create(request.OwnerId),
request.Title!,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!,
request.CoverImage,
request.IsEnabled,
request.IsLocked,
request.DownloadMetadataFromWeb,
request.ShouldSaveMetadataInMediaDirectories,
request.ShouldSkipUnchangedDirectoriesDuringScan,
LibraryId.Create(command.Id),
UserId.Create(command.OwnerId),
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
command.ContentLocations!,
command.CoverImage,
command.IsEnabled,
command.IsLocked,
command.DownloadMetadataFromWeb,
command.ShouldSaveMetadataInMediaDirectories,
command.ShouldSkipUnchangedDirectoriesDuringScan,
getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList()
);
if (createLibraryResult.IsError)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
@@ -17,29 +18,40 @@ public class UpdateLibraryCommandValidator : AbstractValidator<UpdateLibraryComm
/// </summary>
public UpdateLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.OwnerId)
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
RuleFor(command => command.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(command => command.OwnerId)
.NotEmpty()
.WithError(Errors.Users.UserIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Users.UserIdCannotBeEmpty);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description);
RuleFor(command => command.LibraryType)
.NotNull()
.WithError(Errors.Library.LibraryTypeCannotBeNull)
.Must(libraryType => Enum.TryParse<LibraryType>(libraryType, out _))
.WithError(Errors.Library.UnknownLibraryType);
RuleForEach(x => x.ContentLocations)
.NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description)
.MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description);
RuleFor(command => command.ContentLocations)
.NotNull()
.WithError(Errors.Library.PathsListCannotBeNull)
.NotEmpty()
.WithError(Errors.Library.PathsListCannotBeEmpty);
RuleFor(x => x.Title)
.NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description);
RuleForEach(command => command.ContentLocations)
.NotEmpty()
.WithError(Errors.FileSystemManagement.PathCannotBeEmpty)
.MaximumLength(260)
.WithError(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong);
RuleFor(command => command.Title)
.NotEmpty()
.WithError(Errors.Library.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Library.TitleMustBeMaximum255CharactersLong);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibraries;
@@ -9,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr
/// <summary>
/// Query for getting the list of enabled media libraries.
/// </summary>
public record GetEnabledLibrariesQuery : IRequest<ErrorOr<LibraryResponse[]>>;
public record GetEnabledLibrariesQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -7,7 +8,6 @@ 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 Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetEnabledLibr
/// <summary>
/// Handler for the query to get the enabled media libraries.
/// </summary>
public class GetEnabledLibrariesQueryHandler : IRequestHandler<GetEnabledLibrariesQuery, ErrorOr<LibraryResponse[]>>
public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibrariesQuery, ErrorOr<LibraryResponse[]>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -44,12 +44,12 @@ public class GetEnabledLibrariesQueryHandler : IRequestHandler<GetEnabledLibrari
/// <summary>
/// Handles the query to get the enabled media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse[]>> Handle(GetEnabledLibrariesQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
{
// get the enabled libraries from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
@@ -9,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
/// <summary>
/// Query for getting the list of media libraries.
/// </summary>
public record GetLibrariesQuery : IRequest<ErrorOr<LibraryResponse[]>>;
public record GetLibrariesQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -7,7 +8,6 @@ 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 Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -19,7 +19,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
/// <summary>
/// Handler for the query to get the media libraries.
/// </summary>
public class GetLibrariesQueryHandler : IRequestHandler<GetLibrariesQuery, ErrorOr<LibraryResponse[]>>
public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, ErrorOr<LibraryResponse[]>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -44,12 +44,12 @@ public class GetLibrariesQueryHandler : IRequestHandler<GetLibrariesQuery, Error
/// <summary>
/// Handles the query to get the media libraries.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse[]>> Handle(GetLibrariesQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
{
// get the libraries from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Diagnostics;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
[DebuggerDisplay("Id: {Id}")]
public record GetLibraryQuery(
Guid Id
) : IRequest<ErrorOr<LibraryResponse>>;
) : IQuery;
@@ -1,14 +1,16 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -20,11 +22,12 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
/// <summary>
/// Handler for the query to get a library by its Id.
/// </summary>
public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetLibraryQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryHandler"/> class.
@@ -32,29 +35,36 @@ public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<L
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetLibraryQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<GetLibraryQuery> validator)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the query to get a library by its Id.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(GetLibraryQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<LibraryResponse>> HandleAsync(GetLibraryQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,8 +17,10 @@ public class GetLibraryQueryValidator : AbstractValidator<GetLibraryQuery>
/// </summary>
public GetLibraryQueryValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(query => query.Id)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
#endregion
@@ -15,4 +13,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan
public record GetLibraryScanProgressQuery(
Guid LibraryId,
Guid ScanId
) : IRequest<ErrorOr<MediaLibraryScanProgressResponse>>;
) : IQuery;
@@ -1,17 +1,19 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
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.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
@@ -23,12 +25,13 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraryScan
/// <summary>
/// Handler for the query to get the progress of a library scan.
/// </summary>
public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScanProgressQuery, ErrorOr<MediaLibraryScanProgressResponse>>
public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanProgressQuery, ErrorOr<MediaLibraryScanProgressResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IMediaLibrariesScanProgressTracker _mediaLibrariesScanProgressTracker;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetLibraryScanProgressQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryScanProgressQueryHandler"/> class.
@@ -37,31 +40,38 @@ public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScan
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="validator">Injected validator for application validation rules.</param>
public GetLibraryScanProgressQueryHandler(
IMediaLibrariesScanProgressTracker mediaLibrariesScanProgressTracker,
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
IUnitOfWork unitOfWork,
IValidator<GetLibraryScanProgressQuery> validator)
{
_mediaLibrariesScanProgressTracker = mediaLibrariesScanProgressTracker;
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the query to get the progress of a library scan.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="MediaLibraryScanProgressResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<MediaLibraryScanProgressResponse>> Handle(GetLibraryScanProgressQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<MediaLibraryScanProgressResponse>> HandleAsync(GetLibraryScanProgressQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
if (validationResult.Count > 0)
return validationResult;
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
@@ -73,7 +83,7 @@ public class GetLibraryScanProgressQueryHandler : IRequestHandler<GetLibraryScan
return ApplicationErrors.Authorization.NotAuthorized;
ErrorOr<MediaLibraryScanProgress> getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
MediaLibraryScanCompositeId.Create(ScanId.Create(request.ScanId), UserId.Create(_currentUserService.UserId!.Value)));
MediaLibraryScanCompositeId.Create(ScanId.Create(query.ScanId), UserId.Create(_currentUserService.UserId!.Value)));
if (getProgressResult.IsError)
return getProgressResult.Errors;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Errors;
using System;
#endregion
@@ -16,11 +17,16 @@ public class GetLibraryScanProgressQueryValidator : AbstractValidator<GetLibrary
/// </summary>
public GetLibraryScanProgressQueryValidator()
{
RuleFor(x => x.ScanId)
.NotEmpty().WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty.Description);
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(query => query.ScanId)
.NotEmpty()
.WithError(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.LibraryScanning.LibraryScanIdCannotBeEmpty);
RuleFor(query => query.LibraryId)
.NotEmpty()
.WithError(Errors.Library.LibraryIdCannotBeEmpty)
.Must(id => id != Guid.Empty)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -1,8 +1,5 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Collections.Generic;
using Lumina.Application.Common.CQRS;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibraryScans;
@@ -10,4 +7,4 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr
/// <summary>
/// Query for getting the list of ongoing media library scans.
/// </summary>
public record GetRunningLibraryScansQuery : IRequest<ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>>;
public record GetRunningLibraryScansQuery : IQuery;
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
@@ -10,7 +11,6 @@ using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Mediator;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -22,7 +22,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetRunningLibr
/// <summary>
/// Handler for the query to get the ongoing media library scans.
/// </summary>
public class GetRunningLibraryScansQueryHandler : IRequestHandler<GetRunningLibraryScansQuery, ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>>
public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibraryScansQuery, ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
@@ -51,12 +51,12 @@ public class GetRunningLibraryScansQueryHandler : IRequestHandler<GetRunningLibr
/// <summary>
/// Handles the query to get the ongoing media library scans.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="MediaLibraryScanProgress"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>> Handle(GetRunningLibraryScansQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
{
// get the ongoing library scans from the repository
ILibraryScanRepository libraryScanRepository = _unitOfWork.GetRepository<ILibraryScanRepository>();
@@ -1,8 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -56,4 +54,4 @@ public record AddBookCommand(
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<BookRatingDto>? Ratings
) : IRequest<ErrorOr<BookResponse>>;
) : ICommand;
@@ -1,9 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Common.Primitives;
@@ -13,7 +15,6 @@ using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.Boo
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -27,42 +28,49 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Handler for the command to add a book.
/// </summary>
public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<BookResponse>>
public class AddBookCommandHandler : ICommandHandler<AddBookCommand, ErrorOr<BookResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly IValidator<AddBookCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public AddBookCommandHandler(IUnitOfWork unitOfWork)
/// <param name="validator">Injected validator for application validation rules.</param>
public AddBookCommandHandler(IUnitOfWork unitOfWork, IValidator<AddBookCommand> validator)
{
_unitOfWork = unitOfWork;
_validator = validator;
}
/// <summary>
/// Handles the command to add a book.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="command">The command to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="BookResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<BookResponse>> Handle(AddBookCommand request, CancellationToken cancellationToken)
public async Task<ErrorOr<BookResponse>> HandleAsync(AddBookCommand command, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(command);
if (validationResult.Count > 0)
return validationResult;
// TODO: update Api.Book.md documentation when the functionality is fully implemented
List<MediaContributorId> contributorIds = [];
foreach (MediaContributorDto mediaContributor in request.Contributors!)
foreach (MediaContributorDto mediaContributor in command.Contributors!)
{
// TODO: add logic to search the media contributors repository for existing contributors, based on the provided names
}
BookSeries? bookSeries = null;
if (request.Series != null)
if (command.Series != null)
{
// TODO: add logic to search the book series repository for existing book series, based on the provided title
// TODO: uncomment integration and unit tests about series
}
List<ErrorOr<BookRating>> domainRatingsResult = request.Ratings!.ConvertAll(rating => BookRating.Create(
List<ErrorOr<BookRating>> domainRatingsResult = command.Ratings!.ConvertAll(rating => BookRating.Create(
rating.Value ?? default,
rating.MaxValue ?? default,
Optional<BookRatingSource>.FromNullable(rating.Source.HasValue ? (BookRatingSource)(int)rating.Source : (BookRatingSource?)null),
@@ -74,88 +82,88 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
List<BookRating> domainRatings = [.. domainRatingsResult.Select(rating => rating.Value)];
List<ErrorOr<Genre>> domainGenresResult = request.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
List<ErrorOr<Genre>> domainGenresResult = command.Metadata!.Genres!.ConvertAll(genre => Genre.Create(genre.Name!));
errors = [.. domainGenresResult.Where(genreResult => genreResult.IsError).SelectMany(genreResult => genreResult.Errors)];
if (errors.Count != 0)
return errors;
List<Genre> domainGenres = [.. domainGenresResult.Select(genre => genre.Value)];
List<ErrorOr<Tag>> domainTagsResult = request.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
List<ErrorOr<Tag>> domainTagsResult = command.Metadata.Tags!.ConvertAll(tag => Tag.Create(tag.Name!));
errors = [.. domainTagsResult.Where(tagResult => tagResult.IsError).SelectMany(tagResult => tagResult.Errors)];
if (errors.Count != 0)
return errors;
List<Tag> domainTags = [.. domainTagsResult.Select(tag => tag.Value)];
List<ErrorOr<Isbn>> domainIsbnsResult = request.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
List<ErrorOr<Isbn>> domainIsbnsResult = command.ISBNs!.ConvertAll(isbn => Isbn.Create(isbn.Value!, (IsbnFormat)(int)isbn.Format!));
errors = [.. domainIsbnsResult.Where(isbnResult => isbnResult.IsError).SelectMany(isbnResult => isbnResult.Errors)];
if (errors.Count != 0)
return errors;
List<Isbn> domainIsbns = [.. domainIsbnsResult.Select(isbn => isbn.Value)];
ErrorOr<ReleaseInfo> releaseInfoResult = ReleaseInfo.Create(
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo!.OriginalReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(request.Metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(request.Metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(request.Metadata.ReleaseInfo.ReleaseVersion)
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo!.OriginalReleaseDate),
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.OriginalReleaseYear),
Optional<DateOnly>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseDate),
Optional<int>.FromNullable(command.Metadata.ReleaseInfo.ReReleaseYear),
Optional<string>.FromNullable(command.Metadata.ReleaseInfo.ReleaseCountry),
Optional<string>.FromNullable(command.Metadata.ReleaseInfo.ReleaseVersion)
);
if (releaseInfoResult.IsError)
return releaseInfoResult.Errors;
ReleaseInfo releaseInfo = releaseInfoResult.Value;
LanguageInfo? languageInfo = null;
if (request.Metadata.Language is not null)
if (command.Metadata.Language is not null)
{
ErrorOr<LanguageInfo> languageInfoResult = LanguageInfo.Create(
request.Metadata.Language.LanguageCode!,
request.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(request.Metadata.Language.NativeName));
command.Metadata.Language.LanguageCode!,
command.Metadata.Language.LanguageName!,
Optional<string>.FromNullable(command.Metadata.Language.NativeName));
if (languageInfoResult.IsError)
return languageInfoResult.Errors;
languageInfo = languageInfoResult.Value;
}
LanguageInfo? originalLanguageInfo = null;
if (request.Metadata.OriginalLanguage is not null)
if (command.Metadata.OriginalLanguage is not null)
{
ErrorOr<LanguageInfo> originalLanguageInfoResult = LanguageInfo.Create(
request.Metadata.OriginalLanguage.LanguageCode!,
request.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(request.Metadata.OriginalLanguage.NativeName));
command.Metadata.OriginalLanguage.LanguageCode!,
command.Metadata.OriginalLanguage.LanguageName!,
Optional<string>.FromNullable(command.Metadata.OriginalLanguage.NativeName));
if (originalLanguageInfoResult.IsError)
return originalLanguageInfoResult.Errors;
originalLanguageInfo = originalLanguageInfoResult.Value;
}
ErrorOr<WrittenContentMetadata> metadataResult = WrittenContentMetadata.Create(
request.Metadata.Title!,
Optional<string>.FromNullable(request.Metadata.OriginalTitle),
Optional<string>.FromNullable(request.Metadata.Description),
command.Metadata.Title!,
Optional<string>.FromNullable(command.Metadata.OriginalTitle),
Optional<string>.FromNullable(command.Metadata.Description),
releaseInfo,
domainGenres,
domainTags,
Optional<LanguageInfo>.FromNullable(languageInfo),
Optional<LanguageInfo>.FromNullable(originalLanguageInfo),
Optional<string>.FromNullable(request.Metadata.Publisher),
Optional<int>.FromNullable(request.Metadata.PageCount)
Optional<string>.FromNullable(command.Metadata.Publisher),
Optional<int>.FromNullable(command.Metadata.PageCount)
);
if (metadataResult.IsError)
return metadataResult.Errors;
ErrorOr<Book> createBookResult = Book.Create(
LibraryId.Create(request.LibraryId),
request.Path,
LibraryId.Create(command.LibraryId),
command.Path,
metadataResult.Value,
Optional<BookFormat>.FromNullable(request.Format),
Optional<string>.FromNullable(request.Edition),
request.VolumeNumber ?? default,
Optional<BookFormat>.FromNullable(command.Format),
Optional<string>.FromNullable(command.Edition),
command.VolumeNumber ?? default,
Optional<BookSeries>.FromNullable(bookSeries),
Optional<string>.FromNullable(request.ASIN),
Optional<string>.FromNullable(request.GoodreadsId),
Optional<string>.FromNullable(request.LCCN),
Optional<string>.FromNullable(request.OCLCNumber),
Optional<string>.FromNullable(request.OpenLibraryId),
Optional<string>.FromNullable(request.LibraryThingId),
Optional<string>.FromNullable(request.GoogleBooksId),
Optional<string>.FromNullable(request.BarnesAndNobleId),
Optional<string>.FromNullable(request.AppleBooksId),
Optional<string>.FromNullable(command.ASIN),
Optional<string>.FromNullable(command.GoodreadsId),
Optional<string>.FromNullable(command.LCCN),
Optional<string>.FromNullable(command.OCLCNumber),
Optional<string>.FromNullable(command.OpenLibraryId),
Optional<string>.FromNullable(command.LibraryThingId),
Optional<string>.FromNullable(command.GoogleBooksId),
Optional<string>.FromNullable(command.BarnesAndNobleId),
Optional<string>.FromNullable(command.AppleBooksId),
domainIsbns,
contributorIds,
ratings: domainRatings
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
using Lumina.Domain.SharedKernel.Common.Errors;
#endregion
@@ -16,235 +17,339 @@ public class AddBookCommandValidator : AbstractValidator<AddBookCommand>
/// </summary>
public AddBookCommandValidator()
{
RuleFor(x => x.LibraryId)
.NotEmpty().WithMessage(Errors.WrittenContent.BookLibraryCannotBeNull.Description);
RuleFor(x => x.Path)
.NotEmpty().WithMessage(Errors.WrittenContent.BookPathCannotBeEmpty.Description);
RuleFor(x => x.Metadata)
.NotNull().WithMessage(Errors.Metadata.MetadataCannotBeNull.Description)
RuleFor(command => command.LibraryId)
.NotEmpty()
.WithError(Errors.WrittenContent.BookLibraryCannotBeNull);
RuleFor(command => command.Path)
.NotEmpty()
.WithError(Errors.WrittenContent.BookPathCannotBeEmpty);
RuleFor(command => command.Metadata)
.NotNull()
.WithError(Errors.Metadata.MetadataCannotBeNull)
.ChildRules(metadata =>
{
metadata.RuleFor(m => m!.Title)
.NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description);
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.OriginalTitle)
.MaximumLength(255).When(m => m!.OriginalTitle is not null)
.WithMessage(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong.Description);
.MaximumLength(255)
.When(m => m!.OriginalTitle is not null)
.WithError(Errors.Metadata.OriginalTitleMustBeMaximum255CharactersLong);
metadata.RuleFor(m => m!.Description)
.MaximumLength(2000).When(m => m!.Description is not null)
.WithMessage(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong.Description);
.MaximumLength(2000)
.When(m => m!.Description is not null)
.WithError(Errors.Metadata.DescriptionMustBeMaximum2000CharactersLong);
metadata.RuleFor(m => m!.ReleaseInfo)
.NotNull().WithMessage(Errors.Metadata.ReleaseInfoCannotBeNull.Description)
.ChildRules(ri =>
.NotNull()
.WithError(Errors.Metadata.ReleaseInfoCannotBeNull)
.ChildRules(releaseInfo =>
{
ri.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999).When(r => r!.OriginalReleaseYear.HasValue)
.WithMessage(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999).When(r => r!.ReReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseYearMustBeBetween1And9999.Description);
ri.RuleFor(r => r!.ReleaseCountry)
.Matches("^[A-Za-z]{2}$").When(r => r!.ReleaseCountry is not null)
.WithMessage(Errors.Metadata.CountryCodeMustBe2CharactersLong.Description);
ri.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50).When(r => r!.ReleaseVersion is not null)
.WithMessage(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong.Description);
ri.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfo, originalReleaseYear) =>
!releaseInfo!.OriginalReleaseDate.HasValue ||
!releaseInfo.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfo.OriginalReleaseDate.Value.Year)
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.OriginalReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.InclusiveBetween(1, 9999)
.When(r => r!.ReReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearMustBeBetween1And9999);
releaseInfo.RuleFor(r => r!.ReleaseCountry)
.Matches("^[A-Za-z]{2}$")
.When(r => r!.ReleaseCountry is not null)
.WithError(Errors.Metadata.CountryCodeMustBe2CharactersLong);
releaseInfo.RuleFor(r => r!.ReleaseVersion)
.MaximumLength(50)
.When(r => r!.ReleaseVersion is not null)
.WithError(Errors.Metadata.ReleaseVersionMustBeMaximum50CharactersLong);
releaseInfo.RuleFor(r => r!.OriginalReleaseYear)
.Must((releaseInfoInstance, originalReleaseYear) =>
!releaseInfoInstance!.OriginalReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
originalReleaseYear == releaseInfoInstance.OriginalReleaseDate.Value.Year)
.When(r => r!.OriginalReleaseDate.HasValue && r.OriginalReleaseYear.HasValue)
.WithMessage(Errors.Metadata.OriginalReleaseDateAndYearMustMatch.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfo, reReleaseYear) =>
!releaseInfo!.ReReleaseDate.HasValue ||
!releaseInfo.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfo.ReReleaseDate.Value.Year)
.WithError(Errors.Metadata.OriginalReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfo, reReleaseYear) =>
!releaseInfo!.ReReleaseYear.HasValue ||
!releaseInfo.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfo.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear.Description);
ri.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfo, reReleaseDate) =>
!releaseInfo!.ReReleaseDate.HasValue ||
!releaseInfo.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfo.OriginalReleaseDate)
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseYear.HasValue ||
!releaseInfoInstance.OriginalReleaseYear.HasValue ||
reReleaseYear >= releaseInfoInstance.OriginalReleaseYear)
.When(r => r!.ReReleaseYear.HasValue && r.OriginalReleaseYear.HasValue)
.WithError(Errors.Metadata.ReReleaseYearCannotBeEarlierThanOriginalReleaseYear);
releaseInfo.RuleFor(r => r!.ReReleaseDate)
.Must((releaseInfoInstance, reReleaseDate) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.OriginalReleaseDate.HasValue ||
reReleaseDate >= releaseInfoInstance.OriginalReleaseDate)
.When(r => r!.ReReleaseDate.HasValue && r.OriginalReleaseDate.HasValue)
.WithMessage(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate.Description);
ri.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfo, reReleaseYear) =>
!releaseInfo!.ReReleaseDate.HasValue ||
!releaseInfo.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfo.ReReleaseDate.Value.Year)
.WithError(Errors.Metadata.ReReleaseDateCannotBeEarlierThanOriginalReleaseDate);
releaseInfo.RuleFor(r => r!.ReReleaseYear)
.Must((releaseInfoInstance, reReleaseYear) =>
!releaseInfoInstance!.ReReleaseDate.HasValue ||
!releaseInfoInstance.ReReleaseYear.HasValue ||
reReleaseYear == releaseInfoInstance.ReReleaseDate.Value.Year)
.When(r => r!.ReReleaseDate.HasValue && r.ReReleaseYear.HasValue)
.WithMessage(Errors.Metadata.ReReleaseDateAndYearMustMatch.Description);
.WithError(Errors.Metadata.ReReleaseDateAndYearMustMatch);
});
metadata.RuleFor(m => m!.Genres)
.NotNull().WithMessage(Errors.Metadata.GenresListCannotBeNull.Description);
.NotNull()
.WithError(Errors.Metadata.GenresListCannotBeNull);
metadata.RuleForEach(m => m!.Genres)
.ChildRules(g =>
g.RuleFor(genre => genre.Name)
.NotEmpty().WithMessage(Errors.Metadata.GenreNameCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong.Description));
.ChildRules(genre =>
genre.RuleFor(g => g.Name)
.NotEmpty()
.WithError(Errors.Metadata.GenreNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.GenreNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Tags)
.NotNull().WithMessage(Errors.Metadata.TagsListCannotBeNull.Description);
.NotNull()
.WithError(Errors.Metadata.TagsListCannotBeNull);
metadata.RuleForEach(m => m!.Tags)
.ChildRules(t =>
t.RuleFor(tag => tag.Name)
.NotEmpty().WithMessage(Errors.Metadata.TagNameCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.Metadata.TagNameMustBeMaximum50CharactersLong.Description));
metadata.RuleFor(m => m!.Language)
.Custom((language, context) =>
{
if (language is null)
return;
if (string.IsNullOrEmpty(language.LanguageCode))
context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
else if (language.LanguageCode.Length > 2)
context.AddFailure("Language.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description);
if (string.IsNullOrEmpty(language.LanguageName))
context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description);
else if (language.LanguageName.Length > 50)
context.AddFailure("Language.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description);
if (language.NativeName != null && language.NativeName.Length > 50)
context.AddFailure("Language.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description);
});
metadata.RuleFor(m => m!.OriginalLanguage)
.Custom((language, context) =>
{
if (language is null)
return;
if (string.IsNullOrEmpty(language.LanguageCode))
context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeCannotBeEmpty.Description);
else if (language.LanguageCode.Length > 2)
context.AddFailure("OriginalLanguage.LanguageCode", Errors.Metadata.LanguageCodeMustBe2CharactersLong.Description);
if (string.IsNullOrEmpty(language.LanguageName))
context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameCannotBeEmpty.Description);
else if (language.LanguageName.Length > 50)
context.AddFailure("OriginalLanguage.LanguageName", Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong.Description);
if (language.NativeName != null && language.NativeName.Length > 50)
context.AddFailure("OriginalLanguage.NativeName", Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong.Description);
});
.ChildRules(tag =>
tag.RuleFor(t => t.Name)
.NotEmpty()
.WithError(Errors.Metadata.TagNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.TagNameMustBeMaximum50CharactersLong));
metadata.RuleFor(m => m!.Language!.LanguageCode)
.NotEmpty()
.WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.Language!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.Language is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageCode)
.NotEmpty().WithError(Errors.Metadata.LanguageCodeCannotBeEmpty)
.MaximumLength(2)
.WithError(Errors.Metadata.LanguageCodeMustBe2CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.LanguageName)
.NotEmpty()
.WithError(Errors.Metadata.LanguageNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.OriginalLanguage!.NativeName)
.MaximumLength(50)
.WithError(Errors.Metadata.LanguageNativeNameMustBeMaximum50CharactersLong)
.When(m => m!.OriginalLanguage is not null);
metadata.RuleFor(m => m!.Publisher)
.MaximumLength(100).When(m => m!.Publisher is not null)
.WithMessage(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong.Description);
.MaximumLength(100)
.When(m => m!.Publisher is not null)
.WithError(Errors.WrittenContent.PublisherMustBeMaximum100CharactersLong);
metadata.RuleFor(m => m!.PageCount)
.GreaterThan(0).When(m => m!.PageCount.HasValue)
.WithMessage(Errors.WrittenContent.PageCountMustBeGreaterThanZero.Description);
.GreaterThan(0)
.When(m => m!.PageCount.HasValue)
.WithError(Errors.WrittenContent.PageCountMustBeGreaterThanZero);
});
RuleFor(x => x.Format)
.IsInEnum().When(f => f.Format is not null).WithMessage(Errors.WrittenContent.UnknownBookFormat.Description);
RuleFor(x => x.Edition)
.MaximumLength(50).When(x => x.Edition is not null)
.WithMessage(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong.Description);
RuleFor(x => x.VolumeNumber)
.GreaterThan(0).When(x => x.VolumeNumber.HasValue)
.WithMessage(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero.Description);
RuleFor(x => x.Series)
.ChildRules(s =>
s.RuleFor(series => series!.Title)
.NotEmpty().WithMessage(Errors.Metadata.TitleCannotBeEmpty.Description)
.MaximumLength(255)).WithMessage(Errors.Metadata.TitleMustBeMaximum255CharactersLong.Description)
.When(x => x.Series is not null);
RuleFor(x => x.ASIN)
.Length(10).When(x => x.ASIN is not null)
.WithMessage(Errors.WrittenContent.AsinMustBe10CharactersLong.Description);
RuleFor(x => x.GoodreadsId)
.Matches(@"^\d+$").When(x => x.GoodreadsId is not null)
.WithMessage(Errors.WrittenContent.GoodreadsIdMustBeNumeric.Description);
RuleFor(x => x.LCCN)
.Matches(@"^[a-z]{0,3}\d{8,10}$").WithMessage(Errors.WrittenContent.InvalidLccnFormat.Description)
.When(x => x.LCCN is not null);
RuleFor(x => x.OCLCNumber)
.Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(x => x.OCLCNumber is not null)
.WithMessage(Errors.WrittenContent.InvalidOclcFormat.Description);
RuleFor(x => x.OpenLibraryId)
.Matches(@"^OL[1-9]\d*[AMW]$").When(x => x.OpenLibraryId is not null)
.WithMessage(Errors.WrittenContent.InvalidOpenLibraryId.Description);
RuleFor(x => x.LibraryThingId)
.MaximumLength(50).When(x => x.LibraryThingId is not null)
.WithMessage(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong.Description);
RuleFor(x => x.GoogleBooksId)
.Length(12).WithMessage(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong.Description)
.Matches(@"^[A-Za-z0-9_-]{12}$").WithMessage(Errors.WrittenContent.InvalidGoogleBooksIdFormat.Description)
.When(x => x.GoogleBooksId is not null);
RuleFor(x => x.BarnesAndNobleId)
.Length(10).WithMessage(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong.Description)
.Matches(@"^\d{10}$").WithMessage(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat.Description)
.When(x => x.BarnesAndNobleId is not null);
RuleFor(x => x.AppleBooksId)
.Matches(@"^id\d+$").When(x => x.AppleBooksId is not null)
.WithMessage(Errors.WrittenContent.InvalidAppleBooksIdFormat.Description);
RuleFor(x => x.ISBNs)
.NotNull().WithMessage(Errors.WrittenContent.IsbnListCannotBeNull.Description);
RuleForEach(x => x.ISBNs)
RuleFor(command => command.Format)
.IsInEnum()
.When(command => command.Format is not null)
.WithError(Errors.WrittenContent.UnknownBookFormat);
RuleFor(command => command.Edition)
.MaximumLength(50)
.When(command => command.Edition is not null)
.WithError(Errors.WrittenContent.EditionMustBeMaximum50CharactersLong);
RuleFor(command => command.VolumeNumber)
.GreaterThan(0)
.When(command => command.VolumeNumber.HasValue)
.WithError(Errors.WrittenContent.VolumeNumberMustBeGreaterThanZero);
RuleFor(command => command.Series)
.ChildRules(series =>
series.RuleFor(s => s!.Title)
.NotEmpty()
.WithError(Errors.Metadata.TitleCannotBeEmpty)
.MaximumLength(255)
.WithError(Errors.Metadata.TitleMustBeMaximum255CharactersLong))
.When(command => command.Series is not null);
RuleFor(command => command.ASIN)
.Length(10)
.When(command => command.ASIN is not null)
.WithError(Errors.WrittenContent.AsinMustBe10CharactersLong);
RuleFor(command => command.GoodreadsId)
.Matches(@"^\d+$")
.When(command => command.GoodreadsId is not null)
.WithError(Errors.WrittenContent.GoodreadsIdMustBeNumeric);
RuleFor(command => command.LCCN)
.Matches(@"^[a-z]{0,3}\d{8,10}$")
.When(command => command.LCCN is not null)
.WithError(Errors.WrittenContent.InvalidLccnFormat);
RuleFor(command => command.OCLCNumber)
.Matches(@"^(ocm\d{8}|ocn\d{9,}|on\d{10,}|\(OCoLC\)\d{8,}|\d{8,})$").When(command => command.OCLCNumber is not null)
.WithError(Errors.WrittenContent.InvalidOclcFormat);
RuleFor(command => command.OpenLibraryId)
.Matches(@"^OL[1-9]\d*[AMW]$")
.When(command => command.OpenLibraryId is not null)
.WithError(Errors.WrittenContent.InvalidOpenLibraryId);
RuleFor(command => command.LibraryThingId)
.MaximumLength(50)
.When(command => command.LibraryThingId is not null)
.WithError(Errors.WrittenContent.LibraryThingIdMustBeMaximum50CharactersLong);
RuleFor(command => command.GoogleBooksId)
.Length(12)
.When(command => command.GoogleBooksId is not null)
.WithError(Errors.WrittenContent.GoogleBooksIdMustBe12CharactersLong)
.Matches(@"^[A-Za-z0-9_-]{12}$")
.When(command => command.GoogleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidGoogleBooksIdFormat);
RuleFor(command => command.BarnesAndNobleId)
.Length(10)
.When(command => command.BarnesAndNobleId is not null)
.WithError(Errors.WrittenContent.BarnesAndNoblesIdMustBe10CharactersLong)
.Matches(@"^\d{10}$")
.When(command => command.BarnesAndNobleId is not null)
.WithError(Errors.WrittenContent.InvalidBarnesAndNoblesIdFormat);
RuleFor(command => command.AppleBooksId)
.Matches(@"^id\d+$")
.When(command => command.AppleBooksId is not null)
.WithError(Errors.WrittenContent.InvalidAppleBooksIdFormat);
RuleFor(command => command.ISBNs)
.NotNull()
.WithError(Errors.WrittenContent.IsbnListCannotBeNull);
RuleForEach(command => command.ISBNs)
.ChildRules(isbn =>
{
isbn.RuleFor(i => i.Value)
.NotEmpty().WithMessage(Errors.WrittenContent.IsbnValueCannotBeEmpty.Description)
.Matches(i => i.Format == IsbnFormat.Isbn13
? @"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$"
: @"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$")
.WithMessage(i => i.Format == IsbnFormat.Isbn13
? Errors.WrittenContent.InvalidIsbn13Format.Description
: Errors.WrittenContent.InvalidIsbn10Format.Description);
.NotEmpty()
.WithError(Errors.WrittenContent.IsbnValueCannotBeEmpty);
isbn.RuleFor(i => i.Value)
.Matches(@"^(?:ISBN(?:-13)?:? )?(?=[0-9]{13}$|(?=(?:[0-9]+[-\ ]){4})[-\ 0-9]{17}$)97[89][-\ ]?[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9]$")
.When(i => i.Format == IsbnFormat.Isbn13)
.WithError(Errors.WrittenContent.InvalidIsbn13Format);
isbn.RuleFor(i => i.Value)
.Matches(@"^(?:ISBN(?:-10)?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[-\ ]){3})[-\ 0-9X]{13}$)[0-9]{1,5}[-\ ]?[0-9]+[-\ ]?[0-9]+[-\ ]?[0-9X]$")
.When(i => i.Format == IsbnFormat.Isbn10)
.WithError(Errors.WrittenContent.InvalidIsbn10Format);
isbn.RuleFor(i => i.Format)
.IsInEnum().WithMessage(Errors.WrittenContent.UnknownIsbnFormat.Description);
.IsInEnum()
.WithError(Errors.WrittenContent.UnknownIsbnFormat);
});
RuleFor(x => x.Contributors)
.NotNull().WithMessage(Errors.MediaContributor.ContributorsListCannotBeNull.Description);
RuleForEach(x => x.Contributors)
RuleFor(command => command.Contributors)
.NotNull()
.WithError(Errors.MediaContributor.ContributorsListCannotBeNull);
RuleForEach(command => command.Contributors)
.ChildRules(contributor =>
{
contributor.RuleFor(c => c.Name)
.NotNull().WithMessage(Errors.MediaContributor.ContributorNameCannotBeEmpty.Description)
.NotNull()
.WithError(Errors.MediaContributor.ContributorNameCannotBeEmpty)
.ChildRules(name =>
{
name.RuleFor(n => n!.DisplayName)
.NotNull().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description)
.NotEmpty().WithMessage(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty.Description)
.MaximumLength(100).WithMessage(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong.Description);
.NotNull()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.NotEmpty()
.WithError(Errors.MediaContributor.ContributorDisplayNameCannotBeEmpty)
.MaximumLength(100)
.WithError(Errors.MediaContributor.ContributorDisplayNameMustBeMaximum100CharactersLong);
name.RuleFor(n => n!.LegalName)
.MaximumLength(100).When(n => n!.LegalName is not null)
.WithMessage(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong.Description);
.MaximumLength(100)
.When(n => n!.LegalName is not null)
.WithError(Errors.MediaContributor.ContributorLegalNameMustBeMaximum100CharactersLong);
});
contributor.RuleFor(c => c.Role)
.NotNull().WithMessage(Errors.MediaContributor.ContributorRoleCannotBeNull.Description)
.NotNull()
.WithError(Errors.MediaContributor.ContributorRoleCannotBeNull)
.ChildRules(role =>
{
role.RuleFor(r => r!.Name)
.NotEmpty().WithMessage(Errors.MediaContributor.RoleNameCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong.Description);
.NotEmpty()
.WithError(Errors.MediaContributor.RoleNameCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleNameMustBeMaximum50CharactersLong);
role.RuleFor(r => r!.Category)
.NotEmpty().WithMessage(Errors.MediaContributor.RoleCategoryCannotBeEmpty.Description)
.MaximumLength(50).WithMessage(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong.Description);
.NotEmpty()
.WithError(Errors.MediaContributor.RoleCategoryCannotBeEmpty)
.MaximumLength(50)
.WithError(Errors.MediaContributor.RoleCategoryMustBeMaximum50CharactersLong);
});
});
RuleFor(x => x.Ratings)
.NotNull().WithMessage(Errors.Metadata.RatingsListCannotBeNull.Description);
RuleForEach(x => x.Ratings)
RuleFor(command => command.Ratings)
.NotNull()
.WithError(Errors.Metadata.RatingsListCannotBeNull);
RuleForEach(command => command.Ratings)
.ChildRules(rating =>
{
rating.RuleFor(r => r.Value)
.GreaterThan(0).WithMessage(Errors.Metadata.RatingValueMustBePositive.Description)
.Must((r, value) => value <= r.MaxValue).WithMessage(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue.Description);
.GreaterThan(0)
.WithError(Errors.Metadata.RatingValueMustBePositive)
.Must((ratingInstance, value) => value <= ratingInstance.MaxValue)
.WithError(Errors.Metadata.RatingValueCannotBeGreaterThanMaxValue);
rating.RuleFor(r => r.MaxValue)
.GreaterThan(0).WithMessage(Errors.Metadata.RatingMaxValueMustBePositive.Description);
.GreaterThan(0)
.WithError(Errors.Metadata.RatingMaxValueMustBePositive);
rating.RuleFor(r => r.VoteCount)
.GreaterThanOrEqualTo(0).When(r => r.VoteCount.HasValue)
.WithMessage(Errors.Metadata.RatingVoteCountMustBePositive.Description);
.GreaterThanOrEqualTo(0)
.When(r => r.VoteCount.HasValue)
.WithError(Errors.Metadata.RatingVoteCountMustBePositive);
});
}
}
@@ -1,9 +1,6 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using Lumina.Application.Common.CQRS;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
@@ -14,4 +11,4 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <param name="LibraryId">The Id of the media library whose books are retrieved.</param>
public record GetBooksQuery(
Guid LibraryId
) : IRequest<ErrorOr<IEnumerable<BookResponse>>>;
) : IQuery;
@@ -1,11 +1,11 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Mediator;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -16,7 +16,7 @@ namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrar
/// <summary>
/// Handler for the query to get all books.
/// </summary>
public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnumerable<BookResponse>>>
public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, ErrorOr<IEnumerable<BookResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
@@ -32,17 +32,17 @@ public class GetBooksQueryHandler : IRequestHandler<GetBooksQuery, ErrorOr<IEnum
/// <summary>
/// Handles the query to get all books.
/// </summary>
/// <param name="request">The request to be handled.</param>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="BookResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<IEnumerable<BookResponse>>> Handle(GetBooksQuery request, CancellationToken cancellationToken)
public async Task<ErrorOr<IEnumerable<BookResponse>>> HandleAsync(GetBooksQuery query, CancellationToken cancellationToken)
{
// get a books repository
IBookRepository bookRepository = _unitOfWork.GetRepository<IBookRepository>();
// get all books of the media library from the book repository
ErrorOr<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(request.LibraryId, cancellationToken).ConfigureAwait(false);
ErrorOr<IEnumerable<BookEntity>> getBooksResult = await bookRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
return getBooksResult.Match(result => ErrorOrFactory.From(getBooksResult.Value.ToResponses()), errors => errors);
}
}