From 66871ccf621ed2aa20c25652bf74f4d2675ade1d Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 24 Aug 2026 14:18:40 -0700 Subject: [PATCH] Adds metadata aggregation to the media library enrichment job --- .../Common/DTO/Filtering/LibraryFilterDto.cs | 2 +- .../MediaLibrary/Management/LibraryEntity.cs | 2 +- .../UsersManagement/UserSettingsEntity.cs | 7 +- .../Common/DataAccess/UoW/IUnitOfWork.cs | 10 + .../DTO/Configuration/MediaSettingsDto.cs | 5 + .../AddMediaLibraryRequestMapping.cs | 5 +- .../Management/LibraryEntityMapping.cs | 10 +- .../MediaLibrary/Management/LibraryMapping.cs | 8 +- .../Management/UpdateLibraryRequestMapping.cs | 3 +- .../Users/UpdateUserSettingsRequestMapping.cs | 6 +- .../Users/UserSettingsEntityMapping.cs | 14 +- .../Users/UserSettingsMapping.cs | 11 +- .../Commands/AddLibrary/AddLibraryCommand.cs | 5 +- .../AddLibrary/AddLibraryCommandHandler.cs | 11 +- .../UpdateLibrary/UpdateLibraryCommand.cs | 4 +- .../UpdateLibraryCommandHandler.cs | 13 +- .../LibraryScanQueuedDomainEventHandler.cs | 2 +- ...rLibraryMetadataProvidersCommandHandler.cs | 27 +- ...ibraryMetadataProvidersCommandValidator.cs | 3 + ...ryMetadataProviderEnabledCommandHandler.cs | 27 +- ...MetadataProviderEnabledCommandValidator.cs | 5 + .../UpdatePluginSettingsCommandValidator.cs | 3 + ...GetLibraryMetadataProvidersQueryHandler.cs | 35 +- ...tLibraryMetadataProvidersQueryValidator.cs | 26 ++ .../GetPluginSettingsQueryHandler.cs | 13 +- .../GetPluginSettingsQueryValidator.cs | 26 ++ .../UpdateUserSettingsCommand.cs | 8 +- .../UpdateUserSettingsCommandHandler.cs | 13 +- .../Management/AddLibraryRequest.cs | 4 +- .../Management/UpdateLibraryRequest.cs | 6 +- .../Settings/UpdateUserSettingsRequest.cs | 8 +- .../Management/LibraryResponse.cs | 7 +- .../Settings/UserSettingsResponse.cs | 8 +- .../Configuration/LibraryConfiguration.cs | 2 +- .../UserSettingsConfiguration.cs | 7 +- .../Core/Repositories/Books/BookRepository.cs | 18 +- .../BookAlphaFilterSpecification.cs | 10 +- .../Core/UoW/LuminaDbContext.cs | 1 + src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs | 21 + .../FileSystemStructureSeedService.cs | 43 +- .../LibraryAggregate/Library.cs | 20 +- .../Services/IMediaLibraryScanningService.cs | 3 +- .../Services/MediaLibraryScanningService.cs | 9 +- .../Services/Scanners/IMediaTypeScanner.cs | 3 +- .../UserSettingsAggregate/UserSettings.cs | 58 ++- .../Common/Errors/Errors.Configuration.cs | 1 + .../Validators/MediaSettingsDtoValidator.cs | 4 + .../MediaLibraryScanMetadataEnrichmentJob.cs | 335 +++++++++++--- .../Jobs/Common/MetadataAggregator.cs | 127 +++++ .../appsettings.shared.json | 3 +- .../AddLibrary/AddLibraryEndpointSummary.cs | 8 +- .../GetEnabledLibrariesEndpointSummary.cs | 4 +- .../GetLibrariesEndpointSummary.cs | 4 +- .../GetLibrary/GetLibraryEndpointSummary.cs | 4 +- .../UpdateLibraryEndpointSummary.cs | 8 +- .../GetUserSettingsEndpointSummary.cs | 5 +- .../UpdateUserSettingsEndpointSummary.cs | 7 +- .../Common/DTO/Libraries/LibraryDto.cs | 3 +- .../DTO/UsersManagement/UserSettingsDto.cs | 7 +- .../SaveLibrary/SaveLibraryEndpointSummary.cs | 3 +- .../UpdateUserSettingsEndpointSummary.cs | 3 +- .../Views/Library/Management/Item.ar-SA.resx | 6 +- .../Views/Library/Management/Item.de-DE.resx | 4 +- .../Views/Library/Management/Item.en-US.resx | 4 +- .../Views/Library/Management/Item.es-ES.resx | 4 +- .../Views/Library/Management/Item.fr-FR.resx | 4 +- .../Views/Library/Management/Item.it-IT.resx | 4 +- .../Views/Library/Management/Item.ja-JP.resx | 4 +- .../Views/Library/Management/Item.resx | 4 +- .../Views/Library/Management/Item.ro-RO.resx | 4 +- .../Views/Library/Management/Item.uk-UA.resx | 6 +- .../Views/Library/Management/Item.zh-CN.resx | 4 +- .../Resources/Views/Tools/Settings.ar-SA.resx | 6 +- .../Resources/Views/Tools/Settings.de-DE.resx | 4 +- .../Resources/Views/Tools/Settings.en-US.resx | 4 +- .../Resources/Views/Tools/Settings.es-ES.resx | 4 +- .../Resources/Views/Tools/Settings.fr-FR.resx | 4 +- .../Resources/Views/Tools/Settings.it-IT.resx | 4 +- .../Resources/Views/Tools/Settings.ja-JP.resx | 4 +- .../Core/Resources/Views/Tools/Settings.resx | 4 +- .../Resources/Views/Tools/Settings.ro-RO.resx | 4 +- .../Resources/Views/Tools/Settings.uk-UA.resx | 6 +- .../Resources/Views/Tools/Settings.zh-CN.resx | 4 +- .../Core/Views/Library/Management/Item.cshtml | 10 +- .../Core/Views/Tools/Settings.cshtml | 17 +- .../LibraryContentLocationEntityFixture.cs | 42 ++ .../Management/LibraryEntityFixture.cs | 6 +- ...adataProviderConfigurationEntityFixture.cs | 9 +- .../Entities/Plugins/PluginEntityFixture.cs | 17 +- .../UserSettingsEntityFixture.cs | 13 +- .../Configuration/MediaSettingsDtoFixture.cs | 48 ++ .../AddLibrary/AddLibraryCommandFixture.cs | 7 +- .../UpdateLibraryCommandFixture.cs | 6 +- .../UpdateUserSettingsCommandFixture.cs | 12 +- .../Management/AddLibraryRequestFixture.cs | 7 +- .../Management/UpdateLibraryRequestFixture.cs | 6 +- .../UpdateUserSettingsRequestFixture.cs | 52 +++ .../Management/LibraryResponseFixture.cs | 6 +- .../LibraryMetadataProviderResponseFixture.cs | 50 ++ .../Settings/UserSettingsResponseFixture.cs | 56 +++ .../LibraryAggregate/LibraryFixture.cs | 8 +- .../UserSettingsFixture.cs | 13 +- .../Common/DTO/Libraries/LibraryDtoFixture.cs | 13 +- .../DTO/Libraries/ScanLibraryDtoFixture.cs | 43 ++ .../LibraryMetadataProviderDtoFixture.cs | 52 +++ .../PluginSettingDescriptorDtoFixture.cs | 55 +++ .../DTO/Plugins/PluginSettingsDtoFixture.cs | 55 +++ .../UsersManagement/UserSettingsDtoFixture.cs | 23 +- ...rLibraryMetadataProvidersRequestFixture.cs | 46 ++ ...ryMetadataProviderEnabledRequestFixture.cs | 49 ++ .../UpdatePluginSettingsRequestFixture.cs | 9 +- ...etLibraryMetadataProvidersEndpointTests.cs | 54 +-- .../GetPluginSettingsEndpointTests.cs | 33 +- ...erLibraryMetadataProvidersEndpointTests.cs | 51 +- ...aryMetadataProviderEnabledEndpointTests.cs | 67 ++- .../UpdatePluginSettingsEndpointTests.cs | 46 +- .../GetUserSettingsEndpointTests.cs | 21 +- .../UpdateUserSettingsEndpointTests.cs | 37 +- ...a.Presentation.Api.IntegrationTests.csproj | 1 + .../GetUserSettingsEndpointTests.cs | 58 +++ .../Settings/SettingsViewEndpointTests.cs | 46 ++ .../UpdateUserSettingsEndpointTests.cs | 76 +++ ...etLibraryMetadataProvidersEndpointTests.cs | 40 +- .../GetPluginSettingsEndpointTests.cs | 32 +- ...erLibraryMetadataProvidersEndpointTests.cs | 50 +- ...aryMetadataProviderEnabledEndpointTests.cs | 54 +-- .../UpdatePluginSettingsEndpointTests.cs | 44 +- .../GetUserSettingsEndpointTests.cs | 23 +- .../UpdateUserSettingsEndpointTests.cs | 58 ++- .../GetUserSettingsEndpointTests.cs | 46 ++ .../Settings/SettingsViewEndpointTests.cs | 41 ++ .../UpdateUserSettingsEndpointTests.cs | 76 +++ .../AddMediaLibraryRequestMappingTests.cs | 87 ++-- .../Management/LibraryEntityMappingTests.cs | 107 ++--- .../Management/LibraryMappingTests.cs | 9 +- .../UpdateUserSettingsRequestMappingTests.cs | 13 +- .../Users/UserSettingsEntityMappingTests.cs | 4 +- .../Users/UserSettingsMappingTests.cs | 4 +- ...aryMetadataProvidersCommandHandlerTests.cs | 69 ++- ...adataProviderEnabledCommandHandlerTests.cs | 88 +++- ...UpdatePluginSettingsCommandHandlerTests.cs | 8 +- ...braryMetadataProvidersQueryHandlerTests.cs | 75 ++- ...aryMetadataProvidersQueryValidatorTests.cs | 49 ++ .../GetPluginSettingsQueryHandlerTests.cs | 30 +- .../GetPluginSettingsQueryValidatorTests.cs | 49 ++ .../UpdateUserSettingsCommandHandlerTests.cs | 4 +- .../GetUserSettingsQueryHandlerTests.cs | 14 +- .../Lumina.Application.UnitTests.csproj | 1 + .../Management/AddLibraryRequestTests.cs | 46 +- .../Management/UpdateLibraryRequestTests.cs | 54 +-- .../UpdateUserSettingsRequestTests.cs | 23 +- .../Management/LibraryResponseTests.cs | 4 +- .../Settings/UserSettingsResponseTests.cs | 25 +- .../LibraryConfigurationTests.cs | 2 +- .../UserSettingsConfigurationTests.cs | 2 +- .../Repositories/Books/BookRepositoryTests.cs | 62 +-- .../Core/UoW/LuminaDbContextTests.cs | 21 +- .../Core/UoW/UnitOfWorkTests.cs | 26 +- .../LibraryAggregate/LibraryTests.cs | 12 +- .../UserSettingsTests.cs | 21 +- ...iaLibraryScanMetadataEnrichmentJobTests.cs | 435 ++++++++++++++++++ .../Jobs/Common/MetadataAggregatorTests.cs | 332 +++++++++++++ .../Lumina.Infrastructure.UnitTests.csproj | 1 + ...etLibraryMetadataProvidersEndpointTests.cs | 6 +- .../GetPluginSettingsEndpointTests.cs | 14 +- .../GetUserSettingsEndpointTests.cs | 8 +- .../UpdateUserSettingsEndpointTests.cs | 12 +- .../UpdateUserSettingsEndpointTests.cs | 10 +- 168 files changed, 3503 insertions(+), 1062 deletions(-) create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs create mode 100644 src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs create mode 100644 src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs create mode 100644 tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs create mode 100644 tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs create mode 100644 tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs create mode 100644 tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs create mode 100644 tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs create mode 100644 tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs diff --git a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs index 6b77d3dc..c13e4250 100644 --- a/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs +++ b/src/Lumina.Application/Common/DTO/Filtering/LibraryFilterDto.cs @@ -25,5 +25,5 @@ public record LibraryFilterDto : BaseFilterDto /// /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; init; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; init; } } diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs index ef17ab05..a7c07954 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntity.cs @@ -63,7 +63,7 @@ public class LibraryEntity : IStorageEntity, IAuditableEntity /// /// Gets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMetadataFromWeb { get; init; } + public bool CanDownloadMetadataFromWeb { get; init; } /// /// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not. diff --git a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs index 524544bb..5e8de0bf 100644 --- a/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs +++ b/src/Lumina.Application/Common/DataAccess/Entities/UsersManagement/UserSettingsEntity.cs @@ -35,13 +35,18 @@ public class UserSettingsEntity : IStorageEntity, IAuditableEntity /// /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; } /// /// Gets or sets whether the theme data served to this user is cached, or not. /// public bool IsThemeCachingEnabled { get; set; } = true; + /// + /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// + public bool ShouldAggregateMetadataWhenMissing { get; set; } + /// /// Gets or sets the time and date when the entity was added. /// diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs index dc49b1f4..17a48b83 100644 --- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs +++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs @@ -71,6 +71,11 @@ public interface IUnitOfWork /// ILibraryMetadataProviderConfigurationRepository LibraryMetadataProviderConfigurationRepository { get; } + /// + /// Gets the library artwork provider configuration repository. + /// + IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository { get; } + /// /// Gets the plugin repository. /// @@ -97,6 +102,11 @@ public interface IUnitOfWork /// Cancellation token that can be used to stop the execution. Task SaveChangesAsync(CancellationToken cancellationToken); + /// + /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. + /// + void ClearTrackedEntities(); + /// /// Begins a new database transaction. /// diff --git a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs index f68feee4..c77c25f4 100644 --- a/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs +++ b/src/Lumina.Application/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDto.cs @@ -21,4 +21,9 @@ public class MediaSettingsDto /// Gets or sets the directory where media library files are stored. /// public required string LibrariesDirectory { get; init; } + + /// + /// Gets or sets the directory where the media item files are stored. + /// + public required string BooksDirectory { get; init; } } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs index 8e74f24c..f524961e 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMapping.cs @@ -1,9 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; -using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook; using Lumina.Contracts.Requests.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -27,7 +24,7 @@ public static class AddMediaLibraryRequestMapping request.CoverImage, request.IsEnabled, request.IsLocked, - request.DownloadMetadataFromWeb, + request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, request.ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs index 1484cf34..fe652e54 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; @@ -29,11 +29,11 @@ public static class LibraryEntityMapping repositoryEntity.UserId, repositoryEntity.Title, repositoryEntity.LibraryType, - repositoryEntity.ContentLocations.Select(location => location.Path).ToList(), + [.. repositoryEntity.ContentLocations.Select(location => location.Path)], repositoryEntity.CoverImage, repositoryEntity.IsEnabled, repositoryEntity.IsLocked, - repositoryEntity.DownloadMetadataFromWeb, + repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, repositoryEntity.CreatedOnUtc, @@ -59,10 +59,10 @@ public static class LibraryEntityMapping repositoryEntity.CoverImage, repositoryEntity.IsEnabled, repositoryEntity.IsLocked, - repositoryEntity.DownloadMetadataFromWeb, + repositoryEntity.CanDownloadMetadataFromWeb, repositoryEntity.ShouldSaveMetadataInMediaDirectories, repositoryEntity.ShouldSkipUnchangedDirectoriesDuringScan, - repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id)).ToList() + [.. repositoryEntity.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))] ); } diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs index dac14f8a..90f36343 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryMapping.cs @@ -25,14 +25,14 @@ public static class LibraryMapping Title = domainEntity.Title, LibraryType = domainEntity.LibraryType, UserId = domainEntity.UserId.Value, - ContentLocations = domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path }).ToList(), + ContentLocations = [.. domainEntity.ContentLocations.Select(path => new LibraryContentLocationEntity() { Path = path.Path })], CoverImage = domainEntity.CoverImage, IsEnabled = domainEntity.IsEnabled, IsLocked = domainEntity.IsLocked, - DownloadMetadataFromWeb = domainEntity.DownloadMetadataFromWeb, + CanDownloadMetadataFromWeb = domainEntity.CanDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = domainEntity.ShouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = domainEntity.ShouldSkipUnchangedDirectoriesDuringScan, - LibraryScans = domainEntity.ScanIds.Select(scanId => new LibraryScanEntity() + LibraryScans = [.. domainEntity.ScanIds.Select(scanId => new LibraryScanEntity() { Id = scanId.Value, LibraryId = domainEntity.Id.Value, @@ -43,7 +43,7 @@ public static class LibraryMapping CreatedBy = default, CreatedOnUtc = default, UpdatedBy = default, - }).ToList(), + })], CreatedOnUtc = domainEntity.CreatedOnUtc, CreatedBy = Guid.Empty, UpdatedOnUtc = domainEntity.UpdatedOnUtc.HasValue ? domainEntity.UpdatedOnUtc : null, diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs index c0dfc446..374f9e15 100644 --- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/UpdateLibraryRequestMapping.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; #endregion namespace Lumina.Application.Common.Mapping.MediaLibrary.Management; @@ -27,7 +26,7 @@ public static class UpdateLibraryRequestMapping request.CoverImage, request.IsEnabled, request.IsLocked, - request.DownloadMetadataFromWeb, + request.CanDownloadMetadataFromWeb, request.ShouldSaveMetadataInMediaDirectories, request.ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs index 23504a3c..aff25a7d 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMapping.cs @@ -20,7 +20,9 @@ public static class UpdateUserSettingsRequestMapping return new UpdateUserSettingsCommand( request.IsPaginationEnabled, request.ItemsPerPage, - request.IgnoreThePrefixForAlphaPicker, - request.IsThemeCachingEnabled); + request.ShouldIgnoreThePrefixForAlphaPicker, + request.IsThemeCachingEnabled, + request.ShouldAggregateMetadataWhenMissing + ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs index b96f8fdb..b53990fd 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsEntityMapping.cs @@ -1,7 +1,7 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; @@ -28,8 +28,10 @@ public static class UserSettingsEntityMapping UserId.Create(repositoryEntity.UserId), repositoryEntity.IsPaginationEnabled, repositoryEntity.ItemsPerPage, - repositoryEntity.IgnoreThePrefixForAlphaPicker, - repositoryEntity.IsThemeCachingEnabled); + repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker, + repositoryEntity.IsThemeCachingEnabled, + repositoryEntity.ShouldAggregateMetadataWhenMissing + ); } /// @@ -43,7 +45,9 @@ public static class UserSettingsEntityMapping repositoryEntity.UserId, repositoryEntity.IsPaginationEnabled, repositoryEntity.ItemsPerPage, - repositoryEntity.IgnoreThePrefixForAlphaPicker, - repositoryEntity.IsThemeCachingEnabled); + repositoryEntity.ShouldIgnoreThePrefixForAlphaPicker, + repositoryEntity.IsThemeCachingEnabled, + repositoryEntity.ShouldAggregateMetadataWhenMissing + ); } } diff --git a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs index 7a22ee1e..cde37e56 100644 --- a/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs +++ b/src/Lumina.Application/Common/Mapping/UsersManagement/Users/UserSettingsMapping.cs @@ -24,8 +24,9 @@ public static class UserSettingsMapping UserId = domainEntity.UserId.Value, IsPaginationEnabled = domainEntity.IsPaginationEnabled, ItemsPerPage = domainEntity.ItemsPerPage, - IgnoreThePrefixForAlphaPicker = domainEntity.IgnoreThePrefixForAlphaPicker, - IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled + ShouldIgnoreThePrefixForAlphaPicker = domainEntity.ShouldIgnoreThePrefixForAlphaPicker, + IsThemeCachingEnabled = domainEntity.IsThemeCachingEnabled, + ShouldAggregateMetadataWhenMissing = domainEntity.ShouldAggregateMetadataWhenMissing }; } @@ -40,7 +41,9 @@ public static class UserSettingsMapping domainEntity.UserId.Value, domainEntity.IsPaginationEnabled, domainEntity.ItemsPerPage, - domainEntity.IgnoreThePrefixForAlphaPicker, - domainEntity.IsThemeCachingEnabled); + domainEntity.ShouldIgnoreThePrefixForAlphaPicker, + domainEntity.IsThemeCachingEnabled, + domainEntity.ShouldAggregateMetadataWhenMissing + ); } } diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs index a9345eca..995a3ee6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommand.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; -using System; using System.Diagnostics; #endregion @@ -15,7 +14,7 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; /// The path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. -/// Whether this media library should update the metadata of its elements from the web, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. [DebuggerDisplay("Title: {Title}")] @@ -26,7 +25,7 @@ public record AddLibraryCommand( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs index 320cd84f..c4ad4181 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; @@ -10,14 +8,15 @@ using Lumina.Application.Common.Infrastructure.Authorization; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System; using System.Collections.Generic; using System.Threading; @@ -113,7 +112,7 @@ public class AddLibraryCommandHandler : ICommandHandlerThe path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. -/// Whether this media library should update the metadata of its elements from the web, or not. +/// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. [DebuggerDisplay("Title: {Title}")] @@ -30,7 +30,7 @@ public record UpdateLibraryCommand( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs index 1e13108a..8a210168 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; @@ -11,16 +9,17 @@ using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwn using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; -using Lumina.Domain.SharedKernel.Common.Enums.Authorization; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using System; using System.Collections.Generic; using System.Linq; @@ -127,10 +126,10 @@ public class UpdateLibraryCommandHandler : ICommandHandler ScanId.Create(libraryScan.Id)).ToList() + [.. getLibraryResult.Value.LibraryScans.Select(libraryScan => ScanId.Create(libraryScan.Id))] ); if (createLibraryResult.IsFailure) return createLibraryResult.Errors; diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs index 301727f5..d77ae07f 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibraryScanQueuedDomainEventHandler.cs @@ -60,7 +60,7 @@ public class LibraryScanQueuedDomainEventHandler : IDomainEventHandler startScanResult = await _mediaLibraryScanningService.StartScanAsync( - libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, getLibraryScanResult.Value.Library.DownloadMetadataFromWeb, cancellationToken).ConfigureAwait(false); + libraryScanDomainResult.Value, getLibraryScanResult.Value.Library.LibraryType, cancellationToken).ConfigureAwait(false); if (startScanResult.IsFailure) throw new EventualConsistencyException(startScanResult.FirstError, startScanResult.Errors); diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs index b04e7a35..8fc10e5b 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandler.cs @@ -1,15 +1,18 @@ #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 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.ReorderLibraryMetadataProviders; @@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.ReorderLibraryMetadataProvide public class ReorderLibraryMetadataProvidersCommandHandler : 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 ReorderLibraryMetadataProvidersCommandHandler(IUnitOfWork unitOfWork, IValidator validator) + public ReorderLibraryMetadataProvidersCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { + _authorizationService = authorizationService; + _currentUserService = currentUserService; _unitOfWork = unitOfWork; _validator = validator; } @@ -47,6 +56,18 @@ public class ReorderLibraryMetadataProvidersCommandHandler : ICommandHandler 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 metadata 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.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(command.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs index 1a9fd05c..95c01884 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandValidator.cs @@ -2,6 +2,7 @@ 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.ReorderLibraryMetadataProviders; @@ -18,6 +19,8 @@ public class ReorderLibraryMetadataProvidersCommandValidator : AbstractValidator { RuleFor(command => command.LibraryId) .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); RuleFor(command => command.PluginIds) diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs index d3d8eee5..21e21978 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandler.cs @@ -1,15 +1,18 @@ #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 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.SetLibraryMetadataProviderEnabled; @@ -20,15 +23,21 @@ namespace Lumina.Application.Core.Plugins.Commands.SetLibraryMetadataProviderEna public class SetLibraryMetadataProviderEnabledCommandHandler : 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 SetLibraryMetadataProviderEnabledCommandHandler(IUnitOfWork unitOfWork, IValidator validator) + public SetLibraryMetadataProviderEnabledCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { + _authorizationService = authorizationService; + _currentUserService = currentUserService; _unitOfWork = unitOfWork; _validator = validator; } @@ -47,6 +56,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandler : ICommandHandler 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 metadata 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.LibraryMetadataProviderConfigurationRepository.GetByLibraryAndPluginIdAsync(command.LibraryId, command.PluginId, cancellationToken).ConfigureAwait(false); if (getConfigurationResult.IsFailure) return getConfigurationResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs index f631bc44..b910702f 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandValidator.cs @@ -2,6 +2,7 @@ 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.SetLibraryMetadataProviderEnabled; @@ -18,10 +19,14 @@ public class SetLibraryMetadataProviderEnabledCommandValidator : AbstractValidat { 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/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs index 283e4bf5..c100995f 100644 --- a/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs +++ b/src/Lumina.Application/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandValidator.cs @@ -2,6 +2,7 @@ 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.UpdatePluginSettings; @@ -18,6 +19,8 @@ public class UpdatePluginSettingsCommandValidator : AbstractValidator 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/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 6ed087fe..391cf371 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -1,16 +1,20 @@ #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 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.GetLibraryMetadataProviders; @@ -21,14 +25,23 @@ namespace Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; public class GetLibraryMetadataProvidersQueryHandler : 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. - public GetLibraryMetadataProvidersQueryHandler(IUnitOfWork unitOfWork) + /// Injected validator for application validation rules. + public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) { + _authorizationService = authorizationService; + _currentUserService = currentUserService; _unitOfWork = unitOfWork; + _validator = validator; } /// @@ -41,6 +54,22 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler public async Task>> HandleAsync(GetLibraryMetadataProvidersQuery 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 metadata 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.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.cs new file mode 100644 index 00000000..931c1ae3 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidator.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.GetLibraryMetadataProviders; + +/// +/// Validates the needed validation rules for . +/// +public class GetLibraryMetadataProvidersQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetLibraryMetadataProvidersQueryValidator() + { + RuleFor(query => query.LibraryId) + .NotEmpty() + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.LibraryIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs index 5e26b31d..28a8eae3 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandler.cs @@ -1,13 +1,13 @@ #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.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; using Lumina.Plugins.Contracts.Core.Plugins; using System.Collections.Generic; using System.Linq; @@ -24,16 +24,19 @@ public class GetPluginSettingsQueryHandler : IQueryHandler _validator; /// /// Initializes a new instance of the class. /// /// Injected unit of work for interacting with the data access layer repositories. /// Injected manager of the plugins loaded by the host application. - public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager) + /// Injected validator for application validation rules. + public GetPluginSettingsQueryHandler(IUnitOfWork unitOfWork, IPluginManager pluginManager, IValidator validator) { _unitOfWork = unitOfWork; _pluginManager = pluginManager; + _validator = validator; } /// @@ -46,6 +49,10 @@ public class GetPluginSettingsQueryHandler : IQueryHandler public async Task> HandleAsync(GetPluginSettingsQuery query, CancellationToken cancellationToken) { + List validationResult = _validator.Validate(query); + if (validationResult.Count > 0) + return validationResult; + Result getPluginResult = await _unitOfWork.PluginRepository.GetByIdAsync(query.PluginId, cancellationToken).ConfigureAwait(false); if (getPluginResult.IsFailure) return getPluginResult.Errors; diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.cs new file mode 100644 index 00000000..2a94c3b5 --- /dev/null +++ b/src/Lumina.Application/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidator.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.GetPluginSettings; + +/// +/// Validates the needed validation rules for . +/// +public class GetPluginSettingsQueryValidator : AbstractValidator +{ + /// + /// Initializes a new instance of the class. + /// + public GetPluginSettingsQueryValidator() + { + RuleFor(query => query.PluginId) + .NotEmpty() + .WithError(Errors.Plugins.PluginIdCannotBeEmpty) + .Must(id => id != Guid.Empty) + .WithError(Errors.Plugins.PluginIdCannotBeEmpty); + } +} diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs index 0e798ccc..e29088bf 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommand.cs @@ -9,11 +9,13 @@ namespace Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSe /// /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. -/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. +/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. public record UpdateUserSettingsCommand( bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker, - bool IsThemeCachingEnabled + bool ShouldIgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled, + bool ShouldAggregateMetadataWhenMissing ) : ICommand; diff --git a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs index 3028518b..9af3a222 100644 --- a/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs +++ b/src/Lumina.Application/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandler.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; using Lumina.Application.Common.CQRS; using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using System; @@ -72,8 +71,9 @@ public class UpdateUserSettingsCommandHandler : ICommandHandler updateSettingsResult = toDomainEntityResult.Value.UpdateSettings( command.IsPaginationEnabled, command.ItemsPerPage, - command.IgnoreThePrefixForAlphaPicker, - command.IsThemeCachingEnabled); + command.ShouldIgnoreThePrefixForAlphaPicker, + command.IsThemeCachingEnabled, + command.ShouldAggregateMetadataWhenMissing); if (updateSettingsResult.IsFailure) return updateSettingsResult.Errors; diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs index bfc717ba..df43eb8d 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/AddLibraryRequest.cs @@ -13,7 +13,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The path of the image file used as the cover for the library. Optional. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. +/// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. [DebuggerDisplay("Title: {Title}")] @@ -24,7 +24,7 @@ public record AddLibraryRequest( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs index ad62394a..9590f10a 100644 --- a/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaLibrary/Management/UpdateLibraryRequest.cs @@ -1,8 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Diagnostics; -using System.Runtime.InteropServices; #endregion namespace Lumina.Contracts.Requests.MediaLibrary.Management; @@ -18,7 +16,7 @@ namespace Lumina.Contracts.Requests.MediaLibrary.Management; /// The path of the image file used as the cover for the library. Optional. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional. -/// Whether this media library should update the metadata of its elements from the web, or not. Optional. +/// Whether this media library should update the metadata of its elements from the web, or not. Optional. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional. [DebuggerDisplay("Title: {Title}")] @@ -31,7 +29,7 @@ public record class UpdateLibraryRequest( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan ); diff --git a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs index 2b0ad237..b37216ac 100644 --- a/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs +++ b/src/Lumina.Contracts/Requests/UsersManagement/Settings/UpdateUserSettingsRequest.cs @@ -9,12 +9,14 @@ namespace Lumina.Contracts.Requests.UsersManagement.Settings; /// /// Whether pagination is enabled for the user, or not. Required. /// The number of library items displayed per page when pagination is enabled. Required. -/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. Required. /// Whether the theme data served to this user is cached, or not. Required. +/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. Required. [DebuggerDisplay("IsPaginationEnabled: {IsPaginationEnabled}; ItemsPerPage: {ItemsPerPage}")] public sealed record UpdateUserSettingsRequest( bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker, - bool IsThemeCachingEnabled + bool ShouldIgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled, + bool ShouldAggregateMetadataWhenMissing ); diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs index 9ec7de01..9dff6ddc 100644 --- a/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs +++ b/src/Lumina.Contracts/Responses/MediaLibrary/Management/LibraryResponse.cs @@ -16,6 +16,11 @@ namespace Lumina.Contracts.Responses.MediaLibrary.Management; /// The type of the media library. /// The file system paths of the directories where the media library elements are located. /// The path of the image file used as the cover for the library. +/// Whether the media library is enabled or not. A disabled media library is never shown or changed. +/// Whether the media library is locked or not. A locked media library is displayed, but is never changed or updated. +/// Whether the media library should update the metadata of its elements from the web, or not. +/// Whether the media library should copy the downloaded metadata into the media library content locations, or not. +/// Whether the media library should skip the directories whose contents have not changed since the last scan, during the scan. /// The date and time when the library was created. /// The optional date and time when the library was updated. [DebuggerDisplay("Title: {Title}")] @@ -28,7 +33,7 @@ public record LibraryResponse( string? CoverImage, bool IsEnabled, bool IsLocked, - bool DownloadMetadataFromWeb, + bool CanDownloadMetadataFromWeb, bool ShouldSaveMetadataInMediaDirectories, bool ShouldSkipUnchangedDirectoriesDuringScan, DateTime CreatedOnUtc, diff --git a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs index 3c362b34..3f5c59e3 100644 --- a/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs +++ b/src/Lumina.Contracts/Responses/UsersManagement/Settings/UserSettingsResponse.cs @@ -11,13 +11,15 @@ namespace Lumina.Contracts.Responses.UsersManagement.Settings; /// The unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. -/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. +/// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. +/// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. [DebuggerDisplay("UserId: {UserId}")] public sealed record UserSettingsResponse( Guid UserId, bool IsPaginationEnabled, int ItemsPerPage, - bool IgnoreThePrefixForAlphaPicker, - bool IsThemeCachingEnabled + bool ShouldIgnoreThePrefixForAlphaPicker, + bool IsThemeCachingEnabled, + bool ShouldAggregateMetadataWhenMissing ); diff --git a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs index 6e085ae3..8c27891a 100644 --- a/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/LibraryConfiguration.cs @@ -46,7 +46,7 @@ public class LibraryConfiguration : IEntityTypeConfiguration builder.Property(library => library.IsLocked) .HasColumnOrder(5); - builder.Property(library => library.DownloadMetadataFromWeb) + builder.Property(library => library.CanDownloadMetadataFromWeb) .HasDefaultValue(true) .HasColumnOrder(6); diff --git a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs index ca160a72..84a4f221 100644 --- a/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs +++ b/src/Lumina.DataAccess/Common/Configuration/UserSettingsConfiguration.cs @@ -2,7 +2,6 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; -using System; #endregion namespace Lumina.DataAccess.Common.Configuration; @@ -43,10 +42,14 @@ public class UserSettingsConfiguration : IEntityTypeConfiguration settings.IgnoreThePrefixForAlphaPicker) + builder.Property(settings => settings.ShouldIgnoreThePrefixForAlphaPicker) .IsRequired() .HasColumnOrder(4); + builder.Property(settings => settings.ShouldAggregateMetadataWhenMissing) + .IsRequired() + .HasColumnOrder(10); + builder.Property(settings => settings.IsThemeCachingEnabled) .IsRequired() .HasColumnOrder(9); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs index e2927044..1d369cef 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/BookRepository.cs @@ -132,7 +132,7 @@ internal sealed class BookRepository : IBookRepository booksQuery = booksQuery.Where(filterSpecification.ToExpression()); // apply sorting based on the specified sortBy and sortOrder parameters - booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.IgnoreThePrefixForAlphaPicker); + booksQuery = ApplySorting(booksQuery, sortBy, sortOrder ?? SortOrder.Ascending, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); // if no pagination was requested, return all the books of the library if (paginationData is null) @@ -261,8 +261,8 @@ internal sealed class BookRepository : IBookRepository /// The query to sort. /// The field to sort by (case-insensitive). /// The direction of the sorting. - /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. - private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool ignoreThePrefixForAlphaPicker) + /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. + private static IOrderedQueryable ApplySorting(IQueryable booksQuery, string? sortBy, SortOrder sortOrder, bool shouldIgnoreThePrefixForAlphaPicker) { return sortBy?.ToLower() switch { @@ -276,8 +276,8 @@ internal sealed class BookRepository : IBookRepository ? booksQuery.OrderByDescending(book => book.MetadataProvider) : booksQuery.OrderBy(book => book.MetadataProvider), _ => sortOrder == SortOrder.Descending - ? booksQuery.OrderByDescending(BuildTitleSortKey(ignoreThePrefixForAlphaPicker)) - : booksQuery.OrderBy(BuildTitleSortKey(ignoreThePrefixForAlphaPicker)), + ? booksQuery.OrderByDescending(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker)) + : booksQuery.OrderBy(BuildTitleSortKey(shouldIgnoreThePrefixForAlphaPicker)), }; } @@ -286,9 +286,9 @@ internal sealed class BookRepository : IBookRepository /// the title lowercased, falling back to the original title when the title is or empty, and optionally /// stripped of a leading "the " prefix. /// - /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. + /// Whether a leading "the " prefix of a title is ignored when deriving the title sort key, or not. /// An expression that evaluates to the title sort key of a book. - private static Expression> BuildTitleSortKey(bool ignoreThePrefixForAlphaPicker) + private static Expression> BuildTitleSortKey(bool shouldIgnoreThePrefixForAlphaPicker) { ParameterExpression book = Expression.Parameter(typeof(BookEntity), "book"); @@ -306,7 +306,7 @@ internal sealed class BookRepository : IBookRepository // when ignoring the "The " prefix, strip a leading "the " from the lowercased title Expression effectiveTitle = lowerTitle; - if (ignoreThePrefixForAlphaPicker) + if (shouldIgnoreThePrefixForAlphaPicker) { MethodCallExpression startsWithThe = Expression.Call(lowerTitle, s_startsWithMethod, Expression.Constant("the ")); MethodCallExpression strippedTitle = Expression.Call(lowerTitle, s_substringMethod, Expression.Constant(4)); @@ -332,7 +332,7 @@ internal sealed class BookRepository : IBookRepository // include the alpha key filter, if provided if (libraryFilter.FilterAlphaKey is not null) { - BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.IgnoreThePrefixForAlphaPicker); + BookAlphaFilterSpecification alphaFilterSpecification = new(libraryFilter.FilterAlphaKey, libraryFilter.ShouldIgnoreThePrefixForAlphaPicker); filterSpecification = filterSpecification is null ? alphaFilterSpecification : filterSpecification.And(alphaFilterSpecification); diff --git a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs index 460726ec..39731c29 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Books/Specifications/BookAlphaFilterSpecification.cs @@ -23,17 +23,17 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification /// Initializes a new instance of the class. /// /// The alpha key to filter by. A single ASCII letter, , or . - /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. - public BookAlphaFilterSpecification(string? filterAlphaKey, bool ignoreThePrefixForAlphaPicker) + /// Whether the leading "The " prefix of a title should be ignored when computing the alpha key, or not. + public BookAlphaFilterSpecification(string? filterAlphaKey, bool shouldIgnoreThePrefixForAlphaPicker) { _filterAlphaKey = filterAlphaKey; - _ignoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + _shouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; } /// @@ -82,7 +82,7 @@ internal sealed class BookAlphaFilterSpecification : FilterSpecification RolePermissions { get; set; } = null!; public virtual DbSet Plugins { get; set; } = null!; public virtual DbSet LibraryMetadataProviderConfigurations { get; set; } = null!; + public virtual DbSet LibraryArtworkProviderConfigurations { get; set; } = null!; public virtual DbSet Themes { get; set; } = null!; /// diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs index 0a23313a..96cc1296 100644 --- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs +++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs @@ -39,6 +39,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable private ILibraryScanSnapshotRepository? _libraryScanSnapshotRepository; private ILibraryScanStagingResultsRepository? _libraryScanStagingResultsRepository; private ILibraryMetadataProviderConfigurationRepository? _libraryMetadataProviderConfigurationRepository; + private IArtworkProviderConfigurationRepository? _artworkProviderConfigurationRepository; private IPluginRepository? _pluginRepository; private IThemeRepository? _themeRepository; private IUserRepository? _userRepository; @@ -176,6 +177,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable } } + /// + /// Gets the library artwork provider configuration repository. + /// + public IArtworkProviderConfigurationRepository ArtworkProviderConfigurationRepository + { + get + { + _artworkProviderConfigurationRepository ??= new ArtworkProviderConfigurationRepository(_luminaDbContext); + return _artworkProviderConfigurationRepository; + } + } + /// /// Gets the plugin repository. /// @@ -242,6 +255,14 @@ public class UnitOfWork : IUnitOfWork, IDisposable await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); } + /// + /// Detaches all the entities tracked by the unit of work, freeing the memory they occupy. + /// + public void ClearTrackedEntities() + { + _luminaDbContext.ChangeTracker.Clear(); + } + /// /// Begins a new database transaction. /// diff --git a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs index 24249be1..c4eeea2d 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/FileSystemManagementBoundedContext/FileSystemManagementAggregate/Services/FileSystemStructureSeedService.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; -using Lumina.Domain.Common.Errors; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment; using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; #endregion @@ -38,23 +37,41 @@ internal class FileSystemStructureSeedService : IFileSystemStructureSeedService if (rootPathIdResult.IsFailure) return rootPathIdResult.Errors; - // create the libraries directory - Result librariesPathResult = _pathService.CombinePath(rootPath, "libraries"); - if (librariesPathResult.IsFailure) - return librariesPathResult.Errors; + Result createLibrariesDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "libraries"); + if (createLibrariesDirectoryResult.IsFailure) + return createLibrariesDirectoryResult.Errors; - Result libraryPathIdResult = FileSystemPathId.Create(librariesPathResult.Value); - if (libraryPathIdResult.IsFailure) - return libraryPathIdResult.Errors; + Result createBooksDirectoryResult = EnsureDirectory(rootPathIdResult.Value, "books"); + if (createBooksDirectoryResult.IsFailure) + return createBooksDirectoryResult.Errors; - Result librariesDirectoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(libraryPathIdResult.Value); - if (librariesDirectoryExistsResult.IsFailure) - return librariesDirectoryExistsResult.Errors; + return Result.Created; + } + + /// + /// Creates the directory with the provided under the , when it does not already exist. + /// + /// The id of the root path under which the directory is created. + /// The name of the directory to create. + /// An representing either a successful operation, or an error. + private Result EnsureDirectory(FileSystemPathId rootPathId, string directoryName) + { + Result directoryPathResult = _pathService.CombinePath(rootPathId.Path, directoryName); + if (directoryPathResult.IsFailure) + return directoryPathResult.Errors; + + Result directoryPathIdResult = FileSystemPathId.Create(directoryPathResult.Value); + if (directoryPathIdResult.IsFailure) + return directoryPathIdResult.Errors; + + Result directoryExistsResult = _environmentContext.DirectoryProviderService.DirectoryExists(directoryPathIdResult.Value); + if (directoryExistsResult.IsFailure) + return directoryExistsResult.Errors; // only create it if it doesn't already exist - if (!librariesDirectoryExistsResult.Value) + if (!directoryExistsResult.Value) { - Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathIdResult.Value, "libraries"); + Result createDirectoryResult = _environmentContext.DirectoryProviderService.CreateDirectory(rootPathId, directoryName); if (createDirectoryResult.IsFailure) return createDirectoryResult.Errors; } diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs index 445d175c..c49151d9 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/Library.cs @@ -63,7 +63,7 @@ public class Library : AggregateRoot /// /// Gets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMetadataFromWeb { get; private set; } = true; + public bool CanDownloadMetadataFromWeb { get; private set; } = true; /// /// Gets whether this media library should copy the downloaded metadata into the media library content locations, or not. @@ -97,7 +97,7 @@ public class Library : AggregateRoot /// The path of the image file used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. @@ -110,7 +110,7 @@ public class Library : AggregateRoot string? coverImage, bool isEnabled, bool isLocked, - bool downloadMetadataFromWeb, + bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) : base(id) @@ -122,7 +122,7 @@ public class Library : AggregateRoot CoverImage = coverImage; IsEnabled = isEnabled; IsLocked = isLocked; - DownloadMetadataFromWeb = downloadMetadataFromWeb; + CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb; ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories; ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan; _scanIds = scanIds; @@ -138,7 +138,7 @@ public class Library : AggregateRoot /// The path of the image file chosen by the user to be used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. @@ -153,7 +153,7 @@ public class Library : AggregateRoot string? coverImageSourcePath, bool isEnabled, bool isLocked, - bool downloadMetadataFromWeb, + bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) @@ -176,7 +176,7 @@ public class Library : AggregateRoot coverImageSourcePath, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, scanIds @@ -194,7 +194,7 @@ public class Library : AggregateRoot /// The path of the image file chosen by the user to be used as the cover for the library. /// Whether this media library is enabled or not. A disabled media library is never shown or changed. /// Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. - /// Whether this media library should update the metadata of its elements from the web, or not. + /// Whether this media library should update the metadata of its elements from the web, or not. /// Whether this media library should copy the downloaded metadata into the media library content locations, or not. /// Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. /// The list of objects representing the unique identifier of scans of the media library. @@ -210,7 +210,7 @@ public class Library : AggregateRoot string? coverImageSourcePath, bool isEnabled, bool isLocked, - bool downloadMetadataFromWeb, + bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, List scanIds) @@ -233,7 +233,7 @@ public class Library : AggregateRoot coverImageSourcePath, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, scanIds diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs index e50f05f1..80f1dacd 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/IMediaLibraryScanningService.cs @@ -17,10 +17,9 @@ public interface IMediaLibraryScanningService /// /// The media library scan to start. /// The type of the media library to be scanned. - /// Whether the library permits downloading data from the web, or not. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken); + Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken); /// /// Cancels . diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs index 2132a9da..211282ad 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/MediaLibraryScanningService.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Domain.Common.Primitives; -using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Jobs; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress; @@ -9,6 +8,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Scanners; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Threading; @@ -55,10 +55,9 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService /// /// The media library scan to start. /// The type of the media library to be scanned. - /// Whether the library permits downloading data from the web, or not. /// Cancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. - public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, bool downloadMetadataFromWeb, CancellationToken cancellationToken) + public async Task> StartScanAsync(LibraryScan scan, LibraryType libraryType, CancellationToken cancellationToken) { // mark the scan itself as started Result startScanResult = scan.StartScan(); @@ -81,7 +80,7 @@ internal class MediaLibraryScanningService : IMediaLibraryScanningService IMediaTypeScanner scanner = _mediaLibraryScannerFactory.CreateLibraryScanner(libraryType); // get the list of scan jobs for the retrieved scanner. It is impotant to enumerate them here, because deferred execuction would destroy any graph relationships // and properties we might set before putting the jobs on the in-memory queue. - List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId, downloadMetadataFromWeb)]; + List jobs = [.. scanner.CreateScanJobsForLibrary(scan.LibraryId)]; // count total jobs in the chain by traversing the job graph int totalJobs = CountTotalJobs(jobs); diff --git a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs index af55a807..c0027ad4 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryScanAggregate/Services/Scanners/IMediaTypeScanner.cs @@ -21,7 +21,6 @@ public interface IMediaTypeScanner /// 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. - IEnumerable CreateScanJobsForLibrary(LibraryId libraryId, bool downloadMetadataFromWeb); + IEnumerable CreateScanJobsForLibrary(LibraryId libraryId); } diff --git a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs index 6cd60fc9..b463dd44 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettings.cs @@ -4,7 +4,6 @@ using Lumina.Domain.Common.Models.Core; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate.ValueObjects; -using System; using System.Diagnostics; #endregion @@ -20,6 +19,7 @@ public class UserSettings : AggregateRoot private const int DEFAULT_ITEMS_PER_PAGE = 48; private const bool DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER = false; private const bool DEFAULT_IS_THEME_CACHING_ENABLED = true; + private const bool DEFAULT_AGGREGATE_METADATA_WHEN_MISSING = false; /// /// Gets the object representing the unique identifier of the user that owns these settings. @@ -39,13 +39,18 @@ public class UserSettings : AggregateRoot /// /// Gets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; private set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; private set; } /// /// Gets whether the theme data served to this user is cached, or not. /// public bool IsThemeCachingEnabled { get; private set; } + /// + /// Gets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// + public bool ShouldAggregateMetadataWhenMissing { get; private set; } + /// /// Initializes a new instance of the class. /// @@ -53,21 +58,24 @@ public class UserSettings : AggregateRoot /// The object representing the unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. private UserSettings( UserSettingsId id, UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) : base(id) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) : base(id) { UserId = userId; IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; } /// @@ -78,7 +86,7 @@ public class UserSettings : AggregateRoot /// public static Result Create() { - return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED); + return Create(UserId.CreateUnique(), DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING); } /// @@ -90,7 +98,7 @@ public class UserSettings : AggregateRoot /// public static Result Create(UserId userId) { - return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED); + return Create(userId, DEFAULT_IS_PAGINATION_ENABLED, DEFAULT_ITEMS_PER_PAGE, DEFAULT_IGNORE_THE_PREFIX_FOR_ALPHA_PICKER, DEFAULT_IS_THEME_CACHING_ENABLED, DEFAULT_AGGREGATE_METADATA_WHEN_MISSING); } /// @@ -99,8 +107,9 @@ public class UserSettings : AggregateRoot /// The object representing the unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// /// An containing either a successfully created , or an error message. /// @@ -108,8 +117,9 @@ public class UserSettings : AggregateRoot UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; @@ -119,8 +129,9 @@ public class UserSettings : AggregateRoot userId, isPaginationEnabled, itemsPerPage, - ignoreThePrefixForAlphaPicker, - isThemeCachingEnabled); + shouldIgnoreThePrefixForAlphaPicker, + isThemeCachingEnabled, + shouldAggregateMetadataWhenMissing); } /// @@ -130,8 +141,9 @@ public class UserSettings : AggregateRoot /// The object representing the unique identifier of the user that owns these settings. /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// /// An containing either a successfully created , or an error message. /// @@ -140,13 +152,14 @@ public class UserSettings : AggregateRoot UserId userId, bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; - return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, ignoreThePrefixForAlphaPicker, isThemeCachingEnabled); + return new UserSettings(id, userId, isPaginationEnabled, itemsPerPage, shouldIgnoreThePrefixForAlphaPicker, isThemeCachingEnabled, shouldAggregateMetadataWhenMissing); } /// @@ -154,22 +167,25 @@ public class UserSettings : AggregateRoot /// /// Whether pagination is enabled for the user, or not. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// Whether the theme data served to this user is cached, or not. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// An representing either a successful update, or an error. public Result UpdateSettings( bool isPaginationEnabled, int itemsPerPage, - bool ignoreThePrefixForAlphaPicker, - bool isThemeCachingEnabled) + bool shouldIgnoreThePrefixForAlphaPicker, + bool isThemeCachingEnabled, + bool shouldAggregateMetadataWhenMissing) { if (itemsPerPage <= 0) return Errors.UserSettings.ItemsPerPageMustBeGreaterThanZero; IsPaginationEnabled = isPaginationEnabled; ItemsPerPage = itemsPerPage; - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker; + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker; IsThemeCachingEnabled = isThemeCachingEnabled; + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing; return Result.Updated; } } diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs index 1c41488f..60244347 100644 --- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs +++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs @@ -14,6 +14,7 @@ public static partial class Errors public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty)); public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty)); public static Error MediaLibrariesDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaLibrariesDirectoryCannotBeEmpty)); + public static Error MediaBooksDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaBooksDirectoryCannotBeEmpty)); public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty)); public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String)); public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty)); diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs index 846b2d86..3c3b9829 100644 --- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs +++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsDtoValidator.cs @@ -23,5 +23,9 @@ public class MediaSettingsDtoValidator : AbstractValidator RuleFor(settings => settings.LibrariesDirectory) .NotEmpty() .WithError(Errors.Errors.Configuration.MediaLibrariesDirectoryCannotBeEmpty); + + RuleFor(settings => settings.BooksDirectory) + .NotEmpty() + .WithError(Errors.Errors.Configuration.MediaBooksDirectoryCannotBeEmpty); } } diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs index 2f650ac8..7548e7a7 100644 --- a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJob.cs @@ -1,9 +1,12 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Books; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; using Lumina.Contracts.DTO.Common; using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Domain.Common.Events; @@ -77,71 +80,140 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo MediaLibraryScanCompositeId compositeKey = MediaLibraryScanCompositeId.Create(ScanId, UserId); - // get the metadata providers configured for the media library, in their configured order, that support the media library type + // load the media library, whose name is used to build the directory of the book artwork, and whose setting determines + // whether the providers that require access to the web are used during the enrichment + string libraryName = string.Empty; + bool canDownloadMetadataFromWeb = false; + if (unitOfWork.LibraryRepository is not null) + { + Result getLibraryResult = await unitOfWork.LibraryRepository.GetByIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure || getLibraryResult.Value is null) + _logger.LogWarning("Failed to read the media library, the book artwork will not be stored and the providers requiring the web will not be used."); + else + { + libraryName = getLibraryResult.Value.Title; + canDownloadMetadataFromWeb = getLibraryResult.Value.CanDownloadMetadataFromWeb; + } + } + + // get the metadata providers configured for the media library, in their configured order, that support the media library type, + // skipping the providers that require access to the web when the media library does not permit downloading data from the web Result> getConfigurationsResult = await unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) throw new InvalidOperationException(getConfigurationsResult.FirstError.Description); - List providers = []; + List providers = []; foreach (LibraryMetadataProviderConfigurationEntity configuration in getConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) { - List configuredProviders = [.. asyncServiceScope.ServiceProvider - .GetKeyedServices(configuration.PluginId) - .Where(provider => provider.SupportedLibraryType == LibraryType.Book)]; + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; if (configuredProviders.Count == 0) _logger.LogWarning("No metadata provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); providers.AddRange(configuredProviders); } + // read whether the metadata of the books of the user is aggregated from multiple providers, when fields are missing + bool shouldAggregateMetadataWhenMissing = false; + if (unitOfWork.UserSettingsRepository is not null) + { + Result getUserSettingsResult = await unitOfWork.UserSettingsRepository.GetByUserIdAsync(UserId.Value, cancellationToken).ConfigureAwait(false); + if (getUserSettingsResult.IsFailure) + _logger.LogWarning("Failed to read the user settings, the metadata will not be aggregated across providers."); + else + shouldAggregateMetadataWhenMissing = getUserSettingsResult.Value?.ShouldAggregateMetadataWhenMissing ?? false; + } + + // get the artwork providers configured for the media library, in their configured order, that support the media library type. + // the artwork resolution is best-effort, so a failure to read the artwork configurations must not prevent the metadata enrichment from proceeding + List artworkProviders = []; + if (unitOfWork.ArtworkProviderConfigurationRepository is not null) + { + Result> getArtworkConfigurationsResult = await unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getArtworkConfigurationsResult.IsFailure) + _logger.LogWarning("Failed to read the artwork provider configurations."); + else + { + foreach (LibraryArtworkProviderConfigurationEntity configuration in getArtworkConfigurationsResult.Value.Where(configuration => configuration.IsEnabled).OrderBy(configuration => configuration.Rank)) + { + List configuredProviders = [.. asyncServiceScope.ServiceProvider + .GetKeyedServices(configuration.PluginId) + .Where(provider => provider.SupportedLibraryTypes.Contains(LibraryType.Book) + && (canDownloadMetadataFromWeb || !provider.RequiresWebAccess))]; + if (configuredProviders.Count == 0) + _logger.LogWarning("No artwork provider was found for the configured plugin with Id '{PluginId}' and the {LibraryType} library type.", configuration.PluginId, LibraryType.Book); + artworkProviders.AddRange(configuredProviders); + } + } + } + + IBookArtworkService? bookArtworkService = asyncServiceScope.ServiceProvider.GetService(); + // count the books that need their metadata enriched, for progress reporting purposes - Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); - if (getBooksToEnrichCountResult.IsFailure) - throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); - int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - - // set the initial progress of the scan job - Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - - DateTime lastUpdateTime = DateTime.UtcNow; - int minUpdateIntervalMs = 100; - int processedBooksCount = 0; string? lastPath = null; - // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size - while (true) + // when no metadata provider is available, the books must not be marked as failed to enrich, so the enrichment is skipped entirely + if (providers.Count > 0) { - cancellationToken.ThrowIfCancellationRequested(); + Result getBooksToEnrichCountResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataCountAsync(LibraryId.Value, cancellationToken).ConfigureAwait(false); + if (getBooksToEnrichCountResult.IsFailure) + throw new InvalidOperationException(getBooksToEnrichCountResult.FirstError.Description); + int totalBooksToEnrich = getBooksToEnrichCountResult.Value; - Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); - if (getBooksPageResult.IsFailure) - throw new InvalidOperationException(getBooksPageResult.FirstError.Description); - IReadOnlyList booksPage = getBooksPageResult.Value; - if (booksPage.Count == 0) - break; + // set the initial progress of the scan job + Result publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, 0, totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - foreach (BookEntity bookEntity in booksPage) + DateTime lastUpdateTime = DateTime.UtcNow; + int minUpdateIntervalMs = 100; + int processedBooksCount = 0; + + // process the books that need their metadata enriched in pages, keeping the peak memory bounded regardless of the library size + while (true) { cancellationToken.ThrowIfCancellationRequested(); - await EnrichBookAsync(bookEntity, providers, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false); + Result> getBooksPageResult = await unitOfWork.BookRepository.GetBooksNeedingMetadataAsync(LibraryId.Value, lastPath, ENRICHMENT_PAGE_SIZE, cancellationToken).ConfigureAwait(false); + if (getBooksPageResult.IsFailure) + throw new InvalidOperationException(getBooksPageResult.FirstError.Description); + IReadOnlyList booksPage = getBooksPageResult.Value; + if (booksPage.Count == 0) + break; - // check if enough time has passed since last update - DateTime now = DateTime.UtcNow; - if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + foreach (BookEntity bookEntity in booksPage) { - // increment the number of processed elements progress - publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); - if (publishJobProgressResult.IsFailure) - throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); - lastUpdateTime = now; - } - } + cancellationToken.ThrowIfCancellationRequested(); - lastPath = booksPage[^1].Path; + await EnrichBookAsync(bookEntity, providers, shouldAggregateMetadataWhenMissing, artworkProviders, bookArtworkService, libraryName, unitOfWork.BookRepository, cancellationToken).ConfigureAwait(false); + + // check if enough time has passed since last update + DateTime now = DateTime.UtcNow; + if ((now - lastUpdateTime).TotalMilliseconds >= minUpdateIntervalMs) + { + // increment the number of processed elements progress + publishJobProgressResult = await PublishJobProgressAsync(domainEventPublisher, compositeKey, Interlocked.Increment(ref processedBooksCount), totalBooksToEnrich, cancellationToken).ConfigureAwait(false); + if (publishJobProgressResult.IsFailure) + throw new InvalidOperationException(publishJobProgressResult.FirstError.Description); + lastUpdateTime = now; + } + } + + // persist the enriched books of this page, then detach them from the change tracker, keeping the peak memory bounded regardless of the library size + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + unitOfWork.ClearTrackedEntities(); + + lastPath = booksPage[^1].Path; + } + } + else + { + _logger.LogWarning("No metadata provider is configured for the media library with Id '{LibraryId}', the metadata enrichment will be skipped.", LibraryId.Value); } - await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + // persist the changes when no page was processed, so that the scan still saves even when there are no books to enrich + if (lastPath is null) + await unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // this job finished, and it's the last in the chain, the scan is completed Status = LibraryScanJobStatus.Completed; @@ -166,21 +238,29 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } /// - /// Enriches the metadata of the provided , using the provided in their configured order. + /// Enriches the metadata and the artwork of the provided , using the provided metadata and artwork providers in their configured order. /// - /// The book whose metadata is enriched. - /// The metadata providers, in their configured order. - /// The repository used to persist the enriched metadata. + /// The book whose metadata and artwork are enriched. + /// The metadata providers, in their configured order. + /// Whether the metadata of the book is aggregated from multiple providers, when fields are missing, or not. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The name of the media library the book belongs to. + /// The repository used to persist the enriched book. /// Cancellation token that can be used to stop the execution. - private static async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList providers, IBookRepository bookRepository, CancellationToken cancellationToken) + private async Task EnrichBookAsync(BookEntity bookEntity, IReadOnlyList metadataProviders, bool shouldAggregateMetadataWhenMissing, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, IBookRepository bookRepository, CancellationToken cancellationToken) { + // when no metadata provider is available, the book must not be marked as failed to enrich, so the enrichment is skipped + if (metadataProviders.Count == 0) + return; + // convert the book to a domain object Result getBookResult = bookEntity.ToDomainEntity(); if (getBookResult.IsFailure) return; Book book = getBookResult.Value; - BookMetadataLookupDto lookup = new( + BookMetadataLookupDto bookMetadataLookup = new( LibraryId: bookEntity.LibraryId, Path: bookEntity.Path, Isbn: bookEntity.ISBNs.Count > 0 ? bookEntity.ISBNs.Where(isbn => isbn.Value is not null).Select(isbn => isbn.Value!).First() : null, // TODO: this should not take just the first ISBN, it should ask the metadata plugin to retry with the next ISBN, if the first one returned no results @@ -190,24 +270,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo LanguageCode: bookEntity.LanguageCode ); - // try the metadata providers in order, until one returns usable metadata - foreach (IRemoteMetadataProvider provider in providers) + BookMetadataDto? appliedMetadata = shouldAggregateMetadataWhenMissing + ? await AggregateMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false) + : await TryFirstProviderMetadataAsync(book, bookMetadataLookup, metadataProviders, cancellationToken).ConfigureAwait(false); + + if (appliedMetadata is null) + { + // no metadata provider returned usable metadata, mark the book as failed to enrich + book.MarkMetadataAsFailed(); + Result markFailedResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (markFailedResult.IsFailure) + _logger.LogWarning("Failed to persist the failed enrichment state of the book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path); + return; + } + + // resolve the artwork of the book from the artwork providers, in their configured order + await EnrichBookArtworkAsync(book, appliedMetadata, artworkProviders, bookArtworkService, libraryName, cancellationToken).ConfigureAwait(false); + + Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (updateBookResult.IsFailure) + _logger.LogWarning("Failed to persist the enriched book with Id '{BookId}' at path '{BookPath}'.", book.Id.Value, book.Path); + } + + /// + /// Tries the in order, applying the metadata of the first one that returns usable metadata. + /// + /// The book onto which the metadata is applied. + /// The lookup describing the book. + /// The metadata providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The applied metadata, or when no provider returned usable metadata. + private static async Task TryFirstProviderMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + { + foreach (IMetadataProvider metadataProvider in metadataProviders) { try { - MetadataDto? metadataResult = await provider.GetMetadataAsync(lookup, cancellationToken).ConfigureAwait(false); + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) continue; - Result applyMetadataResult = book.ApplyMetadata(bookMetadata, provider.Name, DateTime.UtcNow); + Result applyMetadataResult = book.ApplyMetadata(bookMetadata, metadataProvider.Name, DateTime.UtcNow); if (applyMetadataResult.IsFailure) continue; + return bookMetadata; + } + catch (Exception) + { + // a failing metadata provider must not prevent the other providers from being tried + } + } + return null; + } - Result updateBookResult = await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); - if (updateBookResult.IsFailure) + /// + /// Aggregates the metadata of the from all the , in their configured order, filling the fields that the earlier providers lack with the values of the later ones. + /// + /// The book onto which the aggregated metadata is applied. + /// The lookup describing the book. + /// The metadata providers, in their configured order. + /// Cancellation token that can be used to stop the execution. + /// The applied aggregated metadata, or when no provider returned usable metadata. + private static async Task AggregateMetadataAsync(Book book, BookMetadataLookupDto bookMetadataLookup, IReadOnlyList metadataProviders, CancellationToken cancellationToken) + { + BookMetadataDto? mergedMetadata = null; + List contributingProviders = []; + + foreach (IMetadataProvider metadataProvider in metadataProviders) + { + try + { + MetadataDto? metadataResult = await metadataProvider.GetMetadataAsync(bookMetadataLookup, cancellationToken).ConfigureAwait(false); + if (metadataResult is not BookMetadataDto bookMetadata || !IsUsableMetadata(bookMetadata)) continue; - return; + mergedMetadata = mergedMetadata is null ? bookMetadata : MetadataAggregator.Merge(mergedMetadata, bookMetadata); + contributingProviders.Add(metadataProvider.Name); + // the identifiers and the title discovered by the earlier providers are fed to the later ones, so that they can look up the book precisely + bookMetadataLookup = EnrichLookup(bookMetadataLookup, mergedMetadata); } catch (Exception) { @@ -215,25 +355,84 @@ internal sealed class MediaLibraryScanMetadataEnrichmentJob : MediaLibraryScanJo } } - // no metadata provider returned usable metadata, mark the book as failed to enrich - book.MarkMetadataAsFailed(); - await bookRepository.UpdateAsync(book.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false); + if (mergedMetadata is null) + return null; + + Result applyMetadataResult = book.ApplyMetadata(mergedMetadata, string.Join(", ", contributingProviders.Distinct(StringComparer.Ordinal)), DateTime.UtcNow); + return applyMetadataResult.IsFailure ? null : mergedMetadata; } /// - /// Determines whether the provided is usable, meaning it has a title and at least one primary identifier. + /// Resolves the artwork of the from the , in their configured order, storing the artwork of the first provider that returns it. /// - /// The metadata to validate. - /// when the metadata is usable, otherwise . - private static bool IsUsableMetadata(BookMetadataDto metadata) + /// The book whose artwork is enriched. + /// The metadata applied to the book, used to build the directory of the book artwork. + /// The artwork providers, in their configured order. + /// The service used to store the artwork of the book. + /// The name of the media library the book belongs to. + /// Cancellation token that can be used to stop the execution. + private static async Task EnrichBookArtworkAsync(Book book, BookMetadataDto appliedMetadata, IReadOnlyList artworkProviders, IBookArtworkService? bookArtworkService, string libraryName, CancellationToken cancellationToken) { - if (string.IsNullOrWhiteSpace(metadata.Title)) - return false; - return !string.IsNullOrWhiteSpace(metadata.GoodreadsId) - || !string.IsNullOrWhiteSpace(metadata.OpenLibraryId) - || !string.IsNullOrWhiteSpace(metadata.GoogleBooksId) - || !string.IsNullOrWhiteSpace(metadata.ASIN) - || (metadata.Isbns is not null && metadata.Isbns.Count > 0); + if (bookArtworkService is null || artworkProviders.Count == 0) + return; + + foreach (IArtworkProvider provider in artworkProviders) + { + ArtworkDto? artwork = null; + try + { + artwork = await provider.GetArtworkAsync(new BookMetadataLookupDto(LibraryId: book.LibraryId.Value, Path: book.Path), cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + // a failing artwork provider must not prevent the other providers from being tried + } + + if (artwork is null) + continue; + + // a provider that returns remote artwork must declare that it requires web access, otherwise downloading it would contradict the provider's contract + if (!string.IsNullOrWhiteSpace(artwork.RemoteUrl) && !provider.RequiresWebAccess) + continue; + + string authorName = appliedMetadata.Contributors?.FirstOrDefault(contributor => contributor.Name?.DisplayName is not null)?.Name?.DisplayName ?? string.Empty; + string bookTitle = appliedMetadata.Title ?? book.Metadata.Title; + Result saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(book.LibraryId.Value, book.Id.Value, libraryName, authorName, bookTitle, artwork, cancellationToken).ConfigureAwait(false); + if (saveArtworkResult.IsFailure) + continue; + + book.SetBookCoverImagePath(saveArtworkResult.Value); + return; + } + } + + /// + /// Enriches the with the identifiers and the title discovered by the already queried metadata providers. + /// + /// The lookup to enrich. + /// The metadata discovered by the already queried metadata providers. + /// The enriched lookup. + private static BookMetadataLookupDto EnrichLookup(BookMetadataLookupDto bookMetadataLookup, BookMetadataDto bookMetadata) + { + string? isbn = bookMetadataLookup.Isbn ?? bookMetadata.Isbns?.FirstOrDefault()?.Value; + string? openLibraryId = bookMetadataLookup.OpenLibraryId ?? bookMetadata.OpenLibraryId; + string? title = bookMetadataLookup.Title ?? bookMetadata.Title; + return bookMetadataLookup with + { + Isbn = isbn, + OpenLibraryId = openLibraryId, + Title = title + }; + } + + /// + /// Determines whether the provided is usable, meaning it has a title. + /// + /// The metadata to validate. + /// when the metadata is usable, otherwise . + private static bool IsUsableMetadata(BookMetadataDto bookMetadata) + { + return !string.IsNullOrWhiteSpace(bookMetadata.Title); } /// diff --git a/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs new file mode 100644 index 00000000..3d314e8b --- /dev/null +++ b/src/Lumina.Infrastructure/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregator.cs @@ -0,0 +1,127 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Merges the book metadata returned by multiple metadata providers into a single book metadata, giving priority to the first provider that provides a value for each field. +/// +internal static class MetadataAggregator +{ + /// + /// Merges with , keeping the first non-empty value of each scalar field, and the union of the collection fields. + /// + /// The first metadata to merge, whose values have priority. + /// The second metadata to merge, filling the fields that the first metadata lacks. + /// The merged metadata. + public static BookMetadataDto Merge(BookMetadataDto first, BookMetadataDto second) + { + return new BookMetadataDto( + FirstOrDefaultReference(first.Title, second.Title), + FirstOrDefaultReference(first.OriginalTitle, second.OriginalTitle), + FirstOrDefaultReference(first.Description, second.Description), + MergeReleaseInfo(first.ReleaseInfo, second.ReleaseInfo), + Union(first.Genres, second.Genres, genre => genre.Name), + Union(first.Tags, second.Tags, tag => tag.Name), + FirstOrDefaultReference(first.Language, second.Language), + FirstOrDefaultReference(first.OriginalLanguage, second.OriginalLanguage), + FirstOrDefaultReference(first.Publisher, second.Publisher), + FirstOrDefaultValue(first.PageCount, second.PageCount), + FirstOrDefaultValue(first.Format, second.Format), + FirstOrDefaultReference(first.Edition, second.Edition), + FirstOrDefaultValue(first.VolumeNumber, second.VolumeNumber), + FirstOrDefaultReference(first.Series, second.Series), + FirstOrDefaultReference(first.ASIN, second.ASIN), + FirstOrDefaultReference(first.GoodreadsId, second.GoodreadsId), + FirstOrDefaultReference(first.LCCN, second.LCCN), + FirstOrDefaultReference(first.OCLCNumber, second.OCLCNumber), + FirstOrDefaultReference(first.OpenLibraryId, second.OpenLibraryId), + FirstOrDefaultReference(first.LibraryThingId, second.LibraryThingId), + FirstOrDefaultReference(first.GoogleBooksId, second.GoogleBooksId), + FirstOrDefaultReference(first.BarnesAndNobleId, second.BarnesAndNobleId), + FirstOrDefaultReference(first.AppleBooksId, second.AppleBooksId), + Union(first.Isbns, second.Isbns, isbn => isbn.Value), + Union(first.Contributors, second.Contributors, contributor => $"{contributor.Name?.DisplayName}|{contributor.Role?.Name}"), + Union(first.Ratings, second.Ratings, rating => rating.Source?.ToString()), + FirstOrDefaultReference(first.CoverImagePath, second.CoverImagePath)); + } + + /// + /// Merges the release information of the two metadata, keeping the first non-null value of each field. + /// + /// The first release information, whose values have priority. + /// The second release information, filling the fields that the first one lacks. + /// The merged release information, or when both are . + private static ReleaseInfoDto? MergeReleaseInfo(ReleaseInfoDto? first, ReleaseInfoDto? second) + { + if (first is null && second is null) + return null; + + return new ReleaseInfoDto( + FirstOrDefaultValue(first?.OriginalReleaseDate, second?.OriginalReleaseDate), + FirstOrDefaultValue(first?.OriginalReleaseYear, second?.OriginalReleaseYear), + FirstOrDefaultValue(first?.ReReleaseDate, second?.ReReleaseDate), + FirstOrDefaultValue(first?.ReReleaseYear, second?.ReReleaseYear), + FirstOrDefaultReference(first?.ReleaseCountry, second?.ReleaseCountry), + FirstOrDefaultReference(first?.ReleaseVersion, second?.ReleaseVersion)); + } + + /// + /// Gets the first non-null value of the two reference values. + /// + /// The type of the reference values. + /// The value with priority. + /// The fallback value. + /// The first non-null value, or when both are . + private static T? FirstOrDefaultReference(T? first, T? second) + where T : class + { + return first ?? second; + } + + /// + /// Gets the first non-null value of the two nullable value types. + /// + /// The underlying type of the nullable values. + /// The value with priority. + /// The fallback value. + /// The first non-null value, or when both are . + private static T? FirstOrDefaultValue(T? first, T? second) + where T : struct + { + return first ?? second; + } + + /// + /// Returns the union of the two collections, de-duplicated by the key, keeping the items of the first collection on key conflicts. + /// + /// The type of the collection items. + /// The first collection, whose items have priority. + /// The second collection. + /// The function used to extract the de-duplication key of an item. + /// The union of the two collections, or when both are . + private static List? Union(List? first, List? second, Func keySelector) + where T : class + { + if (first is null && second is null) + return null; + + Dictionary seen = new(StringComparer.OrdinalIgnoreCase); + List result = []; + + void AddRange(List? items) + { + foreach (T item in items ?? []) + if (seen.TryAdd(keySelector(item) ?? string.Empty, item)) + result.Add(item); + } + + AddRange(first); + AddRange(second); + return result; + } +} diff --git a/src/Lumina.Infrastructure/appsettings.shared.json b/src/Lumina.Infrastructure/appsettings.shared.json index 7790a2e1..6671a6dd 100644 --- a/src/Lumina.Infrastructure/appsettings.shared.json +++ b/src/Lumina.Infrastructure/appsettings.shared.json @@ -1,7 +1,8 @@ { "MediaSettings": { "RootDirectory": "media", - "LibrariesDirectory": "libraries" + "LibrariesDirectory": "libraries", + "BooksDirectory": "books" }, "PluginsSettings": { "Directory": "plugins" diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs index 2389d2eb..23cc0cd5 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Management/AddLibrary/AddLibraryEndpointSummary.cs @@ -34,7 +34,7 @@ public class AddLibraryEndpointSummary : Summary r.CoverImage, "The path of the image file used as the cover for the library. Optional."); RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional."); RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional."); - RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); + RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); @@ -57,7 +57,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); @@ -73,7 +73,7 @@ public class AddLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); @@ -53,7 +53,7 @@ public class GetLibraryEndpointSummary : Summary r.CoverImage, "The path of the image file used as the cover for the library. Optional."); RequestParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed. Optional."); RequestParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated. Optional."); - RequestParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); + RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not. Optional."); @@ -61,7 +61,7 @@ public class UpdateLibraryEndpointSummary : Summary(r => r.CoverImage, "The path of the image file used as the cover for the library."); ResponseParam(r => r.IsEnabled, "Whether this media library is enabled or not. A disabled media library is never shown or changed."); ResponseParam(r => r.IsLocked, "Whether this media library is locked or not. A locked media library is displayed, but is never changed or updated."); - ResponseParam(r => r.DownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); + ResponseParam(r => r.CanDownloadMetadataFromWeb, "Whether this media library should update the metadata of its elements from the web, or not."); ResponseParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether this media library should copy the downloaded metadata into the media library content locations, or not."); ResponseParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether this media library should skip the directories whose contents have not changed since the last scan, during the scan, or not."); ResponseParam(r => r.CreatedOnUtc, "The date and time when the entity was created."); @@ -77,7 +77,7 @@ public class UpdateLibraryEndpointSummary : Summary r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Required."); RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Required."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the \"The\" prefix of library item titles is ignored by the alpha picker, or not. Required."); RequestParam(r => r.IsThemeCachingEnabled, "Whether the theme data served to this user is cached, or not. Required."); Response(200, "The settings of the current user were successfully updated."); diff --git a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs index bc43dad9..574d7c33 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/Libraries/LibraryDto.cs @@ -1,5 +1,4 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Presentation.Web.Common.Enums.Library; using System; using System.Collections.Generic; using System.Diagnostics; @@ -56,7 +55,7 @@ public class LibraryDto /// /// Gets or sets whether this media library should update the metadata of its elements from the web, or not. /// - public bool DownloadMetadataFromWeb { get; set; } = true; + public bool CanDownloadMetadataFromWeb { get; set; } = true; /// /// Gets or sets whether this media library should copy the downloaded metadata into the media library content locations, or not. diff --git a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs index c074a3c6..d38be3b3 100644 --- a/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs +++ b/src/Lumina.Presentation.Web/Common/DTO/UsersManagement/UserSettingsDto.cs @@ -29,10 +29,15 @@ public class UserSettingsDto /// /// Gets or sets whether the "The" prefix of library item titles is ignored by the alpha picker, or not. /// - public bool IgnoreThePrefixForAlphaPicker { get; set; } + public bool ShouldIgnoreThePrefixForAlphaPicker { get; set; } /// /// Gets or sets whether the theme data served to this user is cached, or not. /// public bool IsThemeCachingEnabled { get; set; } = true; + + /// + /// Gets or sets whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. + /// + public bool ShouldAggregateMetadataWhenMissing { get; set; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs index 8f00c2dd..73bc9ef4 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Management/SaveLibrary/SaveLibraryEndpointSummary.cs @@ -2,7 +2,6 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.Common; using Lumina.Presentation.Web.Common.DTO.Libraries; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -29,7 +28,7 @@ public class SaveLibraryEndpointSummary : Summary r.ContentLocations, "The collection of directories that contain the media library files. Required."); RequestParam(r => r.IsEnabled, "Whether the media library is enabled or not. Optional."); RequestParam(r => r.IsLocked, "Whether the media library is locked or not. Optional."); - RequestParam(r => r.DownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional."); + RequestParam(r => r.CanDownloadMetadataFromWeb, "Whether the metadata of the media library items should be downloaded from the web, or not. Optional."); RequestParam(r => r.ShouldSaveMetadataInMediaDirectories, "Whether the downloaded metadata should be copied into the media library content locations, or not. Optional."); RequestParam(r => r.ShouldSkipUnchangedDirectoriesDuringScan, "Whether the directories whose contents have not changed since the last scan should be skipped during the scan, or not. Optional."); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs index ead45202..bd430938 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointSummary.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.DTO.UsersManagement; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -23,7 +22,7 @@ public class UpdateUserSettingsEndpointSummary : Summary r.UserId, "The unique identifier of the user that owns the settings. Optional."); RequestParam(r => r.IsPaginationEnabled, "Whether pagination is enabled for the user, or not. Optional."); RequestParam(r => r.ItemsPerPage, "The number of library items displayed per page when pagination is enabled. Optional."); - RequestParam(r => r.IgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional."); + RequestParam(r => r.ShouldIgnoreThePrefixForAlphaPicker, "Whether the leading 'The' prefix of library item titles is ignored by the alpha picker, or not. Optional."); ExampleRequest = new UserSettingsDto(); diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx index 0884bea3..01372ba1 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Management/Item.ar-SA.resx @@ -1,4 +1,4 @@ - +
- : + :
- @_localizer["DescriptionIgnoreThePrefixForAlphaPicker"] + @_localizer["DescriptionShouldIgnoreThePrefixForAlphaPicker"]
@@ -94,8 +94,9 @@ const form = document.getElementById('user-settings-form'); const checkboxIsPaginationEnabled = document.getElementById('IsPaginationEnabled'); const inputItemsPerPage = document.getElementById('ItemsPerPage'); - const checkboxIgnoreThePrefixForAlphaPicker = document.getElementById('IgnoreThePrefixForAlphaPicker'); + const checkboxShouldIgnoreThePrefixForAlphaPicker = document.getElementById('ShouldIgnoreThePrefixForAlphaPicker'); const checkboxIsThemeCachingEnabled = document.getElementById('IsThemeCachingEnabled'); + let shouldAggregateMetadataWhenMissing = false; // toggle the enabled state of the items per page input based on the pagination checkbox function updateItemsPerPageEnabledState() { @@ -108,8 +109,9 @@ if (data) { checkboxIsPaginationEnabled.checked = data.isPaginationEnabled === true; inputItemsPerPage.value = data.itemsPerPage; - checkboxIgnoreThePrefixForAlphaPicker.checked = data.ignoreThePrefixForAlphaPicker === true; + checkboxShouldIgnoreThePrefixForAlphaPicker.checked = data.shouldIgnoreThePrefixForAlphaPicker === true; checkboxIsThemeCachingEnabled.checked = data.isThemeCachingEnabled === true; + shouldAggregateMetadataWhenMissing = data.shouldAggregateMetadataWhenMissing === true; updateItemsPerPageEnabledState(); } } @@ -119,8 +121,9 @@ const formData = { IsPaginationEnabled: checkboxIsPaginationEnabled.checked, ItemsPerPage: Number(inputItemsPerPage.value), - IgnoreThePrefixForAlphaPicker: checkboxIgnoreThePrefixForAlphaPicker.checked, - IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked + ShouldIgnoreThePrefixForAlphaPicker: checkboxShouldIgnoreThePrefixForAlphaPicker.checked, + IsThemeCachingEnabled: checkboxIsThemeCachingEnabled.checked, + ShouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing }; const data = await callApiPostAsync('@_urlService.GetAbsoluteUrl(WebRoutes.Settings.UPDATE_USER_SETTINGS)', formData); if (data && data.isUpdated === true) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs new file mode 100644 index 00000000..ce13ed13 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryContentLocationEntityFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class LibraryContentLocationEntityFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The path of the media library content location. + /// The created . + public LibraryContentLocationEntity Create( + string? path = null) + { + return new LibraryContentLocationEntity + { + Path = path ?? _faker.System.DirectoryPath() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs index 605ca97f..deda345c 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/Management/LibraryEntityFixture.cs @@ -27,7 +27,7 @@ public class LibraryEntityFixture /// Optional. The cover image path of the media library. /// Whether the media library is enabled or not. /// Whether the media library is locked or not. - /// Whether the media library should download metadata from the web or not. + /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. /// The created media library entity. @@ -40,7 +40,7 @@ public class LibraryEntityFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false) { @@ -56,7 +56,7 @@ public class LibraryEntityFixture LibraryScans = [], IsEnabled = isEnabled, IsLocked = isLocked, - DownloadMetadataFromWeb = downloadMetadataFromWeb, + CanDownloadMetadataFromWeb = canDownloadMetadataFromWeb, ShouldSaveMetadataInMediaDirectories = shouldSaveMetadataInMediaDirectories, ShouldSkipUnchangedDirectoriesDuringScan = shouldSkipUnchangedDirectoriesDuringScan, CreatedOnUtc = default, diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs index e43f575f..7af3eb39 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/LibraryMetadataProviderConfigurationEntityFixture.cs @@ -21,14 +21,19 @@ public class LibraryMetadataProviderConfigurationEntityFixture /// The Id of the media library the configuration belongs to. /// The Id of the plugin providing the metadata. /// The rank of the metadata provider, determining the order in which providers are tried. + /// Whether the metadata provider is enabled or not. /// The created . - public LibraryMetadataProviderConfigurationEntity Create(Guid libraryId, Guid pluginId, int rank) + public LibraryMetadataProviderConfigurationEntity 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, faker => faker.Random.Bool()) + .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()) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs index c46f8762..27d9cb12 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/Plugins/PluginEntityFixture.cs @@ -21,17 +21,26 @@ public class PluginEntityFixture /// Creates a random valid . ///
/// The Id of the plugin, or to generate a random one. + /// The name of the plugin, or to generate a random one. + /// The load status of the plugin, or to generate a random one. + /// The serialized settings of the plugin, or to generate random ones. + /// Whether the settings should be included, or forced to . /// The created . - public PluginEntity Create(Guid? id = null) + public PluginEntity Create( + Guid? id = null, + string? name = null, + PluginLoadStatus? loadStatus = null, + string? settingsJson = null, + bool includeSettingsJson = true) { return new Faker() .RuleFor(plugin => plugin.Id, faker => id ?? faker.Random.Guid()) - .RuleFor(plugin => plugin.Name, faker => faker.Company.CompanyName()) + .RuleFor(plugin => plugin.Name, faker => name ?? faker.Company.CompanyName()) .RuleFor(plugin => plugin.Author, faker => faker.Name.FullName()) .RuleFor(plugin => plugin.Version, faker => faker.System.Semver()) .RuleFor(plugin => plugin.Description, faker => faker.Lorem.Sentence()) - .RuleFor(plugin => plugin.LoadStatus, faker => faker.PickRandom()) - .RuleFor(plugin => plugin.SettingsJson, faker => JsonSerializer.Serialize(new Dictionary { [faker.Random.String2(1, 10)] = faker.Random.String2(1, 20) })) + .RuleFor(plugin => plugin.LoadStatus, faker => loadStatus ?? faker.PickRandom()) + .RuleFor(plugin => plugin.SettingsJson, faker => includeSettingsJson ? settingsJson ?? JsonSerializer.Serialize(new Dictionary { [faker.Random.String2(1, 10)] = faker.Random.String2(1, 20) }) : null) .RuleFor(plugin => plugin.CreatedOnUtc, faker => faker.Date.Past()) .RuleFor(plugin => plugin.CreatedBy, faker => faker.Random.Guid()) .RuleFor(plugin => plugin.UpdatedOnUtc, faker => faker.Date.Recent()) diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs index e6e86104..d5074175 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/UsersManagement/UserSettingsEntityFixture.cs @@ -22,16 +22,18 @@ public class UserSettingsEntityFixture /// Optional. The Id of the user that owns these settings. /// Optional. Whether pagination is enabled for the user, or not. /// Optional. The number of library items displayed per page when pagination is enabled. - /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. /// Optional. Whether the theme data served to this user is cached, or not. + /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing, or not. /// The created user settings entity. public UserSettingsEntity Create( Guid? id = null, Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, - bool? ignoreThePrefixForAlphaPicker = null, - bool? isThemeCachingEnabled = null) + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) { return new Faker() .CustomInstantiator(f => new UserSettingsEntity @@ -40,8 +42,9 @@ public class UserSettingsEntityFixture UserId = userId ?? Guid.NewGuid(), IsPaginationEnabled = isPaginationEnabled ?? f.Random.Bool(), ItemsPerPage = itemsPerPage ?? f.Random.Int(1, 100), - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? f.Random.Bool(), - IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool() + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool(), + IsThemeCachingEnabled = isThemeCachingEnabled ?? f.Random.Bool(), + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? f.Random.Bool() }) .Generate(); } diff --git a/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs new file mode 100644 index 00000000..22d42e9a --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/Infrastructure/Models/DTO/Configuration/MediaSettingsDtoFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The root directory where media files are stored. + /// Optional. The directory where media library files are stored. + /// Optional. The directory where the media item files are stored. + /// The created . + public MediaSettingsDto Create( + string? rootDirectory = null, + string? librariesDirectory = null, + string? booksDirectory = null) + { + return new MediaSettingsDto + { + RootDirectory = rootDirectory ?? _faker.System.DirectoryPath(), + LibrariesDirectory = librariesDirectory ?? _faker.System.DirectoryPath(), + BooksDirectory = booksDirectory ?? _faker.System.DirectoryPath() + }; + } + + /// + /// Creates a list of instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs index beb7bf52..96e537b3 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandFixture.cs @@ -2,7 +2,6 @@ using Bogus; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -25,7 +24,7 @@ public class AddLibraryCommandFixture /// Optional. The cover image path of the media library. /// Whether the media library is enabled or not. /// Whether the media library is locked or not. - /// Whether the media library should download metadata from the web or not. + /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. /// The created command. @@ -36,7 +35,7 @@ public class AddLibraryCommandFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false) { @@ -58,7 +57,7 @@ public class AddLibraryCommandFixture .RuleFor(x => x.CoverImage, f => coverImage ?? f.System.FilePath()) .RuleFor(x => x.IsEnabled, isEnabled) .RuleFor(x => x.IsLocked, isLocked) - .RuleFor(x => x.DownloadMetadataFromWeb, downloadMetadataFromWeb) + .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs index 2bdddac8..284c8d6d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandFixture.cs @@ -27,7 +27,7 @@ public class UpdateLibraryCommandFixture /// Optional. The cover image path of the media library. /// Whether the media library is enabled or not. /// Whether the media library is locked or not. - /// Whether the media library should download metadata from the web or not. + /// Whether the media library should download metadata from the web or not. /// Whether the metadata should be saved in the media directories or not. /// Whether unchanged directories should be skipped during a scan or not. /// The created command. @@ -40,7 +40,7 @@ public class UpdateLibraryCommandFixture string? coverImage = null, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = true, bool shouldSkipUnchangedDirectoriesDuringScan = false) { @@ -66,7 +66,7 @@ public class UpdateLibraryCommandFixture .RuleFor(x => x.CoverImage, f => coverImage ?? f.System.FilePath()) .RuleFor(x => x.IsEnabled, isEnabled) .RuleFor(x => x.IsLocked, isLocked) - .RuleFor(x => x.DownloadMetadataFromWeb, downloadMetadataFromWeb) + .RuleFor(x => x.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb) .RuleFor(x => x.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories) .RuleFor(x => x.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan) .Generate(); diff --git a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs index d26b85c7..26814704 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandFixture.cs @@ -19,21 +19,23 @@ public class UpdateUserSettingsCommandFixture ///
/// Optional. Whether pagination is enabled for the user, or not. /// Optional. The number of library items displayed per page when pagination is enabled. - /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. + /// Optional. Whether the "The" prefix is ignored by the alpha picker, or not. /// Optional. Whether the theme data served to this user is cached, or not. /// The created command. public UpdateUserSettingsCommand Create( bool? isPaginationEnabled = null, int? itemsPerPage = null, - bool? ignoreThePrefixForAlphaPicker = null, - bool? isThemeCachingEnabled = null) + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) { return new Faker() - .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default)) + .CustomInstantiator(f => new UpdateUserSettingsCommand(default, default, default, default, default)) .RuleFor(x => x.IsPaginationEnabled, f => isPaginationEnabled ?? f.Random.Bool()) .RuleFor(x => x.ItemsPerPage, f => itemsPerPage ?? f.Random.Int(1, 100)) - .RuleFor(x => x.IgnoreThePrefixForAlphaPicker, f => ignoreThePrefixForAlphaPicker ?? f.Random.Bool()) + .RuleFor(x => x.ShouldIgnoreThePrefixForAlphaPicker, f => shouldIgnoreThePrefixForAlphaPicker ?? f.Random.Bool()) .RuleFor(x => x.IsThemeCachingEnabled, f => isThemeCachingEnabled ?? f.Random.Bool()) + .RuleFor(x => x.ShouldAggregateMetadataWhenMissing, f => shouldAggregateMetadataWhenMissing ?? f.Random.Bool()) .Generate(); } diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs index d297d071..b48be3f2 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/AddLibraryRequestFixture.cs @@ -1,7 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Bogus; using Lumina.Contracts.Requests.MediaLibrary.Management; -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -26,7 +25,7 @@ public class AddLibraryRequestFixture /// Optional. The path of the image file used as the cover. /// Optional. Whether the media library is enabled. /// Optional. Whether the media library is locked. - /// Optional. Whether metadata should be downloaded from the web. + /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. /// The created . @@ -37,7 +36,7 @@ public class AddLibraryRequestFixture string? coverImage = null, bool? isEnabled = null, bool? isLocked = null, - bool? downloadMetadataFromWeb = null, + bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null) { @@ -48,7 +47,7 @@ public class AddLibraryRequestFixture coverImage ?? null, isEnabled ?? _faker.Random.Bool(), isLocked ?? _faker.Random.Bool(), - downloadMetadataFromWeb ?? _faker.Random.Bool(), + canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool() ); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs index ebdd308b..ca1bd352 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/Management/UpdateLibraryRequestFixture.cs @@ -28,7 +28,7 @@ public class UpdateLibraryRequestFixture /// Optional. The path of the image file used as the cover. /// Optional. Whether the media library is enabled. /// Optional. Whether the media library is locked. - /// Optional. Whether metadata should be downloaded from the web. + /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. /// The created . @@ -41,7 +41,7 @@ public class UpdateLibraryRequestFixture string? coverImage = null, bool? isEnabled = null, bool? isLocked = null, - bool? downloadMetadataFromWeb = null, + bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null) { @@ -54,7 +54,7 @@ public class UpdateLibraryRequestFixture coverImage ?? null, isEnabled ?? _faker.Random.Bool(), isLocked ?? _faker.Random.Bool(), - downloadMetadataFromWeb ?? _faker.Random.Bool(), + canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool() ); diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs new file mode 100644 index 00000000..f2f99c6f --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdateUserSettingsRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Whether pagination is enabled for the user. + /// The number of library items displayed per page when pagination is enabled. + /// Whether the "The" prefix is ignored by the alpha picker. + /// Whether the theme data served to this user is cached. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// The created . + public UpdateUserSettingsRequest Create( + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) + { + return new UpdateUserSettingsRequest( + isPaginationEnabled ?? _faker.Random.Bool(), + itemsPerPage ?? _faker.Random.Int(1, 100), + shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), + isThemeCachingEnabled ?? _faker.Random.Bool(), + shouldAggregateMetadataWhenMissing ?? _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/MediaLibrary/Management/LibraryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs index c3402218..06493766 100644 --- a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/Management/LibraryResponseFixture.cs @@ -29,7 +29,7 @@ public class LibraryResponseFixture /// Optional. The path of the image file used as the cover of the library. /// Optional. Whether the media library is enabled. /// Optional. Whether the media library is locked. - /// Optional. Whether metadata should be downloaded from the web. + /// Optional. Whether metadata should be downloaded from the web. /// Optional. Whether metadata should be saved in the media directories. /// Optional. Whether unchanged directories should be skipped during scan. /// Optional. The date and time when the library was created. @@ -44,7 +44,7 @@ public class LibraryResponseFixture string? coverImage = null, bool? isEnabled = null, bool? isLocked = null, - bool? downloadMetadataFromWeb = null, + bool? canDownloadMetadataFromWeb = null, bool? shouldSaveMetadataInMediaDirectories = null, bool? shouldSkipUnchangedDirectoriesDuringScan = null, DateTime? createdOnUtc = null, @@ -59,7 +59,7 @@ public class LibraryResponseFixture coverImage, isEnabled ?? _faker.Random.Bool(), isLocked ?? _faker.Random.Bool(), - downloadMetadataFromWeb ?? _faker.Random.Bool(), + canDownloadMetadataFromWeb ?? _faker.Random.Bool(), shouldSaveMetadataInMediaDirectories ?? _faker.Random.Bool(), shouldSkipUnchangedDirectoriesDuringScan ?? _faker.Random.Bool(), createdOnUtc ?? _faker.Date.Past().ToUniversalTime(), diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.cs new file mode 100644 index 00000000..7b9e2c5a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Plugins/LibraryMetadataProviderResponseFixture.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 LibraryMetadataProviderResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the plugin providing the metadata. + /// Optional. The display name of the metadata provider. + /// Optional. Whether the metadata provider is enabled for the media library. + /// Optional. The rank of the metadata provider. + /// The created . + public LibraryMetadataProviderResponse Create( + Guid? pluginId = null, + string? name = null, + bool? isEnabled = null, + int? rank = null) + { + return new LibraryMetadataProviderResponse( + 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.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs new file mode 100644 index 00000000..7ebc342b --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/UserSettingsResponseFixture.cs @@ -0,0 +1,56 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UserSettingsResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the user that owns these settings. + /// Optional. Whether pagination is enabled for the user. + /// Optional. The number of library items displayed per page when pagination is enabled. + /// Optional. Whether the "The" prefix is ignored by the alpha picker. + /// Optional. Whether the theme data served to this user is cached. + /// Optional. Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. + /// The created . + public UserSettingsResponse Create( + Guid? userId = null, + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) + { + return new UserSettingsResponse( + userId ?? Guid.NewGuid(), + isPaginationEnabled ?? _faker.Random.Bool(), + itemsPerPage ?? _faker.Random.Int(1, 100), + shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), + isThemeCachingEnabled ?? _faker.Random.Bool(), + shouldAggregateMetadataWhenMissing ?? _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.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs index c438f06b..449396f2 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryFixture.cs @@ -35,7 +35,7 @@ public class LibraryFixture /// Whether to include a cover image or not. /// Whether the library is enabled. /// Whether the library is locked. - /// Whether metadata download from the web is enabled. + /// Whether metadata download from the web is enabled. /// Whether metadata should be saved in the media directories. /// Whether unchanged directories should be skipped during scan. /// Optional. The scan Ids associated with the library. @@ -50,7 +50,7 @@ public class LibraryFixture bool includeCoverImage = true, bool isEnabled = true, bool isLocked = false, - bool downloadMetadataFromWeb = true, + bool canDownloadMetadataFromWeb = true, bool shouldSaveMetadataInMediaDirectories = false, bool shouldSkipUnchangedDirectoriesDuringScan = false, IEnumerable? scanIds = null) @@ -75,7 +75,7 @@ public class LibraryFixture resolvedCoverImage, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, resolvedScanIds @@ -89,7 +89,7 @@ public class LibraryFixture resolvedCoverImage, isEnabled, isLocked, - downloadMetadataFromWeb, + canDownloadMetadataFromWeb, shouldSaveMetadataInMediaDirectories, shouldSkipUnchangedDirectoriesDuringScan, resolvedScanIds diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs index 89134b4e..6f15968e 100644 --- a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsFixture.cs @@ -22,22 +22,25 @@ public class UserSettingsFixture /// Optional. The Id of the user that owns the settings. /// Whether pagination is enabled for the user. /// The number of library items displayed per page when pagination is enabled. - /// Whether the "The" prefix of library item titles is ignored by the alpha picker. + /// Whether the "The" prefix of library item titles is ignored by the alpha picker. /// Whether the theme data served to this user is cached. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. /// The created . public UserSettings Create( Guid? userId = null, bool isPaginationEnabled = true, int itemsPerPage = 48, - bool ignoreThePrefixForAlphaPicker = false, - bool isThemeCachingEnabled = true) + bool shouldIgnoreThePrefixForAlphaPicker = false, + bool isThemeCachingEnabled = true, + bool shouldAggregateMetadataWhenMissing = false) { Result settings = UserSettings.Create( userId is null ? UserId.CreateUnique() : UserId.Create(userId.Value), isPaginationEnabled, itemsPerPage, - ignoreThePrefixForAlphaPicker, - isThemeCachingEnabled); + shouldIgnoreThePrefixForAlphaPicker, + isThemeCachingEnabled, + shouldAggregateMetadataWhenMissing); return settings.Value; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs index b6a98ac1..bf1d8f30 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/LibraryDtoFixture.cs @@ -15,6 +15,8 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; [ExcludeFromCodeCoverage] public class LibraryDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// @@ -26,16 +28,15 @@ public class LibraryDtoFixture /// A configured instance. public LibraryDto Create(Guid? id = null, string? title = null, string? libraryType = null, bool? isEnabled = null, List? contentLocations = null) { - Faker faker = new(); return new LibraryDto { Id = id ?? Guid.NewGuid(), UserId = Guid.NewGuid(), - Title = title ?? faker.Commerce.Department(), - LibraryType = libraryType ?? faker.PickRandom("Book", "Video", "Photo"), - CoverImage = faker.Image.PicsumUrl(), - ContentLocations = contentLocations ?? [faker.System.DirectoryPath()], - IsEnabled = isEnabled ?? faker.Random.Bool() + Title = title ?? _faker.Commerce.Department(), + LibraryType = libraryType ?? _faker.PickRandom("Book", "Video", "Photo"), + CoverImage = _faker.Image.PicsumUrl(), + ContentLocations = contentLocations ?? [_faker.System.DirectoryPath()], + IsEnabled = isEnabled ?? _faker.Random.Bool() }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs new file mode 100644 index 00000000..9a040489 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Libraries/ScanLibraryDtoFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Libraries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ScanLibraryDtoFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the media library scan. + /// Optional Id of the scanned media library. + /// A configured instance. + public ScanLibraryDto Create( + Guid? scanId = null, + Guid? libraryId = null) + { + return new ScanLibraryDto + { + ScanId = scanId ?? Guid.NewGuid(), + LibraryId = libraryId ?? Guid.NewGuid() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs new file mode 100644 index 00000000..02c24777 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/LibraryMetadataProviderDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class LibraryMetadataProviderDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the plugin providing the metadata. + /// Optional display name of the metadata provider. + /// Whether the metadata provider is enabled for the media library or not. + /// Optional rank of the metadata provider, determining the order in which providers are tried. + /// A configured instance. + public LibraryMetadataProviderDto Create( + Guid? pluginId = null, + string? name = null, + bool? isEnabled = null, + int? rank = null) + { + return new LibraryMetadataProviderDto + { + PluginId = pluginId ?? Guid.NewGuid(), + Name = name ?? _faker.Company.CompanyName(), + IsEnabled = isEnabled ?? _faker.Random.Bool(), + Rank = rank ?? _faker.Random.Int(0, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs new file mode 100644 index 00000000..be62805c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingDescriptorDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using Lumina.Presentation.Web.Common.Enums.Plugins; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingDescriptorDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The key of the setting. + /// Optional. The display label of the setting. + /// Optional. The type of the setting. + /// Optional. The default value of the setting. + /// Optional. The list of allowed values of the setting. + /// The created . + public PluginSettingDescriptorDto Create( + string? key = null, + string? label = null, + PluginSettingType? type = null, + string? defaultValue = null, + IReadOnlyList? allowedValues = null) + { + return new PluginSettingDescriptorDto + { + Key = key ?? _faker.Random.String2(4, 32), + Label = label ?? _faker.Commerce.ProductName(), + Type = type ?? _faker.Random.Enum(), + DefaultValue = defaultValue, + AllowedValues = allowedValues + }; + } + + /// + /// 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.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs new file mode 100644 index 00000000..7a06532e --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Plugins/PluginSettingsDtoFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class PluginSettingsDtoFixture +{ + private readonly Faker _faker = new(); + private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional unique identifier of the plugin. + /// Whether to populate the current settings values, or leave them null. + /// Whether to populate the settings schema, or leave it empty. + /// A configured instance. + public PluginSettingsDto Create( + Guid? pluginId = null, + bool includeSettings = true, + bool includeSchema = true) + { + string settingKey = _faker.Lorem.Word(); + return new PluginSettingsDto + { + PluginId = pluginId ?? Guid.NewGuid(), + Schema = includeSchema + ? [_pluginSettingDescriptorDtoFixture.Create(key: settingKey)] + : [], + Settings = includeSettings + ? new Dictionary { [settingKey] = _faker.Lorem.Word() } + : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs index 74311aa5..6d49a13d 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/UserSettingsDtoFixture.cs @@ -15,23 +15,34 @@ namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; [ExcludeFromCodeCoverage] public class UserSettingsDtoFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional identifier of the user that owns the settings. /// Whether pagination is enabled for the user. /// Number of library items displayed per page. - /// Whether the "The" prefix is ignored by the alpha picker. + /// Whether the "The" prefix is ignored by the alpha picker. + /// Whether the theme data served to this user is cached. + /// Whether the metadata of the media library items is aggregated from multiple providers, when fields are missing. /// A configured instance. - public UserSettingsDto Create(Guid? userId = null, bool? isPaginationEnabled = null, int? itemsPerPage = null, bool? ignoreThePrefixForAlphaPicker = null) + public UserSettingsDto Create( + Guid? userId = null, + bool? isPaginationEnabled = null, + int? itemsPerPage = null, + bool? shouldIgnoreThePrefixForAlphaPicker = null, + bool? isThemeCachingEnabled = null, + bool? shouldAggregateMetadataWhenMissing = null) { - Faker faker = new(); return new UserSettingsDto { UserId = userId ?? Guid.NewGuid(), - IsPaginationEnabled = isPaginationEnabled ?? faker.Random.Bool(), - ItemsPerPage = itemsPerPage ?? faker.Random.Int(1, 200), - IgnoreThePrefixForAlphaPicker = ignoreThePrefixForAlphaPicker ?? faker.Random.Bool() + IsPaginationEnabled = isPaginationEnabled ?? _faker.Random.Bool(), + ItemsPerPage = itemsPerPage ?? _faker.Random.Int(1, 200), + ShouldIgnoreThePrefixForAlphaPicker = shouldIgnoreThePrefixForAlphaPicker ?? _faker.Random.Bool(), + IsThemeCachingEnabled = isThemeCachingEnabled ?? _faker.Random.Bool(), + ShouldAggregateMetadataWhenMissing = shouldAggregateMetadataWhenMissing ?? _faker.Random.Bool() }; } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs new file mode 100644 index 00000000..18439e07 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/ReorderLibraryMetadataProvidersRequestFixture.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class ReorderLibraryMetadataProvidersRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional plugin Ids in the new order. + /// A configured instance. + public ReorderLibraryMetadataProvidersRequest Create( + Guid? libraryId = null, + List? pluginIds = null) + { + return new ReorderLibraryMetadataProvidersRequest + { + LibraryId = libraryId ?? Guid.NewGuid(), + PluginIds = pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs new file mode 100644 index 00000000..4ee3fa19 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/SetLibraryMetadataProviderEnabledRequestFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Plugins; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; + +/// +/// Fixture class for generating test data. +/// +[ExcludeFromCodeCoverage] +public class SetLibraryMetadataProviderEnabledRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional identifier of the media library. + /// Optional identifier of the plugin. + /// Optional value indicating whether the metadata provider is enabled. + /// A configured instance. + public SetLibraryMetadataProviderEnabledRequest Create( + Guid? libraryId = null, + Guid? pluginId = null, + bool? isEnabled = null) + { + return new SetLibraryMetadataProviderEnabledRequest + { + LibraryId = libraryId ?? Guid.NewGuid(), + PluginId = pluginId ?? Guid.NewGuid(), + IsEnabled = isEnabled ?? _faker.Random.Bool() + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs index 725afc87..973f54ea 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Plugins/UpdatePluginSettingsRequestFixture.cs @@ -15,19 +15,22 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins; [ExcludeFromCodeCoverage] public class UpdatePluginSettingsRequestFixture { + private readonly Faker _faker = new(); + /// /// Creates a new instance with randomized test data. /// /// Optional identifier of the plugin. /// Optional dictionary of settings. /// A configured instance. - public UpdatePluginSettingsRequest Create(Guid? pluginId = null, Dictionary? settings = null) + public UpdatePluginSettingsRequest Create( + Guid? pluginId = null, + Dictionary? settings = null) { - Faker faker = new(); return new UpdatePluginSettingsRequest { PluginId = pluginId ?? Guid.NewGuid(), - Settings = settings ?? new Dictionary { [faker.Lorem.Word()] = faker.Lorem.Word() } + Settings = settings ?? new Dictionary { [_faker.Lorem.Word()] = _faker.Lorem.Word() } }; } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index 4f54bb96..1c913cff 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -1,8 +1,10 @@ #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.Responses.Plugins; using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetLibraryMetadataProviders; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.Extensions.DependencyInjection; @@ -33,6 +35,8 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -56,11 +60,12 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture + /// 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. - /// The Id of the user that owns the data. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB, Guid userId) + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginIdA, Guid pluginIdB) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginIdA, - IsEnabled = true, - Rank = 1, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginIdB, - IsEnabled = false, - Rank = 2, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdA, rank: 1, isEnabled: true)); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginIdB, rank: 2, isEnabled: false)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index 6823f24b..c860ca92 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -1,6 +1,5 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Presentation.Api.Core.Endpoints.Plugins.GetPluginSettings; @@ -10,7 +9,6 @@ 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; @@ -34,6 +32,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -105,36 +104,10 @@ public class GetPluginSettingsEndpointTests : IClassFixture(); - Guid userId = GetCurrentUserId(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = name, - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: 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. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs index c7f44e09..e71c05ac 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -1,8 +1,12 @@ #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.ReorderLibraryMetadataProviders; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; using Microsoft.EntityFrameworkCore; @@ -14,8 +18,6 @@ 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 @@ -29,6 +31,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -52,15 +57,16 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture + /// 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 Id of the user that owns the data. /// The rank of the provider. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, Guid userId, int rank) + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, int rank) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginId, - IsEnabled = true, - Rank = rank, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs index d55d16e4..0eb07d2a 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -1,23 +1,22 @@ #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.Contracts.Responses.Plugins; using Lumina.DataAccess.Core.UoW; -using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Presentation.Api.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; 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.Text.Json; -using System.Text.Json.Serialization; using System.Threading.Tasks; #endregion @@ -31,11 +30,9 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -59,13 +56,11 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture + /// 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 Id of the user that owns the data. /// Whether the provider is enabled. /// The rank of the provider. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, Guid userId, bool isEnabled, int rank) + private async Task SeedConfigurationAsync(Guid libraryId, Guid pluginId, bool isEnabled, int rank) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = pluginId, - IsEnabled = isEnabled, - Rank = rank, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: pluginId, rank: rank, isEnabled: isEnabled)); await dbContext.SaveChangesAsync(); } diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 38398544..bad7f5b0 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; -using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +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.Plugins; @@ -12,7 +13,6 @@ 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; @@ -36,6 +36,8 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -61,9 +63,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { ["Key1"] = "Value1" } + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: pluginId, + settings: new Dictionary { ["Key1"] = "Value1" } ); // Act @@ -85,9 +87,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { ["Key1"] = "Value1" } + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: pluginId, + settings: new Dictionary { ["Key1"] = "Value1" } ); // Act @@ -118,36 +120,10 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture(); - Guid userId = GetCurrentUserId(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = name, - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: name, loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: 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. /// diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 50301fd3..1735ed4b 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -1,13 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; -using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; @@ -27,6 +26,7 @@ public class GetUserSettingsEndpointTests : IClassFixture(); Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; - UserSettingsEntity settings = new() - { - Id = Guid.NewGuid(), - UserId = userId, - IsPaginationEnabled = false, - ItemsPerPage = 24, - IgnoreThePrefixForAlphaPicker = true - }; + UserSettingsEntity settings = _userSettingsEntityFixture.Create( + userId: userId, + isPaginationEnabled: false, + itemsPerPage: 24, + shouldIgnoreThePrefixForAlphaPicker: true); dbContext.UserSettings.Add(settings); await dbContext.SaveChangesAsync(); diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 105106e8..d3a77004 100644 --- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.DataAccess.Core.UoW; using Lumina.Presentation.Api.IntegrationTests.Common.Setup; @@ -28,6 +29,7 @@ public class UpdateUserSettingsEndpointTests : IClassFixture + diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..19fa67c2 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Contains integration tests for the /{culture}/tools/settings/api-get-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserSettings_WhenCalledByAuthenticatedUser_ShouldReturnSettingsFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + UserSettingsDto expectedSettings = _userSettingsDtoFixture.Create(itemsPerPage: 24); + _apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings", expectedSettings); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(24, json.RootElement.GetProperty("data").GetProperty("itemsPerPage").GetInt32()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings"); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs new file mode 100644 index 00000000..d5a1c00b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings; + +/// +/// Contains integration tests for the /{culture}/tools/settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SettingsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SettingsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SettingsView_WhenCalledByAuthenticatedUser_ShouldRenderSettingsPage() + { + // Arrange + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/tools/settings"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + string content = await response.Content.ReadAsStringAsync(); + Assert.Contains("user-settings-form", content); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..be26d418 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Requests.Common; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Contains integration tests for the /{culture}/tools/settings/api-update-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledByAuthenticatedUser_ShouldUpdateSettings() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings", _ => new EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + UserSettingsDto settings = _userSettingsDtoFixture.Create(isThemeCachingEnabled: true); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdateSettingsRequest(settings, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); + } + + /// + /// Builds the update request that sends the given to the user settings endpoint. + /// + /// The user settings to send. + /// The antiforgery token to include in the request. + /// The configured update request. + private static HttpRequestMessage CreateUpdateSettingsRequest(UserSettingsDto settings, string antiforgeryToken) + { + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings") + { + Content = JsonContent.Create(settings) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return updateRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index d215cd92..f8467d7e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -1,19 +1,14 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; +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.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetLibraryMetadataProviders; @@ -30,6 +25,8 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -74,7 +71,7 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture(); Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); return libraryId; } @@ -121,23 +108,12 @@ public class GetLibraryMetadataProvidersEndpointTests : IClassFixture for the library identified by . ///
/// The Id of the media library. - /// The Id of the user that owns the data. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid userId) + private async Task SeedConfigurationAsync(Guid libraryId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = Guid.NewGuid(), - IsEnabled = true, - Rank = 1, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index 0dce62e1..a6f962e6 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -1,18 +1,13 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.GetPluginSettings; @@ -29,6 +24,7 @@ public class GetPluginSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly PluginEntityFixture _pluginEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -71,8 +67,8 @@ public class GetPluginSettingsEndpointTests : IClassFixture // Arrange // authenticate with an admin user and seed a plugin, so a valid pluginId would reach the handler HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - await SeedPluginAsync(userId); + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + await SeedPluginAsync(); // Act HttpResponseMessage response = await client.GetAsync($"/api/v1/plugins/{Uri.EscapeDataString(maliciousPluginId)}/settings"); @@ -91,28 +87,14 @@ public class GetPluginSettingsEndpointTests : IClassFixture } /// - /// Seeds a created by . + /// Seeds a created by the authenticated admin user. /// - /// The Id of the creator. /// A task representing the asynchronous operation. - private async Task SeedPluginAsync(Guid userId) + private async Task SeedPluginAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.Plugins.Add(new PluginEntity - { - Id = Guid.NewGuid(), - Name = "Test Plugin", - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(name: "Test Plugin", loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs index 26964523..aa6a983e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersEndpointTests.cs @@ -1,21 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; +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.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryMetadataProviders; @@ -32,6 +28,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -48,9 +47,9 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture(); Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); return libraryId; } @@ -132,24 +121,13 @@ public class ReorderLibraryMetadataProvidersEndpointTests : IClassFixture for the library identified by . /// /// The Id of the media library. - /// The Id of the user that owns the data. /// The rank of the provider. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid userId, int rank) + private async Task SeedConfigurationAsync(Guid libraryId, int rank) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = Guid.NewGuid(), - IsEnabled = true, - Rank = rank, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs index d25358e1..62ba2bcc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledEndpointTests.cs @@ -1,21 +1,17 @@ #region ========================================================================= USING ===================================================================================== -using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; -using Lumina.Application.Common.DataAccess.Entities.Plugins; +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.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryMetadataProviderEnabled; @@ -32,6 +28,9 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture /// Initializes a new instance of the class. @@ -49,11 +48,7 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture(); Guid libraryId = Guid.NewGuid(); - dbContext.Libraries.Add(new LibraryEntity - { - Id = libraryId, - UserId = userId, - Title = "Test Library", - LibraryType = LibraryType.EBook, - ContentLocations = [], - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: [])); await dbContext.SaveChangesAsync(); return libraryId; } @@ -134,23 +115,12 @@ public class SetLibraryMetadataProviderEnabledEndpointTests : IClassFixture for the library identified by . ///
/// The Id of the media library. - /// The Id of the user that owns the data. /// A task representing the asynchronous operation. - private async Task SeedConfigurationAsync(Guid libraryId, Guid userId) + private async Task SeedConfigurationAsync(Guid libraryId) { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); - dbContext.LibraryMetadataProviderConfigurations.Add(new LibraryMetadataProviderConfigurationEntity - { - Id = Guid.NewGuid(), - LibraryId = libraryId, - PluginId = Guid.NewGuid(), - IsEnabled = false, - Rank = 1, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.LibraryMetadataProviderConfigurations.Add(_libraryMetadataProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false)); await dbContext.SaveChangesAsync(); } } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs index 0a63870d..e0b4ebd4 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Plugins/UpdatePluginSettings/UpdatePluginSettingsEndpointTests.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.Plugins; +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.Plugins; @@ -7,14 +9,10 @@ using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; -using System.Threading.Tasks; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.UpdatePluginSettings; @@ -31,6 +29,8 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly UpdatePluginSettingsRequestFixture _updatePluginSettingsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -47,9 +47,9 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { // Arrange string pluginId = Guid.NewGuid().ToString(); - UpdatePluginSettingsRequest request = new( - PluginId: Guid.NewGuid(), - Settings: new Dictionary { ["Key"] = "Value" } + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: Guid.NewGuid(), + settings: new Dictionary { ["Key"] = "Value" } ); // Act @@ -76,11 +76,11 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture { // Arrange HttpClient client = _apiFactory.CreateClient(); - Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); - Guid pluginId = await SeedPluginAsync(userId); - UpdatePluginSettingsRequest request = new( - PluginId: pluginId, - Settings: new Dictionary { ["Key"] = maliciousValue } + await _apiFactory.CreateAndAuthenticateAdminUserAsync(client); + Guid pluginId = await SeedPluginAsync(); + UpdatePluginSettingsRequest request = _updatePluginSettingsRequestFixture.Create( + pluginId: pluginId, + settings: new Dictionary { ["Key"] = maliciousValue } ); // Act @@ -107,29 +107,15 @@ public class UpdatePluginSettingsEndpointTests : IClassFixture } /// - /// Seeds a created by . + /// Seeds a created by the authenticated admin user. /// - /// The Id of the creator. /// The Id of the seeded plugin. - private async Task SeedPluginAsync(Guid userId) + private async Task SeedPluginAsync() { using IServiceScope scope = _apiFactory.Services.CreateScope(); LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid pluginId = Guid.NewGuid(); - dbContext.Plugins.Add(new PluginEntity - { - Id = pluginId, - Name = "Test Plugin", - Author = "Test Author", - Version = "1.0.0", - Description = "A test plugin.", - LoadStatus = PluginLoadStatus.Loaded, - LoadError = null, - SettingsJson = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow, - UpdatedBy = null - }); + dbContext.Plugins.Add(_pluginEntityFixture.Create(id: pluginId, name: "Test Plugin", loadStatus: PluginLoadStatus.Loaded, includeSettingsJson: false)); await dbContext.SaveChangesAsync(); return pluginId; } diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 9baeba1c..8055436e 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -1,16 +1,15 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; @@ -31,6 +30,8 @@ public class GetUserSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -95,20 +96,12 @@ public class GetUserSettingsEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 45193858..b2dcba4a 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.UsersManagement; -using Lumina.Contracts.Requests.Authentication; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Authentication; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.Contracts.Responses.Authentication; using Lumina.DataAccess.Core.UoW; @@ -8,10 +10,8 @@ using Lumina.Infrastructure.Core.Security; using Lumina.Presentation.Api.SecurityTests.Common.Setup; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; -using System; using System.Diagnostics.CodeAnalysis; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; @@ -32,6 +32,9 @@ public class UpdateUserSettingsEndpointTests : IClassFixture { PropertyNameCaseInsensitive = true }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly LoginRequestFixture _loginRequestFixture = new(); + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -47,11 +50,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture public async Task UpdateUserSettings_WhenUnauthorized_ShouldReturnUnauthorizedResult() { // Arrange - UpdateUserSettingsRequest request = new( - IsPaginationEnabled: true, - ItemsPerPage: 48, - IgnoreThePrefixForAlphaPicker: false, - IsThemeCachingEnabled: true + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: 48, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false ); // Act @@ -77,11 +81,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); await CreateAndAuthenticateUserAsync(client); - UpdateUserSettingsRequest request = new( - IsPaginationEnabled: true, - ItemsPerPage: int.MaxValue, - IgnoreThePrefixForAlphaPicker: false, - IsThemeCachingEnabled: true + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: int.MaxValue, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false ); // Act @@ -100,11 +105,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture // Arrange HttpClient client = _apiFactory.CreateClient(); await CreateAndAuthenticateUserAsync(client); - UpdateUserSettingsRequest request = new( - IsPaginationEnabled: true, - ItemsPerPage: int.MinValue, - IgnoreThePrefixForAlphaPicker: false, - IsThemeCachingEnabled: true + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: int.MinValue, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false ); // Act @@ -132,20 +138,12 @@ public class UpdateUserSettingsEndpointTests : IClassFixture LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); Guid userId = Guid.NewGuid(); string username = $"testuser_{Guid.NewGuid()}"; - dbContext.Users.Add(new UserEntity - { - Id = userId, - Username = username, - Password = _hashService.HashString("TestPass123!"), - Libraries = [], - UserPermissions = [], - UserRole = null, - CreatedBy = userId, - CreatedOnUtc = DateTime.UtcNow - }); + UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: _hashService.HashString("TestPass123!")); + user.TotpSecret = null; + dbContext.Users.Add(user); await dbContext.SaveChangesAsync(); - HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(username, "TestPass123!")); + HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", _loginRequestFixture.Create(username: username, password: "TestPass123!")); string content = await loginResponse.Content.ReadAsStringAsync(); LoginResponse? loginResult = JsonSerializer.Deserialize(content, _jsonOptions); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", loginResult!.Token); diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs new file mode 100644 index 00000000..191e3e59 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.GetUserSettings; + +/// +/// Contains security tests for the /{culture}/tools/settings/api-get-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class GetUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetUserSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-user-settings"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs new file mode 100644 index 00000000..2f45ecdf --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/SettingsViewEndpointTests.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings; + +/// +/// Contains security tests for the /{culture}/tools/settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class SettingsViewEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public SettingsViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task SettingsView_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/tools/settings"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs new file mode 100644 index 00000000..897dc53a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -0,0 +1,76 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdateUserSettings; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.UpdateUserSettings; + +/// +/// Contains security tests for the /{culture}/tools/settings/api-update-user-settings route served by the class. +/// +[ExcludeFromCodeCoverage] +public class UpdateUserSettingsEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly UserSettingsDtoFixture _userSettingsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdateUserSettingsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings") + { + Content = JsonContent.Create(_userSettingsDtoFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); + } + + [Fact] + public async Task UpdateUserSettings_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-user-settings") + { + Content = JsonContent.Create(_userSettingsDtoFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings"); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs index 95c91ab8..f3971046 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/AddMediaLibraryRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System.Diagnostics.CodeAnalysis; @@ -14,20 +15,22 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class AddMediaLibraryRequestMappingTests { + private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - AddLibraryRequest request = new( - "My Library", - "Book", - ["C:/Books", "D:/Media/Books"], - "D:/poster.jpg", - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: ["C:/Books", "D:/Media/Books"], + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act @@ -41,7 +44,7 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.CoverImage, result.CoverImage); Assert.Equal(request.IsEnabled, result.IsEnabled); Assert.Equal(request.IsLocked, result.IsLocked); - Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb); + Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); } @@ -53,16 +56,16 @@ public class AddMediaLibraryRequestMappingTests public void ToCommand_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) { // Arrange - AddLibraryRequest request = new( - "My Library", - libraryType.ToString(), - ["C:/Media"], - "D:/poster.jpg", - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: libraryType.ToString(), + contentLocations: ["C:/Media"], + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act @@ -76,7 +79,7 @@ public class AddMediaLibraryRequestMappingTests Assert.Equal(request.CoverImage, result.CoverImage); Assert.Equal(request.IsEnabled, result.IsEnabled); Assert.Equal(request.IsLocked, result.IsLocked); - Assert.Equal(request.DownloadMetadataFromWeb, result.DownloadMetadataFromWeb); + Assert.Equal(request.CanDownloadMetadataFromWeb, result.CanDownloadMetadataFromWeb); Assert.Equal(request.ShouldSaveMetadataInMediaDirectories, result.ShouldSaveMetadataInMediaDirectories); } @@ -92,16 +95,16 @@ public class AddMediaLibraryRequestMappingTests "F:/Reading Material" ]; - AddLibraryRequest request = new( - "My Library", - "Book", - contentLocations, - "D:/poster.jpg", - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: contentLocations, + coverImage: "D:/poster.jpg", + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act @@ -122,16 +125,16 @@ public class AddMediaLibraryRequestMappingTests "D:/Books" ]; - AddLibraryRequest request = new( - "My Library", - "Book", - contentLocations, - null, - true, - false, - true, - false, - false + AddLibraryRequest request = _addLibraryRequestFixture.Create( + title: "My Library", + libraryType: "Book", + contentLocations: contentLocations, + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: false ); // Act diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs index 455d609d..44bf69ac 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryEntityMappingTests.cs @@ -1,9 +1,9 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using System; using System.Diagnostics.CodeAnalysis; using System.Linq; @@ -17,28 +17,17 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class LibraryEntityMappingTests { + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + [Fact] public void ToResponse_WhenMappingValidLibraryEntity_ShouldMapCorrectly() { // Arrange - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = - [ - new() { Path = "C:/Books" }, - new() { Path = "D:/Media/Books" } - ], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null, - LibraryScans = [] - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books", "D:/Media/Books"], + coverImage: "D:/myPoster.jpg"); // Act LibraryResponse result = entity.ToResponse(); @@ -63,19 +52,11 @@ public class LibraryEntityMappingTests public void ToResponse_WhenMappingDifferentLibraryTypes_ShouldMapCorrectly(LibraryType libraryType) { // Arrange - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = libraryType, - ContentLocations = [new() { Path = "C:/Media" }], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: libraryType, + contentLocations: ["C:/Media"], + coverImage: "D:/myPoster.jpg"); // Act LibraryResponse result = entity.ToResponse(); @@ -89,25 +70,11 @@ public class LibraryEntityMappingTests public void ToResponse_WhenMappingMultipleContentLocations_ShouldMapAllCorrectly() { // Arrange - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = - [ - new() { Path = "C:/Media/Books" }, - new() { Path = "D:/Books" }, - new() { Path = "E:/Digital Library/Books" }, - new() { Path = "F:/Reading Material" } - ], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = null, - UpdatedBy = null - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Media/Books", "D:/Books", "E:/Digital Library/Books", "F:/Reading Material"], + coverImage: "D:/myPoster.jpg"); // Act LibraryResponse result = entity.ToResponse(); @@ -122,19 +89,12 @@ public class LibraryEntityMappingTests { // Arrange DateTime updated = DateTime.UtcNow.AddDays(-1); - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = [new() { Path = "C:/Books" }], - CoverImage = "D:/myPoster.jpg", - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = updated, - UpdatedBy = Guid.NewGuid() - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"], + coverImage: "D:/myPoster.jpg"); + entity.UpdatedOnUtc = updated; // Act LibraryResponse result = entity.ToResponse(); @@ -149,19 +109,12 @@ public class LibraryEntityMappingTests { // Arrange DateTime updated = DateTime.UtcNow.AddDays(-1); - LibraryEntity entity = new() - { - Id = Guid.NewGuid(), - UserId = Guid.NewGuid(), - Title = "My Library", - LibraryType = LibraryType.Book, - ContentLocations = [new() { Path = "C:/Books" }], - CoverImage = null, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedOnUtc = updated, - UpdatedBy = Guid.NewGuid() - }; + LibraryEntity entity = _libraryEntityFixture.Create( + title: "My Library", + libraryType: LibraryType.Book, + contentLocations: ["C:/Books"]); + entity.CoverImage = null; + entity.UpdatedOnUtc = updated; // Act LibraryResponse result = entity.ToResponse(); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs index 0a340076..28e95ff7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/Management/LibraryMappingTests.cs @@ -3,7 +3,6 @@ using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.Mapping.Common.Metadata; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Common; -using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; @@ -34,7 +33,7 @@ public class LibraryMappingTests coverImage: "D:/myPoster.jpg", isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, scanIds: [Guid.NewGuid()]); @@ -54,7 +53,7 @@ public class LibraryMappingTests Assert.Equal(library.UpdatedOnUtc, result.UpdatedOnUtc); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); - Assert.True(result.DownloadMetadataFromWeb); + Assert.True(result.CanDownloadMetadataFromWeb); Assert.False(result.ShouldSaveMetadataInMediaDirectories); Assert.Equal(library.ScanIds.Select(scanId => scanId.Value), result.LibraryScans.Select(libraryScan => libraryScan.Id)); } @@ -93,7 +92,7 @@ public class LibraryMappingTests coverImage: "D:/myPoster.jpg", isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false); // Act @@ -105,7 +104,7 @@ public class LibraryMappingTests Assert.Equal(library.CoverImage, result.CoverImage); Assert.True(result.IsEnabled); Assert.False(result.IsLocked); - Assert.True(result.DownloadMetadataFromWeb); + Assert.True(result.CanDownloadMetadataFromWeb); Assert.False(result.ShouldSaveMetadataInMediaDirectories); } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs index 3a7aa785..0e8ec644 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdateUserSettingsRequestMappingTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.Mapping.UsersManagement.Users; using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using System.Diagnostics.CodeAnalysis; #endregion @@ -13,11 +14,19 @@ namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; [ExcludeFromCodeCoverage] public class UpdateUserSettingsRequestMappingTests { + private readonly UpdateUserSettingsRequestFixture _requestFixture = new(); + [Fact] public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() { // Arrange - UpdateUserSettingsRequest request = new(IsPaginationEnabled: true, ItemsPerPage: 48, IgnoreThePrefixForAlphaPicker: false, IsThemeCachingEnabled: true); + UpdateUserSettingsRequest request = _requestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: 48, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false + ); // Act UpdateUserSettingsCommand result = request.ToCommand(); @@ -26,7 +35,7 @@ public class UpdateUserSettingsRequestMappingTests Assert.NotNull(result); Assert.Equal(request.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(request.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(request.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(request.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(request.IsThemeCachingEnabled, result.IsThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs index f87c367b..de7f9d33 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsEntityMappingTests.cs @@ -33,7 +33,7 @@ public class UserSettingsEntityMappingTests Assert.Equal(entity.UserId, result.Value.UserId.Value); Assert.Equal(entity.IsPaginationEnabled, result.Value.IsPaginationEnabled); Assert.Equal(entity.ItemsPerPage, result.Value.ItemsPerPage); - Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(entity.IsThemeCachingEnabled, result.Value.IsThemeCachingEnabled); } @@ -51,7 +51,7 @@ public class UserSettingsEntityMappingTests Assert.Equal(entity.UserId, result.UserId); Assert.Equal(entity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(entity.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(entity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(entity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); Assert.Equal(entity.IsThemeCachingEnabled, result.IsThemeCachingEnabled); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs index a9241202..4694e62f 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UserSettingsMappingTests.cs @@ -34,7 +34,7 @@ public class UserSettingsMappingTests Assert.Equal(userId, result.UserId); Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] @@ -52,6 +52,6 @@ public class UserSettingsMappingTests Assert.Equal(userId, result.UserId); Assert.Equal(domainEntity.IsPaginationEnabled, result.IsPaginationEnabled); Assert.Equal(domainEntity.ItemsPerPage, result.ItemsPerPage); - Assert.Equal(domainEntity.IgnoreThePrefixForAlphaPicker, result.IgnoreThePrefixForAlphaPicker); + Assert.Equal(domainEntity.ShouldIgnoreThePrefixForAlphaPicker, result.ShouldIgnoreThePrefixForAlphaPicker); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs index 5d0e1272..a26e0808 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/ReorderLibraryMetadataProviders/ReorderLibraryMetadataProvidersCommandHandlerTests.cs @@ -2,17 +2,22 @@ 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.ReorderLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.ReorderLibraryMetadataProviders; 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 System.Diagnostics.CodeAnalysis; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.ReorderLibraryMetadataProviders; @@ -25,8 +30,13 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly ReorderLibraryMetadataProvidersCommandHandler _sut; + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly ReorderLibraryMetadataProvidersCommandFixture _reorderLibraryMetadataProvidersCommandFixture = new(); + private readonly Guid _userId; /// /// Initializes a new instance of the class. @@ -36,10 +46,18 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.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 ReorderLibraryMetadataProvidersCommandHandler(_mockUnitOfWork, _mockValidator); + _sut = new ReorderLibraryMetadataProvidersCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); } [Fact] @@ -47,16 +65,15 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests { // Arrange Guid libraryId = Guid.NewGuid(); - LibraryMetadataProviderConfigurationEntityFixture configurationFixture = new(); - LibraryMetadataProviderConfigurationEntity firstProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 2); - LibraryMetadataProviderConfigurationEntity secondProvider = configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity firstProvider = _configurationEntityFixture.Create(libraryId, Guid.NewGuid(), 2); + LibraryMetadataProviderConfigurationEntity 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(new ReorderLibraryMetadataProvidersCommand(libraryId, [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); + Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [secondProvider.PluginId, firstProvider.PluginId]), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -76,7 +93,7 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdsListCannotBeEmpty]); // Act - Result result = await _sut.HandleAsync(new ReorderLibraryMetadataProvidersCommand(libraryId, [Guid.NewGuid()]), CancellationToken.None); + Result result = await _sut.HandleAsync(_reorderLibraryMetadataProvidersCommandFixture.Create(libraryId: libraryId, pluginIds: [Guid.NewGuid()]), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -85,4 +102,42 @@ public class ReorderLibraryMetadataProvidersCommandHandlerTests 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(_reorderLibraryMetadataProvidersCommandFixture.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(_reorderLibraryMetadataProvidersCommandFixture.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()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs index c0a5a097..2fa3c5a7 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/SetLibraryMetadataProviderEnabled/SetLibraryMetadataProviderEnabledCommandHandlerTests.cs @@ -2,16 +2,22 @@ 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.SetLibraryMetadataProviderEnabled; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; 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 System.Diagnostics.CodeAnalysis; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.SetLibraryMetadataProviderEnabled; @@ -24,8 +30,17 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests { private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockConfigurationRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; private readonly IValidator _mockValidator; private readonly SetLibraryMetadataProviderEnabledCommandHandler _sut; + private readonly SetLibraryMetadataProviderEnabledCommandFixture _setLibraryMetadataProviderEnabledCommandFixture = new(); + private readonly Guid _userId; + + /// + /// Fixture for generating test data. + /// + private readonly LibraryMetadataProviderConfigurationEntityFixture _libraryMetadataProviderConfigurationEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -35,10 +50,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests _mockUnitOfWork = Substitute.For(); _mockConfigurationRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.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 SetLibraryMetadataProviderEnabledCommandHandler(_mockUnitOfWork, _mockValidator); + _sut = new SetLibraryMetadataProviderEnabledCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); } [Fact] @@ -55,7 +78,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests .Returns(Result.Updated); // Act - Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -68,24 +91,18 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests public async Task HandleAsync_WhenConfigurationExists_ShouldUpdateItsEnabledState() { // Arrange - LibraryMetadataProviderConfigurationEntity existingConfiguration = new() - { - Id = Guid.NewGuid(), - LibraryId = Guid.NewGuid(), - PluginId = Guid.NewGuid(), - IsEnabled = false, - Rank = 2, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = default, - UpdatedBy = default - }; + LibraryMetadataProviderConfigurationEntity existingConfiguration = _libraryMetadataProviderConfigurationEntityFixture.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(new SetLibraryMetadataProviderEnabledCommand(existingConfiguration.LibraryId, existingConfiguration.PluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: existingConfiguration.LibraryId, pluginId: existingConfiguration.PluginId, isEnabled: true), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -103,7 +120,7 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); // Act - Result result = await _sut.HandleAsync(new SetLibraryMetadataProviderEnabledCommand(libraryId, pluginId, true), CancellationToken.None); + Result result = await _sut.HandleAsync(_setLibraryMetadataProviderEnabledCommandFixture.Create(libraryId: libraryId, pluginId: pluginId, isEnabled: true), CancellationToken.None); // Assert Assert.True(result.IsFailure); @@ -112,4 +129,43 @@ public class SetLibraryMetadataProviderEnabledCommandHandlerTests 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(_setLibraryMetadataProviderEnabledCommandFixture.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(_setLibraryMetadataProviderEnabledCommandFixture.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()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs index 7f172a0d..d2b3ee7e 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Commands/UpdatePluginSettings/UpdatePluginSettingsCommandHandlerTests.cs @@ -3,14 +3,15 @@ using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Commands.UpdatePluginSettings; +using Lumina.Application.Fixtures.Core.Plugins.Commands.UpdatePluginSettings; 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 System.Diagnostics.CodeAnalysis; #endregion namespace Lumina.Application.UnitTests.Core.Plugins.Commands.UpdatePluginSettings; @@ -25,6 +26,7 @@ public class UpdatePluginSettingsCommandHandlerTests private readonly IPluginRepository _mockPluginRepository; private readonly IValidator _mockValidator; private readonly UpdatePluginSettingsCommandHandler _sut; + private readonly UpdatePluginSettingsCommandFixture _updatePluginSettingsCommandFixture = new(); /// /// Initializes a new instance of the class. @@ -50,7 +52,7 @@ public class UpdatePluginSettingsCommandHandlerTests .Returns(Result.Updated); // Act - Result result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + Result result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None); // Assert Assert.False(result.IsFailure); @@ -67,7 +69,7 @@ public class UpdatePluginSettingsCommandHandlerTests _mockValidator.Validate(Arg.Any()).Returns([Errors.Plugins.PluginIdCannotBeEmpty]); // Act - Result result = await _sut.HandleAsync(new UpdatePluginSettingsCommand(pluginId, settings), CancellationToken.None); + Result result = await _sut.HandleAsync(_updatePluginSettingsCommandFixture.Create(pluginId: pluginId, settings: settings), CancellationToken.None); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs index 774a02f9..d2bb4a86 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandlerTests.cs @@ -2,10 +2,15 @@ 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.GetLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Contracts.Responses.Plugins; +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Primitives; using NSubstitute; using System; @@ -13,6 +18,7 @@ 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.GetLibraryMetadataProviders; @@ -26,10 +32,14 @@ public class GetLibraryMetadataProvidersQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly ILibraryMetadataProviderConfigurationRepository _mockLibraryMetadataProviderConfigurationRepository; private readonly IPluginRepository _mockPluginRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IValidator _mockValidator; private readonly GetLibraryMetadataProvidersQueryHandler _sut; private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly Guid _userId; /// /// Initializes a new instance of the class. @@ -41,8 +51,34 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _mockPluginRepository = Substitute.For(); _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); - _sut = new GetLibraryMetadataProvidersQueryHandler(_mockUnitOfWork); + // 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 GetLibraryMetadataProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenLibraryIdIsEmpty_ShouldReturnValidationError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.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 _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -155,4 +191,41 @@ public class GetLibraryMetadataProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); } + + [Fact] + public async Task HandleAsync_WhenOwnershipPolicyDeniesAccess_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.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 _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.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 _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs new file mode 100644 index 00000000..19a19dae --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetLibraryMetadataProviders; +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.GetLibraryMetadataProviders; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetLibraryMetadataProvidersQueryValidatorTests +{ + private readonly GetLibraryMetadataProvidersQueryValidator _validator = new(); + private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); + + [Fact] + public void Validate_WhenLibraryIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.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 + GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs index 00e7f486..db3a2b55 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryHandlerTests.cs @@ -3,15 +3,15 @@ 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.Plugins; -using Lumina.Application.Common.Mapping.Plugins; +using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings; using Lumina.Contracts.Responses.Plugins; using Lumina.Domain.Common.Primitives; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; -using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.Contracts.Fixtures.Common.Models.DTO.Settings; using NSubstitute; using System; using System.Collections.Generic; @@ -33,9 +33,11 @@ public class GetPluginSettingsQueryHandlerTests private readonly IUnitOfWork _mockUnitOfWork; private readonly IPluginRepository _mockPluginRepository; private readonly IPluginManager _mockPluginManager; + private readonly IValidator _mockValidator; private readonly GetPluginSettingsQueryHandler _sut; private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new(); private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly PluginSettingDescriptorDtoFixture _pluginSettingDescriptorDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -46,8 +48,26 @@ public class GetPluginSettingsQueryHandlerTests _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockPluginManager = Substitute.For(); + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); - _sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager); + _sut = new GetPluginSettingsQueryHandler(_mockUnitOfWork, _mockPluginManager, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenPluginIdIsEmpty_ShouldReturnValidationError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + _mockValidator.Validate(Arg.Any()).Returns([DomainErrors.Plugins.PluginIdCannotBeEmpty]); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Plugins.PluginIdCannotBeEmpty, result.FirstError); + await _mockPluginRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -62,8 +82,8 @@ public class GetPluginSettingsQueryHandlerTests IPlugin loadedPlugin = Substitute.For(); loadedPlugin.GetSettingsSchema().Returns( [ - new PluginSettingDescriptorDto("key1", "Label 1", PluginSettingType.Text, "default"), - new PluginSettingDescriptorDto("key2", "Label 2", PluginSettingType.Select, null, ["a", "b"]) + _pluginSettingDescriptorDtoFixture.Create(key: "key1", label: "Label 1", type: PluginSettingType.Text, defaultValue: "default"), + _pluginSettingDescriptorDtoFixture.Create(key: "key2", label: "Label 2", type: PluginSettingType.Select, allowedValues: ["a", "b"]) ]); _mockPluginManager.GetPlugin(query.PluginId).Returns(loadedPlugin); IReadOnlyDictionary? expectedSettings = JsonSerializer.Deserialize>(plugin.SettingsJson!); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs new file mode 100644 index 00000000..592d5cbb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Plugins/Queries/GetPluginSettings/GetPluginSettingsQueryValidatorTests.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; +using Lumina.Application.Fixtures.Core.Plugins.Queries.GetPluginSettings; +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.GetPluginSettings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPluginSettingsQueryValidatorTests +{ + private readonly GetPluginSettingsQueryValidator _validator = new(); + private readonly GetPluginSettingsQueryFixture _getPluginSettingsQueryFixture = new(); + + [Fact] + public void Validate_WhenPluginIdIsEmpty_ShouldHaveValidationError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + query = query with { PluginId = Guid.Empty }; + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Plugins.PluginIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPluginIdIsValid_ShouldNotHaveValidationError() + { + // Arrange + GetPluginSettingsQuery query = _getPluginSettingsQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs index f33a2666..9085a131 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdateUserSettings/UpdateUserSettingsCommandHandlerTests.cs @@ -74,7 +74,7 @@ public class UpdateUserSettingsCommandHandlerTests settings.UserId == _userId && settings.IsPaginationEnabled == command.IsPaginationEnabled && settings.ItemsPerPage == command.ItemsPerPage && - settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker), + settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker), Arg.Any()); await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); @@ -102,7 +102,7 @@ public class UpdateUserSettingsCommandHandlerTests settings.UserId == _userId && settings.IsPaginationEnabled == command.IsPaginationEnabled && settings.ItemsPerPage == command.ItemsPerPage && - settings.IgnoreThePrefixForAlphaPicker == command.IgnoreThePrefixForAlphaPicker), + settings.ShouldIgnoreThePrefixForAlphaPicker == command.ShouldIgnoreThePrefixForAlphaPicker), Arg.Any()); await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs index ce16f758..81ce23ea 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetUserSettings/GetUserSettingsQueryHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.Errors; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetUserSettings; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.Domain.Common.Primitives; using NSubstitute; @@ -28,6 +29,7 @@ public class GetUserSettingsQueryHandlerTests private readonly IUserSettingsRepository _mockUserSettingsRepository; private readonly GetUserSettingsQueryHandler _sut; private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly GetUserSettingsQueryFixture _getUserSettingsQueryFixture = new(); private readonly Guid _userId = Guid.NewGuid(); /// @@ -49,7 +51,7 @@ public class GetUserSettingsQueryHandlerTests public async Task HandleAsync_WhenSettingsExist_ShouldReturnStoredSettings() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId); _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) .Returns(Result.From(storedSettings)); @@ -62,14 +64,14 @@ public class GetUserSettingsQueryHandlerTests Assert.Equal(storedSettings.UserId, result.Value.UserId); Assert.Equal(storedSettings.IsPaginationEnabled, result.Value.IsPaginationEnabled); Assert.Equal(storedSettings.ItemsPerPage, result.Value.ItemsPerPage); - Assert.Equal(storedSettings.IgnoreThePrefixForAlphaPicker, result.Value.IgnoreThePrefixForAlphaPicker); + Assert.Equal(storedSettings.ShouldIgnoreThePrefixForAlphaPicker, result.Value.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnDefaultSettings() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) .Returns(Result.From(null)); @@ -81,14 +83,14 @@ public class GetUserSettingsQueryHandlerTests Assert.NotEqual(Guid.Empty, result.Value.UserId); Assert.True(result.Value.IsPaginationEnabled); Assert.Equal(48, result.Value.ItemsPerPage); - Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker); } [Fact] public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorized() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); _mockCurrentUserService.UserId.Returns((Guid?)null); // Act @@ -104,7 +106,7 @@ public class GetUserSettingsQueryHandlerTests public async Task HandleAsync_WhenGetByIdReturnsError_ShouldReturnError() { // Arrange - GetUserSettingsQuery query = new(); + GetUserSettingsQuery query = _getUserSettingsQueryFixture.Create(); Error error = Error.Failure("Database.Error", "Failed to retrieve user settings"); _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) .Returns(error); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj index feec240b..1aad9a82 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Application.UnitTests/Lumina.Application.UnitTests.csproj @@ -43,5 +43,6 @@ + diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs index 69278ec0..11e0ea34 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/AddLibraryRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using System.Diagnostics.CodeAnalysis; using System.Text.Json; @@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class AddLibraryRequestTests { + private readonly AddLibraryRequestFixture _addLibraryRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -21,16 +23,16 @@ public class AddLibraryRequestTests public void RoundTrip_WhenSerializingAddLibraryRequest_ShouldPreserveValues() { // Arrange - AddLibraryRequest expected = new( - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + AddLibraryRequest expected = _addLibraryRequestFixture.Create( + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -45,20 +47,20 @@ public class AddLibraryRequestTests public void Deconstruct_WhenCalled_ShouldReturnAllProperties() { // Arrange - AddLibraryRequest sut = new( - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + AddLibraryRequest sut = _addLibraryRequestFixture.Create( + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act - (string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; + (string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; // Assert Assert.Equal(sut.Title, title); @@ -67,7 +69,7 @@ public class AddLibraryRequestTests Assert.Equal(sut.CoverImage, coverImage); Assert.Equal(sut.IsEnabled, isEnabled); Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs index ae55cab5..f384abee 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/MediaLibrary/Management/UpdateLibraryRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.Management; using Lumina.Contracts.Requests.MediaLibrary.Management; using System; using System.Diagnostics.CodeAnalysis; @@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Requests.MediaLibrary.Management; [ExcludeFromCodeCoverage] public class UpdateLibraryRequestTests { + private readonly UpdateLibraryRequestFixture _updateLibraryRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -24,18 +26,18 @@ public class UpdateLibraryRequestTests // Arrange Guid id = Guid.NewGuid(); Guid userId = Guid.NewGuid(); - UpdateLibraryRequest expected = new( - id, - userId, - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + UpdateLibraryRequest expected = _updateLibraryRequestFixture.Create( + id: id, + userId: userId, + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act @@ -52,22 +54,22 @@ public class UpdateLibraryRequestTests // Arrange Guid id = Guid.NewGuid(); Guid userId = Guid.NewGuid(); - UpdateLibraryRequest sut = new( - id, - userId, - "Books", - "Book", - [@"C:\Media\Books"], - null, - true, - false, - true, - false, - true + UpdateLibraryRequest sut = _updateLibraryRequestFixture.Create( + id: id, + userId: userId, + title: "Books", + libraryType: "Book", + contentLocations: [@"C:\Media\Books"], + coverImage: null, + isEnabled: true, + isLocked: false, + canDownloadMetadataFromWeb: true, + shouldSaveMetadataInMediaDirectories: false, + shouldSkipUnchangedDirectoriesDuringScan: true ); // Act - (Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; + (Guid sutId, Guid sutUserId, string? title, string? libraryType, string[]? contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan) = sut; // Assert Assert.Equal(sut.Id, sutId); @@ -78,7 +80,7 @@ public class UpdateLibraryRequestTests Assert.Equal(sut.CoverImage, coverImage); Assert.Equal(sut.IsEnabled, isEnabled); Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs index a8b6cbfc..4b8e2d6a 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Requests/UsersManagement/Settings/UpdateUserSettingsRequestTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using System.Diagnostics.CodeAnalysis; using System.Text.Json; @@ -12,6 +13,7 @@ namespace Lumina.Contracts.UnitTests.Requests.UsersManagement.Settings; [ExcludeFromCodeCoverage] public class UpdateUserSettingsRequestTests { + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -21,7 +23,13 @@ public class UpdateUserSettingsRequestTests public void RoundTrip_WhenSerializingUpdateUserSettingsRequest_ShouldPreserveValues() { // Arrange - UpdateUserSettingsRequest expected = new(true, 50, true, true); + UpdateUserSettingsRequest expected = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: true, + itemsPerPage: 50, + shouldIgnoreThePrefixForAlphaPicker: true, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false + ); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); @@ -36,15 +44,22 @@ public class UpdateUserSettingsRequestTests public void Deconstruct_WhenCalled_ShouldReturnAllProperties() { // Arrange - UpdateUserSettingsRequest sut = new(false, 25, false, false); + UpdateUserSettingsRequest sut = _updateUserSettingsRequestFixture.Create( + isPaginationEnabled: false, + itemsPerPage: 25, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: false, + shouldAggregateMetadataWhenMissing: false + ); // Act - (bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut; + (bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut; // Assert Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); Assert.Equal(sut.ItemsPerPage, itemsPerPage); - Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); + Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing); } } diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs index 601c64db..38d65cd1 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/MediaLibrary/Management/LibraryResponseTests.cs @@ -58,7 +58,7 @@ public class LibraryResponseTests LibraryResponse sut = _libraryResponseFixture.Create(); // Act - (Guid id, Guid userId, string title, LibraryType libraryType, List contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool downloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut; + (Guid id, Guid userId, string title, LibraryType libraryType, List contentLocations, string? coverImage, bool isEnabled, bool isLocked, bool canDownloadMetadataFromWeb, bool shouldSaveMetadataInMediaDirectories, bool shouldSkipUnchangedDirectoriesDuringScan, DateTime createdOnUtc, DateTime? updatedOnUtc) = sut; // Assert Assert.Equal(sut.Id, id); @@ -69,7 +69,7 @@ public class LibraryResponseTests Assert.Equal(sut.CoverImage, coverImage); Assert.Equal(sut.IsEnabled, isEnabled); Assert.Equal(sut.IsLocked, isLocked); - Assert.Equal(sut.DownloadMetadataFromWeb, downloadMetadataFromWeb); + Assert.Equal(sut.CanDownloadMetadataFromWeb, canDownloadMetadataFromWeb); Assert.Equal(sut.ShouldSaveMetadataInMediaDirectories, shouldSaveMetadataInMediaDirectories); Assert.Equal(sut.ShouldSkipUnchangedDirectoriesDuringScan, shouldSkipUnchangedDirectoriesDuringScan); Assert.Equal(sut.CreatedOnUtc, createdOnUtc); diff --git a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs index 0bd9c3ff..a7d884c0 100644 --- a/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs +++ b/tests/UnitTests/Lumina.Contracts.UnitTests/Responses/UsersManagement/Settings/UserSettingsResponseTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; using Lumina.Contracts.Responses.UsersManagement.Settings; using System; using System.Diagnostics.CodeAnalysis; @@ -13,6 +14,7 @@ namespace Lumina.Contracts.UnitTests.Responses.UsersManagement.Settings; [ExcludeFromCodeCoverage] public class UserSettingsResponseTests { + private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new(); private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true @@ -23,7 +25,14 @@ public class UserSettingsResponseTests { // Arrange Guid userId = Guid.NewGuid(); - UserSettingsResponse expected = new(userId, true, 50, true, true); + UserSettingsResponse expected = _userSettingsResponseFixture.Create( + userId: userId, + isPaginationEnabled: true, + itemsPerPage: 50, + shouldIgnoreThePrefixForAlphaPicker: true, + isThemeCachingEnabled: true, + shouldAggregateMetadataWhenMissing: false + ); // Act string json = JsonSerializer.Serialize(expected, _jsonOptions); @@ -39,16 +48,24 @@ public class UserSettingsResponseTests { // Arrange Guid userId = Guid.NewGuid(); - UserSettingsResponse sut = new(userId, false, 25, false, false); + UserSettingsResponse sut = _userSettingsResponseFixture.Create( + userId: userId, + isPaginationEnabled: false, + itemsPerPage: 25, + shouldIgnoreThePrefixForAlphaPicker: false, + isThemeCachingEnabled: false, + shouldAggregateMetadataWhenMissing: false + ); // Act - (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool ignoreThePrefixForAlphaPicker, bool isThemeCachingEnabled) = sut; + (Guid sutUserId, bool isPaginationEnabled, int itemsPerPage, bool shouldIgnoreThePrefixForAlphaPicker, bool isThemeCachingEnabled, bool shouldAggregateMetadataWhenMissing) = sut; // Assert Assert.Equal(sut.UserId, sutUserId); Assert.Equal(sut.IsPaginationEnabled, isPaginationEnabled); Assert.Equal(sut.ItemsPerPage, itemsPerPage); - Assert.Equal(sut.IgnoreThePrefixForAlphaPicker, ignoreThePrefixForAlphaPicker); + Assert.Equal(sut.ShouldIgnoreThePrefixForAlphaPicker, shouldIgnoreThePrefixForAlphaPicker); Assert.Equal(sut.IsThemeCachingEnabled, isThemeCachingEnabled); + Assert.Equal(sut.ShouldAggregateMetadataWhenMissing, shouldAggregateMetadataWhenMissing); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs index 0cade107..4fc59370 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/LibraryConfigurationTests.cs @@ -53,7 +53,7 @@ public class LibraryConfigurationTests IProperty titleProperty = entityType.GetProperty(nameof(LibraryEntity.Title)); IProperty libraryTypeProperty = entityType.GetProperty(nameof(LibraryEntity.LibraryType)); IProperty isEnabledProperty = entityType.GetProperty(nameof(LibraryEntity.IsEnabled)); - IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.DownloadMetadataFromWeb)); + IProperty downloadMetadataProperty = entityType.GetProperty(nameof(LibraryEntity.CanDownloadMetadataFromWeb)); // Assert Assert.False(titleProperty.IsNullable); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs index 2a7cec99..1638dcb9 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/UserSettingsConfigurationTests.cs @@ -52,7 +52,7 @@ public class UserSettingsConfigurationTests IProperty userIdProperty = entityType.GetProperty(nameof(UserSettingsEntity.UserId)); IProperty isPaginationEnabledProperty = entityType.GetProperty(nameof(UserSettingsEntity.IsPaginationEnabled)); IProperty itemsPerPageProperty = entityType.GetProperty(nameof(UserSettingsEntity.ItemsPerPage)); - IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.IgnoreThePrefixForAlphaPicker)); + IProperty ignoreThePrefixProperty = entityType.GetProperty(nameof(UserSettingsEntity.ShouldIgnoreThePrefixForAlphaPicker)); // Assert Assert.False(userIdProperty.IsNullable); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs index f3a7b9b9..1847e96d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Books/BookRepositoryTests.cs @@ -4,7 +4,10 @@ using Lumina.Application.Common.DataAccess.Entities.Common; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DTO.Filtering; using Lumina.Application.Common.DTO.Pagination; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DTO.Filtering; +using Lumina.Application.Fixtures.Common.DTO.Pagination; using Lumina.DataAccess.Core.Repositories.Books; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.Common.Errors; @@ -32,6 +35,13 @@ public class BookRepositoryTests private readonly LuminaDbContext _mockContext; private readonly BookRepository _sut; private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly BookRatingEntityFixture _bookRatingEntityFixture = new(); + private readonly TagEntityFixture _tagEntityFixture = new(); + private readonly GenreEntityFixture _genreEntityFixture = new(); + private readonly IsbnEntityFixture _isbnEntityFixture = new(); + private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new(); + private readonly LibraryFilterDtoFixture _libraryFilterDtoFixture = new(); + private readonly BaseFilterDtoFixture _baseFilterDtoFixture = new(); /// /// Initializes a new instance of the class. @@ -83,12 +93,12 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingTagsFound_ShouldReplaceTagsWithExistingOnes() { // Arrange - TagEntity existingTag = new("Existing"); + TagEntity existingTag = _tagEntityFixture.Create(name: "Existing"); _mockContext.Set().Add(existingTag); await _mockContext.SaveChangesAsync(); BookEntity bookModel = _bookEntityFixture.Create(); - bookModel.Tags = [new("Existing"), new("New")]; + bookModel.Tags = [_tagEntityFixture.Create(name: "Existing"), _tagEntityFixture.Create(name: "New")]; // Act Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -110,12 +120,12 @@ public class BookRepositoryTests public async Task InsertAsync_WhenExistingGenresFound_ShouldReplaceGenresWithExistingOnes() { // Arrange - GenreEntity existingGenre = new("Existing"); + GenreEntity existingGenre = _genreEntityFixture.Create(name: "Existing"); _mockContext.Set().Add(existingGenre); await _mockContext.SaveChangesAsync(); BookEntity bookModel = _bookEntityFixture.Create(); - bookModel.Genres = [new("Existing"), new("New")]; + bookModel.Genres = [_genreEntityFixture.Create(name: "Existing"), _genreEntityFixture.Create(name: "New")]; // Act Result result = await _sut.InsertAsync(bookModel, CancellationToken.None); @@ -168,9 +178,9 @@ public class BookRepositoryTests { // Arrange BookEntity book = _bookEntityFixture.Create(); - book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; - book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; - book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; + book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); @@ -341,8 +351,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -360,8 +370,8 @@ public class BookRepositoryTests public async Task GetPaginatedAsync_WhenFilterDoesNotIncludeLibraryId_ShouldReturnError() { // Arrange - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - BaseFilterDto filter = new(); + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + BaseFilterDto filter = _baseFilterDtoFixture.Create(); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -375,8 +385,8 @@ public class BookRepositoryTests public async Task GetPaginatedAsync_WhenFilterLibraryIdIsEmpty_ShouldReturnError() { // Arrange - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = Guid.Empty }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: Guid.Empty); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -397,7 +407,7 @@ public class BookRepositoryTests _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); - LibraryFilterDto filter = new() { LibraryId = libraryId }; + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(null, null, null, filter, CancellationToken.None); @@ -425,8 +435,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(fellowshipBook, towersBook); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId, SearchTerm = "Fellowship" }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId, searchTerm: "Fellowship"); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -449,8 +459,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(books); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 2, PerPage = 2 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 2, perPage: 2); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); @@ -478,8 +488,8 @@ public class BookRepositoryTests _mockContext.Books.AddRange(bookA, bookB); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, "title", SortOrder.Descending, filter, CancellationToken.None); @@ -496,15 +506,15 @@ public class BookRepositoryTests Guid libraryId = Guid.NewGuid(); BookEntity book = _bookEntityFixture.Create(); book.LibraryId = libraryId; - book.Tags = [new TagEntity("Tag1"), new TagEntity("Tag2")]; - book.Genres = [new GenreEntity("Genre1"), new GenreEntity("Genre2")]; - book.ISBNs = [new IsbnEntity("1234567890", IsbnFormat.Isbn10), new IsbnEntity("1234567890123", IsbnFormat.Isbn13)]; - book.Ratings = [new BookRatingEntity(4.5M, 5, BookRatingSource.Goodreads, 100)]; + book.Tags = [_tagEntityFixture.Create(name: "Tag1"), _tagEntityFixture.Create(name: "Tag2")]; + book.Genres = [_genreEntityFixture.Create(name: "Genre1"), _genreEntityFixture.Create(name: "Genre2")]; + book.ISBNs = [_isbnEntityFixture.Create(value: "1234567890", format: IsbnFormat.Isbn10), _isbnEntityFixture.Create(value: "1234567890123", format: IsbnFormat.Isbn13)]; + book.Ratings = [_bookRatingEntityFixture.Create(value: 4.5M, maxValue: 5, source: BookRatingSource.Goodreads, voteCount: 100)]; _mockContext.Books.Add(book); await _mockContext.SaveChangesAsync(); - PaginationDataDto paginationData = new() { CurrentPage = 1, PerPage = 10 }; - LibraryFilterDto filter = new() { LibraryId = libraryId }; + PaginationDataDto paginationData = _paginationDataDtoFixture.Create(currentPage: 1, perPage: 10); + LibraryFilterDto filter = _libraryFilterDtoFixture.Create(libraryId: libraryId); // Act Result> result = await _sut.GetPaginatedAsync(paginationData, null, null, filter, CancellationToken.None); diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs index fe5586a3..fc94cdc6 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/LuminaDbContextTests.cs @@ -1,12 +1,12 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.DataAccess.Core.UoW; using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; @@ -23,6 +23,7 @@ public class LuminaDbContextTests : IDisposable private readonly string _connectionString; private readonly SqliteConnection _anchorConnection; private readonly LuminaDbContext _context; + private readonly BookEntityFixture _bookEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -46,7 +47,7 @@ public class LuminaDbContextTests : IDisposable // Assert // The count assertion fails when a table is added or removed, reminding to update the assertions below. - Assert.Equal(24, tableNames.Length); + Assert.Equal(25, tableNames.Length); Assert.Contains("Books", tableNames); Assert.Contains("Users", tableNames); Assert.Contains("UserSettings", tableNames); @@ -63,6 +64,7 @@ public class LuminaDbContextTests : IDisposable Assert.Contains("DirectoryScanFingerprints", tableNames); Assert.Contains("Plugins", tableNames); Assert.Contains("LibraryMetadataProviderConfigurations", tableNames); + Assert.Contains("LibraryArtworkProviderConfigurations", tableNames); Assert.Contains("Tags", tableNames); Assert.Contains("Genres", tableNames); Assert.Contains("LibraryContentLocations", tableNames); @@ -78,17 +80,10 @@ public class LuminaDbContextTests : IDisposable { // Arrange _context.Database.EnsureCreated(); - BookEntity book = new() - { - Id = Guid.NewGuid(), - LibraryId = Guid.NewGuid(), - Path = "/books/test.epub", - Title = "Test Book", - MetadataStatus = MetadataStatus.Pending, - CreatedOnUtc = DateTime.UtcNow, - CreatedBy = Guid.NewGuid(), - UpdatedBy = null - }; + BookEntity book = _bookEntityFixture.Create(path: "/books/test.epub", title: "Test Book", includeMetadata: false); + book.MetadataStatus = MetadataStatus.Pending; + book.CreatedOnUtc = DateTime.UtcNow; + book.CreatedBy = Guid.NewGuid(); _context.Books.Add(book); // Act diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs index 1a7a4780..928ae81d 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/UoW/UnitOfWorkTests.cs @@ -1,11 +1,7 @@ #region ========================================================================= USING ===================================================================================== using AutoFixture; using AutoFixture.AutoNSubstitute; -using Lumina.Application.Common.DataAccess.Repositories.Authorization; -using Lumina.Application.Common.DataAccess.Repositories.Books; -using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; -using Lumina.Application.Common.DataAccess.Repositories.Plugins; -using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.Entities.Authorization; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Time; @@ -100,6 +96,26 @@ public class UnitOfWorkTests await dbContext.Received(1).SaveChangesAsync(cancellationToken); } + [Fact] + public async Task ClearTrackedEntities_WhenCalled_ShouldDetachAllTrackedEntities() + { + // Arrange + DbContextOptions options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()) + .Options; + LuminaDbContext dbContext = new(options); + UnitOfWork unitOfWork = new(dbContext); + dbContext.Roles.Add(new RoleEntity { Id = Guid.NewGuid(), RoleName = "TestRole" }); + await dbContext.SaveChangesAsync(CancellationToken.None); + Assert.NotEmpty(dbContext.ChangeTracker.Entries()); + + // Act + unitOfWork.ClearTrackedEntities(); + + // Assert + Assert.Empty(dbContext.ChangeTracker.Entries()); + } + [Fact] public void UnitOfWork_WhenResolvedFromServiceProvider_ShouldExposeRepositories() { diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs index 82cede13..ca069f9b 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/LibraryManagementBoundedContext/LibraryAggregate/LibraryTests.cs @@ -3,7 +3,6 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; -using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -14,7 +13,6 @@ using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; #endregion namespace Lumina.Domain.UnitTests.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate; @@ -50,7 +48,7 @@ public class LibraryTests coverImageSourcePath, isEnabled: false, isLocked: true, - downloadMetadataFromWeb: false, + canDownloadMetadataFromWeb: false, shouldSaveMetadataInMediaDirectories: true, shouldSkipUnchangedDirectoriesDuringScan: true, scanIds); @@ -64,7 +62,7 @@ public class LibraryTests Assert.Equal(coverImageSourcePath, result.Value.CoverImage); Assert.False(result.Value.IsEnabled); Assert.True(result.Value.IsLocked); - Assert.False(result.Value.DownloadMetadataFromWeb); + Assert.False(result.Value.CanDownloadMetadataFromWeb); Assert.True(result.Value.ShouldSaveMetadataInMediaDirectories); Assert.True(result.Value.ShouldSkipUnchangedDirectoriesDuringScan); Assert.Equal(scanIds, result.Value.ScanIds); @@ -87,7 +85,7 @@ public class LibraryTests null, isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, scanIds); @@ -109,7 +107,7 @@ public class LibraryTests null, isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, []); @@ -136,7 +134,7 @@ public class LibraryTests null, isEnabled: true, isLocked: false, - downloadMetadataFromWeb: true, + canDownloadMetadataFromWeb: true, shouldSaveMetadataInMediaDirectories: false, shouldSkipUnchangedDirectoriesDuringScan: false, []); diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs index d1abc2cf..ac6ebbdc 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/UserManagementBoundedContext/UserSettingsAggregate/UserSettingsTests.cs @@ -5,7 +5,6 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserSettingsAggregate; -using System; using System.Diagnostics.CodeAnalysis; #endregion @@ -34,7 +33,8 @@ public class UserSettingsTests Assert.Equal(userId, result.Value.UserId); Assert.True(result.Value.IsPaginationEnabled); Assert.Equal(48, result.Value.ItemsPerPage); - Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldAggregateMetadataWhenMissing); } [Fact] @@ -48,7 +48,8 @@ public class UserSettingsTests Assert.NotNull(result.Value.UserId); Assert.True(result.Value.IsPaginationEnabled); Assert.Equal(48, result.Value.ItemsPerPage); - Assert.False(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldIgnoreThePrefixForAlphaPicker); + Assert.False(result.Value.ShouldAggregateMetadataWhenMissing); } [Fact] @@ -72,15 +73,16 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: false, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: true); // Assert Assert.False(result.IsFailure); Assert.Equal(userId, result.Value.UserId); Assert.False(result.Value.IsPaginationEnabled); Assert.Equal(24, result.Value.ItemsPerPage); - Assert.True(result.Value.IgnoreThePrefixForAlphaPicker); + Assert.True(result.Value.ShouldIgnoreThePrefixForAlphaPicker); Assert.True(result.Value.IsThemeCachingEnabled); + Assert.True(result.Value.ShouldAggregateMetadataWhenMissing); } [Fact] @@ -106,7 +108,7 @@ public class UserSettingsTests UserId userId = _userIdFixture.Create(); // Act - Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true); + Result result = UserSettings.Create(userId, isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); // Assert Assert.True(result.IsFailure); @@ -120,14 +122,15 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, ignoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false); + Result result = userSettings.UpdateSettings(isPaginationEnabled: false, itemsPerPage: 12, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: false, shouldAggregateMetadataWhenMissing: true); // Assert Assert.False(result.IsFailure); Assert.False(userSettings.IsPaginationEnabled); Assert.Equal(12, userSettings.ItemsPerPage); - Assert.True(userSettings.IgnoreThePrefixForAlphaPicker); + Assert.True(userSettings.ShouldIgnoreThePrefixForAlphaPicker); Assert.False(userSettings.IsThemeCachingEnabled); + Assert.True(userSettings.ShouldAggregateMetadataWhenMissing); } [Theory] @@ -139,7 +142,7 @@ public class UserSettingsTests UserSettings userSettings = _userSettingsFixture.Create(); // Act - Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, ignoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true); + Result result = userSettings.UpdateSettings(isPaginationEnabled: true, itemsPerPage: itemsPerPage, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); // Assert Assert.True(result.IsFailure); diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs index 63877702..fab2baae 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MediaLibraryScanMetadataEnrichmentJobTests.cs @@ -1,9 +1,22 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; using Lumina.Application.Common.DataAccess.Repositories.Books; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Users; using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +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.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; @@ -13,14 +26,17 @@ using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggreg using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects; using Lumina.Domain.Fixtures.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using Lumina.Plugins.Contracts.Core.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NSubstitute; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Threading; using System.Threading.Tasks; #endregion @@ -45,6 +61,13 @@ public class MediaLibraryScanMetadataEnrichmentJobTests private readonly ScanIdFixture _scanIdFixture = new(); private readonly UserIdFixture _userIdFixture = new(); private readonly LibraryIdFixture _libraryIdFixture = new(); + private readonly LibraryMetadataProviderConfigurationEntityFixture _configurationEntityFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly ArtworkDtoFixture _artworkDtoFixture = new(); + private readonly BookEntityFixture _bookEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); private readonly ScanId _scanId; private readonly UserId _userId; private readonly LibraryId _libraryId; @@ -106,6 +129,51 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await _mockDomainEventPublisher.Received(1).PublishAsync(Arg.Is(domainEvent => domainEvent.MediaLibraryScanCompositeId.ScanId == _scanId), Arg.Any()); } + [Fact] + public async Task ExecuteAsync_WhenNoMetadataProviderIsConfigured_ShouldSkipEnrichmentWithoutMarkingBooksAsFailed() + { + // Arrange + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([])); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // a library without metadata providers must not mark its books as failed to enrich, so the book repositories are not touched + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataCountAsync(Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().GetBooksNeedingMetadataAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockBookRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenABookPageIsProcessed_ShouldDetachTheTrackedEntitiesAfterSaving() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the tracked entities of the page are detached after saving, so that the peak memory stays bounded regardless of the library size + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockUnitOfWork.Received(1).ClearTrackedEntities(); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + [Fact] public async Task ExecuteAsync_WhenGettingConfigurationsFails_ShouldMarkJobAsFailedAndPublishFailureEvent() { @@ -139,4 +207,371 @@ public class MediaLibraryScanMetadataEnrichmentJobTests await Assert.ThrowsAnyAsync(() => operation); Assert.Equal(LibraryScanJobStatus.Canceled, _sut.Status); } + + [Fact] + public async Task ExecuteAsync_WhenAggregateMetadataIsEnabled_ShouldFeedTheEarlierProvidersFindingsToTheLaterOnes() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + IMetadataProvider secondProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", openLibraryId: "OL123", description: "First Description")); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + // the book has no known identifiers of its own, so the findings of the first provider are fed to the second one + book.OpenLibraryId = null; + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the second provider receives the lookup enriched with the open library Id discovered by the first provider + await secondProvider.Received(1).GetMetadataAsync( + Arg.Is(lookup => lookup is BookMetadataLookupDto && ((BookMetadataLookupDto)lookup).OpenLibraryId == "OL123"), + Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenAggregateMetadataIsDisabled_ShouldOnlyApplyTheFirstUsableProviderMetadata() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid secondPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + IMetadataProvider secondProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title", publisher: "First Publisher")); + secondProvider.Name.Returns("Second Provider"); + secondProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + secondProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Second Title", publisher: "Second Publisher")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, secondPluginId, secondProvider, shouldAggregateMetadataWhenMissing: false); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId, secondPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the second provider is not queried when the aggregation is disabled and the first provider returned usable metadata + await secondProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenNoProviderReturnsUsableMetadata_ShouldMarkTheBookAsFailedToEnrich() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([ + _configurationEntityFixture.Create(_libraryId.Value, firstPluginId, 1) + ])); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await _mockBookRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.MetadataStatus == MetadataStatus.Failed), + Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenArtworkConfigurationRepositoryReturnsFailure_ShouldStillEnrichTheMetadata() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); + + SetupRealServiceProviderForProviders(firstPluginId, firstProvider, shouldAggregateMetadataWhenMissing: true); + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); + mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Error.Failure(description: "Failed to get the artwork provider configurations")); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + await _mockBookRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenAnArtworkProviderReturnsArtwork_ShouldStoreItAndSetTheBookCoverPath() + { + // Arrange + Guid firstPluginId = Guid.NewGuid(); + Guid artworkPluginId = Guid.NewGuid(); + IMetadataProvider firstProvider = Substitute.For(); + firstProvider.Name.Returns("First Provider"); + firstProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + firstProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "First Title")); + + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + IBookArtworkService mockBookArtworkService = Substitute.For(); + mockBookArtworkService.SaveBookArtworkAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From("\\media\\books\\Library\\Author\\Title\\cover.jpeg")); + + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + services.AddKeyedSingleton(artworkPluginId, artworkProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + services.AddSingleton(mockBookArtworkService); + using ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + + IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); + mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, firstPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + await mockBookArtworkService.Received(1).SaveBookArtworkAsync( + _libraryId.Value, + book.Id, + Arg.Any(), + Arg.Any(), + "First Title", + Arg.Any(), + Arg.Any()); + await _mockBookRepository.Received(1).UpdateAsync( + Arg.Is(entity => entity.CoverImagePath == "\\media\\books\\Library\\Author\\Title\\cover.jpeg"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseMetadataProvidersThatRequireWebAccess() + { + // Arrange + Guid localPluginId = Guid.NewGuid(); + Guid webPluginId = Guid.NewGuid(); + IMetadataProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.RequiresWebAccess.Returns(false); + localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); + IMetadataProvider webProvider = Substitute.For(); + webProvider.Name.Returns("Web Provider"); + webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + webProvider.RequiresWebAccess.Returns(true); + webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); + + SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, localPluginId, webPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the local provider is used, but the provider requiring access to the web is skipped, so the book cannot be enriched + await localProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + await webProvider.DidNotReceive().GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryPermitsWebDownloads_ShouldUseMetadataProvidersThatRequireWebAccess() + { + // Arrange + Guid localPluginId = Guid.NewGuid(); + Guid webPluginId = Guid.NewGuid(); + IMetadataProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.RequiresWebAccess.Returns(false); + localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(includeTitle: false)); + IMetadataProvider webProvider = Substitute.For(); + webProvider.Name.Returns("Web Provider"); + webProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + webProvider.RequiresWebAccess.Returns(true); + webProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Web Title")); + + SetupRealServiceProviderForProviders(localPluginId, localProvider, webPluginId, webProvider, shouldAggregateMetadataWhenMissing: false); + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: true))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, localPluginId, webPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the provider requiring access to the web is used when the library permits downloading data from the web + await webProvider.Received(1).GetMetadataAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + [Fact] + public async Task ExecuteAsync_WhenTheLibraryForbidsWebDownloads_ShouldNotUseArtworkProvidersThatRequireWebAccess() + { + // Arrange + Guid localPluginId = Guid.NewGuid(); + Guid artworkPluginId = Guid.NewGuid(); + IMetadataProvider localProvider = Substitute.For(); + localProvider.Name.Returns("Local Provider"); + localProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + localProvider.RequiresWebAccess.Returns(false); + localProvider.GetMetadataAsync(Arg.Any(), Arg.Any()) + .Returns(_bookMetadataDtoFixture.Create(title: "Local Title")); + + IArtworkProvider artworkProvider = Substitute.For(); + artworkProvider.Name.Returns("Web Artwork Provider"); + artworkProvider.SupportedLibraryTypes.Returns([LibraryType.Book]); + artworkProvider.RequiresWebAccess.Returns(true); + artworkProvider.GetArtworkAsync(Arg.Any(), Arg.Any()) + .Returns(_artworkDtoFixture.Create(localPath: "/some/cover.jpg")); + + ServiceCollection services = new(); + services.AddKeyedSingleton(localPluginId, localProvider); + services.AddKeyedSingleton(artworkPluginId, artworkProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + using ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: false))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + + ILibraryRepository mockLibraryRepository = Substitute.For(); + mockLibraryRepository.GetByIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(_libraryEntityFixture.Create(title: "My Library", canDownloadMetadataFromWeb: false))); + _mockUnitOfWork.LibraryRepository.Returns(mockLibraryRepository); + + IArtworkProviderConfigurationRepository mockArtworkConfigurationRepository = Substitute.For(); + mockArtworkConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>([_artworkConfigurationEntityFixture.Create(_libraryId.Value, artworkPluginId, 1)])); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(mockArtworkConfigurationRepository); + + BookEntity book = _bookEntityFixture.Create(libraryId: _libraryId.Value, path: "/books/test.epub"); + SetupSingleBookPage(book, localPluginId); + + // Act + await _sut.ExecuteAsync(Guid.NewGuid(), new { }, CancellationToken.None); + + // Assert + // the artwork provider requiring access to the web is skipped when the library does not permit downloading data from the web + await artworkProvider.DidNotReceive().GetArtworkAsync(Arg.Any(), Arg.Any()); + Assert.Equal(LibraryScanJobStatus.Completed, _sut.Status); + } + + /// + /// Wires a real service provider with the given metadata providers, so that the job resolves them from the dependency injection container. + /// + /// The Id of the plugin providing the first metadata provider. + /// The first metadata provider to resolve. + /// The Id of the plugin providing the second metadata provider, if any. + /// The second metadata provider to resolve, if any. + /// Whether the user settings enable aggregating metadata from multiple providers when fields are missing. + private void SetupRealServiceProviderForProviders(Guid firstPluginId, IMetadataProvider firstProvider, Guid? secondPluginId = null, IMetadataProvider? secondProvider = null, bool shouldAggregateMetadataWhenMissing = false) + { + ServiceCollection services = new(); + services.AddKeyedSingleton(firstPluginId, firstProvider); + if (secondPluginId is not null && secondProvider is not null) + services.AddKeyedSingleton(secondPluginId.Value, secondProvider); + services.AddSingleton(_mockUnitOfWork); + services.AddSingleton(_mockDomainEventPublisher); + // the provider is intentionally not disposed here, so that the async service scope used by the job stays alive for the whole test + ServiceProvider realServiceProvider = services.BuildServiceProvider(); + AsyncServiceScope asyncServiceScope = realServiceProvider.CreateAsyncScope(); + _mockServiceScopeFactory.CreateAsyncScope().Returns(asyncServiceScope); + + IUserSettingsRepository mockUserSettingsRepository = Substitute.For(); + mockUserSettingsRepository.GetByUserIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_userSettingsEntityFixture.Create(shouldAggregateMetadataWhenMissing: shouldAggregateMetadataWhenMissing))); + _mockUnitOfWork.UserSettingsRepository.Returns(mockUserSettingsRepository); + } + + /// + /// Stubs the repositories so that the job processes a single page containing the given book, configured with the given metadata providers. + /// + /// The book the job must enrich. + /// The Ids of the plugins configured as metadata providers for the library. + private void SetupSingleBookPage(BookEntity book, params Guid[] configuredPluginIds) + { + _mockConfigurationRepository.GetByLibraryIdAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From>( + configuredPluginIds.Select((pluginId, index) => _configurationEntityFixture.Create(_libraryId.Value, pluginId, index + 1)).ToList())); + _mockBookRepository.GetBooksNeedingMetadataCountAsync(_libraryId.Value, Arg.Any()) + .Returns(Result.From(1)); + _mockBookRepository.GetBooksNeedingMetadataAsync(_libraryId.Value, Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From>([book]), Result.From>([])); + _mockBookRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Task.CompletedTask); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs new file mode 100644 index 00000000..59a554c5 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/MediaLibrary/Management/Scanning/Jobs/Common/MetadataAggregatorTests.cs @@ -0,0 +1,332 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.Common; +using Lumina.Contracts.Fixtures.Core.DTO.MediaContributors; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary; +using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.MediaLibrary.Management.Scanning.Jobs.Common; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MetadataAggregatorTests +{ + private readonly BookMetadataDtoFixture _bookMetadataDtoFixture = new(); + private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new(); + private readonly IsbnDtoFixture _isbnDtoFixture = new(); + private readonly BookRatingDtoFixture _bookRatingDtoFixture = new(); + private readonly ReleaseInfoDtoFixture _releaseInfoDtoFixture = new(); + private readonly GenreDtoFixture _genreDtoFixture = new(); + private readonly TagDtoFixture _tagDtoFixture = new(); + private readonly LanguageInfoDtoFixture _languageInfoDtoFixture = new(); + + [Fact] + public void Merge_WhenBothMetadataHaveScalarValues_ShouldKeepTheFirstValues() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, + title: "First Title", + originalTitle: "First Original Title", + description: "First Description", + publisher: "First Publisher", + pageCount: 100, + format: BookFormat.Hardcover, + edition: "First Edition", + volumeNumber: 1, + asin: "FIRST-ASIN", + goodreadsId: "FIRST-GOODREADS", + lccn: "FIRST-LCCN", + oclcNumber: "FIRST-OCLC", + openLibraryId: "FIRST-OL", + libraryThingId: "FIRST-LT", + googleBooksId: "FIRST-GOOGLE", + barnesAndNobleId: "FIRST-BN", + appleBooksId: "FIRST-APPLE", + coverImagePath: "First Cover"); + BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, + title: "Second Title", + originalTitle: "Second Original Title", + description: "Second Description", + publisher: "Second Publisher", + pageCount: 200, + format: BookFormat.Paperback, + edition: "Second Edition", + volumeNumber: 2, + asin: "SECOND-ASIN", + goodreadsId: "SECOND-GOODREADS", + lccn: "SECOND-LCCN", + oclcNumber: "SECOND-OCLC", + openLibraryId: "SECOND-OL", + libraryThingId: "SECOND-LT", + googleBooksId: "SECOND-GOOGLE", + barnesAndNobleId: "SECOND-BN", + appleBooksId: "SECOND-APPLE", + coverImagePath: "First Cover"); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("First Title", result.Title); + Assert.Equal("First Original Title", result.OriginalTitle); + Assert.Equal("First Description", result.Description); + Assert.Equal("First Publisher", result.Publisher); + Assert.Equal(100, result.PageCount); + Assert.Equal(BookFormat.Hardcover, result.Format); + Assert.Equal("First Edition", result.Edition); + Assert.Equal(1, result.VolumeNumber); + Assert.Equal("FIRST-ASIN", result.ASIN); + Assert.Equal("FIRST-GOODREADS", result.GoodreadsId); + Assert.Equal("FIRST-LCCN", result.LCCN); + Assert.Equal("FIRST-OCLC", result.OCLCNumber); + Assert.Equal("FIRST-OL", result.OpenLibraryId); + Assert.Equal("FIRST-LT", result.LibraryThingId); + Assert.Equal("FIRST-GOOGLE", result.GoogleBooksId); + Assert.Equal("FIRST-BN", result.BarnesAndNobleId); + Assert.Equal("FIRST-APPLE", result.AppleBooksId); + Assert.Equal("First Cover", result.CoverImagePath); + } + + [Fact] + public void Merge_WhenFirstHasNullScalars_ShouldFallBackToTheSecondValues() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, description: null, publisher: null, pageCount: null); + BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: "Second Title", description: "Second Description", publisher: "Second Publisher", pageCount: 200); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Second Title", result.Title); + Assert.Equal("Second Description", result.Description); + Assert.Equal("Second Publisher", result.Publisher); + Assert.Equal(200, result.PageCount); + } + + [Fact] + public void Merge_WhenBothHaveNullScalars_ShouldReturnNullScalars() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null); + BookMetadataDto second = _bookMetadataDtoFixture.Create(includeOptionalProperties: false, title: null, coverImagePath: null); + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Description); + Assert.Null(result.Publisher); + Assert.Null(result.PageCount); + Assert.Null(result.Format); + Assert.Null(result.Edition); + Assert.Null(result.VolumeNumber); + Assert.Null(result.Series); + } + + [Fact] + public void Merge_WhenBothHaveReleaseInfo_ShouldCoalesceEachField() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false); + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false); + first = first with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001, releaseCountry: "US") }; + second = second with { ReleaseInfo = _releaseInfoDtoFixture.Create(reReleaseDate: new DateOnly(2010, 5, 5), reReleaseYear: 2010, releaseCountry: "UK", releaseVersion: "2.0") }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(2001, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(2010, 5, 5), result.ReleaseInfo.ReReleaseDate); + Assert.Equal(2010, result.ReleaseInfo.ReReleaseYear); + Assert.Equal("US", result.ReleaseInfo.ReleaseCountry); + Assert.Equal("2.0", result.ReleaseInfo.ReleaseVersion); + } + + [Fact] + public void Merge_WhenFirstReleaseInfoIsNull_ShouldUseTheSecondReleaseInfo() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = _releaseInfoDtoFixture.Create(originalReleaseDate: new DateOnly(2001, 1, 1), originalReleaseYear: 2001) }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(new DateOnly(2001, 1, 1), result.ReleaseInfo!.OriginalReleaseDate); + } + + [Fact] + public void Merge_WhenBothReleaseInfosAreNull_ShouldReturnNullReleaseInfo() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { ReleaseInfo = null }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.ReleaseInfo); + } + + [Fact] + public void Merge_WhenBothHaveGenres_ShouldUnionAndDeDuplicateByName() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Space opera")] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Genres = [_genreDtoFixture.Create(name: "Science fiction"), _genreDtoFixture.Create(name: "Fantasy")] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(3, result.Genres!.Count); + Assert.Contains(result.Genres, genre => genre.Name == "Science fiction"); + Assert.Contains(result.Genres, genre => genre.Name == "Space opera"); + Assert.Contains(result.Genres, genre => genre.Name == "Fantasy"); + } + + [Fact] + public void Merge_WhenBothHaveTags_ShouldUnionAndDeDuplicateByName() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag B")] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A"), _tagDtoFixture.Create(name: "Tag C")] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(3, result.Tags!.Count); + Assert.Contains(result.Tags, tag => tag.Name == "Tag A"); + Assert.Contains(result.Tags, tag => tag.Name == "Tag B"); + Assert.Contains(result.Tags, tag => tag.Name == "Tag C"); + } + + [Fact] + public void Merge_WhenBothHaveIsbns_ShouldUnionAndDeDuplicateByValue() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13), _isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Isbns!.Count); + Assert.Contains(result.Isbns, isbn => isbn.Value == "9780306406157"); + Assert.Contains(result.Isbns, isbn => isbn.Value == "0306406152"); + } + + [Fact] + public void Merge_WhenBothHaveContributors_ShouldUnionAndDeDuplicateByDisplayNameAndRole() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author"), _mediaContributorDtoFixture.Create("Translator B", "Translator")] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Author A"); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Translator B"); + } + + [Fact] + public void Merge_WhenBothHaveRatings_ShouldUnionAndDeDuplicateBySource() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null), _bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal(2, result.Ratings!.Count); + Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.Calibre); + Assert.Contains(result.Ratings, rating => rating.Source == BookRatingSource.OpenLibrary); + } + + [Fact] + public void Merge_WhenOnlyFirstHasCollections_ShouldReturnTheFirstCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag A")], Genres = [_genreDtoFixture.Create(name: "Genre A")], Isbns = [_isbnDtoFixture.Create(value: "9780306406157", format: IsbnFormat.Isbn13)], Contributors = [_mediaContributorDtoFixture.Create("Author A", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 8m, maxValue: 10m, source: BookRatingSource.Calibre, voteCount: null)] }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Tag A", Assert.Single(result.Tags!).Name); + Assert.Equal("Genre A", Assert.Single(result.Genres!).Name); + Assert.Equal("9780306406157", Assert.Single(result.Isbns!).Value); + Assert.Equal("Author A", Assert.Single(result.Contributors!).Name!.DisplayName); + Assert.Equal(BookRatingSource.Calibre, Assert.Single(result.Ratings!).Source); + } + + [Fact] + public void Merge_WhenOnlySecondHasCollections_ShouldReturnTheSecondCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = [_tagDtoFixture.Create(name: "Tag B")], Genres = [_genreDtoFixture.Create(name: "Genre B")], Isbns = [_isbnDtoFixture.Create(value: "0306406152", format: IsbnFormat.Isbn10)], Contributors = [_mediaContributorDtoFixture.Create("Author B", "Author")], Ratings = [_bookRatingDtoFixture.Create(value: 4.2m, maxValue: 5m, source: BookRatingSource.OpenLibrary, voteCount: 100)] }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("Tag B", Assert.Single(result.Tags!).Name); + Assert.Equal("Genre B", Assert.Single(result.Genres!).Name); + Assert.Equal("0306406152", Assert.Single(result.Isbns!).Value); + Assert.Equal("Author B", Assert.Single(result.Contributors!).Name!.DisplayName); + Assert.Equal(BookRatingSource.OpenLibrary, Assert.Single(result.Ratings!).Source); + } + + [Fact] + public void Merge_WhenBothHaveNullCollections_ShouldReturnNullCollections() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Tags = null, Genres = null, Isbns = null, Contributors = null, Ratings = null }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Null(result.Genres); + Assert.Null(result.Tags); + Assert.Null(result.Isbns); + Assert.Null(result.Contributors); + Assert.Null(result.Ratings); + } + + [Fact] + public void Merge_WhenBothHaveLanguages_ShouldKeepTheFirstLanguage() + { + // Arrange + BookMetadataDto first = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "en", languageName: "English", nativeName: "English") }; + BookMetadataDto second = _bookMetadataDtoFixture.Create(title: "Title", coverImagePath: "First Cover", includeOptionalProperties: false) with { Language = _languageInfoDtoFixture.Create(languageCode: "de", languageName: "German", nativeName: "Deutsch") }; + + // Act + BookMetadataDto result = MetadataAggregator.Merge(first, second); + + // Assert + Assert.Equal("en", result.Language!.LanguageCode); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj index 0f818641..ffb0928d 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Lumina.Infrastructure.UnitTests.csproj @@ -43,6 +43,7 @@ + diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs index 84542ef6..8dd41075 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetLibraryMetadataProviders/GetLibraryMetadataProvidersEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; 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; @@ -28,6 +29,7 @@ public class GetLibraryMetadataProvidersEndpointTests private readonly IQueryHandler>> _mockHandler; private readonly GetLibraryMetadataProvidersEndpoint _sut; private readonly GetLibraryMetadataProvidersRequestFixture _getLibraryMetadataProvidersRequestFixture = new(); + private readonly LibraryMetadataProviderResponseFixture _libraryMetadataProviderResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -46,8 +48,8 @@ public class GetLibraryMetadataProvidersEndpointTests CancellationToken cancellationToken = CancellationToken.None; IReadOnlyList expectedResponses = [ - new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider A", true, 1), - new LibraryMetadataProviderResponse(Guid.NewGuid(), "Provider B", false, 2) + _libraryMetadataProviderResponseFixture.Create(name: "Provider A", isEnabled: true, rank: 1), + _libraryMetadataProviderResponseFixture.Create(name: "Provider B", isEnabled: false, rank: 2) ]; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponses)); diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs index d91e3728..6277cfcb 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Plugins/GetPluginSettings/GetPluginSettingsEndpointTests.cs @@ -3,6 +3,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.Plugins.Queries.GetPluginSettings; 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; @@ -27,6 +28,7 @@ public class GetPluginSettingsEndpointTests private readonly IQueryHandler> _mockHandler; private readonly GetPluginSettingsEndpoint _sut; private readonly GetPluginSettingsRequestFixture _getPluginSettingsRequestFixture = new(); + private readonly PluginSettingsResponseFixture _pluginSettingsResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -43,10 +45,10 @@ public class GetPluginSettingsEndpointTests // Arrange GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; - PluginSettingsResponse expectedResponse = new( - PluginId: request.PluginId, - Schema: [], - Settings: null + PluginSettingsResponse expectedResponse = _pluginSettingsResponseFixture.Create( + pluginId: request.PluginId, + schema: [], + settings: null ); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -92,7 +94,7 @@ public class GetPluginSettingsEndpointTests GetPluginSettingsRequest request = _getPluginSettingsRequestFixture.Create(); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new PluginSettingsResponse(request.PluginId, [], null))); + .Returns(Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null))); // Act await _sut.ExecuteAsync(request, cancellationToken); @@ -118,7 +120,7 @@ public class GetPluginSettingsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; callInfo.Arg().ThrowIfCancellationRequested(); - return Result.From(new PluginSettingsResponse(request.PluginId, [], null)); + return Result.From(_pluginSettingsResponseFixture.Create(pluginId: request.PluginId, schema: [], settings: null)); }, callInfo.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs index 190e76d7..b5f947be 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetUserSettings/GetUserSettingsEndpointTests.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Settings.Queries.GetUserSettings; +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; using Lumina.Contracts.Responses.UsersManagement.Settings; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetUserSettings; @@ -24,6 +25,7 @@ public class GetUserSettingsEndpointTests { private readonly IQueryHandler> _mockHandler; private readonly GetUserSettingsEndpoint _sut; + private readonly UserSettingsResponseFixture _userSettingsResponseFixture = new(); /// /// Initializes a new instance of the class. @@ -39,7 +41,7 @@ public class GetUserSettingsEndpointTests { // Arrange CancellationToken cancellationToken = CancellationToken.None; - UserSettingsResponse expectedResponse = new(Guid.NewGuid(), true, 48, false, true); + UserSettingsResponse expectedResponse = _userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(expectedResponse)); @@ -79,7 +81,7 @@ public class GetUserSettingsEndpointTests // Arrange CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) - .Returns(Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true))); + .Returns(Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false))); // Act await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); @@ -104,7 +106,7 @@ public class GetUserSettingsEndpointTests operationStarted.SetResult(true); await cancellationRequested.Task; info.Arg().ThrowIfCancellationRequested(); - return Result.From(new UserSettingsResponse(Guid.NewGuid(), true, 48, false, true)); + return Result.From(_userSettingsResponseFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false)); }, info.Arg())); // Act diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 5e15bdf4..b4054779 100644 --- a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -1,6 +1,7 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Application.Common.CQRS; using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdateUserSettings; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; using Lumina.Contracts.Requests.UsersManagement.Settings; using Lumina.Domain.Common.Primitives; using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdateUserSettings; @@ -23,6 +24,7 @@ public class UpdateUserSettingsEndpointTests { private readonly ICommandHandler> _mockHandler; private readonly UpdateUserSettingsEndpoint _sut; + private readonly UpdateUserSettingsRequestFixture _updateUserSettingsRequestFixture = new(); /// /// Initializes a new instance of the class. @@ -37,7 +39,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker() { // Arrange - UpdateUserSettingsRequest request = new(true, 48, false, true); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -54,7 +56,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldReturnProblemResult() { // Arrange - UpdateUserSettingsRequest request = new(true, 0, false, true); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 0, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); CancellationToken cancellationToken = CancellationToken.None; Error expectedError = Error.Validation("UserSettings.ItemsPerPageMustBeGreaterThanZero", "ItemsPerPage must be greater than zero."); _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) @@ -76,7 +78,7 @@ public class UpdateUserSettingsEndpointTests public async Task ExecuteAsync_WhenCalled_ShouldSendUpdateUserSettingsCommandToHandler() { // Arrange - UpdateUserSettingsRequest request = new(true, 24, true, true); + UpdateUserSettingsRequest request = _updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 24, shouldIgnoreThePrefixForAlphaPicker: true, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false); CancellationToken cancellationToken = CancellationToken.None; _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); @@ -89,7 +91,7 @@ public class UpdateUserSettingsEndpointTests Arg.Is(command => command.IsPaginationEnabled == request.IsPaginationEnabled && command.ItemsPerPage == request.ItemsPerPage && - command.IgnoreThePrefixForAlphaPicker == request.IgnoreThePrefixForAlphaPicker && + command.ShouldIgnoreThePrefixForAlphaPicker == request.ShouldIgnoreThePrefixForAlphaPicker && command.IsThemeCachingEnabled == request.IsThemeCachingEnabled), Arg.Is(cancellationToken)); } @@ -112,7 +114,7 @@ public class UpdateUserSettingsEndpointTests }, info.Arg())); // Act - Task operationTask = _sut.ExecuteAsync(new UpdateUserSettingsRequest(true, 48, false, true), cts.Token); + Task operationTask = _sut.ExecuteAsync(_updateUserSettingsRequestFixture.Create(isPaginationEnabled: true, itemsPerPage: 48, shouldIgnoreThePrefixForAlphaPicker: false, isThemeCachingEnabled: true, shouldAggregateMetadataWhenMissing: false), cts.Token); await operationStarted.Task; cts.Cancel(); cancellationRequested.SetResult(true); diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs index 0edb17c5..e734623c 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdateUserSettings/UpdateUserSettingsEndpointTests.cs @@ -38,6 +38,10 @@ public class UpdateUserSettingsEndpointTests _sut = Factory.Create(_mockApiHttpClient, CreateThemeCachePreferenceService()); } + /// + /// Creates a backed by an in-memory hybrid cache. + /// + /// The created theme cache preference service. private static ThemeCachePreferenceService CreateThemeCachePreferenceService() { ServiceCollection services = new(); @@ -50,15 +54,15 @@ public class UpdateUserSettingsEndpointTests { // Arrange UserSettingsDto request = _userSettingsDtoFixture.Create(); - _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns(new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest()); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new Web.Common.Requests.Common.EmptyRequest()); // Act IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); string body = await JsonResultTestHelper.GetResponseBodyAsync(result); // Assert - await _mockApiHttpClient.Received(1).PutAsync( + await _mockApiHttpClient.Received(1).PutAsync( ApiRoutes.Users.UPDATE_USER_SETTINGS, Arg.Is(settings => settings.ItemsPerPage == request.ItemsPerPage && settings.IsPaginationEnabled == request.IsPaginationEnabled), Arg.Any());