From 6693ff3f60d79e8e1992e63ee8a43b51d0d6fdfc Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:18:14 -0700 Subject: [PATCH] Adds artwork provider system and Calibre plugin --- Directory.Packages.props | 1 + .../DependencyInjection/CalibreServices.cs | 46 + .../Models/DTO/Opf/OpfContributorDto.cs | 17 + .../Common/Models/DTO/Opf/OpfCreatorDto.cs | 17 + .../Common/Models/DTO/Opf/OpfDocumentDto.cs | 79 + .../Common/Models/DTO/Opf/OpfIdentifierDto.cs | 17 + .../Core/CalibreArtworkProvider.cs | 67 + .../Core/CalibreBookMetadataProvider.cs | 75 + .../Core/CalibrePlugin.cs | 65 + .../Core/Mapping/CalibreMapper.cs | 242 +++ .../Core/Opf/OpfReader.cs | 158 ++ .../Lumina.Plugins.Calibre.csproj | 32 + .../Properties/AssemblyInfo.cs | 4 + .../BookLibrary/BookEntity.cs | 7 +- ...braryArtworkProviderConfigurationEntity.cs | 59 + ...IArtworkProviderConfigurationRepository.cs | 42 + .../BookLibrary/Books/BookEntityMapping.cs | 17 +- .../BookLibrary/Books/BookMapping.cs | 1 + .../Books/BookMetadataDtoMapping.cs | 12 +- .../Books/GetBooksLiteRequestMapping.cs | 5 +- ...etLibraryArtworkProvidersRequestMapping.cs | 22 + ...tworkProviderConfigurationEntityMapping.cs | 28 + ...erLibraryArtworkProvidersRequestMapping.cs | 25 + ...aryArtworkProviderEnabledRequestMapping.cs | 26 + .../Common/Utilities/ValidatorUtilities.cs | 27 + .../Artwork/IBookArtworkService.cs | 39 + .../Books/Commands/AddBook/AddBookCommand.cs | 8 +- .../AddBook/AddBookCommandValidator.cs | 5 +- .../ReorderLibraryArtworkProvidersCommand.cs | 17 + ...erLibraryArtworkProvidersCommandHandler.cs | 92 ++ ...LibraryArtworkProvidersCommandValidator.cs | 32 + ...SetLibraryArtworkProviderEnabledCommand.cs | 18 + ...aryArtworkProviderEnabledCommandHandler.cs | 107 ++ ...yArtworkProviderEnabledCommandValidator.cs | 32 + .../GetLibraryArtworkProvidersQuery.cs | 14 + .../GetLibraryArtworkProvidersQueryHandler.cs | 88 ++ ...etLibraryArtworkProvidersQueryValidator.cs | 26 + src/Lumina.Contracts/DTO/Common/ArtworkDto.cs | 16 + .../BookLibrary/BookMetadataDto.cs | 6 +- .../BookLibrary/Books/AddBookRequest.cs | 2 +- .../BookLibrary/Books/GetBooksLiteRequest.cs | 4 +- .../GetLibraryArtworkProvidersRequest.cs | 15 + .../ReorderLibraryArtworkProvidersRequest.cs | 18 + ...SetLibraryArtworkProviderEnabledRequest.cs | 19 + .../BookLibrary/Books/BookResponse.cs | 6 +- .../Plugins/LibraryArtworkProviderResponse.cs | 19 + ...tworkProviderConfigurationConfiguration.cs | 57 + ...ookCoverAndMetadataAggregation.Designer.cs | 1358 +++++++++++++++++ ...idersAndBookCoverAndMetadataAggregation.cs | 106 ++ .../LuminaDbContextModelSnapshot.cs | 76 +- .../ArtworkProviderConfigurationRepository.cs | 80 + .../Enums/BookLibrary/BookRatingSource.cs | 5 + .../BookLibraryAggregate/Book.cs | 27 +- .../Scanners/BookLibraryTypeScanner.cs | 17 +- .../InfrastructureLayerServices.cs | 6 + .../Artwork/BookArtworkService.cs | 337 ++++ .../Lumina.Infrastructure.csproj | 1 + .../Core/Metadata/IArtworkProvider.cs | 38 + .../Core/Metadata/IArtworkProviderGeneric.cs | 34 + .../PresentationApiLayerServices.cs | 9 +- .../Library/Management/ApiRoutes.Libraries.cs | 3 + .../Books/AddBook/AddBookEndpointSummary.cs | 13 +- .../Books/GetBooks/GetBooksEndpointSummary.cs | 6 +- .../GetBooksLiteEndpointSummary.cs | 4 +- .../GetLibraryArtworkProvidersEndpoint.cs | 56 + ...tLibraryArtworkProvidersEndpointSummary.cs | 130 ++ .../ReorderLibraryArtworkProvidersEndpoint.cs | 53 + ...rLibraryArtworkProvidersEndpointSummary.cs | 116 ++ ...etLibraryArtworkProviderEnabledEndpoint.cs | 53 + ...ryArtworkProviderEnabledEndpointSummary.cs | 113 ++ src/Lumina.Presentation.Api/Program.cs | 8 +- .../BookLibrary/BookDto.cs | 2 +- .../Enums/BookLibrary/BookRatingSource.cs | 5 + .../Requests/Libraries/GetBooksLiteRequest.cs | 2 +- .../Common/Utilities/ValidatorUtilities.cs | 27 + .../GetLibraryItemsEndpoint.cs | 3 +- .../GetLibraryItemsEndpointSummary.cs | 3 +- .../BookLibrary/Books/Index.cshtml | 4 +- src/Lumina.sln | 45 + ...tworkProviderConfigurationEntityFixture.cs | 57 + ...erLibraryArtworkProvidersCommandFixture.cs | 46 + ...aryArtworkProviderEnabledCommandFixture.cs | 50 + .../GetLibraryArtworkProvidersQueryFixture.cs | 41 + .../Core/DTO/Common/ArtworkDtoFixture.cs | 38 + ...etLibraryArtworkProvidersRequestFixture.cs | 42 + ...erLibraryArtworkProvidersRequestFixture.cs | 45 + ...aryArtworkProviderEnabledRequestFixture.cs | 48 + .../LibraryArtworkProviderResponseFixture.cs | 50 + .../Common/Setup/StubHttpMessageHandler.cs | 55 + .../DTO/Opf/OpfContributorDtoFixture.cs | 38 + .../Models/DTO/Opf/OpfCreatorDtoFixture.cs | 38 + .../Models/DTO/Opf/OpfDocumentDtoFixture.cs | 81 + .../Models/DTO/Opf/OpfIdentifierDtoFixture.cs | 38 + .../Core/Metadata/TestMetadataLookup.cs | 13 + .../Metadata/TestMetadataLookupFixture.cs | 38 + .../Lumina.Plugins.Calibre.Fixtures.csproj | 26 + .../Properties/AssemblyInfo.cs | 20 + ...GetLibraryArtworkProvidersEndpointTests.cs | 153 ++ ...derLibraryArtworkProvidersEndpointTests.cs | 140 ++ ...raryArtworkProviderEnabledEndpointTests.cs | 156 ++ ...GetLibraryArtworkProvidersEndpointTests.cs | 119 ++ ...derLibraryArtworkProvidersEndpointTests.cs | 133 ++ ...raryArtworkProviderEnabledEndpointTests.cs | 126 ++ .../BookArtworkServiceSecurityTests.cs | 236 +++ .../CalibreArtworkProviderSecurityTests.cs | 110 ++ .../Calibre/Opf/OpfReaderSecurityTests.cs | 155 ++ ...raryArtworkProvidersCommandHandlerTests.cs | 183 +++ ...ryArtworkProvidersCommandValidatorTests.cs | 104 ++ ...tworkProviderEnabledCommandHandlerTests.cs | 242 +++ ...orkProviderEnabledCommandValidatorTests.cs | 89 ++ ...ibraryArtworkProvidersQueryHandlerTests.cs | 231 +++ ...raryArtworkProvidersQueryValidatorTests.cs | 49 + ...orkProviderConfigurationRepositoryTests.cs | 137 ++ .../Artwork/BookArtworkServiceTests.cs | 541 +++++++ .../Core/CalibreArtworkProviderTests.cs | 252 +++ .../Core/CalibreBookMetadataProviderTests.cs | 174 +++ .../Core/CalibrePluginTests.cs | 98 ++ .../Core/Mapping/CalibreMapperTests.cs | 367 +++++ .../Core/Opf/OpfReaderTests.cs | 212 +++ .../Lumina.Plugins.Calibre.UnitTests.csproj | 48 + .../Metadata/IArtworkProviderGenericTests.cs | 105 ++ ...GetLibraryArtworkProvidersEndpointTests.cs | 136 ++ ...derLibraryArtworkProvidersEndpointTests.cs | 129 ++ ...raryArtworkProviderEnabledEndpointTests.cs | 129 ++ 124 files changed, 9715 insertions(+), 74 deletions(-) create mode 100644 plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs create mode 100644 plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj create mode 100644 plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs create mode 100644 src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs create mode 100644 src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs create mode 100644 src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs create mode 100644 src/Lumina.Contracts/DTO/Common/ArtworkDto.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs create mode 100644 src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs create mode 100644 src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs create mode 100644 src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs create mode 100644 src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs create mode 100644 src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs create mode 100644 src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs create mode 100644 src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs create mode 100644 src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs create mode 100644 tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj create mode 100644 tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj create mode 100644 tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index f98f56c2..7f669fa1 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -33,6 +33,7 @@ + diff --git a/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs new file mode 100644 index 00000000..20b7b97f --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/DependencyInjection/CalibreServices.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System; +#endregion + +namespace Lumina.Plugins.Calibre.Common.DependencyInjection; + +/// +/// Provides extension methods for registering the Calibre metadata and artwork providers. +/// +internal static class CalibreServices +{ + /// + /// Registers the Calibre book metadata provider, associated with the plugin that provides it. + /// + /// The service collection to register the services into. + /// The unique identifier of the plugin that provides the metadata. + /// The service collection, for chaining. + internal static IServiceCollection AddCalibreBookMetadataProvider(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Register the metadata provider as a keyed by pluginId transient service, so it can be resolved specifically among other IMetadataProvider implementations. + services.AddKeyedTransient(pluginId); + + return services; + } + + /// + /// Registers the Calibre artwork provider, associated with the plugin that provides it. + /// + /// The service collection to register the services into. + /// The unique identifier of the plugin that provides the artwork. + /// The service collection, for chaining. + internal static IServiceCollection AddCalibreArtworkProvider(this IServiceCollection services, Guid pluginId) + { + ArgumentNullException.ThrowIfNull(services); + + // Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations. + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs new file mode 100644 index 00000000..fb72a220 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfContributorDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for a contributor of a book read from an OPF file. +/// +/// The name of the contributor. +/// The role code of the contributor, for example bkp for the book producer. +[DebuggerDisplay("Name: {Name}")] +internal sealed record OpfContributorDto( + string Name, + string? Role +); diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs new file mode 100644 index 00000000..2f79c0f8 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfCreatorDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for a creator of a book read from an OPF file. +/// +/// The name of the creator. +/// The role code of the creator, for example aut for author. +[DebuggerDisplay("Name: {Name}")] +internal sealed record OpfCreatorDto( + string Name, + string? Role +); diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs new file mode 100644 index 00000000..a49ca5e6 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfDocumentDto.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for the metadata read from a Calibre OPF file. +/// +[DebuggerDisplay("Title: {Title}")] +internal sealed class OpfDocumentDto +{ + /// + /// Gets or sets the title of the book. + /// + public string? Title { get; set; } + + /// + /// Gets or sets the description of the book, in HTML format. + /// + public string? Description { get; set; } + + /// + /// Gets or sets the publisher of the book. + /// + public string? Publisher { get; set; } + + /// + /// Gets or sets the publication date of the book. + /// + public DateTimeOffset? PublishDate { get; set; } + + /// + /// Gets or sets the language code of the book. + /// + public string? LanguageCode { get; set; } + + /// + /// Gets or sets the name of the series the book belongs to, if applicable. + /// + public string? Series { get; set; } + + /// + /// Gets or sets the index of the book within its series, if applicable. + /// + public double? SeriesIndex { get; set; } + + /// + /// Gets or sets the personal rating of the book, on a scale of 0 to 10. + /// + public int? Rating { get; set; } + + /// + /// Gets or sets the href of the cover image, relative to the directory of the book. + /// + public string? CoverHref { get; set; } + + /// + /// Gets the creators of the book. + /// + public List Creators { get; } = []; + + /// + /// Gets the contributors of the book. + /// + public List Contributors { get; } = []; + + /// + /// Gets the identifiers of the book, with their schemes. + /// + public List Identifiers { get; } = []; + + /// + /// Gets the subjects of the book, used as tags. + /// + public List Subjects { get; } = []; +} diff --git a/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs new file mode 100644 index 00000000..1d10d643 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Common/Models/DTO/Opf/OpfIdentifierDto.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Plugins.Calibre.Common.Models.DTO.Opf; + +/// +/// Data transfer object for an identifier of a book read from an OPF file, with its scheme. +/// +/// The scheme of the identifier, for example ISBN or GOODREADS. +/// The value of the identifier. +[DebuggerDisplay("{Scheme}: {Value}")] +internal sealed record OpfIdentifierDto( + string Scheme, + string Value +); diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs new file mode 100644 index 00000000..e3ffd5e3 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreArtworkProvider.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using Lumina.Plugins.Calibre.Core.Opf; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.Core; + +/// +/// Provides the cover of a book from the cover reference of the Calibre OPF file located next to the book file. +/// +internal sealed class CalibreArtworkProvider : IArtworkProvider +{ + /// + /// Gets the display name of the artwork provider. + /// + public string Name => "Calibre"; + + /// + /// Gets the media library types this artwork provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook]; + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + public bool RequiresWebAccess => false; + + /// + /// Gets the cover of the book described by . + /// + /// The lookup describing the book to get the cover for. + /// Cancellation token that can be used to stop the execution. + /// The cover of the book, or when no cover was found. + public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Path)) + return Task.FromResult(null); + + string bookDirectory = Path.GetDirectoryName(lookup.Path) ?? string.Empty; + string opfFilePath = Path.Combine(bookDirectory, "metadata.opf"); + if (!File.Exists(opfFilePath)) + return Task.FromResult(null); + + OpfDocumentDto document = OpfReader.Read(opfFilePath); + if (string.IsNullOrWhiteSpace(document.CoverHref)) + return Task.FromResult(null); + + // the cover reference must be a bare file name contained in the directory of the book, so that no file outside of it can be accessed + string coverFileName = Path.GetFileName(document.CoverHref); + if (coverFileName != document.CoverHref || Path.IsPathRooted(document.CoverHref)) + return Task.FromResult(null); + + string coverFilePath = Path.Combine(bookDirectory, coverFileName); + if (!File.Exists(coverFilePath)) + return Task.FromResult(null); + + return Task.FromResult(new ArtworkDto(LocalPath: coverFilePath, RemoteUrl: null)); + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs new file mode 100644 index 00000000..950ddcab --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibreBookMetadataProvider.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Core.Mapping; +using Lumina.Plugins.Calibre.Core.Opf; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.Core; + +/// +/// Provides book metadata from Calibre OPF files by resolving lookups into book metadata DTOs. +/// +internal sealed class CalibreBookMetadataProvider : IMetadataProvider +{ + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "Calibre"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book, LibraryType.EBook]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => false; + + /// + /// Searches for the metadata of the media item described by . + /// + /// The lookup describing the media item to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of metadata candidates found for the media item. + public Task> GetSearchResultsAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) + { + BookMetadataDto? metadata = GetMetadata(bookMetadataLookup); + return Task.FromResult>(metadata is null ? [] : [metadata]); + } + + /// + /// Gets the metadata of the media item described by . + /// + /// The lookup describing the media item to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the media item, or when no metadata was found. + public Task GetMetadataAsync(BookMetadataLookupDto bookMetadataLookup, CancellationToken cancellationToken) + { + return Task.FromResult(GetMetadata(bookMetadataLookup)); + } + + /// + /// Reads the metadata of the book from the OPF file located next to the book file described by . + /// + /// The lookup describing the book to get the metadata for. + /// The metadata of the book, or when no OPF file was found. + private static BookMetadataDto? GetMetadata(BookMetadataLookupDto bookMetadataLookup) + { + if (string.IsNullOrWhiteSpace(bookMetadataLookup.Path)) + return null; + + string opfFilePath = Path.Combine(Path.GetDirectoryName(bookMetadataLookup.Path) ?? string.Empty, "metadata.opf"); + if (!File.Exists(opfFilePath)) + return null; + + return CalibreMapper.Map(OpfReader.Read(opfFilePath)); + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs b/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs new file mode 100644 index 00000000..10138ea1 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/CalibrePlugin.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Calibre.Common.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.Calibre.Core; + +/// +/// Plugin that provides book metadata and book covers from Calibre OPF files. +/// +public sealed class CalibrePlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "Calibre Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Reads book metadata and covers from the OPF files of a Calibre library."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return []; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddCalibreBookMetadataProvider(pluginId: Id); + services.AddCalibreArtworkProvider(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs new file mode 100644 index 00000000..60c2dc54 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/Mapping/CalibreMapper.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Plugins.Calibre.Core.Mapping; + +/// +/// Maps the metadata read from a Calibre OPF file into the application's book metadata DTO. +/// +internal static class CalibreMapper +{ + /// + /// Maps the metadata read from the OPF file into a book metadata DTO. + /// + /// The metadata read from the OPF file. + /// The mapped book metadata. + public static BookMetadataDto Map(OpfDocumentDto document) + { + float? volumeNumber = document.SeriesIndex is > 0 ? (float?)document.SeriesIndex : null; + + return new BookMetadataDto( + Title: document.Title, + OriginalTitle: null, + Description: StripHtml(document.Description), + ReleaseInfo: BuildReleaseInfo(document.PublishDate), + Genres: null, + Tags: [.. document.Subjects.Select(subject => new TagDto(Name: subject))], + Language: MapLanguage(document.LanguageCode), + OriginalLanguage: null, + Publisher: document.Publisher, + PageCount: null, + Format: null, + Edition: null, + VolumeNumber: volumeNumber, + Series: document.Series is null ? null : new BookSeriesDto(Title: document.Series), + ASIN: GetIdentifier(document.Identifiers, "asin", "amazon"), + GoodreadsId: GetIdentifier(document.Identifiers, "goodreads"), + LCCN: GetIdentifier(document.Identifiers, "lccn"), + OCLCNumber: GetIdentifier(document.Identifiers, "oclc"), + OpenLibraryId: GetIdentifier(document.Identifiers, "openlibrary"), + LibraryThingId: null, + GoogleBooksId: GetIdentifier(document.Identifiers, "google", "googlebooks"), + BarnesAndNobleId: null, + AppleBooksId: null, + Isbns: BuildIsbns(document.Identifiers), + Contributors: BuildContributors(document.Creators, document.Contributors), + Ratings: document.Rating is null ? null : [new BookRatingDto(Value: document.Rating, MaxValue: 10m, Source: BookRatingSource.Calibre, VoteCount: null)], + CoverImagePath: null + ); + } + + /// + /// Builds the release information of the book from its publication date. + /// + /// The publication date of the book. + /// The release information of the book, always present even when the publication date is missing. + private static ReleaseInfoDto BuildReleaseInfo(DateTimeOffset? publishDate) + { + // the release info must always be present, even when the publication date is missing, so that the metadata can be applied to the book + if (publishDate is null) + { + return new ReleaseInfoDto( + OriginalReleaseDate: null, + OriginalReleaseYear: null, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: null, + ReleaseVersion: null + ); + } + + DateOnly? releaseDate = DateOnly.FromDateTime(publishDate.Value.Date); + return new ReleaseInfoDto( + OriginalReleaseDate: releaseDate, + OriginalReleaseYear: releaseDate?.Year, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: null, + ReleaseVersion: null + ); + } + + /// + /// Maps the ISBN identifiers of the book into ISBN DTOs, de-duplicating normalized values. + /// + /// The identifiers read from the OPF file. + /// The mapped and de-duplicated ISBN DTOs. + private static List BuildIsbns(List identifiers) + { + List result = []; + HashSet seen = new(StringComparer.OrdinalIgnoreCase); + + foreach (OpfIdentifierDto identifier in identifiers.Where(identifier => string.Equals(identifier.Scheme, "isbn", StringComparison.OrdinalIgnoreCase))) + { + string? normalized = NormalizeIsbn(identifier.Value); + if (normalized is null || !seen.Add(normalized)) + continue; + result.Add(new IsbnDto(Value: normalized, Format: normalized.Length == 10 ? IsbnFormat.Isbn10 : IsbnFormat.Isbn13)); + } + + return result; + } + + /// + /// Maps the creators and contributors of the book into contributor DTOs, de-duplicating identical name and role pairs. + /// + /// The creators read from the OPF file. + /// The contributors read from the OPF file. + /// The mapped contributor DTOs. + private static List BuildContributors(List creators, List contributors) + { + List result = []; + HashSet seen = new(StringComparer.OrdinalIgnoreCase); + + void Add(string? displayName, string role, string category) + { + if (string.IsNullOrWhiteSpace(displayName) || !seen.Add($"{displayName}|{role}")) + return; + result.Add(new MediaContributorDto( + Name: new MediaContributorNameDto(DisplayName: displayName.Trim(), LegalName: null), + Role: new MediaContributorRoleDto(Name: role, Category: category)) + ); + } + + foreach (OpfCreatorDto creator in creators) + Add(creator.Name, "Author", "Writing"); + foreach (OpfContributorDto contributor in contributors) + Add(contributor.Name, MapContributorRole(contributor.Role), MapContributorCategory(contributor.Role)); + + return result; + } + + /// + /// Maps a language code into a language info DTO by matching it against known cultures. + /// + /// The raw language code to map. + /// The mapped language info, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + IEnumerable cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures) + .Concat(CultureInfo.GetCultures(CultureTypes.NeutralCultures)); + + CultureInfo? culture = cultures.FirstOrDefault(candidate => + string.Equals(candidate.TwoLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase) || + string.Equals(candidate.ThreeLetterISOLanguageName, code, StringComparison.OrdinalIgnoreCase)); + + return culture is null + ? new LanguageInfoDto(LanguageCode: code, LanguageName: code, NativeName: null) + : new LanguageInfoDto(LanguageCode: culture.TwoLetterISOLanguageName, LanguageName: culture.EnglishName, NativeName: culture.NativeName); + } + + /// + /// Strips the HTML markup of a description, leaving the text content. + /// + /// The HTML value to strip. + /// The text content, or when the value is empty. + private static string? StripHtml(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + + string decoded = WebUtility.HtmlDecode(value); + string withoutTags = Regex.Replace(decoded, "<[^>]+>", " "); + string collapsed = Regex.Replace(withoutTags, @"\s+", " ").Trim(); + return collapsed.Length == 0 ? null : collapsed; + } + + /// + /// Normalizes an ISBN into its canonical form without separators or whitespace. + /// + /// The ISBN to normalize. + /// The normalized ISBN, or when the value is not a valid ISBN. + private static string? NormalizeIsbn(string isbn) + { + string normalized = new string([.. isbn.Where(character => character is not '-' && !char.IsWhiteSpace(character))]).ToUpperInvariant(); + // valid ISBNs must be 10 or 13 characters in length, all characters except the last one must be digits, and the last one must be a digit for ISBN-13 and X for ISBN-10 + if ((normalized.Length != 10 && normalized.Length != 13) || + normalized[..^1].Any(character => !char.IsDigit(character)) || + (!char.IsDigit(normalized[^1]) && !(normalized.Length == 10 && normalized[^1] == 'X'))) + return null; + + return normalized; + } + + /// + /// Gets the value of the first identifier whose scheme matches one of the . + /// + /// The identifiers read from the OPF file. + /// The identifier schemes to try, in order. + /// The identifier value, or when no identifier matches. + private static string? GetIdentifier(List identifiers, params string[] schemes) + { + foreach (OpfIdentifierDto identifier in identifiers) + if (schemes.Any(scheme => string.Equals(identifier.Scheme, scheme, StringComparison.OrdinalIgnoreCase))) + return identifier.Value; + + return null; + } + + /// + /// Maps a creator or contributor role code into a role name. + /// + /// The role code to map. + /// The mapped role name. + private static string MapContributorRole(string? role) + { + return string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) ? "Author" : string.IsNullOrWhiteSpace(role) ? "Contributor" : role; + } + + /// + /// Maps a creator or contributor role code into a contributor category. + /// + /// The role code to map. + /// The mapped contributor category. + private static string MapContributorCategory(string? role) + { + if (string.Equals(role, "aut", StringComparison.OrdinalIgnoreCase) || role?.Contains("author", StringComparison.OrdinalIgnoreCase) == true) + return "Writing"; + if (string.Equals(role, "ill", StringComparison.OrdinalIgnoreCase)) + return "Art"; + if (string.Equals(role, "trl", StringComparison.OrdinalIgnoreCase)) + return "Translation"; + if (string.Equals(role, "bkp", StringComparison.OrdinalIgnoreCase)) + return "Production"; + return "Other"; + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs b/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs new file mode 100644 index 00000000..cb776e35 --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Core/Opf/OpfReader.cs @@ -0,0 +1,158 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Core.Opf; + +/// +/// Reads the metadata of a book from a Calibre OPF file. +/// +internal static class OpfReader +{ + private const long MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024; + private static readonly XNamespace s_opfNamespace = "http://www.idpf.org/2007/opf"; + private static readonly XNamespace s_dcNamespace = "http://purl.org/dc/elements/1.1/"; + + /// + /// Reads the metadata of the book from the OPF file at . + /// + /// The file system path of the OPF file to read. + /// The metadata read from the OPF file, with the fields that could not be read left empty. + public static OpfDocumentDto Read(string opfFilePath) + { + OpfDocumentDto document = new(); + FileInfo fileInfo = new(opfFilePath); + if (!fileInfo.Exists || fileInfo.Length > MAX_OPF_FILE_SIZE_BYTES) + return document; + + try + { + using FileStream fileStream = File.OpenRead(opfFilePath); + // the OPF file is untrusted XML, so DTD processing and external entity resolution are disabled, and the document size is bounded + XmlReaderSettings xmlReaderSettings = new() + { + DtdProcessing = DtdProcessing.Prohibit, + XmlResolver = null, + MaxCharactersInDocument = MAX_OPF_FILE_SIZE_BYTES, + MaxCharactersFromEntities = 0 + }; + using XmlReader xmlReader = XmlReader.Create(fileStream, xmlReaderSettings); + XDocument xDocument = XDocument.Load(xmlReader, LoadOptions.None); + Parse(xDocument, document); + } + catch (XmlException) + { + // a malformed OPF file must not prevent the enrichment of the book from proceeding + } + + return document; + } + + /// + /// Parses the metadata elements of the into the . + /// + /// The parsed OPF document. + /// The model onto which the parsed metadata is written. + private static void Parse(XDocument xDocument, OpfDocumentDto document) + { + XElement? metadata = xDocument.Root?.Element(s_opfNamespace + "metadata"); + if (metadata is null) + return; + + document.Title = GetElementText(metadata, s_dcNamespace + "title"); + document.Description = GetElementText(metadata, s_dcNamespace + "description"); + document.Publisher = GetElementText(metadata, s_dcNamespace + "publisher"); + document.LanguageCode = GetElementText(metadata, s_dcNamespace + "language"); + document.PublishDate = ParseDate(GetElementText(metadata, s_dcNamespace + "date")); + + foreach (XElement identifier in metadata.Elements(s_dcNamespace + "identifier")) + { + string? scheme = identifier.Attribute(s_opfNamespace + "scheme")?.Value; + if (!string.IsNullOrWhiteSpace(scheme) && !string.IsNullOrWhiteSpace(identifier.Value)) + document.Identifiers.Add(new OpfIdentifierDto(Scheme: scheme.Trim(), Value: identifier.Value.Trim())); + } + + foreach (XElement subject in metadata.Elements(s_dcNamespace + "subject")) + if (!string.IsNullOrWhiteSpace(subject.Value)) + document.Subjects.Add(subject.Value.Trim()); + + foreach (XElement creator in metadata.Elements(s_dcNamespace + "creator")) + if (!string.IsNullOrWhiteSpace(creator.Value)) + document.Creators.Add(new OpfCreatorDto(Name: creator.Value.Trim(), Role: creator.Attribute(s_opfNamespace + "role")?.Value?.Trim())); + + foreach (XElement contributor in metadata.Elements(s_dcNamespace + "contributor")) + if (!string.IsNullOrWhiteSpace(contributor.Value)) + document.Contributors.Add(new OpfContributorDto(Name: contributor.Value.Trim(), Role: contributor.Attribute(s_opfNamespace + "role")?.Value?.Trim())); + + foreach (XElement meta in metadata.Elements(s_opfNamespace + "meta")) + { + string? name = meta.Attribute("name")?.Value; + string? content = meta.Attribute("content")?.Value; + if (name is null || content is null) + continue; + + if (string.Equals(name, "calibre:series", StringComparison.OrdinalIgnoreCase)) + document.Series = content.Trim(); + else if (string.Equals(name, "calibre:series_index", StringComparison.OrdinalIgnoreCase)) + document.SeriesIndex = ParseDouble(content); + else if (string.Equals(name, "calibre:rating", StringComparison.OrdinalIgnoreCase)) + document.Rating = ParseInt(content); + } + + XElement? coverReference = xDocument.Root + ?.Element(s_opfNamespace + "guide") + ?.Elements(s_opfNamespace + "reference") + .FirstOrDefault(reference => string.Equals(reference.Attribute("type")?.Value, "cover", StringComparison.OrdinalIgnoreCase)); + document.CoverHref = coverReference?.Attribute("href")?.Value; + } + + /// + /// Gets the trimmed text of the child element with the specified of the element. + /// + /// The parent element. + /// The name of the child element. + /// The trimmed text, or when the element is missing or empty. + private static string? GetElementText(XElement parent, XName name) + { + string? value = parent.Element(name)?.Value; + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } + + /// + /// Parses a date string into a . + /// + /// The date string to parse. + /// The parsed date, or when the string is empty or cannot be parsed. + private static DateTimeOffset? ParseDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return null; + return DateTimeOffset.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out DateTimeOffset result) ? result : null; + } + + /// + /// Parses a double string. + /// + /// The string to parse. + /// The parsed value, or when the string is empty or cannot be parsed. + private static double? ParseDouble(string value) + { + return double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result) ? result : null; + } + + /// + /// Parses an integer string. + /// + /// The string to parse. + /// The parsed value, or when the string is empty or cannot be parsed. + private static int? ParseInt(string value) + { + return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int result) ? result : null; + } +} diff --git a/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj new file mode 100644 index 00000000..d8974eac --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Lumina.Plugins.Calibre.csproj @@ -0,0 +1,32 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + + + + + + + + + + + + + + false + runtime + + + + + + + diff --git a/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..c7bf9b3a --- /dev/null +++ b/plugins/Lumina.Plugins.Calibre/Properties/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.Fixtures")] diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs index b526c7b5..dd02ed01 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/WrittenContentLibrary/BookLibrary/BookEntity.cs @@ -138,7 +138,7 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets the volume or book number in the series, if applicable. /// - public int? VolumeNumber { get; set; } + public float? VolumeNumber { get; set; } // TODO: uncomment when series is implemented /// /// Gets or sets the series id, if the book is part of a series. @@ -190,6 +190,11 @@ public class BookEntity : IStorageEntity, IAuditableEntity /// public string? AppleBooksId { get; set; } + /// + /// Gets or sets the file system path of the cover image of the book, if applicable. + /// + public string? CoverImagePath { get; set; } + /// /// Gets or sets the list of ISBN (International Standard Book Number) of the book. /// diff --git a/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs new file mode 100644 index 00000000..3bd58781 --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntity.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Common; +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Application.Common.DataAccess.Entities.Plugins; + +/// +/// Repository entity for the configuration of an artwork provider of a media library. +/// +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public class LibraryArtworkProviderConfigurationEntity : IStorageEntity, IAuditableEntity +{ + /// + /// Gets or sets the Id of the configuration. + /// + public required Guid Id { get; init; } + + /// + /// Gets or sets the Id of the media library the configuration belongs to. + /// + public required Guid LibraryId { get; set; } + + /// + /// Gets or sets the Id of the plugin providing the artwork. + /// + public required Guid PluginId { get; set; } + + /// + /// Gets or sets whether the artwork provider is enabled for the media library. + /// + public required bool IsEnabled { get; set; } + + /// + /// Gets or sets the rank of the artwork provider, determining the order in which providers are tried. + /// + public required int Rank { get; set; } + + /// + /// Gets or sets the time and date when the entity was added. + /// + public required DateTime CreatedOnUtc { get; set; } + + /// + /// Gets or sets the Id of the user that created the entity. + /// + public required Guid CreatedBy { get; set; } + + /// + /// Gets or sets the optional time and date when the entity was updated. + /// + public DateTime? UpdatedOnUtc { get; set; } + + /// + /// Gets or sets the optional Id of the user that updated the entity. + /// + public required Guid? UpdatedBy { get; set; } +} diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs new file mode 100644 index 00000000..5f1ddb1f --- /dev/null +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Common.Base; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.DataAccess.Repositories.Plugins; + +/// +/// Interface for the repository for the artwork provider configurations of media libraries. +/// +public interface IArtworkProviderConfigurationRepository : IRepository +{ + /// + /// Gets all the artwork provider configurations of the media library identified by . + /// + /// The Id of the media library whose artwork provider configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Gets the artwork provider configuration of the media library identified by for the plugin identified by . + /// + /// The Id of the media library whose artwork provider configuration is retrieved. + /// The Id of the plugin whose artwork provider configuration is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken); + + /// + /// Inserts the provided into the storage medium, or updates it when it already exists. + /// + /// The artwork provider configuration to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs index 5fa6a3a7..ed2abbc8 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookEntityMapping.cs @@ -110,14 +110,14 @@ public static class BookEntityMapping Optional bookFormat = Optional.FromNullable(repositoryEntity.Format); - return Book.Create( + Result bookResult = Book.Create( BookId.Create(repositoryEntity.Id), LibraryId.Create(repositoryEntity.LibraryId), repositoryEntity.Path, writtenContentMetadataResult.Value, bookFormat, Optional.FromNullable(repositoryEntity.Edition), - Optional.FromNullable(repositoryEntity.VolumeNumber), + Optional.FromNullable(repositoryEntity.VolumeNumber), Optional.None(), Optional.FromNullable(repositoryEntity.ASIN), Optional.FromNullable(repositoryEntity.GoodreadsId), @@ -133,6 +133,13 @@ public static class BookEntityMapping [.. isbnsResult.Select(isbn => isbn.Value)], [], [.. bookRatingsResult.Select(bookRating => bookRating.Value)]); + if (bookResult.IsFailure) + return bookResult.Errors; + + if (repositoryEntity.CoverImagePath is not null) + bookResult.Value.SetBookCoverImagePath(repositoryEntity.CoverImagePath); + + return bookResult; } /// @@ -217,7 +224,8 @@ public static class BookEntityMapping repositoryEntity.LastMetadataUpdateUtc, repositoryEntity.MetadataProvider, repositoryEntity.CreatedOnUtc, - repositoryEntity.UpdatedOnUtc + repositoryEntity.UpdatedOnUtc, + repositoryEntity.CoverImagePath ); } @@ -259,8 +267,7 @@ public static class BookEntityMapping repositoryEntity.Id, repositoryEntity.Title, repositoryEntity.ReReleaseYear ?? repositoryEntity.OriginalReleaseYear, - // TODO: populate from the book cover when cover support is implemented - null + repositoryEntity.CoverImagePath ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs index 1a61e61c..3ad75ac6 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMapping.cs @@ -56,6 +56,7 @@ public static class BookMapping GoogleBooksId = domainEntity.GoogleBooksId.HasValue ? domainEntity.GoogleBooksId.Value : null, BarnesAndNobleId = domainEntity.BarnesAndNobleId.HasValue ? domainEntity.BarnesAndNobleId.Value : null, AppleBooksId = domainEntity.AppleBooksId.HasValue ? domainEntity.AppleBooksId.Value : null, + CoverImagePath = domainEntity.CoverImagePath.HasValue ? domainEntity.CoverImagePath.Value : null, ISBNs = [.. domainEntity.ISBNs.ToRepositoryEntities()], Ratings = [.. domainEntity.Ratings.ToRepositoryEntities()], MetadataStatus = domainEntity.MetadataStatus, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs index e295cd5b..59747d48 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookMetadataDtoMapping.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; - +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Common.ValueObjects.Metadata; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; @@ -30,9 +29,9 @@ public static class BookMetadataDtoMapping public static Result ApplyMetadata(this Book book, BookMetadataDto metadata, string providerName, DateTime lastUpdateUtc) { if (string.IsNullOrWhiteSpace(metadata.Title)) - return Lumina.Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; + return Domain.Common.Errors.Errors.Metadata.TitleCannotBeEmpty; if (metadata.ReleaseInfo is null) - return Lumina.Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull; + return Domain.Common.Errors.Errors.Metadata.ReleaseInfoCannotBeNull; Result releaseInfoResult = ReleaseInfo.Create( Optional.FromNullable(metadata.ReleaseInfo.OriginalReleaseDate), @@ -115,7 +114,7 @@ public static class BookMetadataDtoMapping writtenContentMetadataResult.Value, Optional.FromNullable(metadata.Format.HasValue ? (BookFormat)(int)metadata.Format.Value : (BookFormat?)null), Optional.FromNullable(metadata.Edition), - Optional.FromNullable(metadata.VolumeNumber), + Optional.FromNullable(metadata.VolumeNumber), Optional.None(), Optional.FromNullable(metadata.ASIN), Optional.FromNullable(metadata.GoodreadsId), @@ -132,6 +131,9 @@ public static class BookMetadataDtoMapping lastUpdateUtc ); + if (!string.IsNullOrWhiteSpace(metadata.CoverImagePath)) + book.SetBookCoverImagePath(metadata.CoverImagePath); + return Result.Success; } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs index c3fa2f9f..1a7ca813 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequestMapping.cs @@ -21,18 +21,19 @@ public static class GetBooksLiteRequestMapping { PaginationDataDto? paginationData = null; if (request.CurrentPage is not null || request.PerPage is not null) + { paginationData = new PaginationDataDto { CurrentPage = request.CurrentPage ?? 1, PerPage = request.PerPage ?? 200 }; - + } LibraryFilterDto libraryFilter = new() { LibraryId = request.LibraryId, SearchTerm = request.SearchTerm, FilterAlphaKey = request.FilterAlphaKey, - IgnoreThePrefixForAlphaPicker = request.IgnoreThePrefixForAlphaPicker + ShouldIgnoreThePrefixForAlphaPicker = request.ShouldIgnoreThePrefixForAlphaPicker }; return new GetBooksLiteQuery(paginationData, libraryFilter, request.SortBy, request.SortOrder); diff --git a/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs new file mode 100644 index 00000000..5dc3051b --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/GetLibraryArtworkProvidersRequestMapping.cs @@ -0,0 +1,22 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class GetLibraryArtworkProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted query. + public static GetLibraryArtworkProvidersQuery ToQuery(this GetLibraryArtworkProvidersRequest request) + { + return new GetLibraryArtworkProvidersQuery(LibraryId: request.LibraryId); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs new file mode 100644 index 00000000..d21150ff --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/LibraryArtworkProviderConfigurationEntityMapping.cs @@ -0,0 +1,28 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class LibraryArtworkProviderConfigurationEntityMapping +{ + /// + /// Converts to . + /// + /// The repository entity to be converted. + /// The display name of the artwork provider. + /// The converted response. + public static LibraryArtworkProviderResponse ToResponse(this LibraryArtworkProviderConfigurationEntity configuration, string providerName) + { + return new LibraryArtworkProviderResponse( + PluginId: configuration.PluginId, + Name: providerName, + IsEnabled: configuration.IsEnabled, + Rank: configuration.Rank + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs new file mode 100644 index 00000000..7b0ab2fc --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/ReorderLibraryArtworkProvidersRequestMapping.cs @@ -0,0 +1,25 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class ReorderLibraryArtworkProvidersRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static ReorderLibraryArtworkProvidersCommand ToCommand(this ReorderLibraryArtworkProvidersRequest request) + { + return new ReorderLibraryArtworkProvidersCommand( + LibraryId: request.LibraryId, + PluginIds: request.PluginIds + ); + } +} diff --git a/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs new file mode 100644 index 00000000..4494aeb8 --- /dev/null +++ b/src/Lumina.Application/Common/Mapping/Plugins/SetLibraryArtworkProviderEnabledRequestMapping.cs @@ -0,0 +1,26 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Requests.Plugins; +#endregion + +namespace Lumina.Application.Common.Mapping.Plugins; + +/// +/// Extension methods for converting . +/// +public static class SetLibraryArtworkProviderEnabledRequestMapping +{ + /// + /// Converts to . + /// + /// The request to be converted. + /// The converted command. + public static SetLibraryArtworkProviderEnabledCommand ToCommand(this SetLibraryArtworkProviderEnabledRequest request) + { + return new SetLibraryArtworkProviderEnabledCommand( + LibraryId: request.LibraryId, + PluginId: request.PluginId, + IsEnabled: request.IsEnabled + ); + } +} diff --git a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs index 2e14e2f2..c0c5d385 100644 --- a/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Application/Common/Utilities/ValidatorUtilities.cs @@ -93,6 +93,33 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); } + /// + /// Defines a validation rule that ensures the float property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable float property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + /// /// Defines a validation rule that ensures the time span property is greater than the specified value. /// diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs new file mode 100644 index 00000000..7967bf82 --- /dev/null +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/IBookArtworkService.cs @@ -0,0 +1,39 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Primitives; +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; + +/// +/// Interface for the service for storing the artwork of a book into the internal media directory and serving its relative path. +/// +public interface IBookArtworkService +{ + /// + /// Stores the of the book into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken); + + /// + /// Deletes the artwork of the book from the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// An representing either a successful operation, or an error. + Result DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle); +} diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs index f75de677..0d0b29c9 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommand.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics; -using Lumina.Contracts.DTO.MediaContributors; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; @@ -40,7 +40,7 @@ public record AddBookCommand( WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs index 78df6434..1e804b10 100644 --- a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Books/Commands/AddBook/AddBookCommandValidator.cs @@ -1,8 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Utilities; -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Errors; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using System; #endregion namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; @@ -19,6 +20,8 @@ public class AddBookCommandValidator : AbstractValidator { RuleFor(command => command.LibraryId) .NotEmpty() + .WithError(Errors.WrittenContent.BookLibraryCannotBeNull) + .Must(id => id != Guid.Empty) .WithError(Errors.WrittenContent.BookLibraryCannotBeNull); RuleFor(command => command.Path) diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs new file mode 100644 index 00000000..a202a355 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommand.cs @@ -0,0 +1,17 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Command for reordering the artwork providers of a media library. +/// +/// The Id of the media library whose artwork providers are reordered. +/// The plugin Ids in the new order, from highest to lowest rank. +public record ReorderLibraryArtworkProvidersCommand( + Guid LibraryId, + IReadOnlyList PluginIds +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs new file mode 100644 index 00000000..eff8b941 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandler.cs @@ -0,0 +1,92 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.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.Validation; +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.Commands.ReorderLibraryArtworkProviders; + +/// +/// Handler for the command to reorder the artwork providers of a media library. +/// +public class ReorderLibraryArtworkProvidersCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public ReorderLibraryArtworkProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to reorder the artwork providers of a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(ReorderLibraryArtworkProvidersCommand command, CancellationToken cancellationToken) + { + List 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 reorder the artwork providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return getConfigurationsResult.Errors; + + Dictionary configurationsByPluginId = getConfigurationsResult.Value.ToDictionary(configuration => configuration.PluginId); + for (int rank = 0; rank < command.PluginIds.Count; rank++) + { + Guid pluginId = command.PluginIds[rank]; + if (configurationsByPluginId.TryGetValue(pluginId, out LibraryArtworkProviderConfigurationEntity? configuration)) + { + configuration.Rank = rank + 1; + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + } + } + + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs new file mode 100644 index 00000000..770f3f31 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidator.cs @@ -0,0 +1,32 @@ +#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.ReorderLibraryArtworkProviders; + +/// +/// Validates the needed validation rules for . +/// +public class ReorderLibraryArtworkProvidersCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersCommandValidator() + { + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginIds) + .NotNull() + .WithError(Errors.Plugins.PluginIdsListCannotBeNull) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdsListCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs new file mode 100644 index 00000000..e4acf111 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommand.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Command for enabling or disabling an artwork provider for a media library. +/// +/// The Id of the media library whose artwork provider is enabled or disabled. +/// The unique identifier of the plugin providing the artwork. +/// Whether the artwork provider should be enabled for the media library. +public record SetLibraryArtworkProviderEnabledCommand( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +) : ICommand; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs new file mode 100644 index 00000000..c1974e81 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandler.cs @@ -0,0 +1,107 @@ +#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.Validation; +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.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Handler for the command to enable or disable an artwork provider for a media library. +/// +public class SetLibraryArtworkProviderEnabledCommandHandler : ICommandHandler> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public SetLibraryArtworkProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the command to enable or disable an artwork provider for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An representing either a successful operation, or an error. + /// + public async Task> HandleAsync(SetLibraryArtworkProviderEnabledCommand command, CancellationToken cancellationToken) + { + List 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 artwork providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(command.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result getConfigurationResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); + if (getConfigurationResult.IsFailure) + return getConfigurationResult.Errors; + + LibraryArtworkProviderConfigurationEntity configuration; + if (getConfigurationResult.Value is not null) + { + configuration = getConfigurationResult.Value; + configuration.IsEnabled = command.IsEnabled; + } + else + { + // compute the rank to assign to the new configuration, appending it after the existing ones + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return getConfigurationsResult.Errors; + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + configuration = new LibraryArtworkProviderConfigurationEntity + { + Id = Guid.NewGuid(), + LibraryId = command.LibraryId, + PluginId = command.PluginId, + IsEnabled = command.IsEnabled, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + } + + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return upsertResult.Errors; + await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + return Result.Success; + } +} diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs new file mode 100644 index 00000000..040a486f --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidator.cs @@ -0,0 +1,32 @@ +#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.SetLibraryArtworkProviderEnabled; + +/// +/// Validates the needed validation rules for . +/// +public class SetLibraryArtworkProviderEnabledCommandValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledCommandValidator() + { + RuleFor(command => command.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + + RuleFor(command => command.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs new file mode 100644 index 00000000..df65764d --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQuery.cs @@ -0,0 +1,14 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using System; +#endregion + +namespace Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Query for getting the artwork providers configured for a media library. +/// +/// The Id of the media library whose artwork providers are retrieved. +public record GetLibraryArtworkProvidersQuery( + Guid LibraryId +) : IQuery; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs new file mode 100644 index 00000000..e5f518db --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandler.cs @@ -0,0 +1,88 @@ +#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.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.GetLibraryArtworkProviders; + +/// +/// Handler for the query to get the artwork providers configured for a media library. +/// +public class GetLibraryArtworkProvidersQueryHandler : IQueryHandler>> +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IAuthorizationService _authorizationService; + private readonly ICurrentUserService _currentUserService; + private readonly IValidator _validator; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for authorization related functionality. + /// Injected service to retrieve the current user information. + /// Injected unit of work for interacting with the data access layer repositories. + /// Injected validator for application validation rules. + public GetLibraryArtworkProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + { + _authorizationService = authorizationService; + _currentUserService = currentUserService; + _unitOfWork = unitOfWork; + _validator = validator; + } + + /// + /// Handles the query to get the artwork providers configured for a media library. + /// + /// The request to be handled. + /// Cancellation token that can be used to stop the execution. + /// + /// An containing either a collection of , or an error. + /// + public async Task>> HandleAsync(GetLibraryArtworkProvidersQuery query, CancellationToken cancellationToken) + { + List 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 artwork providers of any library; for everyone else, only their own libraries + bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( + userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false); + if (!canAccessLibrary) + return ApplicationErrors.Authorization.NotAuthorized; + + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return getConfigurationsResult.Errors; + + // build a plugin name lookup from the detected plugins + Result> getPluginsResult = await _unitOfWork.PluginRepository.GetAllAsync(cancellationToken).ConfigureAwait(false); + if (getPluginsResult.IsFailure) + return getPluginsResult.Errors; + Dictionary pluginNames = getPluginsResult.Value.ToDictionary(plugin => plugin.Id, plugin => plugin.Name); + + return getConfigurationsResult.Value + .OrderBy(configuration => configuration.Rank) + .Select(configuration => configuration.ToResponse(pluginNames.GetValueOrDefault(configuration.PluginId) ?? string.Empty)) + .ToList(); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs new file mode 100644 index 00000000..4231fb1a --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidator.cs @@ -0,0 +1,26 @@ +#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.GetLibraryArtworkProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryArtworkProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersQueryValidator() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs b/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs new file mode 100644 index 00000000..725576a6 --- /dev/null +++ b/src/Lumina.Contracts/DTO/Common/ArtworkDto.cs @@ -0,0 +1,16 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.DTO.Common; + +/// +/// Data transfer object for the artwork of a media item, provided by an artwork provider. +/// +/// The local file system path of the artwork, when the artwork is a local file. +/// The remote URL of the artwork, when the artwork is fetched over the web. +[DebuggerDisplay("LocalPath: {LocalPath}, RemoteUrl: {RemoteUrl}")] +public sealed record ArtworkDto( + string? LocalPath, + string? RemoteUrl +); diff --git a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs index f557fe73..d0d5f723 100644 --- a/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs +++ b/src/Lumina.Contracts/DTO/MediaLibrary/WrittenContentLibrary/BookLibrary/BookMetadataDto.cs @@ -36,7 +36,7 @@ namespace Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; /// The list of ISBN (International Standard Book Number) of the book. /// The list of media contributors of the book. /// The list of ratings for the book. -/// The URL of the cover image of the book, if applicable. +/// The path of the cover image of the book, if applicable. public sealed record BookMetadataDto( string? Title, string? OriginalTitle, @@ -50,7 +50,7 @@ public sealed record BookMetadataDto( int? PageCount, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, @@ -64,5 +64,5 @@ public sealed record BookMetadataDto( List? Isbns, List? Contributors, List? Ratings, - string? CoverImageUrl + string? CoverImagePath ) : MetadataDto; diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs index d46fa0c9..7754e087 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/AddBookRequest.cs @@ -39,7 +39,7 @@ public record AddBookRequest( WrittenContentMetadataDto? Metadata, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs index 6a5a1dc1..03b500ac 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/GetBooksLiteRequest.cs @@ -18,7 +18,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibra /// Can be to disable alpha filtering, a single ASCII letter (case-insensitive) to filter by that letter, /// "#" to filter by titles whose first character is a digit, or "*" to filter by titles whose first character is neither a letter nor a digit. /// -/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. +/// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// The name of the field by which to sort the results. Optional. /// The direction in which to sort the results. Optional. [DebuggerDisplay("LibraryId: {LibraryId}")] @@ -28,7 +28,7 @@ public record GetBooksLiteRequest( int? PerPage, string? SearchTerm, string? FilterAlphaKey, - bool IgnoreThePrefixForAlphaPicker, + bool ShouldIgnoreThePrefixForAlphaPicker, string? SortBy, SortOrder? SortOrder ); diff --git a/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs new file mode 100644 index 00000000..ff504590 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/GetLibraryArtworkProvidersRequest.cs @@ -0,0 +1,15 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to get the artwork providers configured for a media library. +/// +/// The unique identifier of the media library whose artwork providers are retrieved. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record GetLibraryArtworkProvidersRequest( + Guid LibraryId +); diff --git a/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs new file mode 100644 index 00000000..0e0f815c --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/ReorderLibraryArtworkProvidersRequest.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to reorder the artwork providers of a media library. +/// +/// The unique identifier of the media library whose artwork providers are reordered. Required. +/// The plugin Ids in the new order, from highest to lowest rank. Required. +[DebuggerDisplay("LibraryId: {LibraryId}")] +public sealed record ReorderLibraryArtworkProvidersRequest( + Guid LibraryId, + IReadOnlyList PluginIds +); diff --git a/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs new file mode 100644 index 00000000..bbfb2b95 --- /dev/null +++ b/src/Lumina.Contracts/Requests/Plugins/SetLibraryArtworkProviderEnabledRequest.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics; +#endregion + +namespace Lumina.Contracts.Requests.Plugins; + +/// +/// Represents a request to enable or disable an artwork provider for a media library. +/// +/// The unique identifier of the media library whose artwork provider is enabled or disabled. Required. +/// The unique identifier of the plugin providing the artwork. Required. +/// Whether the artwork provider should be enabled for the media library. Required. +[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")] +public sealed record SetLibraryArtworkProviderEnabledRequest( + Guid LibraryId, + Guid PluginId, + bool IsEnabled +); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs index 483b7579..bf4ea18d 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/BookResponse.cs @@ -38,6 +38,7 @@ namespace Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibr /// The name of the plugin that enriched the metadata of the book, if applicable. /// The date and time when the book was created. /// The optional date and time when the book was updated. +/// The path of the cover image of the book, if available. [DebuggerDisplay("Title: {Metadata.Title}")] public record BookResponse( Guid Id, @@ -46,7 +47,7 @@ public record BookResponse( WrittenContentMetadataDto Metadata, BookFormat? Format, string? Edition, - int? VolumeNumber, + float? VolumeNumber, BookSeriesDto? Series, string? ASIN, string? GoodreadsId, @@ -64,5 +65,6 @@ public record BookResponse( DateTime? LastMetadataUpdateUtc, string? MetadataProvider, DateTime CreatedOnUtc, - DateTime? UpdatedOnUtc + DateTime? UpdatedOnUtc, + string? CoverPath ); diff --git a/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs new file mode 100644 index 00000000..c9b01c01 --- /dev/null +++ b/src/Lumina.Contracts/Responses/Plugins/LibraryArtworkProviderResponse.cs @@ -0,0 +1,19 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Contracts.Responses.Plugins; + +/// +/// Represents an artwork provider configured for a media library. +/// +/// The unique identifier of the plugin providing the artwork. +/// The display name of the artwork provider. +/// Whether the artwork provider is enabled for the media library. +/// The rank of the artwork provider, determining the order in which providers are tried. +public sealed record LibraryArtworkProviderResponse( + Guid PluginId, + string Name, + bool IsEnabled, + int Rank +); diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs new file mode 100644 index 00000000..89618882 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryArtworkProviderConfigurationConfiguration.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +#endregion + +namespace Lumina.DataAccess.Common.Configuration; + +/// +/// Configures the entity mapping for the entity. +/// +public class LibraryArtworkProviderConfigurationConfiguration : IEntityTypeConfiguration +{ + /// + /// Configures the entity. + /// + /// The builder to be used to configure the entity. + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("LibraryArtworkProviderConfigurations"); + builder.HasKey(configuration => configuration.Id); + builder.Property(configuration => configuration.Id) + .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it + .HasColumnOrder(0); + builder.Property(configuration => configuration.LibraryId) + .IsRequired() + .HasColumnOrder(1); + builder.Property(configuration => configuration.PluginId) + .IsRequired() + .HasColumnOrder(2); + builder.Property(configuration => configuration.IsEnabled) + .IsRequired() + .HasColumnOrder(3); + builder.Property(configuration => configuration.Rank) + .IsRequired() + .HasColumnOrder(4); + + // audit + builder.Property(configuration => configuration.CreatedOnUtc) + .IsRequired() + .HasColumnOrder(5); + + builder.Property(configuration => configuration.CreatedBy) + .IsRequired() + .HasColumnOrder(6); + + builder.Property(configuration => configuration.UpdatedOnUtc) + .HasDefaultValue(null) + .HasColumnOrder(7); + + builder.Property(configuration => configuration.UpdatedBy) + .HasDefaultValue(null) + .HasColumnOrder(8); + + builder.HasIndex(configuration => new { configuration.LibraryId, configuration.PluginId }); + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs new file mode 100644 index 00000000..f95ae4c2 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.Designer.cs @@ -0,0 +1,1358 @@ +// +using System; +using Lumina.DataAccess.Core.UoW; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + [DbContext(typeof(LuminaDbContext))] + [Migration("20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation")] + partial class AddsArtworkProvidersAndBookCoverAndMetadataAggregation + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + + modelBuilder.Entity("BookGenres", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("GenreId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "GenreId"); + + b.HasIndex("GenreId"); + + b.ToTable("BookGenres", (string)null); + }); + + modelBuilder.Entity("BookTags", b => + { + b.Property("BookId") + .HasColumnType("TEXT"); + + b.Property("TagId") + .HasColumnType("TEXT"); + + b.HasKey("BookId", "TagId"); + + b.HasIndex("TagId"); + + b.ToTable("BookTags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Permissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.ToTable("Roles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("RoleId", "PermissionId") + .IsUnique(); + + b.ToTable("RolePermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("PermissionId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.HasIndex("UserId", "PermissionId") + .IsUnique(); + + b.ToTable("UserPermissions", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("UserId"); + + b.HasIndex("RoleId"); + + b.HasIndex("UserId", "RoleId") + .IsUnique(); + + b.ToTable("UserRoles", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Genres", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", b => + { + b.Property("Name") + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b.HasKey("Name"); + + b.ToTable("Tags", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("LastWriteTimeUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("DirectoryScanFingerprints", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + + b.Property("CoverImage") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("IsEnabled") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(4); + + b.Property("IsLocked") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("LibraryType") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("ShouldSaveMetadataInMediaDirectories") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ShouldSkipUnchangedDirectoriesDuringScan") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Libraries", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Status") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("LibraryId", "Status", "CreatedOnUtc") + .IsDescending(true, false, true); + + b.ToTable("LibraryScans", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasMaxLength(24) + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Status") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("Path"); + + b.HasIndex("ContentHash", "FileSize", "Path"); + + b.ToTable("LibraryScanResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.Property("LibraryId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("FileSize") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("LibraryId", "Path"); + + b.HasIndex("LibraryId"); + + b.ToTable("LibraryScanSnapshots", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.Property("LibraryScanId") + .HasColumnType("TEXT"); + + b.Property("Path") + .HasMaxLength(1024) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("ContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("IsNew") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("NeedsRehash") + .HasColumnType("INTEGER") + .HasColumnOrder(6); + + b.Property("PreviousContentHash") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("Size") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("Ticks") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.HasKey("LibraryScanId", "Path"); + + b.HasIndex("LibraryScanId", "NeedsRehash"); + + b.ToTable("LibraryScanStagingResults", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("ASIN") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(21); + + b.Property("AppleBooksId") + .HasColumnType("TEXT") + .HasColumnOrder(29); + + b.Property("BarnesAndNobleId") + .HasMaxLength(10) + .HasColumnType("TEXT") + .HasColumnOrder(28); + + b.Property("CoverImagePath") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(33); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(32); + + b.Property("Description") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("Edition") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(19); + + b.Property("Format") + .HasColumnType("TEXT") + .HasColumnOrder(18); + + b.Property("GoodreadsId") + .HasColumnType("TEXT") + .HasColumnOrder(22); + + b.Property("GoogleBooksId") + .HasMaxLength(12) + .HasColumnType("TEXT") + .HasColumnOrder(27); + + b.Property("LCCN") + .HasColumnType("TEXT") + .HasColumnOrder(23); + + b.Property("LanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("LanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("LanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("LastMetadataUpdateUtc") + .HasColumnType("TEXT") + .HasColumnOrder(39); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(36); + + b.Property("LibraryThingId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(26); + + b.Property("MetadataProvider") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(40); + + b.Property("MetadataStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(38); + + b.Property("OCLCNumber") + .HasColumnType("TEXT") + .HasColumnOrder(24); + + b.Property("OpenLibraryId") + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(25); + + b.Property("OriginalLanguageCode") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("OriginalLanguageName") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("OriginalLanguageNativeName") + .HasColumnType("TEXT") + .HasColumnOrder(15); + + b.Property("OriginalReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("OriginalReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(5); + + b.Property("OriginalTitle") + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PageCount") + .HasColumnType("INTEGER") + .HasColumnOrder(17); + + b.Property("Path") + .IsRequired() + .HasMaxLength(2048) + .HasColumnType("TEXT") + .HasColumnOrder(37); + + b.Property("Publisher") + .HasMaxLength(100) + .HasColumnType("TEXT") + .HasColumnOrder(16); + + b.Property("ReReleaseDate") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ReReleaseYear") + .HasColumnType("INTEGER") + .HasColumnOrder(7); + + b.Property("ReleaseCountry") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("ReleaseVersion") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("Title") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(35); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(34); + + b.Property("VolumeNumber") + .HasColumnType("REAL") + .HasColumnOrder(20); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "MetadataStatus"); + + b.HasIndex("LibraryId", "Path"); + + b.ToTable("Books", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryMetadataProviderConfigurations", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.PluginEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Description") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("LoadError") + .HasMaxLength(2000) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("LoadStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("SettingsJson") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("Version") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.HasKey("Id"); + + b.ToTable("Plugins", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Themes.ThemeEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("Author") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(12); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(11); + + b.Property("Description") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("InstallSource") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("InstalledAtUtc") + .HasColumnType("TEXT") + .HasColumnOrder(10); + + b.Property("IsCurrent") + .HasColumnType("INTEGER") + .HasColumnOrder(8); + + b.Property("IsDeleted") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(false) + .HasColumnOrder(9); + + b.Property("Name") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("PreviewPath") + .HasMaxLength(240) + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("ThemeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(14); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(13); + + b.Property("Version") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.HasKey("Id"); + + b.HasIndex("IsCurrent") + .IsUnique() + .HasFilter("IsCurrent = 1"); + + b.HasIndex("ThemeId") + .IsUnique(); + + b.ToTable("Themes", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("Password") + .IsRequired() + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("TempPassword") + .HasColumnType("TEXT") + .HasColumnOrder(3); + + b.Property("TempPasswordCreated") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("TotpSecret") + .HasColumnType("TEXT") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(9); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users", (string)null); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsPaginationEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(2); + + b.Property("IsThemeCachingEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(9); + + b.Property("ItemsPerPage") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.Property("UserId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UserSettings", (string)null); + }); + + modelBuilder.Entity("BookGenres", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.GenreEntity", null) + .WithMany() + .HasForeignKey("GenreId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("BookTags", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", null) + .WithMany() + .HasForeignKey("BookId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Common.TagEntity", null) + .WithMany() + .HasForeignKey("TagId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RolePermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserPermissionEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", "Permission") + .WithMany("UserPermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("UserPermissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithOne("UserRole") + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.Authorization.UserRoleEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.DirectoryScanFingerprintEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", null) + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("Libraries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryContentLocationEntity", "ContentLocations", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("LibraryId") + .HasColumnType("TEXT"); + + b1.Property("Path") + .IsRequired() + .HasMaxLength(260) + .HasColumnType("TEXT") + .HasColumnName("Path"); + + b1.HasKey("Id"); + + b1.HasIndex("LibraryId"); + + b1.ToTable("LibraryContentLocations", (string)null); + + b1.WithOwner() + .HasForeignKey("LibraryId"); + }); + + b.Navigation("ContentLocations"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany("LibraryScans") + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", "User") + .WithMany("LibraryScans") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanResultEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", "LibraryScan") + .WithMany("LibraryScanResults") + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("LibraryScan"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanSnapshotEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", "Library") + .WithMany() + .HasForeignKey("LibraryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Library"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanStagingResultsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", null) + .WithMany() + .HasForeignKey("LibraryScanId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookEntity", b => + { + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.BookRatingEntity", "Ratings", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("MaxValue") + .HasColumnType("decimal(3,2)"); + + b1.Property("Source") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("TEXT"); + + b1.Property("Value") + .HasColumnType("decimal(3,2)"); + + b1.Property("VoteCount") + .HasColumnType("INTEGER"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookRatings", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.OwnsMany("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary.IsbnEntity", "ISBNs", b1 => + { + b1.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b1.Property("BookId") + .HasColumnType("TEXT"); + + b1.Property("Format") + .IsRequired() + .HasMaxLength(6) + .HasColumnType("TEXT"); + + b1.Property("Value") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("TEXT") + .HasColumnName("ISBN"); + + b1.HasKey("Id"); + + b1.HasIndex("BookId"); + + b1.ToTable("BookISBNs", (string)null); + + b1.WithOwner() + .HasForeignKey("BookId"); + }); + + b.Navigation("ISBNs"); + + b.Navigation("Ratings"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", b => + { + b.HasOne("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", null) + .WithOne() + .HasForeignKey("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserSettingsEntity", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.PermissionEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserPermissions"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Authorization.RoleEntity", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity", b => + { + b.Navigation("LibraryScans"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryScanEntity", b => + { + b.Navigation("LibraryScanResults"); + }); + + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.UsersManagement.UserEntity", b => + { + b.Navigation("Libraries"); + + b.Navigation("LibraryScans"); + + b.Navigation("UserPermissions"); + + b.Navigation("UserRole"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs new file mode 100644 index 00000000..3c087310 --- /dev/null +++ b/src/Lumina.DataAccess/Common/Migrations/20260824072133_AddsArtworkProvidersAndBookCoverAndMetadataAggregation.cs @@ -0,0 +1,106 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Lumina.DataAccess.Common.Migrations +{ + /// + public partial class AddsArtworkProvidersAndBookCoverAndMetadataAggregation : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.RenameColumn( + name: "IgnoreThePrefixForAlphaPicker", + table: "UserSettings", + newName: "ShouldIgnoreThePrefixForAlphaPicker"); + + migrationBuilder.RenameColumn( + name: "DownloadMetadataFromWeb", + table: "Libraries", + newName: "CanDownloadMetadataFromWeb"); + + migrationBuilder.AddColumn( + name: "ShouldAggregateMetadataWhenMissing", + table: "UserSettings", + type: "INTEGER", + nullable: false, + defaultValue: false) + .Annotation("Relational:ColumnOrder", 10); + + migrationBuilder.AlterColumn( + name: "VolumeNumber", + table: "Books", + type: "REAL", + nullable: true, + oldClrType: typeof(int), + oldType: "INTEGER", + oldNullable: true); + + migrationBuilder.AddColumn( + name: "CoverImagePath", + table: "Books", + type: "TEXT", + nullable: true); + + migrationBuilder.CreateTable( + name: "LibraryArtworkProviderConfigurations", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + LibraryId = table.Column(type: "TEXT", nullable: false), + PluginId = table.Column(type: "TEXT", nullable: false), + IsEnabled = table.Column(type: "INTEGER", nullable: false), + Rank = table.Column(type: "INTEGER", nullable: false), + CreatedOnUtc = table.Column(type: "TEXT", nullable: false), + CreatedBy = table.Column(type: "TEXT", nullable: false), + UpdatedOnUtc = table.Column(type: "TEXT", nullable: true), + UpdatedBy = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_LibraryArtworkProviderConfigurations", x => x.Id); + }); + + migrationBuilder.CreateIndex( + name: "IX_LibraryArtworkProviderConfigurations_LibraryId_PluginId", + table: "LibraryArtworkProviderConfigurations", + columns: new[] { "LibraryId", "PluginId" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "LibraryArtworkProviderConfigurations"); + + migrationBuilder.DropColumn( + name: "ShouldAggregateMetadataWhenMissing", + table: "UserSettings"); + + migrationBuilder.DropColumn( + name: "CoverImagePath", + table: "Books"); + + migrationBuilder.RenameColumn( + name: "ShouldIgnoreThePrefixForAlphaPicker", + table: "UserSettings", + newName: "IgnoreThePrefixForAlphaPicker"); + + migrationBuilder.RenameColumn( + name: "CanDownloadMetadataFromWeb", + table: "Libraries", + newName: "DownloadMetadataFromWeb"); + + migrationBuilder.AlterColumn( + name: "VolumeNumber", + table: "Books", + type: "INTEGER", + nullable: true, + oldClrType: typeof(float), + oldType: "REAL", + oldNullable: true); + } + } +} diff --git a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs index 3bf74c6a..fbd03351 100644 --- a/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs +++ b/src/Lumina.DataAccess/Common/Migrations/LuminaDbContextModelSnapshot.cs @@ -270,6 +270,12 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(0); + b.Property("CanDownloadMetadataFromWeb") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER") + .HasDefaultValue(true) + .HasColumnOrder(6); + b.Property("CoverImage") .HasMaxLength(255) .HasColumnType("TEXT") @@ -283,12 +289,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(9); - b.Property("DownloadMetadataFromWeb") - .ValueGeneratedOnAdd() - .HasColumnType("INTEGER") - .HasDefaultValue(true) - .HasColumnOrder(6); - b.Property("IsEnabled") .ValueGeneratedOnAdd() .HasColumnType("INTEGER") @@ -535,6 +535,9 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(28); + b.Property("CoverImagePath") + .HasColumnType("TEXT"); + b.Property("CreatedBy") .HasColumnType("TEXT") .HasColumnOrder(33); @@ -685,8 +688,8 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(34); - b.Property("VolumeNumber") - .HasColumnType("INTEGER") + b.Property("VolumeNumber") + .HasColumnType("REAL") .HasColumnOrder(20); b.HasKey("Id"); @@ -698,6 +701,51 @@ namespace Lumina.DataAccess.Common.Migrations b.ToTable("Books", (string)null); }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryArtworkProviderConfigurationEntity", b => + { + b.Property("Id") + .HasColumnType("TEXT") + .HasColumnOrder(0); + + b.Property("CreatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(6); + + b.Property("CreatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(5); + + b.Property("IsEnabled") + .HasColumnType("INTEGER") + .HasColumnOrder(3); + + b.Property("LibraryId") + .HasColumnType("TEXT") + .HasColumnOrder(1); + + b.Property("PluginId") + .HasColumnType("TEXT") + .HasColumnOrder(2); + + b.Property("Rank") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + + b.Property("UpdatedBy") + .HasColumnType("TEXT") + .HasColumnOrder(8); + + b.Property("UpdatedOnUtc") + .HasColumnType("TEXT") + .HasColumnOrder(7); + + b.HasKey("Id"); + + b.HasIndex("LibraryId", "PluginId"); + + b.ToTable("LibraryArtworkProviderConfigurations", (string)null); + }); + modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.Plugins.LibraryMetadataProviderConfigurationEntity", b => { b.Property("Id") @@ -964,10 +1012,6 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("TEXT") .HasColumnOrder(5); - b.Property("IgnoreThePrefixForAlphaPicker") - .HasColumnType("INTEGER") - .HasColumnOrder(4); - b.Property("IsPaginationEnabled") .HasColumnType("INTEGER") .HasColumnOrder(2); @@ -980,6 +1024,14 @@ namespace Lumina.DataAccess.Common.Migrations .HasColumnType("INTEGER") .HasColumnOrder(3); + b.Property("ShouldAggregateMetadataWhenMissing") + .HasColumnType("INTEGER") + .HasColumnOrder(10); + + b.Property("ShouldIgnoreThePrefixForAlphaPicker") + .HasColumnType("INTEGER") + .HasColumnOrder(4); + b.Property("UpdatedBy") .HasColumnType("TEXT") .HasColumnOrder(8); diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs new file mode 100644 index 00000000..f3e0fc6c --- /dev/null +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.Core.Repositories.Plugins; + +/// +/// Repository for the artwork provider configurations of media libraries. +/// +internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderConfigurationRepository +{ + private readonly LuminaDbContext _luminaDbContext; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Entity Framework DbContext. + public ArtworkProviderConfigurationRepository(LuminaDbContext luminaDbContext) + { + _luminaDbContext = luminaDbContext; + } + + /// + /// Gets all the artwork provider configurations of the media library identified by . + /// + /// The Id of the media library whose artwork provider configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either a collection of , or an error. + public async Task>> GetByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryArtworkProviderConfigurations + .Where(configuration => configuration.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the artwork provider configuration of the media library identified by for the plugin identified by . + /// + /// The Id of the media library whose artwork provider configuration is retrieved. + /// The Id of the plugin whose artwork provider configuration is retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the , or an error. + public async Task> GetByLibraryAndPluginIdAsync(Guid libraryId, Guid pluginId, CancellationToken cancellationToken) + { + return await _luminaDbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(configuration => configuration.LibraryId == libraryId && configuration.PluginId == pluginId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Inserts an artwork provider configuration into the storage medium, or updates it when it already exists. + /// + /// The artwork provider configuration to insert or update. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken) + { + LibraryArtworkProviderConfigurationEntity? existingConfiguration = await _luminaDbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(repositoryConfiguration => repositoryConfiguration.LibraryId == configuration.LibraryId && repositoryConfiguration.PluginId == configuration.PluginId, cancellationToken).ConfigureAwait(false); + if (existingConfiguration is null) + _luminaDbContext.LibraryArtworkProviderConfigurations.Add(configuration); + else + { + // update only the mutable fields, preserving the Id of the existing configuration + existingConfiguration.LibraryId = configuration.LibraryId; + existingConfiguration.PluginId = configuration.PluginId; + existingConfiguration.IsEnabled = configuration.IsEnabled; + existingConfiguration.Rank = configuration.Rank; + } + return Result.Updated; + } +} diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs index bab30199..a007e820 100644 --- a/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/BookLibrary/BookRatingSource.cs @@ -29,4 +29,9 @@ public enum BookRatingSource /// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text. /// GoogleBooks, + + /// + /// Ratings sourced from Calibre, an ebook management application. + /// + Calibre, } diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs index c6b1a436..5fc666a9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Book.cs @@ -1,11 +1,11 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.MediaContributorBoundedContext.MediaContributorAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.BookLibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.WrittenContentLibraryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using System; using System.Collections.Generic; using System.Diagnostics; @@ -66,7 +66,7 @@ public sealed class Book : AggregateRoot /// /// Gets the volume or book number in the series, if applicable. /// - public Optional VolumeNumber { get; private set; } + public Optional VolumeNumber { get; private set; } /// /// Gets the series name, if the book is part of a series. @@ -118,6 +118,11 @@ public sealed class Book : AggregateRoot /// public Optional AppleBooksId { get; private set; } + /// + /// Gets the file system path of the cover image of the book, if applicable. + /// + public Optional CoverImagePath { get; private set; } + /// /// Gets the list of ISBN (International Standard Book Number) of the book. /// @@ -165,7 +170,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, @@ -202,6 +207,7 @@ public sealed class Book : AggregateRoot GoogleBooksId = googleBooksId; BarnesAndNobleId = barnesAndNobleId; AppleBooksId = appleBooksId; + CoverImagePath = Optional.None(); CreatedOnUtc = createdOnUtc; UpdatedOnUtc = updatedOnUtc.HasValue ? updatedOnUtc.Value : null; _isbns = isbns; @@ -240,7 +246,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, @@ -317,7 +323,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, @@ -381,6 +387,15 @@ public sealed class Book : AggregateRoot MetadataStatus = MetadataStatus.Failed; } + /// + /// Sets the file system path of the cover image of the book. + /// + /// The file system path of the cover image of the book. + public void SetBookCoverImagePath(string coverImagePath) + { + CoverImagePath = coverImagePath; + } + /// /// Applies the enriched and the related fields to the book, marking its metadata as enriched by the provided . /// @@ -406,7 +421,7 @@ public sealed class Book : AggregateRoot WrittenContentMetadata metadata, Optional format, Optional edition, - Optional volumeNumber, + Optional volumeNumber, Optional series, Optional asin, Optional goodreadsId, diff --git a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs index 28805417..1b0e72f1 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/WrittenContentLibraryBoundedContext/BookLibraryAggregate/Services/Scanners/BookLibraryTypeScanner.cs @@ -33,9 +33,8 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner /// Creates the media library scan jobs for the provided media library. /// /// The unique identifier of the media library for which to create the media library scan jobs. - /// Whether the library permits downloading data from the web, or not. /// A collection of media library scan jobs. - public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb) + public IEnumerable CreateScanJobsForLibrary(LibraryId libraryId) { // declare the list of jobs that this scanner requires IBooksFileSystemDiscoveryJob fileSystemDiscoveryJob = _mediaScanJobFactory.CreateJob(libraryId); @@ -53,14 +52,12 @@ internal class BookLibraryTypeScanner : IBookLibraryTypeScanner mediaLibraryScanHashJob.AddChild(mediaLibraryScanResultsSaveJob); mediaLibraryScanResultsSaveJob.AddParent(mediaLibraryScanHashJob); - // when the library permits downloading data from the web, the metadata enrichment job is the last job in the directed acyclic job graph, - // running after the scan results save job, so that the books are materialized before their metadata is enriched - if (downloadMetadataFromWeb) - { - IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); - mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); - mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob); - } + // the metadata enrichment job is always the last job in the directed acyclic job graph, running after the scan results save job, + // so that the books are materialized before their metadata is enriched. The job itself is the host-side gate that skips the providers + // requiring access to the web when the media library does not permit downloading data from the web, so that the local providers still run offline + IMediaLibraryScanMetadataEnrichmentJob mediaLibraryScanMetadataEnrichmentJob = _mediaScanJobFactory.CreateJob(libraryId); + mediaLibraryScanResultsSaveJob.AddChild(mediaLibraryScanMetadataEnrichmentJob); + mediaLibraryScanMetadataEnrichmentJob.AddParent(mediaLibraryScanResultsSaveJob); // return the top level jobs that will be triggered when the scan will be started yield return fileSystemDiscoveryJob; diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 16ca5a37..a9c05cd1 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -11,6 +11,7 @@ using Lumina.Application.Common.Infrastructure.Themes; using Lumina.Application.Common.Infrastructure.Time; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Progress; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; @@ -28,6 +29,7 @@ using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.WrittenContent.Books; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Progress; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Queue; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Infrastructure.Core.Plugins; using Lumina.Infrastructure.Core.Security; using Lumina.Infrastructure.Core.Themes; @@ -102,6 +104,10 @@ public static class InfrastructureLayerServices services.AddSingleton(); + // book artwork: stores the artwork of the books into the internal media directory + services.AddHttpClient(); + services.AddScoped(); + // plugins: load the plugin assemblies from the plugins directory, register their services and provide the plugin manager string pluginsDirectorySetting = configuration.GetSection(PluginsSettingsDto.SECTION_NAME)["Directory"] ?? "plugins"; string pluginsDirectory = Path.Combine(AppContext.BaseDirectory, pluginsDirectorySetting); diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs new file mode 100644 index 00000000..39080b78 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkService.cs @@ -0,0 +1,337 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +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.SharedKernel.Common.Enums.PhotoLibrary; +using Microsoft.Extensions.Options; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; + +/// +/// Stores the artwork of a book into the internal media directory, under a per-book directory, and returns its relative path. +/// +internal sealed class BookArtworkService : IBookArtworkService +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _environmentContext; + private readonly IPathService _pathService; + private readonly IHttpClientFactory _httpClientFactory; + private readonly MediaSettingsDto _mediaSettings; + + /// + /// Initializes a new instance of the class. + /// + /// Injected facade service for environment contextual services. + /// Injected service for handling file system paths. + /// Injected factory used to create the HTTP clients that download the remote artwork. + /// Injected service for retrieving . + public BookArtworkService(IEnvironmentContext environmentContext, IPathService pathService, IHttpClientFactory httpClientFactory, IOptions mediaSettingsOptions) + { + _environmentContext = environmentContext; + _pathService = pathService; + _httpClientFactory = httpClientFactory; + _mediaSettings = mediaSettingsOptions.Value; + } + + /// + /// Stores the of the book into the internal media directory, and returns the relative path of the stored artwork. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The artwork to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + public async Task> SaveBookArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, ArtworkDto artwork, CancellationToken cancellationToken) + { + // resolve the local file path of the artwork, downloading it to a temporary file when it is remote + Result resolveSourceResult = await ResolveArtworkSourceAsync(artwork, cancellationToken).ConfigureAwait(false); + if (resolveSourceResult.IsFailure) + return resolveSourceResult.Errors; + string sourcePath = resolveSourceResult.Value.Path; + + try + { + Result storeResult = await StoreArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, sourcePath, cancellationToken).ConfigureAwait(false); + if (storeResult.IsFailure) + return storeResult.Errors; + return storeResult; + } + finally + { + // remove the temporary file downloaded for the remote artwork, never a local file of the user + if (resolveSourceResult.Value.IsTemporary && File.Exists(sourcePath)) + { + try + { + File.Delete(sourcePath); + } + catch (IOException) + { + // a failed cleanup of the temporary file must not mask the result of the operation + } + catch (UnauthorizedAccessException) + { + // a failed cleanup of the temporary file must not mask the result of the operation + } + } + } + } + + /// + /// Deletes the artwork of the book from the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// An representing either a successful operation, or an error. + public Result DeleteBookArtwork(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + Result artworkDirectoryPathResult = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + DeleteCover(artworkDirectoryPathResult.Value); + return Result.Deleted; + } + + /// + /// Stores the artwork file at into the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The file system path of the artwork file to store. + /// Cancellation token that can be used to stop the execution. + /// An containing either the relative path of the stored artwork, or an error. + private async Task> StoreArtworkAsync(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle, string sourcePath, CancellationToken cancellationToken) + { + Result sourcePathIdResult = FileSystemPathId.Create(sourcePath); + if (sourcePathIdResult.IsFailure) + return sourcePathIdResult.Errors; + + Result fileExistsResult = _environmentContext.FileProviderService.FileExists(sourcePathIdResult.Value); + if (fileExistsResult.IsFailure) + return fileExistsResult.Errors; + if (!fileExistsResult.Value) + return Errors.FileSystemManagement.FileNotFound; + + // reject the artwork when it is a symbolic link or a reparse point, which could point to any file of the machine + if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.ReparsePoint)) + return Errors.FileSystemManagement.InvalidPath; + + // reject the artwork when it exceeds the maximum allowed size + FileInfo sourceFileInfo = new(sourcePath); + if (sourceFileInfo.Length > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + + // make sure the file is an actual supported image + Result imageTypeResult = await _environmentContext.FileTypeService.GetImageTypeAsync(sourcePathIdResult.Value, cancellationToken).ConfigureAwait(false); + if (imageTypeResult.IsFailure) + return imageTypeResult.Errors; + if (imageTypeResult.Value == ImageType.None) + return Errors.Library.CoverFileMustBeAnImage; + + Result artworkDirectoryPathResult = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + if (artworkDirectoryPathResult.IsFailure) + return artworkDirectoryPathResult.Errors; + + Result ensureDirectoryResult = EnsureDirectory(artworkDirectoryPathResult.Value); + if (ensureDirectoryResult.IsFailure) + return ensureDirectoryResult.Errors; + + // delete the previous cover of the book, so that a changed artwork does not leave orphaned files behind + DeleteCover(artworkDirectoryPathResult.Value); + + Result artworkDirectoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPathResult.Value); + if (artworkDirectoryPathIdResult.IsFailure) + return artworkDirectoryPathIdResult.Errors; + + // copy the artwork file from the source location + Result copyFileResult = _environmentContext.FileProviderService.CopyFile(sourcePathIdResult.Value, artworkDirectoryPathIdResult.Value, true); + if (copyFileResult.IsFailure) + return copyFileResult.Errors; + + // rename the copied file to the standard naming + Result renameFileResult = _environmentContext.FileProviderService.RenameFile(copyFileResult.Value, $"cover.{imageTypeResult.Value.ToString().ToLowerInvariant()}"); + if (renameFileResult.IsFailure) + return renameFileResult.Errors; + + // get the internal relative path for the copied file + string relativePath = renameFileResult.Value.Path[AppContext.BaseDirectory.Length..]; + if (!relativePath.StartsWith(_pathService.PathSeparator)) + relativePath = $"{_pathService.PathSeparator}{relativePath}"; + return relativePath; + } + + /// + /// Resolves the local file system path of the , downloading it to a temporary file when it is remote. + /// + /// The artwork whose source path is resolved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the resolved local source of the artwork, or an error. + private async Task> ResolveArtworkSourceAsync(ArtworkDto artwork, CancellationToken cancellationToken) + { + if (!string.IsNullOrWhiteSpace(artwork.LocalPath)) + return new ArtworkSourceResult(artwork.LocalPath, IsTemporary: false); + + if (string.IsNullOrWhiteSpace(artwork.RemoteUrl)) + return Errors.FileSystemManagement.FileNotFound; + + // download the remote artwork into a temporary file, aborting when it exceeds the maximum allowed size + using HttpClient httpClient = _httpClientFactory.CreateClient(); + string tempPath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-{Guid.NewGuid():N}"); + bool downloaded = false; + try + { + using HttpResponseMessage response = await httpClient.GetAsync(artwork.RemoteUrl, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + return Errors.FileSystemManagement.FileNotFound; + + await using Stream responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); + await using FileStream fileStream = new(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 81920, useAsync: true); + + byte[] buffer = new byte[81920]; + long totalRead = 0; + int bytesRead; + while ((bytesRead = await responseStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) + { + totalRead += bytesRead; + if (totalRead > MAX_ARTWORK_SIZE_BYTES) + return Errors.FileSystemManagement.FileTooLarge; + await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + downloaded = true; + return new ArtworkSourceResult(tempPath, IsTemporary: true); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception) + { + return Errors.FileSystemManagement.FileNotFound; + } + finally + { + // remove the partially downloaded temporary file when the download failed + if (!downloaded && File.Exists(tempPath)) + File.Delete(tempPath); + } + } + + /// + /// Builds the file system path of the directory of the book artwork, under the internal media directory. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// An containing either the file system path of the book artwork directory, or an error. + private Result BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + Result mediaRootPathResult = _pathService.CombinePath(AppContext.BaseDirectory, _mediaSettings.RootDirectory); + if (mediaRootPathResult.IsFailure) + return mediaRootPathResult.Errors; + Result booksPathResult = _pathService.CombinePath(mediaRootPathResult.Value, _mediaSettings.BooksDirectory); + if (booksPathResult.IsFailure) + return booksPathResult.Errors; + + Result librarySegmentResult = _pathService.SanitizeSegment($"{libraryName}-{libraryId}"); + if (librarySegmentResult.IsFailure) + return librarySegmentResult.Errors; + Result authorSegmentResult = _pathService.SanitizeSegment(string.IsNullOrWhiteSpace(authorName) ? "Unknown" : authorName); + if (authorSegmentResult.IsFailure) + return authorSegmentResult.Errors; + Result bookSegmentResult = _pathService.SanitizeSegment($"{bookTitle}-{bookId}"); + if (bookSegmentResult.IsFailure) + return bookSegmentResult.Errors; + + Result libraryPathResult = _pathService.CombinePath(booksPathResult.Value, librarySegmentResult.Value.Name); + if (libraryPathResult.IsFailure) + return libraryPathResult.Errors; + Result authorPathResult = _pathService.CombinePath(libraryPathResult.Value, authorSegmentResult.Value.Name); + if (authorPathResult.IsFailure) + return authorPathResult.Errors; + return _pathService.CombinePath(authorPathResult.Value, bookSegmentResult.Value.Name); + } + + /// + /// Creates the directory at , along with its missing parents. + /// + /// The file system path of the directory to create. + /// An representing either a successful operation, or an error. + private Result EnsureDirectory(string directoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(directoryPath); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; + if (directoryExistsResult.Value) + return Result.Success; + + string? parentDirectoryPath = Path.GetDirectoryName(directoryPath); + if (!string.IsNullOrEmpty(parentDirectoryPath) && !string.Equals(parentDirectoryPath, directoryPath, StringComparison.Ordinal)) + { + Result createParentResult = EnsureDirectory(parentDirectoryPath); + if (createParentResult.IsFailure) + return createParentResult.Errors; + } + + Result parentDirectoryPathIdResult = FileSystemPathId.Create(parentDirectoryPath ?? directoryPath); + if (parentDirectoryPathIdResult.IsFailure) + return parentDirectoryPathIdResult.Errors; + + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(parentDirectoryPathIdResult.Value, Path.GetFileName(directoryPath)); + if (createDirectoryResult.IsFailure) + return createDirectoryResult.Errors; + return Result.Success; + } + + /// + /// Deletes the cover files of the book from the . + /// + /// The file system path of the directory of the book artwork. + private void DeleteCover(string artworkDirectoryPath) + { + Result directoryPathIdResult = FileSystemPathId.Create(artworkDirectoryPath); + if (directoryPathIdResult.IsFailure) + return; + + Result> getFilesResult = _environmentContext.FileProviderService.GetFilePaths(directoryPathIdResult.Value, true); + if (getFilesResult.IsFailure) + return; + + foreach (FileSystemPathId filePathId in getFilesResult.Value) + if (Regex.IsMatch(filePathId.Path, @"[\\/]cover\.[^.\\/]+$", RegexOptions.IgnoreCase)) + _environmentContext.FileProviderService.DeleteFile(filePathId); + } + + /// + /// Describes the resolved local source of the artwork. + /// + private sealed record ArtworkSourceResult(string Path, bool IsTemporary); +} diff --git a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj index 281327e4..1220a724 100644 --- a/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj +++ b/src/Lumina.Infrastructure/Lumina.Infrastructure.csproj @@ -25,6 +25,7 @@ + diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs new file mode 100644 index 00000000..09b9250c --- /dev/null +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProvider.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.Core.Metadata; + +/// +/// Contract for a plugin that provides artwork for media items (i.e., covers, banners, fanart, etc). +/// +public interface IArtworkProvider +{ + /// + /// Gets the display name of the artwork provider. + /// + string Name { get; } + + /// + /// Gets the media library types this artwork provider supports. + /// + IReadOnlyList SupportedLibraryTypes { get; } + + /// + /// Gets a value indicating whether this artwork provider requires access to the web to retrieve artwork. + /// + bool RequiresWebAccess { get; } + + /// + /// Gets the artwork of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the media item, or when no artwork was found. + Task GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken); +} diff --git a/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs new file mode 100644 index 00000000..ea296737 --- /dev/null +++ b/src/Lumina.Plugins.Contracts/Core/Metadata/IArtworkProviderGeneric.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.Core.Metadata; + +/// +/// Contract for a plugin that provides artwork for media items, typed to the media item lookup type. +/// +/// The type of the lookup describing the media item. +public interface IArtworkProvider : IArtworkProvider + where TLookup : MetadataLookupDto +{ + /// + /// Gets the artwork of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the media item, or when no artwork was found. + Task GetArtworkAsync(TLookup lookup, CancellationToken cancellationToken); + + /// + /// Gets the artwork of the media item described by . + /// + /// The lookup describing the media item to get the artwork for. + /// Cancellation token that can be used to stop the execution. + /// The artwork of the media item, or when no artwork was found or the lookup is of another runtime type. + async Task IArtworkProvider.GetArtworkAsync(MetadataLookupDto lookup, CancellationToken cancellationToken) + { + return lookup is TLookup typedLookup ? await GetArtworkAsync(typedLookup, cancellationToken).ConfigureAwait(false) : null; + } +} diff --git a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs index 920f999a..a854cc7c 100644 --- a/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs +++ b/src/Lumina.Presentation.Api/Common/DependencyInjection/PresentationApiLayerServices.cs @@ -171,7 +171,14 @@ public static class PresentationApiLayerServices services.AddAuthorization(); - services.AddFastEndpoints(endpointDiscoveryOptions => endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]); + services.AddFastEndpoints(endpointDiscoveryOptions => + { + endpointDiscoveryOptions.Assemblies = [ typeof(Program).Assembly ]; + // only scan the application assembly, so that duplicate copies of it loaded into other assembly load + // contexts during the process lifetime are never scanned again; otherwise a single host can register + // every endpoint multiple times and fail with duplicate routes + endpointDiscoveryOptions.DisableAutoDiscovery = true; + }); services.AddOpenApi(); diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs index d10992bb..50657a81 100644 --- a/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs +++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Management/ApiRoutes.Libraries.cs @@ -25,5 +25,8 @@ public static partial class ApiRoutes public const string GET_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers"; public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "/libraries/{libraryId}/metadata-providers/{pluginId}/enabled"; public const string REORDER_LIBRARY_METADATA_PROVIDERS = "/libraries/{libraryId}/metadata-providers/reorder"; + public const string GET_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers"; + public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "/libraries/{libraryId}/artwork-providers/{pluginId}/enabled"; + public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "/libraries/{libraryId}/artwork-providers/reorder"; } } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs index 0c45d1bd..197d0cc7 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/AddBook/AddBookEndpointSummary.cs @@ -1,14 +1,14 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Contracts.Requests.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; -using System.Diagnostics.CodeAnalysis; -using System.Collections.Generic; -using Lumina.Contracts.DTO.Common; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; -using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; -using Lumina.Contracts.DTO.MediaContributors; using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.AddBook; @@ -284,7 +284,8 @@ public class AddLibraryEndpointSummary : Summary r.PerPage, "The maximum number of books to retrieve per page. Optional."); RequestParam(r => r.SearchTerm, "The search term used to filter results. Optional."); RequestParam(r => r.FilterAlphaKey, "The alpha key used to filter the results by the first character of their title, for the alpha picker. Optional."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading \"The \" prefix of a title should be ignored when computing the alpha key, or not. Required."); RequestParam(r => r.SortBy, "The name of the field by which to sort the results. Optional."); RequestParam(r => r.SortOrder, "The direction in which to sort the results. Optional."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs new file mode 100644 index 00000000..8aff60f8 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpoint.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// API endpoint for the /libraries/{libraryId}/artwork-providers route. +/// +public class GetLibraryArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly IQueryHandler>> _getLibraryArtworkProvidersQueryHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling get library artwork providers queries. + public GetLibraryArtworkProvidersEndpoint(IQueryHandler>> getLibraryArtworkProvidersQueryHandler) + { + _getLibraryArtworkProvidersQueryHandler = getLibraryArtworkProvidersQueryHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(Http.GET); + Routes(ApiRoutes.Libraries.GET_LIBRARY_ARTWORK_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Gets the artwork providers configured for the media library identified by . + /// + /// The request containing the Id of the media library whose artwork providers are retrieved. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(GetLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) + { + Result> result = await _getLibraryArtworkProvidersQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..d8618092 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointSummary.cs @@ -0,0 +1,130 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersEndpointSummary() + { + Summary = "Retrieves the artwork providers configured for a media library."; + Description = "Retrieves the artwork providers configured for a media library, with their enabled state and rank."; + + ExampleRequest = new GetLibraryArtworkProvidersRequest( + LibraryId: Guid.NewGuid() + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are retrieved. Required."); + + ResponseParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork."); + ResponseParam(r => r.Name, "The display name of the artwork provider."); + ResponseParam(r => r.IsEnabled, "Whether the artwork provider is enabled for the media library."); + ResponseParam(r => r.Rank, "The rank of the artwork provider, determining the order in which providers are tried."); + + Response(200, "The artwork providers configured for the media library are returned.", + example: new LibraryArtworkProviderResponse[] { + new( + PluginId: Guid.NewGuid(), + Name: "Calibre", + IsEnabled: true, + Rank: 1 + ), + new( + PluginId: Guid.NewGuid(), + Name: "Goodreads", + IsEnabled: false, + Rank: 2 + ) + } + ); + + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/artwork-providers" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artwork-providers" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/artwork-providers", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/artwork-providers", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs new file mode 100644 index 00000000..57e492af --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// API endpoint for the /libraries/{libraryId}/artwork-providers/reorder route. +/// +public class ReorderLibraryArtworkProvidersEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _reorderLibraryArtworkProvidersCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling reorder library artwork providers commands. + public ReorderLibraryArtworkProvidersEndpoint(ICommandHandler> reorderLibraryArtworkProvidersCommandHandler) + { + _reorderLibraryArtworkProvidersCommandHandler = reorderLibraryArtworkProvidersCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS); + Version(1); + DontCatchExceptions(); + } + + /// + /// Reorders the artwork providers of the media library identified by . + /// + /// The request containing the Id of the media library and the plugin Ids in the new order. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken) + { + Result result = await _reorderLibraryArtworkProvidersCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs new file mode 100644 index 00000000..4089dcd1 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointSummary.cs @@ -0,0 +1,116 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersEndpointSummary() + { + Summary = "Reorders the artwork providers of a media library."; + Description = "Reorders the artwork providers of a media library, determining the order in which the providers are tried during the artwork enrichment of the library scans."; + + ExampleRequest = new ReorderLibraryArtworkProvidersRequest( + LibraryId: Guid.NewGuid(), + PluginIds: + [ + Guid.NewGuid(), + Guid.NewGuid() + ] + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required."); + RequestParam(r => r.PluginIds, "The plugin Ids in the new order, from highest to lowest rank. Required."); + + Response(200, "The artwork providers of the media library were successfully reordered."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/reorder", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdsListCannotBeNull", + "PluginIdsListCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs new file mode 100644 index 00000000..b525dac5 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpoint.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Common.Routes.Library.Management; +using Lumina.Presentation.Api.Core.Endpoints.Common; +using Microsoft.AspNetCore.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// API endpoint for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. +/// +public class SetLibraryArtworkProviderEnabledEndpoint : BaseEndpoint +{ + private readonly ICommandHandler> _setLibraryArtworkProviderEnabledCommandHandler; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for handling set library artwork provider enabled commands. + public SetLibraryArtworkProviderEnabledEndpoint(ICommandHandler> setLibraryArtworkProviderEnabledCommandHandler) + { + _setLibraryArtworkProviderEnabledCommandHandler = setLibraryArtworkProviderEnabledCommandHandler; + } + + /// + /// Configures the API endpoint. + /// + public override void Configure() + { + Verbs(FastEndpoints.Http.PUT); + Routes(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED); + Version(1); + DontCatchExceptions(); + } + + /// + /// Enables or disables the artwork provider identified by for the media library. + /// + /// The request containing the Ids of the media library and of the artwork provider. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken) + { + Result result = await _setLibraryArtworkProviderEnabledCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); + return result.Match(success => TypedResults.Ok(success), Problem); + } +} diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs new file mode 100644 index 00000000..0d9a6088 --- /dev/null +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointSummary.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Class used for providing a textual description for the API endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledEndpointSummary() + { + Summary = "Enables or disables an artwork provider for a media library."; + Description = "Enables or disables the artwork provider for the media library, so that it is included or excluded from the artwork enrichment of the library scans."; + + ExampleRequest = new SetLibraryArtworkProviderEnabledRequest( + LibraryId: Guid.NewGuid(), + PluginId: Guid.NewGuid(), + IsEnabled: true + ); + + RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required."); + RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required."); + RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library. Required."); + + Response(200, "The artwork provider was successfully enabled or disabled for the media library."); + + Response(401, "Authentication required.", "application/problem+json", + example: new[] + { + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "You are not authorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "Invalid token: The token expired at '01/01/2024 01:00:00'", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" + }, + new + { + type = "https://tools.ietf.org/html/rfc7235#section-3.1", + status = 401, + title = "Unauthorized", + detail = "The token is invalid", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled" + } + } + ); + + Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.4", + title = "General.Failure", + status = 403, + detail = "NotAuthorized", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", + traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00" + } + ); + + Response(404, "The request failed because the requested media library does not exist.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc9110#section-15.5.5", + title = "General.NotFound", + status = 404, + detail = "LibraryNotFound", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", + traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00" + } + ); + + Response(422, "The request did not pass validation checks.", "application/problem+json", + example: new + { + type = "https://tools.ietf.org/html/rfc4918#section-11.2", + title = "General.Validation", + status = 422, + detail = "OneOrMoreValidationErrorsOccurred", + instance = "/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", + errors = new Dictionary + { + { + "General.Validation", new[] + { + "LibraryIdCannotBeEmpty", + "PluginIdCannotBeEmpty" + } + } + }, + traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00" + } + ); + } +} diff --git a/src/Lumina.Presentation.Api/Program.cs b/src/Lumina.Presentation.Api/Program.cs index 41052581..2e7a659f 100644 --- a/src/Lumina.Presentation.Api/Program.cs +++ b/src/Lumina.Presentation.Api/Program.cs @@ -166,7 +166,13 @@ public class Program app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(mediaRootPath), - RequestPath = "/media" + RequestPath = "/media", + OnPrepareResponse = staticFileContext => + { + // the served media must not run as active content, so that attacker-influenced files (e.g. SVG covers) cannot execute scripts on the API origin + staticFileContext.Context.Response.Headers["X-Content-Type-Options"] = "nosniff"; + staticFileContext.Context.Response.Headers["Content-Security-Policy"] = "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:"; + } }); app.MapHub("/scanProgressHub"); diff --git a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs index b746cff9..3159edd1 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDto.cs @@ -137,7 +137,7 @@ public class BookDto /// /// Gets the volume or book number in the series, if applicable. /// - public int? VolumeNumber { get; init; } + public float? VolumeNumber { get; init; } /// /// Gets the series id, if the book is part of a series. diff --git a/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs b/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs index a72eb429..11beb9f6 100644 --- a/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs +++ b/src/Lumina.Presentation.Web/Common/Enums/BookLibrary/BookRatingSource.cs @@ -29,4 +29,9 @@ public enum BookRatingSource /// Ratings from Google Books, a service that searches the full text of books and magazines that Google has scanned and converted to text. /// GoogleBooks, + + /// + /// Ratings sourced from Calibre, an ebook management application. + /// + Calibre, } diff --git a/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs index d6ccbcd7..ea5c1b47 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/Libraries/GetBooksLiteRequest.cs @@ -42,7 +42,7 @@ public class GetBooksLiteRequest /// /// Gets or sets whether the leading "The " prefix of a title is ignored when computing the alpha key, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; } /// /// Gets or sets the name of the field by which to sort the results. diff --git a/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs b/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs index d0fb3591..f444023c 100644 --- a/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs +++ b/src/Lumina.Presentation.Web/Common/Utilities/ValidatorUtilities.cs @@ -93,6 +93,33 @@ public static class ValidatorUtilities return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); } + /// + /// Defines a validation rule that ensures the float property is greater than the specified value. + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => value > valueToCompare); + } + + /// + /// Defines a validation rule that ensures the nullable float property is greater than the specified value. + /// + /// + /// If the property is , this rule passes (use to check for missing values). + /// + /// The type of the request being validated. + /// The rule builder instance. + /// The value that the property must be greater than. + /// The current instance for method chaining. + public static IRuleBuilder GreaterThan(this IRuleBuilder ruleBuilder, float valueToCompare) + { + return ruleBuilder.Must(value => !value.HasValue || value.Value > valueToCompare); + } + /// /// Defines a validation rule that ensures the time span property is greater than the specified value. /// diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs index c8c344d4..e411d87b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/GetLibraryItems/GetLibraryItemsEndpoint.cs @@ -5,7 +5,6 @@ using Lumina.Presentation.Web.Common.DTO.Libraries; using Lumina.Presentation.Web.Common.Requests.Libraries; using Lumina.Presentation.Web.Common.Routes; using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Text; @@ -71,7 +70,7 @@ public class GetLibraryItemsEndpoint : BaseEndpoint r.PerPage, "Optional. The maximum number of books to retrieve per page."); RequestParam(r => r.SearchTerm, "Optional. The search term used to filter results."); RequestParam(r => r.FilterAlphaKey, "Optional. The alpha key used to filter the results by the first character of their title, for the alpha picker."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading The prefix of a title is ignored when computing the alpha key, or not."); RequestParam(r => r.SortBy, "Optional. The name of the field by which to sort the results."); RequestParam(r => r.SortOrder, "Optional. The direction in which to sort the results."); diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml index 6832ccf2..c6fd0f68 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Index.cshtml @@ -100,7 +100,7 @@ params.set('searchTerm', state.searchTerm); if (state.alphaKey !== null) params.set('filterAlphaKey', state.alphaKey); - params.set('ignoreThePrefixForAlphaPicker', state.ignoreThePrefix); + params.set('shouldIgnoreThePrefixForAlphaPicker', state.ignoreThePrefix); params.set('sortOrder', state.sortOrder); return `${url}?${params.toString()}`; } @@ -259,7 +259,7 @@ async function loadSettingsAsync() { const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.GET_USER_SETTINGS)'); if (data) { - state.ignoreThePrefix = data.ignoreThePrefixForAlphaPicker === true; + state.ignoreThePrefix = data.shouldIgnoreThePrefixForAlphaPicker === true; state.perPage = data.isPaginationEnabled === true ? data.itemsPerPage : null; } } diff --git a/src/Lumina.sln b/src/Lumina.sln index 678d100f..6b83d501 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -208,6 +208,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "plugins", "plugins", "{02EA EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary", "..\plugins\Lumina.Plugins.OpenLibrary\Lumina.Plugins.OpenLibrary.csproj", "{EADCD78B-04D5-4FE3-855C-E3015531EC8E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre", "..\plugins\Lumina.Plugins.Calibre\Lumina.Plugins.Calibre.csproj", "{B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Domain.SharedKernel", "Lumina.Domain.SharedKernel\Lumina.Domain.SharedKernel.csproj", "{9450EAC6-1F33-4BE1-89E3-0275885FE3EE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B}" @@ -244,6 +246,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.OpenLibrary.Fixtures", "..\tests\Common\Lumina.Plugins.OpenLibrary.Fixtures\Lumina.Plugins.OpenLibrary.Fixtures.csproj", "{16F65859-93AB-499F-A0BE-9EC05E20435F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.UnitTests", "..\tests\UnitTests\Lumina.Plugins.Calibre.UnitTests\Lumina.Plugins.Calibre.UnitTests.csproj", "{A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.Plugins.Calibre.Fixtures", "..\tests\Common\Lumina.Plugins.Calibre.Fixtures\Lumina.Plugins.Calibre.Fixtures.csproj", "{B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}" +EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lumina.TestPlugin", "..\tests\Common\Lumina.TestPlugin\Lumina.TestPlugin.csproj", "{65AA7896-2DE2-4F07-A1B2-C1E1774521C2}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "theming", "theming", "{2872042D-061F-4C76-8017-0A518A7E28A7}" @@ -461,6 +467,18 @@ Global {EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x64.Build.0 = Release|Any CPU {EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x86.ActiveCfg = Release|Any CPU {EADCD78B-04D5-4FE3-855C-E3015531EC8E}.Release|x86.Build.0 = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x64.ActiveCfg = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x64.Build.0 = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x86.ActiveCfg = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Debug|x86.Build.0 = Debug|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|Any CPU.Build.0 = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x64.ActiveCfg = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x64.Build.0 = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x86.ActiveCfg = Release|Any CPU + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D}.Release|x86.Build.0 = Release|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {9450EAC6-1F33-4BE1-89E3-0275885FE3EE}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -665,6 +683,30 @@ Global {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x64.Build.0 = Release|Any CPU {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x86.ActiveCfg = Release|Any CPU {16F65859-93AB-499F-A0BE-9EC05E20435F}.Release|x86.Build.0 = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x64.ActiveCfg = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x64.Build.0 = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x86.ActiveCfg = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Debug|x86.Build.0 = Debug|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|Any CPU.Build.0 = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x64.ActiveCfg = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x64.Build.0 = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x86.ActiveCfg = Release|Any CPU + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20}.Release|x86.Build.0 = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x64.ActiveCfg = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x64.Build.0 = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x86.ActiveCfg = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Debug|x86.Build.0 = Debug|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|Any CPU.Build.0 = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x64.ActiveCfg = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x64.Build.0 = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x86.ActiveCfg = Release|Any CPU + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31}.Release|x86.Build.0 = Release|Any CPU {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|Any CPU.Build.0 = Debug|Any CPU {65AA7896-2DE2-4F07-A1B2-C1E1774521C2}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -722,6 +764,7 @@ Global {788FADE4-342D-4919-8E5C-10CA8EDBE954} = {70B56088-6D3A-481E-9459-79AC6B16FEC1} {8CF6FEA4-624C-4EC9-93D6-EB7626059D7C} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {EADCD78B-04D5-4FE3-855C-E3015531EC8E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {B7C4D2E1-5A6F-4B8A-9C3D-1E2F4A5B6C7D} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {9450EAC6-1F33-4BE1-89E3-0275885FE3EE} = {3C316ABB-08D5-4450-9A4E-91059DB54254} {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} = {16E590D3-DD9F-4B45-BF19-C6E317A57D11} {E6449D94-C33A-41CE-9047-7298CF20C311} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} @@ -740,6 +783,8 @@ Global {C4C9EA32-AF10-4D03-9907-8EA9EA06EBFB} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {FEC00EBD-6A64-4280-B0F7-1EC5321C294A} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} {16F65859-93AB-499F-A0BE-9EC05E20435F} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} + {A5E8D4C1-2B3C-4D5E-8F6A-7B8C9D0E1F20} = {53B1231B-37F5-44BA-80D5-DBA979775F5C} + {B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {65AA7896-2DE2-4F07-A1B2-C1E1774521C2} = {7E8A2D6B-3F4C-4E5F-9A6B-1C2D3E4F5A6B} {2872042D-061F-4C76-8017-0A518A7E28A7} = {0C0E5A56-AD29-4D0B-AB87-E865F8B933E2} EndGlobalSection diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs new file mode 100644 index 00000000..657a2a25 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryArtworkProviderConfigurationEntityFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryArtworkProviderConfigurationEntityFixture +{ + /// + /// Creates a random valid for the provided media library, plugin and rank. + /// + /// The Id of the media library the configuration belongs to. + /// The Id of the plugin providing the artwork. + /// The rank of the artwork provider, determining the order in which providers are tried. + /// Whether the artwork provider is enabled or not. + /// The created . + public LibraryArtworkProviderConfigurationEntity Create( + Guid libraryId, + Guid pluginId, + int rank, + bool isEnabled = true) + { + return new Faker() + .RuleFor(configuration => configuration.Id, faker => faker.Random.Guid()) + .RuleFor(configuration => configuration.LibraryId, libraryId) + .RuleFor(configuration => configuration.PluginId, pluginId) + .RuleFor(configuration => configuration.IsEnabled, isEnabled) + .RuleFor(configuration => configuration.Rank, rank) + .RuleFor(configuration => configuration.CreatedOnUtc, faker => faker.Date.Past()) + .RuleFor(configuration => configuration.CreatedBy, faker => faker.Random.Guid()) + .RuleFor(configuration => configuration.UpdatedOnUtc, faker => faker.Date.Recent()) + .RuleFor(configuration => configuration.UpdatedBy, faker => faker.Random.Guid()) + .Generate(); + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// The Id of the media library the configurations belong to. + /// The Id of the plugin providing the artwork. + /// The rank of the artwork providers. + /// List of configured instances. + public List CreateMany(int count, Guid libraryId, Guid pluginId, int rank) + { + return [.. Enumerable.Range(0, count).Select(_ => Create(libraryId, pluginId, rank))]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs new file mode 100644 index 00000000..42ecdbc6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersCommandFixture +{ + /// + /// Creates a random valid command to reorder the artwork providers of a media library. + /// + /// Optional. The Id of the media library whose artwork providers are reordered. + /// Optional. The plugin Ids in the new order. + /// The created command. + public ReorderLibraryArtworkProvidersCommand Create( + Guid? libraryId = null, + IReadOnlyList? pluginIds = null) + { + return new Faker() + .CustomInstantiator(f => new ReorderLibraryArtworkProvidersCommand( + default, + default!)) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) + .RuleFor(x => x.PluginIds, f => pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs new file mode 100644 index 00000000..db917fec --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledCommandFixture +{ + /// + /// Creates a random valid command to enable or disable an artwork provider for a media library. + /// + /// Optional. The Id of the media library whose artwork provider is enabled or disabled. + /// Optional. The Id of the plugin providing the artwork. + /// Whether the artwork provider should be enabled for the media library. + /// The created command. + public SetLibraryArtworkProviderEnabledCommand Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool isEnabled = true) + { + return new Faker() + .CustomInstantiator(f => new SetLibraryArtworkProviderEnabledCommand( + default, + default, + true)) + .RuleFor(x => x.LibraryId, libraryId ?? Guid.NewGuid()) + .RuleFor(x => x.PluginId, pluginId ?? Guid.NewGuid()) + .RuleFor(x => x.IsEnabled, isEnabled) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs new file mode 100644 index 00000000..8f1678e3 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersQueryFixture +{ + /// + /// Creates a random valid query to get the artwork providers of a media library. + /// + /// Optional. The Id of the media library whose artwork providers are retrieved. + /// The created query. + public GetLibraryArtworkProvidersQuery Create( + Guid? libraryId = null) + { + return new Faker() + .CustomInstantiator(f => new GetLibraryArtworkProvidersQuery( + libraryId ?? Guid.NewGuid())) + .Generate(); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs new file mode 100644 index 00000000..54f61ead --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/Common/ArtworkDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.Common; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ArtworkDtoFixture +{ + /// + /// Creates an . + /// + /// Optional. The local file system path of the artwork. + /// Optional. The remote URL of the artwork. + /// The created . + public ArtworkDto Create( + string? localPath = null, + string? remoteUrl = null) + { + return new ArtworkDto(localPath, remoteUrl); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..d6b93aca --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/GetLibraryArtworkProvidersRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artwork providers are retrieved. + /// The created . + public GetLibraryArtworkProvidersRequest Create( + Guid? libraryId = null) + { + return new GetLibraryArtworkProvidersRequest( + libraryId ?? _faker.Random.Guid() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs new file mode 100644 index 00000000..8c65fa86 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/ReorderLibraryArtworkProvidersRequestFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artwork providers are reordered. + /// Optional. The plugin Ids in the new order. + /// The created . + public ReorderLibraryArtworkProvidersRequest Create( + Guid? libraryId = null, + IReadOnlyList? pluginIds = null) + { + return new ReorderLibraryArtworkProvidersRequest( + libraryId ?? _faker.Random.Guid(), + pluginIds ?? [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()] + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs new file mode 100644 index 00000000..cd7f3dbb --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Plugins/SetLibraryArtworkProviderEnabledRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the media library whose artwork provider is enabled or disabled. + /// Optional. The Id of the plugin providing the artwork. + /// Optional. Whether the artwork provider should be enabled. + /// The created . + public SetLibraryArtworkProviderEnabledRequest Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool? isEnabled = null) + { + return new SetLibraryArtworkProviderEnabledRequest( + libraryId ?? _faker.Random.Guid(), + pluginId ?? _faker.Random.Guid(), + isEnabled ?? _faker.Random.Bool() + ); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs new file mode 100644 index 00000000..dc52ae02 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryArtworkProviderResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Plugins; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class LibraryArtworkProviderResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the artwork. + /// Optional. The display name of the artwork provider. + /// Optional. Whether the artwork provider is enabled for the media library. + /// Optional. The rank of the artwork provider. + /// The created . + public LibraryArtworkProviderResponse Create( + Guid? pluginId = null, + string? name = null, + bool? isEnabled = null, + int? rank = null) + { + return new LibraryArtworkProviderResponse( + pluginId ?? Guid.NewGuid(), + name ?? _faker.Company.CompanyName(), + isEnabled ?? _faker.Random.Bool(), + rank ?? _faker.Random.Int(1, 100)); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs new file mode 100644 index 00000000..fc701d23 --- /dev/null +++ b/tests/Common/Lumina.Infrastructure.Fixtures/Common/Setup/StubHttpMessageHandler.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Fixtures.Common.Setup; + +/// +/// test double that returns the configured response for every request, without performing any network I/O. +/// +[ExcludeFromCodeCoverage] +internal sealed class StubHttpMessageHandler : HttpMessageHandler +{ + private HttpStatusCode _statusCode; + private byte[] _responseBody; + + /// + /// Initializes a new instance of the class. + /// + /// The initial status code of the response to return. + /// The initial body of the response to return. + public StubHttpMessageHandler(HttpStatusCode statusCode = HttpStatusCode.OK, byte[]? responseBody = null) + { + _statusCode = statusCode; + _responseBody = responseBody ?? []; + } + + /// + /// Configures the response to return for every subsequent request. + /// + /// The status code of the response to return. + /// The body of the response to return. + public void SetResponse(HttpStatusCode statusCode, byte[] responseBody) + { + _statusCode = statusCode; + _responseBody = responseBody; + } + + /// + /// Returns a response with the configured status code and body. + /// + /// The request, which is ignored. + /// Cancellation token that can be used to cancel the operation. + /// The configured response. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(new HttpResponseMessage(_statusCode) + { + Content = new ByteArrayContent(_responseBody) + }); + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs new file mode 100644 index 00000000..c4fac999 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfContributorDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfContributorDtoFixture +{ + /// + /// Creates an . + /// + /// The name of the contributor. + /// The role code of the contributor, for example bkp for the book producer. + /// The created . + public OpfContributorDto Create( + string name = "Test Contributor", + string? role = null) + { + return new OpfContributorDto(name, role); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs new file mode 100644 index 00000000..2306d084 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfCreatorDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfCreatorDtoFixture +{ + /// + /// Creates an . + /// + /// The name of the creator. + /// The role code of the creator, for example aut for author. + /// The created . + public OpfCreatorDto Create( + string name = "Test Creator", + string? role = null) + { + return new OpfCreatorDto(name, role); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs new file mode 100644 index 00000000..e706f2dd --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfDocumentDtoFixture.cs @@ -0,0 +1,81 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfDocumentDtoFixture +{ + /// + /// Creates an . + /// + /// Optional. The title of the book. + /// Optional. The description of the book, in HTML format. + /// Optional. The publisher of the book. + /// Optional. The publication date of the book. + /// Optional. The language code of the book. + /// Optional. The name of the series the book belongs to. + /// Optional. The index of the book within its series. + /// Optional. The personal rating of the book, on a scale of 0 to 10. + /// Optional. The href of the cover image, relative to the directory of the book. + /// Optional. The subjects of the book, used as tags. + /// Optional. The creators of the book. + /// Optional. The contributors of the book. + /// Optional. The identifiers of the book, with their schemes. + /// The created . + public OpfDocumentDto Create( + string? title = null, + string? description = null, + string? publisher = null, + DateTimeOffset? publishDate = null, + string? languageCode = null, + string? series = null, + double? seriesIndex = null, + int? rating = null, + string? coverHref = null, + IEnumerable? subjects = null, + IEnumerable? creators = null, + IEnumerable? contributors = null, + IEnumerable? identifiers = null) + { + OpfDocumentDto document = new() + { + Title = title, + Description = description, + Publisher = publisher, + PublishDate = publishDate, + LanguageCode = languageCode, + Series = series, + SeriesIndex = seriesIndex, + Rating = rating, + CoverHref = coverHref + }; + if (subjects is not null) + document.Subjects.AddRange(subjects); + if (creators is not null) + document.Creators.AddRange(creators); + if (contributors is not null) + document.Contributors.AddRange(contributors); + if (identifiers is not null) + document.Identifiers.AddRange(identifiers); + return document; + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs new file mode 100644 index 00000000..0b58df76 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Common/Models/DTO/Opf/OpfIdentifierDtoFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class OpfIdentifierDtoFixture +{ + /// + /// Creates an . + /// + /// The scheme of the identifier, for example ISBN or GOODREADS. + /// The value of the identifier. + /// The created . + public OpfIdentifierDto Create( + string scheme = "ISBN", + string value = "9780306406157") + { + return new OpfIdentifierDto(scheme, value); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs new file mode 100644 index 00000000..ac5f3324 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookup.cs @@ -0,0 +1,13 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata; + +/// +/// Concrete used to represent a lookup that is not a book lookup. +/// +[ExcludeFromCodeCoverage] +internal sealed record TestMetadataLookup(Guid LibraryId, string Path) : MetadataLookupDto; diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs new file mode 100644 index 00000000..e8a90623 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Core/Metadata/TestMetadataLookupFixture.cs @@ -0,0 +1,38 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.Calibre.Fixtures.Core.Metadata; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class TestMetadataLookupFixture +{ + /// + /// Creates a that is not a book lookup. + /// + /// The Id of the media library, or to generate a random one. + /// The file system path of the media item. + /// The created . + public TestMetadataLookup Create( + Guid? libraryId = null, + string? path = null) + { + return new TestMetadataLookup(libraryId ?? Guid.NewGuid(), path ?? "/some/path"); + } + + /// + /// Creates a list of . + /// + /// The number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj new file mode 100644 index 00000000..bacaf455 --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Lumina.Plugins.Calibre.Fixtures.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..59eb394e --- /dev/null +++ b/tests/Common/Lumina.Plugins.Calibre.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.Calibre.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.Calibre.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("B6F9E5D2-3C4D-5E6F-9A7B-8C9D0E1F2A31")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.Calibre.UnitTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..7d78014b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,153 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetLibraryArtworkProviders_WhenProvidersAreConfigured_ShouldReturnThemOrderedByRank() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginIdA = Guid.NewGuid(); + Guid pluginIdB = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginIdA, pluginIdB); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? providers = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(providers); + Assert.Equal(2, providers!.Count); + Assert.Equal(pluginIdA, providers[0].PluginId); + Assert.Equal(1, providers[0].Rank); + Assert.Equal(pluginIdB, providers[1].PluginId); + Assert.Equal(2, providers[1].Rank); + } + + [Fact] + public async Task GetLibraryArtworkProviders_WhenNoProvidersAreConfigured_ShouldReturnEmptyList() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + List? providers = await response.Content.ReadFromJsonAsync>(_jsonOptions); + Assert.NotNull(providers); + Assert.Empty(providers!); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds two instances in the database. + /// + /// The Id of the media library. + /// The Id of the first plugin. + /// The Id of the second plugin. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true)); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..6887dc59 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ReorderLibraryArtworkProvidersEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task ReorderLibraryArtworkProviders_WhenCalledWithValidData_ShouldReorderTheProviders() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginIdA = Guid.NewGuid(); + Guid pluginIdB = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginIdA, rank: 1); + await SeedConfigurationAsync(libraryId, pluginIdB, rank: 2); + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( + libraryId: libraryId, + pluginIds: [pluginIdB, pluginIdA] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List configurations = await dbContext.LibraryArtworkProviderConfigurations + .Where(config => config.LibraryId == libraryId) + .OrderBy(config => config.Rank) + .ToListAsync(); + Assert.Equal(2, configurations.Count); + Assert.Equal(pluginIdB, configurations[0].PluginId); + Assert.Equal(1, configurations[0].Rank); + Assert.Equal(pluginIdA, configurations[1].PluginId); + Assert.Equal(2, configurations[1].Rank); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the media library. + /// The Id of the plugin. + /// The rank of the provider. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..a8d33410 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -0,0 +1,156 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetLibraryArtworkProviderEnabledEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task SetLibraryArtworkProviderEnabled_WhenNoConfigurationExists_ShouldCreateIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginId = Guid.NewGuid(); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); + Assert.NotNull(configuration); + Assert.True(configuration!.IsEnabled); + Assert.Equal(1, configuration.Rank); + } + + [Fact] + public async Task SetLibraryArtworkProviderEnabled_WhenConfigurationExists_ShouldUpdateItsEnabledState() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = Guid.NewGuid(); + await SeedLibraryAsync(libraryId, userId); + Guid pluginId = Guid.NewGuid(); + await SeedConfigurationAsync(libraryId, pluginId, isEnabled: false, rank: 1); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + LibraryArtworkProviderConfigurationEntity? configuration = await dbContext.LibraryArtworkProviderConfigurations + .FirstOrDefaultAsync(config => config.LibraryId == libraryId && config.PluginId == pluginId); + Assert.NotNull(configuration); + Assert.True(configuration!.IsEnabled); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the library to seed. + /// The Id of the user that owns the library. + /// A task representing the asynchronous operation. + private async Task SeedLibraryAsync(Guid libraryId, Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a in the database. + /// + /// The Id of the media library. + /// The Id of the plugin. + /// Whether the provider is enabled. + /// The rank of the provider. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Gets the Id of the currently authenticated test user. + /// + /// The Id of the authenticated test user. + private Guid GetCurrentUserId() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..4e6d5c9f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,119 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Contains security tests for the /libraries/{libraryId}/artwork-providers route. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task GetLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + + // Act + HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Libraries--")] // destructive injection + public async Task GetLibraryArtworkProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId) + { + // Arrange + // authenticate with an admin user and seed a library with an artwork provider configuration, so a valid id would reach the handler + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedConfigurationAsync(libraryId); + + // Act + HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artwork-providers"); + + // Assert + // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler + // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding + // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) + // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a for the library identified by . + /// + /// The Id of the media library. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1)); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..9749c528 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Contains security tests for the /libraries/{libraryId}/artwork-providers/reorder route. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create( + libraryId: Guid.NewGuid(), + pluginIds: [Guid.NewGuid()] + ); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Plugins--")] // destructive injection + public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId) + { + // Arrange + // authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedConfigurationAsync(libraryId, rank: 1); + await SeedConfigurationAsync(libraryId, rank: 2); + + // Act + // the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization + // before it ever reaches the endpoint handler + HttpResponseMessage response = await client.PutAsJsonAsync( + $"/api/v1/libraries/{libraryId}/artwork-providers/reorder", + new { libraryId, pluginIds = new[] { maliciousPluginId } }); + + // Assert + // note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and + // FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400 + // (pre-existing production bug, not fixed here) + // note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a for the library identified by . + /// + /// The Id of the media library. + /// The rank of the provider. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId, int rank) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..72501673 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -0,0 +1,126 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Contains security tests for the /libraries/{libraryId}/artwork-providers/{pluginId}/enabled route. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory) + { + _apiFactory = apiFactory; + _client = apiFactory.CreateClient(); + } + + [Fact] + public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string libraryId = Guid.NewGuid().ToString(); + string pluginId = Guid.NewGuid().ToString(); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString()); + Assert.Equal("Unauthorized", problemDetails["title"].GetString()); + Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Libraries--")] // destructive injection + public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId) + { + // Arrange + // authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler + HttpClient client = _apiFactory.CreateClient(); + Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedConfigurationAsync(libraryId); + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true); + + // Act + HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request); + + // Assert + // note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler + // note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding + // ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here) + // note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedLibraryAsync(Guid userId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a for the library identified by . + /// + /// The Id of the media library. + /// A task representing the asynchronous operation. + private async Task SeedConfigurationAsync(Guid libraryId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs new file mode 100644 index 00000000..05c0dbf8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -0,0 +1,236 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Common.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.MediaLibrary.Artwork; + +/// +/// Contains security tests for the contract, exercised through the real implementation resolved from the dependency injection container. +/// +[ExcludeFromCodeCoverage] +public class BookArtworkServiceSecurityTests +{ + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IBookArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookArtworkServiceSecurityTests() + { + IEnvironmentContext mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); + + IConfiguration mockConfiguration = Substitute.For(); + mockConfiguration.GetSection(Arg.Any()).Returns(Substitute.For()); + + ServiceCollection services = new(); + services.AddInfrastructureLayerServices(mockConfiguration); + services.AddScoped(_ => mockEnvironmentContext); + // the real path service is used, so that the sanitization of hostile segment names is exercised + services.AddScoped(_ => CreateRealPathService()); + services.AddSingleton(Options.Create(mediaSettings)); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + using IServiceScope scope = serviceProvider.CreateScope(); + _sut = scope.ServiceProvider.GetRequiredService(); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsAReparsePoint_ShouldRejectIt() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // the environment does not support creating reparse points + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + // Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenNameSegmentsContainPathTraversal_ShouldSanitizeThemIntoLiteralSegments() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[1024]); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(Result.From(true)); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + + string capturedDestinationPath = string.Empty; + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Do(destination => capturedDestinationPath = destination.Path), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg")))); + + // Act + Result result = await _sut.SaveBookArtworkAsync( + Guid.NewGuid(), + Guid.NewGuid(), + libraryName: "..\\..\\Library", + authorName: "..\\evil", + bookTitle: "..\\..\\cover", + _artworkDtoFixture.Create(localPath: sourcePath), + CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.False(string.IsNullOrEmpty(capturedDestinationPath)); + string[] segments = capturedDestinationPath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries); + Assert.DoesNotContain(segments, segment => segment == ".."); + Assert.DoesNotContain(segments, segment => segment == "."); + Assert.DoesNotContain(result.Value.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries), segment => segment == ".."); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLibraryNameIsADotDotSegment_ShouldReturnInvalidPath() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[1024]); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), libraryName: "..", authorName: "Author", bookTitle: "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + /// + /// Creates a real backed by a stubbed path strategy, so that the sanitization of hostile segment names is exercised. + /// + /// The created real path service. + private static IPathService CreateRealPathService() + { + IPathStrategy mockPathStrategy = Substitute.For(); + mockPathStrategy.PathSeparator.Returns(Path.DirectorySeparatorChar); + mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(Path.GetInvalidFileNameChars()); + mockPathStrategy.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(FileSystemPathId.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())).Value)); + mockPathStrategy.IsValidPath(Arg.Any()).Returns(true); + + IPlatformContext mockPlatformContext = Substitute.For(); + mockPlatformContext.PathStrategy.Returns(mockPathStrategy); + IPlatformContextManager mockPlatformContextManager = Substitute.For(); + mockPlatformContextManager.GetCurrentContext().Returns(mockPlatformContext); + + return new PathService(mockPlatformContextManager); + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs new file mode 100644 index 00000000..8dc6371d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/CalibreArtworkProviderSecurityTests.cs @@ -0,0 +1,110 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre; + +/// +/// Contains security tests for the class, exercised through the public artwork provider surface. +/// +[ExcludeFromCodeCoverage] +public class CalibreArtworkProviderSecurityTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheCoverInsideTheBookDirectory() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = WriteBookWithCoverReference(bookDirectory, "cover.jpg"); + File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes"); + IArtworkProvider provider = CreateArtworkProvider(); + + // Act + ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Theory] + [InlineData("../cover.jpg")] // parent directory escape + [InlineData("../../cover.jpg")] // multiple parent directory escape + [InlineData("sub/cover.jpg")] // forward slash path traversal + [InlineData("sub\\cover.jpg")] // backslash path traversal + [InlineData(@"C:\Windows\System32\drivers\etc\hosts")] // absolute Windows path + [InlineData("/etc/passwd")] // absolute Unix path + [InlineData("http://evil.example/cover.jpg")] // remote URL + [InlineData("file:///etc/passwd")] // file URI + public async Task GetArtworkAsync_WhenCoverHrefEscapesTheBookDirectory_ShouldReturnNull(string coverHref) + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = WriteBookWithCoverReference(bookDirectory, coverHref); + IArtworkProvider provider = CreateArtworkProvider(); + + // Act + ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates the Calibre artwork provider by registering the plugin services and resolving the keyed artwork provider. + /// + /// The created Calibre artwork provider. + private static IArtworkProvider CreateArtworkProvider() + { + ServiceCollection services = new(); + new CalibrePlugin().RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + return serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)!; + } + + /// + /// Writes an OPF file that references the given cover into the book directory, and returns the path of the book. + /// + /// The file system path of the directory the OPF file is written into. + /// The href of the cover the OPF file references. + /// The file system path of the book. + private static string WriteBookWithCoverReference(string bookDirectory, string coverHref) + { + string opf = $$"""Test"""; + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf); + return bookPath; + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs new file mode 100644 index 00000000..9930968d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Plugins/Calibre/Opf/OpfReaderSecurityTests.cs @@ -0,0 +1,155 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Calibre.Core.Opf; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre.Opf; + +/// +/// Contains security tests for the class, exercised through the public metadata provider surface. +/// +[ExcludeFromCodeCoverage] +public class OpfReaderSecurityTests +{ + private const int MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024; + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + + [Fact] + public async Task GetMetadataAsync_WhenOpfContainsADoctypeWithAnExternalEntity_ShouldNotExpandTheEntity() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + // the OPF is untrusted XML, so a DTD with an external entity must be rejected instead of being read and expanded + string opfContent = """]>&xxe;"""; + string bookPath = WriteBookWithOpf(bookDirectory, opfContent); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandTheEntities() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string opfContent = """]>&lol3;"""; + string bookPath = WriteBookWithOpf(bookDirectory, opfContent); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfIsOversized_ShouldNotParseIt() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string oversizedContent = $"""{new string('a', MAX_OPF_FILE_SIZE_BYTES + 100)}"""; + string bookPath = WriteBookWithOpf(bookDirectory, oversizedContent); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfIsMalformedXml_ShouldNotExposeAnException() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = WriteBookWithOpf(bookDirectory, """Unclosed"""); + IMetadataProvider provider = CreateMetadataProvider(); + + // Act + MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None); + + // Assert + // a malformed OPF must be swallowed and must not leak an exception to the caller + Assert.NotNull(result); + Assert.Null(((BookMetadataDto)result!).Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates the Calibre metadata provider by registering the plugin services and resolving the keyed metadata provider. + /// + /// The created Calibre metadata provider. + private static IMetadataProvider CreateMetadataProvider() + { + ServiceCollection services = new(); + new CalibrePlugin().RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + return serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)!; + } + + /// + /// Writes an OPF file with the given content into the book directory, and returns the path of the book. + /// + /// The file system path of the directory the OPF file is written into. + /// The content of the OPF file to write. + /// The file system path of the book. + private static string WriteBookWithOpf(string bookDirectory, string opfContent) + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opfContent); + return bookPath; + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-opf-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs new file mode 100644 index 00000000..b733d3e8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandHandlerTests.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.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.Validation; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly ReorderLibraryArtworkProvidersCommandHandler _sut; + private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new ReorderLibraryArtworkProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldAssignRanksInTheProvidedOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryArtworkProviderConfigurationEntity secondProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List { firstProvider, secondProvider }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == secondProvider.PluginId && configuration.Rank == 1), + Arg.Any()); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == firstProvider.PluginId && configuration.Rank == 2), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAProvidedPluginIsNotConfigured_ShouldSkipIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity configuration = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 1); + Guid unknownPluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List { configuration }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [unknownPluginId, configuration.PluginId]), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(candidate => candidate.PluginId == configuration.PluginId && candidate.Rank == 2), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginIdsListCannotBeEmpty, result.FirstError); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get configurations")); + + // Act + Result result = await _sut.HandleAsync(_reorderLibraryArtworkProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs new file mode 100644 index 00000000..cdaa5549 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersCommandValidatorTests.cs @@ -0,0 +1,104 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersCommandValidatorTests +{ + private readonly ReorderLibraryArtworkProvidersCommandValidator _validator = new(); + private readonly ReorderLibraryArtworkProvidersCommandFixture _reorderLibraryArtworkProvidersCommandFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + command = command with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdsIsNull_ShouldHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + command = command with { PluginIds = null! }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); + } + + [Fact] + public void Validate_WhenPluginIdsIsEmpty_ShouldHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + command = command with { PluginIds = [] }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdsAreValid_ShouldNotHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeNull); + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdsListCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + ReorderLibraryArtworkProvidersCommand command = _reorderLibraryArtworkProvidersCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs new file mode 100644 index 00000000..8d6e2260 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandHandlerTests.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.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.Validation; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly SetLibraryArtworkProviderEnabledCommandHandler _sut; + private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); + private readonly Guid _userId; + + /// + /// Fixture for generating test data. + /// + private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockConfigurationRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockConfigurationRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + _sut = new SetLibraryArtworkProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationDoesNotExist_ShouldCreateEnabledConfigurationWithNextRank() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryArtworkProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List()); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 1), + Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationDoesNotExistAndOthersExist_ShouldAppendAfterTheHighestRank() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryArtworkProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List + { + _libraryArtworkProviderConfigurationEntityFixture.Create( + libraryId: libraryId, + pluginId: Guid.NewGuid(), + rank: 3, + isEnabled: true) + }); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: false), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => !configuration.IsEnabled && configuration.Rank == 4), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() + { + // Arrange + LibraryArtworkProviderConfigurationEntity existingConfiguration = _libraryArtworkProviderConfigurationEntityFixture.Create( + libraryId: Guid.NewGuid(), + pluginId: Guid.NewGuid(), + rank: 2, + isEnabled: false); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(existingConfiguration.LibraryId, existingConfiguration.PluginId, Arg.Any()) + .Returns(existingConfiguration); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.IsEnabled && configuration.Rank == 2), + Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutPersisting() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.PluginIdCannotBeEmpty, result.FirstError); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockConfigurationRepository.DidNotReceive().GetByLibraryAndPluginIdAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByLibraryAndPluginIdFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get configuration")); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpsertFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + _mockConfigurationRepository.GetByLibraryAndPluginIdAsync(libraryId, pluginId, Arg.Any()) + .Returns((LibraryArtworkProviderConfigurationEntity?)null); + _mockConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(new List()); + _mockConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to upsert configuration")); + + // Act + Result result = await _sut.HandleAsync(_setLibraryArtworkProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs new file mode 100644 index 00000000..df6d5a97 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledCommandValidatorTests.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledCommandValidatorTests +{ + private readonly SetLibraryArtworkProviderEnabledCommandValidator _validator = new(); + private readonly SetLibraryArtworkProviderEnabledCommandFixture _setLibraryArtworkProviderEnabledCommandFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + command = command with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + command = command with { PluginId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveValidationError() + { + // Arrange + SetLibraryArtworkProviderEnabledCommand command = _setLibraryArtworkProviderEnabledCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs new file mode 100644 index 00000000..052052ba --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryHandlerTests.cs @@ -0,0 +1,231 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.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.Validation; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly IArtworkProviderConfigurationRepository _mockArtworkProviderConfigurationRepository; + private readonly IPluginRepository _mockPluginRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; + private readonly GetLibraryArtworkProvidersQueryHandler _sut; + private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly Guid _userId; + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockArtworkProviderConfigurationRepository = Substitute.For(); + _mockPluginRepository = Substitute.For(); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkProviderConfigurationRepository); + _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + + // default stubs: the current user is authenticated and the library ownership policy allows access + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new GetLibraryArtworkProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.LibraryIdCannotBeEmpty]); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError); + await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenConfigurationsExist_ShouldReturnProvidersOrderedByRankWithPluginNames() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + List configurations = + [ + _configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), + _configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) + ]; + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>(configurations)); + List plugins = + [ + _pluginEntityFixture.Create(firstPluginId), + _pluginEntityFixture.Create(secondPluginId) + ]; + _mockPluginRepository.GetAllAsync(Arg.Any()).Returns(plugins); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Count); + Assert.Equal(firstPluginId, result.Value[0].PluginId); + Assert.Equal(plugins[0].Name, result.Value[0].Name); + Assert.Equal(configurations[1].Rank, result.Value[0].Rank); + Assert.Equal(secondPluginId, result.Value[1].PluginId); + Assert.Equal(plugins[1].Name, result.Value[1].Name); + } + + [Fact] + public async Task HandleAsync_WhenPluginIsMissingFromDetectedPlugins_ShouldUseEmptyName() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + Guid unknownPluginId = Guid.NewGuid(); + List configurations = + [ + _configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) + ]; + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>(configurations)); + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([_pluginEntityFixture.Create()])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderResponse response = Assert.Single(result.Value); + Assert.Equal(unknownPluginId, response.PluginId); + Assert.Equal(string.Empty, response.Name); + } + + [Fact] + public async Task HandleAsync_WhenNoConfigurationsExist_ShouldReturnEmptyList() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenGetConfigurationsFails_ShouldReturnError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + Error error = Error.Failure(description: "Failed to get configurations"); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(error); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetPluginsFails_ShouldReturnError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockArtworkProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockPluginRepository.GetAllAsync(Arg.Any()) + .Returns(Error.Failure(description: "Failed to get plugins")); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, Arg.Is(context => context.LibraryId == query.LibraryId), Arg.Any()); + await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result> result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockArtworkProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..f97132cf --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryArtworkProviders/GetLibraryArtworkProvidersQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersQueryValidatorTests +{ + private readonly GetLibraryArtworkProvidersQueryValidator _validator = new(); + private readonly GetLibraryArtworkProvidersQueryFixture _getLibraryArtworkProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + query = query with { LibraryId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetLibraryArtworkProvidersQuery query = _getLibraryArtworkProvidersQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs new file mode 100644 index 00000000..47de5fc4 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs @@ -0,0 +1,137 @@ +#region ========================================================================= USING ===================================================================================== +using EntityFrameworkCore.Testing.NSubstitute; +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.DataAccess.Core.Repositories.Plugins; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.Common.Primitives; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.DataAccess.UnitTests.Core.Repositories.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ArtworkProviderConfigurationRepositoryTests +{ + private readonly LuminaDbContext _mockContext; + private readonly ArtworkProviderConfigurationRepository _sut; + private readonly LibraryArtworkProviderConfigurationEntityFixture _configurationFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ArtworkProviderConfigurationRepositoryTests() + { + _mockContext = Create.MockedDbContextFor(); + _sut = new ArtworkProviderConfigurationRepository(_mockContext); + } + + [Fact] + public async Task GetByLibraryIdAsync_WhenCalled_ShouldReturnOnlyConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity retrievedConfiguration = Assert.Single(result.Value); + Assert.Equal(configurationOfLibrary.PluginId, retrievedConfiguration.PluginId); + } + + [Fact] + public async Task GetByLibraryIdAsync_WhenLibraryHasNoConfigurations_ShouldReturnEmptyList() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + + // Act + Result> result = await _sut.GetByLibraryIdAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationExists_ShouldReturnIt() + { + // Arrange + LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.Add(configuration); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.GetByLibraryAndPluginIdAsync(configuration.LibraryId, configuration.PluginId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(configuration.Id, result.Value!.Id); + } + + [Fact] + public async Task GetByLibraryAndPluginIdAsync_WhenConfigurationDoesNotExist_ShouldReturnNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + + // Act + Result result = await _sut.GetByLibraryAndPluginIdAsync(libraryId, pluginId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value); + } + + [Fact] + public async Task UpsertAsync_WhenConfigurationDoesNotExist_ShouldInsertIt() + { + // Arrange + LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + + // Act + Result result = await _sut.UpsertAsync(configuration, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + Assert.Single(_mockContext.LibraryArtworkProviderConfigurations); + } + + [Fact] + public async Task UpsertAsync_WhenConfigurationExists_ShouldUpdateIt() + { + // Arrange + LibraryArtworkProviderConfigurationEntity configuration = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.Add(configuration); + await _mockContext.SaveChangesAsync(); + + LibraryArtworkProviderConfigurationEntity updatedConfiguration = _configurationFixture.Create(configuration.LibraryId, configuration.PluginId, 5); + updatedConfiguration.IsEnabled = true; + + // Act + Result result = await _sut.UpsertAsync(updatedConfiguration, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity retrievedConfiguration = _mockContext.LibraryArtworkProviderConfigurations.Single(); + Assert.Equal(5, retrievedConfiguration.Rank); + Assert.True(retrievedConfiguration.IsEnabled); + Assert.Equal(configuration.Id, retrievedConfiguration.Id); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs new file mode 100644 index 00000000..ee54d7b9 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BooksLibrary/Artwork/BookArtworkServiceTests.cs @@ -0,0 +1,541 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +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.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Infrastructure.Fixtures.Common.Setup; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class BookArtworkServiceTests +{ + private const long MAX_ARTWORK_SIZE_BYTES = 10 * 1024 * 1024; + + private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IFileTypeService _mockFileTypeService; + private readonly IFileProviderService _mockFileProviderService; + private readonly IDirectoryProviderService _mockDirectoryProviderService; + private readonly IPathService _mockPathService; + private readonly IHttpClientFactory _mockHttpClientFactory; + private readonly IOptions _mockMediaSettingsOptions; + private readonly BookArtworkService _sut; + private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new(); + private readonly PathSegmentFixture _pathSegmentFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new(); + private readonly StubHttpMessageHandler _stubHttpMessageHandler = new(); + + /// + /// Initializes a new instance of the class. + /// + public BookArtworkServiceTests() + { + _mockEnvironmentContext = Substitute.For(); + _mockFileTypeService = Substitute.For(); + _mockFileProviderService = Substitute.For(); + _mockDirectoryProviderService = Substitute.For(); + _mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService); + _mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService); + _mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService); + + _mockPathService = Substitute.For(); + _mockPathService.PathSeparator.Returns('\\'); + + _mockHttpClientFactory = Substitute.For(); + _mockHttpClientFactory.CreateClient().Returns(new HttpClient(_stubHttpMessageHandler)); + + MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books"); + _mockMediaSettingsOptions = Substitute.For>(); + _mockMediaSettingsOptions.Value.Returns(mediaSettings); + + _sut = new BookArtworkService(_mockEnvironmentContext, _mockPathService, _mockHttpClientFactory, _mockMediaSettingsOptions); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkExists_ShouldCopyItAndReturnARelativePath() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId copiedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(copiedFileId)); + + string renamedFilePath = Path.Combine(artworkDirectoryPath, "cover.jpeg"); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(renamedFilePath); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(renamedFilePath[AppContext.BaseDirectory.Length..].Insert(0, "\\"), result.Value); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + _mockFileProviderService.Received(1).RenameFile(Arg.Any(), "cover.jpeg"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenAuthorNameIsMissing_ShouldUseUnknownForTheDirectorySegment() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName: "Unknown", bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName: " ", bookTitle, _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockPathService.Received(1).SanitizeSegment("Unknown"); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkDoesNotExist_ShouldReturnFileNotFound() + { + // Arrange + string sourcePath = Path.Combine(Path.GetTempPath(), $"missing-artwork-{Guid.NewGuid():N}.jpg"); + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(false)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsALink_ShouldReturnInvalidPath() + { + // Arrange + string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-junction-target-{Guid.NewGuid():N}"); + Directory.CreateDirectory(targetDirectory); + string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-junction-link-{Guid.NewGuid():N}"); + if (!TryCreateJunction(linkPath, targetDirectory)) + { + Directory.Delete(targetDirectory, true); + return; // the environment does not support creating reparse points + } + + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + // Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete + if (OperatingSystem.IsWindows()) + Directory.Delete(linkPath, true); + else + File.Delete(linkPath); + Directory.Delete(targetDirectory, true); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: (int)MAX_ARTWORK_SIZE_BYTES + 1); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + await _mockFileTypeService.DidNotReceive().GetImageTypeAsync(Arg.Any(), Arg.Any()); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenLocalArtworkIsNotAnImage_ShouldReturnCoverFileMustBeAnImage() + { + // Arrange + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.None)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.CoverFileMustBeAnImage, result.FirstError); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenArtworkHasNeitherLocalPathNorRemoteUrl_ShouldReturnFileNotFound() + { + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteUrlIsProvided_ShouldDownloadAndStoreTheArtwork() + { + // Arrange + byte[] imageBytes = new byte[1024]; + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, imageBytes); + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path.StartsWith(Path.GetTempPath())), + Arg.Any(), + true); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadReturnsAnErrorStatus_ShouldReturnFileNotFound() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.NotFound, []); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadExceedsMaxSize_ShouldReturnFileTooLarge() + { + // Arrange + _stubHttpMessageHandler.SetResponse(HttpStatusCode.OK, new byte[MAX_ARTWORK_SIZE_BYTES + 1]); + + // Act + Result result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileTooLarge, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenArtworkHasBothLocalPathAndRemoteUrl_ShouldUseTheLocalFileWithoutDeletingIt() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string sourcePath = CreateTempImageFile(smallImageBytes: 1024); + try + { + _mockFileProviderService.FileExists(Arg.Any()).Returns(Result.From(true)); + _mockFileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(ImageType.JPEG)); + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + + FileSystemPathId renamedFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + _mockFileProviderService.CopyFile(Arg.Any(), Arg.Any(), true) + .Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpg")))); + _mockFileProviderService.RenameFile(Arg.Any(), "cover.jpeg") + .Returns(Result.From(renamedFileId)); + + // Act + Result result = await _sut.SaveBookArtworkAsync(libraryId, bookId, libraryName, authorName, bookTitle, _artworkDtoFixture.Create(localPath: sourcePath, remoteUrl: "http://artwork.example/cover.jpg"), CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.True(File.Exists(sourcePath)); + _mockFileProviderService.Received(1).CopyFile( + Arg.Is(pathId => pathId.Path == sourcePath), + Arg.Any(), + true); + } + finally + { + File.Delete(sourcePath); + } + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteDownloadIsCancelled_ShouldRethrowCancellation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + async Task Act() + { + await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(remoteUrl: "http://artwork.example/cover.jpg"), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + [Fact] + public void DeleteBookArtwork_WhenCalled_ShouldDeleteTheCoverFilesInTheBookDirectory() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid bookId = Guid.NewGuid(); + string libraryName = "Test Library"; + string authorName = "Test Author"; + string bookTitle = "Test Book"; + + string artworkDirectoryPath = BuildArtworkDirectoryPath(libraryId, bookId, libraryName, authorName, bookTitle); + MockArtworkDirectoryStubs(artworkDirectoryPath); + FileSystemPathId coverFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "cover.jpeg")); + FileSystemPathId otherFileId = _fileSystemPathIdFixture.Create(Path.Combine(artworkDirectoryPath, "metadata.json")); + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([coverFileId, otherFileId])); + _mockFileProviderService.DeleteFile(Arg.Any()).Returns(Result.Deleted); + + // Act + Result result = _sut.DeleteBookArtwork(libraryId, bookId, libraryName, authorName, bookTitle); + + // Assert + Assert.False(result.IsFailure); + _mockFileProviderService.Received(1).DeleteFile(coverFileId); + _mockFileProviderService.DidNotReceive().DeleteFile(otherFileId); + } + + [Fact] + public void DeleteBookArtwork_WhenCalledWithInvalidNameSegments_ShouldReturnError() + { + // Arrange + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(Errors.FileSystemManagement.InvalidPath); + + // Act + Result result = _sut.DeleteBookArtwork(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title"); + + // Assert + Assert.True(result.IsFailure); + _mockFileProviderService.DidNotReceive().GetFilePaths(Arg.Any(), true); + } + + /// + /// Stubs the path and file system services so that the artwork is stored into the given directory. + /// + /// The file system path of the directory into which the artwork is stored. + private void MockArtworkDirectoryStubs(string artworkDirectoryPath) + { + string mediaRoot = Path.Combine(AppContext.BaseDirectory, "media"); + string booksPath = Path.Combine(mediaRoot, "books"); + _mockPathService.CombinePath(AppContext.BaseDirectory, "media").Returns(Result.From(mediaRoot)); + _mockPathService.CombinePath(mediaRoot, "books").Returns(Result.From(booksPath)); + + _mockPathService.SanitizeSegment(Arg.Any()) + .Returns(callInfo => + { + string name = callInfo.Arg(); + return Result.From(_pathSegmentFixture.Create(name: name, isDirectory: true, isDrive: false)); + }); + + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(Path.Combine(callInfo.ArgAt(0), callInfo.ArgAt(1)))); + + // every directory except the artwork directory itself already exists, so that only the final directory is created + _mockDirectoryProviderService.DirectoryExists(Arg.Any()) + .Returns(callInfo => Result.From(!string.Equals(callInfo.Arg().Path, artworkDirectoryPath, StringComparison.OrdinalIgnoreCase))); + _mockDirectoryProviderService.CreateDirectory(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(_fileSystemPathIdFixture.Create(Path.Combine(callInfo.Arg().Path, callInfo.Arg())))); + + _mockFileProviderService.GetFilePaths(Arg.Any(), true) + .Returns(Result.From>([])); + } + + /// + /// Builds the file system path of the directory that the artwork of the book is stored into. + /// + /// The Id of the media library the book belongs to. + /// The Id of the book. + /// The name of the media library the book belongs to. + /// The name of the author of the book. + /// The title of the book. + /// The expected file system path of the book artwork directory. + private static string BuildArtworkDirectoryPath(Guid libraryId, Guid bookId, string libraryName, string authorName, string bookTitle) + { + return Path.Combine( + AppContext.BaseDirectory, + "media", + "books", + $"{libraryName}-{libraryId}", + authorName, + $"{bookTitle}-{bookId}"); + } + + /// + /// Creates a temporary image file with the given size and returns its path. + /// + /// The size of the temporary image file, in bytes. + /// The file system path of the created temporary image file. + private static string CreateTempImageFile(int smallImageBytes) + { + string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-artwork-source-{Guid.NewGuid():N}.jpg"); + File.WriteAllBytes(sourcePath, new byte[smallImageBytes]); + return sourcePath; + } + + /// + /// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms. + /// + /// The file system path of the link to create. + /// The file system path of the directory the link points to. + /// when the link was created, otherwise. + private static bool TryCreateJunction(string linkPath, string targetDirectory) + { + try + { + System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows() + ? new() + { + FileName = "cmd.exe", + Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"", + CreateNoWindow = true, + UseShellExecute = false + } + : new() + { + FileName = "ln", + CreateNoWindow = true, + UseShellExecute = false + }; + if (!OperatingSystem.IsWindows()) + { + startInfo.ArgumentList.Add("-s"); + startInfo.ArgumentList.Add(targetDirectory); + startInfo.ArgumentList.Add(linkPath); + } + + System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!; + process.WaitForExit(5000); + return process.ExitCode == 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs new file mode 100644 index 00000000..e82c8dac --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreArtworkProviderTests.cs @@ -0,0 +1,252 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Calibre.Fixtures.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Metadata; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreArtworkProviderTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly TestMetadataLookupFixture _testMetadataLookupFixture = new(); + private readonly CalibreArtworkProvider _sut = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Calibre", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(LibraryType.Book, result[0]); + Assert.Equal(LibraryType.EBook, result[1]); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheLocalCoverPath() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: "cover.jpg"); + File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath); + Assert.Null(result.RemoteUrl); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverHrefIsAnAbsolutePath_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: @"C:\Windows\System32\drivers\etc\hosts"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Theory] + [InlineData("../cover.jpg")] // parent directory escape + [InlineData("sub/cover.jpg")] // path with a separator + [InlineData("sub\\cover.jpg")] // path with a backslash separator + public async Task GetArtworkAsync_WhenCoverHrefContainsPathTraversalOrSeparators_ShouldReturnNull(string coverHref) + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenCoverFileIsMissing_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + WriteOpf(bookDirectory, coverHref: "cover.jpg"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenOpfHasNoCoverReference_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), """Test"""); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetArtworkAsync_WhenLookupIsNotABookLookup_ShouldReturnNull() + { + // Arrange + MetadataLookupDto lookup = _testMetadataLookupFixture.Create(); + IArtworkProvider baseProvider = _sut; + + // Act + ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetArtworkAsync_WhenLookupPathIsEmpty_ShouldReturnNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " "); + + // Act + ArtworkDto? result = await _sut.GetArtworkAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + /// + /// Writes an OPF file that references the given cover into the book directory. + /// + /// The file system path of the directory the OPF file is written into. + /// The href of the cover the OPF file references. + private static void WriteOpf(string bookDirectory, string coverHref) + { + string opf = $$"""Test"""; + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf); + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-artwork-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs new file mode 100644 index 00000000..39e1ef2a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibreBookMetadataProviderTests.cs @@ -0,0 +1,174 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Calibre.Core; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreBookMetadataProviderTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly CalibreBookMetadataProvider _sut = new(); + + private const string OPF_DOCUMENT = """Test Book TitleTest Author"""; + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Calibre", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnBookAndEBook() + { + // Act + IReadOnlyList result = _sut.SupportedLibraryTypes; + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal(LibraryType.Book, result[0]); + Assert.Equal(LibraryType.EBook, result[1]); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnFalse() + { + // Act + bool result = _sut.RequiresWebAccess; + + // Assert + Assert.False(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnTheMappedMetadata() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Test Book Title", result!.Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenOpfFileDoesNotExist_ShouldReturnNull() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetMetadataAsync_WhenLookupPathIsEmpty_ShouldReturnNull() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: " "); + + // Act + BookMetadataDto? result = await _sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenOpfFileExistsNextToTheBook_ShouldReturnASingleMetadataCandidate() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), OPF_DOCUMENT); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + BookMetadataDto metadata = Assert.IsType(Assert.Single(result)); + Assert.Equal("Test Book Title", metadata.Title); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + [Fact] + public async Task GetSearchResultsAsync_WhenOpfFileDoesNotExist_ShouldReturnAnEmptyList() + { + // Arrange + string bookDirectory = CreateTempDirectory(); + try + { + string bookPath = Path.Combine(bookDirectory, "book.epub"); + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(path: bookPath); + + // Act + IReadOnlyList result = await _sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + finally + { + Directory.Delete(bookDirectory, true); + } + } + + /// + /// Creates a unique temporary directory for the book. + /// + /// The file system path of the created temporary directory. + private static string CreateTempDirectory() + { + string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-calibre-metadata-{Guid.NewGuid():N}"); + Directory.CreateDirectory(directoryPath); + return directoryPath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs new file mode 100644 index 00000000..b4dfde86 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/CalibrePluginTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Core; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibrePluginTests +{ + private readonly CalibrePlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(CalibrePlugin.s_pluginId, result); + Assert.Equal(new Guid("a1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("Calibre Metadata", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Reads book metadata and covers from the OPF files of a Calibre library.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnEmptySettingsSchema() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Empty(result); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheKeyedMetadataAndArtworkProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)); + Assert.NotNull(serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + Assert.Null(serviceProvider.GetKeyedService(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs new file mode 100644 index 00000000..297ebbad --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Mapping/CalibreMapperTests.cs @@ -0,0 +1,367 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using Lumina.Plugins.Calibre.Core.Mapping; +using Lumina.Plugins.Calibre.Fixtures.Common.Models.DTO.Opf; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CalibreMapperTests +{ + private readonly OpfDocumentDtoFixture _opfDocumentDtoFixture = new(); + private readonly OpfCreatorDtoFixture _opfCreatorDtoFixture = new(); + private readonly OpfContributorDtoFixture _opfContributorDtoFixture = new(); + private readonly OpfIdentifierDtoFixture _opfIdentifierDtoFixture = new(); + + [Fact] + public void Map_WhenDocumentHasAllFields_ShouldMapThemToTheBookMetadataDto() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create( + title: "Test Book Title", + description: "

