Adds media libraries management view

This commit is contained in:
BinaryAlley committed 2025-01-11 23:11:33 +02:00
1 parent b593cbce93
commit d7c8478101
162 files changed
+3741 -171

No files matched your search

@@ -64,7 +64,7 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
/// <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.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(AddLibraryCommand request, CancellationToken cancellationToken)
{
@@ -93,7 +93,7 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
// 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) &&
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.canCreateLibraries, cancellationToken).ConfigureAwait(false))
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
if (createLibraryResult.IsError)
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Mediator;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary;
/// <summary>
/// Command for deleting a media library by its Id.
/// </summary>
/// <param name="Id">The Id of the media library to delete.</param>
[DebuggerDisplay("Id: {Id}")]
public record DeleteLibraryCommand(
Guid Id
) : IRequest<ErrorOr<Deleted>>;
@@ -0,0 +1,96 @@
#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.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
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.Commands.DeleteLibrary;
/// <summary>
/// Handler for the command to delete a library by its Id.
/// </summary>
public class DeleteLibraryCommandHandler : IRequestHandler<DeleteLibraryCommand, ErrorOr<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IDomainEventsQueue _domainEventsQueue;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryCommandHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public DeleteLibraryCommandHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IDomainEventsQueue domainEventsQueue,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_domainEventsQueue = domainEventsQueue;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the command to delete a library by its Id.
/// </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 successfuly created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteLibraryCommand request, CancellationToken cancellationToken)
{
// 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);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that wants to delete the library is not an Admin or is not the owner of the library, they do not have the right to delete it
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
ErrorOr<Library> createLibraryResult = getLibraryResult.Value.ToDomainEntity();
if (createLibraryResult.IsError)
return createLibraryResult.Errors;
// delete the domain aggregate
ErrorOr<Deleted> deleteDomainLibraryResult = createLibraryResult.Value.Delete();
if (deleteDomainLibraryResult.IsError)
return deleteDomainLibraryResult.Errors;
// queue any domain events
foreach (IDomainEvent domainEvent in createLibraryResult.Value.PopDomainEvents())
_domainEventsQueue.Enqueue(domainEvent);
// perform the deletion
ErrorOr<Deleted> deletePersistenceLibraryResult = await libraryRepository.DeleteByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
if (deletePersistenceLibraryResult.IsError)
return deletePersistenceLibraryResult.Errors;
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
return deletePersistenceLibraryResult;
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteLibraryCommand"/>.
/// </summary>
public class DeleteLibraryCommandValidator : AbstractValidator<DeleteLibraryCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteLibraryCommandValidator"/> class.
/// </summary>
public DeleteLibraryCommandValidator()
{
RuleFor(x => x.Id)
.NotEmpty().WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
}
}
@@ -65,7 +65,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
/// <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.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly updated <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(UpdateLibraryCommand request, CancellationToken cancellationToken)
{
@@ -93,7 +93,7 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
(!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.canCreateLibraries, cancellationToken)))
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken)))
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
@@ -0,0 +1,88 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.Infrastructure.Models.Configuration;
using Lumina.Domain.Common.Exceptions;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events;
using Mediator;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Events;
/// <summary>
/// Handler for the event raised when a media library is deleted.
/// </summary>
public class LibraryDeletedDomainEventHandler : INotificationHandler<LibraryDeletedDomainEvent>
{
private readonly IEnvironmentContext _environmentContext;
private readonly IPathService _pathService;
private readonly MediaSettingsModel _mediaSettingsModel;
/// <summary>
/// Initializes a new instance of the <see cref="LibraryDeletedDomainEventHandler"/> class.
/// </summary>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
/// <param name="pathService">Injected service for handling file system paths.</param>
/// <param name="mediaSettingsModelOptions">Injected service for retrieving <see cref="MediaSettingsModel"/>.</param>
public LibraryDeletedDomainEventHandler(IEnvironmentContext environmentContext, IPathService pathService, IOptions<MediaSettingsModel> mediaSettingsModelOptions)
{
_environmentContext = environmentContext;
_pathService = pathService;
_mediaSettingsModel = mediaSettingsModelOptions.Value;
}
/// <summary>
/// Handles the event raised when a media library is deleted.
/// </summary>
/// <param name="domainEvent">The domain event to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public ValueTask Handle(LibraryDeletedDomainEvent domainEvent, CancellationToken cancellationToken)
{
// delete the media library directory in the internal location for media library files
ErrorOr<string> libraryPathResult = GetLibraryPath(domainEvent.Library.Id.Value);
if (libraryPathResult.IsError)
throw new EventualConsistencyException(libraryPathResult.FirstError, libraryPathResult.Errors);
ErrorOr<FileSystemPathId> newLibraryPathIdResult = FileSystemPathId.Create(libraryPathResult.Value);
if (newLibraryPathIdResult.IsError)
throw new EventualConsistencyException(newLibraryPathIdResult.FirstError, newLibraryPathIdResult.Errors);
ErrorOr<Deleted> deleteLibraryDirectoryResult = _environmentContext.DirectoryProviderService.DeleteDirectory(newLibraryPathIdResult.Value);
if (deleteLibraryDirectoryResult.IsError)
throw new EventualConsistencyException(deleteLibraryDirectoryResult.FirstError, deleteLibraryDirectoryResult.Errors);
return ValueTask.CompletedTask;
}
/// <summary>
/// Gets the file system path of a media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The id of the media library for which to regtrieve the file system path.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either the file system path of the media library, or an error message.
/// </returns>
private ErrorOr<string> GetLibraryPath(Guid libraryId)
{
// root directory for media
ErrorOr<string> rootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettingsModel.RootDirectory);
if (rootPathResult.IsError)
return rootPathResult.Errors;
// libraries directory
ErrorOr<string> librariesPathResult = _pathService.CombinePath(rootPathResult.Value, _mediaSettingsModel.LibrariesDirectory);
if (librariesPathResult.IsError)
return librariesPathResult.Errors;
// this new particular library' directory
ErrorOr<string> libraryPathResult = _pathService.CombinePath(librariesPathResult.Value, libraryId.ToString());
if (libraryPathResult.IsError)
return libraryPathResult.Errors;
return libraryPathResult.Value;
}
}
@@ -33,7 +33,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
private readonly MediaSettingsModel _mediaSettingsModel;
/// <summary>
///
/// Initializes a new instance of the <see cref="LibrarySavedDomainEventHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="environmentContext">Injected facade service for environment contextual services.</param>
@@ -192,7 +192,7 @@ public class LibrarySavedDomainEventHandler : INotificationHandler<LibrarySavedD
if (renameFileResult.IsError)
return renameFileResult.Errors;
return renameFileResult.Value.Path;
return $"cover.{imageCheckResult.Value.ToString().ToLower()}";
}
/// <summary>
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Mediator;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
/// <summary>
/// Query for getting the list of media libraries.
/// </summary>
public record GetLibrariesQuery : IRequest<ErrorOr<LibraryResponse[]>>;
@@ -0,0 +1,73 @@
#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.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;
using System.Threading.Tasks;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibraries;
/// <summary>
/// Handler for the query to authenticate an account.
/// </summary>
public class GetLibrariesQueryHandler : IRequestHandler<GetLibrariesQuery, ErrorOr<LibraryResponse[]>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibrariesQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetLibrariesQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_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 successfuly created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse[]>> Handle(GetLibrariesQuery request, CancellationToken cancellationToken)
{
// get the library with the specified id from the repository
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
ErrorOr<IEnumerable<LibraryEntity>> getLibrariesResult = await libraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsError)
return getLibrariesResult.Errors;
// admins can see all libraries
if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
return ErrorOrFactory.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
else
{
// for regular users, only take the libraries that belong to them
LibraryResponse[] userLibraries = getLibrariesResult.Value
.Where(library => library.UserId == _currentUserService.UserId)
.Select(library => library.ToResponse()).ToArray();
return ErrorOrFactory.From(userLibraries);
}
}
}
@@ -6,15 +6,13 @@ using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
/// <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 of the user requesting the media library.</param>
[DebuggerDisplay("Id: {Id}")]
public record GetLibraryQuery(
Guid Id,
Guid UserId
Guid Id
) : IRequest<ErrorOr<LibraryResponse>>;
@@ -3,8 +3,11 @@ 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.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Enums.Authorization;
using Mediator;
using System.Threading;
using System.Threading.Tasks;
@@ -12,44 +15,57 @@ using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
/// <summary>
/// Handler for the query to authenticate an account.
/// Handler for the query to get a library by its Id.
/// </summary>
public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<LibraryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryQueryHandler"/> class.
/// </summary>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
public GetLibraryQueryHandler(
IAuthorizationService authorizationService,
ICurrentUserService currentUserService,
IUnitOfWork unitOfWork)
{
_authorizationService = authorizationService;
_currentUserService = currentUserService;
_unitOfWork = unitOfWork;
}
/// <summary>
/// Handles the query to authenticate an account.
/// Handles the query to get a library by its Id.
/// </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.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="LibraryResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LibraryResponse>> Handle(GetLibraryQuery request, CancellationToken cancellationToken)
{
// 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);
if (getLibraryResult.IsError)
return getLibraryResult.Errors;
else if (getLibraryResult.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 (getLibraryResult.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
(!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken)))
return ApplicationErrors.Authorization.NotAuthorized;
return getLibraryResult.Value.ToResponse();
}
}
@@ -4,7 +4,7 @@ using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
namespace Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
/// <summary>
/// Validates the needed validation rules for <see cref="GetLibraryQuery"/>.
@@ -19,9 +19,5 @@ public class GetLibraryQueryValidator : AbstractValidator<GetLibraryQuery>
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.Users.UserIdCannotBeEmpty.Description)
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
}
}
@@ -45,7 +45,7 @@ public class AddBookCommandHandler : IRequestHandler<AddBookCommand, ErrorOr<Boo
/// <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="BookResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="BookResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<BookResponse>> Handle(AddBookCommand request, CancellationToken cancellationToken)
{