diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs index 5f1ddb1f..1aa4eafe 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/IArtworkProviderConfigurationRepository.cs @@ -39,4 +39,30 @@ public interface IArtworkProviderConfigurationRepository : IRepositoryCancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> UpsertAsync(LibraryArtworkProviderConfigurationEntity configuration, CancellationToken cancellationToken); + + /// + /// Deletes all the artwork provider configurations of the media library identified by . + /// + /// The Id of the media library whose artwork provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the artwork provider configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose artwork provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken); + + /// + /// Deletes the artwork provider configurations of the media library identified by that reference + /// one of the plugins identified by . + /// + /// The Id of the media library whose artwork provider configurations are deleted. + /// The Ids of the plugins whose configurations of the media library are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable pluginIds, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs index 36c00468..76ea972a 100644 --- a/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs +++ b/src/Lumina.Application/Common/DataAccess/Repositories/Plugins/ILibraryMetadataProviderConfigurationRepository.cs @@ -39,4 +39,30 @@ public interface ILibraryMetadataProviderConfigurationRepository : IRepositoryCancellation token that can be used to stop the execution. /// An representing either a successful operation, or an error. Task> UpsertAsync(LibraryMetadataProviderConfigurationEntity configuration, CancellationToken cancellationToken); + + /// + /// Deletes all the metadata provider configurations of the media library identified by . + /// + /// The Id of the media library whose metadata provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the metadata provider configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose metadata provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken); + + /// + /// Deletes the metadata provider configurations of the media library identified by that reference + /// one of the plugins identified by . + /// + /// The Id of the media library whose metadata provider configurations are deleted. + /// The Ids of the plugins whose configurations of the media library are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable pluginIds, CancellationToken cancellationToken); } diff --git a/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs new file mode 100644 index 00000000..6f81bcbd --- /dev/null +++ b/src/Lumina.Application/Common/Infrastructure/Plugins/IMediaLibraryProviderConfigurationStore.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Application.Common.Infrastructure.Plugins; + +/// +/// Store of the metadata and artwork provider configurations of the media libraries. +/// +public interface IMediaLibraryProviderConfigurationStore +{ + /// + /// Gets the metadata provider configurations of the media library identified by . + /// + /// The Id of the media library whose metadata provider configurations are retrieved. + /// Cancellation token that can be used to stop the execution. + /// An containing either the configurations, or an error. + Task>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Adds a disabled provider configuration for every loaded plugin that supports the provided library type and has no + /// configuration yet for the media library identified by . + /// + /// The Id of the media library whose provider configurations are ensured. + /// The type of the media library, used to determine the plugins whose providers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + + /// + /// Replaces the provider configurations of the media library identified by so that they + /// match the plugins supporting the provided library type. + /// + /// The Id of the media library whose provider configurations are reconciled. + /// The type of the media library, used to determine the plugins whose providers apply. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken); + + /// + /// Deletes all the provider configurations of the media library identified by . + /// + /// The Id of the media library whose provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken); + + /// + /// Deletes all the provider configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken); +} 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 c4ad4181..983bdf9e 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandler.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; @@ -37,6 +38,7 @@ public class AddLibraryCommandHandler : ICommandHandler _validator; /// @@ -46,13 +48,15 @@ public class AddLibraryCommandHandler : ICommandHandlerInjected service to retrieve the current user information. /// Injected service for the queue of domain events. /// Injected facade service for environment contextual services. + /// Injected store of the provider configurations of the media libraries. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. public AddLibraryCommandHandler( IAuthorizationService authorizationService, - ICurrentUserService currentUserService, + ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, IEnvironmentContext environmentContext, + IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) { @@ -61,6 +65,7 @@ public class AddLibraryCommandHandler : ICommandHandler insertLibraryResult = await _unitOfWork.LibraryRepository.InsertAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (insertLibraryResult.IsFailure) return insertLibraryResult.Errors; + Result ensureProviderConfigurationsResult = await _providerConfigurationStore.EnsureProviderConfigurationsAsync( + createLibraryResult.Value.Id.Value, Enum.Parse(command.LibraryType!), cancellationToken).ConfigureAwait(false); + if (ensureProviderConfigurationsResult.IsFailure) + return ensureProviderConfigurationsResult.Errors; await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the newly saved media library from the persistence medium and return it diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs index f5bdffef..968f92d4 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandler.cs @@ -8,6 +8,7 @@ using Lumina.Application.Common.DomainEvents; 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.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Domain.Common.Events; @@ -31,6 +32,7 @@ public class DeleteLibraryCommandHandler : ICommandHandler _validator; /// @@ -39,18 +41,21 @@ public class DeleteLibraryCommandHandler : ICommandHandlerInjected service for authorization related functionality. /// Injected service to retrieve the current user information. /// Injected service for the queue of domain events. + /// Injected store of the provider configurations of the media libraries. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. public DeleteLibraryCommandHandler( IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, + IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; _domainEventsQueue = domainEventsQueue; + _providerConfigurationStore = providerConfigurationStore; _unitOfWork = unitOfWork; _validator = validator; } @@ -100,7 +105,10 @@ public class DeleteLibraryCommandHandler : ICommandHandler removeProviderConfigurationsResult = await _providerConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (removeProviderConfigurationsResult.IsFailure) + return removeProviderConfigurationsResult.Errors; Result deletePersistenceLibraryResult = await _unitOfWork.LibraryRepository.DeleteByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); if (deletePersistenceLibraryResult.IsFailure) return deletePersistenceLibraryResult.Errors; 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 8a210168..52de01c6 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandler.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DomainEvents; 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.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.MediaLibrary.Management; using Lumina.Contracts.Responses.MediaLibrary.Management; @@ -41,6 +42,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler _validator; /// @@ -50,13 +52,15 @@ public class UpdateLibraryCommandHandler : ICommandHandlerInjected service to retrieve the current user information. /// Injected service for the queue of domain events. /// Injected facade service for environment contextual services. + /// Injected store of the provider configurations of the media libraries. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. public UpdateLibraryCommandHandler( - IAuthorizationService authorizationService, + IAuthorizationService authorizationService, ICurrentUserService currentUserService, IDomainEventsQueue domainEventsQueue, IEnvironmentContext environmentContext, + IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) { @@ -65,6 +69,7 @@ public class UpdateLibraryCommandHandler : ICommandHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + else if (getLibraryResult.Value is null) + return DomainErrors.Library.LibraryNotFound; + + // make sure the file is an actual supported image, but only when a new cover image was chosen; the stored cover image is + // relative to the application base directory and is already validated, so it must not block saving unrelated changes + if (command.CoverImage is not null && command.CoverImage != getLibraryResult.Value.CoverImage) { Result fileSystemPathIdResult = FileSystemPathId.Create(command.CoverImage); if (fileSystemPathIdResult.IsFailure) @@ -102,13 +115,6 @@ public class UpdateLibraryCommandHandler : ICommandHandler getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure) - return getLibraryResult.Errors; - else if (getLibraryResult.Value is null) - return DomainErrors.Library.LibraryNotFound; - // admins or users with the permission to manage media libraries can update any library; other users can only update the libraries they own bool hasManagePermission = await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false); bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync( @@ -117,11 +123,12 @@ public class UpdateLibraryCommandHandler : ICommandHandler(command.LibraryType!); Result createLibraryResult = Library.Create( LibraryId.Create(command.Id), UserId.Create(command.OwnerId), command.Title!, - Enum.Parse(command.LibraryType!), + newLibraryType, command.ContentLocations!, command.CoverImage, command.IsEnabled, @@ -136,10 +143,17 @@ public class UpdateLibraryCommandHandler : ICommandHandler updateLibraryResult = await _unitOfWork.LibraryRepository.UpdateAsync(persistenceLibrary, cancellationToken).ConfigureAwait(false); if (updateLibraryResult.IsFailure) return updateLibraryResult.Errors; + if (getLibraryResult.Value.LibraryType != newLibraryType) + { + Result reconcileResult = await _providerConfigurationStore.ReconcileProviderConfigurationsAsync(command.Id, newLibraryType, cancellationToken).ConfigureAwait(false); + if (reconcileResult.IsFailure) + return reconcileResult.Errors; + } await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); // retrieve the updated media library from the persistence medium and return it diff --git a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs index d1a8f916..9772737d 100644 --- a/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs +++ b/src/Lumina.Application/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandler.cs @@ -107,6 +107,22 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler + /// Resolves a media file path stored relative to the application base directory into an absolute file system path. + /// The stored path was created by removing the base directory from the copied file path, so it is resolved by prepending the + /// base directory back. The path is built directly instead of using , because that method + /// treats the combined name as a directory segment and appends a trailing separator, which would make the file path invalid. + /// + /// The path relative to the application base directory, with a leading path separator. + /// An containing the absolute path, or an error. + private Result ResolveInternalMediaPathId(string relativePath) + { + string absolutePath = AppContext.BaseDirectory.TrimEnd(_pathService.PathSeparator) + + _pathService.PathSeparator + + relativePath.TrimStart(_pathService.PathSeparator); + return FileSystemPathId.Create(absolutePath); + } + /// /// Saves the cover image of a media library to the internal media directory. /// @@ -125,8 +141,21 @@ public class LibrarySavedDomainEventHandler : IDomainEventHandler fileExistsResult = _environmentContext.FileProviderService.FileExists(fileSystemPathIdResult.Value); if (fileExistsResult.IsFailure) return fileExistsResult.Errors; + + // when the library is saved without changing its cover, the stored cover image path is already the internal media directory + // path, relative to the application base directory; resolve it against the base directory and keep it when the file is found if (!fileExistsResult.Value) + { + Result internalImagePathIdResult = ResolveInternalMediaPathId(imagePath); + if (internalImagePathIdResult.IsFailure) + return internalImagePathIdResult.Errors; + Result internalFileExistsResult = _environmentContext.FileProviderService.FileExists(internalImagePathIdResult.Value); + if (internalFileExistsResult.IsFailure) + return internalFileExistsResult.Errors; + if (internalFileExistsResult.Value) + return imagePath; return Errors.FileSystemManagement.FileNotFound; + } // make sure the file is an actual supported image Result imageCheckResult = await _environmentContext.FileTypeService.GetImageTypeAsync(fileSystemPathIdResult.Value, cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs index 391cf371..0143c65c 100644 --- a/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs +++ b/src/Lumina.Application/Core/Plugins/Queries/GetLibraryMetadataProviders/GetLibraryMetadataProvidersQueryHandler.cs @@ -5,6 +5,7 @@ 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.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Common.Mapping.Plugins; using Lumina.Contracts.Responses.Plugins; @@ -27,6 +28,7 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler _validator; /// @@ -34,12 +36,14 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler /// Injected service for authorization related functionality. /// Injected service to retrieve the current user information. + /// Injected store of the provider configurations of the media libraries. /// Injected unit of work for interacting with the data access layer repositories. /// Injected validator for application validation rules. - public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork, IValidator validator) + public GetLibraryMetadataProvidersQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IMediaLibraryProviderConfigurationStore providerConfigurationStore, IUnitOfWork unitOfWork, IValidator validator) { _authorizationService = authorizationService; _currentUserService = currentUserService; + _providerConfigurationStore = providerConfigurationStore; _unitOfWork = unitOfWork; _validator = validator; } @@ -70,7 +74,7 @@ public class GetLibraryMetadataProvidersQueryHandler : IQueryHandler> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); + Result> getConfigurationsResult = await _providerConfigurationStore.GetConfigurationsAsync(query.LibraryId, cancellationToken).ConfigureAwait(false); if (getConfigurationsResult.IsFailure) return getConfigurationsResult.Errors; diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs index f3e0fc6c..8a98dfeb 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/ArtworkProviderConfigurationRepository.cs @@ -77,4 +77,55 @@ internal sealed class ArtworkProviderConfigurationRepository : IArtworkProviderC } return Result.Updated; } + + /// + /// Deletes all the artwork provider configurations of the media library identified by . + /// + /// The Id of the media library whose artwork provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + List configurations = await _luminaDbContext.LibraryArtworkProviderConfigurations + .Where(configuration => configuration.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryArtworkProviderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } + + /// + /// Deletes all the artwork provider configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose artwork provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken) + { + List configurations = await _luminaDbContext.LibraryArtworkProviderConfigurations + .Where(configuration => configuration.PluginId == pluginId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryArtworkProviderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } + + /// + /// Deletes the artwork provider configurations of the media library identified by that reference + /// one of the plugins identified by . + /// + /// The Id of the media library whose artwork provider configurations are deleted. + /// The Ids of the plugins whose configurations of the media library are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable pluginIds, CancellationToken cancellationToken) + { + List pluginIdList = [.. pluginIds]; + List configurations = await _luminaDbContext.LibraryArtworkProviderConfigurations + .Where(configuration => configuration.LibraryId == libraryId && pluginIdList.Contains(configuration.PluginId)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryArtworkProviderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } } diff --git a/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs b/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs index ab502d5f..eb54e47d 100644 --- a/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs +++ b/src/Lumina.DataAccess/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepository.cs @@ -77,4 +77,55 @@ internal sealed class LibraryMetadataProviderConfigurationRepository : ILibraryM } return Result.Updated; } + + /// + /// Deletes all the metadata provider configurations of the media library identified by . + /// + /// The Id of the media library whose metadata provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAsync(Guid libraryId, CancellationToken cancellationToken) + { + List configurations = await _luminaDbContext.LibraryMetadataProviderConfigurations + .Where(configuration => configuration.LibraryId == libraryId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryMetadataProviderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } + + /// + /// Deletes all the metadata provider configurations referencing the plugin identified by . + /// + /// The Id of the plugin whose metadata provider configurations are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByPluginIdAsync(Guid pluginId, CancellationToken cancellationToken) + { + List configurations = await _luminaDbContext.LibraryMetadataProviderConfigurations + .Where(configuration => configuration.PluginId == pluginId) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryMetadataProviderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } + + /// + /// Deletes the metadata provider configurations of the media library identified by that reference + /// one of the plugins identified by . + /// + /// The Id of the media library whose metadata provider configurations are deleted. + /// The Ids of the plugins whose configurations of the media library are deleted. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + public async Task> DeleteByLibraryIdAndPluginIdsAsync(Guid libraryId, IEnumerable pluginIds, CancellationToken cancellationToken) + { + List pluginIdList = [.. pluginIds]; + List configurations = await _luminaDbContext.LibraryMetadataProviderConfigurations + .Where(configuration => configuration.LibraryId == libraryId && pluginIdList.Contains(configuration.PluginId)) + .ToListAsync(cancellationToken).ConfigureAwait(false); + if (configurations.Count > 0) + _luminaDbContext.LibraryMetadataProviderConfigurations.RemoveRange(configurations); + return Result.Deleted; + } } diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index a9c05cd1..7f8bd90f 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -115,6 +115,7 @@ public static class InfrastructureLayerServices services.AddSingleton(new PluginManager(pluginLoadResult.Plugins)); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddSingleton(serviceProvider => new PluginDetectionSyncJob( serviceProvider.GetRequiredService(), serviceProvider.GetRequiredService(), diff --git a/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs new file mode 100644 index 00000000..d82ea794 --- /dev/null +++ b/src/Lumina.Infrastructure/Core/Plugins/MediaLibraryProviderConfigurationStore.cs @@ -0,0 +1,280 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Core.Plugins; + +/// +/// Store of the metadata and artwork provider configurations of the media libraries. +/// +internal sealed class MediaLibraryProviderConfigurationStore : IMediaLibraryProviderConfigurationStore +{ + private readonly IUnitOfWork _unitOfWork; + private readonly IPluginManager _pluginManager; + private readonly IServiceProvider _serviceProvider; + + /// + /// 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. + /// Injected provider used to resolve the providers registered by the plugins. + public MediaLibraryProviderConfigurationStore(IUnitOfWork unitOfWork, IPluginManager pluginManager, IServiceProvider serviceProvider) + { + _unitOfWork = unitOfWork; + _pluginManager = pluginManager; + _serviceProvider = serviceProvider; + } + + /// + public async Task>> GetConfigurationsAsync(Guid libraryId, CancellationToken cancellationToken) + { + return await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> EnsureProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) + { + (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); + Result ensureMetadataResult = await EnsureMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false); + if (ensureMetadataResult.IsFailure) + return ensureMetadataResult; + return await EnsureArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> ReconcileProviderConfigurationsAsync(Guid libraryId, LibraryType libraryType, CancellationToken cancellationToken) + { + (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) = GetSupportedProviderPluginIds(libraryType); + Result reconcileMetadataResult = await ReconcileMetadataConfigurationsAsync(libraryId, metadataProviderPluginIds, cancellationToken).ConfigureAwait(false); + if (reconcileMetadataResult.IsFailure) + return reconcileMetadataResult; + return await ReconcileArtworkConfigurationsAsync(libraryId, artworkProviderPluginIds, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> RemoveProviderConfigurationsForLibraryAsync(Guid libraryId, CancellationToken cancellationToken) + { + Result removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (removeMetadataResult.IsFailure) + return removeMetadataResult; + return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + } + + /// + public async Task> RemoveProviderConfigurationsAsync(Guid pluginId, CancellationToken cancellationToken) + { + Result removeMetadataResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + if (removeMetadataResult.IsFailure) + return removeMetadataResult; + return await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByPluginIdAsync(pluginId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Gets the Ids of the loaded plugins that provide metadata or artwork for the provided library type, + /// ordered alphabetically by plugin name so that the assigned ranks are stable. + /// + /// The type of the media library the providers must support. + /// The Ids of the plugins providing metadata, and the Ids of the plugins providing artwork. + private (IReadOnlyList metadataProviderPluginIds, IReadOnlyList artworkProviderPluginIds) GetSupportedProviderPluginIds(LibraryType libraryType) + { + List metadataProviderPluginIds = []; + List artworkProviderPluginIds = []; + foreach (IPlugin plugin in _pluginManager.GetPlugins().OrderBy(plugin => plugin.Name)) + { + if (_serviceProvider.GetKeyedServices(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType))) + metadataProviderPluginIds.Add(plugin.Id); + if (_serviceProvider.GetKeyedServices(plugin.Id).Any(provider => provider.SupportedLibraryTypes.Contains(libraryType))) + artworkProviderPluginIds.Add(plugin.Id); + } + return (metadataProviderPluginIds, artworkProviderPluginIds); + } + + /// + /// Removes the metadata provider configurations of the plugins that no longer support the library type, and adds a disabled + /// configuration for every plugin that supports it and has none yet, keeping the configurations of the plugins that still apply. + /// + /// The Id of the media library whose metadata provider configurations are reconciled. + /// The Ids of the plugins providing metadata for the library type, in rank order. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ReconcileMetadataConfigurationsAsync(Guid libraryId, IReadOnlyList metadataProviderPluginIds, CancellationToken cancellationToken) + { + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + HashSet supportedPluginIds = metadataProviderPluginIds.ToHashSet(); + List stalePluginIds = getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !supportedPluginIds.Contains(pluginId)) + .ToList(); + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + foreach (Guid pluginId in metadataProviderPluginIds) + { + if (configuredPluginIds.Contains(pluginId)) + continue; + LibraryMetadataProviderConfigurationEntity configuration = new() + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = false, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + nextRank++; + } + return Result.Success; + } + + /// + /// Removes the artwork provider configurations of the plugins that no longer support the library type, and adds a disabled + /// configuration for every plugin that supports it and has none yet, keeping the configurations of the plugins that still apply. + /// + /// The Id of the media library whose artwork provider configurations are reconciled. + /// The Ids of the plugins providing artwork for the library type, in rank order. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> ReconcileArtworkConfigurationsAsync(Guid libraryId, IReadOnlyList artworkProviderPluginIds, CancellationToken cancellationToken) + { + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + HashSet supportedPluginIds = artworkProviderPluginIds.ToHashSet(); + List stalePluginIds = getConfigurationsResult.Value + .Select(configuration => configuration.PluginId) + .Where(pluginId => !supportedPluginIds.Contains(pluginId)) + .ToList(); + if (stalePluginIds.Count > 0) + { + Result removeResult = await _unitOfWork.ArtworkProviderConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, stalePluginIds, cancellationToken).ConfigureAwait(false); + if (removeResult.IsFailure) + return Result.Failure(removeResult.Errors); + } + HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + foreach (Guid pluginId in artworkProviderPluginIds) + { + if (configuredPluginIds.Contains(pluginId)) + continue; + LibraryArtworkProviderConfigurationEntity configuration = new() + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = false, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + nextRank++; + } + return Result.Success; + } + + /// + /// Adds a disabled metadata provider configuration for every provided plugin that has no configuration yet for the media library. + /// + /// The Id of the media library whose metadata provider configurations are ensured. + /// The Ids of the plugins providing metadata for the library type, in rank order. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> EnsureMetadataConfigurationsAsync(Guid libraryId, IReadOnlyList metadataProviderPluginIds, CancellationToken cancellationToken) + { + if (metadataProviderPluginIds.Count == 0) + return Result.Success; + Result> getConfigurationsResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + foreach (Guid pluginId in metadataProviderPluginIds) + { + if (configuredPluginIds.Contains(pluginId)) + continue; + LibraryMetadataProviderConfigurationEntity configuration = new() + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = false, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + Result upsertResult = await _unitOfWork.LibraryMetadataProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + nextRank++; + } + return Result.Success; + } + + /// + /// Adds a disabled artwork provider configuration for every provided plugin that has no configuration yet for the media library. + /// + /// The Id of the media library whose artwork provider configurations are ensured. + /// The Ids of the plugins providing artwork for the library type, in rank order. + /// Cancellation token that can be used to stop the execution. + /// An representing either a successful operation, or an error. + private async Task> EnsureArtworkConfigurationsAsync(Guid libraryId, IReadOnlyList artworkProviderPluginIds, CancellationToken cancellationToken) + { + if (artworkProviderPluginIds.Count == 0) + return Result.Success; + Result> getConfigurationsResult = await _unitOfWork.ArtworkProviderConfigurationRepository.GetByLibraryIdAsync(libraryId, cancellationToken).ConfigureAwait(false); + if (getConfigurationsResult.IsFailure) + return Result.Failure(getConfigurationsResult.Errors); + HashSet configuredPluginIds = getConfigurationsResult.Value.Select(configuration => configuration.PluginId).ToHashSet(); + int nextRank = getConfigurationsResult.Value.Count == 0 ? 1 : getConfigurationsResult.Value.Max(configuration => configuration.Rank) + 1; + foreach (Guid pluginId in artworkProviderPluginIds) + { + if (configuredPluginIds.Contains(pluginId)) + continue; + LibraryArtworkProviderConfigurationEntity configuration = new() + { + Id = Guid.NewGuid(), + LibraryId = libraryId, + PluginId = pluginId, + IsEnabled = false, + Rank = nextRank, + CreatedOnUtc = default, + CreatedBy = default, + UpdatedBy = default + }; + Result upsertResult = await _unitOfWork.ArtworkProviderConfigurationRepository.UpsertAsync(configuration, cancellationToken).ConfigureAwait(false); + if (upsertResult.IsFailure) + return Result.Failure(upsertResult.Errors); + nextRank++; + } + return Result.Success; + } +} diff --git a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs index 8a433b7a..212a07a3 100644 --- a/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs +++ b/src/Lumina.Infrastructure/Core/Plugins/PluginDetectionSyncJob.cs @@ -1,5 +1,6 @@ #region ========================================================================= USING ===================================================================================== using Lumina.Domain.Common.Primitives; +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; @@ -106,7 +107,9 @@ internal sealed class PluginDetectionSyncJob : BackgroundService _logger.LogError("Failed to persist the detection of plugin '{PluginName}': {Error}", loadError.AssemblyName, upsertResult.FirstError.Description); } - // remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status + // remove the rows of the plugins that are no longer detected, so that each plugin assembly has exactly one row regardless of its load status, + // and delete the provider configurations of the removed plugins, since their configuration only makes sense while the plugin is installed + IMediaLibraryProviderConfigurationStore providerConfigurationStore = asyncServiceScope.ServiceProvider.GetRequiredService(); Result> getPluginsResult = await unitOfWork.PluginRepository.GetAllAsync(stoppingToken).ConfigureAwait(false); if (getPluginsResult.IsFailure) _logger.LogError("Failed to get the detected plugins while reconciling the plugin rows."); @@ -119,6 +122,23 @@ internal sealed class PluginDetectionSyncJob : BackgroundService Result deleteResult = await unitOfWork.PluginRepository.DeleteByIdAsync(plugin.Id, stoppingToken).ConfigureAwait(false); if (deleteResult.IsFailure) _logger.LogError("Failed to remove the stale detection of plugin '{PluginName}': {Error}", plugin.Name, deleteResult.FirstError.Description); + Result removeConfigurationsResult = await providerConfigurationStore.RemoveProviderConfigurationsAsync(plugin.Id, stoppingToken).ConfigureAwait(false); + if (removeConfigurationsResult.IsFailure) + _logger.LogError("Failed to remove the provider configurations of the removed plugin '{PluginName}': {Error}", plugin.Name, removeConfigurationsResult.FirstError.Description); + } + } + + // seed the provider configurations of the media libraries, so that every library lists the plugins providing metadata or artwork for its type + Result> getLibrariesResult = await unitOfWork.LibraryRepository.GetAllAsync(stoppingToken).ConfigureAwait(false); + if (getLibrariesResult.IsFailure) + _logger.LogError("Failed to get the media libraries while seeding the provider configurations."); + else + { + foreach (LibraryEntity library in getLibrariesResult.Value) + { + Result ensureResult = await providerConfigurationStore.EnsureProviderConfigurationsAsync(library.Id, library.LibraryType, stoppingToken).ConfigureAwait(false); + if (ensureResult.IsFailure) + _logger.LogError("Failed to seed the provider configurations of the media library '{LibraryTitle}': {Error}", library.Title, ensureResult.FirstError.Description); } } diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs index 12cb29bf..fc0ce989 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/AddLibrary/AddLibraryCommandHandlerTests.cs @@ -5,6 +5,7 @@ using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.DomainEvents; using Lumina.Application.Common.Infrastructure.Authentication; using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Commands.AddLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; @@ -14,6 +15,7 @@ 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.Events; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using NSubstitute; using System; @@ -39,6 +41,7 @@ public class AddLibraryCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; private readonly IValidator _mockValidator; private readonly AddLibraryCommandHandler _sut; private readonly AddLibraryCommandFixture _addLibraryCommandFixture = new(); @@ -57,19 +60,22 @@ public class AddLibraryCommandHandlerTests _mockCurrentUserService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); _mockEnvironmentContext = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, is an admin, and the cover image is a valid image + // default stubs: the current user is authenticated, is an admin, the cover image is a valid image, and the provider configurations are seeded successfully _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any()).Returns(true); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.PNG)); _mockLibraryRepository.InsertAsync(Arg.Any(), Arg.Any()) .Returns(Result.Created); + _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); - _sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockUnitOfWork, _mockValidator); + _sut = new AddLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); } [Fact] @@ -88,10 +94,28 @@ public class AddLibraryCommandHandlerTests Assert.False(result.IsFailure); Assert.Equal(persistedLibrary.Id, result.Value.Id); await _mockLibraryRepository.Received(1).InsertAsync(Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync( + Arg.Any(), Arg.Is(libraryType => libraryType == Enum.Parse(command.LibraryType)), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenProviderConfigurationSeedingFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + AddLibraryCommand command = _addLibraryCommandFixture.Create(); + _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to seed provider configurations")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCoverImageIsNull_ShouldSkipImageTypeCheck() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs index bfa3ce45..dae15900 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/DeleteLibrary/DeleteLibraryCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DomainEvents; 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.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Commands.DeleteLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; @@ -36,6 +37,7 @@ public class DeleteLibraryCommandHandlerTests private readonly IAuthorizationService _mockAuthorizationService; private readonly ICurrentUserService _mockCurrentUserService; private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; private readonly IValidator _mockValidator; private readonly DeleteLibraryCommandHandler _sut; private readonly DeleteLibraryCommandFixture _deleteLibraryCommandFixture = new(); @@ -53,18 +55,21 @@ public class DeleteLibraryCommandHandlerTests _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated and the ownership policy allows the deletion + // default stubs: the current user is authenticated, the ownership policy allows the deletion, and the provider configurations are removed successfully _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); + _mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); _mockLibraryRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.Deleted); _mockValidator.Validate(Arg.Any()).Returns([]); - _sut = new DeleteLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockUnitOfWork, _mockValidator); + _sut = new DeleteLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); } [Fact] @@ -82,11 +87,32 @@ public class DeleteLibraryCommandHandlerTests // Assert Assert.False(result.IsFailure); Assert.Equal(Result.Deleted, result.Value); + await _mockProviderConfigurationStore.Received(1).RemoveProviderConfigurationsForLibraryAsync(command.Id, Arg.Any()); await _mockLibraryRepository.Received(1).DeleteByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenProviderConfigurationRemovalFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + DeleteLibraryCommand command = _deleteLibraryCommandFixture.Create(); + LibraryEntity library = _libraryEntityFixture.Create(id: command.Id, userId: _userId); + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(library)); + _mockProviderConfigurationStore.RemoveProviderConfigurationsForLibraryAsync(command.Id, Arg.Any()) + .Returns(Error.Failure(description: "Failed to remove provider configurations")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockLibraryRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs index e529d69e..075425c5 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Commands/UpdateLibrary/UpdateLibraryCommandHandlerTests.cs @@ -6,6 +6,7 @@ using Lumina.Application.Common.DomainEvents; 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.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.MediaLibrary.Management.Commands.UpdateLibrary; using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; @@ -16,6 +17,7 @@ using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.Events; using Lumina.Domain.SharedKernel.Common.Enums.Authorization; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary; using NSubstitute; using System; @@ -41,6 +43,7 @@ public class UpdateLibraryCommandHandlerTests private readonly ICurrentUserService _mockCurrentUserService; private readonly IDomainEventsQueue _mockDomainEventsQueue; private readonly IEnvironmentContext _mockEnvironmentContext; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; private readonly IValidator _mockValidator; private readonly UpdateLibraryCommandHandler _sut; private readonly UpdateLibraryCommandFixture _updateLibraryCommandFixture = new(); @@ -59,10 +62,11 @@ public class UpdateLibraryCommandHandlerTests _mockCurrentUserService = Substitute.For(); _mockDomainEventsQueue = Substitute.For(); _mockEnvironmentContext = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); - // default stubs: the current user is authenticated, has the manage permission, and the cover image is a valid image + // default stubs: the current user is authenticated, has the manage permission, the cover image is a valid image, and the provider configurations are reconciled successfully _mockCurrentUserService.UserId.Returns(_userId); _mockAuthorizationService.HasPermissionAsync(_userId, Arg.Any(), Arg.Any()) .Returns(true); @@ -70,9 +74,11 @@ public class UpdateLibraryCommandHandlerTests .Returns(Result.From(ImageType.PNG)); _mockLibraryRepository.UpdateAsync(Arg.Any(), Arg.Any()) .Returns(Result.Updated); + _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success); _mockValidator.Validate(Arg.Any()).Returns([]); - _sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockUnitOfWork, _mockValidator); + _sut = new UpdateLibraryCommandHandler(_mockAuthorizationService, _mockCurrentUserService, _mockDomainEventsQueue, _mockEnvironmentContext, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); } [Fact] @@ -80,7 +86,9 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType); LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(existingLibrary)); @@ -91,10 +99,51 @@ public class UpdateLibraryCommandHandlerTests Assert.False(result.IsFailure); Assert.Equal(existingLibrary.Id, result.Value.Id); await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.Received(1).ReconcileProviderConfigurationsAsync( + command.Id, Arg.Is(libraryType => libraryType == commandLibraryType), Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); _mockDomainEventsQueue.Received(1).Enqueue(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenLibraryTypeIsUnchanged_ShouldNotReconcileProviderConfigurations() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.LibraryType = Enum.Parse(command.LibraryType); + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockProviderConfigurationStore.DidNotReceive().ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenProviderConfigurationReconciliationFails_ShouldReturnErrorWithoutSaving() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryType commandLibraryType = Enum.Parse(command.LibraryType); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.LibraryType = commandLibraryType == LibraryType.Book ? LibraryType.EBook : LibraryType.Book; + _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(existingLibrary)); + _mockProviderConfigurationStore.ReconcileProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Error.Failure(description: "Failed to reconcile provider configurations")); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCoverImageIsNull_ShouldSkipImageTypeCheck() { @@ -119,6 +168,11 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = "C:/Users/user/cover.jpg" }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Result.From(ImageType.None)); @@ -128,7 +182,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.Library.CoverFileMustBeAnImage, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -137,6 +191,11 @@ public class UpdateLibraryCommandHandlerTests { // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + command = command with { CoverImage = "C:/Users/user/cover.jpg" }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); _mockEnvironmentContext.FileTypeService.GetImageTypeAsync(Arg.Any(), Arg.Any()) .Returns(Error.Failure(description: "Failed to determine image type")); @@ -145,7 +204,7 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } @@ -155,6 +214,10 @@ public class UpdateLibraryCommandHandlerTests // Arrange UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); command = command with { CoverImage = " " }; + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = null; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); // Act Result result = await _sut.HandleAsync(command, CancellationToken.None); @@ -162,10 +225,31 @@ public class UpdateLibraryCommandHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(DomainErrors.FileSystemManagement.InvalidPath, result.FirstError); - await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).GetByIdAsync(command.Id, Arg.Any()); await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenCoverImageIsUnchanged_ShouldSkipImageTypeCheck() + { + // Arrange + UpdateLibraryCommand command = _updateLibraryCommandFixture.Create(); + LibraryEntity existingLibrary = _libraryEntityFixture.Create(id: command.Id, userId: command.OwnerId); + existingLibrary.CoverImage = command.CoverImage; + _mockLibraryRepository.GetByIdAsync(command.Id, Arg.Any()) + .Returns(Result.From(existingLibrary)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockEnvironmentContext.FileTypeService.DidNotReceive() + .GetImageTypeAsync(Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(2).GetByIdAsync(command.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError() { diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs index a7c49d0f..267c59ec 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/Management/Events/LibrarySavedDomainEventHandlerTests.cs @@ -156,6 +156,30 @@ public class LibrarySavedDomainEventHandlerTests await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); } + [Fact] + public async Task HandleAsync_WhenCoverImageIsAlreadyInMediaDirectory_ShouldKeepItWithoutRecopying() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Library library = _libraryFixture.Create(id: libraryId, coverImage: "/Media/Libraries/guid/cover.png"); + LibrarySavedDomainEvent domainEvent = new(Guid.NewGuid(), library, DateTime.UtcNow); + // mirror the real CombinePath behavior, which treats the combined name as a directory segment and appends a trailing + // separator; the internal cover path resolution must still yield the file path without that trailing separator + _mockPathService.CombinePath(Arg.Any(), Arg.Any()) + .Returns(callInfo => Result.From(string.Concat(callInfo.ArgAt(0), callInfo.ArgAt(1)) + '/')); + string internalImagePath = $"{AppContext.BaseDirectory.TrimEnd('/')}/Media/Libraries/guid/cover.png"; + _mockFileProviderService.FileExists(Arg.Any()) + .Returns(callInfo => Result.From(callInfo.Arg().Path == internalImagePath)); + + // Act + await _sut.HandleAsync(domainEvent, CancellationToken.None); + + // Assert + Assert.Equal("/Media/Libraries/guid/cover.png", library.CoverImage); + _mockFileProviderService.DidNotReceive().CopyFile(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockLibraryRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + } + [Fact] public async Task HandleAsync_WhenCoverSourceFileDoesNotExist_ShouldThrowEventualConsistencyException() { 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 d2bb4a86..16e3965f 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 @@ -5,6 +5,7 @@ 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.Plugins; using Lumina.Application.Common.Infrastructure.Validation; using Lumina.Application.Core.Plugins.Queries.GetLibraryMetadataProviders; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; @@ -30,10 +31,10 @@ namespace Lumina.Application.UnitTests.Core.Plugins.Queries.GetLibraryMetadataPr 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 IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; private readonly IValidator _mockValidator; private readonly GetLibraryMetadataProvidersQueryHandler _sut; private readonly GetLibraryMetadataProvidersQueryFixture _getLibraryMetadataProvidersQueryFixture = new(); @@ -47,12 +48,11 @@ public class GetLibraryMetadataProvidersQueryHandlerTests public GetLibraryMetadataProvidersQueryHandlerTests() { _mockUnitOfWork = Substitute.For(); - _mockLibraryMetadataProviderConfigurationRepository = Substitute.For(); _mockPluginRepository = Substitute.For(); - _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockLibraryMetadataProviderConfigurationRepository); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); _mockAuthorizationService = Substitute.For(); _mockCurrentUserService = Substitute.For(); + _mockProviderConfigurationStore = Substitute.For(); _mockValidator = Substitute.For>(); _userId = Guid.NewGuid(); @@ -62,7 +62,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests .Returns(true); _mockValidator.Validate(Arg.Any()).Returns([]); - _sut = new GetLibraryMetadataProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator); + _sut = new GetLibraryMetadataProvidersQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockProviderConfigurationStore, _mockUnitOfWork, _mockValidator); } [Fact] @@ -78,7 +78,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests // Assert Assert.True(result.IsFailure); Assert.Equal(Errors.Plugins.LibraryIdCannotBeEmpty, result.FirstError); - await _mockLibraryMetadataProviderConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any(), Arg.Any()); } [Fact] @@ -93,7 +93,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests _configurationEntityFixture.Create(query.LibraryId, secondPluginId, 2), _configurationEntityFixture.Create(query.LibraryId, firstPluginId, 1) ]; - _mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); List plugins = [ @@ -125,7 +125,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests [ _configurationEntityFixture.Create(query.LibraryId, unknownPluginId, 1) ]; - _mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>(configurations)); _mockPluginRepository.GetAllAsync(Arg.Any()) .Returns(Result.From>([_pluginEntityFixture.Create()])); @@ -145,7 +145,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests { // Arrange GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); - _mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); _mockPluginRepository.GetAllAsync(Arg.Any()) .Returns(Result.From>([])); @@ -164,7 +164,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests // Arrange GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); Error error = Error.Failure(description: "Failed to get configurations"); - _mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(error); // Act @@ -180,7 +180,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests { // Arrange GetLibraryMetadataProvidersQuery query = _getLibraryMetadataProvidersQueryFixture.Create(); - _mockLibraryMetadataProviderConfigurationRepository.GetByLibraryIdAsync(query.LibraryId, Arg.Any()) + _mockProviderConfigurationStore.GetConfigurationsAsync(query.LibraryId, Arg.Any()) .Returns(Result.From>([])); _mockPluginRepository.GetAllAsync(Arg.Any()) .Returns(Error.Failure(description: "Failed to get plugins")); @@ -208,7 +208,7 @@ public class GetLibraryMetadataProvidersQueryHandlerTests 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 _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any(), Arg.Any()); await _mockPluginRepository.DidNotReceive().GetAllAsync(Arg.Any()); } @@ -226,6 +226,6 @@ public class GetLibraryMetadataProvidersQueryHandlerTests 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()); + await _mockProviderConfigurationStore.DidNotReceive().GetConfigurationsAsync(Arg.Any(), Arg.Any()); } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs index 47de5fc4..fa8a878a 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/ArtworkProviderConfigurationRepositoryTests.cs @@ -134,4 +134,66 @@ public class ArtworkProviderConfigurationRepositoryTests Assert.True(retrievedConfiguration.IsEnabled); Assert.Equal(configuration.Id, retrievedConfiguration.Id); } + + [Fact] + public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldRemoveOnlyConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryArtworkProviderConfigurations); + Assert.Equal(configurationOfAnotherLibrary.Id, remainingConfiguration.Id); + } + + [Fact] + public async Task DeleteByPluginIdAsync_WhenCalled_ShouldRemoveConfigurationsOfThePlugin() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity configurationOfPlugin = _configurationFixture.Create(Guid.NewGuid(), pluginId, 1); + LibraryArtworkProviderConfigurationEntity configurationOfAnotherPlugin = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryArtworkProviderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByPluginIdAsync(pluginId, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryArtworkProviderConfigurations); + Assert.Equal(configurationOfAnotherPlugin.Id, remainingConfiguration.Id); + } + + [Fact] + public async Task DeleteByLibraryIdAndPluginIdsAsync_WhenCalled_ShouldRemoveOnlyTheConfigurationsOfTheProvidedPlugins() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid removedPluginId = Guid.NewGuid(); + Guid keptPluginId = Guid.NewGuid(); + LibraryArtworkProviderConfigurationEntity removedConfiguration = _configurationFixture.Create(libraryId, removedPluginId, 1); + LibraryArtworkProviderConfigurationEntity keptConfiguration = _configurationFixture.Create(libraryId, keptPluginId, 2); + _mockContext.LibraryArtworkProviderConfigurations.AddRange(removedConfiguration, keptConfiguration); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByLibraryIdAndPluginIdsAsync(libraryId, [removedPluginId], CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryArtworkProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryArtworkProviderConfigurations); + Assert.Equal(keptConfiguration.Id, remainingConfiguration.Id); + } } diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs index fa2c46ea..be0b5039 100644 --- a/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Core/Repositories/Plugins/LibraryMetadataProviderConfigurationRepositoryTests.cs @@ -104,4 +104,66 @@ public class LibraryMetadataProviderConfigurationRepositoryTests Assert.Equal(5, retrievedConfiguration.Rank); Assert.True(retrievedConfiguration.IsEnabled); } + + [Fact] + public async Task DeleteByLibraryIdAsync_WhenCalled_ShouldRemoveOnlyConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity configurationOfLibrary = _configurationFixture.Create(libraryId, Guid.NewGuid(), 1); + LibraryMetadataProviderConfigurationEntity configurationOfAnotherLibrary = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfLibrary, configurationOfAnotherLibrary); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByLibraryIdAsync(libraryId, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryMetadataProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryMetadataProviderConfigurations); + Assert.Equal(configurationOfAnotherLibrary.Id, remainingConfiguration.Id); + } + + [Fact] + public async Task DeleteByPluginIdAsync_WhenCalled_ShouldRemoveConfigurationsOfThePlugin() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity configurationOfPlugin = _configurationFixture.Create(Guid.NewGuid(), pluginId, 1); + LibraryMetadataProviderConfigurationEntity configurationOfAnotherPlugin = _configurationFixture.Create(Guid.NewGuid(), Guid.NewGuid(), 1); + _mockContext.LibraryMetadataProviderConfigurations.AddRange(configurationOfPlugin, configurationOfAnotherPlugin); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByPluginIdAsync(pluginId, CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryMetadataProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryMetadataProviderConfigurations); + Assert.Equal(configurationOfAnotherPlugin.Id, remainingConfiguration.Id); + } + + [Fact] + public async Task DeleteByLibraryIdAndPluginIdsAsync_WhenCalled_ShouldRemoveOnlyTheConfigurationsOfTheProvidedPlugins() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid removedPluginId = Guid.NewGuid(); + Guid keptPluginId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity removedConfiguration = _configurationFixture.Create(libraryId, removedPluginId, 1); + LibraryMetadataProviderConfigurationEntity keptConfiguration = _configurationFixture.Create(libraryId, keptPluginId, 2); + _mockContext.LibraryMetadataProviderConfigurations.AddRange(removedConfiguration, keptConfiguration); + await _mockContext.SaveChangesAsync(); + + // Act + Result result = await _sut.DeleteByLibraryIdAndPluginIdsAsync(libraryId, [removedPluginId], CancellationToken.None); + await _mockContext.SaveChangesAsync(); + + // Assert + Assert.False(result.IsFailure); + LibraryMetadataProviderConfigurationEntity remainingConfiguration = Assert.Single(_mockContext.LibraryMetadataProviderConfigurations); + Assert.Equal(keptConfiguration.Id, remainingConfiguration.Id); + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs new file mode 100644 index 00000000..ff19d273 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/MediaLibraryProviderConfigurationStoreTests.cs @@ -0,0 +1,298 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.Plugins; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Infrastructure.Core.Plugins; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Core.Plugins; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MediaLibraryProviderConfigurationStoreTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ILibraryMetadataProviderConfigurationRepository _mockMetadataConfigurationRepository; + private readonly IArtworkProviderConfigurationRepository _mockArtworkConfigurationRepository; + private readonly IPluginManager _mockPluginManager; + private readonly LibraryMetadataProviderConfigurationEntityFixture _metadataConfigurationFixture = new(); + private readonly LibraryArtworkProviderConfigurationEntityFixture _artworkConfigurationFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MediaLibraryProviderConfigurationStoreTests() + { + _mockUnitOfWork = Substitute.For(); + _mockMetadataConfigurationRepository = Substitute.For(); + _mockArtworkConfigurationRepository = Substitute.For(); + _mockUnitOfWork.LibraryMetadataProviderConfigurationRepository.Returns(_mockMetadataConfigurationRepository); + _mockUnitOfWork.ArtworkProviderConfigurationRepository.Returns(_mockArtworkConfigurationRepository); + _mockPluginManager = Substitute.For(); + _mockPluginManager.GetPlugins().Returns([]); + } + + [Fact] + public async Task GetConfigurationsAsync_WhenCalled_ShouldReturnTheConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + LibraryMetadataProviderConfigurationEntity configuration = _metadataConfigurationFixture.Create(libraryId, Guid.NewGuid(), 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([configuration])); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result> result = await sut.GetConfigurationsAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(configuration.Id, Assert.Single(result.Value).Id); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenPluginsSupportTheLibraryType_ShouldAddDisabledConfigurationsInAlphabeticalRankOrder() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha"); + IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta"); + _mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null), + (betaPluginId, CreateMetadataProvider(LibraryType.Book), CreateArtworkProvider(LibraryType.Book))); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + _mockArtworkConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId && configuration.Rank == 1 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 2 && !configuration.IsEnabled), + Arg.Any()); + await _mockArtworkConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 1 && !configuration.IsEnabled), + Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenConfigurationAlreadyExists_ShouldNotAddAnotherOne() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null)); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, pluginId, 4); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenPluginDoesNotSupportTheLibraryType_ShouldNotAddConfiguration() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Movie), null)); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync(Arg.Any(), Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().GetByLibraryIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task EnsureProviderConfigurationsAsync_WhenReadingConfigurationsFails_ShouldReturnError() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid pluginId = Guid.NewGuid(); + IPlugin plugin = CreatePlugin(pluginId, "Plugin"); + _mockPluginManager.GetPlugins().Returns([plugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut((pluginId, CreateMetadataProvider(LibraryType.Book), null)); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Error.Failure(description: "Failed to read configurations")); + + // Act + Result result = await sut.EnsureProviderConfigurationsAsync(libraryId, LibraryType.Book, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + } + + [Fact] + public async Task ReconcileProviderConfigurationsAsync_WhenCalled_ShouldRemoveStaleConfigurationsAndAddTheSupportedOnes() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid alphaPluginId = Guid.NewGuid(); + Guid betaPluginId = Guid.NewGuid(); + IPlugin alphaPlugin = CreatePlugin(alphaPluginId, "Alpha"); + IPlugin betaPlugin = CreatePlugin(betaPluginId, "Beta"); + _mockPluginManager.GetPlugins().Returns([alphaPlugin, betaPlugin]); + MediaLibraryProviderConfigurationStore sut = CreateSut( + (alphaPluginId, CreateMetadataProvider(LibraryType.Book), null), + (betaPluginId, CreateMetadataProvider(LibraryType.EBook), null)); + LibraryMetadataProviderConfigurationEntity existingConfiguration = _metadataConfigurationFixture.Create(libraryId, alphaPluginId, 1); + _mockMetadataConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([existingConfiguration])); + _mockArtworkConfigurationRepository.GetByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.From>([])); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAndPluginIdsAsync(libraryId, Arg.Any>(), Arg.Any()) + .Returns(Result.Deleted); + _mockMetadataConfigurationRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await sut.ReconcileProviderConfigurationsAsync(libraryId, LibraryType.EBook, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).DeleteByLibraryIdAndPluginIdsAsync( + libraryId, Arg.Is>(pluginIds => pluginIds.SequenceEqual(new[] { alphaPluginId })), Arg.Any()); + await _mockMetadataConfigurationRepository.Received(1).UpsertAsync( + Arg.Is(configuration => configuration.PluginId == betaPluginId && configuration.Rank == 2 && !configuration.IsEnabled), + Arg.Any()); + await _mockMetadataConfigurationRepository.DidNotReceive().UpsertAsync( + Arg.Is(configuration => configuration.PluginId == alphaPluginId), Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsForLibraryAsync_WhenCalled_ShouldDeleteTheConfigurationsOfTheLibrary() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByLibraryIdAsync(libraryId, Arg.Any()) + .Returns(Result.Deleted); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsForLibraryAsync(libraryId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + await _mockArtworkConfigurationRepository.Received(1).DeleteByLibraryIdAsync(libraryId, Arg.Any()); + } + + [Fact] + public async Task RemoveProviderConfigurationsAsync_WhenCalled_ShouldDeleteTheConfigurationsOfThePlugin() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + _mockMetadataConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + _mockArtworkConfigurationRepository.DeleteByPluginIdAsync(pluginId, Arg.Any()) + .Returns(Result.Deleted); + MediaLibraryProviderConfigurationStore sut = CreateSut(); + + // Act + Result result = await sut.RemoveProviderConfigurationsAsync(pluginId, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockMetadataConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); + await _mockArtworkConfigurationRepository.Received(1).DeleteByPluginIdAsync(pluginId, Arg.Any()); + } + + /// + /// Creates the store under test wired to the mocked dependencies, optionally registering the providers of the loaded plugins. + /// + /// The providers registered by the loaded plugins, keyed by their plugin, when any. + /// The created store. + private MediaLibraryProviderConfigurationStore CreateSut(params (Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider)[] pluginProviders) + { + ServiceCollection services = new(); + foreach ((Guid pluginId, IMetadataProvider? metadataProvider, IArtworkProvider? artworkProvider) in pluginProviders) + { + if (metadataProvider is not null) + services.AddKeyedSingleton(pluginId, (_, _) => metadataProvider); + if (artworkProvider is not null) + services.AddKeyedSingleton(pluginId, (_, _) => artworkProvider); + } + return new MediaLibraryProviderConfigurationStore(_mockUnitOfWork, _mockPluginManager, services.BuildServiceProvider()); + } + + /// + /// Creates a mocked plugin with the provided identity. + /// + /// The Id of the plugin. + /// The name of the plugin. + /// The created plugin mock. + private static IPlugin CreatePlugin(Guid id, string name) + { + IPlugin plugin = Substitute.For(); + plugin.Id.Returns(id); + plugin.Name.Returns(name); + return plugin; + } + + /// + /// Creates a mocked metadata provider supporting the provided library type. + /// + /// The library type supported by the provider. + /// The created metadata provider mock. + private static IMetadataProvider CreateMetadataProvider(LibraryType supportedLibraryType) + { + IMetadataProvider provider = Substitute.For(); + provider.SupportedLibraryTypes.Returns([supportedLibraryType]); + return provider; + } + + /// + /// Creates a mocked artwork provider supporting the provided library type. + /// + /// The library type supported by the provider. + /// The created artwork provider mock. + private static IArtworkProvider CreateArtworkProvider(LibraryType supportedLibraryType) + { + IArtworkProvider provider = Substitute.For(); + provider.SupportedLibraryTypes.Returns([supportedLibraryType]); + return provider; + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs index 50efc90a..632e3235 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Core/Plugins/PluginDetectionSyncJobTests.cs @@ -1,10 +1,14 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Common.DataAccess.Entities.Plugins; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; using Lumina.Application.Common.DataAccess.Repositories.Plugins; using Lumina.Application.Common.DataAccess.UoW; using Lumina.Application.Common.Infrastructure.Plugins; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins; using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; using Lumina.Domain.SharedKernel.Common.Enums.Plugins; using Lumina.Infrastructure.Common.Models.DTO.Plugins; using Lumina.Infrastructure.Core.Plugins; @@ -38,10 +42,13 @@ public class PluginDetectionSyncJobTests private readonly IServiceProvider _mockServiceProvider; private readonly IUnitOfWork _mockUnitOfWork; private readonly IPluginRepository _mockPluginRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IMediaLibraryProviderConfigurationStore _mockProviderConfigurationStore; private readonly IPluginManager _mockPluginManager; private readonly ILogger _mockLogger; private readonly PluginLoadErrorDtoFixture _pluginLoadErrorDtoFixture; private readonly PluginEntityFixture _pluginEntityFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); /// /// Initializes a new instance of the class. @@ -57,7 +64,15 @@ public class PluginDetectionSyncJobTests _mockUnitOfWork = Substitute.For(); _mockPluginRepository = Substitute.For(); _mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockProviderConfigurationStore = Substitute.For(); + _mockProviderConfigurationStore.RemoveProviderConfigurationsAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success); _mockServiceProvider.GetService(typeof(IUnitOfWork)).Returns(_mockUnitOfWork); + _mockServiceProvider.GetService(typeof(IMediaLibraryProviderConfigurationStore)).Returns(_mockProviderConfigurationStore); _mockPluginManager = Substitute.For(); _mockLogger = Substitute.For>(); @@ -182,6 +197,31 @@ public class PluginDetectionSyncJobTests // Assert await _mockPluginRepository.Received(1).DeleteByIdAsync(stalePluginRow.Id, Arg.Any()); await _mockPluginRepository.DidNotReceive().DeleteByIdAsync(loadedPluginRow.Id, Arg.Any()); + await _mockProviderConfigurationStore.Received(1).RemoveProviderConfigurationsAsync(stalePluginRow.Id, Arg.Any()); + await _mockProviderConfigurationStore.DidNotReceive().RemoveProviderConfigurationsAsync(loadedPluginRow.Id, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task StartAsync_WhenMediaLibrariesExist_ShouldEnsureTheirProviderConfigurations() + { + // Arrange + IPlugin loadedPlugin = CreatePlugin(Guid.NewGuid(), "Loaded Plugin", new Version(1, 0, 0)); + _mockPluginManager.GetPlugins().Returns([loadedPlugin]); + _mockPluginRepository.UpsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(Result.Updated)); + LibraryEntity bookLibrary = _libraryEntityFixture.Create(libraryType: LibraryType.Book); + _mockLibraryRepository.GetAllAsync(Arg.Any()) + .Returns(Result.From((IEnumerable)[bookLibrary])); + _mockProviderConfigurationStore.EnsureProviderConfigurationsAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Success); + PluginDetectionSyncJob sut = CreateSut(); + + // Act + await StartAndWaitForExecutionAsync(sut); + + // Assert + await _mockProviderConfigurationStore.Received(1).EnsureProviderConfigurationsAsync(bookLibrary.Id, LibraryType.Book, Arg.Any()); await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); }