A test description with markup.

", + publisher: "Test Publisher", + publishDate: new DateTimeOffset(2015, 6, 15, 0, 0, 0, TimeSpan.Zero), + languageCode: "en", + series: "The Series", + seriesIndex: 2.5, + rating: 8, + subjects: ["Science fiction", "Space opera"], + creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", "oth")], + contributors: + [ + _opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"), + _opfContributorDtoFixture.Create("Test Translator", "trl") + ], + identifiers: + [ + _opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"), + _opfIdentifierDtoFixture.Create("goodreads", "123456"), + _opfIdentifierDtoFixture.Create("ASIN", "B00TEST1"), + _opfIdentifierDtoFixture.Create("lccn", "test-lccn"), + _opfIdentifierDtoFixture.Create("oclc", "ocm12345678"), + _opfIdentifierDtoFixture.Create("openlibrary", "OL100M"), + _opfIdentifierDtoFixture.Create("google", "google-id") + ]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("Test Book Title", result.Title); + Assert.Equal("A test description with markup .", result.Description); + Assert.Equal("Test Publisher", result.Publisher); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(2015, 6, 15), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(2015, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal("The Series", result.Series!.Title); + Assert.Equal(2.5f, result.VolumeNumber); + Assert.Equal("B00TEST1", result.ASIN); + Assert.Equal("123456", result.GoodreadsId); + Assert.Equal("test-lccn", result.LCCN); + Assert.Equal("ocm12345678", result.OCLCNumber); + Assert.Equal("OL100M", result.OpenLibraryId); + Assert.Equal("google-id", result.GoogleBooksId); + Assert.Null(result.Genres); + Assert.Null(result.CoverImagePath); + } + + [Fact] + public void Map_WhenDescriptionContainsHtmlEntities_ShouldDecodeAndStripThem() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: "A & B <tag>description</tag> with multiple spaces"); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("A & B description with multiple spaces", result.Description); + } + + [Fact] + public void Map_WhenDescriptionIsEmpty_ShouldReturnNullDescription() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(description: " "); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Description); + } + + [Theory] + [InlineData(0)] // a zero series index is not a meaningful volume number + public void Map_WhenSeriesIndexIsZero_ShouldReturnNullVolumeNumber(double seriesIndex) + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(seriesIndex: seriesIndex); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.VolumeNumber); + } + + [Fact] + public void Map_WhenSeriesIndexIsNull_ShouldReturnNullVolumeNumber() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.VolumeNumber); + } + + [Fact] + public void Map_WhenSeriesIsNull_ShouldReturnNullSeries() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Series); + } + + [Fact] + public void Map_WhenRatingIsPresent_ShouldMapItToACalibreRatingWithMaxValueTen() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(rating: 8); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + BookRatingDto rating = Assert.Single(result.Ratings!); + Assert.Equal(8m, rating.Value); + Assert.Equal(10m, rating.MaxValue); + Assert.Equal(BookRatingSource.Calibre, rating.Source); + Assert.Null(rating.VoteCount); + } + + [Fact] + public void Map_WhenRatingIsMissing_ShouldReturnNullRatings() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Ratings); + } + + [Fact] + public void Map_WhenSubjectsArePresent_ShouldMapThemToTagsWithNullGenres() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(subjects: ["Science fiction", "Space opera"]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Genres); + Assert.Equal(2, result.Tags!.Count); + Assert.Equal("Science fiction", result.Tags[0].Name); + Assert.Equal("Space opera", result.Tags[1].Name); + } + + [Fact] + public void Map_WhenCreatorsAndContributorsArePresent_ShouldMapRolesAndCategories() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create( + creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Co Author", null)], + contributors: + [ + _opfContributorDtoFixture.Create("Test Translator", "trl"), + _opfContributorDtoFixture.Create("Test Illustrator", "ill"), + _opfContributorDtoFixture.Create("calibre (3.48.0) [https://calibre-ebook.com]", "bkp"), + _opfContributorDtoFixture.Create("Misc Contributor", null) + ]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal(6, result.Contributors!.Count); + + MediaContributorDto author = result.Contributors[0]; + Assert.Equal("Test Author", author.Name!.DisplayName); + Assert.Equal("Author", author.Role!.Name); + Assert.Equal("Writing", author.Role.Category); + + MediaContributorDto coAuthor = result.Contributors[1]; + Assert.Equal("Co Author", coAuthor.Name!.DisplayName); + Assert.Equal("Author", coAuthor.Role!.Name); + Assert.Equal("Writing", coAuthor.Role.Category); + + MediaContributorDto translator = result.Contributors[2]; + Assert.Equal("Test Translator", translator.Name!.DisplayName); + Assert.Equal("trl", translator.Role!.Name); + Assert.Equal("Translation", translator.Role.Category); + + MediaContributorDto illustrator = result.Contributors[3]; + Assert.Equal("Test Illustrator", illustrator.Name!.DisplayName); + Assert.Equal("ill", illustrator.Role!.Name); + Assert.Equal("Art", illustrator.Role.Category); + + MediaContributorDto production = result.Contributors[4]; + Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", production.Name!.DisplayName); + Assert.Equal("bkp", production.Role!.Name); + Assert.Equal("Production", production.Role.Category); + + MediaContributorDto misc = result.Contributors[5]; + Assert.Equal("Misc Contributor", misc.Name!.DisplayName); + Assert.Equal("Contributor", misc.Role!.Name); + Assert.Equal("Other", misc.Role.Category); + } + + [Fact] + public void Map_WhenCreatorsAreDuplicatedWithTheSameRole_ShouldDeDuplicateThem() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(creators: [_opfCreatorDtoFixture.Create("Test Author", "aut"), _opfCreatorDtoFixture.Create("Test Author", "aut")]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + MediaContributorDto author = Assert.Single(result.Contributors!); + Assert.Equal("Test Author", author.Name!.DisplayName); + } + + [Fact] + public void Map_WhenIsbnIdentifiersArePresent_ShouldNormalizeAndMapThem() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers: + [ + _opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"), + _opfIdentifierDtoFixture.Create("ISBN", "0306406152"), + _opfIdentifierDtoFixture.Create("ISBN", "978-0-306-40615-7"), + _opfIdentifierDtoFixture.Create("ISBN", "not-an-isbn") + ]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal(2, result.Isbns!.Count); + Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157" && isbn.Format == IsbnFormat.Isbn13); + Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152" && isbn.Format == IsbnFormat.Isbn10); + } + + [Fact] + public void Map_WhenNoIdentifiersArePresent_ShouldReturnEmptyIsbnList() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Empty(result.Isbns!); + } + + [Fact] + public void Map_WhenAmazonIdentifiersArePresent_ShouldMapAsin() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(identifiers: [_opfIdentifierDtoFixture.Create("amazon", "B00TEST1")]); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("B00TEST1", result.ASIN); + } + + [Fact] + public void Map_WhenLanguageCodeIsUnknown_ShouldReturnTheRawCode() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: "zz"); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Equal("zz", result.Language!.LanguageCode); + Assert.Equal("zz", result.Language.LanguageName); + } + + [Fact] + public void Map_WhenLanguageCodeIsEmpty_ShouldReturnNullLanguage() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(languageCode: " "); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Language); + } + + [Fact] + public void Map_WhenDocumentHasNoMetadata_ShouldReturnEmptyDto() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Description); + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.Publisher); + Assert.Null(result.Series); + Assert.Null(result.VolumeNumber); + Assert.Null(result.Ratings); + } + + [Fact] + public void Map_WhenPublishDateIsMissing_ShouldReturnEmptyReleaseInfo() + { + // Arrange + OpfDocumentDto document = _opfDocumentDtoFixture.Create(publishDate: null); + + // Act + BookMetadataDto result = CalibreMapper.Map(document); + + // Assert + // a book without a publication date must still be enrichable, so the release info is present with empty fields + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.ReleaseInfo!.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs new file mode 100644 index 00000000..b5435fcb --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Core/Opf/OpfReaderTests.cs @@ -0,0 +1,212 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Calibre.Common.Models.DTO.Opf; +using Lumina.Plugins.Calibre.Core.Opf; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +#endregion + +namespace Lumina.Plugins.Calibre.UnitTests.Core.Opf; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class OpfReaderTests +{ + [Fact] + public void Read_WhenOpfFileContainsAllSupportedFields_ShouldParseThemAll() + { + // Arrange + string opfFilePath = CreateOpfFile("""Test Book TitleTest AuthorSecond Creatorcalibre (3.48.0) [https://calibre-ebook.com]Test Translator<p>A test description with <b>markup</b>.</p>Test Publisher2015-06-15en978-0-306-40615-7123456B00TEST1test-lccnocm12345678OL100Mgoogle-idScience fictionSpace opera"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Equal("Test Book Title", result.Title); + Assert.Equal("

