Implements library management update library

This commit is contained in:
BinaryAlley committed 2024-11-17 21:02:10 +02:00
1 parent d0d53fd471
commit 291d1fa329
68 files changed
+1003 -110

No files matched your search

@@ -20,6 +20,6 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary;
public record AddLibraryCommand(
Guid UserId,
string? Title,
LibraryType? LibraryType,
string? LibraryType,
string[]? ContentLocations
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -1,13 +1,15 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -40,23 +42,31 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
{
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
request.UserId,
request.Title!,
request.LibraryType ?? LibraryType.Other,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!
);
if (createLibraryResult.IsError)
return createLibraryResult.Errors;
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// insert the repository entity and save changes
ErrorOr<Created> insertLibraryResult = await libraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
if (insertLibraryResult.IsError)
return insertLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return persistenceLibrary.ToResponse();
// retrieve the newly saved media library from the persistence medium and return it
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (retrievedLibraryResult.IsError)
return retrievedLibraryResult.Errors;
if (retrievedLibraryResult.Value is null)
return Errors.Persistence.ErrorPersistingMediaLibrary;
return retrievedLibraryResult.Value.ToResponse();
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using System;
#endregion
@@ -22,7 +23,8 @@ public class AddLibraryCommandValidator : AbstractValidator<AddLibraryCommand>
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.IsInEnum().WithMessage(Errors.Library.UnknownLibraryType.Description);
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
/// <summary>
/// Command for updating a media library.
/// </summary>
/// <param name="Id">The Id of the media library.</param>
/// <param name="OwnerId">The Id of the user owning the media library.</param>
/// <param name="CurrentUserId">The Id of the user making the request to update the media library.</param>
/// <param name="LibraryType">The type of the media library.</param>
/// <param name="ContentLocations">The file system paths of the directories where the media library elements are located.</param>
/// <param name="Title">The title of the media library.</param>
[DebuggerDisplay("Title: {Title}")]
public record UpdateLibraryCommand(
Guid Id,
Guid OwnerId,
Guid CurrentUserId,
string? Title,
string? LibraryType,
string[]? ContentLocations
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -0,0 +1,85 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Mediator;
using System;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
/// <summary>
/// Handler for the command to update a media library.
/// </summary>
public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public UpdateLibraryCommandHandler(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the command to update a media library.
/// </summary>
/// <param name="request">The request 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)
{
// get a library repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (resultGetLibrary.IsError)
return resultGetLibrary.Errors;
else if (resultGetLibrary.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it
if (resultGetLibrary.Value.UserId != request.CurrentUserId) // TODO: after implementing the Admin role, add that permission check here too
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
ErrorOr<Library> createLibraryResult = Library.Create(
LibraryId.Create(request.Id),
request.OwnerId,
request.Title!,
Enum.Parse<LibraryType>(request.LibraryType!),
request.ContentLocations!
);
if (createLibraryResult.IsError)
return createLibraryResult.Errors;
// convert the domain library entity to a repository library entity
LibraryEntity persistenceLibrary = createLibraryResult.Value.ToRepositoryEntity();
// update the repository entity and save changes
ErrorOr<Updated> updateLibraryResult = await libraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false);
if (updateLibraryResult.IsError)
return updateLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// retrieve the updated media library from the persistence medium and return it
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
if (retrievedLibraryResult.IsError)
return retrievedLibraryResult.Errors;
if (retrievedLibraryResult.Value is null)
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
return retrievedLibraryResult.Value.ToResponse();
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Enums.MediaLibrary;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary;
/// <summary>
/// Validates the needed validation rules for <see cref="UpdateLibraryCommand"/>.
/// </summary>
public class UpdateLibraryCommandValidator : AbstractValidator<UpdateLibraryCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="UpdateLibraryCommandValidator"/> class.
/// </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.CurrentUserId)
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
RuleFor(x => x.OwnerId)
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
RuleFor(x => x.LibraryType)
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
.Must(x => Enum.TryParse<LibraryType>(x, out _))
.WithMessage(Errors.Library.UnknownLibraryType.Description);
RuleFor(x => x.ContentLocations)
.NotNull().WithMessage(Errors.Library.PathsListCannotBeNull.Description)
.NotEmpty().WithMessage(Errors.Library.PathsListCannotBeEmpty.Description);
RuleForEach(x => x.ContentLocations)
.NotEmpty().WithMessage(Errors.FileSystemManagement.PathCannotBeEmpty.Description)
.MaximumLength(260).WithMessage(Errors.FileSystemManagement.PathMustBeMaximum260CharactersLong.Description);
RuleFor(x => x.Title)
.NotEmpty().WithMessage(Errors.Library.TitleCannotBeEmpty.Description)
.MaximumLength(255).WithMessage(Errors.Library.TitleMustBeMaximum255CharactersLong.Description);
}
}
@@ -0,0 +1,20 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// <summary>
/// Query for getting a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library to get.</param>
/// <param name="UserId">The Id os the user requesting the media library.</param>
[DebuggerDisplay("Path: {Path}")]
public record GetLibraryQuery(
Guid Id,
Guid UserId
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetLibraryQueryHandler(
IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to authenticate an account.
/// </summary>
/// <param name="request">The request 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)
{
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (resultGetLibrary.IsError)
return resultGetLibrary.Errors;
else if (resultGetLibrary.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that requested the library is not an Admin or is not the owner of the library, they do not have the right to view it
if (resultGetLibrary.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too
return ApplicationErrors.Authorization.NotAuthorized;
return resultGetLibrary.Value.ToResponse();
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
/// <summary>
/// Validates the needed validation rules for <see cref="GetLibraryQuery"/>.
/// </summary>
public class GetLibraryQueryValidator : AbstractValidator<GetLibraryQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryValidator"/> class.
/// </summary>
public GetLibraryQueryValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
RuleFor(x => x.UserId)
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
}
}
@@ -46,7 +46,7 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
{
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
@@ -59,7 +59,7 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
resultSelectUser.Value.TempPassword = null;
resultSelectUser.Value.TempPasswordCreated = null;
// update the user
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -56,7 +56,7 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)
@@ -76,7 +76,7 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow;
// update the user
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
if (resultUpdateUser.IsError)
return resultUpdateUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -60,7 +60,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
{
// check if any users already exists (admin account is only set once!)
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is not null)
@@ -85,7 +85,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
}
// insert the user
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken);
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
if (resultInsertUser.IsError)
return resultInsertUser.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
@@ -60,7 +60,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
{
// check if any users already exists
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken);
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
if (resultSelectUser.IsError)
return resultSelectUser.Errors;
else if (resultSelectUser.Value is null)