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

@@ -13,6 +13,6 @@ public interface IDeleteAllRepositoryAction
/// <summary>
/// Deletes all entities from the storage medium.
/// </summary>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Deleted>> DeleteAllAsync();
}
@@ -17,6 +17,6 @@ public interface IDeleteByIdRepositoryAction<TId> where TId : notnull
/// </summary>
/// <param name="id">The id of the element to be deleted.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Deleted>> DeleteByIdAsync(TId id, CancellationToken cancellationToken);
}
@@ -18,6 +18,6 @@ public interface IInsertRepositoryAction<TModel> where TModel : IStorageEntity
/// </summary>
/// <param name="data">The element to be saved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Created>> InsertAsync(TModel data, CancellationToken cancellationToken);
}
@@ -18,6 +18,6 @@ public interface IUpdateRepositoryAction<TModel> where TModel : IStorageEntity
/// </summary>
/// <param name="data">The element that will be updated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Updated>> UpdateAsync(TModel data, CancellationToken cancellationToken);
}
@@ -12,7 +12,9 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
/// </summary>
public interface ILibraryRepository : IRepository<LibraryEntity>,
IGetByIdRepositoryAction<LibraryEntity, Guid>,
IGetAllRepositoryAction<LibraryEntity>,
IInsertRepositoryAction<LibraryEntity>,
IUpdateRepositoryAction<LibraryEntity>
IUpdateRepositoryAction<LibraryEntity>,
IDeleteByIdRepositoryAction<Guid>
{
}
@@ -17,7 +17,7 @@ public interface IDataSeedService
/// </summary>
/// <param name="adminId">The Id of the admin admin user who will own these permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Created>> SetDefaultAuthorizationPermissionsAsync(Guid adminId, CancellationToken cancellationToken);
/// <summary>
@@ -25,7 +25,7 @@ public interface IDataSeedService
/// </summary>
/// <param name="userId">The Id of the admin user for whom roles will be set.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Created>> SetDefaultAuthorizationRolesAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
@@ -33,7 +33,7 @@ public interface IDataSeedService
/// </summary>
/// <param name="userId">The Id of the admin user to receive admin role permissions.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Created>> SetAdminRolePermissionsAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
@@ -41,6 +41,6 @@ public interface IDataSeedService
/// </summary>
/// <param name="userId">The Id of the admin user to receive the admin role.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successfull operation, or an error.</returns>
/// <returns>An <see cref="ErrorOr{TValue}"/> representing either a successful operation, or an error.</returns>
Task<ErrorOr<Created>> SetAdminRoleToAdministratorAccount(Guid userId, CancellationToken cancellationToken);
}
@@ -26,7 +26,7 @@ public class DomainEventsQueue : IDomainEventsQueue
/// </summary>
/// <param name="domainEvent">When this method returns, contains the domain event removed from the queue, or the default value of <see cref="IDomainEvent"/> if the queue is empty.
/// </param>
/// <returns><see langword="true"/> if a domain event was successfully dequeued, <see langword="false"/> otherwise.</returns>
/// <returns><see langword="true"/> if a domain event was successfuly dequeued, <see langword="false"/> otherwise.</returns>
public bool TryDequeue(out IDomainEvent domainEvent)
{
return _queue.TryDequeue(out domainEvent!);
@@ -20,6 +20,6 @@ public interface IDomainEventsQueue
/// </summary>
/// <param name="domainEvent">When this method returns, contains the domain event removed from the queue, or the default value of <see cref="IDomainEvent"/> if the queue is empty.
/// </param>
/// <returns><see langword="true"/> if a domain event was successfully dequeued, <see langword="false"/> otherwise.</returns>
/// <returns><see langword="true"/> if a domain event was successfuly dequeued, <see langword="false"/> otherwise.</returns>
bool TryDequeue(out IDomainEvent domainEvent);
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary;
using Lumina.Contracts.Requests.MediaLibrary.Management;
#endregion
namespace Lumina.Application.Common.Mapping.MediaLibrary.Management;
/// <summary>
/// Extension methods for converting <see cref="DeleteLibraryRequest"/>.
/// </summary>
public static class DeleteLibraryRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="DeleteLibraryCommand"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted command.</returns>
public static DeleteLibraryCommand ToCommand(this DeleteLibraryRequest request)
{
return new DeleteLibraryCommand(
request.Id
);
}
}
@@ -1,5 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.MediaLibrary.Management.Queries;
using Lumina.Application.Core.MediaLibrary.Management.Queries.GetLibrary;
using Lumina.Contracts.Requests.MediaLibrary.Management;
using System;
#endregion
@@ -15,13 +15,11 @@ public static class GetLibraryRequestMapping
/// Converts <paramref name="request"/> to <see cref="GetLibraryQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <param name="userId">The Id of the user requesting the media library.</param>
/// <returns>The converted query.</returns>
public static GetLibraryQuery ToQuery(this GetLibraryRequest request, Guid userId)
public static GetLibraryQuery ToQuery(this GetLibraryRequest request)
{
return new GetLibraryQuery(
request.Id,
userId
request.Id
);
}
}
@@ -1,6 +1,9 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using System.Linq;
#endregion
@@ -29,4 +32,21 @@ public static class LibraryEntityMapping
repositoryEntity.UpdatedOnUtc
);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="Library"/>.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>The converted domain entity.</returns>
public static ErrorOr<Library> ToDomainEntity(this LibraryEntity repositoryEntity)
{
return Library.Create(
LibraryId.Create(repositoryEntity.Id),
repositoryEntity.UserId,
repositoryEntity.Title,
repositoryEntity.LibraryType,
repositoryEntity.ContentLocations.Select(contentLocation => contentLocation.Path),
repositoryEntity.CoverImage
);
}
}
@@ -30,7 +30,7 @@ public static class BookEntityMapping
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully converted <see cref="Book"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly converted <see cref="Book"/>, or an error message.
/// </returns>
public static ErrorOr<Book> ToDomainEntity(this BookEntity repositoryEntity)
{
@@ -137,7 +137,7 @@ public static class BookEntityMapping
/// <param name="repositoryEntities">The repository entities to be converted.</param>
/// <returns>The converted domain entities.</returns>
/// <returns>
/// An colection of <see cref="ErrorOr{TValue}"/> containing either successfully converted <see cref="Book"/>, or error messages.
/// An colection of <see cref="ErrorOr{TValue}"/> containing either successfuly converted <see cref="Book"/>, or error messages.
/// </returns>
public static IEnumerable<ErrorOr<Book>> ToDomainEntities(this IEnumerable<BookEntity> repositoryEntities)
{
@@ -19,7 +19,7 @@ public static class IsbnDtoMapping
/// </summary>
/// <param name="dto">The DTO to be converted.</param>
/// <returns>
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully converted <see cref="Isbn"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly converted <see cref="Isbn"/>, or an error message.
/// </returns>
public static ErrorOr<Isbn> ToDomainEntity(this IsbnDto dto)
{
@@ -44,7 +44,7 @@ public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<Rol
/// <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="RoleResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
{
@@ -46,7 +46,7 @@ public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, 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 deleted <see cref="RoleResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly deleted <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
{
@@ -44,7 +44,7 @@ public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, 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 updated <see cref="RoleResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly updated <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
{
@@ -66,7 +66,7 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
/// <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="RegistrationResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="RegistrationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(SetupApplicationCommand request, CancellationToken cancellationToken)
{
@@ -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)
{
@@ -41,7 +41,7 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
/// <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="ChangePasswordResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="ChangePasswordResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
{
@@ -50,7 +50,7 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
/// <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="RecoverPasswordResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="RecoverPasswordResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RecoverPasswordResponse>> Handle(RecoverPasswordCommand request, CancellationToken cancellationToken)
{
@@ -59,7 +59,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
/// <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="RegistrationResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="RegistrationResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<RegistrationResponse>> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
{
@@ -59,7 +59,7 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
/// <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="LoginResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly created <see cref="LoginResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<LoginResponse>> Handle(LoginUserQuery request, CancellationToken cancellationToken)
{
@@ -48,7 +48,7 @@ public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<Update
/// <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="RoleResponse"/>, or an error message.
/// An <see cref="ErrorOr{TValue}"/> containing either a successfuly updated <see cref="RoleResponse"/>, or an error message.
/// </returns>
public async ValueTask<ErrorOr<AuthorizationResponse>> Handle(UpdateUserRoleAndPermissionsCommand request, CancellationToken cancellationToken)
{