mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 10:11:10 +00:00
Adds book reading support with EPUB and PDF reader plugins
This commit is contained in:
1 parent
275fd83ff2
commit
f7ccdf3d1c
271 files changed
+11501
-361
No files matched your search
+1
-1
@@ -2,7 +2,7 @@
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Exceptions;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path.
|
||||
+1
-1
@@ -9,7 +9,7 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding a book.
|
||||
+1
-1
@@ -23,7 +23,7 @@ using System.Threading.Tasks;
|
||||
using Lumina.Contracts.DTO.MediaContributors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add a book.
|
||||
+1
-1
@@ -6,7 +6,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.AddBook;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddBookCommand"/>.
|
||||
+1
-1
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting all the books of a media library.
|
||||
+1
-1
@@ -19,7 +19,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get all books.
|
||||
+1
-1
@@ -5,7 +5,7 @@ using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooks;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetBooksQuery"/>.
|
||||
+1
-1
@@ -5,7 +5,7 @@ using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the lightweight details of all the books of a media library.
|
||||
+1
-1
@@ -19,7 +19,7 @@ using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the lightweight details of all books.
|
||||
+1
-1
@@ -6,7 +6,7 @@ using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Queries.GetBooksLite;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetBooksLiteQuery"/>.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Query for checking the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading availability is checked.</param>
|
||||
public record GetReadingAvailabilityQuery(
|
||||
Guid BookId
|
||||
) : IQuery;
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
public class GetReadingAvailabilityQueryHandler : IQueryHandler<GetReadingAvailabilityQuery, Result<ReadingAvailabilityResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingAvailabilityQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingAvailabilityQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingAvailabilityQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to check the reading availability of a book.
|
||||
/// </summary>
|
||||
/// <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="Result{TValue}"/> containing either the reading availability of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingAvailabilityResponse>> HandleAsync(GetReadingAvailabilityQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
return await _bookReadingService.GetAvailabilityAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingAvailability;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingAvailabilityQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingAvailabilityQueryValidator : AbstractValidator<GetReadingAvailabilityQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingAvailabilityQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingAvailabilityQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading manifest is retrieved.</param>
|
||||
public record GetReadingManifestQuery(
|
||||
Guid BookId
|
||||
) : IQuery;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
public class GetReadingManifestQueryHandler : IQueryHandler<GetReadingManifestQuery, Result<ReadingManifestResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingManifestQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingManifestQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingManifestQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the reading manifest of a book.
|
||||
/// </summary>
|
||||
/// <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="Result{TValue}"/> containing either the reading manifest of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingManifestResponse>> HandleAsync(GetReadingManifestQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preference decides whether a PDF is rendered as page images or has its text layer extracted; a
|
||||
// missing settings row falls back to the default, which is to extract the text layer.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
|
||||
return await _bookReadingService.GetManifestAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingManifest;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingManifestQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingManifestQueryValidator : AbstractValidator<GetReadingManifestQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingManifestQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingManifestQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose resource is retrieved.</param>
|
||||
/// <param name="ResourceKey">The opaque resource key of the resource.</param>
|
||||
public record GetReadingResourceQuery(
|
||||
Guid BookId,
|
||||
string ResourceKey
|
||||
) : IQuery;
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
public class GetReadingResourceQueryHandler : IQueryHandler<GetReadingResourceQuery, Result<ReadingResourceDataDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingResourceQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingResourceQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingResourceQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a resource of a book, for reading.
|
||||
/// </summary>
|
||||
/// <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="Result{TValue}"/> containing either the resource of the book, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingResourceDataDto>> HandleAsync(GetReadingResourceQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preference decides whether a PDF is rendered as page images or has its text layer extracted; a
|
||||
// missing settings row falls back to the default, which is to extract the text layer.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
|
||||
return await _bookReadingService.GetResourceAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.ResourceKey, shouldRenderPdfAsImages, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingResource;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingResourceQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingResourceQueryValidator : AbstractValidator<GetReadingResourceQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingResourceQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingResourceQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.ResourceKey)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.ResourceKeyCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <param name="BookId">The Id of the book whose reading section is retrieved.</param>
|
||||
/// <param name="LocationRef">The opaque location reference of the reading section.</param>
|
||||
public record GetReadingSectionQuery(
|
||||
Guid BookId,
|
||||
string LocationRef
|
||||
) : IQuery;
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
public class GetReadingSectionQueryHandler : IQueryHandler<GetReadingSectionQuery, Result<ReadingSectionDto>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReadingService _bookReadingService;
|
||||
private readonly IValidator<GetReadingSectionQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="bookReadingService">Injected service for reading books using the book reader plugins.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public GetReadingSectionQueryHandler(IUnitOfWork unitOfWork, IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReadingService bookReadingService, IValidator<GetReadingSectionQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReadingService = bookReadingService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the content of a reading section of a book.
|
||||
/// </summary>
|
||||
/// <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="Result{TValue}"/> containing either the content of the reading section, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<ReadingSectionDto>> HandleAsync(GetReadingSectionQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The authorization policy works on the media library, so the book is fetched first to learn its LibraryId, and
|
||||
// the library is fetched afterwards for its type, which the reader plugins match against when resolving the format.
|
||||
Result<BookEntity?> getBookResult = await _unitOfWork.BookRepository.GetByIdAsync(query.BookId, cancellationToken).ConfigureAwait(false);
|
||||
if (getBookResult.IsFailure)
|
||||
return getBookResult.Errors;
|
||||
if (getBookResult.Value is null)
|
||||
return DomainErrors.Reading.BookNotFound;
|
||||
BookEntity book = getBookResult.Value;
|
||||
|
||||
// Admins can read the books of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(book.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(book.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
LibraryEntity library = getLibraryResult.Value;
|
||||
|
||||
// The per-user reading preferences decide how the book is rendered: whether a PDF is rendered as page images or has its text
|
||||
// layer extracted, and whether the styles of the section content are preserved; a missing settings row falls back to the
|
||||
// defaults, which are to extract the text layer and to preserve the styles.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
bool shouldRenderPdfAsImages = getSettingsResult.Value is not null && getSettingsResult.Value.ShouldRenderPdfAsImages;
|
||||
bool shouldPreserveStyles = getSettingsResult.Value is null || getSettingsResult.Value.ShouldPreserveBookStyles;
|
||||
|
||||
return await _bookReadingService.GetSectionAsync(book.Id, book.LibraryId, book.Path, library.LibraryType, query.LocationRef, shouldRenderPdfAsImages, shouldPreserveStyles, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading.Queries.GetReadingSection;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetReadingSectionQuery"/>.
|
||||
/// </summary>
|
||||
public class GetReadingSectionQueryValidator : AbstractValidator<GetReadingSectionQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetReadingSectionQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetReadingSectionQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.BookId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.BookIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.LocationRef)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Reading.LocationRefCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Reading;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the service for reading books, using the book reader plugins configured for their media library.
|
||||
/// </summary>
|
||||
public interface IBookReadingService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reading manifest of the book stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the reading manifest of the book, or an error.</returns>
|
||||
Task<Result<ReadingManifestResponse>> GetManifestAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, bool shouldRenderPdfAsImages, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the content of the reading section identified by <paramref name="locationRef"/> of the book stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="locationRef">The opaque location reference of the reading section.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
|
||||
/// <param name="shouldPreserveStyles">Whether the styles of the section content are preserved when it is sanitized, or stripped.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the content of the reading section, or an error.</returns>
|
||||
Task<Result<ReadingSectionDto>> GetSectionAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string locationRef, bool shouldRenderPdfAsImages, bool shouldPreserveStyles, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resource identified by <paramref name="resourceKey"/> of the book stored at <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="resourceKey">The opaque resource key of the resource.</param>
|
||||
/// <param name="shouldRenderPdfAsImages">Whether the book, when it is a PDF, is rendered as page images instead of extracting its text layer.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the resource, or an error.</returns>
|
||||
Task<Result<ReadingResourceDataDto>> GetResourceAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, string resourceKey, bool shouldRenderPdfAsImages, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the book stored at <paramref name="path"/> can be opened for reading, resolving the book reader configured
|
||||
/// for its media library and verifying that the reader is enabled, without extracting the book.
|
||||
/// </summary>
|
||||
/// <param name="bookId">The Id of the book.</param>
|
||||
/// <param name="libraryId">The Id of the media library the book belongs to.</param>
|
||||
/// <param name="path">The file system path of the book.</param>
|
||||
/// <param name="libraryType">The type of the media library the book belongs to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> containing either the reading availability of the book, or an error.</returns>
|
||||
Task<Result<ReadingAvailabilityResponse>> GetAvailabilityAsync(Guid bookId, Guid libraryId, string path, LibraryType libraryType, CancellationToken cancellationToken);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Command for enabling or disabling a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book reader is enabled or disabled.</param>
|
||||
/// <param name="PluginId">The unique identifier of the plugin providing the book reader.</param>
|
||||
/// <param name="IsEnabled">Whether the book reader should be enabled for the media library.</param>
|
||||
public record SetLibraryBookReaderEnabledCommand(
|
||||
Guid LibraryId,
|
||||
Guid PluginId,
|
||||
bool IsEnabled
|
||||
) : ICommand;
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
public class SetLibraryBookReaderEnabledCommandHandler : ICommandHandler<SetLibraryBookReaderEnabledCommand, Result<Success>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReaderEnablementCache _enablementCache;
|
||||
private readonly IValidator<SetLibraryBookReaderEnabledCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandHandler"/> 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="enablementCache">Injected cache of whether the book reader of a plugin is enabled for a media library.</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 SetLibraryBookReaderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderEnablementCache enablementCache, IUnitOfWork unitOfWork, IValidator<SetLibraryBookReaderEnabledCommand> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_enablementCache = enablementCache;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to enable or disable a book reader for a media library.
|
||||
/// </summary>
|
||||
/// <param name="command">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> representing either a successful operation, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<Success>> HandleAsync(SetLibraryBookReaderEnabledCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Admins can configure the book readers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<LibraryBookReaderConfigurationEntity?> getConfigurationResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationResult.IsFailure)
|
||||
return getConfigurationResult.Errors;
|
||||
|
||||
LibraryBookReaderConfigurationEntity configuration;
|
||||
if (getConfigurationResult.Value is not null)
|
||||
{
|
||||
configuration = getConfigurationResult.Value;
|
||||
configuration.IsEnabled = command.IsEnabled;
|
||||
}
|
||||
else
|
||||
{
|
||||
configuration = new LibraryBookReaderConfigurationEntity
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LibraryId = command.LibraryId,
|
||||
PluginId = command.PluginId,
|
||||
IsEnabled = command.IsEnabled,
|
||||
CreatedOnUtc = default,
|
||||
CreatedBy = default,
|
||||
UpdatedBy = default
|
||||
};
|
||||
}
|
||||
|
||||
Result<Updated> upsertResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResult.IsFailure)
|
||||
return upsertResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// The reading service caches the enablement of a reader, because it consults it on every request; the cache is invalidated here,
|
||||
// so that disabling a reader cuts access to its books immediately, without waiting for the cache to expire.
|
||||
_enablementCache.Invalidate(command.LibraryId, command.PluginId);
|
||||
return Result.Success;
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Commands.SetLibraryBookReaderEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="SetLibraryBookReaderEnabledCommand"/>.
|
||||
/// </summary>
|
||||
public class SetLibraryBookReaderEnabledCommandValidator : AbstractValidator<SetLibraryBookReaderEnabledCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="SetLibraryBookReaderEnabledCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public SetLibraryBookReaderEnabledCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PluginId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.PluginIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library whose book readers are retrieved.</param>
|
||||
public record GetLibraryBookReadersQuery(
|
||||
Guid LibraryId
|
||||
) : IQuery;
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Reading;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.Plugins;
|
||||
using Lumina.Contracts.Responses.Plugins;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
public class GetLibraryBookReadersQueryHandler : IQueryHandler<GetLibraryBookReadersQuery, Result<IReadOnlyList<LibraryBookReaderResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IBookReaderRegistry _bookReaderRegistry;
|
||||
private readonly IValidator<GetLibraryBookReadersQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryHandler"/> 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="bookReaderRegistry">Injected registry of the book readers provided by the loaded plugins.</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 GetLibraryBookReadersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IBookReaderRegistry bookReaderRegistry, IUnitOfWork unitOfWork, IValidator<GetLibraryBookReadersQuery> validator)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_bookReaderRegistry = bookReaderRegistry;
|
||||
_unitOfWork = unitOfWork;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the book readers configured for a media library.
|
||||
/// </summary>
|
||||
/// <param name="query">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a collection of <see cref="LibraryBookReaderResponse"/>, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<IReadOnlyList<LibraryBookReaderResponse>>> HandleAsync(GetLibraryBookReadersQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(query);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// Admins can read the book readers of any library; for everyone else, only their own libraries.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>> getConfigurationsResult = await _unitOfWork.LibraryBookReaderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getConfigurationsResult.IsFailure)
|
||||
return getConfigurationsResult.Errors;
|
||||
|
||||
// Build a plugin name lookup from the detected plugins.
|
||||
Result<IEnumerable<PluginEntity>> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getPluginsResult.IsFailure)
|
||||
return getPluginsResult.Errors;
|
||||
Dictionary<Guid, string> pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name);
|
||||
|
||||
IReadOnlyDictionary<Guid, IReadOnlyList<string>> supportedExtensionsByPluginId = _bookReaderRegistry.GetSupportedExtensionsByPluginId();
|
||||
|
||||
return getConfigurationsResult.Value
|
||||
.OrderBy(configuration => configuration.IsEnabled ? 0 : 1)
|
||||
.ThenBy(configuration => pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty, StringComparer.OrdinalIgnoreCase)
|
||||
.Select(configuration => configuration.ToResponse(
|
||||
pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty,
|
||||
supportedExtensionsByPluginId.GetValueOrDefault(configuration.PluginId) ?? []))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Plugins.Queries.GetLibraryBookReaders;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetLibraryBookReadersQuery"/>.
|
||||
/// </summary>
|
||||
public class GetLibraryBookReadersQueryValidator : AbstractValidator<GetLibraryBookReadersQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibraryBookReadersQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetLibraryBookReadersQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Plugins.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -12,10 +12,14 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe
|
||||
/// <param name="ShouldIgnoreThePrefixForAlphaPicker">Whether the "The" prefix of library item titles is ignored by the alpha picker, or not.</param>
|
||||
/// <param name="IsThemeCachingEnabled">Whether the theme data served to this user is cached, or not.</param>
|
||||
/// <param name="ShouldAggregateMetadataWhenMissing">Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not.</param>
|
||||
/// <param name="ShouldRenderPdfAsImages">Whether PDF books are rendered as page images for the user, or not.</param>
|
||||
/// <param name="ShouldPreserveBookStyles">Whether the styles of the book content are preserved when it is rendered for the user, or not.</param>
|
||||
public record UpdateUserSettingsCommand(
|
||||
bool IsPaginationEnabled,
|
||||
int ItemsPerPage,
|
||||
bool ShouldIgnoreThePrefixForAlphaPicker,
|
||||
bool IsThemeCachingEnabled,
|
||||
bool ShouldAggregateMetadataWhenMissing
|
||||
bool ShouldAggregateMetadataWhenMissing,
|
||||
bool ShouldRenderPdfAsImages,
|
||||
bool ShouldPreserveBookStyles
|
||||
) : ICommand;
|
||||
+10
-6
@@ -53,27 +53,29 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// an authenticated request must always carry a user identity
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// get the existing settings of the current user, if any
|
||||
// Get the existing settings of the current user, if any.
|
||||
Result<UserSettingsEntity?> getSettingsResult = await _unitOfWork.UserSettingsRepository.GetByUserIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getSettingsResult.IsFailure)
|
||||
return getSettingsResult.Errors;
|
||||
|
||||
if (getSettingsResult.Value is null)
|
||||
{
|
||||
// create the settings of the current user, since they are not stored yet
|
||||
// Create the settings of the current user, since they are not stored yet.
|
||||
Result<UserSettings> createSettingsResult = UserSettings.Create(
|
||||
UserId.Create(userId),
|
||||
command.IsPaginationEnabled,
|
||||
command.ItemsPerPage,
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
command.ShouldAggregateMetadataWhenMissing,
|
||||
command.ShouldRenderPdfAsImages,
|
||||
command.ShouldPreserveBookStyles);
|
||||
if (createSettingsResult.IsFailure)
|
||||
return createSettingsResult.Errors;
|
||||
|
||||
@@ -83,7 +85,7 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
}
|
||||
else
|
||||
{
|
||||
// update the stored settings of the current user
|
||||
// Update the stored settings of the current user.
|
||||
Result<UserSettings> toDomainEntityResult = getSettingsResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
@@ -93,7 +95,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler<UpdateUserSettin
|
||||
command.ItemsPerPage,
|
||||
command.ShouldIgnoreThePrefixForAlphaPicker,
|
||||
command.IsThemeCachingEnabled,
|
||||
command.ShouldAggregateMetadataWhenMissing);
|
||||
command.ShouldAggregateMetadataWhenMissing,
|
||||
command.ShouldRenderPdfAsImages,
|
||||
command.ShouldPreserveBookStyles);
|
||||
if (updateSettingsResult.IsFailure)
|
||||
return updateSettingsResult.Errors;
|
||||
|
||||
|
||||
Reference in new issue
Block a user