A test description with markup.

", result.Description); + Assert.Equal("Test Publisher", result.Publisher); + Assert.Equal(2015, result.PublishDate!.Value.Year); + Assert.Equal(6, result.PublishDate.Value.Month); + Assert.Equal(15, result.PublishDate.Value.Day); + Assert.Equal("en", result.LanguageCode); + Assert.Equal("The Series", result.Series); + Assert.Equal(2.5, result.SeriesIndex); + Assert.Equal(8, result.Rating); + Assert.Equal("cover.jpg", result.CoverHref); + Assert.Equal(2, result.Creators.Count); + Assert.Equal("Test Author", result.Creators[0].Name); + Assert.Equal("aut", result.Creators[0].Role); + Assert.Equal(2, result.Contributors.Count); + Assert.Equal("calibre (3.48.0) [https://calibre-ebook.com]", result.Contributors[0].Name); + Assert.Equal("bkp", result.Contributors[0].Role); + Assert.Equal(7, result.Identifiers.Count); + Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ISBN" && identifier.Value == "978-0-306-40615-7"); + Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "goodreads" && identifier.Value == "123456"); + Assert.Contains(result.Identifiers, identifier => identifier.Scheme == "ASIN" && identifier.Value == "B00TEST1"); + Assert.Equal(2, result.Subjects.Count); + Assert.Equal("Science fiction", result.Subjects[0]); + Assert.Equal("Space opera", result.Subjects[1]); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileDoesNotExist_ShouldReturnEmptyDocument() + { + // Act + OpfDocumentDto result = OpfReader.Read(Path.Combine(Path.GetTempPath(), $"missing-{Guid.NewGuid():N}.opf")); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + Assert.Empty(result.Creators); + Assert.Empty(result.Subjects); + } + + [Fact] + public void Read_WhenMetadataContainsWhitespaceOnlyValues_ShouldSkipThem() + { + // Arrange + string opfFilePath = CreateOpfFile(""" """); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Creators); + Assert.Empty(result.Subjects); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenMetadataElementIsMissing_ShouldReturnEmptyDocument() + { + // Arrange + string opfFilePath = CreateOpfFile(""""""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileDeclaresADoctypeWithEntities_ShouldNotExpandThem() + { + // Arrange + // the DTD is prohibited, so the document must not be parsed and the entity must not be expanded into the title + string opfFilePath = CreateOpfFile("""]>&xxe;"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandThem() + { + // Arrange + string opfFilePath = CreateOpfFile("""]>&lol3;"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileIsOversized_ShouldReturnEmptyDocument() + { + // Arrange + string opfFilePath = Path.Combine(Path.GetTempPath(), $"oversized-{Guid.NewGuid():N}.opf"); + string oversizedContent = $"""{new string('a', (5 * 1024 * 1024) + 100)}"""; + File.WriteAllText(opfFilePath, oversizedContent); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + } + finally + { + File.Delete(opfFilePath); + } + } + + [Fact] + public void Read_WhenOpfFileIsMalformedXml_ShouldReturnEmptyDocument() + { + // Arrange + string opfFilePath = CreateOpfFile("""Unclosed"""); + + try + { + // Act + OpfDocumentDto result = OpfReader.Read(opfFilePath); + + // Assert + Assert.Null(result.Title); + Assert.Empty(result.Identifiers); + } + finally + { + File.Delete(opfFilePath); + } + } + + /// + /// Creates a temporary OPF file with the given content and returns its path. + /// + /// The content of the OPF file to create. + /// The file system path of the created OPF file. + private static string CreateOpfFile(string content) + { + string opfFilePath = Path.Combine(Path.GetTempPath(), $"opf-{Guid.NewGuid():N}.opf"); + File.WriteAllText(opfFilePath, content); + return opfFilePath; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj new file mode 100644 index 00000000..4309ec26 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Calibre.UnitTests/Lumina.Plugins.Calibre.UnitTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs new file mode 100644 index 00000000..2172609c --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.Contracts.UnitTests/Core/Metadata/IArtworkProviderGenericTests.cs @@ -0,0 +1,105 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.Contracts.UnitTests.Core.Metadata; + +/// +/// Contains unit tests for the interface. +/// +[ExcludeFromCodeCoverage] +public class IArtworkProviderGenericTests +{ + private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly OtherMetadataLookupDtoFixture _otherMetadataLookupDtoFixture = new(); + + [Fact] + public async Task GetArtworkAsync_WhenCalledThroughBaseInterface_ShouldForwardToTypedImplementation() + { + // Arrange + BookMetadataLookupDto lookup = _bookMetadataLookupDtoFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + ArtworkDto expectedArtwork = _artworkDtoFixture.Create(); + TestBookArtworkProvider provider = new(expectedArtwork); + IArtworkProvider baseProvider = provider; + + // Act + ArtworkDto? result = await baseProvider.GetArtworkAsync(lookup, cancellationToken); + + // Assert + Assert.Equal(expectedArtwork, result); + Assert.Same(lookup, provider.ReceivedLookup); + Assert.Equal(cancellationToken, provider.ReceivedCancellationToken); + } + + [Fact] + public async Task GetArtworkAsync_WhenLookupIsOfAnotherRuntimeType_ShouldReturnNull() + { + // Arrange + MetadataLookupDto otherLookup = _otherMetadataLookupDtoFixture.Create(); + TestBookArtworkProvider provider = new(_artworkDtoFixture.Create()); + IArtworkProvider baseProvider = provider; + + // Act + ArtworkDto? result = await baseProvider.GetArtworkAsync(otherLookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Null(provider.ReceivedLookup); + } + + /// + /// Test double for the typed artwork provider interface that records the forwarded arguments. + /// + [ExcludeFromCodeCoverage] + private sealed class TestBookArtworkProvider : IArtworkProvider + { + private readonly ArtworkDto _artwork; + + /// + /// Gets the lookup that was forwarded to the typed implementation. + /// + public BookMetadataLookupDto? ReceivedLookup { get; private set; } + + /// + /// Gets the cancellation token that was forwarded to the typed implementation. + /// + public CancellationToken ReceivedCancellationToken { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The artwork returned by the typed implementation. + public TestBookArtworkProvider(ArtworkDto artwork) + { + _artwork = artwork; + } + + /// + public string Name => "Test Provider"; + + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Book]; + + /// + public bool RequiresWebAccess => false; + + /// + public Task GetArtworkAsync(BookMetadataLookupDto lookup, CancellationToken cancellationToken) + { + ReceivedLookup = lookup; + ReceivedCancellationToken = cancellationToken; + return Task.FromResult(_artwork); + } + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..88583a22 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryArtworkProviders/GetLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Queries.GetLibraryArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Fixtures.Core.Responses.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryArtworkProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.GetLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryArtworkProvidersEndpointTests +{ + private readonly IQueryHandler>> _mockHandler; + private readonly GetLibraryArtworkProvidersEndpoint _sut; + private readonly GetLibraryArtworkProvidersRequestFixture _getLibraryArtworkProvidersRequestFixture = new(); + private readonly LibraryArtworkProviderResponseFixture _libraryArtworkProviderResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetLibraryArtworkProvidersEndpointTests() + { + _mockHandler = Substitute.For>>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithLibraryArtworkProviderResponses() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + IReadOnlyList expectedResponses = + [ + _libraryArtworkProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1), + _libraryArtworkProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2) + ]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponses)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok> okResult = Assert.IsType>>(result); + Assert.Equal(expectedResponses, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("Library.NotFound", "The requested library was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("Library.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The requested library was not found.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetLibraryArtworkProvidersQueryToSender() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => query.LibraryId == request.LibraryId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + GetLibraryArtworkProvidersRequest request = _getLibraryArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From>([]); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs new file mode 100644 index 00000000..272e253b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/ReorderLibraryArtworkProviders/ReorderLibraryArtworkProvidersEndpointTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.ReorderLibraryArtworkProviders; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryArtworkProvidersEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly ReorderLibraryArtworkProvidersEndpoint _sut; + private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ReorderLibraryArtworkProvidersEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Success, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendReorderLibraryArtworkProvidersCommandToSender() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.PluginIds.SequenceEqual(request.PluginIds)), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs new file mode 100644 index 00000000..4668185b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/SetLibraryArtworkProviderEnabled/SetLibraryArtworkProviderEnabledEndpointTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Plugins.Commands.SetLibraryArtworkProviderEnabled; +using Lumina.Contracts.Fixtures.Core.Requests.Plugins; +using Lumina.Contracts.Requests.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryArtworkProviderEnabledEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly SetLibraryArtworkProviderEnabledEndpoint _sut; + private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public SetLibraryArtworkProviderEnabledEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithSuccess() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Success, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.NotFound("LibraryArtworkProviderConfiguration.NotFound", "The artwork provider configuration was not found."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemDetails = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode); + Assert.Equal("application/problem+json", problemDetails.ContentType); + Assert.IsType(problemDetails.ProblemDetails); + + Assert.Equal("LibraryArtworkProviderConfiguration.NotFound", problemDetails.ProblemDetails.Title); + Assert.Equal("The artwork provider configuration was not found.", problemDetails.ProblemDetails.Detail); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.ProblemDetails.Status); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.ProblemDetails.Type); + Assert.NotNull(problemDetails.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendSetLibraryArtworkProviderEnabledCommandToSender() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Success)); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == request.LibraryId && + command.PluginId == request.PluginId && + command.IsEnabled == request.IsEnabled), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Success); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +}